@palbase/backend 39.1.2 → 39.1.4
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/test/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/test/index.ts","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/_dnt.shims.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/consts.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/kems/dhkemPrimitives/ec.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/utils/noble.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/hash.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/hmac.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/u64.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/sha3.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/utils.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/_arx.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/_poly1305.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/chacha.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/exporterContext.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/mutex.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/recipientContext.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/senderContext.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/cipherSuiteNative.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/kems/dhkemPrimitives/x25519.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/kems/dhkemPrimitives/x448.js","../../../core/src/config.ts","../../../core/src/errors.ts","../../../core/src/platform.ts","../../../core/src/pow.ts","../../../core/src/sealed.ts","../../../core/src/sealed-json.ts","../../../core/src/sealed-keys.ts","../../../core/src/url.ts","../../../core/src/http.ts","../../../core/src/token.ts","../../src/test/api.ts","../../src/test/container.ts","../../src/db/bulk.ts","../../src/db/input-guards.ts","../../src/db/tx-plan.ts","../../src/__tests__/helpers/mock-db.ts","../../src/runtime.ts","../../src/db/transaction-options.ts","../../src/db/schema-json.ts","../../src/test/fake-db.ts","../../src/test/with-services.ts"],"sourcesContent":["export { api, createTestApi, TestApiError } from \"./api.js\";\nexport { isolated } from \"./container.js\";\nexport type { IsolatedContainer } from \"./container.js\";\nexport { fakeDatabase } from \"./fake-db.js\";\nexport { withServices } from \"./with-services.js\";\nexport type { FakeDatabase, RecordedQuery } from \"./fake-db.js\";\nexport type {\n CallOptions,\n ErrorEnvelope,\n RecordedRequest,\n TestApi,\n TestApiConfig,\n TestIdentity,\n} from \"./api.js\";\n","const dntGlobals = {};\nexport const dntGlobalThis = createMergeProxy(globalThis, dntGlobals);\nfunction createMergeProxy(baseObj, extObj) {\n return new Proxy(baseObj, {\n get(_target, prop, _receiver) {\n if (prop in extObj) {\n return extObj[prop];\n }\n else {\n return baseObj[prop];\n }\n },\n set(_target, prop, value) {\n if (prop in extObj) {\n delete extObj[prop];\n }\n baseObj[prop] = value;\n return true;\n },\n deleteProperty(_target, prop) {\n let success = false;\n if (prop in extObj) {\n delete extObj[prop];\n success = true;\n }\n if (prop in baseObj) {\n delete baseObj[prop];\n success = true;\n }\n return success;\n },\n ownKeys(_target) {\n const baseKeys = Reflect.ownKeys(baseObj);\n const extKeys = Reflect.ownKeys(extObj);\n const extKeysSet = new Set(extKeys);\n return [...baseKeys.filter((k) => !extKeysSet.has(k)), ...extKeys];\n },\n defineProperty(_target, prop, desc) {\n if (prop in extObj) {\n delete extObj[prop];\n }\n Reflect.defineProperty(baseObj, prop, desc);\n return true;\n },\n getOwnPropertyDescriptor(_target, prop) {\n if (prop in extObj) {\n return Reflect.getOwnPropertyDescriptor(extObj, prop);\n }\n else {\n return Reflect.getOwnPropertyDescriptor(baseObj, prop);\n }\n },\n has(_target, prop) {\n return prop in extObj || prop in baseObj;\n },\n });\n}\n","// The input length limit (psk, psk_id, info, exporter_context, ikm).\nexport const INPUT_LENGTH_LIMIT = 8192;\nexport const INFO_LENGTH_LIMIT = 268435456;\n// The minimum length of a PSK.\nexport const MINIMUM_PSK_LENGTH = 32;\n// b\"\"\nexport const EMPTY = /* @__PURE__ */ new Uint8Array(0);\n// Common BigInt constants\nexport const N_0 = 0n;\nexport const N_1 = 1n;\nexport const N_2 = 2n;\nexport const N_7 = 7n;\nexport const N_32 = 32n;\nexport const N_256 = 256n;\nexport const N_0x71 = 0x71n;\nexport const BYTE_TO_BIGINT_256 = /* @__PURE__ */ (() => {\n const out = new Array(256);\n let i = 0;\n let value = 0n;\n while (i < 256) {\n out[i] = value;\n i++;\n value += 1n;\n }\n return out;\n})();\n","import { NativeAlgorithm } from \"../../algorithm.js\";\nimport { BYTE_TO_BIGINT_256, EMPTY } from \"../../consts.js\";\nimport { toArrayBuffer } from \"../../kdfs/hkdf.js\";\nimport { DeriveKeyPairError, DeserializeError, NotSupportedError, SerializeError, } from \"../../errors.js\";\nimport { KemId } from \"../../identifiers.js\";\nimport { KEM_USAGES, LABEL_DKP_PRK } from \"../../interfaces/dhkemPrimitives.js\";\nimport { Bignum } from \"../../utils/bignum.js\";\nimport { base64UrlToBytes, i2Osp } from \"../../utils/misc.js\";\n// b\"candidate\"\n// deno-fmt-ignore\nconst LABEL_CANDIDATE = /* @__PURE__ */ new Uint8Array([\n 99, 97, 110, 100, 105, 100, 97, 116, 101,\n]);\n// the order of the curve being used.\n// deno-fmt-ignore\nconst ORDER_P_256 = /* @__PURE__ */ new Uint8Array([\n 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84,\n 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51,\n]);\n// deno-fmt-ignore\nconst ORDER_P_384 = /* @__PURE__ */ new Uint8Array([\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xc7, 0x63, 0x4d, 0x81, 0xf4, 0x37, 0x2d, 0xdf,\n 0x58, 0x1a, 0x0d, 0xb2, 0x48, 0xb0, 0xa7, 0x7a,\n 0xec, 0xec, 0x19, 0x6a, 0xcc, 0xc5, 0x29, 0x73,\n]);\n// deno-fmt-ignore\nconst ORDER_P_521 = /* @__PURE__ */ new Uint8Array([\n 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xfa, 0x51, 0x86, 0x87, 0x83, 0xbf, 0x2f,\n 0x96, 0x6b, 0x7f, 0xcc, 0x01, 0x48, 0xf7, 0x09,\n 0xa5, 0xd0, 0x3b, 0xb5, 0xc9, 0xb8, 0x89, 0x9c,\n 0x47, 0xae, 0xbb, 0x6f, 0xb7, 0x1e, 0x91, 0x38,\n 0x64, 0x09,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_256 = /* @__PURE__ */ new Uint8Array([\n 48, 65, 2, 1, 0, 48, 19, 6, 7, 42,\n 134, 72, 206, 61, 2, 1, 6, 8, 42, 134,\n 72, 206, 61, 3, 1, 7, 4, 39, 48, 37,\n 2, 1, 1, 4, 32,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_384 = /* @__PURE__ */ new Uint8Array([\n 48, 78, 2, 1, 0, 48, 16, 6, 7, 42,\n 134, 72, 206, 61, 2, 1, 6, 5, 43, 129,\n 4, 0, 34, 4, 55, 48, 53, 2, 1, 1,\n 4, 48,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_521 = /* @__PURE__ */ new Uint8Array([\n 48, 96, 2, 1, 0, 48, 16, 6, 7, 42,\n 134, 72, 206, 61, 2, 1, 6, 5, 43, 129,\n 4, 0, 35, 4, 73, 48, 71, 2, 1, 1,\n 4, 66,\n]);\nconst EC_P_256_PARAMS = {\n p: 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn,\n b: 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604bn,\n gx: 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296n,\n gy: 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5n,\n coordinateSize: 32,\n};\nconst EC_P_384_PARAMS = {\n p: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffffn,\n b: 0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aefn,\n gx: 0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7n,\n gy: 0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5fn,\n coordinateSize: 48,\n};\nconst EC_P_521_PARAMS = {\n p: (1n << 521n) - 1n,\n b: 0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00n,\n gx: 0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66n,\n gy: 0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650n,\n coordinateSize: 66,\n};\nfunction mod(a, p) {\n const r = a % p;\n return r >= 0n ? r : r + p;\n}\nfunction modPow(base, exponent, p) {\n let result = 1n;\n let b = mod(base, p);\n let e = exponent;\n while (e > 0n) {\n if ((e & 1n) === 1n) {\n result = mod(result * b, p);\n }\n b = mod(b * b, p);\n e >>= 1n;\n }\n return result;\n}\nfunction modSqrt(rhs, p) {\n // P-256/P-384/P-521 primes satisfy p % 4 == 3.\n const y = modPow(rhs, (p + 1n) >> 2n, p);\n if (mod(y * y, p) !== mod(rhs, p)) {\n throw new Error(\"Invalid ECDH point\");\n }\n return y;\n}\nfunction bytesToBigInt(bytes) {\n let v = 0n;\n for (const b of bytes) {\n v = (v << 8n) | BYTE_TO_BIGINT_256[b];\n }\n return v;\n}\nfunction bigIntToBytes(v, len) {\n const out = new Uint8Array(len);\n let n = v;\n for (let i = len - 1; i >= 0; i--) {\n out[i] = Number(n & 0xffn);\n n >>= 8n;\n }\n if (n !== 0n) {\n throw new Error(\"Invalid coordinate length\");\n }\n return out;\n}\nfunction buildRawUncompressedPublicKey(x, y, coordinateSize) {\n const out = new Uint8Array(1 + coordinateSize * 2);\n out[0] = 0x04;\n out.set(bigIntToBytes(x, coordinateSize), 1);\n out.set(bigIntToBytes(y, coordinateSize), 1 + coordinateSize);\n return out;\n}\nexport class Ec extends NativeAlgorithm {\n constructor(kem, hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // EC specific arguments for deriving key pair.\n Object.defineProperty(this, \"_order\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_bitmask\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_curveParams\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._hkdf = hkdf;\n switch (kem) {\n case KemId.DhkemP256HkdfSha256:\n this._alg = { name: \"ECDH\", namedCurve: \"P-256\" };\n this._nPk = 65;\n this._nSk = 32;\n this._nDh = 32;\n this._order = ORDER_P_256;\n this._bitmask = 0xFF;\n this._pkcs8AlgId = PKCS8_ALG_ID_P_256;\n this._curveParams = EC_P_256_PARAMS;\n break;\n case KemId.DhkemP384HkdfSha384:\n this._alg = { name: \"ECDH\", namedCurve: \"P-384\" };\n this._nPk = 97;\n this._nSk = 48;\n this._nDh = 48;\n this._order = ORDER_P_384;\n this._bitmask = 0xFF;\n this._pkcs8AlgId = PKCS8_ALG_ID_P_384;\n this._curveParams = EC_P_384_PARAMS;\n break;\n default:\n // case KemId.DhkemP521HkdfSha512:\n this._alg = { name: \"ECDH\", namedCurve: \"P-521\" };\n this._nPk = 133;\n this._nSk = 66;\n this._nDh = 66;\n this._order = ORDER_P_521;\n this._bitmask = 0x01;\n this._pkcs8AlgId = PKCS8_ALG_ID_P_521;\n this._curveParams = EC_P_521_PARAMS;\n break;\n }\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(this._alg, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const rawIkm = toArrayBuffer(ikm);\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY, LABEL_DKP_PRK, new Uint8Array(rawIkm));\n const bn = new Bignum(this._nSk);\n for (let counter = 0; bn.isZero() || !bn.lessThan(this._order); counter++) {\n if (counter > 255) {\n throw new Error(\"Faild to derive a key pair\");\n }\n const bytes = new Uint8Array(await this._hkdf.labeledExpand(dkpPrk, LABEL_CANDIDATE, i2Osp(counter, 1), this._nSk));\n bytes[0] = bytes[0] & this._bitmask;\n bn.set(bytes);\n }\n const sk = await this._deserializePkcs8Key(bn.val());\n bn.reset();\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch {\n try {\n // Firefox fails to export JWK from some imported ECDH private keys.\n return await this._derivePublicKeyWithoutJwkExport(key);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n }\n async dh(sk, pk) {\n try {\n await this._setup();\n const bits = await this._api.deriveBits({\n name: \"ECDH\",\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.crv === \"undefined\" || key.crv !== this._alg.namedCurve) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n async _derivePublicKeyWithoutJwkExport(key) {\n const basePointRaw = buildRawUncompressedPublicKey(this._curveParams.gx, this._curveParams.gy, this._curveParams.coordinateSize);\n const basePoint = await this._api.importKey(\"raw\", basePointRaw.buffer, this._alg, true, []);\n const xBytes = new Uint8Array(await this._api.deriveBits({\n name: \"ECDH\",\n public: basePoint,\n }, key, this._nDh * 8));\n const p = this._curveParams.p;\n const x = bytesToBigInt(xBytes);\n const rhs = mod(modPow(x, 3n, p) - 3n * x + this._curveParams.b, p);\n let y = modSqrt(rhs, p);\n // Canonicalize sign so the encoded point is deterministic.\n if ((y & 1n) === 1n) {\n y = p - y;\n }\n const pubRaw = buildRawUncompressedPublicKey(x, y, this._curveParams.coordinateSize);\n return await this._api.importKey(\"raw\", pubRaw.buffer, this._alg, true, []);\n }\n}\n","// deno-lint-ignore-file no-explicit-any\n/**\n * This file is based on noble-curves (https://github.com/paulmillr/noble-curves).\n *\n * noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-curves/blob/b9d49d2b41d550571a0c5be443ecb62109fa3373/src/utils.ts\n */\n/**\n * Hex, bytes and number utilities.\n * @module\n */\nimport { loadCrypto } from \"./misc.js\";\nimport { N_0 } from \"../consts.js\";\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) && a.constructor.name === \"Uint8Array\");\n}\n/** Asserts something is positive integer. */\nexport function anumber(n, title = \"\") {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >0, got ${n}`);\n }\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(value, length, title = \"\") {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : \"\";\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + \"expected Uint8Array\" + ofLen + \", got \" + got);\n }\n return value;\n}\n// ahash function is now imported from ../hash/hash.ts\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error(\"Hash instance has been destroyed\");\n if (checkFinished && instance.finished) {\n throw new Error(\"Hash#digest() has already been called\");\n }\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out, undefined, \"digestInto() output\");\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n// Used in weierstrass, der\nfunction abignumer(n) {\n if (typeof n === \"bigint\") {\n if (!isPosBig(n))\n throw new Error(\"positive bigint expected, got \" + n);\n }\n else\n anumber(n);\n return n;\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Pre-computed buffer for endianness detection */\nconst _endianTestBuffer = /* @__PURE__ */ new Uint32Array([0x11223344]);\nconst _endianTestBytes = /* @__PURE__ */ new Uint8Array(_endianTestBuffer.buffer);\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ _endianTestBytes[0] === 0x44;\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport function swap8IfBE(n) {\n return isLE ? n : byteSwap(n);\n}\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport function swap32IfBE(u) {\n return isLE ? u : byteSwap32(u);\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore: to use toHex\ntypeof Uint8Array.from([]).toHex === \"function\" &&\n // @ts-ignore: to use fromHex\n typeof Uint8Array.fromHex === \"function\")();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, \"0\"));\nconst HEX_TO_BIGINT = /* @__PURE__ */ [\n 0n,\n 1n,\n 2n,\n 3n,\n 4n,\n 5n,\n 6n,\n 7n,\n 8n,\n 9n,\n 10n,\n 11n,\n 12n,\n 13n,\n 14n,\n 15n,\n];\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore: to use toHex\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = \"\";\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== \"string\") {\n throw new Error(\"hex string expected, got \" + typeof hex);\n }\n // @ts-ignore: to use fromHex\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) {\n throw new Error(\"hex string expected, got unpadded hex of length \" + hl);\n }\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' +\n hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== \"string\")\n throw new Error(\"string expected\");\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\nexport function numberToHexUnpadded(num) {\n const hex = abignumer(num).toString(16);\n return hex.length & 1 ? \"0\" + hex : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== \"string\") {\n throw new Error(\"hex string expected, got \" + typeof hex);\n }\n let out = N_0;\n for (let i = 0; i < hex.length; i++) {\n const n = asciiToBase16(hex.charCodeAt(i));\n if (n === undefined) {\n throw new Error('hex string expected, got non-hex character \"' + hex[i] +\n '\" at index ' + i);\n }\n out = (out << 4n) | HEX_TO_BIGINT[n];\n }\n return out; // Big Endian\n}\nexport function numberToBigint(num) {\n anumber(num, \"numberToBigint\");\n let n = num;\n let out = N_0;\n let bit = 1n;\n while (n > 0) {\n if (n % 2 === 1)\n out += bit;\n n = Math.floor(n / 2);\n bit <<= 1n;\n }\n return out;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n anumber(len);\n n = abignumer(n);\n const res = hexToBytes(n.toString(16).padStart(len * 2, \"0\"));\n if (res.length !== len)\n throw new Error(\"number too large\");\n return res;\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes) {\n return Uint8Array.from(bytes);\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as utf8ToBytes for ASCII or throws.\n */\nexport function asciiToBytes(ascii) {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n }\n return charCode;\n });\n}\n// Is positive bigint\nfunction isPosBig(n) {\n return typeof n === \"bigint\" && N_0 <= n;\n}\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max)) {\n throw new Error(\"expected valid \" + title + \": \" + min + \" <= n < \" + max + \", got \" + n);\n }\n}\nexport function validateObject(object, fields = {}, optFields = {}) {\n if (!object || typeof object !== \"object\") {\n throw new Error(\"expected valid options object\");\n }\n function checkField(fieldName, expectedType, isOpt) {\n const val = object[fieldName];\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null) {\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n// createHasher function is now exported above with ahash\n// /** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\n// export function randomBytes(bytesLength = 32): Uint8Array {\n// const cr = typeof globalThis != null && (globalThis as any).crypto;\n// if (!cr || typeof cr.getRandomValues !== \"function\") {\n// throw new Error(\"crypto.getRandomValues must be defined\");\n// }\n// return cr.getRandomValues(new Uint8Array(bytesLength));\n// }\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport async function randomBytesAsync(bytesLength = 32) {\n const api = await loadCrypto();\n const rnd = new Uint8Array(bytesLength);\n api.getRandomValues(rnd);\n return rnd;\n}\n// 06 09 60 86 48 01 65 03 04 02\nexport function oidNist(suffix) {\n return {\n oid: Uint8Array.from([\n 0x06,\n 0x09,\n 0x60,\n 0x86,\n 0x48,\n 0x01,\n 0x65,\n 0x03,\n 0x04,\n 0x02,\n suffix,\n ]),\n };\n}\n","/**\n * This file is based on noble-curves (https://github.com/paulmillr/noble-curves).\n *\n * noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-curves/blob/b9d49d2b41d550571a0c5be443ecb62109fa3373/src/utils.ts\n */\n/**\n * Hash utilities and type definitions extracted from noble.ts\n * @module\n */\nimport { anumber } from \"../utils/noble.js\";\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== \"function\" || typeof h.create !== \"function\") {\n throw new Error(\"Hash must wrapped by utils.createHasher\");\n }\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\nexport function createHasher(hashCons, info = {}) {\n const hashFn = (msg, opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n const hashC = Object.assign(hashFn, {\n outputLen: tmp.outputLen,\n blockLen: tmp.blockLen,\n create: (opts) => hashCons(opts),\n ...info,\n });\n return Object.freeze(hashC);\n}\n","// deno-lint-ignore-file no-explicit-any\n/**\n * This file is based on noble-hashes (https://github.com/paulmillr/noble-hashes).\n *\n * noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-hashes/blob/2e0c00e1aa134082ba1380bf3afb8b1641f60fed/src/hmac.ts\n */\n/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, clean } from \"../utils/noble.js\";\nimport { ahash } from \"./hash.js\";\nexport class _HMAC {\n constructor(hash, key) {\n Object.defineProperty(this, \"oHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"iHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"blockLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"outputLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"finished\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, \"destroyed\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n ahash(hash);\n abytes(key, undefined, \"key\");\n this.iHash = hash.create();\n if (typeof this.iHash.update !== \"function\") {\n throw new Error(\"Expected instance of class which extends utils.Hash\");\n }\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n abytes(out, this.outputLen, \"output\");\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new _HMAC(hash, key);\n","/**\n * This file is based on noble-hashes (https://github.com/paulmillr/noble-hashes).\n *\n * noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-hashes/blob/4e358a46d682adfb005ae6314ec999f2513086b9/src/_u64.ts\n */\n/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = 0xffffffffn;\nconst _32n = 32n;\nfunction fromBig(n, le = false) {\n if (le) {\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n }\n return {\n h: Number((n >> _32n) & U32_MASK64) | 0,\n l: Number(n & U32_MASK64) | 0,\n };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n const Ah = new Uint32Array(len);\n const Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig, };\n// prettier-ignore\nconst u64 = {\n fromBig,\n split,\n toBig,\n shrSH,\n shrSL,\n rotrSH,\n rotrSL,\n rotrBH,\n rotrBL,\n rotr32H,\n rotr32L,\n rotlSH,\n rotlSL,\n rotlBH,\n rotlBL,\n add,\n add3L,\n add3H,\n add4L,\n add4H,\n add5H,\n add5L,\n};\nexport default u64;\n","/**\n * This file is based on noble-hashes (https://github.com/paulmillr/noble-hashes).\n *\n * noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-hashes/blob/4e358a46d682adfb005ae6314ec999f2513086b9/src/sha3.ts\n */\n/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from \"./u64.js\";\nimport { abytes, aexists, anumber, aoutput, clean, oidNist, swap32IfBE, u32, } from \"../utils/noble.js\";\nimport { createHasher, } from \"./hash.js\";\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = 0n;\nconst _1n = 1n;\nconst _2n = 2n;\nconst _7n = 7n;\nconst _256n = 256n;\nconst _0x71n = 0x71n;\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = []; // no pure annotation: var is always used\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s, rounds = 24, B) {\n if (!B)\n B = new Uint32Array(10);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++) {\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n }\n // for (let x = 0; x < 10; x += 2) {\n // const idx1 = (x + 8) % 10;\n // const idx0 = (x + 2) % 10;\n // const B0 = B[idx0];\n // const B1 = B[idx0 + 1];\n // const Th = rotlH(B0, B1, 1) ^ B[idx1];\n // const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n // for (let y = 0; y < 50; y += 10) {\n // s[x + y] ^= Th;\n // s[x + y + 1] ^= Tl;\n // }\n // }\n { // x=0: idx0=2, idx1=8\n const Th = rotlH(B[2], B[3], 1) ^ B[8];\n const Tl = rotlL(B[2], B[3], 1) ^ B[9];\n s[0] ^= Th;\n s[1] ^= Tl;\n s[10] ^= Th;\n s[11] ^= Tl;\n s[20] ^= Th;\n s[21] ^= Tl;\n s[30] ^= Th;\n s[31] ^= Tl;\n s[40] ^= Th;\n s[41] ^= Tl;\n }\n { // x=2: idx0=4, idx1=0\n const Th = rotlH(B[4], B[5], 1) ^ B[0];\n const Tl = rotlL(B[4], B[5], 1) ^ B[1];\n s[2] ^= Th;\n s[3] ^= Tl;\n s[12] ^= Th;\n s[13] ^= Tl;\n s[22] ^= Th;\n s[23] ^= Tl;\n s[32] ^= Th;\n s[33] ^= Tl;\n s[42] ^= Th;\n s[43] ^= Tl;\n }\n { // x=4: idx0=6, idx1=2\n const Th = rotlH(B[6], B[7], 1) ^ B[2];\n const Tl = rotlL(B[6], B[7], 1) ^ B[3];\n s[4] ^= Th;\n s[5] ^= Tl;\n s[14] ^= Th;\n s[15] ^= Tl;\n s[24] ^= Th;\n s[25] ^= Tl;\n s[34] ^= Th;\n s[35] ^= Tl;\n s[44] ^= Th;\n s[45] ^= Tl;\n }\n { // x=6: idx0=8, idx1=4\n const Th = rotlH(B[8], B[9], 1) ^ B[4];\n const Tl = rotlL(B[8], B[9], 1) ^ B[5];\n s[6] ^= Th;\n s[7] ^= Tl;\n s[16] ^= Th;\n s[17] ^= Tl;\n s[26] ^= Th;\n s[27] ^= Tl;\n s[36] ^= Th;\n s[37] ^= Tl;\n s[46] ^= Th;\n s[47] ^= Tl;\n }\n { // x=8: idx0=0, idx1=6\n const Th = rotlH(B[0], B[1], 1) ^ B[6];\n const Tl = rotlL(B[0], B[1], 1) ^ B[7];\n s[8] ^= Th;\n s[9] ^= Tl;\n s[18] ^= Th;\n s[19] ^= Tl;\n s[28] ^= Th;\n s[29] ^= Tl;\n s[38] ^= Th;\n s[39] ^= Tl;\n s[48] ^= Th;\n s[49] ^= Tl;\n }\n // Rho (ρ) and Pi (π) — fully unrolled\n let curH = s[2];\n let curL = s[3];\n // for (let t = 0; t < 24; t++) {\n // const shift = SHA3_ROTL[t];\n // const Th = rotlH(curH, curL, shift);\n // const Tl = rotlL(curH, curL, shift);\n // const PI = SHA3_PI[t];\n // curH = s[PI];\n // curL = s[PI + 1];\n // s[PI] = Th;\n // s[PI + 1] = Tl;\n // }\n let Th, Tl;\n // t=0: shift=1(S), PI=20\n Th = rotlSH(curH, curL, 1);\n Tl = rotlSL(curH, curL, 1);\n curH = s[20];\n curL = s[21];\n s[20] = Th;\n s[21] = Tl;\n // t=1: shift=3(S), PI=14\n Th = rotlSH(curH, curL, 3);\n Tl = rotlSL(curH, curL, 3);\n curH = s[14];\n curL = s[15];\n s[14] = Th;\n s[15] = Tl;\n // t=2: shift=6(S), PI=22\n Th = rotlSH(curH, curL, 6);\n Tl = rotlSL(curH, curL, 6);\n curH = s[22];\n curL = s[23];\n s[22] = Th;\n s[23] = Tl;\n // t=3: shift=10(S), PI=34\n Th = rotlSH(curH, curL, 10);\n Tl = rotlSL(curH, curL, 10);\n curH = s[34];\n curL = s[35];\n s[34] = Th;\n s[35] = Tl;\n // t=4: shift=15(S), PI=36\n Th = rotlSH(curH, curL, 15);\n Tl = rotlSL(curH, curL, 15);\n curH = s[36];\n curL = s[37];\n s[36] = Th;\n s[37] = Tl;\n // t=5: shift=21(S), PI=6\n Th = rotlSH(curH, curL, 21);\n Tl = rotlSL(curH, curL, 21);\n curH = s[6];\n curL = s[7];\n s[6] = Th;\n s[7] = Tl;\n // t=6: shift=28(S), PI=10\n Th = rotlSH(curH, curL, 28);\n Tl = rotlSL(curH, curL, 28);\n curH = s[10];\n curL = s[11];\n s[10] = Th;\n s[11] = Tl;\n // t=7: shift=36(B), PI=32\n Th = rotlBH(curH, curL, 36);\n Tl = rotlBL(curH, curL, 36);\n curH = s[32];\n curL = s[33];\n s[32] = Th;\n s[33] = Tl;\n // t=8: shift=45(B), PI=16\n Th = rotlBH(curH, curL, 45);\n Tl = rotlBL(curH, curL, 45);\n curH = s[16];\n curL = s[17];\n s[16] = Th;\n s[17] = Tl;\n // t=9: shift=55(B), PI=42\n Th = rotlBH(curH, curL, 55);\n Tl = rotlBL(curH, curL, 55);\n curH = s[42];\n curL = s[43];\n s[42] = Th;\n s[43] = Tl;\n // t=10: shift=2(S), PI=48\n Th = rotlSH(curH, curL, 2);\n Tl = rotlSL(curH, curL, 2);\n curH = s[48];\n curL = s[49];\n s[48] = Th;\n s[49] = Tl;\n // t=11: shift=14(S), PI=8\n Th = rotlSH(curH, curL, 14);\n Tl = rotlSL(curH, curL, 14);\n curH = s[8];\n curL = s[9];\n s[8] = Th;\n s[9] = Tl;\n // t=12: shift=27(S), PI=30\n Th = rotlSH(curH, curL, 27);\n Tl = rotlSL(curH, curL, 27);\n curH = s[30];\n curL = s[31];\n s[30] = Th;\n s[31] = Tl;\n // t=13: shift=41(B), PI=46\n Th = rotlBH(curH, curL, 41);\n Tl = rotlBL(curH, curL, 41);\n curH = s[46];\n curL = s[47];\n s[46] = Th;\n s[47] = Tl;\n // t=14: shift=56(B), PI=38\n Th = rotlBH(curH, curL, 56);\n Tl = rotlBL(curH, curL, 56);\n curH = s[38];\n curL = s[39];\n s[38] = Th;\n s[39] = Tl;\n // t=15: shift=8(S), PI=26\n Th = rotlSH(curH, curL, 8);\n Tl = rotlSL(curH, curL, 8);\n curH = s[26];\n curL = s[27];\n s[26] = Th;\n s[27] = Tl;\n // t=16: shift=25(S), PI=24\n Th = rotlSH(curH, curL, 25);\n Tl = rotlSL(curH, curL, 25);\n curH = s[24];\n curL = s[25];\n s[24] = Th;\n s[25] = Tl;\n // t=17: shift=43(B), PI=4\n Th = rotlBH(curH, curL, 43);\n Tl = rotlBL(curH, curL, 43);\n curH = s[4];\n curL = s[5];\n s[4] = Th;\n s[5] = Tl;\n // t=18: shift=62(B), PI=40\n Th = rotlBH(curH, curL, 62);\n Tl = rotlBL(curH, curL, 62);\n curH = s[40];\n curL = s[41];\n s[40] = Th;\n s[41] = Tl;\n // t=19: shift=18(S), PI=28\n Th = rotlSH(curH, curL, 18);\n Tl = rotlSL(curH, curL, 18);\n curH = s[28];\n curL = s[29];\n s[28] = Th;\n s[29] = Tl;\n // t=20: shift=39(B), PI=44\n Th = rotlBH(curH, curL, 39);\n Tl = rotlBL(curH, curL, 39);\n curH = s[44];\n curL = s[45];\n s[44] = Th;\n s[45] = Tl;\n // t=21: shift=61(B), PI=18\n Th = rotlBH(curH, curL, 61);\n Tl = rotlBL(curH, curL, 61);\n curH = s[18];\n curL = s[19];\n s[18] = Th;\n s[19] = Tl;\n // t=22: shift=20(S), PI=12\n Th = rotlSH(curH, curL, 20);\n Tl = rotlSL(curH, curL, 20);\n curH = s[12];\n curL = s[13];\n s[12] = Th;\n s[13] = Tl;\n // t=23: shift=44(B), PI=2\n Th = rotlBH(curH, curL, 44);\n Tl = rotlBL(curH, curL, 44);\n s[2] = Th;\n s[3] = Tl;\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n B[0] = s[y];\n B[1] = s[y + 1];\n B[2] = s[y + 2];\n B[3] = s[y + 3];\n B[4] = s[y + 4];\n B[5] = s[y + 5];\n B[6] = s[y + 6];\n B[7] = s[y + 7];\n B[8] = s[y + 8];\n B[9] = s[y + 9];\n s[y + 0] ^= ~B[2] & B[4];\n s[y + 1] ^= ~B[3] & B[5];\n s[y + 2] ^= ~B[4] & B[6];\n s[y + 3] ^= ~B[5] & B[7];\n s[y + 4] ^= ~B[6] & B[8];\n s[y + 5] ^= ~B[7] & B[9];\n s[y + 6] ^= ~B[8] & B[0];\n s[y + 7] ^= ~B[9] & B[1];\n s[y + 8] ^= ~B[0] & B[2];\n s[y + 9] ^= ~B[1] & B[3];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n}\n/** Keccak sponge function. */\nexport class Keccak {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n Object.defineProperty(this, \"state\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"pos\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"posOut\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"finished\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, \"state32\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"destroyed\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, \"_B\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint32Array(10)\n });\n Object.defineProperty(this, \"blockLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"suffix\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"outputLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"enableXOF\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, \"rounds\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen, \"outputLen\");\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200)) {\n throw new Error(\"only keccak-f1600 function is supported\");\n }\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone() {\n return this._cloneInto();\n }\n /** Resets instance to initial (empty) state for reuse. */\n reset() {\n this.state.fill(0);\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n }\n keccak() {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds, this._B);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n abytes(data);\n return this.updateUnsafe(data);\n }\n /** Like update(), but skips validation. Caller must ensure valid state and input. */\n updateUnsafe(data) {\n const { blockLen, state } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n return this.writeIntoUnsafe(out);\n }\n /** Like writeInto(), but skips validation. Caller must ensure valid state and output. */\n writeIntoUnsafe(out) {\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF) {\n throw new Error(\"XOF is not possible for this instance\");\n }\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error(\"digest() was already called\");\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);\n// /** SHA3-224 hash function. */\n// export const sha3_224: CHash = /* @__PURE__ */ genKeccak(\n// 0x06,\n// 144,\n// 28,\n// /* @__PURE__ */ oidNist(0x07),\n// );\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256 = /* @__PURE__ */ genKeccak(0x06, 136, 32, \n/* @__PURE__ */ oidNist(0x08));\n/** SHA3-384 hash function. */\nexport const sha3_384 = /* @__PURE__ */ genKeccak(0x06, 104, 48, \n/* @__PURE__ */ oidNist(0x09));\n/** SHA3-512 hash function. */\nexport const sha3_512 = /* @__PURE__ */ genKeccak(0x06, 72, 64, \n/* @__PURE__ */ oidNist(0x0a));\n/** keccak-224 hash function. */\nexport const keccak_224 = /* @__PURE__ */ genKeccak(0x01, 144, 28);\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256 = /* @__PURE__ */ genKeccak(0x01, 136, 32);\n/** keccak-384 hash function. */\nexport const keccak_384 = /* @__PURE__ */ genKeccak(0x01, 104, 48);\n/** keccak-512 hash function. */\nexport const keccak_512 = /* @__PURE__ */ genKeccak(0x01, 72, 64);\nconst genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true), info);\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b));\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c));\n// /** SHAKE128 XOF with 256-bit output (NIST version). */\n// export const shake128_32: CHashXOF<Keccak, ShakeOpts> =\n// /* @__PURE__ */\n// genShake(0x1f, 168, 32, /* @__PURE__ */ oidNist(0x0b));\n// /** SHAKE256 XOF with 512-bit output (NIST version). */\n// export const shake256_64: CHashXOF<Keccak, ShakeOpts> =\n// /* @__PURE__ */\n// genShake(0x1f, 136, 64, /* @__PURE__ */ oidNist(0x0c));\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/utils.ts\n */\n/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\nimport { abytes, aexists, anumber, aoutput, clean, copyBytes, createView, isLE, numberToBigint, u32, } from \"@hpke/common\";\nexport { abytes, aexists, anumber, aoutput, clean, copyBytes, createView, isLE, u32, };\n/** Asserts something is boolean. */\nexport function abool(b) {\n if (typeof b !== \"boolean\")\n throw new Error(`boolean expected, not ${b}`);\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Wraps a cipher: validates args, ensures encrypt() can only be called once.\n * @__NO_SIDE_EFFECTS__\n */\n// deno-lint-ignore no-explicit-any\nexport const wrapCipher = (params, constructor) => {\n // deno-lint-ignore no-explicit-any\n function wrappedCipher(key, ...args) {\n // Validate key\n abytes(key, undefined, \"key\");\n // Big-Endian hardware is rare. Just in case someone still decides to run ciphers:\n if (!isLE) {\n throw new Error(\"Non little-endian hardware is not yet supported\");\n }\n // Validate nonce if nonceLength is present\n if (params.nonceLength !== undefined) {\n const nonce = args[0];\n abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, \"nonce\");\n }\n // Validate AAD if tagLength present\n const tagl = params.tagLength;\n if (tagl && args[1] !== undefined)\n abytes(args[1], undefined, \"AAD\");\n const cipher = constructor(key, ...args);\n const checkOutput = (fnLength, output) => {\n if (output !== undefined) {\n if (fnLength !== 2)\n throw new Error(\"cipher output not supported\");\n abytes(output, undefined, \"output\");\n }\n };\n // Create wrapped cipher with validation and single-use encryption\n let called = false;\n const wrCipher = {\n encrypt(data, output) {\n if (called) {\n throw new Error(\"cannot encrypt() twice with same key + nonce\");\n }\n called = true;\n abytes(data);\n checkOutput(cipher.encrypt.length, output);\n return cipher.encrypt(data, output);\n },\n decrypt(data, output) {\n abytes(data);\n if (tagl && data.length < tagl) {\n throw new Error('\"ciphertext\" expected length bigger than tagLength=' + tagl);\n }\n checkOutput(cipher.decrypt.length, output);\n return cipher.decrypt(data, output);\n },\n };\n return wrCipher;\n }\n Object.assign(wrappedCipher, params);\n return wrappedCipher;\n};\nexport function checkOpts(defaults, opts) {\n if (opts == null || typeof opts !== \"object\") {\n throw new Error(\"options must be defined\");\n }\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** Compares 2 uint8array-s in kinda constant time. */\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * By default, returns u8a of length.\n * When out is available, it checks it for validity and uses it.\n */\nexport function getOutput(expectedLength, out, onlyAligned = true) {\n if (out === undefined)\n return new Uint8Array(expectedLength);\n if (out.length !== expectedLength) {\n throw new Error('\"output\" expected Uint8Array of length ' + expectedLength + \", got: \" +\n out.length);\n }\n if (onlyAligned && !isAligned32(out)) {\n throw new Error(\"invalid output, must be aligned\");\n }\n return out;\n}\nexport function u64Lengths(dataLength, aadLength, isLE) {\n abool(isLE);\n const num = new Uint8Array(16);\n const view = createView(num);\n view.setBigUint64(0, numberToBigint(aadLength), isLE);\n view.setBigUint64(8, numberToBigint(dataLength), isLE);\n return num;\n}\n// Is byte array aligned to 4 byte offset (u32)?\nexport function isAligned32(bytes) {\n return bytes.byteOffset % 4 === 0;\n}\n// copy bytes to new u8a (aligned). Because Buffer.slice is broken.\n// Re-exported from @hpke/common.\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/_arx.ts\n */\n/**\n * Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\n\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n const counter = new Uint8Array(4);\n chacha(..., counter, ...); // counter is now 1\n chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | cnt(1) | nonce(3)\n chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).\n\n[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/\n[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2\n\n * @module\n */\nimport { abool, abytes, anumber, checkOpts, clean, copyBytes, u32, } from \"./utils.js\";\n// Can't use similar utils.utf8ToBytes, because it uses `TextEncoder` - not available in all envs\nconst _utf8ToBytes = (str) => Uint8Array.from(str.split(\"\").map((c) => c.charCodeAt(0)));\nconst sigma16 = _utf8ToBytes(\"expand 16-byte k\");\nconst sigma32 = _utf8ToBytes(\"expand 32-byte k\");\nconst sigma16_32 = u32(sigma16);\nconst sigma32_32 = u32(sigma32);\n/** Rotate left. */\nexport function rotl(a, b) {\n return (a << b) | (a >>> (32 - b));\n}\n// Is byte array aligned to 4 byte offset (u32)?\nfunction isAligned32(b) {\n return b.byteOffset % 4 === 0;\n}\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\nconst BLOCK_LEN32 = 16;\n// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ]\n// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ]\nconst MAX_COUNTER = 2 ** 32 - 1;\nconst U32_EMPTY = Uint32Array.of();\nfunction runCipher(core, sigma, key, nonce, data, output, counter, rounds) {\n const len = data.length;\n const block = new Uint8Array(BLOCK_LEN);\n const b32 = u32(block);\n // Make sure that buffers aligned to 4 bytes\n const isAligned = isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n if (counter >= MAX_COUNTER)\n throw new Error(\"arx: counter overflow\");\n const take = Math.min(BLOCK_LEN, len - pos);\n // aligned to 4 bytes\n if (isAligned && take === BLOCK_LEN) {\n const pos32 = pos / 4;\n if (pos % 4 !== 0)\n throw new Error(\"arx: invalid block position\");\n for (let j = 0, posj; j < BLOCK_LEN32; j++) {\n posj = pos32 + j;\n o32[posj] = d32[posj] ^ b32[j];\n }\n pos += BLOCK_LEN;\n continue;\n }\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n}\n/** Creates ARX-like (ChaCha, Salsa) cipher stream from core function. */\nexport function createCipher(core, opts) {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({\n allowShortKeys: false,\n counterLength: 8,\n counterRight: false,\n rounds: 20,\n }, opts);\n if (typeof core !== \"function\")\n throw new Error(\"core must be a function\");\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (key, nonce, data, output, counter = 0) => {\n abytes(key, undefined, \"key\");\n abytes(nonce, undefined, \"nonce\");\n abytes(data, undefined, \"data\");\n const len = data.length;\n if (output === undefined)\n output = new Uint8Array(len);\n abytes(output, undefined, \"output\");\n anumber(counter);\n if (counter < 0 || counter >= MAX_COUNTER) {\n throw new Error(\"arx: counter overflow\");\n }\n if (output.length < len) {\n throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);\n }\n const toClean = [];\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n const l = key.length;\n let k;\n let sigma;\n if (l === 32) {\n toClean.push(k = copyBytes(key));\n sigma = sigma32_32;\n }\n else if (l === 16 && allowShortKeys) {\n k = new Uint8Array(32);\n k.set(key);\n k.set(key, 16);\n sigma = sigma16_32;\n toClean.push(k);\n }\n else {\n abytes(key, 32, \"arx key\");\n throw new Error(\"invalid key size\");\n // throw new Error(`\"arx key\" expected Uint8Array of length 32, got length=${l}`);\n }\n // Nonce\n // salsa20: 8 (8-byte counter)\n // chacha20orig: 8 (8-byte counter)\n // chacha20: 12 (4-byte counter)\n // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)\n // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)\n // Align nonce to 4 bytes\n if (!isAligned32(nonce))\n toClean.push(nonce = copyBytes(nonce));\n const k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24) {\n throw new Error(`arx: extended nonce must be 24 bytes`);\n }\n extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);\n nonce = nonce.subarray(16);\n }\n // Handle nonce counter\n const nonceNcLen = 16 - counterLength;\n if (nonceNcLen !== nonce.length) {\n throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n }\n // Pad counter when nonce is 64 bit\n if (nonceNcLen !== 12) {\n const nc = new Uint8Array(12);\n nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n nonce = nc;\n toClean.push(nonce);\n }\n const n32 = u32(nonce);\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n clean(...toClean);\n return output;\n };\n}\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/_poly1305.ts\n */\n/**\n * Poly1305 ([PDF](https://cr.yp.to/mac/poly1305-20050329.pdf),\n * [wiki](https://en.wikipedia.org/wiki/Poly1305))\n * is a fast and parallel secret-key message-authentication code suitable for\n * a wide variety of applications. It was standardized in\n * [RFC 8439](https://www.rfc-editor.org/rfc/rfc8439) and is now used in TLS 1.3.\n *\n * Polynomial MACs are not perfect for every situation:\n * they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.\n * See [invisible salamanders attack](https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/).\n * To combat invisible salamanders, `hash(key)` can be included in ciphertext,\n * however, this would violate ciphertext indistinguishability:\n * an attacker would know which key was used - so `HKDF(key, i)`\n * could be used instead.\n *\n * Check out [original website](https://cr.yp.to/mac.html).\n * Based on Public Domain [poly1305-donna](https://github.com/floodyberry/poly1305-donna).\n * @module\n */\nimport { abytes, aexists, aoutput, clean, copyBytes, } from \"./utils.js\";\nfunction u8to16(a, i) {\n return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\n}\n// function bytesToNumberLE(bytes: Uint8Array): bigint {\n// return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n// }\n// /** Small version of `poly1305` without loop unrolling. Unused, provided for auditability. */\n// function poly1305_small(msg: Uint8Array, key: Uint8Array): Uint8Array {\n// abytes(msg);\n// abytes(key, 32, \"key\");\n// const POW_2_130_5 = 2n ** 130n - 5n; // 2^130-5\n// const POW_2_128_1 = 2n ** 128n - 1n; // 2^128-1\n// const CLAMP_R = 0x0ffffffc0ffffffc0ffffffc0fffffffn;\n// const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R;\n// const s = bytesToNumberLE(key.subarray(16));\n// // Process by 16 byte chunks\n// let acc = 0n;\n// for (let i = 0; i < msg.length; i += 16) {\n// const m = msg.subarray(i, i + 16);\n// const n = bytesToNumberLE(m) | (1n << (8n * mLen)); // mLen: bigint\n// acc = ((acc + n) * r) % POW_2_130_5;\n// }\n// const res = (acc + s) & POW_2_128_1;\n// return numberToBytesBE(res, 16).reverse(); // LE\n// }\n// Can be used to replace `computeTag` in chacha.ts. Unused, provided for auditability.\n// function poly1305_computeTag_small(\n// authKey: Uint8Array,\n// lengths: Uint8Array,\n// ciphertext: Uint8Array,\n// AAD?: Uint8Array,\n// ): Uint8Array {\n// const res = [];\n// const updatePadded2 = (msg: Uint8Array) => {\n// res.push(msg);\n// const leftover = msg.length % 16;\n// if (leftover) res.push(new Uint8Array(16).slice(leftover));\n// };\n// if (AAD) updatePadded2(AAD);\n// updatePadded2(ciphertext);\n// res.push(lengths);\n// return poly1305_small(concatBytes(...res), authKey);\n// }\n/** Poly1305 class. Prefer poly1305() function instead. */\nexport class Poly1305 {\n // Can be speed-up using BigUint64Array, at the cost of complexity\n constructor(key) {\n Object.defineProperty(this, \"blockLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 16\n });\n Object.defineProperty(this, \"outputLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 16\n });\n Object.defineProperty(this, \"buffer\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint8Array(16)\n });\n Object.defineProperty(this, \"r\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint16Array(10)\n }); // Allocating 1 array with .subarray() here is slower than 3\n Object.defineProperty(this, \"h\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint16Array(10)\n });\n Object.defineProperty(this, \"pad\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint16Array(8)\n });\n Object.defineProperty(this, \"pos\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"finished\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n key = copyBytes(abytes(key, 32, \"key\"));\n const t0 = u8to16(key, 0);\n const t1 = u8to16(key, 2);\n const t2 = u8to16(key, 4);\n const t3 = u8to16(key, 6);\n const t4 = u8to16(key, 8);\n const t5 = u8to16(key, 10);\n const t6 = u8to16(key, 12);\n const t7 = u8to16(key, 14);\n // https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47\n this.r[0] = t0 & 0x1fff;\n this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = (t4 >>> 1) & 0x1ffe;\n this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = (t7 >>> 5) & 0x007f;\n for (let i = 0; i < 8; i++)\n this.pad[i] = u8to16(key, 16 + 2 * i);\n }\n process(data, offset, isLast = false) {\n const hibit = isLast ? 0 : 1 << 11;\n const { h, r } = this;\n const r0 = r[0];\n const r1 = r[1];\n const r2 = r[2];\n const r3 = r[3];\n const r4 = r[4];\n const r5 = r[5];\n const r6 = r[6];\n const r7 = r[7];\n const r8 = r[8];\n const r9 = r[9];\n const t0 = u8to16(data, offset + 0);\n const t1 = u8to16(data, offset + 2);\n const t2 = u8to16(data, offset + 4);\n const t3 = u8to16(data, offset + 6);\n const t4 = u8to16(data, offset + 8);\n const t5 = u8to16(data, offset + 10);\n const t6 = u8to16(data, offset + 12);\n const t7 = u8to16(data, offset + 14);\n const h0 = h[0] + (t0 & 0x1fff);\n const h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n const h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n const h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n const h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n const h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n const h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n const h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n const h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n const h9 = h[9] + ((t7 >>> 5) | hibit);\n let c = 0;\n let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) +\n h4 * (5 * r6);\n c = d0 >>> 13;\n d0 &= 0x1fff;\n d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) +\n h9 * (5 * r1);\n c += d0 >>> 13;\n d0 &= 0x1fff;\n let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) +\n h4 * (5 * r7);\n c = d1 >>> 13;\n d1 &= 0x1fff;\n d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) +\n h9 * (5 * r2);\n c += d1 >>> 13;\n d1 &= 0x1fff;\n let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n c = d2 >>> 13;\n d2 &= 0x1fff;\n d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) +\n h9 * (5 * r3);\n c += d2 >>> 13;\n d2 &= 0x1fff;\n let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n c = d3 >>> 13;\n d3 &= 0x1fff;\n d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) +\n h9 * (5 * r4);\n c += d3 >>> 13;\n d3 &= 0x1fff;\n let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n c = d4 >>> 13;\n d4 &= 0x1fff;\n d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) +\n h9 * (5 * r5);\n c += d4 >>> 13;\n d4 &= 0x1fff;\n let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n c = d5 >>> 13;\n d5 &= 0x1fff;\n d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) +\n h9 * (5 * r6);\n c += d5 >>> 13;\n d5 &= 0x1fff;\n let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n c = d6 >>> 13;\n d6 &= 0x1fff;\n d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n c += d6 >>> 13;\n d6 &= 0x1fff;\n let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n c = d7 >>> 13;\n d7 &= 0x1fff;\n d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n c += d7 >>> 13;\n d7 &= 0x1fff;\n let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n c = d8 >>> 13;\n d8 &= 0x1fff;\n d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n c += d8 >>> 13;\n d8 &= 0x1fff;\n let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n c = d9 >>> 13;\n d9 &= 0x1fff;\n d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n c += d9 >>> 13;\n d9 &= 0x1fff;\n c = ((c << 2) + c) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = c >>> 13;\n d1 += c;\n h[0] = d0;\n h[1] = d1;\n h[2] = d2;\n h[3] = d3;\n h[4] = d4;\n h[5] = d5;\n h[6] = d6;\n h[7] = d7;\n h[8] = d8;\n h[9] = d9;\n }\n finalize() {\n const { h, pad } = this;\n const g = new Uint16Array(10);\n let c = h[1] >>> 13;\n h[1] &= 0x1fff;\n for (let i = 2; i < 10; i++) {\n h[i] += c;\n c = h[i] >>> 13;\n h[i] &= 0x1fff;\n }\n h[0] += c * 5;\n c = h[0] >>> 13;\n h[0] &= 0x1fff;\n h[1] += c;\n c = h[1] >>> 13;\n h[1] &= 0x1fff;\n h[2] += c;\n g[0] = h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (let i = 1; i < 10; i++) {\n g[i] = h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= 1 << 13;\n let mask = (c ^ 1) - 1;\n for (let i = 0; i < 10; i++)\n g[i] &= mask;\n mask = ~mask;\n for (let i = 0; i < 10; i++)\n h[i] = (h[i] & mask) | g[i];\n h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n let f = h[0] + pad[0];\n h[0] = f & 0xffff;\n for (let i = 1; i < 8; i++) {\n f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n h[i] = f & 0xffff;\n }\n clean(g);\n }\n update(data) {\n aexists(this);\n abytes(data);\n data = copyBytes(data);\n const { buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input\n if (take === blockLen) {\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(data, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(buffer, 0, false);\n this.pos = 0;\n }\n }\n return this;\n }\n destroy() {\n clean(this.h, this.r, this.buffer, this.pad);\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, h } = this;\n let { pos } = this;\n if (pos) {\n buffer[pos++] = 1;\n for (; pos < 16; pos++)\n buffer[pos] = 0;\n this.process(buffer, 0, true);\n }\n this.finalize();\n let opos = 0;\n for (let i = 0; i < 8; i++) {\n out[opos++] = h[i] >>> 0;\n out[opos++] = h[i] >>> 8;\n }\n return out;\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n}\nexport function wrapConstructorWithKey(hashCons) {\n const hashC = (msg, key) => hashCons(key).update(msg).digest();\n const tmp = hashCons(new Uint8Array(32)); // tmp array, used just once below\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key) => hashCons(key);\n return hashC;\n}\n/** Poly1305 MAC from RFC 8439. */\nexport const poly1305 = \n/** @__PURE__ */ (() => wrapConstructorWithKey((key) => new Poly1305(key)))();\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/chacha.ts\n */\n/**\n * ChaCha stream cipher, released\n * in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.\n * It was standardized in [RFC 8439](https://www.rfc-editor.org/rfc/rfc8439) and\n * is now used in TLS 1.3.\n *\n * [XChaCha20](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha)\n * extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with\n * randomly-generated nonces.\n *\n * Check out [PDF](http://cr.yp.to/chacha/chacha-20080128.pdf) and\n * [wiki](https://en.wikipedia.org/wiki/Salsa20) and\n * [website](https://cr.yp.to/chacha.html).\n *\n * @module\n */\nimport { createCipher, rotl } from \"./_arx.js\";\nimport { poly1305 } from \"./_poly1305.js\";\nimport { abytes, clean, equalBytes, getOutput, u64Lengths, wrapCipher, } from \"./utils.js\";\n/**\n * ChaCha core function. It is implemented twice:\n * 1. Simple loop (chachaCore_small, hchacha_small)\n * 2. Unrolled loop (chachaCore, hchacha) - 4x faster, but larger & harder to read\n * The specific implementation is selected in `createCipher` below.\n */\nfunction chachaCore(s, k, n, out, cnt, rounds = 20) {\n const y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key\n y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key\n y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Counter\tNonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 7);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 7);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 7);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 8);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 7);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 7);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 7);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 7);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 16);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 7);\n }\n // Write output\n let oi = 0;\n out[oi++] = (y00 + x00) | 0;\n out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0;\n out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0;\n out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0;\n out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0;\n out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0;\n out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0;\n out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0;\n out[oi++] = (y15 + x15) | 0;\n}\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.\n */\nexport const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// Pad to digest size with zeros\nconst updatePadded = (h, msg) => {\n h.update(msg);\n const leftover = msg.length % 16;\n if (leftover)\n h.update(ZEROS16.subarray(leftover));\n};\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(fn, key, nonce, ciphertext, AAD) {\n if (AAD !== undefined)\n abytes(AAD, undefined, \"AAD\");\n const authKey = fn(key, nonce, ZEROS32);\n const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);\n // Methods below can be replaced with\n // return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD)\n const h = poly1305.create(authKey);\n if (AAD)\n updatePadded(h, AAD);\n updatePadded(h, ciphertext);\n h.update(lengths);\n const res = h.digest();\n clean(authKey, lengths);\n return res;\n}\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them, but it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead = (xorStream) => (key, nonce, AAD) => {\n const tagLength = 16;\n return {\n encrypt(plaintext, output) {\n const plength = plaintext.length;\n output = getOutput(plength + tagLength, output, false);\n output.set(plaintext);\n const oPlain = output.subarray(0, -tagLength);\n // Actual encryption\n xorStream(key, nonce, oPlain, oPlain, 1);\n const tag = computeTag(xorStream, key, nonce, oPlain, AAD);\n output.set(tag, plength); // append tag\n clean(tag);\n return output;\n },\n decrypt(ciphertext, output) {\n output = getOutput(ciphertext.length - tagLength, output, false);\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n if (!equalBytes(passedTag, tag))\n throw new Error(\"invalid tag\");\n output.set(ciphertext.subarray(0, -tagLength));\n // Actual decryption\n xorStream(key, nonce, output, output, 1); // start stream with i=1\n clean(tag);\n return output;\n },\n };\n};\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n *\n * Unsafe to use random nonces under the same key, due to collision chance.\n * Prefer XChaCha instead.\n */\nexport const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, _poly1305_aead(chacha20));\n","import { ExportError, INPUT_LENGTH_LIMIT, InvalidParamError, toArrayBuffer, } from \"@hpke/common\";\nimport { emitNotSupported } from \"./utils/emitNotSupported.js\";\n// b\"sec\"\nconst LABEL_SEC = new Uint8Array([115, 101, 99]);\nexport class ExporterContextImpl {\n constructor(api, kdf, exporterSecret) {\n Object.defineProperty(this, \"_api\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"exporterSecret\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_kdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._api = api;\n this._kdf = kdf;\n this.exporterSecret = exporterSecret;\n }\n async seal(_data, _aad) {\n return await emitNotSupported();\n }\n async open(_data, _aad) {\n return await emitNotSupported();\n }\n async export(exporterContext, len) {\n const rawExporterContext = toArrayBuffer(exporterContext);\n if (rawExporterContext.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long exporter context\");\n }\n try {\n return await this._kdf.labeledExpand(this.exporterSecret, LABEL_SEC, new Uint8Array(rawExporterContext), len);\n }\n catch (e) {\n throw new ExportError(e);\n }\n }\n}\nexport class RecipientExporterContextImpl extends ExporterContextImpl {\n}\nexport class SenderExporterContextImpl extends ExporterContextImpl {\n constructor(api, kdf, exporterSecret, enc) {\n super(api, kdf, exporterSecret);\n Object.defineProperty(this, \"enc\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.enc = enc;\n return;\n }\n}\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _Mutex_locked;\nexport class Mutex {\n constructor() {\n _Mutex_locked.set(this, Promise.resolve());\n }\n async lock() {\n let releaseLock;\n const nextLock = new Promise((resolve) => {\n releaseLock = resolve;\n });\n const previousLock = __classPrivateFieldGet(this, _Mutex_locked, \"f\");\n __classPrivateFieldSet(this, _Mutex_locked, nextLock, \"f\");\n await previousLock;\n return releaseLock;\n }\n}\n_Mutex_locked = new WeakMap();\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _RecipientContextImpl_mutex;\nimport { EMPTY, OpenError, toArrayBuffer } from \"@hpke/common\";\nimport { EncryptionContextImpl } from \"./encryptionContext.js\";\nimport { Mutex } from \"./mutex.js\";\nexport class RecipientContextImpl extends EncryptionContextImpl {\n constructor() {\n super(...arguments);\n _RecipientContextImpl_mutex.set(this, void 0);\n }\n async open(data, aad = EMPTY.buffer) {\n __classPrivateFieldSet(this, _RecipientContextImpl_mutex, __classPrivateFieldGet(this, _RecipientContextImpl_mutex, \"f\") ?? new Mutex(), \"f\");\n const release = await __classPrivateFieldGet(this, _RecipientContextImpl_mutex, \"f\").lock();\n let pt;\n try {\n pt = await this._ctx.key.open(this.computeNonce(this._ctx), toArrayBuffer(data), toArrayBuffer(aad));\n }\n catch (e) {\n throw new OpenError(e);\n }\n finally {\n release();\n }\n this.incrementSeq(this._ctx);\n return pt;\n }\n}\n_RecipientContextImpl_mutex = new WeakMap();\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _SenderContextImpl_mutex;\nimport { EMPTY, SealError, toArrayBuffer } from \"@hpke/common\";\nimport { EncryptionContextImpl } from \"./encryptionContext.js\";\nimport { Mutex } from \"./mutex.js\";\nexport class SenderContextImpl extends EncryptionContextImpl {\n constructor(api, kdf, params, enc) {\n super(api, kdf, params);\n Object.defineProperty(this, \"enc\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n _SenderContextImpl_mutex.set(this, void 0);\n this.enc = enc;\n }\n async seal(data, aad = EMPTY.buffer) {\n __classPrivateFieldSet(this, _SenderContextImpl_mutex, __classPrivateFieldGet(this, _SenderContextImpl_mutex, \"f\") ?? new Mutex(), \"f\");\n const release = await __classPrivateFieldGet(this, _SenderContextImpl_mutex, \"f\").lock();\n let ct;\n try {\n ct = await this._ctx.key.seal(this.computeNonce(this._ctx), toArrayBuffer(data), toArrayBuffer(aad));\n }\n catch (e) {\n throw new SealError(e);\n }\n finally {\n release();\n }\n this.incrementSeq(this._ctx);\n return ct;\n }\n}\n_SenderContextImpl_mutex = new WeakMap();\n","import { AeadId, EMPTY, i2Osp, INFO_LENGTH_LIMIT, INPUT_LENGTH_LIMIT, InvalidParamError, MINIMUM_PSK_LENGTH, Mode, NativeAlgorithm, toUint8Array, } from \"@hpke/common\";\nimport { RecipientExporterContextImpl, SenderExporterContextImpl, } from \"./exporterContext.js\";\nimport { RecipientContextImpl } from \"./recipientContext.js\";\nimport { SenderContextImpl } from \"./senderContext.js\";\n// b\"base_nonce\"\n// deno-fmt-ignore\nconst LABEL_BASE_NONCE = new Uint8Array([\n 98, 97, 115, 101, 95, 110, 111, 110, 99, 101,\n]);\n// b\"exp\"\nconst LABEL_EXP = new Uint8Array([101, 120, 112]);\n// b\"info_hash\"\n// deno-fmt-ignore\nconst LABEL_INFO_HASH = new Uint8Array([\n 105, 110, 102, 111, 95, 104, 97, 115, 104,\n]);\n// b\"key\"\nconst LABEL_KEY = new Uint8Array([107, 101, 121]);\n// b\"psk_id_hash\"\n// deno-fmt-ignore\nconst LABEL_PSK_ID_HASH = new Uint8Array([\n 112, 115, 107, 95, 105, 100, 95, 104, 97, 115, 104,\n]);\n// b\"secret\"\nconst LABEL_SECRET = new Uint8Array([115, 101, 99, 114, 101, 116]);\n// b\"HPKE\"\n// deno-fmt-ignore\nconst SUITE_ID_HEADER_HPKE = new Uint8Array([\n 72, 80, 75, 69, 0, 0, 0, 0, 0, 0,\n]);\n/**\n * The Hybrid Public Key Encryption (HPKE) ciphersuite,\n * which is implemented using only\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n *\n * This is the super class of {@link CipherSuite} and the same as\n * {@link https://jsr.io/@hpke/core/doc/~/CipherSuite | @hpke/core#CipherSuite} as follows:\n * which supports only the ciphersuites that can be implemented on the native\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n * Therefore, the following cryptographic algorithms are not supported for now:\n * - DHKEM(X25519, HKDF-SHA256)\n * - DHKEM(X448, HKDF-SHA512)\n * - ChaCha20Poly1305\n *\n * In addtion, the HKDF functions contained in this class can only derive\n * keys of the same length as the `hashSize`.\n *\n * If you want to use the unsupported cryptographic algorithms\n * above or derive keys longer than the `hashSize`,\n * please use {@link CipherSuite}.\n *\n * This class provides following functions:\n *\n * - Creates encryption contexts both for senders and recipients.\n * - {@link createSenderContext}\n * - {@link createRecipientContext}\n * - Provides single-shot encryption API.\n * - {@link seal}\n * - {@link open}\n *\n * The calling of the constructor of this class is the starting\n * point for HPKE operations for both senders and recipients.\n *\n * @example Use only ciphersuites supported by Web Cryptography API.\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * CipherSuite,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n *\n * @example Use a ciphersuite which is currently not supported by Web Cryptography API.\n *\n * ```ts\n * import { Aes128Gcm, HkdfSha256, CipherSuite } from \"@hpke/core\";\n * // Use an extension module.\n * import { DhkemX25519HkdfSha256 } from \"@hpke/dhkem-x25519\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemX25519HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class CipherSuiteNative extends NativeAlgorithm {\n /**\n * @param params A set of parameters for building a cipher suite.\n *\n * If the error occurred, throws {@link InvalidParamError}.\n *\n * @throws {@link InvalidParamError}\n */\n constructor(params) {\n super();\n Object.defineProperty(this, \"_kem\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_kdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_aead\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_suiteId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // KEM\n if (typeof params.kem === \"number\") {\n throw new InvalidParamError(\"KemId cannot be used\");\n }\n this._kem = params.kem;\n // KDF\n if (typeof params.kdf === \"number\") {\n throw new InvalidParamError(\"KdfId cannot be used\");\n }\n this._kdf = params.kdf;\n // AEAD\n if (typeof params.aead === \"number\") {\n throw new InvalidParamError(\"AeadId cannot be used\");\n }\n this._aead = params.aead;\n this._suiteId = new Uint8Array(SUITE_ID_HEADER_HPKE);\n this._suiteId.set(i2Osp(this._kem.id, 2), 4);\n this._suiteId.set(i2Osp(this._kdf.id, 2), 6);\n this._suiteId.set(i2Osp(this._aead.id, 2), 8);\n this._kdf.init(this._suiteId);\n }\n /**\n * Gets the KEM context of the ciphersuite.\n */\n get kem() {\n return this._kem;\n }\n /**\n * Gets the KDF context of the ciphersuite.\n */\n get kdf() {\n return this._kdf;\n }\n /**\n * Gets the AEAD context of the ciphersuite.\n */\n get aead() {\n return this._aead;\n }\n /**\n * Creates an encryption context for a sender.\n *\n * If the error occurred, throws {@link DecapError} | {@link ValidationError}.\n *\n * @param params A set of parameters for the sender encryption context.\n * @returns A sender encryption context.\n * @throws {@link EncapError}, {@link ValidationError}\n */\n async createSenderContext(params) {\n this._validateInputLength(params);\n await this._setup();\n const dh = await this._kem.encap(params);\n let mode;\n if (params.psk !== undefined) {\n mode = params.senderKey !== undefined ? Mode.AuthPsk : Mode.Psk;\n }\n else {\n mode = params.senderKey !== undefined ? Mode.Auth : Mode.Base;\n }\n return await this._keyScheduleS(mode, dh.sharedSecret, dh.enc, params);\n }\n /**\n * Creates an encryption context for a recipient.\n *\n * If the error occurred, throws {@link DecapError}\n * | {@link DeserializeError} | {@link ValidationError}.\n *\n * @param params A set of parameters for the recipient encryption context.\n * @returns A recipient encryption context.\n * @throws {@link DecapError}, {@link DeserializeError}, {@link ValidationError}\n */\n async createRecipientContext(params) {\n this._validateInputLength(params);\n await this._setup();\n const sharedSecret = await this._kem.decap(params);\n let mode;\n if (params.psk !== undefined) {\n mode = params.senderPublicKey !== undefined ? Mode.AuthPsk : Mode.Psk;\n }\n else {\n mode = params.senderPublicKey !== undefined ? Mode.Auth : Mode.Base;\n }\n return await this._keyScheduleR(mode, sharedSecret, params);\n }\n /**\n * Encrypts a message to a recipient.\n *\n * If the error occurred, throws `EncapError` | `MessageLimitReachedError` | `SealError` | `ValidationError`.\n *\n * @param params A set of parameters for building a sender encryption context.\n * @param pt A plain text as bytes to be encrypted.\n * @param aad Additional authenticated data as bytes fed by an application.\n * @returns A cipher text and an encapsulated key as bytes.\n * @throws {@link EncapError}, {@link MessageLimitReachedError}, {@link SealError}, {@link ValidationError}\n */\n async seal(params, pt, aad = EMPTY.buffer) {\n const ctx = await this.createSenderContext(params);\n return {\n ct: await ctx.seal(pt, aad),\n enc: ctx.enc,\n };\n }\n /**\n * Decrypts a message from a sender.\n *\n * If the error occurred, throws `DecapError` | `DeserializeError` | `OpenError` | `ValidationError`.\n *\n * @param params A set of parameters for building a recipient encryption context.\n * @param ct An encrypted text as bytes to be decrypted.\n * @param aad Additional authenticated data as bytes fed by an application.\n * @returns A decrypted plain text as bytes.\n * @throws {@link DecapError}, {@link DeserializeError}, {@link OpenError}, {@link ValidationError}\n */\n async open(params, ct, aad = EMPTY.buffer) {\n const ctx = await this.createRecipientContext(params);\n return await ctx.open(ct, aad);\n }\n // private verifyPskInputs(mode: Mode, params: KeyScheduleParams) {\n // const gotPsk = (params.psk !== undefined);\n // const gotPskId = (params.psk !== undefined && params.psk.id.byteLength > 0);\n // if (gotPsk !== gotPskId) {\n // throw new Error('Inconsistent PSK inputs');\n // }\n // if (gotPsk && (mode === Mode.Base || mode === Mode.Auth)) {\n // throw new Error('PSK input provided when not needed');\n // }\n // if (!gotPsk && (mode === Mode.Psk || mode === Mode.AuthPsk)) {\n // throw new Error('Missing required PSK input');\n // }\n // return;\n // }\n async _keySchedule(mode, sharedSecret, params) {\n // Currently, there is no point in executing this function\n // because this hpke library does not allow users to explicitly specify the mode.\n //\n // this.verifyPskInputs(mode, params);\n const pskId = params.psk === undefined\n ? EMPTY\n : toUint8Array(params.psk.id);\n const pskIdHash = await this._kdf.labeledExtract(EMPTY, LABEL_PSK_ID_HASH, pskId);\n const info = params.info === undefined ? EMPTY : toUint8Array(params.info);\n const infoHash = await this._kdf.labeledExtract(EMPTY, LABEL_INFO_HASH, info);\n const keyScheduleContext = new Uint8Array(1 + pskIdHash.byteLength + infoHash.byteLength);\n keyScheduleContext.set(new Uint8Array([mode]), 0);\n keyScheduleContext.set(new Uint8Array(pskIdHash), 1);\n keyScheduleContext.set(new Uint8Array(infoHash), 1 + pskIdHash.byteLength);\n const psk = params.psk === undefined ? EMPTY : toUint8Array(params.psk.key);\n const ikm = this._kdf.buildLabeledIkm(LABEL_SECRET, psk);\n const exporterSecretInfo = this._kdf.buildLabeledInfo(LABEL_EXP, keyScheduleContext, this._kdf.hashSize);\n const exporterSecret = await this._kdf.extractAndExpand(sharedSecret, ikm, exporterSecretInfo, this._kdf.hashSize);\n if (this._aead.id === AeadId.ExportOnly) {\n return { aead: this._aead, exporterSecret: exporterSecret };\n }\n const keyInfo = this._kdf.buildLabeledInfo(LABEL_KEY, keyScheduleContext, this._aead.keySize);\n const key = await this._kdf.extractAndExpand(sharedSecret, ikm, keyInfo, this._aead.keySize);\n const baseNonceInfo = this._kdf.buildLabeledInfo(LABEL_BASE_NONCE, keyScheduleContext, this._aead.nonceSize);\n const baseNonce = await this._kdf.extractAndExpand(sharedSecret, ikm, baseNonceInfo, this._aead.nonceSize);\n return {\n aead: this._aead,\n exporterSecret: exporterSecret,\n key: key,\n baseNonce: new Uint8Array(baseNonce),\n seq: 0,\n };\n }\n async _keyScheduleS(mode, sharedSecret, enc, params) {\n const res = await this._keySchedule(mode, sharedSecret, params);\n if (res.key === undefined) {\n return new SenderExporterContextImpl(this._api, this._kdf, res.exporterSecret, enc);\n }\n return new SenderContextImpl(this._api, this._kdf, res, enc);\n }\n async _keyScheduleR(mode, sharedSecret, params) {\n const res = await this._keySchedule(mode, sharedSecret, params);\n if (res.key === undefined) {\n return new RecipientExporterContextImpl(this._api, this._kdf, res.exporterSecret);\n }\n return new RecipientContextImpl(this._api, this._kdf, res);\n }\n _validateInputLength(params) {\n if (params.info !== undefined &&\n params.info.byteLength > INFO_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long info\");\n }\n if (params.psk !== undefined) {\n if (params.psk.key.byteLength < MINIMUM_PSK_LENGTH) {\n throw new InvalidParamError(`PSK must have at least ${MINIMUM_PSK_LENGTH} bytes`);\n }\n if (params.psk.key.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long psk.key\");\n }\n if (params.psk.id.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long psk.id\");\n }\n }\n return;\n }\n}\n","import { base64UrlToBytes, DeriveKeyPairError, DeserializeError, EMPTY, KEM_USAGES, LABEL_DKP_PRK, LABEL_SK, NativeAlgorithm, NotSupportedError, SerializeError, toArrayBuffer, } from \"@hpke/common\";\nconst ALG_NAME = \"X25519\";\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_X25519 = new Uint8Array([\n 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,\n 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20,\n]);\nconst BASE_POINT_X25519 = /* @__PURE__ */ (() => {\n const p = new Uint8Array(32);\n p[0] = 9;\n return p;\n})();\nexport class X25519 extends NativeAlgorithm {\n constructor(hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._alg = { name: ALG_NAME };\n this._hkdf = hkdf;\n this._nPk = 32;\n this._nSk = 32;\n this._nDh = 32;\n this._pkcs8AlgId = PKCS8_ALG_ID_X25519;\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(ALG_NAME, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const rawIkm = toArrayBuffer(ikm);\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY, LABEL_DKP_PRK, new Uint8Array(rawIkm));\n const rawSk = await this._hkdf.labeledExpand(dkpPrk, LABEL_SK, EMPTY, this._nSk);\n const rawSkBytes = new Uint8Array(rawSk);\n const sk = await this._deserializePkcs8Key(rawSkBytes);\n rawSkBytes.fill(0);\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch {\n try {\n // Firefox fails to export JWK from some imported X25519 private keys.\n const bp = await this._api.importKey(\"raw\", BASE_POINT_X25519.buffer, this._alg, true, []);\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: bp,\n }, key, this._nPk * 8);\n return await this._api.importKey(\"raw\", bits, this._alg, true, []);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n }\n async dh(sk, pk) {\n await this._setup();\n try {\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.kty === \"undefined\" || key.kty !== \"OKP\") {\n throw new Error(`Invalid kty: ${key.crv}`);\n }\n if (typeof key.crv === \"undefined\" || key.crv !== ALG_NAME) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n}\n","import { base64UrlToBytes, DeriveKeyPairError, DeserializeError, EMPTY, KEM_USAGES, LABEL_DKP_PRK, LABEL_SK, NativeAlgorithm, NotSupportedError, SerializeError, toArrayBuffer, } from \"@hpke/common\";\nconst ALG_NAME = \"X448\";\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_X448 = new Uint8Array([\n 0x30, 0x46, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,\n 0x03, 0x2b, 0x65, 0x6f, 0x04, 0x3a, 0x04, 0x38,\n]);\nconst BASE_POINT_X448 = /* @__PURE__ */ (() => {\n const p = new Uint8Array(56);\n p[0] = 5;\n return p;\n})();\nexport class X448 extends NativeAlgorithm {\n constructor(hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._alg = { name: ALG_NAME };\n this._hkdf = hkdf;\n this._nPk = 56;\n this._nSk = 56;\n this._nDh = 56;\n this._pkcs8AlgId = PKCS8_ALG_ID_X448;\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(ALG_NAME, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const rawIkm = toArrayBuffer(ikm);\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY, LABEL_DKP_PRK, new Uint8Array(rawIkm));\n const rawSk = await this._hkdf.labeledExpand(dkpPrk, LABEL_SK, EMPTY, this._nSk);\n const rawSkBytes = new Uint8Array(rawSk);\n const sk = await this._deserializePkcs8Key(rawSkBytes);\n rawSkBytes.fill(0);\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch {\n try {\n // Some runtimes cannot export JWK from imported X448 private keys.\n const bp = await this._api.importKey(\"raw\", BASE_POINT_X448.buffer, this._alg, true, []);\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: bp,\n }, key, this._nPk * 8);\n return await this._api.importKey(\"raw\", bits, this._alg, true, []);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n }\n async dh(sk, pk) {\n await this._setup();\n try {\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.kty === \"undefined\" || key.kty !== \"OKP\") {\n throw new Error(`Invalid kty: ${key.crv}`);\n }\n if (typeof key.crv === \"undefined\" || key.crv !== ALG_NAME) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n}\n","import type { HttpClient } from './http.js';\nimport type { ProjectConfig } from './types.js';\n\nconst CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes\n\nexport class ConfigFetcher {\n protected readonly httpClient: HttpClient;\n private cachedConfig: ProjectConfig | null = null;\n private cacheTimestamp = 0;\n\n constructor(httpClient: HttpClient) {\n this.httpClient = httpClient;\n }\n\n async getConfig(): Promise<ProjectConfig | null> {\n const now = Date.now();\n\n if (this.cachedConfig && now - this.cacheTimestamp < CACHE_TTL_MS) {\n return this.cachedConfig;\n }\n\n try {\n const response = await this.httpClient.request<ProjectConfig>('GET', '/v1/config');\n\n if (response.error || !response.data) {\n return null;\n }\n\n this.cachedConfig = response.data;\n this.cacheTimestamp = now;\n\n return this.cachedConfig;\n } catch {\n return null;\n }\n }\n}\n","export class PalbaseError extends Error {\n readonly code: string;\n readonly status: number;\n readonly details?: unknown;\n\n constructor(code: string, message: string, status: number, details?: unknown) {\n super(message);\n this.name = 'PalbaseError';\n this.code = code;\n this.status = status;\n this.details = details;\n }\n}\n","export type Platform = 'browser' | 'node' | 'react-native' | 'deno' | 'bun';\n\ndeclare const Deno: unknown;\n\nexport function detectPlatform(): Platform {\n if (typeof Deno !== 'undefined') {\n return 'deno';\n }\n\n const runtime = globalThis as typeof globalThis & { process?: { versions?: Record<string, string> } };\n if (runtime.process?.versions) {\n if ('bun' in runtime.process.versions) {\n return 'bun';\n }\n if ('node' in runtime.process.versions) {\n return 'node';\n }\n }\n\n if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {\n return 'react-native';\n }\n\n return 'browser';\n}\n\n/**\n * The platform word this SDK puts on the wire (`X-Platform`), which the server\n * reads to target flags and to label telemetry.\n *\n * It is NOT `detectPlatform()`'s value verbatim: that reports the JS host\n * (\"browser\"), while the wire wants the platform. iOS sends \"ios\", not the name\n * of its runtime, and a condition author writes `client.platform == 'web'` —\n * the word every other flag vendor uses too. Server hosts keep their own names,\n * where the distinction is the useful part.\n */\nexport function wirePlatform(): string {\n const host = detectPlatform();\n return host === 'browser' ? 'web' : host;\n}\n","// Proof-of-work: the bot gate in front of /auth/signup and /auth/login.\n//\n// The server answers an unsolved request with 403 and a challenge in the body:\n//\n// { \"error\": \"pow_required\", \"challenge\": { \"id\", \"prefix\", \"difficulty\" } }\n//\n// A client finds any nonce whose SHA-256(prefix + nonce) begins with\n// `difficulty` zero bits, then repeats the request carrying the id and nonce as\n// headers. The work is the point: a person signing up pays it once and does not\n// notice, a script signing up ten thousand times pays it ten thousand times.\n//\n// # Why this lives in core, and not one layer up\n//\n// Until 2026-08-14 nothing shipped could solve it: the gate was written with the\n// server and its own integration harness, and every real client sent requests\n// without the headers and got 403. It was then solved in @palbase/web's own\n// request path — which covers `pb.call` and the module facades and NOT\n// `pb.auth.*`, because those go through @palbase/auth's client and from there\n// into core's HttpClient. So the fix landed everywhere except the two endpoints\n// the gate actually guards, and `npm i @palbase/web` still could not sign a\n// person in. Measured 2026-08-18 against a real stack, on the published 7.3.0.\n//\n// The lesson is where a retry belongs: at the layer that ISSUES the request.\n// Core owns fetch for every client in this repo, so core owns the challenge.\n//\n// WebCrypto rather than a hashing dependency: `crypto.subtle` is present in\n// browsers and in Node 18+, which is the same floor the rest of the SDK sets.\n// Measured at the server's default difficulty of 16: ~330ms, ~65k digests.\n\n/** The challenge a `pow_required` response carries. */\nexport interface PowChallenge {\n id: string;\n prefix: string;\n difficulty: number;\n}\n\n/** Header names the retry must carry. Mirrors the server's constants. */\nexport const POW_CHALLENGE_ID_HEADER = 'X-PoW-Challenge-ID';\nexport const POW_NONCE_HEADER = 'X-PoW-Nonce';\n\n/**\n * Reads a challenge out of an error envelope, or returns null when the envelope\n * is not a `pow_required` one.\n *\n * The whole wire envelope is stored on the error, so the challenge arrives\n * without the HTTP layer having to know about proof-of-work at all.\n */\nexport function asPowChallenge(details: unknown): PowChallenge | null {\n if (typeof details !== 'object' || details === null) return null;\n const env = details as Record<string, unknown>;\n if (env.error !== 'pow_required') return null;\n const c = env.challenge;\n if (typeof c !== 'object' || c === null) return null;\n const { id, prefix, difficulty } = c as Record<string, unknown>;\n if (typeof id !== 'string' || typeof prefix !== 'string') return null;\n if (typeof difficulty !== 'number' || !Number.isInteger(difficulty) || difficulty < 0) return null;\n return { id, prefix, difficulty };\n}\n\nconst encoder = new TextEncoder();\n\n/**\n * One SHA-256, by the fastest route this runtime offers.\n *\n * Awaiting `crypto.subtle.digest` once per nonce is what made this expensive,\n * and the cost is the await rather than the hashing. Measured on one machine,\n * 200k digests of a 40-byte input:\n *\n *\tawaited crypto.subtle.digest 105,597 digests/s\n *\tsync node:crypto createHash 1,324,503 digests/s — 12.5x\n *\n * That is the difference between difficulty 24 taking 159 seconds and taking\n * 13. Node, Bun and Deno all have the sync one; a browser has only WebCrypto,\n * and there it stays async.\n *\n * The specifier is assembled at runtime so a browser bundler does not try to\n * resolve `node:crypto` and fail the build over a branch that never runs there.\n */\ntype Hasher = (input: string) => Uint8Array | Promise<Uint8Array>;\n\nlet hasher: Hasher | null = null;\n\nasync function digester(): Promise<Hasher> {\n if (hasher) return hasher;\n // Read off globalThis with an inline shape rather than by naming `process`,\n // which needs @types/node — a dependency this package does not have and should\n // not grow for one branch. It typechecked locally only because those types\n // were hoisted into node_modules by a sibling package; the publish workflow's\n // clean checkout is what said so, which is exactly what it is for.\n const runtime = globalThis as {\n process?: { versions?: { node?: string; bun?: string } };\n };\n const nodeish =\n runtime.process?.versions?.node !== undefined ||\n runtime.process?.versions?.bun !== undefined;\n if (nodeish) {\n try {\n const mod = (await import(/* @vite-ignore */ `${'node:'}crypto`)) as {\n createHash?: (alg: string) => { update(s: string): { digest(): Uint8Array } };\n };\n if (typeof mod.createHash === 'function') {\n const createHash = mod.createHash;\n hasher = (input: string) => new Uint8Array(createHash('sha256').update(input).digest());\n return hasher;\n }\n } catch {\n // No node:crypto here. WebCrypto below is not a fallback in the apologetic\n // sense — it is the only hash a browser has, and it is correct.\n }\n }\n hasher = async (input: string) =>\n new Uint8Array(await crypto.subtle.digest('SHA-256', encoder.encode(input)));\n return hasher;\n}\n\n/** Monotonic where it exists, wall-clock where it does not. */\nconst now = (): number =>\n typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now()\n : Date.now();\n\n/** Counts leading zero bits, stopping at the first byte that has a one. */\nfunction leadingZeroBits(hash: Uint8Array): number {\n let bits = 0;\n for (const byte of hash) {\n if (byte === 0) {\n bits += 8;\n continue;\n }\n // clz32 counts across 32 bits; a byte occupies the low 8, so the first 24\n // are always zero and get subtracted back off.\n return bits + Math.clz32(byte) - 24;\n }\n return bits;\n}\n\n/**\n * The hardest challenge this client will attempt.\n *\n * Not a taste: it is the server's own ceiling. palauth maps a risk score to a\n * difficulty and its worst case is 24 (`DifficultyForRisk`, bot/pow.go:156-166).\n * Anything above that cannot have come from a stack behaving as designed, and\n * the cost of humouring it falls entirely on this side — each step up DOUBLES\n * the work, so difficulty 30 is sixty-four times a legitimate worst case and, on\n * the web, sixty-four times a frozen main thread. Refused immediately, by name.\n */\nexport const MAX_POW_DIFFICULTY = 24;\n\n/**\n * Finds a nonce satisfying the challenge and returns the headers a retry needs.\n *\n * THE BUDGET SCALES WITH THE CHALLENGE, and the first version of this did not.\n * It bounded the search at a flat `1 << 24` — which is not a generous bound for\n * difficulty 24, it is the EXPECTED number of attempts. Finding a nonce is a\n * geometric process: the chance of needing more than 2^d attempts is 1/e, so a\n * flat 2^24 would have failed roughly 37% of legitimate hardest-risk challenges,\n * and failed them for precisely the users the gate exists to slow down — who\n * would have been unable to sign in at all rather than made to wait.\n *\n * Eight times expected puts that at e^-8, about three in ten thousand, while\n * leaving the common case (the server's default 16, and 12 for an unremarkable\n * caller) exactly as cheap as it was.\n *\n * `powBudget` is exported and separate so the RELATIONSHIP can be asserted\n * directly. A test that only watches a cheap challenge succeed cannot tell this\n * budget from the flat one it replaced — measured: reinstating `1 << 24` left\n * such a test green.\n */\nexport function powBudget(difficulty: number): number {\n return 8 * 2 ** difficulty;\n}\n\n/**\n * The longest a solve may be ALLOWED to take, and the difference from a\n * deadline is the whole point.\n *\n * The first version of this was a flat 120s deadline, and it was measured to be\n * worse than the flat iteration budget it was meant to backstop: at ~105k\n * digests/s, difficulty 24 EXPECTS 159 seconds, so a 120s clock killed the\n * majority of legitimate hardest-risk solves — reintroducing, larger, exactly\n * the class of defect that replacing `1 << 24` had removed. Guessing a number\n * for an unknown machine cannot work: the same difficulty is 13 seconds on a\n * runtime with a sync hasher and 159 on one without.\n *\n * So the machine is MEASURED, and the decision moves to the front. A short\n * calibration gives the rate this process actually hashes at; if the whole\n * iteration budget cannot fit in this window at that rate, the solve is refused\n * IMMEDIATELY, naming the numbers. A caller then learns in milliseconds that\n * this difficulty is unpayable here, instead of after two minutes of work\n * thrown away.\n *\n * What remains after that is a guarantee rather than a gamble: a solve that\n * starts can always finish inside its budget, so the only failure left is the\n * budget's own e^-8.\n */\nexport const POW_TIME_BUDGET_MS = 120_000;\n\n/**\n * The window the rate is measured over, and the warm-up it deliberately skips.\n *\n * All of these are REAL attempts — the search starts at nonce 0 and never\n * restarts — so calibration costs nothing but the reading. The first 1024 are\n * excluded from the timing because they include this loop's own JIT warm-up:\n * measured, timing from zero reported 747k digests/s on a machine whose steady\n * rate is 1.32M, and the decision below would have refused a difficulty this\n * machine can pay in half the allowance.\n */\nconst CALIBRATION_WARMUP = 1024;\nconst CALIBRATION_END = 9216;\n\nexport async function solvePowChallenge(\n challenge: PowChallenge,\n maxIterations = powBudget(challenge.difficulty),\n // The caller's AbortSignal, honoured INSIDE the loop rather than only around\n // the fetch it precedes — for the callers that have one. `pb.auth.signIn` does\n // NOT: it reaches the network through @palbase/auth's client, which takes\n // credentials and nothing else. So it is the extra a caller can opt into, and\n // POW_TIME_BUDGET_MS below is what actually bounds the work.\n signal?: AbortSignal,\n): Promise<Record<string, string>> {\n if (challenge.difficulty > MAX_POW_DIFFICULTY) {\n throw new Error(\n `proof-of-work: refusing difficulty ${challenge.difficulty}; this client attempts at most ${MAX_POW_DIFFICULTY}, which is the highest a Palbase stack issues`,\n );\n }\n\n const digest = await digester();\n let warmedAt = 0;\n let calibrated = false;\n // Armed by the calibration below, never before it: until the rate is known\n // there is no honest number to put here.\n let deadline = Number.POSITIVE_INFINITY;\n\n for (let nonce = 0; nonce < maxIterations; nonce++) {\n // Checked in batches: reading them is cheap but not free, and a\n // 1024-digest granularity bounds the delay at a few milliseconds.\n if ((nonce & 1023) === 0) {\n if (signal?.aborted) {\n throw new DOMException('proof-of-work solve aborted', 'AbortError');\n }\n if (now() > deadline) {\n throw new Error(\n `proof-of-work: gave up on difficulty ${challenge.difficulty} after ${POW_TIME_BUDGET_MS / 1000}s ` +\n `and ${nonce.toLocaleString()} attempts — the tail this run drew is longer than the allowance`,\n );\n }\n }\n\n // THE DECISION, TAKEN ONCE AND TAKEN EARLY.\n //\n // After CALIBRATION_DIGESTS real attempts the rate of THIS process is\n // known, so the question \"can this machine pay this difficulty\" has an\n // answer instead of an assumption. If the whole budget cannot fit in the\n // time budget, refuse here — milliseconds in, with the numbers — rather\n // than spend two minutes and throw them away. If it fits, everything after\n // this point is guaranteed to finish inside the window, so the only\n // remaining failure is the budget's own e^-8.\n if (nonce === CALIBRATION_WARMUP) {\n warmedAt = now();\n }\n if (!calibrated && nonce === CALIBRATION_END) {\n calibrated = true;\n const elapsed = Math.max(now() - warmedAt, 0.001);\n const rate = (CALIBRATION_END - CALIBRATION_WARMUP) / (elapsed / 1000);\n // EXPECTED, not worst case, and the difference is the whole judgement.\n //\n // Finding a nonce is geometric: 2^difficulty attempts on average, with a\n // long tail the 8x budget covers. Refusing because the TAIL will not fit\n // would turn away work whose expected cost is seventeen seconds — measured\n // exactly that on this machine at difficulty 24. Refusing on the EXPECTED\n // cost turns away only what is genuinely unpayable here, and what it lets\n // through is then cut by the clock with probability e^-(budget/expected):\n // at 120s against a 17s expectation that is one run in a thousand, and at\n // difficulty 20 on a browser it is one in a hundred and fifty thousand.\n const expectedMs = (2 ** challenge.difficulty / rate) * 1000;\n if (expectedMs > POW_TIME_BUDGET_MS) {\n throw new Error(\n `proof-of-work: difficulty ${challenge.difficulty} needs about ${Math.round(expectedMs / 1000)}s here ` +\n `(${Math.round(rate).toLocaleString()} digests/s) and this client allows ${POW_TIME_BUDGET_MS / 1000}s; ` +\n `refusing before spending the time rather than after`,\n );\n }\n deadline = now() + (POW_TIME_BUDGET_MS - (now() - warmedAt));\n }\n\n const hash = await digest(challenge.prefix + nonce);\n if (leadingZeroBits(hash) >= challenge.difficulty) {\n return {\n [POW_CHALLENGE_ID_HEADER]: challenge.id,\n [POW_NONCE_HEADER]: String(nonce),\n };\n }\n }\n throw new Error(\n `proof-of-work: no nonce found for difficulty ${challenge.difficulty} within ${maxIterations} attempts`,\n );\n}\n","import { Chacha20Poly1305 } from '@hpke/chacha20poly1305';\nimport { CipherSuite, HkdfSha256 } from '@hpke/core';\nimport { DhkemX25519HkdfSha256 } from '@hpke/dhkem-x25519';\nimport { PalbaseError } from './errors.js';\nimport { fromBase64, toBase64 } from './sealed-json.js';\nimport type { SealingKey } from './sealed-keys.js';\n\nexport const SEALED_CONTENT_TYPE = 'application/palbase-sealed+json';\nexport const SEALED_HEADER = 'X-Palbase-Sealed';\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder('utf-8', { fatal: true });\nconst responseLabel = 'palbase-sealed/response/v1';\n\nexport function sealingRequired(path: string): boolean {\n // Mirrors v2/internal/server/sealed.go. Tenant/runtime routes cannot unseal.\n return new URL(path, 'https://unused.invalid').pathname.startsWith('/auth/');\n}\n\nexport function requestAAD(\n host: string,\n method: string,\n path: string,\n ict: string,\n ts: number,\n idem: string,\n): Uint8Array<ArrayBuffer> {\n const fields = [host, method, path, ict, idem].map((field) => encoder.encode(field));\n const bytes = new Uint8Array(fields.reduce((size, field) => size + 4 + field.length, 8));\n const view = new DataView(bytes.buffer);\n let offset = 0;\n for (const [index, field] of fields.entries()) {\n if (index === 4) {\n view.setBigUint64(offset, BigInt(ts));\n offset += 8;\n }\n view.setUint32(offset, field.length);\n offset += 4;\n bytes.set(field, offset);\n offset += field.length;\n }\n return bytes;\n}\n\nexport function sealingSuite(): CipherSuite {\n return new CipherSuite({\n kem: new DhkemX25519HkdfSha256(),\n kdf: new HkdfSha256(),\n aead: new Chacha20Poly1305(),\n });\n}\n\nexport async function sealRequest(\n key: SealingKey,\n url: string,\n init: RequestInit,\n): Promise<Uint8Array<ArrayBuffer>> {\n const suite = sealingSuite();\n const sender = await suite.createSenderContext({\n recipientPublicKey: await suite.kem.importKey('raw', key.publicKey.buffer),\n });\n const headers = new Headers(init.headers);\n const ict = headers.get('content-type') ?? 'application/json';\n const ts = Math.floor(Date.now() / 1000);\n const target = new URL(url);\n const method = init.method ?? 'GET';\n // Go binds r.URL.Path (decoded, without the query), not RequestURI.\n const aad = requestAAD(\n target.host,\n method,\n decodeURIComponent(target.pathname),\n ict,\n ts,\n headers.get('idempotency-key') ?? '',\n );\n const ct = await sender.seal(encoder.encode(typeof init.body === 'string' ? init.body : ''), aad);\n const envelope = JSON.stringify({\n v: 2,\n kid: key.kid,\n enc: toBase64(new Uint8Array(sender.enc)),\n ct: toBase64(new Uint8Array(ct)),\n ict,\n ts,\n });\n if (method === 'GET' || method === 'HEAD' || init.body === undefined) {\n headers.set(\n SEALED_HEADER,\n toBase64(encoder.encode(envelope)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, ''),\n );\n delete init.body;\n } else {\n headers.delete(SEALED_HEADER);\n headers.set('Content-Type', SEALED_CONTENT_TYPE);\n init.body = envelope;\n }\n headers.delete('Content-Length');\n init.headers = Object.fromEntries(headers.entries());\n // Do not redirect a credential-bearing envelope to a different endpoint.\n init.redirect = 'error';\n return new Uint8Array(await sender.export(encoder.encode(responseLabel), 32));\n}\n\nexport async function openSealedResponse(\n response: Response,\n exporter: Uint8Array | undefined,\n method: string,\n): Promise<Response> {\n if (\n response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() !==\n SEALED_CONTENT_TYPE\n ) {\n // Edge/middleware errors are plaintext. A successful auth result cannot be.\n if (exporter && response.ok && method !== 'HEAD') {\n throw new PalbaseError(\n 'sealed_response_invalid',\n 'The server returned an unencrypted response.',\n response.status,\n );\n }\n return response;\n }\n // HTTP HEAD has no response body, including when the handler sealed it.\n if (method === 'HEAD') return response;\n try {\n if (!exporter) throw new Error('No sealing context');\n const envelope = (await response.json()) as {\n v: number;\n n: string;\n ct: string;\n ict: string;\n st: number;\n };\n if (\n envelope.v !== 2 ||\n !Number.isInteger(envelope.st) ||\n envelope.st < 200 ||\n envelope.st > 599 ||\n typeof envelope.ict !== 'string'\n ) {\n throw new Error('Invalid response envelope');\n }\n const plaintext = await new Chacha20Poly1305()\n .createEncryptionContext(exporter)\n .open(\n fromBase64(envelope.n),\n fromBase64(envelope.ct),\n encoder.encode(`${responseLabel}\\n${envelope.ict}\\n${envelope.st}`),\n );\n const headers = new Headers(response.headers);\n headers.set('Content-Type', envelope.ict);\n headers.delete('Content-Length');\n headers.delete('Content-Encoding');\n // The outer status is always 200; auth failures and PoW live inside the seal.\n return new Response([204, 205, 304].includes(envelope.st) ? null : decoder.decode(plaintext), {\n status: envelope.st,\n headers,\n });\n } catch {\n throw new PalbaseError(\n 'sealed_response_invalid',\n 'The encrypted server response could not be verified.',\n response.status,\n );\n }\n}\n","// Signatures cover the original JSON bytes, not JSON.stringify(JSON.parse(raw)).\n// Go's encoder preserves struct field order and escapes characters differently.\nexport function rawObjectFields(raw: string): Map<string, string> {\n const parsed: unknown = JSON.parse(raw);\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('Expected a JSON object');\n }\n const fields = new Map<string, string>();\n let i = 0;\n const space = () => {\n while (/\\s/.test(raw[i] ?? '') && i < raw.length) i++;\n };\n const stringEnd = (start: number) => {\n let end = start + 1;\n while (end < raw.length) {\n if (raw[end] === '\\\\') end += 2;\n else if (raw[end++] === '\"') return end;\n }\n throw new Error('Unterminated JSON string');\n };\n space();\n i++; // opening object, already validated by JSON.parse\n while (true) {\n space();\n if (raw[i] === '}') return fields;\n const nameEnd = stringEnd(i);\n const name = JSON.parse(raw.slice(i, nameEnd)) as string;\n i = nameEnd;\n space();\n i++; // colon\n space();\n const start = i;\n if (raw[i] === '\"') i = stringEnd(i);\n else if (raw[i] === '{' || raw[i] === '[') {\n let depth = 0;\n do {\n const c = raw[i];\n if (c === '\"') {\n i = stringEnd(i);\n continue;\n }\n if (c === '{' || c === '[') depth++;\n if (c === '}' || c === ']') depth--;\n i++;\n } while (depth > 0 && i < raw.length);\n } else {\n while (i < raw.length && !/[\\s,}]/.test(raw[i] ?? '')) i++;\n }\n // A first-match slice and JSON.parse's last-match value must never disagree.\n if (fields.has(name)) throw new Error('Duplicate JSON field');\n fields.set(name, raw.slice(start, i));\n space();\n if (raw[i] === ',') i++;\n }\n}\n\nexport function fromBase64(value: string): Uint8Array<ArrayBuffer> {\n return Uint8Array.from(atob(value), (c) => c.charCodeAt(0));\n}\n\nexport function toBase64(bytes: Uint8Array): string {\n // Avoid a spread: envelopes can exceed the engine's argument-count limit.\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n","import { ed25519 } from '@noble/curves/ed25519.js';\nimport { PalbaseError } from './errors.js';\nimport { fromBase64, rawObjectFields } from './sealed-json.js';\nimport { endpointUrl } from './url.js';\nimport type { HttpClientOptions } from './types.js';\n\nexport const SEALED_KEYSET_PATH = '/palbase-sealed-keys.json';\nexport const SEALED_SUITE = 'DHKEM-X25519-HKDF-SHA256/HKDF-SHA256/ChaCha20Poly1305';\n// Fleet PUBLIC key, identical to the iOS SDK pin. Never learned from a response.\nconst FLEET_ROOT = 'mRDTIWzhW0JCk0e2Jvkn679VeZBB38zOOfPTMO6vBpU=';\nconst REFRESH_MS = 5 * 60_000;\nconst FAILURE_COOLDOWN_MS = 60_000;\nconst encoder = new TextEncoder();\n\nexport interface SealingKey {\n kid: string;\n publicKey: Uint8Array<ArrayBuffer>;\n expires: number;\n version: number;\n}\n\nexport function expectedSealedStack(baseUrl: string, apiKey: string): string {\n // Fleet tenant hosts name the stack even when a legacy key says pb_project_.\n // Apex/custom/self-host URLs instead need the key's ref (or an explicit pin).\n const host = new URL(baseUrl).hostname;\n return (\n /^([a-z0-9]{4,24})\\.(?:(?:dev|staging)\\.)?palbase\\.studio$/.exec(host)?.[1] ??\n /^pb_([^_]+)_/.exec(apiKey)?.[1] ??\n ''\n );\n}\n\nfunction record(raw: string | undefined): Record<string, unknown> {\n if (!raw) throw new Error('Missing signed object');\n rawObjectFields(raw); // also refuses duplicate fields\n return JSON.parse(raw) as Record<string, unknown>;\n}\n\nfunction string(value: unknown): string {\n if (typeof value !== 'string' || !value) throw new Error('Missing string');\n return value;\n}\n\nfunction integer(value: unknown): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new Error('Invalid integer');\n }\n return value;\n}\n\nfunction verifySignature(raw: string, signed: Record<string, unknown>, publicKey: Uint8Array) {\n if (\n signed.alg !== 'ed25519' ||\n publicKey.length !== 32 ||\n !ed25519.verify(fromBase64(string(signed.sig)), encoder.encode(raw), publicKey, {\n zip215: false,\n })\n )\n throw new Error('Invalid sealed key signature');\n}\n\n/** Verify fleet → expected stack → keyset, retaining the exact signed bytes. */\nexport function verifySealingKey(\n raw: string,\n expectedRef: string,\n root: string,\n lastVersion: number,\n now: number,\n): SealingKey {\n const fields = rawObjectFields(raw);\n const signed = record(raw);\n const statementRaw = fields.get('binding');\n const statement = record(statementRaw);\n const bindingRaw = rawObjectFields(statementRaw ?? '').get('binding');\n if (!bindingRaw || statement.rootKid !== 'sealed-root-v1') {\n throw new Error('Unknown sealed trust root');\n }\n verifySignature(bindingRaw, statement, fromBase64(root));\n const binding = record(bindingRaw);\n if (\n binding.v !== 1 ||\n !expectedRef ||\n string(binding.stackRef).trim().toLowerCase() !== expectedRef.toLowerCase()\n ) {\n throw new Error('Sealed binding belongs to another stack');\n }\n const bindingExpiry = integer(binding.expires);\n if (bindingExpiry * 1000 <= now) throw new Error('Expired sealed binding');\n const keysetRaw = fields.get('keyset');\n if (!keysetRaw) throw new Error('Missing sealed keyset');\n verifySignature(keysetRaw, signed, fromBase64(string(binding.signingKey)));\n const keyset = record(keysetRaw);\n const version = integer(keyset.version);\n const expires = Math.min(integer(keyset.expires), bindingExpiry);\n if (version < lastVersion) throw new Error('Sealed keyset version went backwards');\n if (expires * 1000 <= now) throw new Error('Expired sealed keyset');\n if (keyset.v !== 1 || !Array.isArray(keyset.keys)) throw new Error('Invalid sealed keyset');\n for (const item of keyset.keys) {\n if (item === null || typeof item !== 'object') continue;\n const entry = item as Record<string, unknown>;\n if (entry.alg !== SEALED_SUITE) continue;\n const publicKey = fromBase64(string(entry.pub));\n if (publicKey.length !== 32) throw new Error('Invalid sealing public key');\n return { kid: string(entry.kid), publicKey, expires, version };\n }\n throw new Error('No supported sealing key');\n}\n\nexport class SealedKeyStore {\n private cached?: SealingKey;\n private pending?: Promise<SealingKey>;\n private fetchedAt = 0;\n private retryAfter = 0;\n private lastVersion = 0;\n private lastError?: PalbaseError;\n private rotationRefreshAt = 0;\n\n constructor(\n private readonly baseUrl: string,\n private readonly apiKey: string,\n private readonly options?: Exclude<HttpClientOptions['sealed'], false>,\n ) {}\n\n async current(signal?: AbortSignal, rotate = false): Promise<SealingKey> {\n signal?.throwIfAborted();\n const now = Date.now();\n const valid = this.cached && this.cached.expires * 1000 > now ? this.cached : undefined;\n if (this.pending) return this.waitFor(this.pending, signal);\n // A forged unknown-kid response cannot turn every request into a key fetch.\n if (rotate && now - this.rotationRefreshAt >= FAILURE_COOLDOWN_MS) {\n this.fetchedAt = 0;\n this.retryAfter = 0;\n this.rotationRefreshAt = now;\n }\n if (valid && now - this.fetchedAt < REFRESH_MS) return valid;\n if (now < this.retryAfter) {\n if (valid) return valid;\n throw this.lastError;\n }\n const pending = this.fetchKey()\n .then((key) => {\n this.cached = key;\n this.lastVersion = key.version;\n this.fetchedAt = Date.now();\n this.retryAfter = 0;\n return key;\n })\n .catch((error: unknown) => {\n this.retryAfter = Date.now() + FAILURE_COOLDOWN_MS;\n this.lastError =\n error instanceof PalbaseError\n ? error\n : new PalbaseError(\n 'sealed_key_unavailable',\n 'The server encryption key could not be verified. Please try again later.',\n 0,\n );\n // A transient refresh failure may reuse a verified, unexpired key only.\n if (this.cached && this.cached.expires * 1000 > Date.now()) return this.cached;\n throw this.lastError;\n })\n .finally(() => {\n this.pending = undefined;\n });\n this.pending = pending;\n return this.waitFor(pending, signal);\n }\n\n private async fetchKey(): Promise<SealingKey> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), 15_000);\n try {\n const response = await fetch(endpointUrl(this.baseUrl, SEALED_KEYSET_PATH), {\n headers: this.apiKey ? { apikey: this.apiKey } : {},\n signal: controller.signal,\n cache: 'no-store',\n redirect: 'error',\n });\n if (!response.ok) throw new Error('Sealed keyset unavailable');\n const raw = await response.text();\n if (raw.length > 64 * 1024) throw new Error('Sealed keyset too large');\n const expectedRef = this.options?.stackRef ?? expectedSealedStack(this.baseUrl, this.apiKey);\n return verifySealingKey(\n raw,\n expectedRef,\n this.options?.root ?? FLEET_ROOT,\n this.lastVersion,\n Date.now(),\n );\n } finally {\n clearTimeout(timer);\n }\n }\n\n // One caller's cancellation must not abort a shared key fetch for other calls.\n private waitFor(pending: Promise<SealingKey>, signal?: AbortSignal): Promise<SealingKey> {\n if (!signal) return pending;\n return new Promise((resolve, reject) => {\n const aborted = () => reject(signal.reason);\n signal.addEventListener('abort', aborted, { once: true });\n pending.then(resolve, reject).finally(() => signal.removeEventListener('abort', aborted));\n if (signal.aborted) aborted();\n });\n }\n}\n","/**\n * Join the configured base URL with an SDK path.\n *\n * A BASE URL MAY CARRY A PATH, NOT JUST AN ORIGIN — a self-host published\n * under `https://api.example.com/palbase`, or an app that routes the browser\n * through its own server (`<origin>/pb`, rewritten upstream) because the\n * Environment's edge does not answer its origin with CORS headers.\n *\n * `new URL('/palbase-sealed-keys.json', base)` reads as the careful way to do\n * this and is the one form that DROPS that path: the leading slash makes the\n * path absolute against the base's ORIGIN. The sealed key store used it while\n * every ordinary request concatenated, so one request in the client asked a\n * different server than all the others — measured live 2026-09-11, the keyset\n * fetch landed on the app's own 404 page and every sealed call failed with\n * `sealed_key_unavailable`. The other two SDK surfaces never had the split:\n * iOS appends (`SealedKeyStore.swift`), Android concatenates onto a\n * slash-trimmed base (`SealedKeyStore.kt`) — this is their shape.\n */\nexport function endpointUrl(base: string, path: string): string {\n return `${base.replace(/\\/+$/, '')}${path}`;\n}\n","import { PalbaseError } from './errors.js';\nimport { wirePlatform } from './platform.js';\nimport { asPowChallenge, solvePowChallenge } from './pow.js';\nimport { openSealedResponse, sealingRequired, sealRequest } from './sealed.js';\nimport { SealedKeyStore } from './sealed-keys.js';\nimport type { TokenManager } from './token.js';\nimport { endpointUrl } from './url.js';\nimport type { HttpClientOptions, PalbaseResponse, RequestOptions } from './types.js';\n\n/**\n * Default production host. Dev / staging / local callers override via\n * `options.url`. Apex-style routing is the only supported production path;\n * Kong resolves Environment identity from the API key.\n */\nconst PALBASE_DEFAULT_HOST = 'api.palbase.studio';\n\n/**\n * Parse the Environment ref from a Palbase API key.\n *\n * Canonical shape: `pb_{environment_ref}_c{random}`, where the Environment ref\n * is 4-24 lowercase ASCII alphanumeric characters and random is AT LEAST 20\n * base62 chars.\n *\n * The length is a floor, not an equality. The stack's own minter writes 20\n * (v2/cmd/palsvc/initenv.go) and the cloud control plane writes 32\n * (cloud/platform/server/services/keys.ts), and the door that admits the\n * request refuses to rule on the difference: *\"a shorter or longer secret is\n * not a security property this door can rule on\"*\n * (v2/internal/platform/identitymw.go: parseAPIKey). A client that is stricter\n * than the server does not add safety — it just refuses working keys, which is\n * exactly what this one did to every cloud project until 2026-08-25.\n *\n * Returns the Environment ref on match; `null` otherwise.\n */\nconst API_KEY_RE = /^pb_([a-z0-9]{4,24})_c[A-Za-z0-9]{20,}$/;\n\nfunction parseEnvironmentRef(apiKey: string): string | null {\n return API_KEY_RE.exec(apiKey)?.[1] ?? null;\n}\nconst MAX_RETRIES = 3;\nconst INITIAL_BACKOFF_MS = 200;\n/**\n * Upper bound on a single 429 retry sleep. A server may return a long\n * Retry-After (a locked account can send minutes/hours); honoring it verbatim\n * would HANG the request for that whole window. Cap each retry at 10s — after\n * MAX_RETRIES the 429 envelope surfaces to the caller (fail fast, don't sleep\n * minutes). The clamp never skips a retry; it only bounds how long each waits.\n */\nconst MAX_RETRY_DELAY_MS = 10_000;\n\n/**\n * Carry a 429's retry hint into the error envelope when only the header has it.\n *\n * A REFUSAL FROM THE EDGE CARRIES NOTHING BUT THE HEADER. Envoy and the\n * gateway limiter answer before any Palbase service is reached, so their 429\n * has no `retry_after` and no `data.retryAfter` — and every reader above this\n * layer (`@palbase/web`'s BackendError, the iOS SDK) looks in the BODY. The\n * seconds were on the wire and unreachable to all of them.\n *\n * Lifted under `retry_after`, the platform's own name for it (palauth's\n * rate-limit envelope), never overwriting a hint the service itself sent — a\n * service knows its window, the edge only knows its own.\n */\nfunction withRetryHint(\n body: Record<string, unknown> | undefined,\n response: Response,\n): Record<string, unknown> | undefined {\n if (response.status !== 429) return body;\n const data = body?.data;\n const alreadyStated =\n typeof body?.retry_after === 'number' ||\n (typeof data === 'object' && data !== null && 'retryAfter' in data);\n if (alreadyStated) return body;\n const seconds = Number.parseInt(response.headers.get('Retry-After') ?? '', 10);\n if (Number.isNaN(seconds) || seconds <= 0) return body;\n return { ...body, retry_after: seconds };\n}\n\n/**\n * Request interceptor. Runs before every HTTP request.\n * Can modify headers, body, or reject the request.\n */\nexport type RequestInterceptor = (request: {\n headers: Record<string, string>;\n method: string;\n path: string;\n}) => void | Promise<void>;\n\nexport class HttpClient {\n protected readonly apiKey: string;\n protected readonly options?: HttpClientOptions;\n\n tokenManager: TokenManager | null = null;\n\n /**\n * Admin JWT used for platform admin endpoints (/admin/*).\n * When set, takes precedence over tokenManager access token in the\n * Authorization header.\n */\n adminToken: string | null = null;\n\n private readonly interceptors: RequestInterceptor[] = [];\n private readonly forbiddenListeners = new Set<(body: Record<string, unknown>) => void>();\n private sealedKeys?: SealedKeyStore;\n\n constructor(apiKey: string, options?: HttpClientOptions) {\n this.apiKey = apiKey;\n this.options = options;\n }\n\n /** Set (or clear) the admin JWT used on admin endpoints. */\n setAdminToken(token: string | null): void {\n this.adminToken = token;\n }\n\n /**\n * Called with the RAW body of every 403 this client receives (FR-010). Core\n * does not know the envelope's fields — the layer that does (palbe) reads\n * `required` out of it. Nothing is retried or swallowed: the error still\n * returns to the caller.\n */\n onForbidden(handler: (body: Record<string, unknown>) => void): () => void {\n this.forbiddenListeners.add(handler);\n return () => {\n this.forbiddenListeners.delete(handler);\n };\n }\n\n /**\n * Create a scoped HttpClient that adds the given extra headers to every\n * request. The returned client shares the admin token and token manager\n * with the parent at runtime — later changes on the parent propagate to\n * the scope and vice versa.\n *\n * Typical use: adding an Environment-routing header for an admin call.\n */\n withHeaders(extra: Record<string, string>): HttpClient {\n const mergedHeaders = { ...(this.options?.headers ?? {}), ...extra };\n\n const scoped: HttpClient = new HttpClient(this.apiKey, {\n ...this.options,\n headers: mergedHeaders,\n });\n scoped.tokenManager = this.tokenManager;\n // Delegate adminToken reads + writes to the parent so the scope always\n // sees the latest token, and setAdminToken on the scope affects the parent.\n // The scope shares the parent's 403 listeners: a refusal is a refusal\n // whichever header set the request carried.\n Object.defineProperty(scoped, 'forbiddenListeners', {\n get: () => this.forbiddenListeners,\n });\n Object.defineProperty(scoped, 'adminToken', {\n get: () => this.adminToken,\n set: (v: string | null) => {\n this.adminToken = v;\n },\n configurable: true,\n });\n Object.defineProperty(scoped, 'sealedKeys', {\n get: () => this.sealedKeys,\n set: (v: SealedKeyStore | undefined) => {\n this.sealedKeys = v;\n },\n });\n return scoped;\n }\n\n /** Add a request interceptor. Runs before every request. */\n addInterceptor(interceptor: RequestInterceptor): void {\n this.interceptors.push(interceptor);\n }\n\n async request<T>(\n method: string,\n path: string,\n options?: RequestOptions,\n ): Promise<PalbaseResponse<T>> {\n // If token is expired and refresh is available, refresh before making the request\n if (\n !options?.skipSessionRefresh &&\n this.tokenManager?.isExpired() &&\n this.tokenManager.getRefreshToken() &&\n this.tokenManager.refreshFunction\n ) {\n try {\n await this.tokenManager.refreshSession();\n } catch (e) {\n const status = e instanceof PalbaseError ? e.status : 0;\n if (status === 400 || status === 401 || status === 403) {\n // Terminal: the refresh token is dead (revoked/expired/forbidden).\n // Clear the session (listeners persist the sign-out) and proceed\n // unauthenticated — the endpoint will 401 into the normal error\n // envelope instead of bricking every subsequent call including\n // the recovery sign-in.\n this.tokenManager.clearSession();\n } else {\n throw e; // network/5xx: transient, stay loud\n }\n }\n }\n\n return this.executeWithRetry<T>(method.toUpperCase(), path, options, 0);\n }\n\n /**\n * A response read as it arrives, for `text/event-stream` routes.\n *\n * Deliberately NOT `executeWithRetry`: a retry replays the request, and a\n * stream the caller has already begun reading cannot be replayed — the frames\n * it handed over would arrive a second time. A stream that fails to open fails\n * to the caller, once, with its status.\n *\n * The buffered path's headers, base URL and interceptors are reused verbatim,\n * so a streaming call is authenticated exactly like every other call; only the\n * body handling differs. `Accept` says what the caller wants, and the status\n * is returned beside the body because the CALLER decides what a non-2xx means\n * (an error envelope arrives as an ordinary buffered body).\n */\n async requestStream(\n method: string,\n path: string,\n options?: RequestOptions,\n ): Promise<{ status: number; body: ReadableStream<Uint8Array> | null; contentType: string }> {\n method = method.toUpperCase();\n if (\n !options?.skipSessionRefresh &&\n this.tokenManager?.isExpired() &&\n this.tokenManager.getRefreshToken() &&\n this.tokenManager.refreshFunction\n ) {\n try {\n await this.tokenManager.refreshSession();\n } catch (e) {\n const status = e instanceof PalbaseError ? e.status : 0;\n if (status === 400 || status === 401 || status === 403) {\n this.tokenManager.clearSession();\n } else {\n throw e;\n }\n }\n }\n\n const url = endpointUrl(this.getBaseUrl(), path);\n const headers = { ...this.buildHeaders(options), Accept: 'text/event-stream' };\n for (const interceptor of this.interceptors) {\n await interceptor({ headers, method, path });\n }\n\n const fetchOptions: RequestInit = { method, headers, signal: options?.signal };\n if (options?.body !== undefined) fetchOptions.body = JSON.stringify(options.body);\n const exporter = await this.prepareSealed(url, path, fetchOptions);\n\n const response = await openSealedResponse(await fetch(url, fetchOptions), exporter, method);\n return {\n status: response.status,\n body: response.body,\n contentType: response.headers.get('content-type') ?? '',\n };\n }\n\n private async prepareSealed(\n url: string,\n path: string,\n init: RequestInit,\n ): Promise<Uint8Array<ArrayBuffer> | undefined> {\n if (this.options?.sealed === false || !sealingRequired(path)) return undefined;\n this.sealedKeys ??= new SealedKeyStore(this.getBaseUrl(), this.apiKey, this.options?.sealed);\n const key = await this.sealedKeys.current(init.signal ?? undefined);\n init.signal?.throwIfAborted();\n try {\n return await sealRequest(key, url, init);\n } catch (error) {\n init.signal?.throwIfAborted();\n if (error instanceof PalbaseError) throw error;\n throw new PalbaseError('sealed_request_failed', 'The request could not be encrypted.', 0);\n }\n }\n\n private getBaseUrl(): string {\n // Explicit URL always wins (local dev, staging, test rigs).\n if (this.options?.url) {\n return this.options.url;\n }\n\n // Validate the key shape up front so apex-routed callers still\n // fail loud on a malformed key instead of hitting the gateway\n // with bad credentials.\n if (this.apiKey && parseEnvironmentRef(this.apiKey) === null) {\n throw new PalbaseError(\n 'invalid_api_key',\n 'Invalid API key format. Expected pb_{environment_ref}_c{at least 20 base62 chars}. For dev/staging pass `url: \"https://api.dev.palbase.studio\"` via options.',\n 0,\n );\n }\n\n return `https://${PALBASE_DEFAULT_HOST}`;\n }\n\n private buildHeaders(options?: RequestOptions): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n // Client identity, the web counterpart of the iOS SDK's\n // ClientInfo.augment(). The server reads these to resolve flag targeting\n // conditions and to label telemetry, so an app declares nothing and calls\n // nothing — whatever the SDK can know, it sends.\n 'X-Platform': wirePlatform(),\n };\n // The host app's own version is not knowable on the web (no bundle to read\n // it from), so it is opt-in; when given it fills the same header iOS fills\n // from CFBundleShortVersionString.\n const appVersion = this.options?.appVersion?.trim();\n if (appVersion) {\n headers['X-Palbase-Client-Version'] = appVersion;\n }\n\n // Palbase Environment keys live in the `apikey` header — never in\n // `Authorization` — because Kong's key-auth resolves them on that\n // header and the gateway's pre-function plugin stamps the downstream\n // identity.\n const effectiveKey = this.apiKey;\n if (effectiveKey) {\n headers['apikey'] = effectiveKey;\n }\n\n // User session token, if any. Kong's pre-function plugin strips\n // Authorization on /v1/* routes anyway (PostgREST has no JWT\n // secret and would crash on a Bearer it can't decode), but\n // sending it preserves the contract for /auth/* endpoints that\n // do consume the bearer (e.g. session refresh).\n const token = this.tokenManager?.getAccessToken();\n if (token) {\n headers['Authorization'] = `Bearer ${token}`;\n }\n\n // adminToken (platform admin JWT) takes precedence — used by the\n // @palbase/admin internal flows that hit /admin/* routes; those\n // routes verify the bearer themselves and aren't subject to the\n // /v1/* Authorization-strip rule.\n if (this.adminToken) {\n headers['Authorization'] = `Bearer ${this.adminToken}`;\n }\n\n // Merge global custom headers\n if (this.options?.headers) {\n Object.assign(headers, this.options.headers);\n }\n\n // Merge per-request headers\n if (options?.headers) {\n Object.assign(headers, options.headers);\n }\n\n return headers;\n }\n\n private async executeWithRetry<T>(\n method: string,\n path: string,\n options: RequestOptions | undefined,\n attempt: number,\n // Headers a PREVIOUS attempt earned and this one has to carry. Today that\n // is only the solved proof-of-work pair; it is a parameter rather than a\n // field because it belongs to one request's second try, and a field would\n // leak it onto every later call made through this client.\n earned?: Record<string, string>,\n rotated = false,\n ): Promise<PalbaseResponse<T>> {\n const url = endpointUrl(this.getBaseUrl(), path);\n const headers = { ...this.buildHeaders(options), ...earned };\n\n // Run interceptors\n for (const interceptor of this.interceptors) {\n await interceptor({ headers, method, path });\n }\n\n const fetchOptions: RequestInit = {\n method,\n headers,\n signal: options?.signal,\n };\n\n if (options?.body !== undefined) {\n fetchOptions.body = JSON.stringify(options.body);\n }\n // A fresh HPKE encapsulation on EVERY attempt: reusing an envelope trips\n // the server replay guard, even when the first response was lost.\n const exporter = await this.prepareSealed(url, path, fetchOptions);\n\n let response: Response;\n try {\n response = await fetch(url, fetchOptions);\n } catch (error) {\n options?.signal?.throwIfAborted();\n // Network error — retry with backoff\n if (options?.retry !== false && attempt < MAX_RETRIES - 1) {\n const backoff = INITIAL_BACKOFF_MS * 2 ** attempt;\n await this.delay(backoff);\n // WITHOUT `earned`, and that is the whole point of this line.\n //\n // A network error means the response was lost, not that the request\n // was. If it reached the server, the challenge is already SPENT —\n // palauth's VerifyChallenge reads and deletes in one step\n // (bot/pow.go:96-104), deliberately, because a proof presented twice is\n // not proof. Replaying the nonce would then answer `pow_invalid`, and\n // the one-solve guard below would refuse to try again: a request one\n // fresh solve away from succeeding, failed. Dropping it costs nothing\n // in the other case — if the server never saw the request, a fresh\n // challenge works exactly as well as the old one.\n return this.executeWithRetry<T>(method, path, options, attempt + 1, undefined, rotated);\n }\n\n // All retries exhausted — throw PalbaseError\n throw new PalbaseError(\n 'network_error',\n error instanceof Error ? error.message : 'Network request failed',\n 0,\n );\n }\n response = await openSealedResponse(response, exporter, method);\n\n // Handle 429 Too Many Requests — retry with Retry-After or backoff;\n // if retries exhausted, fall through to normal error response handling below\n if (response.status === 429) {\n if (options?.retry !== false && attempt < MAX_RETRIES - 1) {\n const retryAfter = response.headers.get('Retry-After');\n const parsed = retryAfter ? Number.parseInt(retryAfter, 10) : Number.NaN;\n // Clamp the server-requested wait: a long Retry-After (locked account)\n // must not hang the request — cap each sleep, exhaust MAX_RETRIES, then\n // fall through to surface the 429 envelope below.\n const delayMs = Number.isNaN(parsed)\n ? INITIAL_BACKOFF_MS * 2 ** attempt\n : Math.min(parsed * 1000, MAX_RETRY_DELAY_MS);\n await this.delay(delayMs);\n // WITH `earned`, unlike the network path above: a 429 is a refusal the\n // server issued INSTEAD of doing the work, so the challenge was never\n // consumed. The edge's rate limiter answers before palsvc, and on the\n // auth routes palauth's own limiter runs BEFORE the proof-of-work\n // middleware (auth/internal/server/server.go: rl.LoginByIP, then powMW).\n return this.executeWithRetry<T>(method, path, options, attempt + 1, earned, rotated);\n }\n }\n\n // Parse response body\n let data: T | null = null;\n let errorBody:\n | { error?: string; error_description?: string; status?: number; required?: string }\n | undefined;\n\n // HEAD responses have no body by spec — skip parsing.\n const contentType = response.headers.get('Content-Type');\n if (\n method !== 'HEAD' &&\n ![204, 205, 304].includes(response.status) &&\n contentType?.includes('json')\n ) {\n const body = (await response.json()) as Record<string, unknown>;\n if (response.ok) {\n data = body as T;\n } else {\n errorBody = body as typeof errorBody;\n }\n }\n\n if (\n exporter &&\n !rotated &&\n response.status === 400 &&\n errorBody?.error === 'sealed_unknown_kid'\n ) {\n await this.sealedKeys?.current(options?.signal, true);\n return this.executeWithRetry<T>(method, path, options, attempt, earned, true);\n }\n\n // Proof-of-work: /auth/signup and /auth/token sit behind a bot gate that\n // answers an unsolved request with 403 and the challenge in the body. Solve\n // it and repeat the request carrying the two headers; the caller never\n // learns the gate is there.\n //\n // HERE, in core, because this is the layer that issues the request for every\n // client in the repo — @palbase/auth's sign-in, @palbase/web's facades, the\n // server SDK. The same retry lived one layer up in @palbase/web until\n // 2026-08-18 and covered everything EXCEPT `pb.auth.*`, which reaches the\n // network through this method; so the gate stayed unsatisfiable on exactly\n // the two endpoints it guards.\n //\n // ONE retry, and only when the body really carries a challenge: `earned`\n // being set already means this IS the second try. A 403 that says\n // pow_required without a challenge is a server the client cannot satisfy,\n // and looping on it would turn a broken gate into a hang.\n if (response.status === 403 && !earned) {\n const challenge = asPowChallenge(errorBody);\n if (challenge) {\n return this.executeWithRetry<T>(\n method,\n path,\n options,\n attempt,\n await solvePowChallenge(challenge, undefined, options?.signal),\n rotated,\n );\n }\n }\n\n if (!response.ok) {\n if (response.status === 403 && errorBody !== undefined) {\n const body: Record<string, unknown> = errorBody;\n for (const listener of this.forbiddenListeners) {\n try {\n listener(body);\n } catch {\n // A consumer's handler must not turn a well-formed refusal into a\n // thrown error, nor stop the listeners after it (same rule as\n // internal.ts' configured listeners).\n }\n }\n }\n return {\n data: null,\n error: new PalbaseError(\n errorBody?.error ?? 'unknown_error',\n errorBody?.error_description ?? response.statusText,\n response.status,\n withRetryHint(errorBody, response),\n ),\n status: response.status,\n };\n }\n\n // Parse PostgREST Content-Range for count queries (e.g. \"0-9/42\" or \"*/42\").\n const contentRange = response.headers.get('Content-Range');\n let count: number | undefined;\n if (contentRange) {\n const slash = contentRange.lastIndexOf('/');\n if (slash >= 0) {\n const totalPart = contentRange.slice(slash + 1);\n if (totalPart !== '*') {\n const parsed = Number.parseInt(totalPart, 10);\n if (!Number.isNaN(parsed)) {\n count = parsed;\n }\n }\n }\n }\n\n return {\n data,\n error: null,\n status: response.status,\n ...(count !== undefined ? { count } : {}),\n };\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n","import type { AuthStateCallback, Session, Unsubscribe } from './types.js';\n\nexport class TokenManager {\n private session: Session | null = null;\n private listeners: Set<AuthStateCallback> = new Set();\n private refreshPromise: Promise<void> | null = null;\n private refreshing = false;\n\n refreshFunction: ((refreshToken: string) => Promise<Session>) | null = null;\n\n setSession(session: Session): void {\n this.session = session;\n this.notify('SESSION_SET', session);\n }\n\n getAccessToken(): string | null {\n return this.session?.accessToken ?? null;\n }\n\n getRefreshToken(): string | null {\n return this.session?.refreshToken ?? null;\n }\n\n clearSession(): void {\n this.session = null;\n this.notify('SESSION_CLEARED', null);\n }\n\n isExpired(): boolean {\n if (!this.session) return true;\n return Date.now() >= this.session.expiresAt;\n }\n\n async refreshSession(): Promise<void> {\n if (!this.session?.refreshToken || !this.refreshFunction) {\n return;\n }\n\n // Collapse concurrent refresh calls into a single request\n if (this.refreshPromise) {\n return this.refreshPromise;\n }\n\n // Re-entrancy guard: the wired refreshFunction issues its own HTTP request\n // (POST /auth/token/refresh) through HttpClient, whose pre-flight calls\n // refreshSession() again SYNCHRONOUSLY — before `refreshPromise` below is\n // assigned (the whole chain runs before the first real await). Without\n // this flag that recursion is unbounded (stack overflow). Returning early\n // lets the refresh request itself proceed unauthenticated — it carries\n // the refresh token in its body, not the Bearer header.\n if (this.refreshing) {\n return;\n }\n\n this.refreshing = true;\n this.refreshPromise = this.executeRefresh(this.session.refreshToken);\n\n try {\n await this.refreshPromise;\n } finally {\n this.refreshPromise = null;\n this.refreshing = false;\n }\n }\n\n onAuthStateChange(callback: AuthStateCallback): Unsubscribe {\n this.listeners.add(callback);\n return () => {\n this.listeners.delete(callback);\n };\n }\n\n private async executeRefresh(refreshToken: string): Promise<void> {\n if (!this.refreshFunction) return;\n const startedSession = this.session;\n try {\n const newSession = await this.refreshFunction(refreshToken);\n // Sign-out, a new sign-in, or another session adoption takes precedence\n // over a refresh that started against an older session.\n if (this.session === startedSession) this.setSession(newSession);\n } catch (error) {\n // The caller would clear its session on a terminal refresh error. An\n // error from an older session must not clear a newer one.\n if (this.session === startedSession) throw error;\n }\n }\n\n private notify(event: 'SESSION_SET' | 'SESSION_CLEARED', session: Session | null): void {\n for (const listener of this.listeners) {\n listener(event, session);\n }\n }\n}\n","/** The client a tenant's tests use to call their own backend.\n *\n * These tests run against a REAL deployment — the release the deploy just built,\n * serving from the same Environment as production, with the same database, the\n * same secrets and the same gateway in front of it. So this client is a plain\n * HTTP client, not a simulation: every call crosses the gateway, the API key\n * check, the auth rail, the zod validation at the boundary, and row-level\n * security, exactly as a shipped app's call does.\n *\n * There is deliberately no schema knowledge here. The tenant already wrote their\n * types — `import type { TodoSchema } from \"../models/todos/shared.js\"` — so a\n * test types its own call (`api.get<TodoSchema[]>(\"/todos\")`) and can validate it\n * with the same zod schema the endpoint declares. A second generated client would\n * be a second thing to keep in step.\n */\n\nimport { asPowChallenge, solvePowChallenge } from \"@palbase/core\";\n\n/** How to reach the release under test. Supplied by the deploy, never guessed. */\nexport interface TestApiConfig {\n baseUrl: string;\n apiKey: string;\n /** This deploy's secret. Without it the request is served the LIVE release.\n *\n * OPTIONAL against a stack running on this machine: a local stack serves one\n * version — the directory `palbase start` mounted — so there is no candidate\n * to select. Required everywhere else. */\n candidateToken?: string;\n /** The run's minted logins, keyed by the name declared in config/test-users.ts. */\n identities?: Record<string, TestIdentity>;\n /** The fetch to use. Injected by tests of this client; production passes none. */\n fetch?: typeof fetch;\n}\n\n/** One login the deploy minted for this run.\n *\n * `accessToken` is the session issued when the identity was created, and is what\n * `signInAs` uses. The credentials come along for a test that wants to exercise\n * the login rail itself — but a suite that switches users repeatedly must not be\n * signing in each time: those calls come from one address and trip the login rate\n * limiter, failing tests for a reason that has nothing to do with the code\n * under test.\n */\nexport interface TestIdentity {\n id?: string;\n email: string;\n password: string;\n accessToken?: string;\n}\n\n/** One call the suite made, in the order it was made. */\nexport interface RecordedRequest {\n method: string;\n path: string;\n status: number;\n ms: number;\n}\n\n/** A non-2xx answer, carrying the platform's error envelope.\n *\n * The envelope is the contract every Palbase endpoint answers with, so a test\n * asserts on `status`/`error`/`data` rather than parsing a message. The message\n * exists for the human reading a failed deploy.\n */\nexport class TestApiError extends Error {\n readonly status: number;\n readonly error: string;\n /** Payload of an error your code threw — `new BadRequest({ fields })` arrives here. */\n readonly data: unknown;\n /** The whole envelope, exactly as the server sent it. */\n readonly body: ErrorEnvelope;\n\n constructor(method: string, path: string, status: number, body: unknown) {\n const envelope = (body ?? {}) as ErrorEnvelope;\n const code = envelope.error ?? String(status);\n super(`${method} ${path} → ${status} ${code}${envelope.error_description ? `: ${envelope.error_description}` : \"\"}`);\n this.name = \"TestApiError\";\n this.status = status;\n this.error = code;\n this.data = envelope.data;\n this.body = envelope;\n }\n}\n\n/** A Palbase error response.\n *\n * `data` carries the payload of an error your code threw. Validation refused at\n * the boundary — before your handler runs — answers with `details` instead, one\n * entry per field. The index signature is deliberate: whatever the server sends\n * is readable from a test, so no assertion is ever blocked on this type being\n * exhaustive.\n */\nexport interface ErrorEnvelope {\n error?: string;\n error_description?: string;\n status?: number;\n request_id?: string;\n data?: unknown;\n details?: Array<{ field: string; message: string }>;\n [key: string]: unknown;\n}\n\nexport interface CallOptions {\n headers?: Record<string, string>;\n}\n\nexport interface TestApi {\n get<T = unknown>(path: string, opts?: CallOptions): Promise<T>;\n post<T = unknown>(path: string, body?: unknown, opts?: CallOptions): Promise<T>;\n patch<T = unknown>(path: string, body?: unknown, opts?: CallOptions): Promise<T>;\n put<T = unknown>(path: string, body?: unknown, opts?: CallOptions): Promise<T>;\n delete<T = unknown>(path: string, opts?: CallOptions): Promise<T>;\n /** HTTP QUERY (RFC 10008): a safe, idempotent read whose filter travels in the body. */\n query<T = unknown>(path: string, body?: unknown, opts?: CallOptions): Promise<T>;\n /** Sign in with credentials you supply. */\n signIn(credentials: { email: string; password: string }): Promise<{ id: string; email?: string }>;\n /**\n * Sign in as one of the identities this run was given, by the name you\n * declared it under in `config/test-users.ts`.\n *\n * Each is minted by the platform for the length of ONE deploy, seeded with the\n * data that declaration describes, and retired after — which is why this works\n * on every Environment including production, where a committed fixture password\n * is refused on purpose.\n */\n signInAs(name: string): Promise<{ id: string; email?: string }>;\n signOut(): Promise<void>;\n /** Drop the bearer without calling the server — the anonymous caller. */\n asAnonymous(): void;\n /** Every call made, in order. Printed for the failing test in a red deploy. */\n readonly requests: readonly RecordedRequest[];\n}\n\nfunction required(value: string, envName: string): string {\n if (!value) {\n throw new Error(\n `${envName} is not set — the test client has nowhere to send requests. ` +\n `This is set by the deploy that runs your tests; if you are running them by hand, set it yourself.`,\n );\n }\n return value;\n}\n\n/** A stack running on this machine. There is exactly ONE version there — the\n * directory `palbase start` mounted — so there is no candidate to select, and\n * demanding a token for one made local runs invent a value to satisfy a header\n * nothing reads. */\nfunction isLocalTarget(baseUrl: string): boolean {\n try {\n const { hostname } = new URL(baseUrl);\n return hostname === \"127.0.0.1\" || hostname === \"localhost\" || hostname === \"[::1]\" || hostname === \"::1\";\n } catch {\n return false;\n }\n}\n\n/** Seconds until a JWT's `exp`, or null when the token carries no readable one.\n * Read WITHOUT verifying: this is a diagnosis, never a decision — the server\n * remains the only authority on whether a token is good. */\nfunction secondsUntilExpiry(token: string): number | null {\n const body = token.split(\".\")[1];\n if (!body) return null;\n try {\n const claims = JSON.parse(Buffer.from(body, \"base64url\").toString(\"utf8\")) as { exp?: unknown };\n return typeof claims.exp === \"number\" ? claims.exp - Math.floor(Date.now() / 1000) : null;\n } catch {\n return null;\n }\n}\n\nexport function createTestApi(config: TestApiConfig): TestApi {\n const baseUrl = required(config.baseUrl, \"PALBASE_TEST_BASE_URL\").replace(/\\/$/, \"\");\n const apiKey = required(config.apiKey, \"PALBASE_TEST_API_KEY\");\n const local = isLocalTarget(baseUrl);\n // Local stacks serve one version, so there is nothing to select. Everywhere\n // else the token stays REQUIRED: without it the gateway serves the LIVE\n // release and the suite would grade code that is not under test.\n const candidateToken = local ? (config.candidateToken ?? \"\") : required(config.candidateToken ?? \"\", \"PALBASE_TEST_CANDIDATE\");\n const doFetch = config.fetch ?? fetch;\n\n const requests: RecordedRequest[] = [];\n let bearer: string | null = null;\n\n async function call<T>(method: string, path: string, body: unknown, opts: CallOptions = {}): Promise<T> {\n const headers: Record<string, string> = {\n apikey: apiKey,\n // Selects the release under test. Omit it and the gateway serves the LIVE\n // one, which would make the whole suite grade the wrong code. Absent only\n // against a local stack, which has a single version.\n ...(candidateToken ? { \"x-palbase-candidate\": candidateToken } : {}),\n ...opts.headers,\n };\n if (bearer) headers.authorization = `Bearer ${bearer}`;\n if (body !== undefined) headers[\"content-type\"] = \"application/json\";\n\n const startedAt = Date.now();\n const res = await doFetch(`${baseUrl}${path}`, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n const text = await res.text();\n const parsed: unknown = text ? safeParse(text) : undefined;\n\n requests.push({ method, path, status: res.status, ms: Date.now() - startedAt });\n\n if (!res.ok) {\n // A 401 on a token that has simply RUN OUT is the most likely 401 a suite\n // sees, and the least legible: the mint issues ~30 minutes, so a file of\n // credentials written yesterday answers `401 unauthorized` with nothing to\n // act on. Measured on a customer run: the next step taken was to blame the\n // credentials rather than their age.\n if (res.status === 401 && bearer) {\n const left = secondsUntilExpiry(bearer);\n if (left !== null && left <= 0) {\n throw new TestApiError(method, path, res.status, {\n error: \"access_token_expired\",\n error_description:\n `this run's access token EXPIRED ${Math.abs(left)}s ago — a test identity is minted for the ` +\n `length of ONE deploy, so a saved token does not survive to the next run. Re-mint it ` +\n \"(`palbase test-user create --json`, or let `palbase test` do it) and run again.\",\n });\n }\n }\n throw new TestApiError(method, path, res.status, parsed);\n }\n return parsed as T;\n }\n\n return {\n requests,\n get: (path, opts) => call(\"GET\", path, undefined, opts),\n post: (path, body, opts) => call(\"POST\", path, body, opts),\n patch: (path, body, opts) => call(\"PATCH\", path, body, opts),\n put: (path, body, opts) => call(\"PUT\", path, body, opts),\n delete: (path, opts) => call(\"DELETE\", path, undefined, opts),\n query: (path, body, opts) => call(\"QUERY\", path, body, opts),\n\n async signInAs(name) {\n const identity = (config.identities ?? {})[name];\n if (!identity) {\n const declared = Object.keys(config.identities ?? {});\n throw new Error(\n `no test identity named ${JSON.stringify(name)} — the deploy mints one per user declared in ` +\n `config/test-users.ts` +\n (declared.length\n ? `; this run has: ${declared.join(\", \")}`\n : // Not \"you declared none\": from here the two causes are\n // indistinguishable, and blaming the customer's config for a\n // platform failure sends them to look in the wrong file. The\n // deploy log names which one it was.\n \", and this run has none — either your config declares no users \" +\n \"or the deploy could not mint them; the deploy log says which\"),\n );\n }\n // The session the mint already issued — no network call, so switching\n // users is free and the login rail never sees this run.\n if (identity.accessToken) {\n bearer = identity.accessToken;\n return { id: identity.id ?? \"\", email: identity.email };\n }\n return this.signIn(identity);\n },\n\n async signIn(credentials) {\n // PROOF-OF-WORK IS PART OF LOGGING IN, so a client that cannot solve one\n // cannot log in at all. The web SDK has solved it since bot protection\n // shipped; this harness went straight to `fetch` and therefore answered\n // `403 pow_required` on every password login — which made the whole\n // credentials path DEAD on a stack with the gate on, exactly when a\n // suite falls back to it because its minted token ran out.\n //\n // One retry, and only when the refusal really carries a challenge: a 403\n // saying pow_required without one is a server this client cannot satisfy,\n // and looping would turn a broken gate into a hang. Same rule as\n // @palbase/core's own retry.\n const attempt = async (extra?: Record<string, string>) =>\n call<{ access_token: string; user?: { id: string; email?: string } }>(\n \"POST\",\n \"/auth/login\",\n credentials,\n extra ? { headers: extra } : {},\n );\n\n let result: { access_token: string; user?: { id: string; email?: string } };\n try {\n result = await attempt();\n } catch (e) {\n const refusal = e as { status?: number; body?: unknown };\n const challenge = refusal.status === 403 ? asPowChallenge(refusal.body) : null;\n if (!challenge) throw e;\n result = await attempt(await solvePowChallenge(challenge));\n }\n bearer = result.access_token;\n return result.user ?? { id: \"\" };\n },\n async signOut() {\n await call(\"POST\", \"/auth/logout\", undefined);\n bearer = null;\n },\n asAnonymous() {\n bearer = null;\n },\n };\n}\n\n/** The run's identities, as the deploy passed them. Absent is not an error: a\n * project that declares none still runs every test that needs no login. */\nfunction parseIdentities(raw: string | undefined): Record<string, TestIdentity> {\n if (!raw) return {};\n try {\n return JSON.parse(raw) as Record<string, TestIdentity>;\n } catch {\n return {};\n }\n}\n\nfunction safeParse(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/** The client the deploy configured, from the environment it set.\n *\n * Constructed lazily so importing this module outside a test run — a typecheck,\n * an editor — does not fail on absent configuration.\n */\nlet configured: TestApi | null = null;\n\nexport const api: TestApi = new Proxy({} as TestApi, {\n get(_target, prop) {\n configured ??= createTestApi({\n baseUrl: process.env.PALBASE_TEST_BASE_URL ?? \"\",\n apiKey: process.env.PALBASE_TEST_API_KEY ?? \"\",\n candidateToken: process.env.PALBASE_TEST_CANDIDATE ?? \"\",\n identities: parseIdentities(process.env.PALBASE_TEST_IDENTITIES),\n });\n return Reflect.get(configured, prop, configured);\n },\n});\n","import \"reflect-metadata\";\n\nimport type { Token } from \"../container.js\";\n\nexport interface IsolatedContainer {\n /** Substitutes a token. Chainable; the last write for a token wins. */\n with<T>(t: Token<T>, v: T): IsolatedContainer;\n get<T>(t: Token<T>): T;\n}\n\n/**\n * How a test replaces a dependency.\n *\n * Rebuilds the graph with the overrides in place and never touches the process\n * singleton cache, so the next test in the same process does not meet a doubled\n * instance left behind by this one. Substitution is DEEP: `Report` asks for\n * `Money` and gets whatever the graph was rebuilt with, however many hops down.\n *\n * Substitution is by `with` alone — there is no separate platform map, because\n * platform services are ambient rather than injected (FR-005).\n *\n * Module boundaries are NOT enforced here, deliberately. They are a build-time\n * rule about the shipped application; making a unit test fail on them would\n * force every test to restate a module layout it is not testing. What a test\n * gets is a graph, not a second opinion about the architecture.\n */\nexport function isolated(): IsolatedContainer {\n const over = new Map<Token, unknown>();\n const local = new Map<Token, unknown>();\n\n const make = (c: Token): unknown => {\n if (over.has(c)) return over.get(c);\n const hit = local.get(c);\n if (hit !== undefined) return hit;\n const meta = (Reflect.getMetadata(\"design:paramtypes\", c) as unknown[] | undefined) ?? [];\n const inst = new (c as unknown as new (...a: unknown[]) => unknown)(\n ...meta.map((d) => make(d as Token)),\n );\n local.set(c, inst);\n return inst;\n };\n\n const api: IsolatedContainer = {\n with<T>(t: Token<T>, v: T): IsolatedContainer {\n over.set(t as Token, v);\n return api;\n },\n get<T>(t: Token<T>): T {\n return make(t as Token) as T;\n },\n };\n return api;\n}\n","export interface InsertManyOptions<Key extends string = string> {\n onConflict?: readonly Key[];\n /** Defaults to ignore when onConflict is supplied. */\n action?: \"ignore\" | \"update\";\n /** false returns the affected row count and skips row serialization. */\n returning?: boolean;\n}\n\nexport function validateInsertManyOptions(opts: InsertManyOptions | undefined): void {\n if (!opts) return;\n if (opts.returning !== undefined && typeof opts.returning !== \"boolean\") throw new Error(\"insertMany returning must be a boolean\");\n if (opts.action !== undefined && opts.action !== \"ignore\" && opts.action !== \"update\") throw new Error(\"insertMany action must be ignore or update\");\n if (opts.onConflict !== undefined && (!Array.isArray(opts.onConflict) || opts.onConflict.some(c => typeof c !== \"string\" || c.length === 0))) {\n throw new Error(\"insertMany onConflict must be an array of column names\");\n }\n if (opts.action !== undefined && !opts.onConflict?.length) throw new Error(\"insertMany action requires nonempty onConflict columns\");\n}\n","/**\n * The refusals a Database call gets BEFORE any SQL exists — written once, so the\n * engine and the test double cannot disagree about them.\n *\n * WHY THIS FILE EXISTS. `fakeDatabase()` is a second implementation of the same\n * surface (`__tests__/helpers/mock-db.ts`), and it never touched `compileWhere`\n * or `asBindParams`. Measured against the published 24.1.0: all four of the\n * calls that release had just started refusing went through the fake SILENTLY —\n * `update{title:undefined}`, `insert{title:undefined}`, `findMany{done:{}}`,\n * `deleteMany{owner,created_at:{}}`.\n *\n * The scaffold tells authors to test the service layer against exactly that\n * fake. So a test went green on a call production would throw on, and the\n * author found out in production instead — the same \"the surface does not match\n * the engine\" shape these refusals exist to end, arriving through the door the\n * SDK hands people for testing.\n *\n * These are pure and SQL-free on purpose: an in-memory store can run them as\n * easily as the driver path can.\n */\n\n/**\n * İşaretçilerin MARKASI — `col()` ve `sqlFragment()` ürünlerini bu süreçte\n * üretilmiş olmakla tanımlar.\n *\n * NEDEN ŞEKİL DEĞİL DE MARKA (gözcü W2-A/C1 ve W2-B/C3, ikisi de ÖLÇTÜ):\n * şekil kontrolü, işaretçiyi güvenilmeyen bir istek gövdesinden UYDURULABİLİR\n * kılıyordu. Ölçülen iki sonuç:\n *\n * findMany(\"docs\", { owner_id: JSON.parse('{\"$col\":\"owner_id\"}') })\n * → WHERE true AND t.\"owner_id\" = t.\"owner_id\" ← kiracılık predikatı totoloji\n * findMany(\"todos\", JSON.parse('{\"$sql\":{\"text\":[\"1=1 -- pwned\"],\"values\":[]}}'))\n * → WHERE true AND 1=1 -- pwned ← saldırganın metni SQL'e HARFİYEN\n *\n * `{ where: { tenant_id: tid, ...req.body.filter } }` bu SDK'nın öğrettiği\n * desen; T010/T014 öncesinde aynı anahtarlar \"bilinmeyen operatör\" diye\n * REDDEDİLİYORDU. Marka o reddi geri getiriyor.\n *\n * Sembol GLOBAL kayıttan (`Symbol.for`) ve ENUMERABLE DEĞİL. İkisi de kasıtlı:\n * global kayıt paketin iki kopyası arasında da eşleşir; enumerable olmaması ise\n * `JSON.stringify` ve `{...ref, gt: 5}` yayılımının markayı DÜŞÜRMESİNİ sağlar —\n * yani telden geçen ya da elle karıştırılan hiçbir şey işaretçi sayılmaz.\n * Kardeş özellik (`increment`) zaten `Symbol.for(\"palbase.tx.expr\")` kullanıyor;\n * bu onun aynısı.\n */\nconst REF_BRAND = Symbol.for(\"palbase.db.ref\");\n\n/** İşaretçiyi markalar. Yalnız `col()` ve `sqlFragment()` çağırır. */\nexport function brandRef<T extends object>(v: T, kind: \"col\" | \"sql\" | \"ref\"): T {\n Object.defineProperty(v, REF_BRAND, { value: kind, enumerable: false });\n return v;\n}\n\nfunction brandOf(v: unknown): unknown {\n if (typeof v !== \"object\" || v === null) return undefined;\n // KENDİ özelliği olmalı, prototip zincirinden MİRAS ALINMIŞ değil:\n // `Object.create(col(\"x\"))` markayı zincirden okuyup işaretçi sayılıyordu\n // (gözcü ölçtü). Telden erişilemez — JSON `__proto__` üstünden sembol\n // yazamaz — ama daraltmak bedava ve \"işaretçi bu süreçte ÜRETİLDİ\"\n // iddiasının tam karşılığı budur.\n return Object.hasOwn(v, REF_BRAND) ? (v as Record<symbol, unknown>)[REF_BRAND] : undefined;\n}\n\n/**\n * Bir değer, MARKASIZ bir işaretçi taklidi mi? (`{$col:…}` / `{$sql:…}`)\n *\n * Üst düzeyde bunlar zaten \"bilinmeyen operatör\" diye reddediliyor. Ama\n * operatörün SAĞINDA — `{ amount: { gt: {\"$col\":\"other\"} } }` — sessizce\n * PARAMETRE olarak bağlanıyorlardı: sayısal kolonda sürücünün 22P02'si,\n * jsonb/text kolonunda ise HİÇBİR SATIR, hatasız (gözcü ölçtü).\n *\n * `in` listesindeki aynı kusur adıyla reddediliyor; bu onun bir seviye\n * yanındaki hâli ve aynı cevabı hak ediyor.\n */\nexport function looksLikeUnbrandedRef(v: unknown): \"col\" | \"sql\" | \"expr\" | null {\n if (typeof v !== \"object\" || v === null) return null;\n if (brandOf(v) !== undefined) return null; // gerçek işaretçi\n if (isColumnExpr(v)) return null; // gerçek ifade tutamağı (kendi markası var)\n const o = v as { $col?: unknown; $sql?: unknown; $expr?: unknown };\n if (typeof o.$col === \"string\") return \"col\";\n if (o.$sql !== undefined && typeof o.$sql === \"object\" && o.$sql !== null) return \"sql\";\n // `$expr` `now()`/`increment()`'in TEL BİÇİMİ. `now()` filtrede geçerli bir\n // değer olduğu andan itibaren bu şekil de uydurulabilir hâle geldi: ÖLÇÜLDÜ,\n // gövdeden gelen `{\"$expr\":{\"fn\":\"now\"}}` sessizce PARAMETRE olarak bağlanıp\n // sorguyu hatasız biçimde boş sonuca çeviriyordu. `$col`/`$sql`/`$ref` ile\n // aynı kapı, aynı gerekçe.\n if (o.$expr !== undefined && typeof o.$expr === \"object\" && o.$expr !== null) return \"expr\";\n return null;\n}\n\n/**\n * `col()` ürünü mü? (FR-011)\n *\n * Burada, çünkü bu dosya \"iki uygulamanın da okuduğu kurallar\" dosyası: motor,\n * `fakeDatabase` ve guard AYNI cevabı vermek zorunda.\n */\nexport function isColRef(v: unknown): v is { readonly $col: string } {\n return brandOf(v) === \"col\" && typeof (v as { $col?: unknown }).$col === \"string\";\n}\n\n/**\n * `sqlFragment` ürünü mü? (FR-018)\n *\n * `isColRef` ile aynı gerekçeyle burada: motor, guard ve `fakeDatabase` üçü de\n * aynı cevabı vermek zorunda — biri fragment'i \"kolon haritası\" sanarsa filtre\n * sessizce düşer.\n */\n/**\n * Plan REFERANSI mı? (`{ $ref: { op, field } }`)\n *\n * `$ref` bu dilin MARKASIZ KALAN TEK işaretçisiydi — `engine/db.ts` onu\n * `\"$ref\" in v` diye tanıyordu — ve SDK'nın öğrettiği desen\n * `{ where: { tenant_id: tid, ...req.body.filter } }`. Ölçüldü (gözcü):\n * istek gövdesinden gelen `{\"id\":{\"$ref\":{\"op\":0,\"field\":\"id\"}}}` filtreyi\n * ÖNCEKİ bir işlemin satır değeriyle karşılaştırtıyor —\n * DELETE … WHERE t.\"tenant_id\" = $1 AND t.\"id\" = $2 PRM [\"t1\",\"SIZAN_DEGER\"]\n * gövdenin hiç görmediği bir değer. Enjeksiyon değil (değerler bound) ama bir\n * ORACLE: `op`/`field` seçip `rows_affected`'tan o değeri öğrenmek.\n *\n * Marka `Symbol.for` olduğu için SDK'nın İKİ KOPYASI arasında da eşleşiyor —\n * kontrolcü bundle'ı kendi kopyasını inline ediyor, planı çalıştıran ise\n * runtime'ınki. Ve plan gövdesi JSON'lanmıyor: tek üretim `txPlan` uygulaması\n * süreç içi (`engine/db.ts`), doğrulandı.\n */\nexport function isPlanRef(v: unknown): v is { readonly $ref: { op: number; field: string } } {\n if (brandOf(v) !== \"ref\") return false;\n const r = (v as { $ref?: { op?: unknown; field?: unknown } }).$ref;\n return r !== undefined && typeof r.op === \"number\" && typeof r.field === \"string\";\n}\n\n/** Markasız bir `{ $ref: … }` taklidi mi? Adıyla reddedilmesi için. */\nexport function looksLikeUnbrandedPlanRef(v: unknown): boolean {\n if (typeof v !== \"object\" || v === null || brandOf(v) !== undefined) return false;\n const r = (v as { $ref?: unknown }).$ref;\n return r !== undefined && typeof r === \"object\" && r !== null;\n}\n\nexport function isSqlFragment(v: unknown): v is { readonly $sql: { text: string[]; values: unknown[] } } {\n if (brandOf(v) !== \"sql\") return false;\n const f = (v as { $sql?: { text?: unknown; values?: unknown } }).$sql;\n return f !== undefined && Array.isArray(f.text) && Array.isArray(f.values);\n}\n\n/**\n * İFADE TUTAMAĞI DEĞER DEĞİLDİR — değer bekleyen yollarda adıyla reddedilir.\n *\n * `increment()` / `decrement()` / `now()` bir Proxy döndürür ve yalnız\n * `updateMany` ile plan yolunun `updateWhere`'i onu SQL'e derler. `insert` /\n * `update` / `put` / `supersede` derlemez; oralarda tutamak bound parametre\n * olarak sürücüye gidiyordu ve reddi SÜRÜCÜ veriyordu (\"Unknown object is not\n * a valid PostgreSQL type\") — yazarın yazdığı hiçbir şeyi adlandırmayan bir\n * mesaj (inceleme I-2/I8, ölçüldü). Plan yolu aynı hatayı kendi diliyle\n * reddediyor; bu, doğrudan yolun karşılığı.\n *\n * Sembol `tx-plan.ts`'in markasıyla AYNI global kayıttan okunuyor; bu dosya\n * kural dosyası olduğu için oraya bağımlılık kurmuyor.\n */\nconst TX_EXPR = Symbol.for(\"palbase.tx.expr\");\n\n/**\n * `now()` — SUNUCU SAATİ, karşılaştırma değeri olarak.\n *\n * `increment()`/`decrement()` bir YAZMA ifadesidir ve filtrede anlamsızdır;\n * `now()` öyle değil: `expires_at > now()` sıradan bir karşılaştırma ve her\n * backend'in en sık yazdığı yüklemlerden biri. Filtrede TÜM ifade tutamaklarını\n * reddetmek, yazarı bunun için `sqlFragment`e düşürüyordu — yani sorgunun\n * içine giren parça, en sıradan koşul için gerekiyordu.\n *\n * Ayrım MARKAYLA: bir istek gövdesinden gelen `{\"$expr\":{\"fn\":\"now\"}}` bu\n * süreçte `now()` ile üretilmediği için marka taşımaz ve reddedilir.\n */\nexport function isNowExpr(v: unknown): boolean {\n if (!isColumnExpr(v)) return false;\n try {\n const e = (v as Record<symbol, unknown>)[TX_EXPR];\n return typeof e === \"object\" && e !== null && (e as { fn?: unknown }).fn === \"now\";\n } catch {\n return false;\n }\n}\n\nexport function isColumnExpr(v: unknown): boolean {\n if (typeof v !== \"object\" && typeof v !== \"function\") return false;\n if (v === null) return false;\n try {\n return (v as Record<symbol, unknown>)[TX_EXPR] !== undefined;\n } catch {\n // Tutamak bir Proxy; bilinmeyen bir prop'ta trap fırlatabilir.\n return false;\n }\n}\n\n/**\n * Değer bekleyen bir yazma yolunda ifade tutamağı ya da `col()` var mı?\n *\n * Motor ve `fakeDatabase` AYNI cevabı vermek zorunda: fake tutamağı satıra\n * YAZIYORDU (`row[k] = proxy`) ve satır artık JSON'a bile çevrilemiyordu, motor\n * ise sürücüde patlıyordu. İki farklı yanlış, tek doğru.\n */\nexport function assertNoExpressionHandles(\n caller: string,\n table: string,\n cols: readonly string[],\n data: Record<string, unknown>,\n): void {\n for (const c of cols) {\n const v = data[c];\n // `now()` ile sayaç ifadeleri AYRI cevaplar hak ediyor: ikisinin de\n // çalışan alternatifi var ama farklı (P6 — hata çalışan bir alternatifi\n // ADIYLA söyler). Tek bir \"ifade tutamağı\" mesajı, `now()` yazan kişiye\n // `increment()` öneriyordu.\n if (isNowExpr(v)) {\n throw new Error(\n `${caller}(${table}): \"${c}\" now() aldı — bu yolda değer beklenir. ` +\n `Satır EKLENİRKEN sunucu saatini yazmanın yolu kolonu defaultNow() ile ` +\n `bildirmek (varsayılan kolonun yanında durur, her çağrıda tekrarlanmaz); ` +\n `var olan bir satırı damgalamak için updateMany({ where, set: { ${c}: now() } }) ` +\n `ya da $transaction içinde tx.public.${table}.updateWhere(where, { ${c}: now() }).`,\n );\n }\n if (isColumnExpr(v)) {\n throw new Error(\n `${caller}(${table}): \"${c}\" bir ifade tutamağı aldı (increment()/decrement()). ` +\n `Bu yolda değer beklenir. Sayaç artışı için updateMany({ where, set: { ${c}: increment(n) } }) ` +\n `ya da $transaction içinde tx.public.${table}.updateWhere(where, { ${c}: increment(n) }) kullanın.`,\n );\n }\n if (isColRef(v)) {\n throw new Error(\n `${caller}(${table}): \"${c}\" bir col() aldı. Kolon referansı yalnız FİLTREDE durabilir; ` +\n `bir kolonun değerini başka bir kolona yazmak için $query kullanın.`,\n );\n }\n }\n}\n\n/** The comparison operators a filter value may carry. Kept here because the\n * guard has to tell an operator object from a plain value. */\nconst KNOWN_OPS = new Set([\n \"gt\", \"gte\", \"lt\", \"lte\", \"neq\", \"in\",\n // K1 metin operatörleri (FR-005) ve null testi (FR-006). Bu küme\n // `fakeDatabase()` ile ORTAK kaynaktır: fake bir çağrıyı motorun reddettiği\n // yerde kabul ederse, yazarın testi üretimde patlayan koda karşı yeşil verir.\n \"contains\", \"icontains\", \"startsWith\", \"endsWith\", \"isNull\",\n]);\n\n/**\n * `eq` ADIYLA reddedilir, ve reddi buradadır çünkü guard'ı motor da fake de\n * okuyor.\n *\n * Eşitliğin yazımı ÇIPLAK DEĞERDİR: `{ owner: \"u1\" }`. `eq`'i ikinci bir yazım\n * olarak eklemek, bu run'ın kapatmak için var olduğu şeyi — aynı iş için iki\n * uyumsuz yazım — filtre dilinin İÇİNDE yeniden açardı. Ve eskiden kabul eden\n * ile reddeden ayrışıyordu: guard `eq`'i geçiriyor, derleyici\n * `bilinmeyen operatör \"eq\"` diyordu (gözcü ölçtü).\n */\nconst REFUSED_OPS: Record<string, string> = {\n eq: 'eşitlik ÇIPLAK yazılır: { <kolon>: <değer> } (ya da kolon karşılaştırması için { <kolon>: col(\"…\") })',\n};\n\n/**\n * Refuse a filter that would compile to something other than what it reads like.\n *\n * Three shapes, each measured in production before it was closed:\n *\n * `{ col: undefined }` binds NULL; `= NULL` matches no row, so the query\n * answered \"no records\" and said nothing.\n * `{ col: {} }` produces no term at all — every row on the read\n * path, a dropped condition on the write path.\n * `{ col: { gte: undefined } }` and an `undefined` inside `in`: the same NULL,\n * one level down.\n */\nexport function assertUsableFilter(\n caller: string,\n table: string,\n where: Record<string, unknown> | undefined,\n): void {\n // Bileşim anahtarları (FR-007) bir KOLON adı değildir; kolon doğrulamasından\n // ve operatör kontrolünden muaftır, kendi dalları özyinelemeli olarak aynı\n // kurallardan geçer.\n const COMPOSITES = new Set([\"OR\", \"AND\", \"NOT\"]);\n\n if (!where) return;\n // Fragment bir kolon haritası DEĞİLDİR (FR-018): içeriği SQL'dir, kolon\n // doğrulaması ona uygulanamaz. Değerleri zaten bound gidiyor.\n if (isSqlFragment(where)) return;\n for (const [col, cond] of Object.entries(where)) {\n // Bileşim anahtarları (FR-007) kolon DEĞİLDİR: dalları aynı kurallardan\n // özyinelemeli geçer, ama kendileri operatör kontrolüne girmez.\n if (COMPOSITES.has(col)) {\n const branches = col === \"NOT\" ? [cond] : cond;\n if (!Array.isArray(branches) && col !== \"NOT\") {\n throw new Error(`${caller}(${table}): where.${col} bir dizi olmalı`);\n }\n for (const b of branches as unknown[]) {\n if (b === null || typeof b !== \"object\") {\n throw new Error(`${caller}(${table}): where.${col} dalları filtre nesnesi olmalı`);\n }\n assertUsableFilter(caller, table, b as Record<string, unknown>);\n }\n continue;\n }\n // `has` de kolon DEĞİLDİR: anahtarları İLİŞKİ adları, değerleri BİR TABLO\n // ÖTESİNİN filtresi. İç filtre aynı kurallardan geçiyor — `has` ikinci bir\n // filtre dili değil, aynı dilin bir tablo ötesi.\n //\n // İlişki ADI burada doğrulanMIYOR: grafiği yalnız motor tanıyor (ve tip,\n // derleme anında). Guard'ın onu bilmesi ilişki grafiğinin İKİNCİ bir\n // yorumcusu demekti — `buildRelations`'ın yorumunun adıyla yasakladığı şey.\n if (col === \"has\") {\n if (cond === null || typeof cond !== \"object\" || Array.isArray(cond)) {\n throw new Error(`${caller}(${table}): where.has bir ilişki haritası olmalı ({ <ilişki>: { … } })`);\n }\n for (const [rel, inner] of Object.entries(cond as Record<string, unknown>)) {\n if (inner === null || typeof inner !== \"object\" || Array.isArray(inner)) {\n throw new Error(`${caller}(${table}): where.has.${rel} bir filtre nesnesi olmalı`);\n }\n assertUsableFilter(caller, table, inner as Record<string, unknown>);\n }\n continue;\n }\n if (cond === undefined) {\n throw new Error(\n `${caller}(${table}): where.${col} değeri undefined — bu bir filtre değeri değil. ` +\n `Bağlanınca NULL olur ve '= NULL' hiçbir satıra uymaz, yani sorgu sessizce ` +\n `boş sonuç dönerdi. Değer yoksa anahtarı filtreye hiç koymayın.`,\n );\n }\n if (cond === null || typeof cond !== \"object\" || Array.isArray(cond)) continue;\n // `col()` ürünü bir DEĞER'dir, operatör nesnesi değil (FR-011). Ayırt\n // edilmezse `{ $col: \"x\" }` bir operatör haritası sanılır ve \"bilinmeyen\n // operatör $col\" diye reddedilirdi.\n if (isColRef(cond)) continue;\n // `now()` de bir DEĞER'dir, aynı gerekçeyle — ve tutamak bir Proxy olduğu\n // için `Object.entries` BOŞ döner: ayırt edilmezse \"boş operatör nesnesi\"\n // diye reddedilirdi, yani doğru yazım yanlış bir hatayla karşılanırdı.\n if (isNowExpr(cond)) continue;\n\n const entries = Object.entries(cond as Record<string, unknown>);\n if (entries.length === 0) {\n throw new Error(\n `${caller}(${table}): where.${col} boş bir operatör nesnesi ({}) — hiçbir koşul ` +\n `üretmez, yani bu alan filtreden sessizce DÜŞERDİ. Koşul kurulmayacaksa ` +\n `anahtarı filtreye hiç koymayın (D-21).`,\n );\n }\n for (const [op, v] of entries) {\n if (op === \"in\") {\n if (!Array.isArray(v)) throw new Error(`${caller}(${table}): where.${col}.in bir dizi olmalı`);\n if (v.some((x) => x === undefined)) {\n throw new Error(\n `${caller}(${table}): where.${col}.in listesinde undefined var — sessizce NULL'a ` +\n `bağlanır ve o eleman hiçbir satırla eşleşmez. Listeyi kurarken eleyin.`,\n );\n }\n continue;\n }\n // Sağ tarafta kolon durabilir: `{ total: { gt: col(\"amount_paid\") } }`.\n // Değer kontrolleri (undefined) ona da uygulanır, ama `in` gibi şekil\n // kontrolleri değil — o dal aşağıda zaten ayrı.\n if (REFUSED_OPS[op] !== undefined) {\n // Bilinmeyen değil — BİLİNEREK reddedilen. Hata çalışan yazımı söylüyor.\n throw new Error(`${caller}(${table}): where.${col}.${op} bu filtre dilinde yok — ${REFUSED_OPS[op]}`);\n }\n if (!KNOWN_OPS.has(op)) {\n throw new Error(\n `${caller}(${table}): where.${col} bilinmeyen operatör \"${op}\" (gt/gte/lt/lte/neq/in/contains/icontains/startsWith/endsWith/isNull)`,\n );\n }\n if (v === undefined) {\n throw new Error(\n `${caller}(${table}): where.${col}.${op} değeri undefined — karşılaştırmanın ` +\n `sağ tarafı NULL olur ve sonuç hiçbir satıra uymaz. Koşulu kurmayın.`,\n );\n }\n }\n }\n}\n\n/**\n * Refuse a write whose value never arrived.\n *\n * `{ title: req.body.title }` with no `title` in the body bound NULL and\n * answered 200 — the column was ERASED. `null` is untouched, and the difference\n * is the whole point: null is an author SAYING \"empty this column\"; undefined is\n * nobody saying anything.\n */\nexport function assertUsableWriteValues(\n caller: string,\n table: string,\n cols: readonly string[],\n data: Record<string, unknown>,\n): void {\n for (const c of cols) {\n if (data[c] === undefined) {\n throw new Error(\n `${caller}(${table}): \"${c}\" değeri undefined — bu bir yazma değeri değil. ` +\n `Kolonu boşaltmak istiyorsan null yaz; kolonu değiştirmek istemiyorsan nesneye hiç koyma ` +\n `(bir eksik istek alanı sessizce NULL yazıyordu — FR-016).`,\n );\n }\n }\n}\n","/**\n * tx-plan.ts — `Database.$transaction()` as a PLAN, not a pinned session.\n *\n * A transaction used to be a conversation: BEGIN, then one network round trip\n * per operation, then COMMIT. Each of those round trips cost ~4 ms and, because\n * the pooler runs in transaction mode, an open transaction pinned a Postgres\n * backend for the whole conversation. A 121-operation statement upload pinned\n * one backend for ~490 ms.\n *\n * So the callback no longer TALKS to the database. It DESCRIBES what should\n * happen; the description is serialised and sent once; the broker runs the whole\n * thing inside one transaction and answers once. Committing on return and\n * rolling back on throw is unchanged — that is the only property tenant code\n * actually asked for.\n *\n * The consequences, stated plainly, because they are the whole design:\n *\n * - The callback is SYNCHRONOUS. There is nothing to await: no statement has\n * run yet when it returns. `async` on the callback and `await` inside it are\n * both compile errors (see {@link TxPlan} and {@link NotAwaitable}).\n * - `insert()` does not hand back a row, it hands back {@link TxRows}. Reading\n * a field requires `.expectOne(err)` first, which makes \"what if the row\n * isn't there\" a question you cannot route around: it is the argument.\n * - A field read from a row is a {@link Ref} — a PROMISE OF A VALUE THE SERVER\n * WILL PRODUCE, not the value. It can be written into a later operation and\n * it can be returned from the callback (it is substituted for the real value\n * before `transaction()` resolves). It cannot be branched on. See the\n * \"Truthiness\" note below — this is the sharp edge of the whole design.\n * - Control flow that needs a real value must move OUT of the callback: read\n * before the transaction, or express the condition as a guard\n * (`updateWhere({ id, accepted_at: null }, …).expectOne(new Conflict(…))`)\n * which the server evaluates and which rolls the whole plan back.\n *\n * # Truthiness — the hole this file CANNOT close\n *\n * JavaScript does not let a Proxy trap truthiness. `if (ref)` takes the true\n * branch, always, for every Ref, and no `get` handler ever runs. `tsc` is silent\n * because a Ref is a perfectly good object. So:\n *\n * const pot = tx.tables.pots.select({ id }, { limit: 1 }).expectOne(e);\n * if (!pot.balance) { … } // ← ALWAYS false. Silently wrong data.\n *\n * What this file does close: coercion (`Symbol.toPrimitive`/`valueOf`/\n * `toString`), awaiting (`then` is a callable member with a non-thenable\n * signature, which is a *compile* error), serialisation (`toJSON`), and nesting\n * a Ref inside a literal value where the server would store it as data. What it\n * cannot close is a bare truthiness test. The real defence is the build-time\n * static analysis (`tx_analysis.js`, phase P4); until that ships, this hole is\n * open and this comment is the only warning.\n *\n * # Wire contract\n *\n * The JSON this file emits is consumed by\n * the plan executor in `engine/db.ts`. That executor rejects\n * unknown fields at every level, so an op carries EXACTLY the fields its kind\n * takes. Everything here that looks like a needless restriction is one of the\n * server's rules made visible early:\n *\n * - `$ref` only points BACKWARDS, and only at an op statically known to yield\n * at most one row (insert, or a `one`/`atMost 1` guard, or `select limit 1`).\n * `.expectOne()` is what this file uses to satisfy that, always.\n * - `$expr` is a closed set: `inc`/`dec` (update only — they read the column's\n * current value) and `now()`.\n * - `update`/`delete` require a `where`; `insert` refuses one.\n * - `insertMany` rows must all set the same columns.\n * - ≤1000 ops, ≤5000 rows per insertMany, ≤8 MiB of JSON.\n *\n * Column keys are emitted SORTED, so the same callback always produces byte-\n * identical JSON. That is what lets the Go decoder be locked to golden files\n * this SDK emits (`testdata/tx_plan_golden/`).\n */\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\n/**\n * A plan handle was used as if it were a value: awaited, coerced to a string or\n * number, serialised, or nested inside another value.\n *\n * Thrown while the callback is still BUILDING the plan, so nothing has been sent\n * and nothing has been written.\n */\n// TİP-ONLY, ve döngü kasıtlı: `typed-db.ts` bu dosyadan tip alıyor, bu dosya\n// ondan `WhereOp` alıyor. Çalışma zamanında hiçbir şey ithal edilmiyor (import\n// type), yani modül döngüsü yok — paylaşılan olan şey TEK FİLTRE DİLİ, ve onu\n// iki yerde ayrı ayrı tanımlamak bu run'ın kapattığı \"iki yazım\"ın tipteki\n// hâli olurdu.\nimport type { WhereOpWith, ColRefOf, HasOnly, SqlFragment } from \"./typed-db.js\";\nimport { isColRef, isSqlFragment, brandRef, isNowExpr } from \"./input-guards.js\";\n\nexport class TxRefError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TxRefError\";\n }\n}\n\n/**\n * The plan the callback described cannot be sent: it breaks a rule the server\n * would reject, and rejecting it here names the line that wrote it instead of\n * returning a 400 about an op index.\n */\nexport class TxPlanError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TxPlanError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Wire types — mirror the plan executor in `engine/db.ts` exactly.\n// ---------------------------------------------------------------------------\n\n/** A backwards reference to an earlier op's single-row result. */\nexport interface TxWireRef {\n $ref: { op: number; field: string };\n}\n\n/** A call from the server's closed function set. */\nexport interface TxWireExpr {\n $expr: { fn: \"inc\" | \"dec\"; by: number | string } | { fn: \"now\" };\n}\n\n/** One value in a `values`/`set`/`where` map: a literal, a `$ref` or a `$expr`. */\nexport type TxWireValue = TxWireRef | TxWireExpr | unknown;\n\n/** The tenant's declared expectation about an op's row count. `slot` indexes the\n * client-side error table — the error OBJECT never travels. */\nexport interface TxWireGuard {\n kind: \"one\" | \"none\" | \"atLeast\" | \"atMost\";\n n: number;\n slot: number;\n}\n\n/** One operation in the wire plan. Fields are omitted, never null: the decoder\n * rejects a field that does not belong to the op's kind. */\nexport interface TxWireOp {\n /** upsert and insertMany: the columns Postgres matches on. */\n onConflict?: readonly string[];\n /** insertMany only: what a collision does. Absent means no ON CONFLICT clause\n * at all, which is what every insertMany did before this option existed. */\n action?: \"ignore\" | \"update\";\n op: \"insert\" | \"insertMany\" | \"upsert\" | \"update\" | \"delete\" | \"select\";\n table: string;\n values?: Record<string, TxWireValue>;\n rows?: Record<string, TxWireValue>[];\n set?: Record<string, TxWireValue>;\n where?: Record<string, TxWireValue>;\n limit?: number;\n lock?: \"update\";\n guard?: TxWireGuard;\n}\n\n/** The plan the engine executes on the request's own transaction. */\nexport interface TxPlanBody {\n ops: TxWireOp[];\n}\n\n/** One op's outcome, positionally matched to the plan's ops. */\nexport interface TxPlanOpResult {\n rows: Record<string, unknown>[];\n rows_affected: number;\n}\n\n/** One result per op, in plan order. */\nexport interface TxPlanResponse {\n results: TxPlanOpResult[];\n}\n\n/**\n * The fields the runtime must copy from the broker's error envelope onto the\n * rejection it throws out of {@link DBClient.txPlan}.\n *\n * `slot` is the whole point: on a guard failure the server answers with the\n * INDEX of the expectation that did not hold, never with an error message of its\n * own, and this SDK maps that index back to the `Error` the callback handed to\n * `.expectOne(…)`. Without `slot` a guard failure degrades to a generic 409.\n */\nexport interface TxPlanRejection {\n status?: number;\n /** `tx_plan_invalid` | `tx_guard_failed` | `tx_ref_unresolved` | a pg class. */\n error_code?: string;\n /** Present only for `tx_guard_failed`: the client-side error table index. */\n slot?: number;\n /** Present on a database error: which op failed. */\n op?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Handle types\n// ---------------------------------------------------------------------------\n\ndeclare const refBrand: unique symbol;\ndeclare const rowBrand: unique symbol;\ndeclare const rowsBrand: unique symbol;\n\n/**\n * Makes a handle a compile error to `await`.\n *\n * `then` is declared as a CALLABLE member whose signature is not `PromiseLike`,\n * which is precisely the shape TypeScript rejects: `await handle` is TS1320 and\n * `async () => handle` is TS1058. A non-callable `then` would not do it — the\n * compiler simply ignores those.\n */\nexport interface NotAwaitable {\n /** Not a promise. Nothing here has run yet; there is nothing to await. */\n then(doNotAwaitAPlanHandle: \"a transaction plan is built synchronously\"): never;\n}\n\n/**\n * A value the SERVER will produce, standing in for a column of a row this plan\n * writes or reads.\n *\n * Legal uses: write it into a later operation's `values`/`set`/`where`, or\n * return it from the callback (it is replaced by the real value before\n * `transaction()` resolves).\n *\n * Illegal, and caught: `await`, `String(ref)`, `` `${ref}` ``, `ref + 1`,\n * `JSON.stringify(ref)`, burying it inside a jsonb object.\n *\n * Illegal, and NOT caught: `if (ref)`. See the truthiness note at the top.\n */\nexport interface Ref<T> extends NotAwaitable {\n readonly [refBrand]: T;\n}\n\n/** The brand carried by a single-row handle, and the seam `Materialized` reads\n * to turn `return st` into the whole row. */\nexport interface TxRowHandle<Row> extends NotAwaitable {\n readonly [rowBrand]: Row;\n}\n\n/**\n * A row this plan is known to produce exactly one of. Every property is a\n * {@link Ref}; returning the handle itself yields the whole row.\n *\n * Only `.expectOne(err)` produces one — which is the design: a row you can read\n * fields from is a row whose absence you have already answered for.\n */\nexport type TxRow<Row> = { readonly [K in keyof Row]: Ref<Row[K]> } & TxRowHandle<Row>;\n\n/**\n * The result of one operation, before any expectation is declared about it.\n *\n * Deliberately not a row and not a list: an operation's row count is not known\n * until the server runs it, so the only thing that can be said about it here is\n * an EXPECTATION. Declaring one is also the only way to get a readable row.\n *\n * At most one expectation per operation — the wire carries one guard per op, and\n * a second call throws rather than silently dropping the first.\n */\nexport interface TxRows<Row> extends NotAwaitable {\n readonly [rowsBrand]: Row;\n /**\n * Require exactly one row, and read it. On any other count the server rolls\n * the whole transaction back and this `error` is thrown to the caller.\n *\n * This is the only way to reach a row's fields, and the only shape a `$ref`\n * may point at.\n */\n expectOne(error: Error): TxRow<Row>;\n /** Require zero rows (e.g. \"this membership must not already exist\"). */\n expectNone(error: Error): void;\n /** Require at least `n` rows. */\n expectAtLeast(n: number, error: Error): void;\n /** Require at most `n` rows. */\n expectAtMost(n: number, error: Error): void;\n}\n\n/** `now()` — the server's clock, usable wherever a value is. */\nexport interface TxNow extends NotAwaitable {\n readonly $expr: { fn: \"now\" };\n}\n\n/** `inc(n)` / `dec(n)` — read the column's CURRENT value and write it back\n * changed. Only meaningful in an update's `set`, which is where the types allow\n * it and where the server allows it. */\nexport interface TxColumnExpr extends NotAwaitable {\n readonly $expr: { fn: \"inc\" | \"dec\"; by: number | string };\n}\n\n/**\n * Resolve a callback's return type against what actually comes back: every\n * {@link Ref} becomes its value, every {@link TxRow} becomes its row, and\n * anything else keeps its shape.\n *\n * A {@link TxRows} resolves to an explanatory string type rather than a row\n * list: it has no single answer to give, and saying so in the type is louder\n * than a runtime throw.\n */\nexport type Materialized<T> = T extends Ref<infer U>\n ? U\n : T extends TxRowHandle<infer R>\n ? R\n : T extends TxRows<unknown>\n ? \"a TxRows cannot leave the transaction callback — read a row with .expectOne(err) first\"\n : T extends Date\n ? T\n : T extends object\n ? { [K in keyof T]: Materialized<T[K]> }\n : T;\n\n// ---------------------------------------------------------------------------\n// Author-facing value types\n// ---------------------------------------------------------------------------\n\n/** A value written by an INSERT: a literal, an earlier row's field, or `now()`.\n * `inc`/`dec` are absent on purpose — they read a current value, and an inserted\n * row has none. */\nexport type TxInsertValue<V> = V | Ref<V> | TxNow;\n\n/** A value written by an UPDATE's `set`: everything an insert takes, plus the\n * read-modify-write expressions. */\n/**\n * TEK KURAL: ifade tutamağı yalnız sayısal-benzeri kolonlarda.\n *\n * Bu tip KOŞULSUZDU ve doğrudan yolun `SetValue<V>`'si koşulluydu, yani aynı\n * nesne için İKİ tip kuralı vardı: `tx.tables.todos.updateWhere({id}, { done:\n * increment(1) })` (boolean kolon!) DERLENİYOR, `updateMany`'nin aynısı derleme\n * hatası veriyordu. Bu run'ın kapatmak için var olduğu şey \"aynı iş için iki\n * uyumsuz yazım\"dı; tip kuralı ikinci yazımın kendisi olmuştu (gözcü I6/I-1).\n */\nexport type TxSetValue<V> =\n | V\n | Ref<V>\n | TxNow\n | (NonNullable<V> extends number | string ? TxColumnExpr : never);\n\n/** An insert payload: the table's insert shape, with refs and `now()` allowed. */\nexport type TxInsertShape<Insert> = { [K in keyof Insert]: TxInsertValue<Insert[K]> };\n\n/** An update's `set`: any subset of the insert shape, with expressions allowed. */\nexport type TxSetShape<Insert> = { [K in keyof Insert]?: TxSetValue<Insert[K]> };\n\n/**\n * A filter. Every entry is an equality test and they are AND-ed; a `null`\n * becomes `IS NULL`, which is what makes `{ accepted_at: null }` a usable\n * \"not yet accepted\" guard rather than a clause that matches nothing.\n */\n/**\n * Plan filtresinin tipi — `WhereFilter<Row>` ile AYNI sözlük, artı `Ref`.\n *\n * Eskiden yalnız eşitlikti (`Row[K] | Ref<Row[K]>`), ve iki şeye mal oluyordu:\n * FR-014'ün amiral deseni (`{ balance: { gte: amount } }`) `$transaction`\n * İÇİNDE yazılamıyordu — koşullu bir yazmayı plana koyamayan yazar `$query`'ye\n * düşüyordu — ve motor tarafında tip atlandığında aynı nesne SESSİZCE parametre\n * olarak bağlanıyordu.\n *\n * `Ref` fazladan üye ve öyle kalmalı: bir plan filtresi ÖNCEKİ bir işlemin\n * döndürdüğü değere bakabilir, `findMany` bakamaz — plan dışında böyle bir\n * \"önceki işlem\" yok.\n */\ntype TxWhereField<Row, K extends keyof Row> = WhereOpWith<\n Row[K],\n // `Ref` KOLON REFERANSININ YANINDA duruyor, `V`'nin içinde DEĞİL: `V`'ye\n // eklenseydi `TextOps<V>`'nin `V extends string` sorusu HAYIR olur ve\n // `contains`/`startsWith` sessizce kaybolurdu (ölçüldü).\n ColRefOf<Row, Row[K]> | Ref<Row[K]>\n>;\n\nexport type TxWhere<Row, Rels = unknown> = {\n [K in keyof Row]?: TxWhereField<Row, K>;\n} & {\n // Düz op'lardaki `WhereFilter` ile AYNI: dal bir `sqlFragment` de olabilir.\n // İki filtre dilinin bir dalda ayrışması, \"tek dil\" iddiasını tam da bileşim\n // anında boşa çıkarırdı — ve motor plan yolunda da fragment'i derliyor\n // (ölçüldü: `SELECT t.* FROM \"crew\" t WHERE true AND (((a > 1)) AND (…))`).\n OR?: (TxWhere<Row, Rels> | SqlFragment)[];\n AND?: (TxWhere<Row, Rels> | SqlFragment)[];\n NOT?: TxWhere<Row, Rels> | SqlFragment;\n} & HasOnly<Rels>;\n\n/** Options for a plan `select`. */\nexport interface TxSelectOptions {\n /** Cap the rows read. */\n limit?: number;\n /** Take a real `FOR UPDATE` row lock for the rest of the transaction. */\n lock?: \"update\";\n}\n\n/** One table, as the plan sees it. */\nexport interface TxTable<Row, Insert, Rels = unknown> {\n /** Insert one row. Returns a handle — call `.expectOne(err)` to read fields. */\n insert(values: TxInsertShape<Insert>): TxRows<Row>;\n /**\n * Insert many rows in ONE statement. Every row must set the same columns\n * (a row that omits one would silently take the column's default).\n *\n * An empty list writes nothing and sends nothing.\n */\n /**\n * Insert many rows in ONE statement, optionally choosing what a collision does.\n *\n * Without `opts` this is a plain multi-row INSERT and a collision aborts the\n * transaction — the behaviour every call had before the option existed.\n *\n * `action: \"ignore\"` emits `ON CONFLICT DO NOTHING`, which is how \"insert the\n * ones that are new\" becomes one round-trip instead of one per row with a\n * 23505 caught around each. **The returned rows are the ones actually\n * INSERTED**: a row that collided is skipped, so it is absent from the result\n * — Postgres does not return what it did not write.\n *\n * `action: \"update\"` emits `ON CONFLICT DO UPDATE`, setting every non-conflict\n * column from the incoming row, and every row comes back.\n */\n insertMany(\n rows: readonly TxInsertShape<Insert>[],\n opts?: {\n onConflict: readonly Extract<keyof Row, string>[];\n action?: \"ignore\" | \"update\";\n },\n ): TxRows<Row>;\n /**\n * Satırı yaz, `onConflict` kolonlarında çakışırsa üzerine yaz — planın\n * savepoint'i içinde, `Database.<şema>.<tablo>.put()` ile AYNI anlamda.\n *\n * Adı bilerek aynı: aynı iş için transaction içinde ve dışında iki farklı\n * yazım, bu run'ın kapatmak için var olduğu şeydir (P1). TEL şekli\n * (`op: \"upsert\"`) değişmedi — o iç sözleşme, yazarın gördüğü ad değil.\n *\n * Bir operasyon olmasının sebebi: alternatifi burada yazılamaz — başarısız\n * bir insert tüm transaction'ı abort eder, yani \"dene, sonra geri düş\" iki\n * plan adımı olamaz.\n */\n put(\n values: TxInsertShape<Insert>,\n options: { onConflict: readonly Extract<keyof Row, string>[] },\n ): TxRows<Row>;\n /**\n * Update every row matching `where`. The filter comes first because it is the\n * dangerous half: an update whose `where` you got wrong rewrites rows you\n * never looked at. The server refuses an update with no `where` at all.\n */\n updateWhere(where: TxWhere<Row, Rels>, set: TxSetShape<Insert>): TxRows<Row>;\n /** Delete every row matching `where`. The server refuses an unfiltered delete. */\n deleteWhere(where: TxWhere<Row, Rels>): TxRows<Row>;\n /** Read rows, optionally locking them for the rest of the transaction. */\n select(where?: TxWhere<Row, Rels>, options?: TxSelectOptions): TxRows<Row>;\n}\n\n/**\n * The handle a transaction callback receives.\n *\n * It carries tables and nothing else: no `query`, no `findById`, no `asService`.\n * A read whose value the plan does not write belongs OUTSIDE the transaction,\n * where it costs one round trip and can be branched on like an ordinary value.\n */\nexport interface TxPlanHandle<TTables> {\n /**\n * @deprecated `tx.public` kullanın. Bu ad public'in takma adı olarak DURUYOR\n * (göç notu onu öğretiyor ve her mevcut çağrı onu kullanıyor), ama ARTIK\n * ÖĞRETİLMİYOR: doğrudan yüzeyde `Database.tables` FR-001 ile kaldırıldı, ve\n * plan yüzeyinin onu öğretmeye devam etmesi yazarı bir yüzeyde çalışıp\n * diğerinde derlenmeyen bir yazıma alıştırıyordu (gözcü M-6).\n */\n tables: TTables;\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — expressions\n// ---------------------------------------------------------------------------\n\n/** Internal marker read by the serialiser. */\nconst EXPR = Symbol.for(\"palbase.tx.expr\");\nconst REF = Symbol.for(\"palbase.tx.ref\");\nconst ROW = Symbol.for(\"palbase.tx.row\");\nconst ROWS = Symbol.for(\"palbase.tx.rows\");\n\ninterface RefDescriptor {\n op: number;\n field: string;\n}\n\n/** Property reads that must not silently produce a value on a plan handle.\n * `then` is the one that matters for correctness (it makes `await` a compile\n * error AND stops a handle from being adopted by a promise); the rest turn a\n * silent wrong answer — `\"[object Object]\"`, `NaN`, `{}` — into a thrown one. */\nconst TRAPPED_PROPS: readonly (string | symbol)[] = [\n \"then\",\n \"valueOf\",\n \"toString\",\n \"toJSON\",\n Symbol.toPrimitive,\n];\n\nfunction trap(prop: string | symbol, what: string, hint: string): never {\n const name = typeof prop === \"symbol\" ? prop.description ?? String(prop) : prop;\n throw new TxRefError(\n `${what} was used as a value (via \\`${name}\\`). Nothing in a transaction ` +\n `callback has run yet, so there is no value to read. ${hint}`,\n );\n}\n\n/** The server's `now()`. */\nexport function now(): TxNow {\n return makeExpr({ fn: \"now\" }) as TxNow;\n}\n\n/** Add `by` to the column's current value. Only valid in an update's `set`. */\nexport function increment(by: number | string): TxColumnExpr {\n assertAmount(by, \"increment\");\n return makeExpr({ fn: \"inc\", by }) as TxColumnExpr;\n}\n\n/**\n * `increment`'in eski adı. AYNI fabrikadır — iki uygulama değil, iki ad.\n *\n * @deprecated `increment()` kullanın; bu ad geriye dönük uyumluluk için duruyor.\n */\nexport const inc = increment;\n\n/** Subtract `by` from the column's current value. Only valid in an update's `set`. */\nexport function decrement(by: number | string): TxColumnExpr {\n assertAmount(by, \"decrement\");\n return makeExpr({ fn: \"dec\", by }) as TxColumnExpr;\n}\n\n/**\n * `decrement`'in eski adı. AYNI fabrikadır.\n *\n * @deprecated `decrement()` kullanın.\n */\nexport const dec = decrement;\n\n/**\n * Miktarın taşınabilir olduğunu doğrular.\n *\n * String kabul edilir ve KASITLIDIR (D-007): `numeric` bir kolonda miktar JS\n * `number`'a uğrarsa 0.1 + 0.2 orada 0.30000000000000004'tür ve para hesabı\n * sessizce kayar. String hem burada hem `renderValue`'da bound parametre olarak\n * taşınır — Postgres onu tam ondalık olarak okur.\n */\nfunction assertAmount(by: number | string, fn: string): void {\n if (typeof by === \"string\") {\n // Metin SQL'e girmiyor (bound parametre), ama şekli yine de doğrulanır:\n // \"abc\" bind edilirse hata Postgres'ten gelir, çağıranın diliyle değil.\n if (!/^-?\\d+(\\.\\d+)?$/.test(by)) {\n throw new TxPlanError(\n `${fn}() ondalık bir sayı metni bekliyor, \"${by}\" aldı — kabul edilen biçim: \"12\", \"-12\", \"12.50\"`,\n );\n }\n } else if (typeof by !== \"number\" || !Number.isFinite(by)) {\n // JSON has no NaN/Infinity: they would serialise to `null` and the server\n // would reject the plan with an unhelpful decode error.\n throw new TxPlanError(`${fn}() needs a finite number, got ${String(by)}`);\n }\n // NEGATİF MİKTAR REDDEDİLİR — ve bu şekil kontrolünden çok daha fazlası.\n // `decrement(\"-5\")` `SET c = c - $1` derliyordu, `$1 = -5`, yani beş EKLİYORDU.\n // FR-014'ün amiral deseninde (`where: { balance: { gte: amount } }`) miktar\n // istek gövdesinden geliyorsa `balance >= -5` her zaman doğru: hesap\n // KREDİLENDİRİLİR ve çağrı bunu 1 satırla \"başarı\" diye raporlar. Guard\n // okunduğunda işaret kontrol edilmiş gibi duruyordu (gözcü I9, ölçüldü).\n const negative = typeof by === \"string\" ? by.trimStart().startsWith(\"-\") : by < 0;\n if (negative) {\n const other = fn === \"increment\" ? \"decrement\" : \"increment\";\n throw new TxPlanError(\n `${fn}() negatif miktar almaz (\"${String(by)}\"). Ters yön için ${other}() kullanın — ` +\n `işaretin miktarda saklanması, yönü okuyan hiçbir kod tarafından görülmezdi.`,\n );\n }\n}\n\n/**\n * Bir değer `increment()`/`decrement()` ürünü mü? Öyleyse tel şekli.\n *\n * DOĞRUDAN yol (`updateMany`) da bu ifadeyi anlamak zorunda: aynı nesnenin iki\n * yerde çalışması, \"kolona ekle\"nin tek yazımı olmasının şartı (P1).\n */\nexport function columnExprOf(v: unknown): TxWireExpr[\"$expr\"] | null {\n return exprOf(v);\n}\n\nfunction makeExpr(expr: TxWireExpr[\"$expr\"]): unknown {\n return new Proxy(\n { [EXPR]: expr } as Record<string | symbol, unknown>,\n {\n get(target, prop) {\n if (prop === EXPR) return target[EXPR];\n if (TRAPPED_PROPS.includes(prop)) {\n trap(prop, \"A plan expression\", \"Write it into an operation instead.\");\n }\n return undefined;\n },\n },\n );\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — refs and row handles\n// ---------------------------------------------------------------------------\n\nfunction makeRef(op: number, field: string): unknown {\n const target: Record<string | symbol, unknown> = { [REF]: { op, field } satisfies RefDescriptor };\n return new Proxy(target, {\n get(t, prop) {\n if (prop === REF) return t[REF];\n if (TRAPPED_PROPS.includes(prop)) {\n trap(\n prop,\n `\\`${field}\\` of a row this transaction has not written yet`,\n \"Pass it to another operation in the same plan, or return it from the \" +\n \"callback and read it after `transaction()` resolves.\",\n );\n }\n return undefined;\n },\n });\n}\n\nfunction makeRowHandle(op: number): unknown {\n const target: Record<string | symbol, unknown> = { [ROW]: op };\n return new Proxy(target, {\n get(t, prop) {\n if (prop === ROW) return t[ROW];\n if (TRAPPED_PROPS.includes(prop)) {\n trap(\n prop,\n \"A row this transaction has not written yet\",\n \"Read one of its columns to reference it, or return the row from the \" +\n \"callback and read it after `transaction()` resolves.\",\n );\n }\n if (typeof prop === \"symbol\") return undefined;\n return makeRef(op, prop);\n },\n });\n}\n\nfunction refDescriptor(v: unknown): RefDescriptor | null {\n if (typeof v !== \"object\" || v === null) return null;\n const d = (v as Record<symbol, unknown>)[REF];\n return isRefDescriptor(d) ? d : null;\n}\n\nfunction isRefDescriptor(d: unknown): d is RefDescriptor {\n return (\n typeof d === \"object\" &&\n d !== null &&\n typeof (d as RefDescriptor).op === \"number\" &&\n typeof (d as RefDescriptor).field === \"string\"\n );\n}\n\nfunction rowOpIndex(v: unknown): number | null {\n if (typeof v !== \"object\" || v === null) return null;\n const op = (v as Record<symbol, unknown>)[ROW];\n return typeof op === \"number\" ? op : null;\n}\n\nfunction exprOf(v: unknown): TxWireExpr[\"$expr\"] | null {\n if (typeof v !== \"object\" || v === null) return null;\n const e = (v as Record<symbol, unknown>)[EXPR];\n return typeof e === \"object\" && e !== null ? (e as TxWireExpr[\"$expr\"]) : null;\n}\n\nfunction isRowsHandle(v: unknown): boolean {\n return typeof v === \"object\" && v !== null && (v as Record<symbol, unknown>)[ROWS] !== undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — value encoding\n// ---------------------------------------------------------------------------\n\n/**\n * Encode one value of a `values`/`set`/`where` map.\n *\n * The nesting check is not defensive tidiness. The server treats `$ref` as a\n * tagged value only at the TOP of a column's value; a ref buried inside a jsonb\n * payload is just data, and would be stored as the literal object\n * `{\"$ref\":{...}}` — a write that succeeds, commits, and is wrong. So a nested\n * handle is a hard error here, where the line that wrote it is still on the\n * stack.\n */\nfunction encodeValue(value: unknown, column: string, allowColumnExpr: boolean): TxWireValue {\n const ref = refDescriptor(value);\n if (ref) return brandRef({ $ref: { op: ref.op, field: ref.field } }, \"ref\") satisfies TxWireRef;\n\n // `now()` bir KARŞILAŞTIRMA değeri olarak geçer — sunucu saati. Diğer\n // ifadeler (increment/decrement) yazma ifadesidir ve aşağıda adıyla\n // reddediliyor. Düz op yolu ile aynı ayrım, aynı gerekçe.\n if (isNowExpr(value)) return { $expr: { fn: \"now\" } };\n const expr = exprOf(value);\n if (expr) {\n if (expr.fn !== \"now\" && !allowColumnExpr) {\n throw new TxPlanError(\n `\\`${column}\\`: ${expr.fn}() reads the column's current value, so it is ` +\n `only valid in updateWhere(where, set).`,\n );\n }\n return { $expr: expr } satisfies TxWireExpr;\n }\n\n if (rowOpIndex(value) !== null) {\n throw new TxPlanError(\n `\\`${column}\\`: a row handle is not a value. Read the column you meant ` +\n `(e.g. \\`row.id\\`).`,\n );\n }\n if (isRowsHandle(value)) {\n throw new TxPlanError(\n `\\`${column}\\`: an operation result is not a value. Declare an expectation ` +\n `first (\\`.expectOne(err)\\`) and read a column from the row.`,\n );\n }\n\n assertNoNestedHandles(value, column);\n return value;\n}\n\n/**\n * Encode a FİLTRE — `values`/`set` ile AYNI kodlayıcı değil, ve olmaması bir\n * düzeltme.\n *\n * `encodeValue` bir `$ref`'i yalnız kolonun EN ÜSTÜNDE kabul ediyor, çünkü bir\n * insert değerinin İÇİNE gömülü ref sunucuda çözülmez, literal JSON olarak\n * SAKLANIR — \"başarıyla commit olan ve yanlış olan bir yazma\". O kural DEĞER\n * yolu için doğru.\n *\n * FİLTREDE öyle değil: motorun `resolveRefsDeep`'i bir ref'i filtrenin HER\n * yerinde çözüyor — operatörün sağında, `OR`/`AND`/`NOT` dallarının içinde. Ama\n * kodlayıcı hâlâ değer kuralını uyguluyordu, yani üç katman üç farklı cevap\n * veriyordu (gözcü C-2): tip kabul, motor çözüyor, kodlayıcı REDDEDİYOR — ve\n * reddin metni değer-yuvalama vakasını anlatıyor, filtrede olmayan bir şeyi.\n *\n * İFADE TUTAMAĞI ve SATIR TUTAMAĞI filtrede HÂLÂ reddediliyor: onları motor\n * filtrede çözmüyor ve çözmemeli — `increment()` bir yazma ifadesi, bir\n * karşılaştırma değil.\n */\nfunction encodeFilterValue(value: unknown, column: string): unknown {\n const ref = refDescriptor(value);\n if (ref) return brandRef({ $ref: { op: ref.op, field: ref.field } }, \"ref\") satisfies TxWireRef;\n\n const expr = exprOf(value);\n if (expr) {\n throw new TxPlanError(\n `\\`${column}\\`: ${expr.fn}() bir YAZMA ifadesi, karşılaştırma değil — ` +\n `filtrede kullanılamaz. Kolonu bir değerle ya da col() ile karşılaştırın.`,\n );\n }\n if (rowOpIndex(value) !== null) {\n throw new TxPlanError(\n `\\`${column}\\`: a row handle is not a value. Read the column you meant (e.g. \\`row.id\\`).`,\n );\n }\n if (isRowsHandle(value)) {\n throw new TxPlanError(\n `\\`${column}\\`: an operation result is not a value. Declare an expectation ` +\n `first (\\`.expectOne(err)\\`) and read a column from the row.`,\n );\n }\n if (Array.isArray(value)) return value.map((v) => encodeFilterValue(v, column));\n // `col()` ve `sqlFragment` OLDUĞU GİBİ geçer: markaları süreç içinde korunur\n // ve derleyici ikisini de kendi tanıyor.\n if (value !== null && typeof value === \"object\" && !(value instanceof Date) && !isColRef(value) && !isSqlFragment(value)) {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n out[k] = encodeFilterValue(v, column);\n }\n return out;\n }\n return value;\n}\n\n/** Filtre haritası — anahtarlar SIRALI (aynı geri çağrı bayt-özdeş JSON üretsin). */\nfunction encodeFilterMap(map: Record<string, unknown>): Record<string, TxWireValue> {\n const out: Record<string, TxWireValue> = {};\n for (const key of Object.keys(map).sort()) {\n const value = map[key];\n if (value === undefined) continue;\n out[key] = encodeFilterValue(value, key) as TxWireValue;\n }\n return out;\n}\n\nfunction assertNoNestedHandles(value: unknown, column: string): void {\n if (typeof value !== \"object\" || value === null) return;\n if (value instanceof Date) return;\n if (refDescriptor(value) || exprOf(value) || rowOpIndex(value) !== null || isRowsHandle(value)) {\n throw new TxPlanError(\n `\\`${column}\\`: a plan handle is nested inside a value. The server would ` +\n `store it as literal JSON, not resolve it. Put the reference directly in ` +\n `the column.`,\n );\n }\n if (Array.isArray(value)) {\n for (const item of value) assertNoNestedHandles(item, column);\n return;\n }\n for (const item of Object.values(value as Record<string, unknown>)) {\n assertNoNestedHandles(item, column);\n }\n}\n\n/**\n * Encode a column map, dropping `undefined` and emitting keys SORTED.\n *\n * Sorting is what makes the same callback produce byte-identical JSON every\n * time, which is what lets the Go decoder be locked to goldens this SDK emits.\n * Dropping `undefined` mirrors what `JSON.stringify` would do anyway, but does\n * it where the resulting column list is still checkable.\n */\nfunction encodeMap(\n map: Record<string, unknown>,\n allowColumnExpr: boolean,\n): Record<string, TxWireValue> {\n const out: Record<string, TxWireValue> = {};\n for (const key of Object.keys(map).sort()) {\n const value = map[key];\n // AÇIK `undefined` REDDEDİLİR (D-017 kapandı).\n //\n // \"Kolon varsayılanını al\" demenin yolu anahtarı HİÇ KOYMAMAK; bu döngü\n // zaten yalnız var olan anahtarları geziyor, yani o niyet bozulmadan\n // çalışıyor. Ayırt edilen şey başka: anahtarın DURDUĞU ama değerinin\n // `undefined` olduğu hâl — yani `{ title: req.body.title }` gövdede\n // `title` yokken. O ölçülmüş bir olaydı: kolon sessizce yazılmadı ve\n // istek 200 döndü.\n //\n // Doğrudan yol bunu baştan beri adıyla reddediyordu; plan yolu sessizce\n // düşürüyordu. Aynı girdiye zıt iki cevap, \"tek filtre dili, tek cevap\"\n // iddiasını yazma tarafında boşa çıkarıyordu.\n if (value === undefined) {\n throw new TxPlanError(\n `${key} değeri undefined — bu bir yazma değeri değil. Anahtar duruyor ` +\n `ama değeri yok, yani kolon sessizce YAZILMAZDI (istek gövdesinden ` +\n `gelen bir alanın eksik olması bu şekilde görünür). Kolon ` +\n `varsayılanını istiyorsanız anahtarı hiç koymayın; NULL yazmak ` +\n `istiyorsanız açıkça null yazın.`,\n );\n }\n out[key] = encodeValue(value, key, allowColumnExpr);\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — the builder\n// ---------------------------------------------------------------------------\n\n/** How many rows an op can produce, as far as the CLIENT can tell before it\n * runs. Only the empty `insertMany` is knowable, and knowing it is what lets a\n * doomed expectation fail on the line that declared it. */\nconst SKIPPED_OP = -1;\n\nclass TxRowsImpl<Row> implements TxRows<Row> {\n // Present so `isRowsHandle` recognises the object; never read for its value.\n readonly [ROWS] = true;\n // Phantom: the type brand that stops a bare object passing as a TxRows. Never\n // present at run time, which is what `declare` says.\n declare readonly [rowsBrand]: Row;\n private guarded = false;\n\n constructor(\n private readonly builder: TxPlanBuilder,\n private readonly opIndex: number,\n private readonly what: string,\n ) {}\n\n // The type-level `await` guard made real: TS rejects `await rows` at compile\n // time, and reaching this means someone called `.then(...)` by hand.\n then(): never {\n throw new TxRefError(\n `${this.what} cannot be awaited: a transaction callback builds a plan, it ` +\n `does not run statements. Remove the \\`await\\`.`,\n );\n }\n\n expectOne(error: Error): TxRow<Row> {\n this.declareGuard(\"one\", 1, error);\n if (this.opIndex === SKIPPED_OP) throw error;\n return makeRowHandle(this.opIndex) as TxRow<Row>;\n }\n\n expectNone(error: Error): void {\n this.declareGuard(\"none\", 0, error);\n }\n\n expectAtLeast(n: number, error: Error): void {\n assertGuardCount(n, \"expectAtLeast\");\n this.declareGuard(\"atLeast\", n, error);\n if (this.opIndex === SKIPPED_OP && n > 0) throw error;\n }\n\n expectAtMost(n: number, error: Error): void {\n assertGuardCount(n, \"expectAtMost\");\n this.declareGuard(\"atMost\", n, error);\n }\n\n private declareGuard(kind: TxWireGuard[\"kind\"], n: number, error: Error): void {\n if (!(error instanceof Error)) {\n // The error object is the ONLY thing that describes this failure to the\n // caller — the server sends back an index, never a message.\n throw new TxPlanError(\n `${this.what}: an expectation needs the Error to throw when it does not ` +\n `hold (e.g. \\`.expect…(new Conflict(\"already accepted\"))\\`).`,\n );\n }\n if (this.guarded) {\n throw new TxPlanError(\n `${this.what} already has an expectation. One operation carries one ` +\n `expectation; declare the second one on its own operation.`,\n );\n }\n this.guarded = true;\n if (this.opIndex === SKIPPED_OP) return;\n this.builder.attachGuard(this.opIndex, kind, n, error);\n }\n}\n\nfunction assertGuardCount(n: number, fn: string): void {\n if (!Number.isInteger(n) || n < 0) {\n throw new TxPlanError(`${fn}(n) needs a non-negative integer, got ${String(n)}`);\n }\n}\n\n/** Bounds mirrored from the plan executor so an over-sized plan is named here rather\n * than rejected as an opaque 400 after it has crossed the network. */\nconst MAX_OPS = 1000;\nconst MAX_ROWS = 5000;\n\n/**\n * Accumulates ops and the client-side error table while the callback runs.\n *\n * Exported for the runtime and for tests that need the serialised plan without\n * a server; author code never sees it.\n */\nexport class TxPlanBuilder {\n private readonly ops: TxWireOp[] = [];\n /** Errors handed to expectations, indexed by the `slot` the server echoes. */\n private readonly slots: Error[] = [];\n\n /** The table surface handed to the callback. Untyped here; the public\n * `transaction()` signatures put the schema types on top. */\n table(name: string): TxTable<Record<string, unknown>, Record<string, unknown>> {\n return {\n insert: (values) => {\n const encoded = encodeMap(values as Record<string, unknown>, false);\n if (Object.keys(encoded).length === 0) {\n throw new TxPlanError(`${name}.insert() needs at least one column`);\n }\n return this.push({ op: \"insert\", table: name, values: encoded }, `${name}.insert()`);\n },\n\n put: (values, options) => {\n const encoded = encodeMap(values as Record<string, unknown>, false);\n if (Object.keys(encoded).length === 0) {\n throw new TxPlanError(`${name}.put() needs at least one column`);\n }\n if (options.onConflict.length === 0) {\n throw new TxPlanError(`${name}.put() needs at least one onConflict column`);\n }\n return this.push(\n { op: \"upsert\", table: name, values: encoded, onConflict: options.onConflict },\n `${name}.upsert()`,\n );\n },\n\n insertMany: (rows, opts) => {\n if (rows.length === 0) {\n // Nothing to write. Emitting an op would be a guaranteed 400 (the\n // server requires rows), and refusing outright would punish the\n // ordinary \"filtered every candidate out\" case.\n return new TxRowsImpl(this, SKIPPED_OP, `${name}.insertMany()`);\n }\n if (rows.length > MAX_ROWS) {\n throw new TxPlanError(\n `${name}.insertMany() has ${rows.length} rows; the limit is ${MAX_ROWS}. ` +\n `Split the write across requests.`,\n );\n }\n const encoded = rows.map((row) => encodeMap(row as Record<string, unknown>, false));\n assertUniformRows(encoded, name);\n if (opts !== undefined && opts.onConflict.length === 0) {\n throw new TxPlanError(\n `${name}.insertMany() was given a conflict action with no onConflict ` +\n `columns. Postgres matches a collision on columns, so name them.`,\n );\n }\n return this.push(\n {\n op: \"insertMany\",\n table: name,\n rows: encoded,\n // Omitted entirely when no options were given, so the op a plain\n // insertMany produces is byte-identical to the one it produced\n // before this option existed.\n ...(opts !== undefined\n ? { onConflict: opts.onConflict, action: opts.action ?? \"ignore\" }\n : {}),\n },\n `${name}.insertMany()`,\n );\n },\n\n updateWhere: (where, set) => {\n const encodedWhere = encodeFilterMap(where as Record<string, unknown>);\n const encodedSet = encodeMap(set as Record<string, unknown>, true);\n if (Object.keys(encodedWhere).length === 0) {\n throw new TxPlanError(\n `${name}.updateWhere() needs a filter. An update with no filter ` +\n `rewrites the whole table.`,\n );\n }\n if (Object.keys(encodedSet).length === 0) {\n throw new TxPlanError(`${name}.updateWhere() needs at least one column to set`);\n }\n return this.push(\n { op: \"update\", table: name, set: encodedSet, where: encodedWhere },\n `${name}.updateWhere()`,\n );\n },\n\n deleteWhere: (where) => {\n const encodedWhere = encodeFilterMap(where as Record<string, unknown>);\n if (Object.keys(encodedWhere).length === 0) {\n throw new TxPlanError(\n `${name}.deleteWhere() needs a filter. A delete with no filter empties ` +\n `the table.`,\n );\n }\n return this.push(\n { op: \"delete\", table: name, where: encodedWhere },\n `${name}.deleteWhere()`,\n );\n },\n\n select: (where, options) => {\n const op: TxWireOp = { op: \"select\", table: name };\n const encodedWhere = encodeFilterMap((where ?? {}) as Record<string, unknown>);\n if (Object.keys(encodedWhere).length > 0) op.where = encodedWhere;\n if (options?.limit !== undefined) {\n if (!Number.isInteger(options.limit) || options.limit < 0) {\n throw new TxPlanError(\n `${name}.select(): limit needs a non-negative integer, got ${String(options.limit)}`,\n );\n }\n op.limit = options.limit;\n }\n if (options?.lock !== undefined) op.lock = options.lock;\n return this.push(op, `${name}.select()`);\n },\n };\n }\n\n private push(op: TxWireOp, what: string): TxRows<Record<string, unknown>> {\n if (this.ops.length >= MAX_OPS) {\n throw new TxPlanError(\n `this transaction has ${MAX_OPS} operations, which is the limit. Use ` +\n `insertMany() for bulk writes, or split the work across requests.`,\n );\n }\n const index = this.ops.length;\n this.ops.push(op);\n return new TxRowsImpl(this, index, what);\n }\n\n /** Attach an expectation to an op and record its error in the slot table. */\n attachGuard(opIndex: number, kind: TxWireGuard[\"kind\"], n: number, error: Error): void {\n const op = this.ops[opIndex];\n // Unreachable: the index came from `push`. A loud failure beats a silently\n // unguarded write if that ever stops being true.\n if (!op) throw new TxPlanError(`internal: expectation on unknown operation ${opIndex}`);\n const slot = this.slots.length;\n this.slots.push(error);\n op.guard = { kind, n, slot };\n }\n\n /** The serialisable plan. Empty when the callback described no writes. */\n body(): TxPlanBody {\n return { ops: this.ops };\n }\n\n /** The error the server's `slot` selects, or `null` when it names one this\n * plan never declared (a server/client disagreement, not a tenant error). */\n errorForSlot(slot: number): Error | null {\n return this.slots[slot] ?? null;\n }\n}\n\nfunction assertUniformRows(rows: Record<string, TxWireValue>[], table: string): void {\n const first = rows[0];\n if (!first) return;\n const want = Object.keys(first);\n const wantKey = want.join(\",\");\n for (let i = 1; i < rows.length; i++) {\n const got = Object.keys(rows[i] as Record<string, TxWireValue>);\n if (got.join(\",\") !== wantKey) {\n // One statement, one column list. A ragged row would take the DB default\n // for the column it omitted — a write that succeeds and is wrong.\n throw new TxPlanError(\n `${table}.insertMany(): every row must set the same columns. Row 0 sets ` +\n `[${want.join(\", \")}] but row ${i} sets [${got.join(\", \")}]. ` +\n `(A property set to \\`undefined\\` counts as absent — use \\`null\\`.)`,\n );\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — materialisation\n// ---------------------------------------------------------------------------\n\n/**\n * Replace every handle in the callback's return value with what the server\n * actually produced.\n *\n * Walks arrays and PLAIN objects only. Class instances (a Date, a Zod schema, a\n * domain object) are returned untouched — recursing into them would rebuild them\n * as bare objects, and nothing inside one can be a handle that this SDK created.\n */\nexport function materializeResult(value: unknown, results: TxPlanOpResult[]): unknown {\n const ref = refDescriptor(value);\n if (ref) {\n const row = rowOf(results, ref.op, `\\`${ref.field}\\``);\n if (!(ref.field in row)) {\n throw new TxPlanError(\n `the transaction's operation ${ref.op} returned no column \\`${ref.field}\\`.`,\n );\n }\n return row[ref.field];\n }\n\n const rowOp = rowOpIndex(value);\n if (rowOp !== null) return rowOf(results, rowOp, \"a row\");\n\n if (isRowsHandle(value)) {\n throw new TxPlanError(\n \"an operation result cannot be returned from a transaction callback: its \" +\n \"row count is not known until the plan runs. Declare an expectation \" +\n \"(`.expectOne(err)`) and return the row, or a column of it.\",\n );\n }\n\n if (Array.isArray(value)) return value.map((item) => materializeResult(item, results));\n\n if (isPlainObject(value)) {\n const out: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) out[key] = materializeResult(item, results);\n return out;\n }\n\n return value;\n}\n\nfunction rowOf(results: TxPlanOpResult[], opIndex: number, what: string): Record<string, unknown> {\n const result = results[opIndex];\n if (!result) {\n throw new TxPlanError(\n `the transaction returned no result for operation ${opIndex}, so ${what} ` +\n `cannot be read.`,\n );\n }\n const row = result.rows[0];\n if (!row) {\n // Unreachable through the public API: a handle only exists behind an\n // `expectOne`, and the server rolls back rather than answering 200 with a\n // guard unmet. Loud, because the alternative is `undefined` in tenant data.\n throw new TxPlanError(\n `the transaction's operation ${opIndex} returned no row, so ${what} cannot ` +\n `be read.`,\n );\n }\n return row;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — the driver\n// ---------------------------------------------------------------------------\n\n/** What {@link runTxPlan} needs from the runtime: one call, one transaction. */\nexport interface TxPlanTransport {\n txPlan(plan: TxPlanBody): Promise<TxPlanResponse>;\n}\n\n/**\n * Build the plan, send it, and resolve the callback's return value.\n *\n * A callback that throws never reaches the network: there is nothing to roll\n * back because nothing was sent. A callback that describes no writes also skips\n * the round trip entirely.\n *\n * The RETURN type is `unknown` here on purpose. `Materialized<T>` is a compile-\n * time rewrite of the callback's return type, and it belongs on the public\n * `transaction()` signatures where `T` is inferred from the author's callback;\n * threading it through this driver as well would mean inferring `T` twice, from\n * two different positions, and reconciling them. The public wrappers narrow\n * once, at the seam where the value types were erased anyway.\n */\nexport async function runTxPlan<THandle>(\n transport: TxPlanTransport,\n // TUTAMAĞIN TAMAMI, yalnız `tables` DEĞİL. Tutamak artık şema yüzeyini de\n // taşıyor (`tx.public.x`, `tx.<şema>.x`), ve onu BURADA `{ tables }` diye\n // yeniden kurmak o yüzeyi sessizce düşürürdü.\n handle: THandle,\n builder: TxPlanBuilder,\n fn: (tx: THandle) => unknown,\n): Promise<unknown> {\n const returned = fn(handle);\n const body = builder.body();\n if (body.ops.length === 0) {\n return materializeResult(returned, []);\n }\n\n let response: TxPlanResponse;\n try {\n response = await transport.txPlan(body);\n } catch (err) {\n throw translateRejection(err, builder);\n }\n return materializeResult(returned, response.results);\n}\n\n/**\n * Turn the broker's rejection back into the tenant's own error.\n *\n * The server never sees the `Error` an expectation was given — only its slot\n * index — so this is the only place the intended error can be produced. A\n * rejection this SDK does not recognise passes through untouched: inventing an\n * error for it would hide the real failure.\n */\nfunction translateRejection(err: unknown, builder: TxPlanBuilder): unknown {\n if (typeof err !== \"object\" || err === null) return err;\n const rejection = err as TxPlanRejection;\n if (rejection.error_code !== \"tx_guard_failed\" || typeof rejection.slot !== \"number\") {\n return err;\n }\n return builder.errorForSlot(rejection.slot) ?? err;\n}\n","import type { DBClient, DBOps } from \"../../endpoint.js\";\nimport { validateInsertManyOptions, type InsertManyOptions } from \"../../db/bulk.js\";\n// The SAME refusals the engine applies. Without these the fake accepted every\n// call the driver path had just started rejecting, and the scaffold points\n// authors at this fake to test their services — so the test went green and\n// production threw. Measured against the published 24.1.0.\nimport { assertUsableFilter, assertUsableWriteValues, assertNoExpressionHandles, isColRef, isSqlFragment, isNowExpr, isColumnExpr } from \"../../db/input-guards.js\";\n\n/**\n * `sqlFragment` sahte veritabanında ÇALIŞTIRILAMAZ — ve sessizce yok sayılamaz.\n *\n * Fake'in bir SQL değerlendiricisi yok. Fragment'i görmezden gelmek, filtreyi\n * hiç uygulamamak demektir: test TÜM satırları görür, üretim ise süzülmüş\n * satırları. Yazarın testi o gün yeşil, üretim yanlış olur — bu dosyanın var\n * olma sebebi tam olarak o sınıf hata. O yüzden adıyla reddediliyor, ve hata\n * çalışan bir alternatif söylüyor (P6).\n */\nfunction refuseFragment(caller: string, table: string, where: unknown): void {\n if (isSqlFragment(where)) {\n throw new Error(\n `${caller}(${table}): fakeDatabase bir sqlFragment'i değerlendiremez — sahte depo SQL çalıştırmaz. ` +\n `Filtreyi tipli filtre diliyle kurun (gt/gte/lt/lte/neq/in/contains/isNull, OR/AND/NOT), ` +\n `ya da bu testi gerçek bir Postgres'e karşı yazın.`,\n );\n }\n // İÇ İÇE de reddedilir. Yalnız ÜST DÜZEYE bakmak, { OR: [ sqlFragment tag, … ] }\n // filtresini fake'te SESSİZCE boş sonuca çeviriyordu; motor onu derliyor\n // (W2-B/C5, ölçüldü). Reddin de bileşim dallarını dolaşması gerekiyor.\n if (where === null || typeof where !== \"object\") return;\n for (const [k, v] of Object.entries(where as Record<string, unknown>)) {\n if (k === \"OR\" || k === \"AND\") {\n for (const branch of (Array.isArray(v) ? v : [])) refuseFragment(caller, table, branch);\n } else if (k === \"NOT\") {\n refuseFragment(caller, table, v);\n }\n }\n}\n\n/**\n * Sayaç aritmetiği — motorun döndürdüğü ALANDA.\n *\n * Postgres `numeric` kolonu STRING döndürür ve toplamayı tam yapar. Fake\n * `Number()` ile hesaplıyordu; ölçülen sonuçlar: `\"0.10\" + \"0.20\"` →\n * `0.30000000000000004`, `\"12345678901234567890\" + 1` →\n * `12345678901234567000`, ve satırın tipi string'den number'a KAYIYORDU.\n * D-007'nin (string miktar) var olma sebebi tam olarak bu kayıptı; fake onu\n * geri getiriyordu (inceleme I-4/I-3).\n *\n * `null` + n = `null`: Postgres'te de öyle, satır değişmez.\n */\nfunction addDecimal(cell: unknown, by: number | string, sign: 1 | -1): unknown {\n if (cell === null || cell === undefined) return null;\n if (typeof cell === \"number\" && typeof by === \"number\") return cell + sign * by;\n const a = String(cell);\n const b = String(by);\n const parse = (x: string): { unit: bigint; scale: number } | null => {\n const m = /^([+-]?)(\\d*)(?:\\.(\\d*))?$/.exec(x.trim());\n if (m === null || (m[2] === \"\" && (m[3] ?? \"\") === \"\")) return null;\n const frac = m[3] ?? \"\";\n const unit = BigInt(`${m[1] === \"-\" ? \"-\" : \"\"}${m[2] === \"\" ? \"0\" : m[2]}${frac}`);\n return { unit, scale: frac.length };\n };\n const pa = parse(a);\n const pb = parse(b);\n if (pa === null || pb === null) {\n // Motor bu durumda Postgres'e sorar ve `operator does not exist:\n // text + integer` alır. Sessizce NaN yazmak yerine ADIYLA reddediyoruz.\n throw new Error(\n `fakeDatabase: increment()/decrement() sayısal olmayan bir değere uygulandı (\"${a}\") — ` +\n `Postgres bunu \"operator does not exist\" ile reddeder.`,\n );\n }\n const scale = Math.max(pa.scale, pb.scale);\n const lift = (v: { unit: bigint; scale: number }): bigint =>\n v.unit * 10n ** BigInt(scale - v.scale);\n const total = lift(pa) + BigInt(sign) * lift(pb);\n if (scale === 0) return typeof cell === \"number\" ? Number(total) : total.toString();\n const neg = total < 0n;\n const digits = (neg ? -total : total).toString().padStart(scale + 1, \"0\");\n const out = `${neg ? \"-\" : \"\"}${digits.slice(0, -scale)}.${digits.slice(-scale)}`;\n return typeof cell === \"number\" ? Number(out) : out;\n}\nimport { columnExprOf } from \"../../db/tx-plan.js\";\nimport type {\n TxPlanBody,\n TxPlanOpResult,\n TxPlanRejection,\n TxPlanResponse,\n TxWireGuard,\n TxWireOp,\n TxWireValue,\n} from \"../../db/tx-plan.js\";\n\n/** Tracked records for assertions. */\ninterface TrackedRecords {\n inserted: Map<string, Record<string, unknown>[]>;\n updated: Map<string, Record<string, unknown>[]>;\n deleted: Map<string, string[]>;\n}\n\n/** Mock DB client with tracking and seed data support. */\n/**\n * TEK EŞLEŞTİRİCİ — `findMany`, `updateMany`, `deleteMany` ve `count` bunu\n * kullanır.\n *\n * Motorda tek bir `compileWhereBare` var; fake'te DÖRT ayrı eşleştirici vardı\n * ve üçü yalnız katı eşitliğe bakıyordu. Ölçülen sonuç (inceleme C3/C6/I2):\n * `updateMany({ id, balance: { gte: \"5.00\" } }, …)` fake'te HİÇBİR satır\n * eşleştirmiyordu, yani FR-014'ün doc'unun ÖĞRETTİĞİ \"yetersiz bakiye\" deseni\n * fake'e karşı HER ZAMAN başarısız dala düşüyor — yazar başarı yolunu hiç test\n * edemiyor, üretimde para gerçekten çekiliyor.\n */\nfunction rowMatchesFilter(\n caller: string,\n table: string,\n row: Record<string, unknown>,\n f: Record<string, unknown>,\n): boolean {\n return Object.entries(f).every(([k, c]) => {\n if (k === \"OR\") return (c as Record<string, unknown>[]).some((b) => rowMatchesFilter(caller, table, row, b));\n if (k === \"AND\") return (c as Record<string, unknown>[]).every((b) => rowMatchesFilter(caller, table, row, b));\n if (k === \"NOT\") return !rowMatchesFilter(caller, table, row, c as Record<string, unknown>);\n // `has` ilişki GRAFİĞİ ister ve sahte deponun grafiği YOK — tablolar bir\n // Map'te, aralarındaki yabancı anahtarlar hiçbir yerde. Sessizce yok saymak\n // filtreyi hiç uygulamamak olurdu: test TÜM satırları görür, üretim\n // süzülmüş satırları. Bu dosyanın var olma sebebi tam olarak o sınıf.\n if (k === \"has\") {\n throw new Error(\n `${caller}(${table}): fakeDatabase bir \\`has\\` filtresini çözemez — ilişki grafiği ` +\n `bildirimden türetiliyor ve sahte deponun bildirimi yok. Bu testi gerçek bir Postgres'e ` +\n `karşı yazın, ya da ilişkiyi filtrede AÇIKÇA kurun (önce ilişki tablosunu okuyup ` +\n `{ id: { in: [...] } } ile süzün).`,\n );\n }\n return matchesCell(caller, table, row, k, c);\n });\n}\n\n/**\n * SQL'in üç değerli mantığı: NULL taşıyan karşılaştırma UNKNOWN'dır, yani satır\n * EŞLEŞMEZ. Fake `===` kullanıyordu ve iki NULL kolonu EŞİT sayıyordu — motorun\n * her yerde uyguladığı FR-006 doktrininin tersi (inceleme I3, ölçüldü).\n */\nfunction cmp(a: unknown, b: unknown, op: string): boolean {\n if (a === null || a === undefined || b === null || b === undefined) return false;\n const l = a instanceof Date ? a.getTime() : a;\n const r = b instanceof Date ? b.getTime() : b;\n switch (op) {\n case \"eq\": return l === r;\n case \"neq\": return l !== r;\n case \"gt\": return (l as number) > (r as number);\n case \"gte\": return (l as number) >= (r as number);\n case \"lt\": return (l as number) < (r as number);\n case \"lte\": return (l as number) <= (r as number);\n default: return false;\n }\n}\n\nfunction matchesCell(\n caller: string,\n table: string,\n row: Record<string, unknown>,\n key: string,\n cond: unknown,\n): boolean {\n // Kolon-kolon karşılaştırma (FR-011) — motorla PARİTE. Fake `col()`'u\n // tanımasaydı `{ $col: \"x\" }` nesnesini DEĞER sanıp eşitlik kurar, hiçbir\n // satır dönmez ve yazarın testi sessizce boş sonuca geçerdi.\n if (isColRef(cond)) return cmp(row[key], row[cond.$col], \"eq\");\n // `now()` — motorla PARİTE. Tutamak bir Proxy, yani `Object.entries` BOŞ\n // döner ve `.every()` boş listede TRUE'dur: ayırt edilmezse koşul HER SATIRLA\n // eşleşirdi. Yani \"süresi geçmemişler\" filtresi testte süresi geçenleri de\n // döndürür, test yeşil kalır ve üretimde davranış AYRIŞIRDI.\n if (isNowExpr(cond)) return cmp(row[key], new Date().toISOString(), \"eq\");\n if (cond !== null && typeof cond === \"object\" && !Array.isArray(cond)) {\n return Object.entries(cond as Record<string, unknown>).every(([op, v]) => {\n const cell = row[key];\n if (isNowExpr(v)) {\n if (![\"neq\", \"gt\", \"gte\", \"lt\", \"lte\"].includes(op)) {\n throw new Error(`${caller}(${table}): where.${key}.${op} now() ile kullanılamaz`);\n }\n return cmp(cell, new Date().toISOString(), op);\n }\n if (isColumnExpr(v)) {\n throw new Error(\n `${caller}(${table}): where.${key}.${op} bir YAZMA ifadesi aldı (increment/decrement) — ` +\n `karşılaştırma değeri değil. Sunucu saati için now() kullanın.`,\n );\n }\n if (isColRef(v)) {\n if (![\"neq\", \"gt\", \"gte\", \"lt\", \"lte\"].includes(op)) {\n throw new Error(`${caller}(${table}): where.${key}.${op} col() ile kullanılamaz`);\n }\n return cmp(cell, row[v.$col], op);\n }\n switch (op) {\n case \"in\":\n if (!Array.isArray(v)) throw new Error(`${caller}(${table}): where.${key}.in bir dizi olmalı`);\n if (v.some(isColRef)) {\n throw new Error(\n `${caller}(${table}): where.${key}.in col() ile kullanılamaz — kolon karşılaştırması için gt/gte/lt/lte/neq kullanın`,\n );\n }\n return v.includes(cell);\n case \"neq\": case \"gt\": case \"gte\": case \"lt\": case \"lte\":\n return cmp(cell, v, op);\n // K1 metin operatörleri (FR-005) ve null testi (FR-006). Bunlar BURADA\n // da olmak zorunda: guard onları KABUL ettiği anda fake sessizce yanlış\n // cevap verir ve yazarın testi, üretimde farklı davranan koda karşı\n // yeşil verirdi (input-guards.ts'in uyardığı tam sınıf).\n case \"isNull\":\n if (typeof v !== \"boolean\") throw new Error(`${caller}(${table}): where.${key}.isNull bir boolean olmalı`);\n return v ? cell == null : cell != null;\n case \"contains\": case \"icontains\": case \"startsWith\": case \"endsWith\": {\n if (typeof v !== \"string\") throw new Error(`${caller}(${table}): where.${key}.${op} bir string olmalı`);\n if (typeof cell !== \"string\") return false;\n if (op === \"contains\") return cell.includes(v);\n if (op === \"icontains\") return cell.toLowerCase().includes(v.toLowerCase());\n if (op === \"startsWith\") return cell.startsWith(v);\n return cell.endsWith(v);\n }\n default:\n throw new Error(`${caller}(${table}): where.${key} bilinmeyen operatör \"${op}\"`);\n }\n });\n }\n return row[key] === cond;\n}\n\nexport interface MockDBClient extends DBClient {\n /** Get records inserted into a table. */\n inserted(table: string): Record<string, unknown>[];\n /** Get records updated in a table. */\n updated(table: string): Record<string, unknown>[];\n /** Get IDs deleted from a table. */\n deleted(table: string): string[];\n /** Pre-seed data into a table for findById/findMany. */\n seed(table: string, data: Record<string, unknown>[]): void;\n}\n\n/** Create a mock DB client with in-memory tracking. */\nexport function createMockDB(): MockDBClient {\n const store = new Map<string, Record<string, unknown>[]>();\n const tracked: TrackedRecords = {\n inserted: new Map(),\n updated: new Map(),\n deleted: new Map(),\n };\n\n function rowsOf(table: string): Record<string, unknown>[] {\n let rows = store.get(table);\n if (!rows) {\n rows = [];\n store.set(table, rows);\n }\n return rows;\n }\n\n function track(\n map: Map<string, Record<string, unknown>[]>,\n table: string,\n row: Record<string, unknown>,\n ): void {\n const list = map.get(table);\n if (list) list.push(row);\n else map.set(table, [row]);\n }\n\n/**\n * EKLEME yolunda değerleri motorun yaptığı gibi çöz — `now()` sunucu saati,\n * sayaç ifadesi adıyla ret.\n *\n * Fake bunu bilmeseydi `assertNoExpressionHandles` `now()`'ı reddeder, test\n * kırmızı olur ve yazar ÇALIŞAN bir çağrıyı bozuk sanırdı. Sürüm 28'de motor\n * beş ekleme kurucusunun hepsinde `now()` derliyor.\n */\nfunction resolveInsertValues(\n caller: string,\n table: string,\n data: Record<string, unknown>,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(data)) {\n const expr = columnExprOf(v);\n if (expr !== null && expr.fn === \"now\") {\n out[k] = new Date().toISOString();\n continue;\n }\n if (expr !== null) {\n throw new Error(\n `${caller}(${table}): \"${k}\" ${expr.fn === \"inc\" ? \"increment()\" : \"decrement()\"} aldı — ` +\n `satır HENÜZ YOK, yani \"kolonun şu anki değeri\" diye bir şey yok.`,\n );\n }\n out[k] = v;\n }\n return out;\n}\n\n // Build the op surface first (the six string-keyed ops). `txPlan` below\n // interprets a whole plan against the SAME in-memory store and tracking maps,\n // so a transaction's writes are visible to later assertions exactly as a\n // direct write would be.\n const ops: DBOps = {\n diagnostics: () => null,\n // The bulk ops and count run against the SAME in-memory store the direct\n // ops write to, so a test that writes three rows and counts them gets 3 —\n // a mock that answered 0 would make the surface look broken in exactly the\n // tests meant to prove it works.\n async updateMany(\n table: string,\n where: Record<string, unknown>,\n set: Record<string, unknown>,\n opts?: { returning?: boolean },\n ) {\n if (Object.keys(where).length === 0) throw new Error(`updateMany(${table}): boş filtre`);\n assertUsableFilter(\"updateMany\", table, where);\n refuseFragment(\"updateMany\", table, where);\n assertUsableWriteValues(\"updateMany\", table, Object.keys(set), set);\n const hit = (store.get(table) ?? []).filter((r) =>\n rowMatchesFilter(\"updateMany\", table, r, where),\n );\n // increment()/decrement() (FR-012) — motorla PARİTE. Fake ifadeyi DEĞER\n // sanıp yazsaydı, sayaç kolonu bir proxy nesnesine dönerdi ve yazarın\n // testi \"artış oldu\" diye değil, sessizce bozuk veriyle geçerdi.\n for (const row of hit) {\n for (const [k, v] of Object.entries(set)) {\n const expr = columnExprOf(v);\n if (expr !== null && expr.fn === \"now\") {\n // Motor `SET col = now()` derliyor; fake'in karşılığı bir zaman damgası.\n row[k] = new Date();\n continue;\n }\n if (expr !== null) {\n row[k] = addDecimal(row[k], expr.by as number | string, expr.fn === \"inc\" ? 1 : -1);\n continue;\n }\n row[k] = v;\n }\n }\n // HER YAZMA `updated()`'a DÜŞER. `update` ve tx-plan'ın update op'u zaten\n // kaydediyordu; `updateMany` kaydetmiyordu, yani defter YARI KÖRDÜ:\n // servisini `updateMany` ile yazan bir tüketici\n // `expect(fake.updated(\"accounts\")).toEqual([])` yazar ve yazma GERÇEKTEN\n // olduğu hâlde yeşil alırdı — FR-008'in aynadaki hâli.\n for (const row of hit) track(tracked.updated, table, row);\n\n // `returning: false` SAYI döndürür, dizi değil — motor gibi\n // (engine/db.ts) ve tipli yüzeyin daralttığı gibi (db/typed-db.ts).\n // Sahte daima dizi döndürdüğü sürece\n // const n = await db.updateMany(t, w, s, { returning: false });\n // if (n === 0) throw new Conflict(...)\n // guard'ı testte HİÇ çalışmaz ([] === 0 değil), üretimde çalışır: test\n // yeşil, canlıda 409. `update`→null ile aynı sınıf yalan.\n return opts?.returning === false ? hit.length : hit;\n },\n async deleteMany(table: string, where: Record<string, unknown>) {\n if (Object.keys(where).length === 0) throw new Error(`deleteMany(${table}): boş filtre`);\n assertUsableFilter(\"deleteMany\", table, where);\n refuseFragment(\"deleteMany\", table, where);\n const list = store.get(table) ?? [];\n const keep = list.filter((r) => !rowMatchesFilter(\"deleteMany\", table, r, where));\n store.set(table, keep);\n return list.length - keep.length;\n },\n async count(table: string, where: Record<string, unknown> = {}) {\n assertUsableFilter(\"count\", table, where);\n // `refuseFragment` burada ATLANMIŞTI: fragment'li count fake'te sessizce\n // 0 döndürüyordu, motor gerçek sayıyı (W2-B/C4).\n refuseFragment(\"count\", table, where);\n return (store.get(table) ?? []).filter((r) =>\n rowMatchesFilter(\"count\", table, r, where),\n ).length;\n },\n async search(_table: string, _params?: Record<string, unknown>) {\n return [];\n },\n async facets(_table: string, _params?: Record<string, unknown>) {\n return {};\n },\n async similar() {\n return [];\n },\n async recommend() {\n return [];\n },\n async supersede(_table: string, _id: string, row: Record<string, unknown>) {\n return { id: crypto.randomUUID(), ...row };\n },\n async query(_sql: string, _params?: unknown[]) {\n return [];\n },\n\n async insert(table: string, raw: Record<string, unknown>) {\n const data = resolveInsertValues(\"insert\", table, raw);\n assertUsableWriteValues(\"insert\", table, Object.keys(data), data);\n // Motorla PARİTE: ifade tutamağı bu yolda değer değildir. Fake onu\n // satıra YAZIYORDU; satır artık JSON'a bile çevrilemiyordu.\n assertNoExpressionHandles(\"insert\", table, Object.keys(data), data);\n const record = { id: crypto.randomUUID(), ...data };\n rowsOf(table).push(record);\n track(tracked.inserted, table, record);\n return record;\n },\n\n /**\n * `insertMany` — motorla PARİTE, ANAHTAR KÜMESİ kuralı dahil.\n *\n * Fake bu kuralı bilmeseydi farklı şekilli satırları kabul eder, test yeşil\n * kalır, üretimde motor adıyla reddederdi — yani fake, sürüm atlamayı\n * kolaylaştırmak yerine gizlerdi.\n */\n /**\n * `aggregate` — motorla PARİTE, PARA KESİNLİĞİ dahil.\n *\n * Fake toplamayı JS `number` ile yapsaydı test yeşil kalır ve üretimde\n * `numeric` kesinliği kaybolurdu — yani fake tam da korunması gereken şeyi\n * gizlerdi. `addDecimal` BigInt ölçekli toplama yapıyor, motorun\n * `sum(numeric)::text`'inin karşılığı.\n */\n async aggregate(table: string, q: Parameters<DBOps[\"aggregate\"]>[1]) {\n const rows = (store.get(table) ?? []).filter((r) =>\n q.where === undefined || rowMatchesFilter(\"aggregate\", table, r, q.where),\n );\n const groups = q.groupBy ?? [];\n const shape = (bucket: Record<string, unknown>[]): Record<string, unknown> => {\n const out: Record<string, unknown> = {};\n for (const c of q.sum ?? []) {\n const vals = bucket.map((r) => r[c]).filter((v) => v !== null && v !== undefined);\n ((out[\"sum\"] ??= {}) as Record<string, unknown>)[c] =\n vals.length === 0 ? null : String(vals.reduce<string | number>((a, v) => addDecimal(a, v as string | number, 1) as string, \"0\"));\n }\n for (const c of q.avg ?? []) {\n const vals = bucket.map((r) => r[c]).filter((v) => v !== null && v !== undefined);\n ((out[\"avg\"] ??= {}) as Record<string, unknown>)[c] =\n vals.length === 0\n ? null\n : String(Number(vals.reduce<string | number>((a, v) => addDecimal(a, v as string | number, 1) as string, \"0\")) / vals.length);\n }\n for (const [fn, pick] of [[\"min\", -1], [\"max\", 1]] as const) {\n for (const c of q[fn] ?? []) {\n const vals = bucket.map((r) => r[c]).filter((v) => v !== null && v !== undefined);\n ((out[fn] ??= {}) as Record<string, unknown>)[c] =\n vals.length === 0\n ? null\n : vals.reduce((a, v) => (cmp(v, a, pick === 1 ? \"gt\" : \"lt\") ? v : a));\n }\n }\n if (q.count === true) out[\"count\"] = bucket.length;\n return out;\n };\n if (groups.length === 0) return shape(rows);\n const byKey = new Map<string, Record<string, unknown>[]>();\n for (const r of rows) {\n const k = JSON.stringify(groups.map((c) => r[c]));\n byKey.set(k, [...(byKey.get(k) ?? []), r]);\n }\n return [...byKey.values()].map((bucket) => {\n const out = shape(bucket);\n for (const c of groups) out[c] = bucket[0]![c];\n return out;\n });\n },\n\n insertMany: (async function(table: string, rows: readonly Record<string, unknown>[], opts?: InsertManyOptions) {\n validateInsertManyOptions(opts);\n if (opts?.onConflict?.length) throw new Error(\"fakeDatabase insertMany cannot enforce PostgreSQL unique constraints; use an integration test for onConflict\");\n if (rows.length === 0) return opts?.returning === false ? 0 : [];\n const cols = Object.keys(rows[0]!);\n for (let i = 1; i < rows.length; i++) {\n const missing = cols.filter((c) => !(c in rows[i]!));\n const extra = Object.keys(rows[i]!).filter((k) => !cols.includes(k));\n if (missing.length > 0 || extra.length > 0) {\n throw new Error(\n `insertMany(${table}): ${i}. satırın kolonları ilk satırla aynı değil` +\n (missing.length > 0 ? ` (eksik: ${missing.join(\", \")})` : \"\") +\n (extra.length > 0 ? ` (fazla: ${extra.join(\", \")})` : \"\") +\n `. Eksikler için null yazın, ya da farklı şekilli satırları ayrı çağrılarda ekleyin.`,\n );\n }\n }\n const out: Record<string, unknown>[] = [];\n for (const rawRow of rows) {\n const data = resolveInsertValues(\"insertMany\", table, rawRow);\n assertUsableWriteValues(\"insertMany\", table, cols, data);\n assertNoExpressionHandles(\"insertMany\", table, cols, data);\n const record = { id: crypto.randomUUID(), ...data };\n rowsOf(table).push(record);\n track(tracked.inserted, table, record);\n out.push(record);\n }\n return opts?.returning === false ? out.length : out;\n }) as DBOps[\"insertMany\"],\n\n /**\n * `claim` — motorla PARİTE (FR-033).\n *\n * Fake bunu sunmasaydı `claim` ile yazılmış bir servis, iskelenin yazarlara\n * önerdiği test yolunda `undefined is not a function` verirdi; sunup da\n * FARKLI davransaydı (ör. hep `inserted: true`) idempotency testi üretimde\n * çalışmayan koda karşı yeşil olurdu.\n *\n * Anahtar ZATEN VARSA var olan satır dönüyor ve hiçbir şey yazılmıyor —\n * motorun 23505 dalının aynısı.\n */\n /**\n * `lockRows` — sahte depoda kilit YOKTUR, ama çağrı da patlamamalı.\n *\n * Motorla parite burada \"aynı SQL\" değil, \"aynı SÖZLEŞME\": boş liste\n * no-op, tekrar edenler tekilleşir, ve PK'sı olmayan tablo adıyla\n * reddedilir. Kilidin kendisi tek işlemli bir sahte depoda anlamsız —\n * ama sözleşmeyi bozan bir çağrı burada da hata almalı.\n */\n async lockRows(table: string, ids: readonly string[]) {\n if (ids.length === 0) return;\n const rows = store.get(table) ?? [];\n const unique = [...new Set(ids)].sort();\n const missing = unique.filter((id) => !rows.some((r) => r[\"id\"] === id));\n if (missing.length > 0 && rows.length > 0) {\n // Sessiz geçmek, testin \"kilitledim\" sanmasına yol açardı.\n throw new Error(\n `lockRows(${table}): şu id'ler yok: ${missing.join(\", \")} — kilitlenecek satır bulunamadı.`,\n );\n }\n },\n\n /**\n * `lockRowsWhere` — `lockRows` ile AYNI gerekçe, aynı parite seviyesi.\n *\n * Kilit tek işlemli bir sahte depoda anlamsız, ama motorun REDDETTİĞİ bir\n * çağrı burada da reddedilmeli: boş filtre (bütün tabloyu kilitlemek) ve\n * tanınmayan bir kilit modu. Fake bunları geçirseydi, yazarın testi\n * üretimde patlayan bir çağrıya karşı yeşil olurdu.\n */\n async lockRowsWhere(\n table: string,\n where: Record<string, unknown>,\n opts?: { mode?: \"update\" | \"share\" | \"noKeyUpdate\" },\n ) {\n const mode = opts?.mode ?? \"update\";\n if (mode !== \"update\" && mode !== \"share\" && mode !== \"noKeyUpdate\") {\n throw new Error(\n `lockRowsWhere(${table}): bilinmeyen mode \"${String(mode)}\" — \"update\", \"share\" ya da \"noKeyUpdate\".`,\n );\n }\n if (Object.keys(where).length === 0) throw new Error(`lockRowsWhere(${table}): boş filtre`);\n assertUsableFilter(\"lockRowsWhere\", table, where);\n refuseFragment(\"lockRowsWhere\", table, where);\n // Eşleşen satırlar OKUNUYOR: filtre fake'in kendi eşleştiricisinden\n // geçmezse (ör. tanınmayan operatör) çağıran bunu burada öğrenir.\n (store.get(table) ?? []).filter((r) => rowMatchesFilter(\"lockRowsWhere\", table, r, where));\n },\n\n /** Sahte depoda kilit yok; sözleşme (çağrı patlamaz) korunuyor. */\n async advisoryXactLock(_key: string) {\n return undefined;\n },\n\n async claim(\n table: string,\n unique: Record<string, unknown>,\n extra: Record<string, unknown> = {},\n ) {\n const keyCols = Object.keys(unique);\n if (keyCols.length === 0) {\n throw new Error(\n `claim(${table}): benzersiz alan verilmedi. claim, bir anahtarı sahiplenmektir; ` +\n `anahtar yoksa sahiplenecek bir şey de yok — insert(${table}, …) kullanın.`,\n );\n }\n assertUsableWriteValues(\"claim\", table, keyCols, unique);\n const existing = (store.get(table) ?? []).find((r) =>\n keyCols.every((c) => r[c] === unique[c]),\n );\n if (existing) return { inserted: false, row: existing };\n const data = resolveInsertValues(\"claim\", table, { ...unique, ...extra });\n assertUsableWriteValues(\"claim\", table, Object.keys(data), data);\n assertNoExpressionHandles(\"claim\", table, Object.keys(data), data);\n const record = { id: crypto.randomUUID(), ...data };\n rowsOf(table).push(record);\n track(tracked.inserted, table, record);\n return { inserted: true, row: record };\n },\n\n // Same semantics the engine's SQL has: match on the conflict columns, update\n // everything else, and return the resulting row either way.\n async put(\n table: string,\n rawData: Record<string, unknown>,\n opts: { onConflict: readonly string[] },\n ) {\n if (opts.onConflict.length === 0) {\n throw new Error(`put into ${table}: onConflict en az bir kolon adı ister`);\n }\n const data = resolveInsertValues(\"put\", table, rawData);\n assertUsableWriteValues(\"upsert\", table, Object.keys(data), data);\n // Motorla PARİTE: ifade tutamağı bu yolda değer değildir. Fake onu\n // satıra YAZIYORDU; satır artık JSON'a bile çevrilemiyordu.\n assertNoExpressionHandles(\"upsert\", table, Object.keys(data), data);\n const rows = rowsOf(table);\n const existing = rows.find((r) => opts.onConflict.every((c) => r[c] === data[c]));\n if (existing) {\n for (const [k, v] of Object.entries(data)) {\n if (!opts.onConflict.includes(k)) existing[k] = v;\n }\n return existing;\n }\n const record = { id: crypto.randomUUID(), ...data };\n rows.push(record);\n track(tracked.inserted, table, record);\n return record;\n },\n\n async update(table: string, id: string, data: Record<string, unknown>) {\n assertUsableWriteValues(\"update\", table, Object.keys(data), data);\n const rows = store.get(table) ?? [];\n const idx = rows.findIndex((r) => r[\"id\"] === id);\n // 28'de motor `update(id)` ile `updateMany`'nin SET kurucusunu PAYLAŞIYOR,\n // yani `now()` ve sayaç ifadeleri burada da geçerli. Fake eskisi gibi\n // reddetseydi, ÇALIŞAN bir çağrı testte kırmızı olurdu — fake'in var olma\n // amacının tam tersi.\n const current = idx >= 0 ? rows[idx]! : {};\n const applied: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(data)) {\n const expr = columnExprOf(v);\n if (expr !== null && expr.fn === \"now\") {\n applied[k] = new Date();\n continue;\n }\n if (expr !== null) {\n applied[k] = addDecimal(current[k], expr.by, expr.fn === \"inc\" ? 1 : -1);\n continue;\n }\n applied[k] = v;\n }\n assertNoExpressionHandles(\"update\", table, Object.keys(applied), applied);\n // 0 SATIR → NULL, motorun KENDİSİ gibi (engine/db.ts:\n // `rows[0] ? asTableRow(table, rows[0]) : null`).\n //\n // Eskiden eşleşme yokken `{ id, ...applied }` UYDURULUYOR ve o uydurma\n // satır `updated()`'a da yazılıyordu. İki sonucu vardı: eşleşmeyen bir\n // update'i test eden kod SESSİZCE geçiyor ama üretimde `null` alıp\n // patlıyordu; ve \"0 satır → null\" sözleşmesi bu harness'la hiç\n // doğrulanamıyordu — bir tüketici projesi iddiayı yazamayıp yorum olarak\n // bırakmak zorunda kaldı (FR-007, FR-008).\n if (idx < 0) return null;\n const updated = { ...rows[idx], ...applied };\n rows[idx] = updated;\n track(tracked.updated, table, updated);\n return updated;\n },\n\n async delete(table: string, id: string) {\n const rows = store.get(table) ?? [];\n const idx = rows.findIndex((r) => r[\"id\"] === id);\n // EŞLEŞME YOKSA DEFTERE YAZILMAZ — `update` ile aynı kural (FR-008).\n // Eskiden eşleşmeyen bir `delete` de `deleted()`'a düşüyordu: silme\n // GERÇEKLEŞMEDİĞİ hâlde `expect(fake.deleted(\"x\")).toEqual([\"yok\"])`\n // yeşil oluyordu, yani defter olmayan bir yazmayı rapor ediyordu.\n if (idx < 0) return;\n rows.splice(idx, 1);\n const list = tracked.deleted.get(table);\n if (list) list.push(id);\n else tracked.deleted.set(table, [id]);\n },\n\n async findUnique() {\n throw new Error(\"MockDB.findUnique cannot verify declared PostgreSQL unique constraints; use a PostgreSQL integration test\");\n },\n async findById(table: string, id: string) {\n const rows = store.get(table) ?? [];\n return rows.find((r) => r[\"id\"] === id) ?? null;\n },\n\n // The SAME filter language the engine compiles to SQL: a plain value is\n // equality, an object is an operator set. A fake that understood less would\n // pass a service test that the live database then fails — which is the one\n // thing a stand-in must never do.\n async page() {\n throw new Error(\"fakeDatabase cannot reproduce PostgreSQL cursor ordering, collations or RLS; use a PostgreSQL integration test or inject an explicit page response\");\n },\n async findMany(\n table: string,\n query?: Record<string, unknown>,\n opts?: {\n orderBy?:\n | { column: string; direction?: \"asc\" | \"desc\"; nulls?: \"first\" | \"last\" }\n | { column: string; direction?: \"asc\" | \"desc\"; nulls?: \"first\" | \"last\" }[];\n select?: string[];\n with?: Record<string, unknown>;\n limit?: number;\n offset?: number;\n },\n ) {\n assertUsableFilter(\"findMany\", table, query);\n refuseFragment(\"findMany\", table, query);\n const { limit, offset } = opts ?? {};\n if (limit !== undefined && (!Number.isInteger(limit) || limit < 0)) {\n throw new Error(`findMany: limit bir negatif olmayan tam sayı olmalı (geldi: ${String(limit)})`);\n }\n if (offset !== undefined) {\n if (!Number.isInteger(offset) || offset < 0) {\n throw new Error(`findMany: offset bir negatif olmayan tam sayı olmalı (geldi: ${String(offset)})`);\n }\n if (limit === undefined) {\n throw new Error(\n \"findMany: offset yalnız limit ile birlikte verilir — limitsiz offset bir sayfa değil, sınırsız bir kuyruğun kaydırılmışıdır\",\n );\n }\n }\n // `with` — fake'in ilişki grafiği YOK, ve olsaydı ikinci bir yorumcu\n // olurdu (motorunki `buildRelations`'tan geliyor). Sessizce YOK SAYMAK\n // en kötüsü olurdu: yazar `rows[0].orders` yazar, `undefined` gelir ve\n // test motorun döndürdüğünden BAŞKA bir şeyi doğrular.\n if (opts?.with !== undefined && Object.keys(opts.with).length > 0) {\n throw new Error(\n `findMany(${table}): fakeDatabase \\`with\\` desteklemiyor — ilişki grafiği ` +\n `yabancı anahtarlardan TÜRETİLİYOR ve fake şemayı okumuyor. İlişkili ` +\n `satırları ölçen bir test gerçek motoru kullanmalı; fake ile ölçmek ` +\n `istiyorsanız ilgili satırları \\`seed\\` ile ayrı koyup ayrı sorgulayın.`,\n );\n }\n const rows = store.get(table) ?? [];\n let out = query\n ? rows.filter((row) => rowMatchesFilter(\"findMany\", table, row, query))\n : [...rows];\n // Çoklu sıralama ve NULL yeri — motorla PARİTE (FR-008). Tek obje de\n // kabul edilir; liste hâline getirilip aynı yoldan geçer.\n const orderSpecs = opts?.orderBy === undefined\n ? []\n : Array.isArray(opts.orderBy) ? opts.orderBy : [opts.orderBy];\n if (orderSpecs.length > 0) {\n out = [...out].sort((a, b) => {\n for (const o of orderSpecs) {\n const dir = o.direction === \"desc\" ? -1 : 1;\n const x = a[o.column];\n const y = b[o.column];\n const xNull = x === null || x === undefined;\n const yNull = y === null || y === undefined;\n if (xNull || yNull) {\n if (xNull && yNull) continue;\n // Verilmezse Postgres varsayılanı: ASC'de NULLS LAST, DESC'te FIRST.\n const nullsFirst = o.nulls === undefined ? dir === -1 : o.nulls === \"first\";\n return (xNull ? 1 : -1) * (nullsFirst ? -1 : 1);\n }\n if (x === y) continue;\n return ((x as never) < (y as never) ? -1 : 1) * dir;\n }\n return 0;\n });\n }\n const start = offset ?? 0;\n const page = limit === undefined ? out : out.slice(start, start + limit);\n // Projeksiyon (FR-009) — motorla PARİTE. Fake tam satır döndürürse, `select`\n // ile yazılmış bir kod sahte veritabanında seçilmemiş kolonu okur ve GEÇER;\n // gerçek motorda o kolon SQL'e hiç girmediği için `undefined` olur.\n const cols = opts?.select;\n if (cols === undefined || cols.length === 0) return page;\n return page.map((row) => Object.fromEntries(cols.map((c) => [c, row[c]])));\n },\n };\n\n /**\n * Interpret a whole plan, atomically.\n *\n * The rollback is the point. A test that asserts \"the second write failed, so\n * the first one is not there\" must be able to FAIL — a mock that applied ops\n * and left them applied would pass that test while the real broker rolled the\n * transaction back, or the other way round. So the store and the tracking maps\n * are snapshotted, and any failure restores both before rejecting.\n *\n * The rejection carries the same envelope fields the runtime copies off the\n * broker's response (`error_code`, `slot`), because the SDK maps `slot` back\n * to the caller's own Error — a mock that rejected with a bare Error would\n * make every guard in every tenant test look like a generic failure.\n */\n async function txPlan(plan: TxPlanBody): Promise<TxPlanResponse> {\n const snapshot = new Map<string, Record<string, unknown>[]>();\n for (const [table, rows] of store) snapshot.set(table, [...rows]);\n const trackedSnapshot: TrackedRecords = {\n inserted: cloneTracked(tracked.inserted),\n updated: cloneTracked(tracked.updated),\n deleted: new Map([...tracked.deleted].map(([k, v]) => [k, [...v]])),\n };\n\n const results: TxPlanOpResult[] = [];\n try {\n for (const op of plan.ops) {\n const result = applyOp(op, results);\n results.push(result);\n const failure = guardFailure(op.guard, result.rows.length);\n if (failure) throw failure;\n }\n } catch (err) {\n store.clear();\n for (const [table, rows] of snapshot) store.set(table, rows);\n tracked.inserted = trackedSnapshot.inserted;\n tracked.updated = trackedSnapshot.updated;\n tracked.deleted = trackedSnapshot.deleted;\n throw err;\n }\n return { results };\n }\n\n function applyOp(op: TxWireOp, results: TxPlanOpResult[]): TxPlanOpResult {\n switch (op.op) {\n case \"upsert\": {\n const values = resolveMap(op.values ?? {}, results, null);\n const conflict = op.onConflict ?? [];\n const rows = rowsOf(op.table);\n const hit = rows.find((r) => conflict.every((c) => r[c] === values[c]));\n if (hit) {\n for (const [key, value] of Object.entries(values)) {\n if (!conflict.includes(key)) hit[key] = value;\n }\n return { rows: [hit], rows_affected: 1 };\n }\n const created = { id: crypto.randomUUID(), ...values };\n rows.push(created);\n track(tracked.inserted, op.table, created);\n return { rows: [created], rows_affected: 1 };\n }\n case \"insert\": {\n const record = { id: crypto.randomUUID(), ...resolveMap(op.values ?? {}, results, null) };\n rowsOf(op.table).push(record);\n track(tracked.inserted, op.table, record);\n return { rows: [record], rows_affected: 1 };\n }\n case \"insertMany\": {\n const written = (op.rows ?? []).map((row) => {\n const record = { id: crypto.randomUUID(), ...resolveMap(row, results, null) };\n rowsOf(op.table).push(record);\n track(tracked.inserted, op.table, record);\n return record;\n });\n return { rows: written, rows_affected: written.length };\n }\n case \"update\": {\n const rows = rowsOf(op.table);\n const where = resolveMap(op.where ?? {}, results, null);\n const written: Record<string, unknown>[] = [];\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n if (!row || !matches(row, where)) continue;\n const next = { ...row, ...resolveMap(op.set ?? {}, results, row) };\n rows[i] = next;\n track(tracked.updated, op.table, next);\n written.push(next);\n }\n return { rows: written, rows_affected: written.length };\n }\n case \"delete\": {\n const rows = rowsOf(op.table);\n const where = resolveMap(op.where ?? {}, results, null);\n const removed = rows.filter((row) => matches(row, where));\n for (const row of removed) {\n rows.splice(rows.indexOf(row), 1);\n const id = row[\"id\"];\n const list = tracked.deleted.get(op.table);\n const key = typeof id === \"string\" ? id : String(id);\n if (list) list.push(key);\n else tracked.deleted.set(op.table, [key]);\n }\n return { rows: removed, rows_affected: removed.length };\n }\n case \"select\": {\n const where = resolveMap(op.where ?? {}, results, null);\n let found = rowsOf(op.table).filter((row) => matches(row, where));\n if (op.limit !== undefined) found = found.slice(0, op.limit);\n return { rows: found, rows_affected: found.length };\n }\n }\n }\n\n const client: MockDBClient = {\n ...ops,\n async command(plan, options) {\n if (options?.mode === \"compiled\") throw new Error(\"fakeDatabase does not run the PostgreSQL command executor; verify compiled mode against PostgreSQL\");\n return client.txPlan(plan);\n },\n\n async atomic() {\n throw new Error(\"fakeDatabase cannot verify physical transaction isolation, COMMIT or retry; test $atomic against PostgreSQL or inject a transaction test double explicitly\");\n },\n\n // No real savepoint in memory: the fake runs the callback against the SAME\n // store. An assertion about rollback here would be asserting the fake.\n attempt: <T,>(fn: (tx: DBOps) => Promise<T>): Promise<T> => fn(ops),\n\n txPlan,\n\n // In tests there is no real DB role; `asService()` returns the same\n // in-memory client so RLS-bypass code paths still hit the same store and\n // tracking maps. The omitted `asService` matches the contract (no\n // double-bypass), so callers can't recurse.\n asService(): Omit<DBClient, \"asService\"> {\n return client;\n },\n\n inserted(table: string) {\n return tracked.inserted.get(table) ?? [];\n },\n\n updated(table: string) {\n return tracked.updated.get(table) ?? [];\n },\n\n deleted(table: string) {\n return tracked.deleted.get(table) ?? [];\n },\n\n seed(table: string, data: Record<string, unknown>[]) {\n store.set(table, [...data]);\n },\n };\n\n return client;\n}\n\nfunction cloneTracked(\n map: Map<string, Record<string, unknown>[]>,\n): Map<string, Record<string, unknown>[]> {\n return new Map([...map].map(([k, v]) => [k, [...v]]));\n}\n\n/** Resolve one plan value: a `$ref` into an earlier result, a `$expr`, or a\n * literal. `current` is the row being updated, which is what `inc`/`dec` read. */\nfunction resolveValue(\n value: TxWireValue,\n results: TxPlanOpResult[],\n current: Record<string, unknown> | null,\n column: string,\n): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n const tagged = value as { $ref?: { op: number; field: string }; $expr?: Record<string, unknown> };\n\n if (tagged.$ref) {\n const row = results[tagged.$ref.op]?.rows[0];\n if (!row) {\n throw txRejection(409, \"tx_ref_unresolved\", {\n message: `operation ${tagged.$ref.op} produced no row to reference`,\n });\n }\n return row[tagged.$ref.field];\n }\n\n if (tagged.$expr) {\n const fn = tagged.$expr[\"fn\"];\n if (fn === \"now\") return new Date().toISOString();\n const by = Number(tagged.$expr[\"by\"]);\n const base = Number(current?.[column] ?? 0);\n return fn === \"dec\" ? base - by : base + by;\n }\n\n return value;\n}\n\nfunction resolveMap(\n map: Record<string, TxWireValue>,\n results: TxPlanOpResult[],\n current: Record<string, unknown> | null,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(map)) {\n out[key] = resolveValue(value, results, current, key);\n }\n return out;\n}\n\n/** Equality filter, with `null` meaning IS NULL — the broker's rule, so a\n * `{ accepted_at: null }` guard behaves the same in a test as in production. */\nfunction matches(row: Record<string, unknown>, where: Record<string, unknown>): boolean {\n return Object.entries(where).every(([key, value]) =>\n value === null ? row[key] === null || row[key] === undefined : row[key] === value,\n );\n}\n\nfunction guardFailure(guard: TxWireGuard | undefined, count: number): unknown {\n if (!guard) return null;\n const ok =\n guard.kind === \"one\"\n ? count === 1\n : guard.kind === \"none\"\n ? count === 0\n : guard.kind === \"atLeast\"\n ? count >= guard.n\n : count <= guard.n;\n if (ok) return null;\n return txRejection(409, \"tx_guard_failed\", {\n slot: guard.slot,\n message: `expected ${guard.kind} ${guard.n} row(s), got ${count}`,\n });\n}\n\n/** Build a rejection shaped like the one the runtime throws for a broker error:\n * an Error carrying the envelope's `status`/`error_code`/`slot`. */\nfunction txRejection(\n status: number,\n code: string,\n extra: { slot?: number; message: string },\n): Error & TxPlanRejection {\n const err = new Error(extra.message) as Error & TxPlanRejection;\n err.status = status;\n err.error_code = code;\n if (extra.slot !== undefined) err.slot = extra.slot;\n return err;\n}\n","/**\n * runtime.ts — request-scoped service singletons.\n *\n * The backend SDK no longer threads a `ctx` god-object through every handler.\n * Instead, controller methods import PascalCase service singletons directly:\n *\n * import { Controller, Post, Body, Database } from \"@palbase/backend\";\n *\n * \\@Controller(\"/todos\")\n * export default class TodosController {\n * \\@Post(\"\") create(\\@Body(CreateTodoBody) body: CreateTodoBody): unknown {\n * return Database.public.todos.insert({ title: body.title });\n * }\n * }\n *\n * The singletons are thin Proxies. Every property access forwards to the live\n * client for the CURRENT request scope, resolved through {@link __getRuntime}.\n *\n * # Request-scope resolution (persistent app-server)\n *\n * The runtime is a long-running Node process that serves many concurrent\n * requests on one event loop (NOT a fresh subprocess per request). A single\n * module-global slot would let one in-flight request's services bleed into\n * another's. So the services are carried in an {@link AsyncLocalStorage} store\n * ({@link __requestALS}) that the runtime sets per request with\n * {@link __runWithRuntime}; every async continuation of that request reads its\n * own store. `__getRuntime` reads the ALS store first; the module-global slot\n * (set by {@link __setRuntime}) is only a fallback for callers that run OUTSIDE\n * an ALS scope (dev-server, unit tests, the legacy single-shot path). Because\n * each `br-<ref>` pod is single-tenant, there is no cross-tenant leakage; the\n * ALS store is what prevents cross-REQUEST leakage within the shared process.\n *\n * The seam that makes `import { Database } from \"@palbase/backend\"` resolve to\n * the runtime-injected client: `@palbase/backend` is marked esbuild-EXTERNAL\n * when the tenant bundle is built, and the package is installed globally in the\n * pod (NODE_PATH=/usr/local/lib/node_modules). So worker.js's\n * `require('@palbase/backend')` and the bundle's `import` resolve to ONE shared\n * module instance — the ALS store and `__setRuntime` slot on that instance are\n * visible to the singletons the bundle imported.\n */\n\nimport type { PalbaseFlagKey } from \"./stack.js\";\nimport type { Buckets, BucketTypes, Schemas } from \"./db/env.js\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type {\n DBClient,\n AtomicClient,\n DBOps,\n CacheClient,\n Logger,\n PalbaseDocsClient,\n SecretsService,\n} from \"./endpoint.js\";\nimport type {\n PalbaseAuthAdminClient,\n PalbaseStorageClient,\n PalbaseBucketClient,\n PalbaseNotificationsClient,\n PalbaseFlagsClient,\n PalbaseFlagsServiceClient,\n PalbaseFlagContext,\n PalbaseFlagVariant,\n PalbaseFlag,\n PalbaseFlagValue,\n PalbaseSetOverrideResult,\n PalbaseRealtimeClient,\n} from \"./clients.js\";\nimport type { PalbaseResult } from \"./endpoint.js\";\nimport type {\n EnvTypedDatabase,\n EnvServiceDatabase,\n AtomicDatabase,\n EnvTables,\n TxPlan,\n TxTables,\n} from \"./db/typed-db.js\";\nimport type { Materialized } from \"./db/tx-plan.js\";\nimport { TxPlanBuilder, runTxPlan } from \"./db/tx-plan.js\";\nimport { assertPlanRetry, type AtomicOptions } from \"./db/transaction-options.js\";\nimport { qualifiedTableKey } from \"./db/schema-json.js\";\nimport type { DollarOps } from \"./db/typed-db.js\";\n\n/** The set of live clients the runtime injects per request scope.\n *\n * Realtime is BROADCAST-ONLY here (a stateless handler can push an event but\n * cannot hold a subscription socket — `subscribe()` lives on the client SDK).\n *\n * EXCLUDED on purpose: Functions, Links, Analytics. They are not exposed as\n * backend handler singletons — out of scope for backend endpoints. `Auth` is\n * here in its ROLE-ASSIGNMENT shape only: signing in is the client SDK's job,\n * but granting a role is an operator verb the tenant's own handler needs\n * (FR-009). */\nexport interface RuntimeServices {\n Database: DBClient;\n Auth: PalbaseAuthAdminClient;\n Secrets: SecretsService;\n Documents: PalbaseDocsClient;\n Storage: PalbaseStorageClient;\n Cache: CacheClient;\n Log: Logger;\n Notifications: PalbaseNotificationsClient;\n Flags: PalbaseFlagsClient;\n Realtime: PalbaseRealtimeClient;\n}\n\n/**\n * The per-request ALS box.\n *\n * `runtime` is the service bundle. `userId` is the request's authenticated user\n * id, written by the runtime immediately after it assembles the request object\n * (worker.js: `requestALS.getStore().userId = pbReq.user?.id || null`) and\n * `null` on an anonymous request. It was already being written there for the\n * Flags client's auto-bind; declaring it here makes the existing contract typed\n * instead of implicit, which is what lets `currentSubjectId()` read a\n * server-owned identity rather than trusting anything the caller sent.\n */\nexport interface RequestStore {\n runtime: RuntimeServices;\n userId?: string | null;\n /** This request's id (`req_…`), written by the runtime. Used as the spend\n * idempotency scope when the caller supplied no `Idempotency-Key`. */\n requestId?: string;\n /** The caller's `Idempotency-Key` header, or `null` when absent. What makes a\n * client's retry replay its first result instead of charging twice. */\n idempotencyKey?: string | null;\n}\n\n/**\n * Per-request store. The persistent runtime runs each request inside\n * {@link __runWithRuntime}, so every async continuation of that request reads\n * its OWN `runtime` (and any other request-scoped fields the runtime adds).\n *\n * Exported with a `__` prefix so the runtime (worker.js) shares the SAME ALS\n * instance across the one module instance — two ALS instances would silently\n * not see each other's stores. NOT part of the public author-facing API.\n */\n/**\n * The per-request store — ON globalThis under a well-known Symbol, for the same\n * reason `lifecycleHooks` and the controller registry are.\n *\n * MEASURED, through the production package gate: `tsup` emits `dist/index.cjs`\n * and `dist/test/index.cjs` as SEPARATE bundles and each inlines this module.\n * With a module-local `AsyncLocalStorage`, `withServices` (which ships from the\n * `/test` subpath) opened a scope in ITS copy while the `Database` singleton\n * (which ships from the root) read the OTHER copy's — and the ambient service a\n * test had just installed was invisible:\n *\n * Error: Palbase services accessed outside a request scope.\n *\n * The unit tests could not see it: inside the package there is only ever one\n * copy. It took calling the built artifact the way a consumer does. Same class\n * as the defect `@Module`'s slot comment describes — two module-local values\n * where the two halves of one contract must agree.\n *\n * SÜRÜMSÜZ, VE BU BİLİNÇLİ. Anahtar `…requestALS@32` gibi sürümlenseydi iki\n * major aynı süreçte ALS'i paylaşmayı BIRAKIRDI — yani yukarıda anlatılan kusur\n * sürüm sınırında geri gelirdi. Bedeli de gerçek ve burada yazılı:\n * `RequestStore.runtime` zorunlu bir `RuntimeServices` ve o küme büyüyor\n * (30.0.0 `Auth` ile 9→10). Eski bir majorün yazdığı kutuyu yeni bir major\n * okursa yeni alan `undefined` gelir.\n *\n * Bu pakette YEDİ well-known Symbol var ve hepsi sürümsüz (`httpError`,\n * `engineRaised`, `channels`, `errorRegistry`, `declarationRefusal`,\n * `lifecycleHooks`, ve bu). Yalnız BİRİNİ sürümlemek tutarsızlıktan başka bir\n * şey üretmez: karar paket geneli olmalı ve `RequestStore`'un şekil\n * sözleşmesiyle birlikte alınmalı (sapma defteri D-05).\n */\nconst REQUEST_ALS: unique symbol = Symbol.for(\"palbase.backend.requestALS\") as never;\n\nexport const __requestALS: AsyncLocalStorage<RequestStore> = ((): AsyncLocalStorage<RequestStore> => {\n const g = globalThis as unknown as Record<symbol, AsyncLocalStorage<RequestStore> | undefined>;\n return (g[REQUEST_ALS] ??= new AsyncLocalStorage<RequestStore>());\n})();\n\n/** Process-global fallback slot. Used only OUTSIDE an ALS scope (dev-server,\n * unit tests, legacy single-shot worker). Inside the persistent server every\n * request runs in {@link __requestALS}, which takes precedence. */\nlet runtime: RuntimeServices | null = null;\n\n/** Install the live clients in the process-global fallback slot.\n *\n * Persistent-server requests should use {@link __runWithRuntime} instead; this\n * remains for dev-server / tests / the legacy single-shot path that run without\n * an ALS scope. NOT part of the public author-facing API. */\nexport function __setRuntime(services: RuntimeServices): void {\n runtime = services;\n}\n\n/** Run `fn` with `services` bound as the request-scoped runtime.\n *\n * The persistent worker calls this once per request so concurrent requests\n * never share a services slot. NOT part of the public author-facing API. */\nexport function __runWithRuntime<T>(services: RuntimeServices, fn: () => T): T {\n return __requestALS.run({ runtime: services }, fn);\n}\n\n/** Read the live clients, throwing if accessed outside a request scope.\n *\n * Resolves the ALS store first (persistent server, per-request), then the\n * process-global fallback (dev-server / tests). NOT part of the public\n * author-facing API — used by the runtime and the singleton Proxies. */\n/**\n * Bir kutunun TAŞIMASI GEREKEN servisler.\n *\n * `withServices`'in listesiyle aynı gerçeği söylüyor ama BURADA yaşamak\n * zorunda: `test/` yalnız test yüzeyinde, bu kontrol ise her isteğin yolunda.\n * İkisi de `satisfies` ile `RuntimeServices`'a pinli, yani biri eksik kalırsa\n * derleme durur.\n */\nconst REQUIRED_SERVICES = [\n \"Database\",\n \"Auth\",\n \"Secrets\",\n \"Documents\",\n \"Storage\",\n \"Cache\",\n \"Log\",\n \"Notifications\",\n \"Flags\",\n \"Realtime\",\n] as const satisfies readonly (keyof RuntimeServices)[];\n\n/**\n * ÇAPRAZ-MAJOR KUTUYU ADIYLA REDDET (sapma defteri D-05).\n *\n * `__requestALS` sürümSÜZ bir `Symbol.for` altında ve bu bilinçli: iki bundle\n * (`dist/index.cjs` ve `dist/test/index.cjs`) ambient kapsamı ancak öyle\n * paylaşır. Bedeli de gerçek — tek süreçte iki major varsa ESKİ olanın yazdığı\n * kutuyu YENİ olan okur, ve servis kümesi büyümüşse (30.0.0'da 9→10, `Auth`)\n * yeni alan `undefined` gelir.\n *\n * `undefined` bir servis, erişildiğinde `Reflect.get called on non-object`\n * verir: ne eksik olanın adı, ne sebebi. Bu kontrol o sessizliği bir cümleye\n * çevirir. Maliyeti istek başına on `in` kontrolü.\n */\nfunction refuseIncompleteBox(services: RuntimeServices): RuntimeServices {\n const missing = REQUIRED_SERVICES.filter((k) => services[k] === undefined);\n if (missing.length > 0) {\n throw new Error(\n `the request scope is missing ${missing.join(\", \")} — this box was most likely written by a ` +\n `DIFFERENT @palbase/backend major sharing the same process (the request store is a ` +\n `process-wide well-known Symbol, deliberately, so two bundles of ONE version can share it). ` +\n `Align the versions, or pass every service when building the scope yourself.`,\n );\n }\n return services;\n}\n\nexport function __getRuntime(): RuntimeServices {\n const scoped = __requestALS.getStore();\n if (scoped) return refuseIncompleteBox(scoped.runtime);\n if (runtime === null) {\n throw new Error(\n \"Palbase services accessed outside a request scope. The Database/Documents/… \" +\n \"singletons are only available inside an endpoint handler (or after the \" +\n \"runtime has called __runWithRuntime / __setRuntime).\",\n );\n }\n return runtime;\n}\n\n// ─── lifecycle: where a long-lived resource lives (FR-013) ─────────────────\n//\n// `Resource` was removed in 23.0.0 and nothing replaced the LIFECYCLE half of\n// it. What that left behind is measurable: a connection pool (the driver in\n// `docs/resources.md`'s own example was Neo4j) had no documented place to be\n// opened and NO WAY AT ALL to be closed, so every deploy left the pool it\n// opened behind. These two hooks are that half — and only that half. The\n// secret-distribution half does not come back: a handler reads `Secrets.get`,\n// and a start hook, which runs before any request scope exists, reads the\n// `process.env` the runtime mirrors the vault into at boot.\n\n/** A lifecycle hook. Sync or async; the runtime awaits what it returns. */\nexport type LifecycleHook = () => void | Promise<void>;\n\n/** Runs one release's shutdown hooks. Handed back by {@link __runStartHooks}\n * and called by the engine's `app.shutdown()`. Idempotent. */\nexport type ShutdownRunner = () => Promise<void>;\n\ninterface DeclaredHook {\n name: string;\n run: LifecycleHook;\n}\n\ninterface DeclaredLifecycle {\n start: DeclaredHook[];\n shutdown: DeclaredHook[];\n}\n\n/**\n * What has been DECLARED and not yet claimed by an app.\n *\n * On globalThis under a well-known Symbol for the reason the controller\n * registry is (`decorators/controller.ts`): a deployed bundle inlines its own\n * copy of this package, and the engine that has to RUN these hooks holds the\n * other copy. Two module-local arrays would mean the engine reads the empty one\n * and every declared hook is silently never run — which is exactly how\n * `Resource`'s `init(env)` died.\n */\nconst LIFECYCLE: unique symbol = Symbol.for(\"palbase.backend.lifecycleHooks\") as never;\n\nfunction declaredLifecycle(): DeclaredLifecycle {\n const g = globalThis as unknown as Record<symbol, DeclaredLifecycle | undefined>;\n return (g[LIFECYCLE] ??= { start: [], shutdown: [] });\n}\n\n/**\n * Run `hook` ONCE while the application comes up, before it serves anything.\n *\n * Call it at MODULE SCOPE in a file the application imports — the same rule\n * `defineDefaultAuth` and `@Controller` follow, and for the same reason: the\n * declaration is claimed when the app boots, which is after module loading and\n * before the first request. `name` is not decoration: a hook that throws is\n * reported by that name and the boot is REFUSED, so it is what tells an\n * operator which resource did not come up.\n *\n * There is no request scope yet, so the `Database`/`Secrets`/… singletons are\n * NOT available inside a start hook. A secret is read from `process.env` here\n * (the runtime mirrors the vault into it at boot).\n *\n * @example\n * // resources/graph.ts\n * import neo4j from \"neo4j-driver\";\n * import { onStart, onShutdown } from \"@palbase/backend\";\n *\n * export let graph: Driver;\n * onStart(\"graph\", () => {\n * graph = neo4j.driver(process.env.NEO4J_URL!, neo4j.auth.basic(\"neo4j\", process.env.NEO4J_PASSWORD!));\n * });\n * onShutdown(\"graph\", () => graph.close());\n */\nexport function onStart(name: string, hook: LifecycleHook): void {\n declaredLifecycle().start.push({ name, run: hook });\n}\n\n/**\n * Run `hook` while the application shuts down — the place a pool opened in\n * {@link onStart} is closed.\n *\n * Shutdown is BEST-EFFORT by design: a hook that throws is reported by name and\n * the rest still run. A drain that abandoned the remaining hooks on the first\n * failure would leak exactly what this exists to release, and the process is\n * leaving anyway.\n *\n * Hooks run in REVERSE declaration order, so a resource is released before what\n * it was built on.\n */\nexport function onShutdown(name: string, hook: LifecycleHook): void {\n declaredLifecycle().shutdown.push({ name, run: hook });\n}\n\nfunction reason(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/** Best-effort drain: every hook runs, a failure is reported, none is silent. */\nasync function drain(hooks: DeclaredHook[]): Promise<void> {\n for (const h of [...hooks].reverse()) {\n try {\n await h.run();\n } catch (err) {\n console.error(`[palbase] shutdown hook \"${h.name}\" failed: ${reason(err)}`, err);\n }\n }\n}\n\n/**\n * CLAIM what has been declared, run the start hooks, and hand back the runner\n * for this release's shutdown hooks. Called by the engine's `createApp`; the\n * `App.shutdown()` it builds calls what comes back. NOT part of the public\n * author-facing API.\n *\n * IT CLAIMS RATHER THAN READS, which is what makes it correct in this runtime:\n * a candidate release is loaded BESIDE the live one in one process\n * (`v2/runtime/src/registry-scope.ts`), and both bundles append to the one\n * shared slot above. If each app read the whole list, the live app's shutdown\n * would close the candidate's pool and the candidate's would close the live\n * app's. Taking the declarations leaves each app holding exactly its own.\n *\n * A start hook that throws REFUSES THE BOOT — with the hook's name in the\n * message — after releasing whatever the earlier hooks already opened. Serving\n * from a half-initialised app is the silence this whole surface replaces, and a\n * boot that dies holding an open pool is the leak it replaces.\n */\nexport async function __runStartHooks(): Promise<ShutdownRunner> {\n const slot = declaredLifecycle();\n const start = slot.start.splice(0);\n const shutdown = slot.shutdown.splice(0);\n\n for (const h of start) {\n try {\n await h.run();\n } catch (err) {\n await drain(shutdown);\n throw new Error(`[palbase] start hook \"${h.name}\" failed: ${reason(err)}`, { cause: err });\n }\n }\n\n let drained = false;\n return async () => {\n // SIGTERM racing a redeploy asks twice; a pool is closed once.\n if (drained) return;\n drained = true;\n await drain(shutdown);\n };\n}\n\n/** Drop every declaration. For tests, which declare repeatedly in one process.\n * NOT part of the public author-facing API. */\nexport function __resetLifecycleHooks(): void {\n const g = globalThis as unknown as Record<symbol, DeclaredLifecycle | undefined>;\n delete g[LIFECYCLE];\n}\n\n/**\n * Build a Proxy singleton that forwards every property access to the live\n * client named `key` on the current runtime.\n *\n * The single `as RuntimeServices[K]` is the only contained cast in the surface:\n * `Reflect.get` on a typed object returns `unknown` for a `string | symbol`\n * key, but `prop` is constrained to keys of the client interface at the call\n * sites (the exported singletons are typed below), so the forward is sound.\n */\nfunction makeServiceProxy<K extends keyof RuntimeServices>(key: K): RuntimeServices[K] {\n const handler: ProxyHandler<RuntimeServices[K]> = {\n get(_target, prop, receiver) {\n const client = __getRuntime()[key];\n const value = Reflect.get(client as object, prop, receiver) as unknown;\n // Bind methods to their owning client so `this` stays correct when the\n // author destructures or calls `Database.query(...)`.\n return typeof value === \"function\" ? value.bind(client) : value;\n },\n };\n // The Proxy target is irrelevant (all access goes through `get`); the cast\n // names the surface type the singleton presents to authors.\n return new Proxy({} as RuntimeServices[K], handler);\n}\n\n/**\n * Build the `.tables` accessor for the top-level `Database`. Each\n * `tables.<name>` access returns a small object that forwards the five CRUD ops\n * to the underlying client using `name` as the string table identifier. The\n * shapes are typed against the generated `palbase-env.d.ts` (`EnvTables`); at\n * runtime they are plain string-keyed calls, so no schema value is needed here.\n *\n * Returns `EnvTables` — TS cannot infer the mapped type through the Proxy, so\n * a single structural narrowing names the surface (the proxy returns a\n * correctly-shaped accessor for whatever string member is read).\n */\n/** T018 (C-8): similar/recommend'in string-keyed yüzü. DBOps'a (endpoint.ts)\n * BİLEREK eklenmedi — search-param imza üçlüsü (engine/db + typed-db +\n * endpoint) büyümesin: proxy dispatch runtime'da engine ops'una zaten ulaşır,\n * derleme güvenliğini typed yüzey (EnvTypedTable) verir. */\nexport interface RecoOps {\n similar(table: string, id: string, params?: Record<string, unknown>): Promise<Record<string, unknown>[]>;\n recommend(table: string, params: Record<string, unknown>): Promise<Record<string, unknown>[]>;\n}\n\n/**\n * The Proxy behind EVERY `.tables` map — public's and every other schema's.\n *\n * `prefix` is what the wire name is built from: `\"\"` for `public`, so its tables\n * stay BARE, and `\"<schema>.\"` for any other, so `schema(\"billing\").tables\n * .invoices` reaches the broker as `billing.invoices` (D-10 — the same\n * schema-qualified key `toSchemaJSON` and the generated `relations` use).\n *\n * One trap for both surfaces: two copies would be two op lists that can drift,\n * and the one that forgets an op does not complain — it answers `undefined`.\n */\nfunction makeTableProxy(ops: () => DBOps & RecoOps, prefix: string): object {\n return new Proxy(\n {},\n {\n get(_t, prop: string | symbol) {\n if (typeof prop !== \"string\") return undefined;\n const name = `${prefix}${prop}`;\n return {\n insert: (data: Record<string, unknown>) => ops().insert(name, data),\n // DÖRDÜNCÜ FİİL, aynı gerekçeyle: tip söz veriyor, ops katmanı\n // uyguluyor, ve bir handler'ın gerçekten dokunduğu yer BURASI.\n // `runtime-table-verbs` kapısı bunu adıyla saydı.\n aggregate: (q: Parameters<DBOps[\"aggregate\"]>[1]) => ops().aggregate(name, q),\n insertMany: (\n rows: readonly Record<string, unknown>[],\n opts?: import(\"./db/bulk.js\").InsertManyOptions,\n ) => ops().insertMany(name, rows, opts),\n update: (q: { where: { id: string }; set: Record<string, unknown> }) =>\n ops().update(name, q.where.id, q.set),\n delete: (id: string) => ops().delete(name, id),\n findById: (id: string) => ops().findById(name, id),\n findUnique: (q: { where: Record<string, unknown>; select?: readonly string[]; with?: Record<string, unknown> }) =>\n ops().findUnique(name, q.where, { select: q.select, with: q.with }),\n page: (q?: Record<string, unknown>) => {\n const { where, ...opts } = q ?? {};\n return ops().page(name, where as Record<string, unknown> | undefined, opts as import(\"./db/page.js\").RawPageOptions);\n },\n findMany: (q?: Record<string, unknown>) => {\n // `where` AYIKLANIR; kalan alanlar (orderBy/limit/offset) ham op'un\n // ikinci parametresine gider. Tümünü geçirmek `where`'i tel üstünde\n // ikinci kez gönderirdi — `typed-db.test.ts` bunu yakalıyor.\n const { where, ...opts } = q ?? {};\n return ops().findMany(\n name,\n where as Record<string, unknown> | undefined,\n opts as Parameters<DBOps[\"findMany\"]>[2],\n );\n },\n put: (q: { data: Record<string, unknown>; onConflict: readonly string[] }) =>\n ops().put(name, q.data, { onConflict: q.onConflict }),\n // THREE VERBS THE TYPE PROMISED AND THIS PROXY DID NOT EMIT.\n //\n // `EnvTypedTableBase` declares `updateMany`, `deleteMany` and `count`\n // (typed-db.ts) and the ops layer implements all three — only this\n // proxy, which is what a handler actually touches, left them out. So\n // the type said the verb exists, autocomplete offered it, and the call\n // answered `undefined is not a function`.\n //\n // Older than this run, but the run rewrote this proxy for\n // `Database.schema(name).tables.*` and would have carried the gap onto\n // the new surface too.\n updateMany: (q: { where: Record<string, unknown>; set: Record<string, unknown>; returning?: boolean }) =>\n ops().updateMany(name, q.where, q.set, q.returning === undefined ? undefined : { returning: q.returning }),\n deleteMany: (q: { where: Record<string, unknown> }) => ops().deleteMany(name, q.where),\n count: (q?: { where?: Record<string, unknown> }) => ops().count(name, q?.where),\n search: (params?: Record<string, unknown>) => ops().search(name, params),\n similar: (id: string, params?: Record<string, unknown>) => ops().similar(name, id, params),\n recommend: (params: Record<string, unknown>) => ops().recommend(name, params),\n facets: (params: { facets: string[] } & Record<string, unknown>) => ops().facets(name, params),\n supersede: (id: string, row: Record<string, unknown>) => ops().supersede(name, id, row),\n claim: (unique: Record<string, unknown>, extra?: Record<string, unknown>) =>\n ops().claim(name, unique, extra),\n };\n },\n },\n );\n}\n\n\n/** The raw string-keyed `DBClient` for the current request scope. */\nconst rawDatabase: DBClient = makeServiceProxy(\"Database\");\n\n/**\n * Wrap a raw `DBClient` into the typed `{ ...ops, tables, transaction }`\n * surface. The five string ops forward straight through; `tables` is the\n * env-typed accessor; `transaction` yields typed tables. Reused for both the\n * default (RLS-enforced) `Database` and the `asService()` sibling — each is\n * fed its own raw client (the default proxy vs `rawDatabase.asService()`).\n *\n * The `satisfies` pins the op surface so a missing/renamed op is a compile\n * error; the assembled object carries `tables`/`transaction` alongside.\n */\n/**\n * PACKAGE-INTERNAL, and deliberately NOT re-exported from `index.ts`.\n *\n * `test/fake-db.ts` builds the fake's surface with the SAME constructor\n * production uses, so the two cannot drift: the day a `$op` is added here, the\n * fake grows it in the same commit. Exporting it from the public index instead\n * would put a runtime-assembly detail on the author-facing API (FR-006).\n */\nexport function makeTypedSurface(raw: AtomicClient & Partial<Pick<DBClient, \"atomic\">>): EnvServiceDatabase {\n // Proxy dispatch her üyeyi taşır; RecoOps tipi DBClient'a eklenmediğinden\n // (yukarıdaki karar) similar/recommend erişimi bu daraltmadan geçer.\n const reco = raw as Omit<DBClient, \"asService\"> & RecoOps;\n // `$` ÖNEKİ AÇIKÇA YAZILIR, dinamik üretilmez.\n //\n // Bir tur `Object.fromEntries(Object.entries(ops).map(…))` ile üretilmişti ve\n // `database.test.ts`'in sayımı onu göremedi: sayım DEKLARASYONLARI okuyor,\n // string literal'leri değil. Görünmeyen bir yüzey denetlenemez — ve o testin\n // varlık sebebi tam olarak budur (FR-044: yüzeyde bağlantı bilgisi olmadığını\n // kanıtlamak, ama önce yüzeye gerçekten ULAŞTIĞINI kanıtlamak).\n const ops = {\n $query: (sql: string, params?: unknown[]) => raw.query(sql, params),\n $diagnostics: () => raw.diagnostics(),\n $insert: (table: string, data: Record<string, unknown>) => raw.insert(table, data),\n $update: (table: string, id: string, data: Record<string, unknown>) =>\n raw.update(table, id, data),\n $delete: (table: string, id: string) => raw.delete(table, id),\n $findById: (table: string, id: string) => raw.findById(table, id),\n $findUnique: (table: string, where: Record<string, unknown>, opts?: Parameters<DBOps[\"findUnique\"]>[2]) => raw.findUnique(table, where, opts),\n $page: (table: string, query?: Record<string, unknown>, opts?: import(\"./db/page.js\").RawPageOptions) => raw.page(table, query, opts),\n $findMany: (table: string, query?: Record<string, unknown>, opts?: Parameters<DBOps[\"findMany\"]>[2]) =>\n raw.findMany(table, query, opts),\n $put: (table: string, data: Record<string, unknown>, opts: { onConflict: readonly string[] }) =>\n raw.put(table, data, opts),\n // `opts` İLETİLİR. Düşürüldüğü sürece `Database.$updateMany(t, w, s,\n // { returning: false })` sessizce SATIRLARI döndürüyordu, sayıyı değil —\n // ve `if (n === 0) throw new Conflict(...)` guard'ı HİÇ çalışmıyordu,\n // çünkü `[] === 0` yanlıştır. Komşu forwarder'lar (`$findMany`, `$put`)\n // kendi opsiyonlarını zaten iletiyordu; bu biri unutulmuştu.\n $updateMany: (\n table: string,\n where: Record<string, unknown>,\n set: Record<string, unknown>,\n opts?: Parameters<DBOps[\"updateMany\"]>[3],\n ) => raw.updateMany(table, where, set, opts),\n $deleteMany: (table: string, where: Record<string, unknown>) => raw.deleteMany(table, where),\n $count: (table: string, where?: Record<string, unknown>) => raw.count(table, where),\n $search: (table: string, params?: Record<string, unknown>) => raw.search(table, params),\n $similar: (table: string, id: string, params?: Record<string, unknown>) =>\n reco.similar(table, id, params),\n $recommend: (table: string, params: Record<string, unknown>) => reco.recommend(table, params),\n $facets: (table: string, params: { facets: string[] } & Record<string, unknown>) => reco.facets(table, params),\n $claim: (table: string, unique: Record<string, unknown>, extra?: Record<string, unknown>) =>\n reco.claim(table, unique, extra),\n $lockRows: (table: string, ids: readonly string[]) => reco.lockRows(table, ids),\n $lockRowsWhere: (\n table: string,\n where: Record<string, unknown>,\n opts?: Parameters<DBOps[\"lockRowsWhere\"]>[2],\n ) => reco.lockRowsWhere(table, where, opts),\n $advisoryXactLock: (key: string) => reco.advisoryXactLock(key),\n $aggregate: (table: string, q: Parameters<DBOps[\"aggregate\"]>[1]) => raw.aggregate(table, q),\n $insertMany: ((\n table: string,\n rows: readonly Record<string, unknown>[],\n opts?: import(\"./db/bulk.js\").InsertManyOptions,\n ) => raw.insertMany(table, rows, opts)) as DBOps[\"insertMany\"],\n $supersede: (table: string, id: string, row: Record<string, unknown>) =>\n raw.supersede(table, id, row),\n } satisfies DollarOps<Omit<DBOps & RecoOps, \"attempt\">>;\n // `ops` DOĞRUDAN verilir, spread edilmez: sayım (`database.test.ts`) nesneyi\n // deklarasyonundan takip ediyor ve bir spread onu kaybettiriyor. Görünmeyen\n // yüzey denetlenemez.\n const base = Object.assign(ops as unknown as Record<string, unknown>, {\n $atomic<T>(fn: (tx: AtomicDatabase) => Promise<T>, options?: AtomicOptions): Promise<T> {\n if (typeof raw.atomic !== \"function\") {\n throw new Error(\"This Database handle cannot open a root transaction; nested $atomic is not supported\");\n }\n // ALS.run scopes only this callback and its continuations, never another\n // Promise.all branch. Calls made by ordinary services through Database\n // therefore share the callback's physical transaction and identity.\n const parent = __requestALS.getStore();\n let runtime: RuntimeServices | undefined;\n try { runtime = __getRuntime(); } catch { /* Direct typed engine handles need no ambient runtime. */ }\n return raw.atomic(async (tx) => {\n const typed = makeTypedSurface(tx);\n const invoke = () => fn(typed);\n if (!runtime) return invoke();\n const refuse = (): never => { throw new Error(\"Database.$atomic owns one transaction and identity; nested roots and $asService are not allowed\"); };\n const ambient = Object.assign({}, tx, { atomic: refuse, asService: refuse });\n return __requestALS.run({ ...parent, runtime: { ...runtime, Database: ambient } }, invoke);\n }, options);\n },\n // Both surfaces get it: a savepoint on the service transaction is as useful\n // as one on the request's, and each is bound to its own connection.\n $attempt: <T,>(fn: (tx: DBOps) => Promise<T>) => raw.attempt(fn),\n $transaction<T>(\n fn: (tx: TxPlan) => T extends Promise<unknown> ? never : T,\n opts?: { retry?: number },\n ): Promise<Materialized<T>> {\n // A FRESH builder per call: it holds this transaction's ops and its error\n // slot table, and the runtime serves concurrent requests on one event loop.\n // A shared builder would splice one request's writes into another's plan.\n //\n assertPlanRetry(opts);\n const builder = new TxPlanBuilder();\n return runTxPlan(raw, makeTxPlanHandle(builder), builder, fn) as Promise<Materialized<T>>;\n },\n $command<T>(fn: (tx: TxPlan) => T extends Promise<unknown> ? never : T, options?: import(\"./db/command.js\").CommandOptions): Promise<Materialized<T>> {\n const builder = new TxPlanBuilder();\n return runTxPlan({ txPlan: plan => raw.command(plan, options) }, makeTxPlanHandle(builder), builder, fn) as Promise<Materialized<T>>;\n },\n });\n // ŞEMA ERİŞİMİ BİR PROXY'DİR, çünkü hangi şemaların bildirildiğini yalnız TİP\n // bilir — runtime'da `Database.billing` diye bir üye yoktur, o ada dokunulduğu\n // anda üretilir. `$`'la başlamayan her ad bir ŞEMA adıdır; ayrım tam olarak\n // budur ve tip tarafındaki DollarOps ile aynı kuralı uygular.\n return new Proxy(base, {\n get(target, prop, receiver) {\n // `tables` DOĞRUDAN YÜZEYDE DE public'in takma adı.\n //\n // Plan tutamağı `tx.tables.todos`'u öğretiyor (göç notu da öyle), ama\n // `Database.public.todos` aynı kelimeyi ADI `tables` OLAN BİR ŞEMA sanıp\n // tele `tables.todos` yazıyordu. Tip onu reddettiği için derlenen kodda\n // erişilemezdi — ama `as any` ya da düz JS ile geçen biri sessizce\n // olmayan bir şemaya gidiyordu, ve iki yüzeyin aynı kelimeye zıt cevap\n // vermesi bu run'ın kapattığı sınıfın kendisi (gözcü M-6).\n if (prop === \"tables\") return makeTableProxy(() => reco, \"\");\n if (typeof prop === \"string\" && !prop.startsWith(\"$\") && !(prop in target)) {\n // Nitelikli tablo anahtarının kuralı BURADA TEKRARLANMAZ (FR-058): tek\n // yazıcı `qualifiedTableKey` ve `table-key-single-source.test.ts` ikinci\n // bir yazıcıyı reddediyor. Prefix ondan türetilir — boş tablo adıyla\n // çağrıldığında geriye ya \"\" (public) ya \"<şema>.\" kalır.\n return makeTableProxy(() => reco, qualifiedTableKey(prop, \"\"));\n }\n return Reflect.get(target, prop, receiver);\n },\n }) as unknown as EnvServiceDatabase;\n}\n\n/**\n * `makeTableProxy`'nin plan ikizi: `tables.<name>` yields the\n * table's PLAN operations, recorded into `builder` instead of sent one by one.\n *\n * Same Proxy shape and same reason for the single narrowing — TS cannot infer a\n * mapped type through a Proxy, so the cast names what the trap returns.\n */\nfunction makeTxTablesAccessor(builder: TxPlanBuilder, prefix = \"\"): TxTables {\n const tablesProxy = new Proxy(\n {},\n {\n get(_t, prop: string | symbol) {\n if (typeof prop !== \"string\") return undefined;\n return builder.table(prefix + prop);\n },\n },\n );\n return tablesProxy as TxTables;\n}\n\n/**\n * Plan tutamağı — `Database` ile AYNI şekil: `tx.public.x`, `tx.<şema>.x`, ve\n * geriye dönük `tx.tables.x`.\n *\n * Şema adı tablo adının ÖNÜNE geçiyor (`billing.invoices`), tıpkı doğrudan\n * yüzeyin `makeTypedSurface` proxy'sinin yaptığı gibi — ve motor artık onu\n * `quoteTable` ile İKİ parça hâlinde tırnaklıyor. Bu ikisi olmadan `billing`\n * şemasındaki iki tabloyu tek atomik planda yazmak imkânsızdı.\n *\n * `tables` ve `public` DIŞINDAKİ HER ad şema kabul edilir ve altındaki tablolar\n * `<ad>.<tablo>` diye adlanır. Yanlış bir şema adı TİPTE yakalanıyor\n * (`keyof Schemas`) — `tx.constructor.x` ve `tx.toString.x` dahil, ölçüldü.\n *\n * TİPTEN KAÇAN bir ad için savunma `quoteTable`'ın KAÇIŞIDIR, başka bir şey\n * değil: `runPlanOp` `op.table`'ı doğrulamadan ona veriyor ve `quoteTable`\n * tırnak ikizleyerek tek bir tanımlayıcı üretiyor. Ölçüldü: `a\"; DROP TABLE t; --`\n * → `\"a\"\"; DROP TABLE t; --\"`, yani enjeksiyon değil, `relation does not exist`.\n * (Bu yorum bir zamanlar `validateSchemaIdentifier`'a atıf yapıyordu — o\n * fonksiyon Go tarafında yaşıyor ve BU yolu hiç görmüyor; gözcü yakaladı.)\n */\nfunction makeTxPlanHandle(builder: TxPlanBuilder): TxPlan {\n const publicTables = makeTxTablesAccessor(builder);\n return new Proxy(\n {},\n {\n get(_t, prop: string | symbol) {\n if (typeof prop !== \"string\") return undefined;\n if (prop === \"tables\") return publicTables;\n // ÖNEK TEK YAZICIDAN (FR-058): `qualifiedTableKey`. Bu kuralı burada\n // elle yazmıştım — public'i çıplak bırakıp diğerine nokta ekleyen bir\n // if/return çifti — ve FR-058 kapısı onu GÖRMEDİ, çünkü kapı yalnız\n // ternary arıyordu. (Kural burada KELİMEYLE anlatılıyor, kod biçiminde\n // DEĞİL: kapı metni tarıyor ve bir yorumdaki kopya da onu tetikler.)\n // İkinci bir yazıcı, kapının var olma sebebi olan sınıfın kendisi:\n // `env-gen.ts`'in kendi kopyası bir public FK'yi başka bir şemanın\n // tablosuna etiketlemişti ve hiçbir şey bunu söylememişti.\n // Boş tablo adıyla çağrılınca geriye ya \"\" (public) ya \"<şema>.\" kalır.\n return makeTxTablesAccessor(builder, qualifiedTableKey(prop, \"\"));\n },\n },\n ) as TxPlan;\n}\n\n/**\n * The project's own Postgres (pgx, schema `env_<envId>`).\n *\n * Typed by default: `Database.public.<name>.insert({...})` is typed against\n * the project's generated `palbase-env.d.ts` with NO import and NO generic.\n * The raw string ops (`Database.$query`/`$insert`/`$update`/`$delete`/\n * `$findById`/`$findMany`) are also available for read-only SQL and for a table\n * name only known at runtime — which the typed surface cannot express past\n * seven tables (see `db/tx-union-key.test-d.ts`).\n *\n * RLS is enforced by default (the runtime runs each op as `authenticated` with\n * the verified user's claims). To bypass RLS, call `Database.$asService()` —\n * explicit and greppable — which runs as the `service_role` (BYPASSRLS).\n *\n * @example\n * import { Database } from \"@palbase/backend\";\n *\n * const todo = await Database.public.todos.insert({ title: req.input.title });\n * todo.id; // string ✓\n * const rows = await Database.$query(\"SELECT id FROM todos WHERE done = $1\", [false]);\n * const all = await Database.$asService().public.todos.findMany({}); // RLS bypass\n */\nexport const Database: EnvTypedDatabase = Object.assign(makeTypedSurface(rawDatabase), {\n /**\n * Lazily resolve the runtime's service-role sibling on each call. We do NOT\n * cache it: `rawDatabase.asService()` reads the CURRENT request scope through\n * the runtime proxy, and the per-request runtime injects a service client\n * bound to that request's identity headers — caching would leak one request's\n * sibling into another concurrent request.\n */\n $asService(): EnvServiceDatabase {\n return makeTypedSurface(rawDatabase.asService());\n },\n}) as unknown as EnvTypedDatabase;\n\n/** Firestore-like document client (PalDocs). */\nexport const Documents: PalbaseDocsClient = makeServiceProxy(\"Documents\");\n\n/**\n * `buckets.<name>` — the storage twin of `Database.public.<name>`, and the same\n * mechanism: `config/storage.ts` generates a `Buckets` augmentation into\n * `palbase-env.d.ts`, so a bucket name is a property with no import and no\n * generic, and a typo is a compile error.\n *\n * The intermediate `.buckets` is there for the reason `.tables` is: bucket\n * names must not share a namespace with the client's own methods, or the day\n * somebody declares a bucket called `bucket` the surface breaks.\n */\nexport type EnvBuckets = {\n [K in keyof Buckets]: TypedBucketClient<Buckets[K] extends BucketTypes ? Buckets[K] : BucketTypes>;\n};\n\n/** One bucket, with its declared variant names in the type. */\nexport interface TypedBucketClient<B extends BucketTypes> extends Omit<PalbaseBucketClient, \"getPublicUrl\"> {\n /** The public URL for the object, or for one of THIS bucket's declared\n * renditions. A name the bucket does not declare is a compile error. */\n getPublicUrl(path: string, options?: { variant?: B[\"variants\"] }): string;\n}\n\nfunction makeBucketsAccessor(storage: () => PalbaseStorageClient): EnvBuckets {\n return new Proxy(\n {},\n {\n get(_t, prop: string | symbol) {\n if (typeof prop !== \"string\") return undefined;\n return storage().bucket(prop);\n },\n },\n ) as EnvBuckets;\n}\n\nconst rawStorage: PalbaseStorageClient = makeServiceProxy(\"Storage\");\n\n/**\n * Object storage: buckets, objects, renditions and signed URLs.\n *\n * `Storage.buckets.posts.upload(...)` is the typed path. `Storage.bucket(name)`\n * remains for a name computed at runtime — rare, and it gives up the typing,\n * which is the honest trade rather than a second blessed way to do it.\n */\nexport const Storage: PalbaseStorageClient & { buckets: EnvBuckets } = Object.assign(\n {\n // FORWARDED explicitly, not assigned onto the service proxy.\n //\n // `Object.assign(rawStorage, {buckets})` writes onto the proxy's TARGET, and\n // the proxy's only trap is `get`, which forwards every read to the module\n // client — so the property landed somewhere nothing reads and\n // `Storage.buckets.docs` was `undefined` in a deployed handler. It\n // typechecked, every test passed, and the live call answered\n // \"TypeError: undefined is not an object\". `Database` never had the bug\n // because it builds a plain surface the same way this now does.\n bucket: (name: string) => rawStorage.bucket(name),\n },\n { buckets: makeBucketsAccessor(() => rawStorage) },\n);\n\n/** JSON-typed cache (get/set/incr/getOrSet). */\nexport const Cache: CacheClient = makeServiceProxy(\"Cache\");\n\n\n/**\n * This tenant's secrets — API keys, provider credentials, signing material the\n * BACKEND owns.\n *\n * `await Secrets.get(\"STRIPE_KEY\")` in a handler. There is no `.env` to read\n * and no file to mount: a secret is written through the vault's authenticated\n * API (or the CLI/MCP that calls it), and this is how the deployed code reads\n * it back. A name this tenant has not set answers null — as does every name\n * the STACK holds, because no route returns a platform secret's value at all.\n */\nexport const Secrets: SecretsService = makeServiceProxy(\"Secrets\");\n\n/**\n * Role assignment, as an operator — `Auth.assignRole(userId, \"agent\")`.\n *\n * The half of auth a SERVER owns. Signing in, MFA and device attestation are a\n * person acting on their own account and live on the client SDK; granting a\n * role is the tenant's product doing something to somebody else, which is\n * exactly what a handler is for. It writes with the service-role credential,\n * because an end user who could write their own assignment would make every\n * permission underneath it meaningless.\n *\n * The write is visible to the very next request: authority is read from the\n * table on each call, never carried on a token.\n */\nexport const Auth: PalbaseAuthAdminClient = makeServiceProxy(\"Auth\");\n\n/** Structured logger. */\nexport const Log: Logger = makeServiceProxy(\"Log\");\n\n/** Push / email / SMS / in-app notifications. */\nexport const Notifications: PalbaseNotificationsClient = makeServiceProxy(\"Notifications\");\n\n\n/**\n * The raw runtime Flags client for the current request scope. Carries the\n * default-surface reads + `setOverride` AND the runtime's `asService()` sibling\n * (the br-pod's `buildFlagsClient` returns both). The default `Flags` singleton\n * below forwards reads + `setOverride` through here; `Flags.$asService()`\n * forwards to this client's own `asService()`.\n */\nconst rawFlags: PalbaseFlagsClient = makeServiceProxy(\"Flags\");\n\n/**\n * Feature flags.\n *\n * Mirrors the `Database` / `Database.$asService()` model. The default surface is\n * RLS-equivalent for flags: reads resolve against the CURRENT request user and\n * `Flags.setOverride(key, value)` writes an override for that same signed-in\n * user (no userId argument, no admin power). Cross-user admin writes\n * (`setOverrideForUser`, …) live behind `Flags.$asService()` — explicit and\n * greppable, just like `Database.$asService()`.\n *\n * @example\n * import { Flags } from \"@palbase/backend\";\n *\n * if (await Flags.isEnabled(\"new_checkout\")) { ... } // current user\n * await Flags.setOverride(\"new_checkout\", true); // current user\n * await Flags.$asService().setOverrideForUser(\"u_9\", \"x\", true); // cross-user\n */\n/**\n * The ambient `Flags` singleton's own surface — NOT the raw client's.\n *\n * MEASURED, as a consumer, against the built tarball: annotating the singleton\n * as `PalbaseFlagsClient` ERASED the `$asService` that `Object.assign` adds, so\n * `Flags.$asService()` did not exist for anyone outside this package —\n *\n * TS2551: Property '$asService' does not exist on type 'PalbaseFlagsClient'.\n * Did you mean 'asService'?\n *\n * — while the only path that DID compile (`asService()`) throws by design. The\n * feature was written and unreachable, which is the defect class this surface\n * exists to remove.\n *\n * `Database` never had the problem because its singleton carries its OWN type\n * (`EnvTypedDatabase`) rather than the raw client's (`DBClient`). This is that,\n * for `Flags`. The raw `PalbaseFlagsClient.asService()` is untouched (FR-023) —\n * it is the seam this forwards to.\n */\nexport type PalbaseFlagsAmbient = Omit<PalbaseFlagsClient, \"asService\"> & {\n /** RLS'i aşan, kullanıcılar arası yazma yüzeyi. */\n $asService(): PalbaseFlagsServiceClient;\n /** 31.0.0 öncesinin adı — SESSİZCE çalışmaz, yerini söyleyerek fırlatır. */\n asService(): never;\n};\n\nexport const Flags: PalbaseFlagsAmbient = Object.assign(\n {\n isEnabled(\n flagName: PalbaseFlagKey,\n context?: PalbaseFlagContext,\n ): Promise<PalbaseResult<boolean>> {\n return rawFlags.isEnabled(flagName, context);\n },\n getVariant(\n flagName: PalbaseFlagKey,\n context?: PalbaseFlagContext,\n ): Promise<PalbaseResult<PalbaseFlagVariant>> {\n return rawFlags.getVariant(flagName, context);\n },\n getAll(context?: PalbaseFlagContext): Promise<PalbaseResult<PalbaseFlag[]>> {\n return rawFlags.getAll(context);\n },\n /**\n * Resolve a flag's value, with an optional fallback.\n *\n * FORWARDED as of 2026-08-15. This surface is written out by hand, method\n * by method, and `get` was missing from it — so the client implemented it,\n * thirty assertions covered it, and `Flags.get(\"x\")` was `undefined` in a\n * deployed handler. Exactly the shape of the `Storage.buckets` defect found\n * the same day: a hand-maintained forwarding list is a list somebody has to\n * remember to update.\n */\n get(\n flagName: PalbaseFlagKey,\n defaultOrContext?: PalbaseFlagValue | PalbaseFlagContext,\n maybeContext?: PalbaseFlagContext,\n ): Promise<PalbaseResult<PalbaseFlagValue>> {\n return rawFlags.get(flagName, defaultOrContext, maybeContext);\n },\n setOverride(\n key: PalbaseFlagKey,\n value: PalbaseFlagValue,\n ): Promise<PalbaseResult<PalbaseSetOverrideResult>> {\n return rawFlags.setOverride(key, value);\n },\n },\n {\n /**\n * Lazily resolve the runtime's cross-user sibling on each call. We do NOT\n * cache it: `rawFlags.asService()` reads the CURRENT request scope through\n * the runtime proxy, so caching would leak one request's sibling into\n * another concurrent request. Mirrors `Database.$asService()`.\n */\n $asService(): PalbaseFlagsServiceClient {\n return rawFlags.asService();\n },\n /**\n * The name this member carried before 32.0.0.\n *\n * It does NOT work silently. A retired member that quietly keeps returning\n * is how a rename becomes a mystery: the old call site goes on compiling,\n * the new name never spreads, and the two live side by side until somebody\n * greps for one and misses half the codebase. `Database` made this split\n * first (`$asService`), and this JSDoc promised \"exactly like\n * Database.$asService()\" while the promise went unkept.\n */\n asService(): never {\n throw new Error(\n \"Flags.asService() was renamed to Flags.$asService() in 32.0.0 — system members carry the `$` prefix, like Database.$asService().\",\n );\n },\n },\n);\n\n/**\n * The Realtime broadcast singleton for the current request scope. Backend-side\n * Realtime is BROADCAST-ONLY (a stateless handler can push but not subscribe —\n * `subscribe()` lives on the client SDK's `pb.realtime`). Fire-and-forget:\n * `broadcast` resolves once accepted (or with an `error`), never blocking the\n * handler on subscribers.\n *\n * @example\n * import { Realtime } from \"@palbase/backend\";\n *\n * await Realtime.broadcast(\"room:42\", \"message\", { text, from: user.id });\n */\nexport const Realtime: PalbaseRealtimeClient = makeServiceProxy(\"Realtime\");\n","/** A PostgreSQL isolation level supported by the explicit root transaction. */\nexport type TransactionIsolation = \"read committed\" | \"repeatable read\" | \"serializable\";\n\nexport interface AtomicOptions {\n /** Each retry opens a fresh transaction and reruns the complete callback.\n * Defaults to zero. Keep external effects outside it; persist an outbox instead. */\n retry?: number;\n isolation?: TransactionIsolation;\n readOnly?: boolean;\n /** Maximum wait for a PostgreSQL lock. Defaults to 5000 ms. */\n lockTimeoutMs?: number;\n /** PostgreSQL statement timeout; applies to every statement in this scope. */\n statementTimeoutMs?: number;\n /** Total work deadline including queueing and retries. Active Bun queries are\n * cancelled; rollback settles before release. An in-flight COMMIT is awaited. */\n timeoutMs?: number;\n signal?: AbortSignal;\n\n}\n\nexport function retryBudget(value: number | undefined): number {\n const n = value ?? 0;\n if (!Number.isInteger(n) || n < 0 || n > 10) {\n throw new Error(\"transaction retry must be an integer between 0 and 10\");\n }\n return n;\n}\n\nexport function validateAtomicOptions(options: AtomicOptions): void {\n retryBudget(options.retry);\n if (options.isolation !== undefined && ![\"read committed\", \"repeatable read\", \"serializable\"].includes(options.isolation)) {\n throw new Error(\"transaction isolation must be read committed, repeatable read or serializable\");\n }\n if (options.readOnly !== undefined && typeof options.readOnly !== \"boolean\") {\n throw new Error(\"transaction readOnly must be a boolean\");\n }\n for (const name of [\"lockTimeoutMs\", \"statementTimeoutMs\", \"timeoutMs\"] as const) {\n const n = options[name];\n if (n !== undefined && (!Number.isInteger(n) || n < 1 || n > 2_147_483_647)) {\n throw new Error(`transaction ${name} must be a positive integer in milliseconds`);\n }\n }\n if (options.signal !== undefined && (typeof options.signal.aborted !== \"boolean\" || typeof options.signal.addEventListener !== \"function\")) {\n throw new Error(\"transaction signal must be an AbortSignal\");\n }\n}\n\n/** A savepoint cannot replace the enclosing transaction's snapshot or retry COMMIT. */\nexport function assertPlanRetry(options: { retry?: number } | undefined): void {\n if (retryBudget(options?.retry) !== 0) {\n throw new Error(\n \"Database.$transaction is a savepoint plan on the request transaction and cannot retry its snapshot or COMMIT. \" +\n \"Use Database.$atomic(async tx => { ... }, { retry, isolation }) and put all decision reads and writes inside that callback.\",\n );\n }\n}\n","// The wire shape of a declared schema — what the deploy reads.\n//\n// `defineSchema(...)` produces a value full of builders and phantom types, which\n// is the right shape for authoring and the wrong shape for anything outside this\n// process. The deploy is Go: it introspects the live database, diffs it against\n// the declaration, and applies the difference. So the declaration has to leave\n// TypeScript as data, and this file is where that happens.\n//\n// It lives in the SDK because the SDK owns the DSL. The alternative — a script\n// beside the deploy that reaches into `._def` — is a second reading of a private\n// shape, and it drifts the moment a column gains a property: the DSL keeps\n// working, the emitter silently omits it, and the database is missing something\n// nobody can see in the source.\n//\n// The field names below are a CONTRACT with Go's `schema.SchemaJSON`. Renaming\n// one here without renaming it there produces a declaration that parses to\n// something emptier than it was — the failure mode being a column, a policy, or\n// a whole table that quietly never gets created.\n// Politika ifadesinin tel şekli `policy.ts`'te TEK kez bildiriliyor. İki kopya\n// olsaydı biri `exists` düğümünü alır, diğeri almaz ve fark ancak Go tarafı\n// bilmediği bir `kind` gördüğünde ortaya çıkardı.\nimport type { PolicyExpr as PolicyExprJSON } from \"./policy.js\";\nexport type { PolicyExpr as PolicyExprJSON } from \"./policy.js\";\nimport type { ColumnBuilder, ColumnDef } from \"./columns.js\";\nimport type { PolicyDef } from \"./policy.js\";\nimport type { MemoryDecl, SchemaDef, SearchDecl, TableDef } from \"./schema.js\";\n\n/** One column, flattened. Mirrors Go's `schema.ColumnJSON`. */\nexport interface ColumnJSON {\n type: string;\n nullable: boolean;\n primaryKey: boolean;\n defaultValue?: unknown;\n defaultRandom?: boolean;\n defaultNow?: boolean;\n renamedFrom?: string;\n /** See Go's `schema.ColumnJSON.Ignored` — the contraction gate's only signal. */\n ignored?: boolean;\n owns?: boolean;\n references?: { table: string; column: string };\n onDeleteAction?: string;\n /** FR-044: türev FK index'i kapatılmışsa `false`. Bildirilmemişse alan YOK. */\n index?: boolean;\n /** FR-049: kolon increment() ile güncelleniyorsa `true`. Aksi hâlde alan YOK. */\n counter?: boolean;\n enumName?: string;\n enumValues?: string[];\n unique?: boolean;\n dimensions?: number;\n}\n\n/** One RLS policy. Mirrors Go's `schema.PolicyJSON`. */\nexport interface PolicyJSON {\n name: string;\n command: string;\n roles: string[];\n /**\n * `USING (...)` — ham string (kaçış kapağı, FR-028) ya da YAPI (FR-022).\n *\n * Go tarafı ikisini de okur: string olan verbatim emit edilir, yapı olan\n * `generator.go`'da SQL'e çevrilir (C-6). Yapı hâli InitPlan sarmalamasını\n * ve `TO <rol>` daraltmasını GÜVENLE yapılabilir kılan şey — string üstünde\n * regex'le denemek yorum içindeki bir `auth.uid()`'yi de sarmalardı.\n */\n using: string | PolicyExprJSON | null;\n withCheck: string | PolicyExprJSON | null;\n permissive: boolean;\n}\n\n\n/** One table. Mirrors Go's `schema.TableJSON`. */\nexport interface TableJSON {\n /**\n * The schema this table lives in. `public` unless declared otherwise.\n *\n * The table carries it because the diff iterates over KEYS but passes the\n * VALUE around: a bare name inside a qualified key space writes the migration\n * into the wrong schema, silently.\n */\n schema: string;\n name: string;\n columns: Record<string, ColumnJSON>;\n rls: boolean;\n policies: PolicyJSON[];\n primaryKey?: string[];\n uniqueConstraints?: { name: string; columns: string[] }[];\n rawConstraints?: { name: string; up: string }[];\n checks?: { name: string; expr: string }[];\n indexes?: IndexJSON[];\n /** Canlıdan düşürülecek constraint adları (FR-008). Sıfır değerde OMIT. */\n dropConstraints?: string[];\n /** Tablo düzeyi çok sütunlu FOREIGN KEY'ler (FR-001). Sıfır değerde OMIT. */\n foreignKeys?: ForeignKeyJSON[];\n /** Koşullu FK'lar — donan demetler (FR-012). Sıfır değerde OMIT. */\n freeze?: FreezeJSON[];\n /** Guard'lar — bildirimsel kısıtın yetişemediği yazma redleri (FR-015). Sıfır değerde OMIT. */\n guards?: GuardJSON[];\n /** Bir kez koşacak veri düzeltmeleri (FR-033). Sıfır değerde OMIT. */\n backfills?: BackfillJSON[];\n /**\n * appendOnly (FR-030): tablo yalnız INSERT kabul eder. Sıfır değerde OMIT —\n * bildirmeyen tablolar wire'da bayt-aynı kalır.\n */\n appendOnly?: boolean;\n search?: SearchJSON;\n memory?: MemoryJSON;\n}\n\n/**\n * Bir index'in wire şekli — Go'nun `IndexJSON`'ıyla ALAN-ADI SÖZLEŞMESİ.\n *\n * `name` + `columns` bugünkü hâl; kalanı FR-041…043'ün taşıyıcısı. Hepsi sıfır\n * değerde OMIT edilir: bildirmeyen bir index wire'da eskisiyle bayt-aynı kalır,\n * yoksa dokunulmamış her şema diff'te değişmiş görünür ve her deploy churn üretir.\n */\nexport interface IndexJSON {\n name: string;\n /** `CREATE UNIQUE INDEX` (FR-007). Sıfır değerde OMIT. */\n unique?: boolean;\n columns: string[];\n /** Partial index koşulu (FR-042) — filtre şekli `WhereFilter` ile aynı. */\n where?: unknown;\n /** İfade index'i (FR-043), ör. `lower(email)`. `columns` ile birlikte kullanılmaz. */\n expression?: string;\n /** Kolon sırası (FR-043). */\n sort?: \"asc\" | \"desc\";\n /** NULL sırası (FR-043). */\n nulls?: \"first\" | \"last\";\n /** Covering index — `INCLUDE (...)` (FR-043). */\n include?: string[];\n}\n\n/**\n * Tablo düzeyi çok sütunlu FOREIGN KEY'in wire şekli — Go'nun `ForeignKeyJSON`'ı\n * ile ALAN-ADI SÖZLEŞMESİ (FR-001). Bir ad değişirse wire sessizce kopar.\n *\n * `onUpdate`/`onDelete`/`match` sıfır değerinde OMIT: bildirmeyen bir FK\n * Postgres'in varsayılanını (NO ACTION / MATCH SIMPLE) alır ve telde yer\n * kaplamaz (NFR-006).\n */\nexport interface ForeignKeyJSON {\n name: string;\n columns: string[];\n refTable: string;\n refColumns: string[];\n onUpdate?: string;\n onDelete?: string;\n match?: string;\n}\n\n/**\n * Koşullu FK'nın (\"donan demet\") wire şekli — Go'nun `FreezeJSON`'ı ile\n * ALAN-ADI SÖZLEŞMESİ (C-8, FR-012).\n *\n * `when` politika ifade yapısının ta kendisi — `IndexJSON.where` ile aynı\n * duruş: üçüncü bir yüklem lehçesi açmak, aynı sorunun iki yazımı demekti.\n * Alanların hiçbiri opsiyonel değil: bir freeze'in koşulu, donan sütunları ve\n * hedefi olmadan anlamı yok ve `toFreezeDef` bunları bildirim anında şart\n * koşuyor. Sıfır değerde OMIT edilen şey DİZİNİN KENDİSİ (`TableJSON.freeze`).\n */\nexport interface FreezeJSON {\n name: string;\n when: unknown;\n columns: string[];\n refTable: string;\n refColumns: string[];\n}\n\n/**\n * Bir guard'ın wire şekli — Go'nun `GuardJSON`'ı ile ALAN-ADI SÖZLEŞMESİ\n * (C-4/C-8, FR-015).\n *\n * `when` ile `exists` AYRI alanlar: Postgres bir trigger'ın `WHEN` yan\n * tümcesinde alt sorguya izin vermiyor (`cannot use subquery in trigger WHEN\n * condition`), yani çapraz satır yüklemi gövdedeki `EXISTS` bloğuna inmek\n * zorunda (FR-019). Ayrımı emitter'ın yükleme bakıp tahmin etmesi yerine wire'da\n * taşımak, o kuralı bildirimin kendi şekline yazar.\n *\n * `detail`/`hint`/`column` sıfır değerde OMIT — bildirmeyen bir guard telde yer\n * kaplamaz (NFR-006). `message` her zaman var: reddin kullanıcıya ulaşan tek\n * çıktısı o.\n */\nexport interface GuardJSON {\n name: string;\n event: string;\n when?: unknown;\n exists?: unknown;\n message: string;\n detail?: string;\n hint?: string;\n column?: string;\n}\n\n/**\n * Bir backfill'in wire şekli — Go'nun `BackfillJSON`'ı ile ALAN-ADI SÖZLEŞMESİ\n * (C-8, FR-033).\n *\n * `name` kimliğin TAMAMI: \"koştu mu\" sorusu ona göre cevaplanıyor, `sql`'e göre\n * değil. Aynı adın altında değişen bir gövde ikinci bir koşu üretmez.\n */\nexport interface BackfillJSON {\n name: string;\n sql: string;\n}\n\n/** C-11 wire şekli — Go'nun MemoryJSON'ıyla alan-adı sözleşmesi (D-019).\n * Beyansız tablolarda alan OMIT — eski şemalar bayt-aynı (NFR-B1). */\nexport interface MemoryJSON {\n from: string[];\n into: string;\n subject?: string;\n extract: { provider: string; model: string };\n}\n\n/** A whole declaration. Mirrors Go's `schema.SchemaJSON`. */\nexport interface SchemaJSON {\n tables: Record<string, TableJSON>;\n extensions: string[];\n /**\n * Every declared schema, with its HTTP reachability.\n *\n * The flag has nowhere else to live: `/v1/db` must know which schemas are\n * reachable, and introspection must know which schemas the project DECLARED —\n * a live database also contains internal module schemas that are none of the\n * diff's business.\n */\n schemas: SchemaMetaJSON[];\n}\n\nexport interface SchemaMetaJSON {\n name: string;\n exposed: boolean;\n}\n\n/** The definition behind a column, whichever side of the builder it arrives on. */\nfunction defOf(column: ColumnBuilder | ColumnDef): ColumnDef {\n return \"_def\" in column ? column._def : column;\n}\n\nfunction columnToJSON(column: ColumnBuilder | ColumnDef): ColumnJSON {\n const def = defOf(column);\n const out: ColumnJSON = {\n type: def.type,\n nullable: def.nullable,\n primaryKey: def.primaryKey,\n };\n // Every optional field is omitted rather than emitted as undefined: Go\n // distinguishes \"absent\" from \"present and empty\" on several of these, and a\n // `defaultValue: null` is a real default that says NULL.\n if (def.defaultValue !== undefined) out.defaultValue = def.defaultValue;\n if (def.defaultRandom === true) out.defaultRandom = true;\n if (def.defaultNow === true) out.defaultNow = true;\n if (def.renamedFrom !== undefined) out.renamedFrom = def.renamedFrom;\n // Go'daki schema.ColumnJSON'un aynası. `omitempty` karşılığı: yalnız TRUE ise yazılır,\n // böylece işaretsiz bir şemanın JSON'u bu alandan önceki hâliyle byte-eş kalır.\n if (def.ignored === true) out.ignored = true;\n // OWNERSHIP HAS TO CROSS THE WIRE, because the gate that enforces it is on the\n // other side. `ownedByUser()` sets `owns` on the column, and Go's\n // `validateOwnership` reads `ColumnJSON.Owns` to refuse a table that declares\n // two owners — but nothing was carrying the flag between them.\n //\n // Measured on the live cluster: a table with TWO `ownedByUser()` columns\n // pushed clean and both foreign keys landed on `auth.users` ON DELETE CASCADE.\n // The rule existed in the DSL and in the generator; the wire in between said\n // nothing, so the generator saw ZERO ownership columns and had nothing to\n // refuse. A flag with a reader and no writer is a dead wire.\n if (def.owns === true) out.owns = true;\n if (def.references !== undefined) {\n out.references = { table: def.references.table, column: def.references.column };\n }\n if (def.onDeleteAction !== undefined) out.onDeleteAction = def.onDeleteAction;\n // Yalnız `false` taşınıyor: \"bildirilmedi\" ile \"açık\" aynı şey ve wire'a\n // yazmak bildirmeyen her kolonu diff'te değişmiş gösterirdi.\n if (def.index === false) out.index = false;\n if (def.counter === true) out.counter = true;\n if (def.enumName !== undefined) out.enumName = def.enumName;\n if (def.enumValues !== undefined) out.enumValues = [...def.enumValues];\n if (def.unique === true) out.unique = true;\n if (def.dimensions !== undefined) out.dimensions = def.dimensions;\n return out;\n}\n\nfunction policyToJSON(policy: PolicyDef): PolicyJSON {\n return {\n name: policy.name,\n command: policy.command ?? \"all\",\n roles: policy.roles ? [...policy.roles] : [],\n // null rather than omitted: a policy with no USING clause is a different\n // thing from one whose clause the emitter forgot, and Go reads the\n // difference.\n using: policy.using ?? null,\n withCheck: policy.withCheck ?? null,\n permissive: policy.permissive !== false,\n };\n}\n\n/** C-4 wire şekli — Go'nun SearchJSON'ıyla ALAN ADI sözleşmesi (C-5).\n * `mode`/`chunks` yalnız yeni-biçim chunk-modunda emit edilir (D-010);\n * satır-modu ve eski biçim bayt-aynı kalır (NFR-B1). */\nexport interface SearchJSON {\n text?: { columns: string[] };\n vector?: {\n column?: string;\n metric: string;\n embed?: { provider: string; model: string; from: string[]; apiKeyName?: string; dimensions?: number; baseURL?: string };\n staleness?: \"null\" | \"keep\";\n mode?: \"row\" | \"chunks\";\n chunks?: { sizeChars?: number; overlapChars?: number };\n }[];\n /** FR-026: sorgu-yeniden-yazımı haritası — beyan yoksa OMIT (NFR-B1). */\n synonyms?: Record<string, string[]>;\n /** C-1: sonuç yeniden-sıralama beyanı — beyan yoksa OMIT. */\n /** FR-029: geçerlilik türevleri — beyan yoksa OMIT. */\n validity?: boolean;\n}\n\n/** T020 (C-1): iki biçimin de üst-düzey ortak alanları — beyan yoksa OMIT,\n * boş synonyms haritası da OMIT (NFR-B1 baytları kımıldamaz). */\nfunction commonSearchFields(search: SearchDecl, out: SearchJSON): void {\n if (search.synonyms !== undefined && Object.keys(search.synonyms).length > 0) {\n out.synonyms = Object.fromEntries(\n Object.entries(search.synonyms).map(([word, alts]) => [word, [...alts]]),\n );\n }\n if (search.validity === true) out.validity = true;\n}\n\n/** Beyanı normalize eder: vector her zaman DİZİ, metric her zaman dolu (vars. cosine),\n * authoring'deki `from`/`model` wire'da `embed` altında toplanır. Alan yoksa OMIT —\n * search'süz şema bayt-aynı kalır (NFR-006). */\nfunction searchToJSON(search: SearchDecl, vectorColumn: string | undefined): SearchJSON {\n if (search.from !== undefined && search.model !== undefined) {\n // YENİ biçim (D-007): from tek listedir — FTS'i de embed'i de besler.\n // Mod ŞEMADAN türer (D-010): tabloda vector kolonu varsa satır-modu\n // (column yazılır, mode OMIT — eski davranışla aynı wire), yoksa\n // chunk-modu (mode:\"chunks\", column yok — vektörler türev tabloda).\n const out: SearchJSON = {};\n const textCols =\n search.text === false ? undefined : Array.isArray(search.text) && search.text.length > 0 ? search.text : search.from;\n if (textCols !== undefined) out.text = { columns: [...textCols] };\n const v: NonNullable<SearchJSON[\"vector\"]>[number] = { metric: search.metric ?? \"cosine\" };\n if (vectorColumn !== undefined) v.column = vectorColumn;\n v.embed = {\n provider: search.model.provider,\n model: search.model.model,\n from: [...search.from],\n ...(search.model.apiKeyName !== undefined ? { apiKeyName: search.model.apiKeyName } : {}),\n ...(search.model.dimensions !== undefined ? { dimensions: search.model.dimensions } : {}),\n ...(search.model.baseURL !== undefined ? { baseURL: search.model.baseURL } : {}),\n };\n if (search.staleness !== undefined) v.staleness = search.staleness;\n if (vectorColumn === undefined) {\n v.mode = \"chunks\";\n if (search.chunks !== undefined) {\n const c: NonNullable<typeof v.chunks> = {};\n if (search.chunks.size !== undefined && search.chunks.size > 0) c.sizeChars = search.chunks.size;\n if (search.chunks.overlap !== undefined && search.chunks.overlap > 0) c.overlapChars = search.chunks.overlap;\n if (Object.keys(c).length > 0) v.chunks = c;\n }\n }\n out.vector = [v];\n commonSearchFields(search, out);\n return out;\n }\n const out: SearchJSON = {};\n // Eski biçimde text yalnız dizi olabilir (boolean'ı defineSchema zaten\n // reddediyor); Array.isArray hem tipi daraltır hem o sözleşmeyi belgeler.\n if (Array.isArray(search.text) && search.text.length > 0) out.text = { columns: [...search.text] };\n const legs = search.vector === undefined ? []\n : Array.isArray(search.vector) ? search.vector : [search.vector];\n if (legs.length > 0) {\n out.vector = legs.map((leg) => {\n const v: NonNullable<SearchJSON[\"vector\"]>[number] = { metric: leg.metric ?? \"cosine\" };\n if (leg.column !== undefined) v.column = leg.column;\n if (leg.staleness !== undefined) v.staleness = leg.staleness;\n if (leg.model !== undefined) {\n v.embed = {\n provider: leg.model.provider,\n model: leg.model.model,\n from: [...(leg.from ?? [])],\n ...(leg.model.apiKeyName !== undefined ? { apiKeyName: leg.model.apiKeyName } : {}),\n ...(leg.model.dimensions !== undefined ? { dimensions: leg.model.dimensions } : {}),\n ...(leg.model.baseURL !== undefined ? { baseURL: leg.model.baseURL } : {}),\n };\n }\n return v;\n });\n }\n commonSearchFields(search, out);\n return out;\n}\n\nfunction memoryToJSON(m: MemoryDecl): MemoryJSON {\n return {\n from: [...m.from],\n into: m.into,\n ...(m.subject !== undefined ? { subject: m.subject } : {}),\n extract: { provider: m.extract.provider, model: m.extract.model },\n };\n}\n\nfunction tableToJSON(table: TableDef, schemaName: string): TableJSON {\n const columns: Record<string, ColumnJSON> = {};\n for (const [name, column] of Object.entries(table.columns)) {\n columns[name] = columnToJSON(column);\n }\n\n const out: TableJSON = {\n name: table.name,\n schema: schemaName,\n columns,\n // Read, not re-derived. `defineSchema` already resolves the fail-closed\n // default (RLS on unless the author wrote `rls: false`, and forced on by any\n // policy), and a second copy of a SECURITY default is exactly the thing that\n // drifts — the direction it drifted last time was \"expose everything\", and\n // the live proof was one user reading another's rows.\n rls: table.rls,\n // KOŞAN SÜRÜMÜN SÖZÜ TELE ÇIKAR — yoksa daralma kapısı onu göremez.\n // `ColumnJSON.ignored` ile aynı sözleşme: işaretlenmemişse alan YOK.\n ...(table.ignored === true ? { ignored: true } : {}),\n policies: (table.policies ?? []).map(policyToJSON),\n };\n\n if (table.primaryKey !== undefined && table.primaryKey.length > 0) {\n out.primaryKey = [...table.primaryKey];\n }\n if (table.unique !== undefined && table.unique.length > 0) {\n out.uniqueConstraints = table.unique.map((u) => ({ name: u.name, columns: [...u.columns] }));\n }\n if (table.raw !== undefined && table.raw.length > 0) {\n out.rawConstraints = table.raw.map((r) => ({ name: r.name, up: r.up }));\n }\n if (table.checks !== undefined && table.checks.length > 0) {\n out.checks = table.checks.map((c) => ({ name: c.name, expr: c.expr }));\n }\n if (table.indexes !== undefined && table.indexes.length > 0) {\n out.indexes = table.indexes.map((i) => {\n // `columns` expression-index'te YOKTUR (ikisi birbirinin alternatifi).\n // Boş dizi ile taşınır: Go tarafı `expression` doluysa onu kullanır.\n const ix: IndexJSON = { name: i.name, columns: i.columns ? [...i.columns] : [] };\n if (i.unique === true) ix.unique = true;\n if (i.where !== undefined) ix.where = i.where;\n if (i.expression !== undefined) ix.expression = i.expression;\n if (i.sort !== undefined) ix.sort = i.sort;\n if (i.nulls !== undefined) ix.nulls = i.nulls;\n if (i.include !== undefined) ix.include = [...i.include];\n return ix;\n });\n }\n if (table.dropConstraints !== undefined && table.dropConstraints.length > 0) {\n out.dropConstraints = [...table.dropConstraints];\n }\n if (table.foreignKeys !== undefined && table.foreignKeys.length > 0) {\n out.foreignKeys = table.foreignKeys.map((fk) => {\n const j: ForeignKeyJSON = {\n name: fk.name,\n columns: [...fk.columns],\n refTable: fk.refTable,\n refColumns: [...fk.refColumns],\n };\n if (fk.onUpdate !== undefined) j.onUpdate = fk.onUpdate;\n if (fk.onDelete !== undefined) j.onDelete = fk.onDelete;\n if (fk.match !== undefined) j.match = fk.match;\n return j;\n });\n }\n if (table.freeze !== undefined && table.freeze.length > 0) {\n out.freeze = table.freeze.map((f) => ({\n name: f.name,\n when: f.when,\n columns: [...f.columns],\n refTable: f.refTable,\n refColumns: [...f.refColumns],\n }));\n }\n if (table.guards !== undefined && table.guards.length > 0) {\n out.guards = table.guards.map((g) => ({\n name: g.name,\n event: g.event,\n ...(g.when !== undefined ? { when: g.when } : {}),\n ...(g.exists !== undefined ? { exists: g.exists } : {}),\n message: g.message,\n ...(g.detail !== undefined ? { detail: g.detail } : {}),\n ...(g.hint !== undefined ? { hint: g.hint } : {}),\n ...(g.column !== undefined ? { column: g.column } : {}),\n }));\n }\n if (table.backfills !== undefined && table.backfills.length > 0) {\n out.backfills = table.backfills.map((b) => ({ name: b.name, sql: b.sql }));\n }\n // Sıfır değerde YAZILMAZ: `appendOnly: false` ile \"bildirilmemiş\" wire'da\n // ayırt edilemez olmalı, yoksa her eski şema diff'te değişmiş görünür.\n if (table.appendOnly === true) out.appendOnly = true;\n if (table.search !== undefined) {\n // D-010 mod kararının tek girdisi: tabloda dimensions'lı (vector) kolon\n // adı. Birden çoksa ilkini yazmak YANLIŞ olurdu — o durum eski biçimin\n // işidir ve yeni biçim + çoklu vector kolonu apply'da reddedilir.\n const vectorColumn = Object.entries(columns).find(([, c]) => c.dimensions !== undefined)?.[0];\n const sj = searchToJSON(table.search, vectorColumn);\n if (sj.text !== undefined || sj.vector !== undefined) out.search = sj;\n }\n if (table.memory !== undefined) {\n out.memory = memoryToJSON(table.memory);\n }\n return out;\n}\n\n/**\n * The key a table answers to in `SchemaJSON.tables`.\n *\n * A public table is BARE, anything else is schema-qualified. This is not a new\n * convention: `RefJSON.Table` already carries `auth.users`, and introspection\n * already returns a public referent bare and a non-public one qualified. Adding\n * a second key space would make two interpreters of the same database.\n */\nexport function qualifiedTableKey(schemaName: string, tableName: string): string {\n // An ABSENT schema means public, exactly as Go's `isPublicSchema` says. This\n // branch used to be missing here and present in the engine's private copy, so\n // the two writers of one rule answered DIFFERENTLY for `\"\"`: one qualified it\n // into a schema literally named the empty string, the other left it bare.\n return schemaName === \"\" || schemaName === \"public\" ? tableName : `${schemaName}.${tableName}`;\n}\n\n/**\n * Serialize declared schemas into the JSON the deploy applies.\n *\n * Takes every schema the project declares — one file per schema — because a\n * cross-schema foreign key can only be checked when both ends are in hand.\n */\nexport function toSchemaJSON(schemas: readonly SchemaDef[]): SchemaJSON {\n const tables: Record<string, TableJSON> = {};\n const extensions: string[] = [];\n const meta: SchemaMetaJSON[] = [];\n const seen = new Set<string>();\n for (const schema of schemas) {\n if (seen.has(schema.name)) {\n throw new Error(`two schemas declare the name \"${schema.name}\" — schema names must be unique`);\n }\n seen.add(schema.name);\n for (const table of Object.values(schema.tables)) {\n const json = tableToJSON(table, schema.name);\n tables[qualifiedTableKey(schema.name, json.name)] = json;\n }\n extensions.push(...(schema.extensions ?? []));\n // The schema list travels because the flag has nowhere else to live: without\n // it /v1/db cannot know which schemas are reachable over HTTP, and nothing\n // downstream can read the DECLARED schema set that introspection needs.\n meta.push({ name: schema.name, exposed: schema.exposed });\n }\n return { tables, extensions: [...new Set(extensions)], schemas: meta };\n}\n","/**\n * `fakeDatabase()` — the in-memory `Database` a SERVICE-LAYER test runs against.\n *\n * WHY IT IS PUBLIC. The scaffold's own AGENTS.md tells authors to \"test the\n * service layer… the test passes a stand-in\", and the SDK shipped no stand-in to\n * pass. So every project wrote its own: a measured customer run carried two — a\n * hand-written `MembershipDb` interface for one service, and a bare `{ query }`\n * object in the tests of another. Both are guesses at this SDK's own surface,\n * and both stop compiling the moment the surface grows.\n *\n * The engine already had exactly this object; it just lived under `__tests__/`\n * where only this package could reach it.\n *\n * WHAT IT IS NOT. It does not interpret SQL. `query()` records what it was asked\n * and answers no rows, because a fake that parsed SQL would be a second, worse\n * Postgres — and a test that passed against it would prove nothing about the\n * real one. Assert on `queries` when the SQL is the thing under test, and put\n * anything that depends on what SQL RETURNS in a live test (`palbase test`).\n */\nimport { createMockDB } from \"../__tests__/helpers/mock-db.js\";\nimport type { DBClient } from \"../endpoint.js\";\nimport { makeTypedSurface } from \"../runtime.js\";\nimport type { EnvServiceDatabase } from \"../db/typed-db.js\";\n\n/** One `Database.$query(...)` call, as the service made it. */\nexport interface RecordedQuery {\n sql: string;\n params: unknown[];\n}\n\n/** What a service-layer test is handed. */\nexport interface FakeDatabase {\n /** Pass this where the service expects `Database`.\n *\n * Built with the SAME constructor the production `Database` uses\n * (`makeTypedSurface`), so the fake's surface cannot drift from the real one\n * — including the `$`-prefixed raw ops and the typed `public` schema surface. */\n db: EnvServiceDatabase;\n /**\n * The RAW `DBClient` behind {@link FakeDatabase.db} (FR-028).\n *\n * `RuntimeServices.Database` is the raw client — the ambient `Database`\n * singleton is what WRAPS it with `makeTypedSurface`. So a test that installs\n * the fake as the ambient runtime passes THIS:\n *\n * withServices({ Database: fake.raw }, () => …)\n *\n * Passing `db` there would wrap an already-wrapped surface and every `$op`\n * would miss (measured). Two fields because there are two call sites: `db`\n * goes straight to a service, `raw` goes into the runtime.\n */\n raw: DBClient;\n /** Every `query()` call, in order. */\n queries: readonly RecordedQuery[];\n /** Put rows in a table before the code under test runs. */\n seed(table: string, rows: Record<string, unknown>[]): void;\n /** Rows inserted into a table, for asserting a write happened. */\n inserted(table: string): Record<string, unknown>[];\n /** Rows updated in a table. */\n updated(table: string): Record<string, unknown>[];\n /** Ids deleted from a table. */\n deleted(table: string): string[];\n}\n\nexport function fakeDatabase(): FakeDatabase {\n const mock = createMockDB();\n const queries: RecordedQuery[] = [];\n\n // The recorder wraps `query` and leaves every other op alone, so the fake's\n // behaviour is the engine's mock plus one observation.\n const db: DBClient = Object.assign(Object.create(Object.getPrototypeOf(mock) as object) as DBClient, mock, {\n query: async (sql: string, params: unknown[] = []) => {\n queries.push({ sql, params });\n return mock.query(sql, params);\n },\n });\n\n return {\n db: makeTypedSurface(db),\n raw: db,\n queries,\n seed: (table, rows) => mock.seed(table, rows),\n inserted: (table) => mock.inserted(table),\n updated: (table) => mock.updated(table),\n deleted: (table) => mock.deleted(table),\n };\n}\n","/**\n * `withServices()` — run code with only the platform services a test supplies.\n *\n * WHY IT IS PUBLIC. `isolated()` substitutes CONSTRUCTOR dependencies, and its\n * own documentation says why it cannot help here: \"platform services are\n * ambient rather than injected\". So the repository layer — the one place that\n * really does `import { Database } from \"@palbase/backend\"` — had no supported\n * way to be unit-tested, while `__runWithRuntime` demands EVERY service. A\n * measured consumer project wrote this helper by hand, exploding proxies\n * included, and 30.0.0 then added a tenth required service (`Auth`) which broke\n * that hand-written copy. Shipping it here is what stops that from recurring.\n *\n * WHAT IS ABSENT IS LOUD. An unsupplied service is neither `undefined` nor a\n * silent no-op: touching it throws and NAMES itself, so a test that quietly\n * grew a dependency on `Cache` fails saying \"Cache\", not \"cannot read\n * properties of undefined\".\n *\n * SCOPE IS THE REQUEST ALS, never the process-global slot. Two tests in one\n * file must not be able to see each other's services, and a helper that wrote\n * the global slot would leak the first test's fake into the second.\n *\n * EKSİKSİZLİK DERLEYİCİYE SORULUR, BİR LİSTEYE DEĞİL. İlk yazımı servis\n * adlarını bir diziye koyup `satisfies readonly (keyof RuntimeServices)[]` ile\n * pinliyordu — ama `satisfies` yalnız \"her ELEMAN bir anahtar mı\" diye bakar,\n * \"her ANAHTAR listede mi\" diye BAKMAZ. Ölçüldü: `RuntimeServices`'a on birinci\n * bir servis eklenip liste dokunulmadan bırakıldığında `tsc --strict` TEMİZ\n * derliyor, ve eksik servise erişen tüketici `TypeError: Reflect.get called on\n * non-object` alıyor — ne servisin adı, ne çaresi. Yani bu dosyanın var olma\n * sebebi olan kusurun ta kendisi, bu dosya tarafından üretiliyordu.\n *\n * Şimdi `filled` düz bir `RuntimeServices` nesne literali: bir alan eksik\n * kalırsa TypeScript `TS2741: Property '<ad>' is missing` diyor ve derleme\n * durur. `as unknown as` yok.\n */\nimport { __runWithRuntime, __requestALS, type RuntimeServices } from \"../runtime.js\";\n\n/**\n * A stand-in that refuses every read by NAME.\n *\n * The Proxy target is irrelevant (all access goes through `get`); the single\n * narrowing names the surface the caller expects — the same one-point cast\n * `makeServiceProxy` already uses for exactly this shape.\n */\nfunction absent<K extends keyof RuntimeServices>(name: K): RuntimeServices[K] {\n return new Proxy({} as RuntimeServices[K], {\n get(_target, prop) {\n throw new Error(\n `${String(name)}.${String(prop)} was read, but this test did not provide ${String(name)}. ` +\n `Pass it: withServices({ ${String(name)}: … }, () => …)`,\n );\n },\n });\n}\n\n/** The supplied service, or one that names itself when touched. */\nfunction pick<K extends keyof RuntimeServices>(\n services: Partial<RuntimeServices>,\n key: K,\n): RuntimeServices[K] {\n return services[key] ?? absent(key);\n}\n\nexport function withServices<T>(services: Partial<RuntimeServices>, fn: () => T): T {\n // Nesne LİTERALİ, üretilmiş bir kayıt değil: eksik bir alan burada derleme\n // hatasıdır (ölçüldü: TS2741), bir çalışma zamanı sürprizi değil.\n const filled: RuntimeServices = {\n Database: pick(services, \"Database\"),\n Auth: pick(services, \"Auth\"),\n Secrets: pick(services, \"Secrets\"),\n Documents: pick(services, \"Documents\"),\n Storage: pick(services, \"Storage\"),\n Cache: pick(services, \"Cache\"),\n Log: pick(services, \"Log\"),\n Notifications: pick(services, \"Notifications\"),\n Flags: pick(services, \"Flags\"),\n Realtime: pick(services, \"Realtime\"),\n };\n // `userId`'yi MOTORUN yazdığı gibi yaz. Motor `runWithRuntime`'ın hemen\n // ardından kutuya `userId ?? null` koyuyor ve `RequestStore`'un sözleşmesi\n // \"anonim istekte null\" diyor. Yalnız `{ runtime }` yazmak `undefined`\n // bırakırdı; `undefined` ile `null`'ı ayıran her dal testte bir yol,\n // üretimde başka bir yol koşardı — testin yeşilliği üretim hakkında yalan\n // söylerdi.\n return __requestALS.run({ runtime: filled, userId: null }, fn);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;ACAA,IAAMA,aAAa,CAAC;AACb,IAAMC,gBAAgBC,iBAAiBC,YAAYH,UAAAA;AAC1D,SAASE,iBAAiBE,SAASC,QAAM;AACrC,SAAO,IAAIC,MAAMF,SAAS;IACtBG,IAAIC,SAASC,MAAMC,WAAS;AACxB,UAAID,QAAQJ,QAAQ;AAChB,eAAOA,OAAOI,IAAAA;MAClB,OACK;AACD,eAAOL,QAAQK,IAAAA;MACnB;IACJ;IACAE,IAAIH,SAASC,MAAMG,OAAK;AACpB,UAAIH,QAAQJ,QAAQ;AAChB,eAAOA,OAAOI,IAAAA;MAClB;AACAL,cAAQK,IAAAA,IAAQG;AAChB,aAAO;IACX;IACAC,eAAeL,SAASC,MAAI;AACxB,UAAIK,UAAU;AACd,UAAIL,QAAQJ,QAAQ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,OAAOC,IAAAA,GAAlC;IACNC,UAAU,wBAACF,UAAUf,KAAKiB,SAASF,KAAAA,GAAzB;IACVG,SAAS,wBAACH,UAAUf,KAAKkB,QAAQH,KAAAA,GAAxB;IACTI,SAAS,wBAACJ,UAAUf,KAAKmB,QAAQJ,KAAAA,GAAxB;EACX;AACF;AAtBgBhB;;;ACrBhB,SAASqB,OAAwCC,MAAO;AACtD,SAAO,IAAIC,MAAM,CAAC,GAAyB;IACzCC,IAAIC,SAASC,MAAI;AACf,YAAM,IAAIC,MACR,GAAGC,OAAON,IAAAA,CAAAA,IAASM,OAAOF,IAAAA,CAAAA,4CAAiDE,OAAON,IAAAA,CAAAA,6BACrDM,OAAON,IAAAA,CAAAA,2BAAsB;IAE9D;EACF,CAAA;AACF;AATSD;AAYT,SAASQ,KACPC,UACAC,KAAM;AAEN,SAAOD,SAASC,GAAAA,KAAQV,OAAOU,GAAAA;AACjC;AALSF;AAOF,SAASG,aAAgBF,UAAoCG,IAAW;AAG7E,QAAMC,SAA0B;IAC9BC,UAAUN,KAAKC,UAAU,UAAA;IACzBM,MAAMP,KAAKC,UAAU,MAAA;IACrBO,SAASR,KAAKC,UAAU,SAAA;IACxBQ,WAAWT,KAAKC,UAAU,WAAA;IAC1BS,SAASV,KAAKC,UAAU,SAAA;IACxBU,OAAOX,KAAKC,UAAU,OAAA;IACtBW,KAAKZ,KAAKC,UAAU,KAAA;IACpBY,eAAeb,KAAKC,UAAU,eAAA;IAC9Ba,OAAOd,KAAKC,UAAU,OAAA;IACtBc,UAAUf,KAAKC,UAAU,UAAA;EAC3B;AAOA,SAAOe,aAAaC,IAAI;IAAEC,SAASb;IAAQc,QAAQ;EAAK,GAAGf,EAAAA;AAC7D;AAtBgBD;","names":["dntGlobals","dntGlobalThis","createMergeProxy","globalThis","baseObj","extObj","Proxy","get","_target","prop","_receiver","set","value","deleteProperty","success","ownKeys","baseKeys","Reflect","extKeys","extKeysSet","Set","filter","k","has","defineProperty","desc","getOwnPropertyDescriptor","N_0","EC_P_521_PARAMS","p","b","gx","gy","coordinateSize","isBytes","a","Uint8Array","ArrayBuffer","isView","name","anumber","n","title","Number","isSafeInteger","prefix","Error","abytes","value","length","bytes","len","needsLen","undefined","ofLen","got","aexists","instance","checkFinished","destroyed","finished","aoutput","out","min","outputLen","u32","arr","Uint32Array","buffer","byteOffset","Math","floor","byteLength","clean","arrays","i","length","fill","_endianTestBuffer","_endianTestBytes","Uint8Array","isLE","createView","arr","DataView","buffer","byteOffset","byteLength","numberToBigint","num","anumber","n","out","N_0","bit","Math","floor","copyBytes","bytes","Uint8Array","from","ahash","h","create","Error","anumber","outputLen","blockLen","_HMAC","hash","key","Object","defineProperty","enumerable","configurable","writable","value","ahash","abytes","undefined","iHash","create","update","Error","blockLen","outputLen","pad","Uint8Array","set","length","digest","i","oHash","clean","buf","aexists","digestInto","out","finished","destroy","_cloneInto","to","getPrototypeOf","destroyed","clone","hmac","message","U32_MASK64","_32n","fromBig","n","le","h","Number","l","split","lst","len","length","Ah","Uint32Array","Al","i","_0n","_1n","_2n","_7n","_256n","_0x71n","SHA3_PI","SHA3_ROTL","_SHA3_IOTA","round","R","x","y","push","t","j","BigInt","IOTAS","split","SHA3_IOTA_H","SHA3_IOTA_L","abool","b","Error","wrapCipher","params","constructor","wrappedCipher","key","args","abytes","undefined","isLE","Error","nonceLength","nonce","varSizeNonce","tagl","tagLength","cipher","checkOutput","fnLength","output","called","wrCipher","encrypt","data","length","decrypt","Object","assign","checkOpts","defaults","opts","merged","equalBytes","a","b","diff","i","getOutput","expectedLength","out","onlyAligned","Uint8Array","isAligned32","u64Lengths","dataLength","aadLength","abool","num","view","createView","setBigUint64","numberToBigint","bytes","byteOffset","_utf8ToBytes","str","Uint8Array","from","split","map","c","charCodeAt","sigma16","sigma32","sigma16_32","u32","sigma32_32","rotl","a","b","isAligned32","byteOffset","BLOCK_LEN","BLOCK_LEN32","MAX_COUNTER","U32_EMPTY","Uint32Array","of","runCipher","core","sigma","key","nonce","data","output","counter","rounds","len","length","block","b32","isAligned","d32","o32","pos","Error","take","Math","min","pos32","j","posj","createCipher","opts","allowShortKeys","extendNonceFn","counterLength","counterRight","checkOpts","anumber","abool","abytes","undefined","toClean","l","k","push","copyBytes","set","k32","subarray","nonceNcLen","nc","n32","clean","u8to16","a","i","Poly1305","key","Object","defineProperty","enumerable","configurable","writable","value","Uint8Array","Uint16Array","copyBytes","abytes","t0","t1","t2","t3","t4","t5","t6","t7","r","pad","process","data","offset","isLast","hibit","h","r0","r1","r2","r3","r4","r5","r6","r7","r8","r9","h0","h1","h2","h3","h4","h5","h6","h7","h8","h9","c","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","finalize","g","mask","f","clean","update","aexists","buffer","blockLen","len","length","pos","take","Math","min","set","subarray","destroy","digestInto","out","aoutput","finished","opos","digest","outputLen","res","slice","wrapConstructorWithKey","hashCons","hashC","msg","tmp","create","poly1305","chachaCore","s","k","n","out","cnt","rounds","y00","y01","y02","y03","y04","y05","y06","y07","y08","y09","y10","y11","y12","y13","y14","y15","x00","x01","x02","x03","x04","x05","x06","x07","x08","x09","x10","x11","x12","x13","x14","x15","r","rotl","oi","chacha20","createCipher","counterRight","counterLength","allowShortKeys","ZEROS16","Uint8Array","updatePadded","h","msg","update","leftover","length","subarray","ZEROS32","computeTag","fn","key","nonce","ciphertext","AAD","undefined","abytes","authKey","lengths","u64Lengths","poly1305","create","res","digest","clean","_poly1305_aead","xorStream","tagLength","encrypt","plaintext","output","plength","getOutput","set","oPlain","tag","decrypt","data","passedTag","equalBytes","Error","chacha20poly1305","wrapCipher","blockSize","nonceLength","LABEL_SEC","Uint8Array","_Mutex_locked","_Mutex_locked","WeakMap","_RecipientContextImpl_mutex","_RecipientContextImpl_mutex","WeakMap","_SenderContextImpl_mutex","_SenderContextImpl_mutex","WeakMap","LABEL_BASE_NONCE","Uint8Array","LABEL_EXP","LABEL_INFO_HASH","LABEL_KEY","LABEL_PSK_ID_HASH","LABEL_SECRET","SUITE_ID_HEADER_HPKE","PKCS8_ALG_ID_X25519","Uint8Array","PKCS8_ALG_ID_X448","Uint8Array","runtime","mod","encoder","encoder","TestApiError","Error","status","error","data","body","method","path","envelope","code","String","error_description","name","required","value","envName","isLocalTarget","baseUrl","hostname","URL","secondsUntilExpiry","token","split","claims","JSON","parse","Buffer","from","toString","exp","Math","floor","Date","now","createTestApi","config","replace","apiKey","local","candidateToken","doFetch","fetch","requests","bearer","call","opts","headers","apikey","authorization","undefined","startedAt","res","stringify","text","parsed","safeParse","push","ms","ok","left","abs","get","post","patch","put","delete","query","signInAs","identity","identities","declared","Object","keys","length","join","accessToken","id","email","signIn","credentials","attempt","extra","result","e","refusal","challenge","asPowChallenge","solvePowChallenge","access_token","user","signOut","asAnonymous","parseIdentities","raw","configured","api","Proxy","_target","prop","process","env","PALBASE_TEST_BASE_URL","PALBASE_TEST_API_KEY","PALBASE_TEST_CANDIDATE","PALBASE_TEST_IDENTITIES","Reflect","isolated","over","Map","local","make","c","has","get","hit","undefined","meta","Reflect","getMetadata","inst","map","d","set","api","with","t","v","validateInsertManyOptions","opts","returning","undefined","Error","action","onConflict","Array","isArray","some","c","length","REF_BRAND","Symbol","for","brandRef","v","kind","Object","defineProperty","value","enumerable","brandOf","undefined","hasOwn","isColRef","v","brandOf","$col","isSqlFragment","v","brandOf","f","$sql","undefined","Array","isArray","text","values","TX_EXPR","Symbol","for","isNowExpr","isColumnExpr","e","fn","assertNoExpressionHandles","caller","table","cols","data","c","Error","isColRef","KNOWN_OPS","Set","REFUSED_OPS","eq","assertUsableFilter","where","COMPOSITES","col","cond","Object","entries","has","branches","b","rel","inner","length","op","some","x","assertUsableWriteValues","TxRefError","Error","message","name","TxPlanError","EXPR","Symbol","for","REF","ROW","ROWS","TRAPPED_PROPS","toPrimitive","trap","prop","what","hint","description","String","columnExprOf","v","exprOf","makeRef","op","field","target","REF","Proxy","get","t","prop","TRAPPED_PROPS","includes","trap","undefined","makeRowHandle","ROW","refDescriptor","v","d","isRefDescriptor","rowOpIndex","exprOf","e","EXPR","isRowsHandle","ROWS","encodeValue","value","column","allowColumnExpr","ref","brandRef","$ref","isNowExpr","$expr","fn","expr","TxPlanError","assertNoNestedHandles","encodeFilterValue","Array","isArray","map","Date","isColRef","isSqlFragment","out","k","Object","entries","encodeFilterMap","key","keys","sort","item","values","encodeMap","SKIPPED_OP","TxRowsImpl","guarded","builder","opIndex","what","then","TxRefError","expectOne","error","declareGuard","expectNone","expectAtLeast","n","assertGuardCount","expectAtMost","kind","Error","attachGuard","Number","isInteger","String","MAX_OPS","MAX_ROWS","TxPlanBuilder","ops","slots","table","name","insert","encoded","length","push","put","options","onConflict","insertMany","rows","opts","row","assertUniformRows","action","updateWhere","where","set","encodedWhere","encodedSet","deleteWhere","select","limit","lock","index","slot","guard","body","errorForSlot","first","want","wantKey","join","i","got","materializeResult","results","rowOf","rowOp","isPlainObject","result","proto","getPrototypeOf","prototype","runTxPlan","transport","handle","returned","response","txPlan","err","translateRejection","rejection","error_code","refuseFragment","caller","table","where","isSqlFragment","Error","k","v","Object","entries","branch","Array","isArray","addDecimal","cell","by","sign","undefined","a","String","b","parse","x","m","exec","trim","frac","unit","BigInt","scale","length","pa","pb","Math","max","lift","total","Number","toString","neg","digits","padStart","out","slice","rowMatchesFilter","row","f","every","c","some","matchesCell","cmp","op","l","Date","getTime","r","key","cond","isColRef","$col","isNowExpr","toISOString","includes","isColumnExpr","toLowerCase","startsWith","endsWith","createMockDB","store","Map","tracked","inserted","updated","deleted","rowsOf","rows","get","set","track","map","list","push","resolveInsertValues","data","expr","columnExprOf","fn","ops","diagnostics","updateMany","opts","keys","assertUsableFilter","assertUsableWriteValues","hit","filter","returning","deleteMany","keep","count","search","_table","_params","facets","similar","recommend","supersede","_id","id","crypto","randomUUID","query","_sql","insert","raw","assertNoExpressionHandles","record","aggregate","q","groups","groupBy","shape","bucket","sum","vals","reduce","avg","pick","byKey","JSON","stringify","values","insertMany","validateInsertManyOptions","onConflict","cols","i","missing","extra","join","rawRow","lockRows","ids","unique","Set","sort","lockRowsWhere","mode","advisoryXactLock","_key","claim","keyCols","existing","find","put","rawData","update","idx","findIndex","current","applied","delete","splice","findUnique","findById","page","findMany","limit","offset","isInteger","with","orderSpecs","orderBy","o","dir","direction","column","y","xNull","yNull","nullsFirst","nulls","start","select","fromEntries","txPlan","plan","snapshot","trackedSnapshot","cloneTracked","results","result","applyOp","failure","guardFailure","guard","err","clear","resolveMap","conflict","value","rows_affected","created","written","matches","next","removed","indexOf","found","client","command","options","atomic","attempt","asService","seed","resolveValue","tagged","$ref","txRejection","message","field","$expr","base","ok","kind","n","slot","status","code","error_code","retryBudget","value","n","Number","isInteger","Error","assertPlanRetry","options","retryBudget","retry","Error","qualifiedTableKey","schemaName","tableName","REQUEST_ALS","Symbol","for","__requestALS","g","globalThis","AsyncLocalStorage","runtime","REQUIRED_SERVICES","refuseIncompleteBox","services","missing","filter","k","undefined","length","Error","join","__getRuntime","scoped","__requestALS","getStore","runtime","makeServiceProxy","key","handler","get","_target","prop","receiver","client","__getRuntime","value","Reflect","bind","Proxy","makeTableProxy","ops","prefix","_t","undefined","name","insert","data","aggregate","q","insertMany","rows","opts","update","where","id","set","delete","findById","findUnique","select","with","page","findMany","put","onConflict","updateMany","returning","deleteMany","count","search","params","similar","recommend","facets","supersede","row","claim","unique","extra","rawDatabase","makeTypedSurface","raw","reco","$query","sql","query","$diagnostics","diagnostics","$insert","table","$update","$delete","$findById","$findUnique","$page","$findMany","$put","$updateMany","$deleteMany","$count","$search","$similar","$recommend","$facets","$claim","$lockRows","ids","lockRows","$lockRowsWhere","lockRowsWhere","$advisoryXactLock","advisoryXactLock","$aggregate","$insertMany","$supersede","base","Object","assign","$atomic","fn","options","atomic","Error","parent","__requestALS","getStore","runtime","tx","typed","invoke","refuse","ambient","asService","run","Database","$attempt","attempt","$transaction","assertPlanRetry","builder","TxPlanBuilder","runTxPlan","makeTxPlanHandle","$command","txPlan","plan","command","target","startsWith","qualifiedTableKey","makeTxTablesAccessor","tablesProxy","publicTables","$asService","Documents","makeBucketsAccessor","storage","bucket","rawStorage","Storage","buckets","Cache","Secrets","Auth","Log","Notifications","rawFlags","Flags","isEnabled","flagName","context","getVariant","getAll","defaultOrContext","maybeContext","setOverride","Realtime","fakeDatabase","mock","createMockDB","queries","db","Object","assign","create","getPrototypeOf","query","sql","params","push","makeTypedSurface","raw","seed","table","rows","inserted","updated","deleted","absent","name","Proxy","get","_target","prop","Error","String","pick","services","key","withServices","fn","filled","Database","Auth","Secrets","Documents","Storage","Cache","Log","Notifications","Flags","Realtime","__requestALS","run","runtime","userId"]}
|
|
1
|
+
{"version":3,"sources":["../../src/test/index.ts","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/_dnt.shims.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/consts.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/kems/dhkemPrimitives/ec.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/utils/noble.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/hash.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/hmac.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/u64.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/sha3.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/utils.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/_arx.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/_poly1305.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/chacha.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/exporterContext.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/mutex.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/recipientContext.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/senderContext.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/cipherSuiteNative.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/kems/dhkemPrimitives/x25519.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/kems/dhkemPrimitives/x448.js","../../../core/src/config.ts","../../../core/src/errors.ts","../../../core/src/platform.ts","../../../core/src/pow.ts","../../../core/src/sealed.ts","../../../core/src/sealed-json.ts","../../../core/src/sealed-keys.ts","../../../core/src/url.ts","../../../core/src/http.ts","../../../core/src/token.ts","../../src/test/api.ts","../../src/test/container.ts","../../src/db/bulk.ts","../../src/db/input-guards.ts","../../src/db/tx-plan.ts","../../src/__tests__/helpers/mock-db.ts","../../src/runtime.ts","../../src/db/transaction-options.ts","../../src/db/schema-json.ts","../../src/test/fake-db.ts","../../src/test/with-services.ts"],"sourcesContent":["export { api, createTestApi, TestApiError } from \"./api.js\";\nexport { isolated } from \"./container.js\";\nexport type { IsolatedContainer } from \"./container.js\";\nexport { fakeDatabase } from \"./fake-db.js\";\nexport { withServices } from \"./with-services.js\";\nexport type { FakeDatabase, RecordedQuery } from \"./fake-db.js\";\nexport type {\n CallOptions,\n ErrorEnvelope,\n RecordedRequest,\n TestApi,\n TestApiConfig,\n TestIdentity,\n} from \"./api.js\";\n","const dntGlobals = {};\nexport const dntGlobalThis = createMergeProxy(globalThis, dntGlobals);\nfunction createMergeProxy(baseObj, extObj) {\n return new Proxy(baseObj, {\n get(_target, prop, _receiver) {\n if (prop in extObj) {\n return extObj[prop];\n }\n else {\n return baseObj[prop];\n }\n },\n set(_target, prop, value) {\n if (prop in extObj) {\n delete extObj[prop];\n }\n baseObj[prop] = value;\n return true;\n },\n deleteProperty(_target, prop) {\n let success = false;\n if (prop in extObj) {\n delete extObj[prop];\n success = true;\n }\n if (prop in baseObj) {\n delete baseObj[prop];\n success = true;\n }\n return success;\n },\n ownKeys(_target) {\n const baseKeys = Reflect.ownKeys(baseObj);\n const extKeys = Reflect.ownKeys(extObj);\n const extKeysSet = new Set(extKeys);\n return [...baseKeys.filter((k) => !extKeysSet.has(k)), ...extKeys];\n },\n defineProperty(_target, prop, desc) {\n if (prop in extObj) {\n delete extObj[prop];\n }\n Reflect.defineProperty(baseObj, prop, desc);\n return true;\n },\n getOwnPropertyDescriptor(_target, prop) {\n if (prop in extObj) {\n return Reflect.getOwnPropertyDescriptor(extObj, prop);\n }\n else {\n return Reflect.getOwnPropertyDescriptor(baseObj, prop);\n }\n },\n has(_target, prop) {\n return prop in extObj || prop in baseObj;\n },\n });\n}\n","// The input length limit (psk, psk_id, info, exporter_context, ikm).\nexport const INPUT_LENGTH_LIMIT = 8192;\nexport const INFO_LENGTH_LIMIT = 268435456;\n// The minimum length of a PSK.\nexport const MINIMUM_PSK_LENGTH = 32;\n// b\"\"\nexport const EMPTY = /* @__PURE__ */ new Uint8Array(0);\n// Common BigInt constants\nexport const N_0 = 0n;\nexport const N_1 = 1n;\nexport const N_2 = 2n;\nexport const N_7 = 7n;\nexport const N_32 = 32n;\nexport const N_256 = 256n;\nexport const N_0x71 = 0x71n;\nexport const BYTE_TO_BIGINT_256 = /* @__PURE__ */ (() => {\n const out = new Array(256);\n let i = 0;\n let value = 0n;\n while (i < 256) {\n out[i] = value;\n i++;\n value += 1n;\n }\n return out;\n})();\n","import { NativeAlgorithm } from \"../../algorithm.js\";\nimport { BYTE_TO_BIGINT_256, EMPTY } from \"../../consts.js\";\nimport { toArrayBuffer } from \"../../kdfs/hkdf.js\";\nimport { DeriveKeyPairError, DeserializeError, NotSupportedError, SerializeError, } from \"../../errors.js\";\nimport { KemId } from \"../../identifiers.js\";\nimport { KEM_USAGES, LABEL_DKP_PRK } from \"../../interfaces/dhkemPrimitives.js\";\nimport { Bignum } from \"../../utils/bignum.js\";\nimport { base64UrlToBytes, i2Osp } from \"../../utils/misc.js\";\n// b\"candidate\"\n// deno-fmt-ignore\nconst LABEL_CANDIDATE = /* @__PURE__ */ new Uint8Array([\n 99, 97, 110, 100, 105, 100, 97, 116, 101,\n]);\n// the order of the curve being used.\n// deno-fmt-ignore\nconst ORDER_P_256 = /* @__PURE__ */ new Uint8Array([\n 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84,\n 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51,\n]);\n// deno-fmt-ignore\nconst ORDER_P_384 = /* @__PURE__ */ new Uint8Array([\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xc7, 0x63, 0x4d, 0x81, 0xf4, 0x37, 0x2d, 0xdf,\n 0x58, 0x1a, 0x0d, 0xb2, 0x48, 0xb0, 0xa7, 0x7a,\n 0xec, 0xec, 0x19, 0x6a, 0xcc, 0xc5, 0x29, 0x73,\n]);\n// deno-fmt-ignore\nconst ORDER_P_521 = /* @__PURE__ */ new Uint8Array([\n 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n 0xff, 0xfa, 0x51, 0x86, 0x87, 0x83, 0xbf, 0x2f,\n 0x96, 0x6b, 0x7f, 0xcc, 0x01, 0x48, 0xf7, 0x09,\n 0xa5, 0xd0, 0x3b, 0xb5, 0xc9, 0xb8, 0x89, 0x9c,\n 0x47, 0xae, 0xbb, 0x6f, 0xb7, 0x1e, 0x91, 0x38,\n 0x64, 0x09,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_256 = /* @__PURE__ */ new Uint8Array([\n 48, 65, 2, 1, 0, 48, 19, 6, 7, 42,\n 134, 72, 206, 61, 2, 1, 6, 8, 42, 134,\n 72, 206, 61, 3, 1, 7, 4, 39, 48, 37,\n 2, 1, 1, 4, 32,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_384 = /* @__PURE__ */ new Uint8Array([\n 48, 78, 2, 1, 0, 48, 16, 6, 7, 42,\n 134, 72, 206, 61, 2, 1, 6, 5, 43, 129,\n 4, 0, 34, 4, 55, 48, 53, 2, 1, 1,\n 4, 48,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_521 = /* @__PURE__ */ new Uint8Array([\n 48, 96, 2, 1, 0, 48, 16, 6, 7, 42,\n 134, 72, 206, 61, 2, 1, 6, 5, 43, 129,\n 4, 0, 35, 4, 73, 48, 71, 2, 1, 1,\n 4, 66,\n]);\nconst EC_P_256_PARAMS = {\n p: 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn,\n b: 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604bn,\n gx: 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296n,\n gy: 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5n,\n coordinateSize: 32,\n};\nconst EC_P_384_PARAMS = {\n p: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffffn,\n b: 0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aefn,\n gx: 0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7n,\n gy: 0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5fn,\n coordinateSize: 48,\n};\nconst EC_P_521_PARAMS = {\n p: (1n << 521n) - 1n,\n b: 0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00n,\n gx: 0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66n,\n gy: 0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650n,\n coordinateSize: 66,\n};\nfunction mod(a, p) {\n const r = a % p;\n return r >= 0n ? r : r + p;\n}\nfunction modPow(base, exponent, p) {\n let result = 1n;\n let b = mod(base, p);\n let e = exponent;\n while (e > 0n) {\n if ((e & 1n) === 1n) {\n result = mod(result * b, p);\n }\n b = mod(b * b, p);\n e >>= 1n;\n }\n return result;\n}\nfunction modSqrt(rhs, p) {\n // P-256/P-384/P-521 primes satisfy p % 4 == 3.\n const y = modPow(rhs, (p + 1n) >> 2n, p);\n if (mod(y * y, p) !== mod(rhs, p)) {\n throw new Error(\"Invalid ECDH point\");\n }\n return y;\n}\nfunction bytesToBigInt(bytes) {\n let v = 0n;\n for (const b of bytes) {\n v = (v << 8n) | BYTE_TO_BIGINT_256[b];\n }\n return v;\n}\nfunction bigIntToBytes(v, len) {\n const out = new Uint8Array(len);\n let n = v;\n for (let i = len - 1; i >= 0; i--) {\n out[i] = Number(n & 0xffn);\n n >>= 8n;\n }\n if (n !== 0n) {\n throw new Error(\"Invalid coordinate length\");\n }\n return out;\n}\nfunction buildRawUncompressedPublicKey(x, y, coordinateSize) {\n const out = new Uint8Array(1 + coordinateSize * 2);\n out[0] = 0x04;\n out.set(bigIntToBytes(x, coordinateSize), 1);\n out.set(bigIntToBytes(y, coordinateSize), 1 + coordinateSize);\n return out;\n}\nexport class Ec extends NativeAlgorithm {\n constructor(kem, hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // EC specific arguments for deriving key pair.\n Object.defineProperty(this, \"_order\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_bitmask\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_curveParams\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._hkdf = hkdf;\n switch (kem) {\n case KemId.DhkemP256HkdfSha256:\n this._alg = { name: \"ECDH\", namedCurve: \"P-256\" };\n this._nPk = 65;\n this._nSk = 32;\n this._nDh = 32;\n this._order = ORDER_P_256;\n this._bitmask = 0xFF;\n this._pkcs8AlgId = PKCS8_ALG_ID_P_256;\n this._curveParams = EC_P_256_PARAMS;\n break;\n case KemId.DhkemP384HkdfSha384:\n this._alg = { name: \"ECDH\", namedCurve: \"P-384\" };\n this._nPk = 97;\n this._nSk = 48;\n this._nDh = 48;\n this._order = ORDER_P_384;\n this._bitmask = 0xFF;\n this._pkcs8AlgId = PKCS8_ALG_ID_P_384;\n this._curveParams = EC_P_384_PARAMS;\n break;\n default:\n // case KemId.DhkemP521HkdfSha512:\n this._alg = { name: \"ECDH\", namedCurve: \"P-521\" };\n this._nPk = 133;\n this._nSk = 66;\n this._nDh = 66;\n this._order = ORDER_P_521;\n this._bitmask = 0x01;\n this._pkcs8AlgId = PKCS8_ALG_ID_P_521;\n this._curveParams = EC_P_521_PARAMS;\n break;\n }\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(this._alg, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const rawIkm = toArrayBuffer(ikm);\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY, LABEL_DKP_PRK, new Uint8Array(rawIkm));\n const bn = new Bignum(this._nSk);\n for (let counter = 0; bn.isZero() || !bn.lessThan(this._order); counter++) {\n if (counter > 255) {\n throw new Error(\"Faild to derive a key pair\");\n }\n const bytes = new Uint8Array(await this._hkdf.labeledExpand(dkpPrk, LABEL_CANDIDATE, i2Osp(counter, 1), this._nSk));\n bytes[0] = bytes[0] & this._bitmask;\n bn.set(bytes);\n }\n const sk = await this._deserializePkcs8Key(bn.val());\n bn.reset();\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch {\n try {\n // Firefox fails to export JWK from some imported ECDH private keys.\n return await this._derivePublicKeyWithoutJwkExport(key);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n }\n async dh(sk, pk) {\n try {\n await this._setup();\n const bits = await this._api.deriveBits({\n name: \"ECDH\",\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.crv === \"undefined\" || key.crv !== this._alg.namedCurve) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n async _derivePublicKeyWithoutJwkExport(key) {\n const basePointRaw = buildRawUncompressedPublicKey(this._curveParams.gx, this._curveParams.gy, this._curveParams.coordinateSize);\n const basePoint = await this._api.importKey(\"raw\", basePointRaw.buffer, this._alg, true, []);\n const xBytes = new Uint8Array(await this._api.deriveBits({\n name: \"ECDH\",\n public: basePoint,\n }, key, this._nDh * 8));\n const p = this._curveParams.p;\n const x = bytesToBigInt(xBytes);\n const rhs = mod(modPow(x, 3n, p) - 3n * x + this._curveParams.b, p);\n let y = modSqrt(rhs, p);\n // Canonicalize sign so the encoded point is deterministic.\n if ((y & 1n) === 1n) {\n y = p - y;\n }\n const pubRaw = buildRawUncompressedPublicKey(x, y, this._curveParams.coordinateSize);\n return await this._api.importKey(\"raw\", pubRaw.buffer, this._alg, true, []);\n }\n}\n","// deno-lint-ignore-file no-explicit-any\n/**\n * This file is based on noble-curves (https://github.com/paulmillr/noble-curves).\n *\n * noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-curves/blob/b9d49d2b41d550571a0c5be443ecb62109fa3373/src/utils.ts\n */\n/**\n * Hex, bytes and number utilities.\n * @module\n */\nimport { loadCrypto } from \"./misc.js\";\nimport { N_0 } from \"../consts.js\";\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) && a.constructor.name === \"Uint8Array\");\n}\n/** Asserts something is positive integer. */\nexport function anumber(n, title = \"\") {\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new Error(`${prefix}expected integer >0, got ${n}`);\n }\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(value, length, title = \"\") {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : \"\";\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n throw new Error(prefix + \"expected Uint8Array\" + ofLen + \", got \" + got);\n }\n return value;\n}\n// ahash function is now imported from ../hash/hash.ts\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error(\"Hash instance has been destroyed\");\n if (checkFinished && instance.finished) {\n throw new Error(\"Hash#digest() has already been called\");\n }\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out, undefined, \"digestInto() output\");\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n// Used in weierstrass, der\nfunction abignumer(n) {\n if (typeof n === \"bigint\") {\n if (!isPosBig(n))\n throw new Error(\"positive bigint expected, got \" + n);\n }\n else\n anumber(n);\n return n;\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Pre-computed buffer for endianness detection */\nconst _endianTestBuffer = /* @__PURE__ */ new Uint32Array([0x11223344]);\nconst _endianTestBytes = /* @__PURE__ */ new Uint8Array(_endianTestBuffer.buffer);\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ _endianTestBytes[0] === 0x44;\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport function swap8IfBE(n) {\n return isLE ? n : byteSwap(n);\n}\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport function swap32IfBE(u) {\n return isLE ? u : byteSwap32(u);\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore: to use toHex\ntypeof Uint8Array.from([]).toHex === \"function\" &&\n // @ts-ignore: to use fromHex\n typeof Uint8Array.fromHex === \"function\")();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, \"0\"));\nconst HEX_TO_BIGINT = /* @__PURE__ */ [\n 0n,\n 1n,\n 2n,\n 3n,\n 4n,\n 5n,\n 6n,\n 7n,\n 8n,\n 9n,\n 10n,\n 11n,\n 12n,\n 13n,\n 14n,\n 15n,\n];\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore: to use toHex\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = \"\";\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== \"string\") {\n throw new Error(\"hex string expected, got \" + typeof hex);\n }\n // @ts-ignore: to use fromHex\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) {\n throw new Error(\"hex string expected, got unpadded hex of length \" + hl);\n }\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' +\n hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== \"string\")\n throw new Error(\"string expected\");\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\nexport function numberToHexUnpadded(num) {\n const hex = abignumer(num).toString(16);\n return hex.length & 1 ? \"0\" + hex : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== \"string\") {\n throw new Error(\"hex string expected, got \" + typeof hex);\n }\n let out = N_0;\n for (let i = 0; i < hex.length; i++) {\n const n = asciiToBase16(hex.charCodeAt(i));\n if (n === undefined) {\n throw new Error('hex string expected, got non-hex character \"' + hex[i] +\n '\" at index ' + i);\n }\n out = (out << 4n) | HEX_TO_BIGINT[n];\n }\n return out; // Big Endian\n}\nexport function numberToBigint(num) {\n anumber(num, \"numberToBigint\");\n let n = num;\n let out = N_0;\n let bit = 1n;\n while (n > 0) {\n if (n % 2 === 1)\n out += bit;\n n = Math.floor(n / 2);\n bit <<= 1n;\n }\n return out;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n anumber(len);\n n = abignumer(n);\n const res = hexToBytes(n.toString(16).padStart(len * 2, \"0\"));\n if (res.length !== len)\n throw new Error(\"number too large\");\n return res;\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes) {\n return Uint8Array.from(bytes);\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as utf8ToBytes for ASCII or throws.\n */\nexport function asciiToBytes(ascii) {\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new Error(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n }\n return charCode;\n });\n}\n// Is positive bigint\nfunction isPosBig(n) {\n return typeof n === \"bigint\" && N_0 <= n;\n}\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max)) {\n throw new Error(\"expected valid \" + title + \": \" + min + \" <= n < \" + max + \", got \" + n);\n }\n}\nexport function validateObject(object, fields = {}, optFields = {}) {\n if (!object || typeof object !== \"object\") {\n throw new Error(\"expected valid options object\");\n }\n function checkField(fieldName, expectedType, isOpt) {\n const val = object[fieldName];\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null) {\n throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n }\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n// createHasher function is now exported above with ahash\n// /** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\n// export function randomBytes(bytesLength = 32): Uint8Array {\n// const cr = typeof globalThis != null && (globalThis as any).crypto;\n// if (!cr || typeof cr.getRandomValues !== \"function\") {\n// throw new Error(\"crypto.getRandomValues must be defined\");\n// }\n// return cr.getRandomValues(new Uint8Array(bytesLength));\n// }\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport async function randomBytesAsync(bytesLength = 32) {\n const api = await loadCrypto();\n const rnd = new Uint8Array(bytesLength);\n api.getRandomValues(rnd);\n return rnd;\n}\n// 06 09 60 86 48 01 65 03 04 02\nexport function oidNist(suffix) {\n return {\n oid: Uint8Array.from([\n 0x06,\n 0x09,\n 0x60,\n 0x86,\n 0x48,\n 0x01,\n 0x65,\n 0x03,\n 0x04,\n 0x02,\n suffix,\n ]),\n };\n}\n","/**\n * This file is based on noble-curves (https://github.com/paulmillr/noble-curves).\n *\n * noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-curves/blob/b9d49d2b41d550571a0c5be443ecb62109fa3373/src/utils.ts\n */\n/**\n * Hash utilities and type definitions extracted from noble.ts\n * @module\n */\nimport { anumber } from \"../utils/noble.js\";\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== \"function\" || typeof h.create !== \"function\") {\n throw new Error(\"Hash must wrapped by utils.createHasher\");\n }\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\nexport function createHasher(hashCons, info = {}) {\n const hashFn = (msg, opts) => hashCons(opts).update(msg).digest();\n const tmp = hashCons(undefined);\n const hashC = Object.assign(hashFn, {\n outputLen: tmp.outputLen,\n blockLen: tmp.blockLen,\n create: (opts) => hashCons(opts),\n ...info,\n });\n return Object.freeze(hashC);\n}\n","// deno-lint-ignore-file no-explicit-any\n/**\n * This file is based on noble-hashes (https://github.com/paulmillr/noble-hashes).\n *\n * noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-hashes/blob/2e0c00e1aa134082ba1380bf3afb8b1641f60fed/src/hmac.ts\n */\n/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, clean } from \"../utils/noble.js\";\nimport { ahash } from \"./hash.js\";\nexport class _HMAC {\n constructor(hash, key) {\n Object.defineProperty(this, \"oHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"iHash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"blockLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"outputLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"finished\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, \"destroyed\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n ahash(hash);\n abytes(key, undefined, \"key\");\n this.iHash = hash.create();\n if (typeof this.iHash.update !== \"function\") {\n throw new Error(\"Expected instance of class which extends utils.Hash\");\n }\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n abytes(out, this.outputLen, \"output\");\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new _HMAC(hash, key);\n","/**\n * This file is based on noble-hashes (https://github.com/paulmillr/noble-hashes).\n *\n * noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-hashes/blob/4e358a46d682adfb005ae6314ec999f2513086b9/src/_u64.ts\n */\n/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = 0xffffffffn;\nconst _32n = 32n;\nfunction fromBig(n, le = false) {\n if (le) {\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n }\n return {\n h: Number((n >> _32n) & U32_MASK64) | 0,\n l: Number(n & U32_MASK64) | 0,\n };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n const Ah = new Uint32Array(len);\n const Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig, };\n// prettier-ignore\nconst u64 = {\n fromBig,\n split,\n toBig,\n shrSH,\n shrSL,\n rotrSH,\n rotrSL,\n rotrBH,\n rotrBL,\n rotr32H,\n rotr32L,\n rotlSH,\n rotlSL,\n rotlBH,\n rotlBL,\n add,\n add3L,\n add3H,\n add4L,\n add4H,\n add5H,\n add5L,\n};\nexport default u64;\n","/**\n * This file is based on noble-hashes (https://github.com/paulmillr/noble-hashes).\n *\n * noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-hashes/blob/4e358a46d682adfb005ae6314ec999f2513086b9/src/sha3.ts\n */\n/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from \"./u64.js\";\nimport { abytes, aexists, anumber, aoutput, clean, oidNist, swap32IfBE, u32, } from \"../utils/noble.js\";\nimport { createHasher, } from \"./hash.js\";\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = 0n;\nconst _1n = 1n;\nconst _2n = 2n;\nconst _7n = 7n;\nconst _256n = 256n;\nconst _0x71n = 0x71n;\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = []; // no pure annotation: var is always used\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s, rounds = 24, B) {\n if (!B)\n B = new Uint32Array(10);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++) {\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n }\n // for (let x = 0; x < 10; x += 2) {\n // const idx1 = (x + 8) % 10;\n // const idx0 = (x + 2) % 10;\n // const B0 = B[idx0];\n // const B1 = B[idx0 + 1];\n // const Th = rotlH(B0, B1, 1) ^ B[idx1];\n // const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n // for (let y = 0; y < 50; y += 10) {\n // s[x + y] ^= Th;\n // s[x + y + 1] ^= Tl;\n // }\n // }\n { // x=0: idx0=2, idx1=8\n const Th = rotlH(B[2], B[3], 1) ^ B[8];\n const Tl = rotlL(B[2], B[3], 1) ^ B[9];\n s[0] ^= Th;\n s[1] ^= Tl;\n s[10] ^= Th;\n s[11] ^= Tl;\n s[20] ^= Th;\n s[21] ^= Tl;\n s[30] ^= Th;\n s[31] ^= Tl;\n s[40] ^= Th;\n s[41] ^= Tl;\n }\n { // x=2: idx0=4, idx1=0\n const Th = rotlH(B[4], B[5], 1) ^ B[0];\n const Tl = rotlL(B[4], B[5], 1) ^ B[1];\n s[2] ^= Th;\n s[3] ^= Tl;\n s[12] ^= Th;\n s[13] ^= Tl;\n s[22] ^= Th;\n s[23] ^= Tl;\n s[32] ^= Th;\n s[33] ^= Tl;\n s[42] ^= Th;\n s[43] ^= Tl;\n }\n { // x=4: idx0=6, idx1=2\n const Th = rotlH(B[6], B[7], 1) ^ B[2];\n const Tl = rotlL(B[6], B[7], 1) ^ B[3];\n s[4] ^= Th;\n s[5] ^= Tl;\n s[14] ^= Th;\n s[15] ^= Tl;\n s[24] ^= Th;\n s[25] ^= Tl;\n s[34] ^= Th;\n s[35] ^= Tl;\n s[44] ^= Th;\n s[45] ^= Tl;\n }\n { // x=6: idx0=8, idx1=4\n const Th = rotlH(B[8], B[9], 1) ^ B[4];\n const Tl = rotlL(B[8], B[9], 1) ^ B[5];\n s[6] ^= Th;\n s[7] ^= Tl;\n s[16] ^= Th;\n s[17] ^= Tl;\n s[26] ^= Th;\n s[27] ^= Tl;\n s[36] ^= Th;\n s[37] ^= Tl;\n s[46] ^= Th;\n s[47] ^= Tl;\n }\n { // x=8: idx0=0, idx1=6\n const Th = rotlH(B[0], B[1], 1) ^ B[6];\n const Tl = rotlL(B[0], B[1], 1) ^ B[7];\n s[8] ^= Th;\n s[9] ^= Tl;\n s[18] ^= Th;\n s[19] ^= Tl;\n s[28] ^= Th;\n s[29] ^= Tl;\n s[38] ^= Th;\n s[39] ^= Tl;\n s[48] ^= Th;\n s[49] ^= Tl;\n }\n // Rho (ρ) and Pi (π) — fully unrolled\n let curH = s[2];\n let curL = s[3];\n // for (let t = 0; t < 24; t++) {\n // const shift = SHA3_ROTL[t];\n // const Th = rotlH(curH, curL, shift);\n // const Tl = rotlL(curH, curL, shift);\n // const PI = SHA3_PI[t];\n // curH = s[PI];\n // curL = s[PI + 1];\n // s[PI] = Th;\n // s[PI + 1] = Tl;\n // }\n let Th, Tl;\n // t=0: shift=1(S), PI=20\n Th = rotlSH(curH, curL, 1);\n Tl = rotlSL(curH, curL, 1);\n curH = s[20];\n curL = s[21];\n s[20] = Th;\n s[21] = Tl;\n // t=1: shift=3(S), PI=14\n Th = rotlSH(curH, curL, 3);\n Tl = rotlSL(curH, curL, 3);\n curH = s[14];\n curL = s[15];\n s[14] = Th;\n s[15] = Tl;\n // t=2: shift=6(S), PI=22\n Th = rotlSH(curH, curL, 6);\n Tl = rotlSL(curH, curL, 6);\n curH = s[22];\n curL = s[23];\n s[22] = Th;\n s[23] = Tl;\n // t=3: shift=10(S), PI=34\n Th = rotlSH(curH, curL, 10);\n Tl = rotlSL(curH, curL, 10);\n curH = s[34];\n curL = s[35];\n s[34] = Th;\n s[35] = Tl;\n // t=4: shift=15(S), PI=36\n Th = rotlSH(curH, curL, 15);\n Tl = rotlSL(curH, curL, 15);\n curH = s[36];\n curL = s[37];\n s[36] = Th;\n s[37] = Tl;\n // t=5: shift=21(S), PI=6\n Th = rotlSH(curH, curL, 21);\n Tl = rotlSL(curH, curL, 21);\n curH = s[6];\n curL = s[7];\n s[6] = Th;\n s[7] = Tl;\n // t=6: shift=28(S), PI=10\n Th = rotlSH(curH, curL, 28);\n Tl = rotlSL(curH, curL, 28);\n curH = s[10];\n curL = s[11];\n s[10] = Th;\n s[11] = Tl;\n // t=7: shift=36(B), PI=32\n Th = rotlBH(curH, curL, 36);\n Tl = rotlBL(curH, curL, 36);\n curH = s[32];\n curL = s[33];\n s[32] = Th;\n s[33] = Tl;\n // t=8: shift=45(B), PI=16\n Th = rotlBH(curH, curL, 45);\n Tl = rotlBL(curH, curL, 45);\n curH = s[16];\n curL = s[17];\n s[16] = Th;\n s[17] = Tl;\n // t=9: shift=55(B), PI=42\n Th = rotlBH(curH, curL, 55);\n Tl = rotlBL(curH, curL, 55);\n curH = s[42];\n curL = s[43];\n s[42] = Th;\n s[43] = Tl;\n // t=10: shift=2(S), PI=48\n Th = rotlSH(curH, curL, 2);\n Tl = rotlSL(curH, curL, 2);\n curH = s[48];\n curL = s[49];\n s[48] = Th;\n s[49] = Tl;\n // t=11: shift=14(S), PI=8\n Th = rotlSH(curH, curL, 14);\n Tl = rotlSL(curH, curL, 14);\n curH = s[8];\n curL = s[9];\n s[8] = Th;\n s[9] = Tl;\n // t=12: shift=27(S), PI=30\n Th = rotlSH(curH, curL, 27);\n Tl = rotlSL(curH, curL, 27);\n curH = s[30];\n curL = s[31];\n s[30] = Th;\n s[31] = Tl;\n // t=13: shift=41(B), PI=46\n Th = rotlBH(curH, curL, 41);\n Tl = rotlBL(curH, curL, 41);\n curH = s[46];\n curL = s[47];\n s[46] = Th;\n s[47] = Tl;\n // t=14: shift=56(B), PI=38\n Th = rotlBH(curH, curL, 56);\n Tl = rotlBL(curH, curL, 56);\n curH = s[38];\n curL = s[39];\n s[38] = Th;\n s[39] = Tl;\n // t=15: shift=8(S), PI=26\n Th = rotlSH(curH, curL, 8);\n Tl = rotlSL(curH, curL, 8);\n curH = s[26];\n curL = s[27];\n s[26] = Th;\n s[27] = Tl;\n // t=16: shift=25(S), PI=24\n Th = rotlSH(curH, curL, 25);\n Tl = rotlSL(curH, curL, 25);\n curH = s[24];\n curL = s[25];\n s[24] = Th;\n s[25] = Tl;\n // t=17: shift=43(B), PI=4\n Th = rotlBH(curH, curL, 43);\n Tl = rotlBL(curH, curL, 43);\n curH = s[4];\n curL = s[5];\n s[4] = Th;\n s[5] = Tl;\n // t=18: shift=62(B), PI=40\n Th = rotlBH(curH, curL, 62);\n Tl = rotlBL(curH, curL, 62);\n curH = s[40];\n curL = s[41];\n s[40] = Th;\n s[41] = Tl;\n // t=19: shift=18(S), PI=28\n Th = rotlSH(curH, curL, 18);\n Tl = rotlSL(curH, curL, 18);\n curH = s[28];\n curL = s[29];\n s[28] = Th;\n s[29] = Tl;\n // t=20: shift=39(B), PI=44\n Th = rotlBH(curH, curL, 39);\n Tl = rotlBL(curH, curL, 39);\n curH = s[44];\n curL = s[45];\n s[44] = Th;\n s[45] = Tl;\n // t=21: shift=61(B), PI=18\n Th = rotlBH(curH, curL, 61);\n Tl = rotlBL(curH, curL, 61);\n curH = s[18];\n curL = s[19];\n s[18] = Th;\n s[19] = Tl;\n // t=22: shift=20(S), PI=12\n Th = rotlSH(curH, curL, 20);\n Tl = rotlSL(curH, curL, 20);\n curH = s[12];\n curL = s[13];\n s[12] = Th;\n s[13] = Tl;\n // t=23: shift=44(B), PI=2\n Th = rotlBH(curH, curL, 44);\n Tl = rotlBL(curH, curL, 44);\n s[2] = Th;\n s[3] = Tl;\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n B[0] = s[y];\n B[1] = s[y + 1];\n B[2] = s[y + 2];\n B[3] = s[y + 3];\n B[4] = s[y + 4];\n B[5] = s[y + 5];\n B[6] = s[y + 6];\n B[7] = s[y + 7];\n B[8] = s[y + 8];\n B[9] = s[y + 9];\n s[y + 0] ^= ~B[2] & B[4];\n s[y + 1] ^= ~B[3] & B[5];\n s[y + 2] ^= ~B[4] & B[6];\n s[y + 3] ^= ~B[5] & B[7];\n s[y + 4] ^= ~B[6] & B[8];\n s[y + 5] ^= ~B[7] & B[9];\n s[y + 6] ^= ~B[8] & B[0];\n s[y + 7] ^= ~B[9] & B[1];\n s[y + 8] ^= ~B[0] & B[2];\n s[y + 9] ^= ~B[1] & B[3];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n}\n/** Keccak sponge function. */\nexport class Keccak {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n Object.defineProperty(this, \"state\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"pos\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"posOut\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"finished\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, \"state32\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"destroyed\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, \"_B\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint32Array(10)\n });\n Object.defineProperty(this, \"blockLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"suffix\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"outputLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"enableXOF\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(this, \"rounds\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen, \"outputLen\");\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200)) {\n throw new Error(\"only keccak-f1600 function is supported\");\n }\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone() {\n return this._cloneInto();\n }\n /** Resets instance to initial (empty) state for reuse. */\n reset() {\n this.state.fill(0);\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n }\n keccak() {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds, this._B);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n abytes(data);\n return this.updateUnsafe(data);\n }\n /** Like update(), but skips validation. Caller must ensure valid state and input. */\n updateUnsafe(data) {\n const { blockLen, state } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n return this.writeIntoUnsafe(out);\n }\n /** Like writeInto(), but skips validation. Caller must ensure valid state and output. */\n writeIntoUnsafe(out) {\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF) {\n throw new Error(\"XOF is not possible for this instance\");\n }\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error(\"digest() was already called\");\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);\n// /** SHA3-224 hash function. */\n// export const sha3_224: CHash = /* @__PURE__ */ genKeccak(\n// 0x06,\n// 144,\n// 28,\n// /* @__PURE__ */ oidNist(0x07),\n// );\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256 = /* @__PURE__ */ genKeccak(0x06, 136, 32, \n/* @__PURE__ */ oidNist(0x08));\n/** SHA3-384 hash function. */\nexport const sha3_384 = /* @__PURE__ */ genKeccak(0x06, 104, 48, \n/* @__PURE__ */ oidNist(0x09));\n/** SHA3-512 hash function. */\nexport const sha3_512 = /* @__PURE__ */ genKeccak(0x06, 72, 64, \n/* @__PURE__ */ oidNist(0x0a));\n/** keccak-224 hash function. */\nexport const keccak_224 = /* @__PURE__ */ genKeccak(0x01, 144, 28);\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256 = /* @__PURE__ */ genKeccak(0x01, 136, 32);\n/** keccak-384 hash function. */\nexport const keccak_384 = /* @__PURE__ */ genKeccak(0x01, 104, 48);\n/** keccak-512 hash function. */\nexport const keccak_512 = /* @__PURE__ */ genKeccak(0x01, 72, 64);\nconst genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true), info);\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b));\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c));\n// /** SHAKE128 XOF with 256-bit output (NIST version). */\n// export const shake128_32: CHashXOF<Keccak, ShakeOpts> =\n// /* @__PURE__ */\n// genShake(0x1f, 168, 32, /* @__PURE__ */ oidNist(0x0b));\n// /** SHAKE256 XOF with 512-bit output (NIST version). */\n// export const shake256_64: CHashXOF<Keccak, ShakeOpts> =\n// /* @__PURE__ */\n// genShake(0x1f, 136, 64, /* @__PURE__ */ oidNist(0x0c));\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/utils.ts\n */\n/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\nimport { abytes, aexists, anumber, aoutput, clean, copyBytes, createView, isLE, numberToBigint, u32, } from \"@hpke/common\";\nexport { abytes, aexists, anumber, aoutput, clean, copyBytes, createView, isLE, u32, };\n/** Asserts something is boolean. */\nexport function abool(b) {\n if (typeof b !== \"boolean\")\n throw new Error(`boolean expected, not ${b}`);\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Wraps a cipher: validates args, ensures encrypt() can only be called once.\n * @__NO_SIDE_EFFECTS__\n */\n// deno-lint-ignore no-explicit-any\nexport const wrapCipher = (params, constructor) => {\n // deno-lint-ignore no-explicit-any\n function wrappedCipher(key, ...args) {\n // Validate key\n abytes(key, undefined, \"key\");\n // Big-Endian hardware is rare. Just in case someone still decides to run ciphers:\n if (!isLE) {\n throw new Error(\"Non little-endian hardware is not yet supported\");\n }\n // Validate nonce if nonceLength is present\n if (params.nonceLength !== undefined) {\n const nonce = args[0];\n abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, \"nonce\");\n }\n // Validate AAD if tagLength present\n const tagl = params.tagLength;\n if (tagl && args[1] !== undefined)\n abytes(args[1], undefined, \"AAD\");\n const cipher = constructor(key, ...args);\n const checkOutput = (fnLength, output) => {\n if (output !== undefined) {\n if (fnLength !== 2)\n throw new Error(\"cipher output not supported\");\n abytes(output, undefined, \"output\");\n }\n };\n // Create wrapped cipher with validation and single-use encryption\n let called = false;\n const wrCipher = {\n encrypt(data, output) {\n if (called) {\n throw new Error(\"cannot encrypt() twice with same key + nonce\");\n }\n called = true;\n abytes(data);\n checkOutput(cipher.encrypt.length, output);\n return cipher.encrypt(data, output);\n },\n decrypt(data, output) {\n abytes(data);\n if (tagl && data.length < tagl) {\n throw new Error('\"ciphertext\" expected length bigger than tagLength=' + tagl);\n }\n checkOutput(cipher.decrypt.length, output);\n return cipher.decrypt(data, output);\n },\n };\n return wrCipher;\n }\n Object.assign(wrappedCipher, params);\n return wrappedCipher;\n};\nexport function checkOpts(defaults, opts) {\n if (opts == null || typeof opts !== \"object\") {\n throw new Error(\"options must be defined\");\n }\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** Compares 2 uint8array-s in kinda constant time. */\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * By default, returns u8a of length.\n * When out is available, it checks it for validity and uses it.\n */\nexport function getOutput(expectedLength, out, onlyAligned = true) {\n if (out === undefined)\n return new Uint8Array(expectedLength);\n if (out.length !== expectedLength) {\n throw new Error('\"output\" expected Uint8Array of length ' + expectedLength + \", got: \" +\n out.length);\n }\n if (onlyAligned && !isAligned32(out)) {\n throw new Error(\"invalid output, must be aligned\");\n }\n return out;\n}\nexport function u64Lengths(dataLength, aadLength, isLE) {\n abool(isLE);\n const num = new Uint8Array(16);\n const view = createView(num);\n view.setBigUint64(0, numberToBigint(aadLength), isLE);\n view.setBigUint64(8, numberToBigint(dataLength), isLE);\n return num;\n}\n// Is byte array aligned to 4 byte offset (u32)?\nexport function isAligned32(bytes) {\n return bytes.byteOffset % 4 === 0;\n}\n// copy bytes to new u8a (aligned). Because Buffer.slice is broken.\n// Re-exported from @hpke/common.\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/_arx.ts\n */\n/**\n * Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\n\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n const counter = new Uint8Array(4);\n chacha(..., counter, ...); // counter is now 1\n chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | cnt(1) | nonce(3)\n chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).\n\n[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/\n[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2\n\n * @module\n */\nimport { abool, abytes, anumber, checkOpts, clean, copyBytes, u32, } from \"./utils.js\";\n// Can't use similar utils.utf8ToBytes, because it uses `TextEncoder` - not available in all envs\nconst _utf8ToBytes = (str) => Uint8Array.from(str.split(\"\").map((c) => c.charCodeAt(0)));\nconst sigma16 = _utf8ToBytes(\"expand 16-byte k\");\nconst sigma32 = _utf8ToBytes(\"expand 32-byte k\");\nconst sigma16_32 = u32(sigma16);\nconst sigma32_32 = u32(sigma32);\n/** Rotate left. */\nexport function rotl(a, b) {\n return (a << b) | (a >>> (32 - b));\n}\n// Is byte array aligned to 4 byte offset (u32)?\nfunction isAligned32(b) {\n return b.byteOffset % 4 === 0;\n}\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\nconst BLOCK_LEN32 = 16;\n// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ]\n// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ]\nconst MAX_COUNTER = 2 ** 32 - 1;\nconst U32_EMPTY = Uint32Array.of();\nfunction runCipher(core, sigma, key, nonce, data, output, counter, rounds) {\n const len = data.length;\n const block = new Uint8Array(BLOCK_LEN);\n const b32 = u32(block);\n // Make sure that buffers aligned to 4 bytes\n const isAligned = isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n if (counter >= MAX_COUNTER)\n throw new Error(\"arx: counter overflow\");\n const take = Math.min(BLOCK_LEN, len - pos);\n // aligned to 4 bytes\n if (isAligned && take === BLOCK_LEN) {\n const pos32 = pos / 4;\n if (pos % 4 !== 0)\n throw new Error(\"arx: invalid block position\");\n for (let j = 0, posj; j < BLOCK_LEN32; j++) {\n posj = pos32 + j;\n o32[posj] = d32[posj] ^ b32[j];\n }\n pos += BLOCK_LEN;\n continue;\n }\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n}\n/** Creates ARX-like (ChaCha, Salsa) cipher stream from core function. */\nexport function createCipher(core, opts) {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({\n allowShortKeys: false,\n counterLength: 8,\n counterRight: false,\n rounds: 20,\n }, opts);\n if (typeof core !== \"function\")\n throw new Error(\"core must be a function\");\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (key, nonce, data, output, counter = 0) => {\n abytes(key, undefined, \"key\");\n abytes(nonce, undefined, \"nonce\");\n abytes(data, undefined, \"data\");\n const len = data.length;\n if (output === undefined)\n output = new Uint8Array(len);\n abytes(output, undefined, \"output\");\n anumber(counter);\n if (counter < 0 || counter >= MAX_COUNTER) {\n throw new Error(\"arx: counter overflow\");\n }\n if (output.length < len) {\n throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);\n }\n const toClean = [];\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n const l = key.length;\n let k;\n let sigma;\n if (l === 32) {\n toClean.push(k = copyBytes(key));\n sigma = sigma32_32;\n }\n else if (l === 16 && allowShortKeys) {\n k = new Uint8Array(32);\n k.set(key);\n k.set(key, 16);\n sigma = sigma16_32;\n toClean.push(k);\n }\n else {\n abytes(key, 32, \"arx key\");\n throw new Error(\"invalid key size\");\n // throw new Error(`\"arx key\" expected Uint8Array of length 32, got length=${l}`);\n }\n // Nonce\n // salsa20: 8 (8-byte counter)\n // chacha20orig: 8 (8-byte counter)\n // chacha20: 12 (4-byte counter)\n // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)\n // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)\n // Align nonce to 4 bytes\n if (!isAligned32(nonce))\n toClean.push(nonce = copyBytes(nonce));\n const k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24) {\n throw new Error(`arx: extended nonce must be 24 bytes`);\n }\n extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);\n nonce = nonce.subarray(16);\n }\n // Handle nonce counter\n const nonceNcLen = 16 - counterLength;\n if (nonceNcLen !== nonce.length) {\n throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n }\n // Pad counter when nonce is 64 bit\n if (nonceNcLen !== 12) {\n const nc = new Uint8Array(12);\n nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n nonce = nc;\n toClean.push(nonce);\n }\n const n32 = u32(nonce);\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n clean(...toClean);\n return output;\n };\n}\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/_poly1305.ts\n */\n/**\n * Poly1305 ([PDF](https://cr.yp.to/mac/poly1305-20050329.pdf),\n * [wiki](https://en.wikipedia.org/wiki/Poly1305))\n * is a fast and parallel secret-key message-authentication code suitable for\n * a wide variety of applications. It was standardized in\n * [RFC 8439](https://www.rfc-editor.org/rfc/rfc8439) and is now used in TLS 1.3.\n *\n * Polynomial MACs are not perfect for every situation:\n * they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.\n * See [invisible salamanders attack](https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/).\n * To combat invisible salamanders, `hash(key)` can be included in ciphertext,\n * however, this would violate ciphertext indistinguishability:\n * an attacker would know which key was used - so `HKDF(key, i)`\n * could be used instead.\n *\n * Check out [original website](https://cr.yp.to/mac.html).\n * Based on Public Domain [poly1305-donna](https://github.com/floodyberry/poly1305-donna).\n * @module\n */\nimport { abytes, aexists, aoutput, clean, copyBytes, } from \"./utils.js\";\nfunction u8to16(a, i) {\n return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\n}\n// function bytesToNumberLE(bytes: Uint8Array): bigint {\n// return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n// }\n// /** Small version of `poly1305` without loop unrolling. Unused, provided for auditability. */\n// function poly1305_small(msg: Uint8Array, key: Uint8Array): Uint8Array {\n// abytes(msg);\n// abytes(key, 32, \"key\");\n// const POW_2_130_5 = 2n ** 130n - 5n; // 2^130-5\n// const POW_2_128_1 = 2n ** 128n - 1n; // 2^128-1\n// const CLAMP_R = 0x0ffffffc0ffffffc0ffffffc0fffffffn;\n// const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R;\n// const s = bytesToNumberLE(key.subarray(16));\n// // Process by 16 byte chunks\n// let acc = 0n;\n// for (let i = 0; i < msg.length; i += 16) {\n// const m = msg.subarray(i, i + 16);\n// const n = bytesToNumberLE(m) | (1n << (8n * mLen)); // mLen: bigint\n// acc = ((acc + n) * r) % POW_2_130_5;\n// }\n// const res = (acc + s) & POW_2_128_1;\n// return numberToBytesBE(res, 16).reverse(); // LE\n// }\n// Can be used to replace `computeTag` in chacha.ts. Unused, provided for auditability.\n// function poly1305_computeTag_small(\n// authKey: Uint8Array,\n// lengths: Uint8Array,\n// ciphertext: Uint8Array,\n// AAD?: Uint8Array,\n// ): Uint8Array {\n// const res = [];\n// const updatePadded2 = (msg: Uint8Array) => {\n// res.push(msg);\n// const leftover = msg.length % 16;\n// if (leftover) res.push(new Uint8Array(16).slice(leftover));\n// };\n// if (AAD) updatePadded2(AAD);\n// updatePadded2(ciphertext);\n// res.push(lengths);\n// return poly1305_small(concatBytes(...res), authKey);\n// }\n/** Poly1305 class. Prefer poly1305() function instead. */\nexport class Poly1305 {\n // Can be speed-up using BigUint64Array, at the cost of complexity\n constructor(key) {\n Object.defineProperty(this, \"blockLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 16\n });\n Object.defineProperty(this, \"outputLen\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 16\n });\n Object.defineProperty(this, \"buffer\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint8Array(16)\n });\n Object.defineProperty(this, \"r\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint16Array(10)\n }); // Allocating 1 array with .subarray() here is slower than 3\n Object.defineProperty(this, \"h\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint16Array(10)\n });\n Object.defineProperty(this, \"pad\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: new Uint16Array(8)\n });\n Object.defineProperty(this, \"pos\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, \"finished\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n key = copyBytes(abytes(key, 32, \"key\"));\n const t0 = u8to16(key, 0);\n const t1 = u8to16(key, 2);\n const t2 = u8to16(key, 4);\n const t3 = u8to16(key, 6);\n const t4 = u8to16(key, 8);\n const t5 = u8to16(key, 10);\n const t6 = u8to16(key, 12);\n const t7 = u8to16(key, 14);\n // https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47\n this.r[0] = t0 & 0x1fff;\n this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = (t4 >>> 1) & 0x1ffe;\n this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = (t7 >>> 5) & 0x007f;\n for (let i = 0; i < 8; i++)\n this.pad[i] = u8to16(key, 16 + 2 * i);\n }\n process(data, offset, isLast = false) {\n const hibit = isLast ? 0 : 1 << 11;\n const { h, r } = this;\n const r0 = r[0];\n const r1 = r[1];\n const r2 = r[2];\n const r3 = r[3];\n const r4 = r[4];\n const r5 = r[5];\n const r6 = r[6];\n const r7 = r[7];\n const r8 = r[8];\n const r9 = r[9];\n const t0 = u8to16(data, offset + 0);\n const t1 = u8to16(data, offset + 2);\n const t2 = u8to16(data, offset + 4);\n const t3 = u8to16(data, offset + 6);\n const t4 = u8to16(data, offset + 8);\n const t5 = u8to16(data, offset + 10);\n const t6 = u8to16(data, offset + 12);\n const t7 = u8to16(data, offset + 14);\n const h0 = h[0] + (t0 & 0x1fff);\n const h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n const h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n const h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n const h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n const h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n const h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n const h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n const h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n const h9 = h[9] + ((t7 >>> 5) | hibit);\n let c = 0;\n let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) +\n h4 * (5 * r6);\n c = d0 >>> 13;\n d0 &= 0x1fff;\n d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) +\n h9 * (5 * r1);\n c += d0 >>> 13;\n d0 &= 0x1fff;\n let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) +\n h4 * (5 * r7);\n c = d1 >>> 13;\n d1 &= 0x1fff;\n d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) +\n h9 * (5 * r2);\n c += d1 >>> 13;\n d1 &= 0x1fff;\n let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n c = d2 >>> 13;\n d2 &= 0x1fff;\n d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) +\n h9 * (5 * r3);\n c += d2 >>> 13;\n d2 &= 0x1fff;\n let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n c = d3 >>> 13;\n d3 &= 0x1fff;\n d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) +\n h9 * (5 * r4);\n c += d3 >>> 13;\n d3 &= 0x1fff;\n let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n c = d4 >>> 13;\n d4 &= 0x1fff;\n d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) +\n h9 * (5 * r5);\n c += d4 >>> 13;\n d4 &= 0x1fff;\n let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n c = d5 >>> 13;\n d5 &= 0x1fff;\n d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) +\n h9 * (5 * r6);\n c += d5 >>> 13;\n d5 &= 0x1fff;\n let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n c = d6 >>> 13;\n d6 &= 0x1fff;\n d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n c += d6 >>> 13;\n d6 &= 0x1fff;\n let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n c = d7 >>> 13;\n d7 &= 0x1fff;\n d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n c += d7 >>> 13;\n d7 &= 0x1fff;\n let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n c = d8 >>> 13;\n d8 &= 0x1fff;\n d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n c += d8 >>> 13;\n d8 &= 0x1fff;\n let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n c = d9 >>> 13;\n d9 &= 0x1fff;\n d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n c += d9 >>> 13;\n d9 &= 0x1fff;\n c = ((c << 2) + c) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = c >>> 13;\n d1 += c;\n h[0] = d0;\n h[1] = d1;\n h[2] = d2;\n h[3] = d3;\n h[4] = d4;\n h[5] = d5;\n h[6] = d6;\n h[7] = d7;\n h[8] = d8;\n h[9] = d9;\n }\n finalize() {\n const { h, pad } = this;\n const g = new Uint16Array(10);\n let c = h[1] >>> 13;\n h[1] &= 0x1fff;\n for (let i = 2; i < 10; i++) {\n h[i] += c;\n c = h[i] >>> 13;\n h[i] &= 0x1fff;\n }\n h[0] += c * 5;\n c = h[0] >>> 13;\n h[0] &= 0x1fff;\n h[1] += c;\n c = h[1] >>> 13;\n h[1] &= 0x1fff;\n h[2] += c;\n g[0] = h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (let i = 1; i < 10; i++) {\n g[i] = h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= 1 << 13;\n let mask = (c ^ 1) - 1;\n for (let i = 0; i < 10; i++)\n g[i] &= mask;\n mask = ~mask;\n for (let i = 0; i < 10; i++)\n h[i] = (h[i] & mask) | g[i];\n h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n let f = h[0] + pad[0];\n h[0] = f & 0xffff;\n for (let i = 1; i < 8; i++) {\n f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n h[i] = f & 0xffff;\n }\n clean(g);\n }\n update(data) {\n aexists(this);\n abytes(data);\n data = copyBytes(data);\n const { buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input\n if (take === blockLen) {\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(data, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(buffer, 0, false);\n this.pos = 0;\n }\n }\n return this;\n }\n destroy() {\n clean(this.h, this.r, this.buffer, this.pad);\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, h } = this;\n let { pos } = this;\n if (pos) {\n buffer[pos++] = 1;\n for (; pos < 16; pos++)\n buffer[pos] = 0;\n this.process(buffer, 0, true);\n }\n this.finalize();\n let opos = 0;\n for (let i = 0; i < 8; i++) {\n out[opos++] = h[i] >>> 0;\n out[opos++] = h[i] >>> 8;\n }\n return out;\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n}\nexport function wrapConstructorWithKey(hashCons) {\n const hashC = (msg, key) => hashCons(key).update(msg).digest();\n const tmp = hashCons(new Uint8Array(32)); // tmp array, used just once below\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key) => hashCons(key);\n return hashC;\n}\n/** Poly1305 MAC from RFC 8439. */\nexport const poly1305 = \n/** @__PURE__ */ (() => wrapConstructorWithKey((key) => new Poly1305(key)))();\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/chacha.ts\n */\n/**\n * ChaCha stream cipher, released\n * in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.\n * It was standardized in [RFC 8439](https://www.rfc-editor.org/rfc/rfc8439) and\n * is now used in TLS 1.3.\n *\n * [XChaCha20](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha)\n * extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with\n * randomly-generated nonces.\n *\n * Check out [PDF](http://cr.yp.to/chacha/chacha-20080128.pdf) and\n * [wiki](https://en.wikipedia.org/wiki/Salsa20) and\n * [website](https://cr.yp.to/chacha.html).\n *\n * @module\n */\nimport { createCipher, rotl } from \"./_arx.js\";\nimport { poly1305 } from \"./_poly1305.js\";\nimport { abytes, clean, equalBytes, getOutput, u64Lengths, wrapCipher, } from \"./utils.js\";\n/**\n * ChaCha core function. It is implemented twice:\n * 1. Simple loop (chachaCore_small, hchacha_small)\n * 2. Unrolled loop (chachaCore, hchacha) - 4x faster, but larger & harder to read\n * The specific implementation is selected in `createCipher` below.\n */\nfunction chachaCore(s, k, n, out, cnt, rounds = 20) {\n const y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key\n y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key\n y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Counter\tNonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 7);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 7);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 7);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 8);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 7);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 7);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 7);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 7);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 16);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 7);\n }\n // Write output\n let oi = 0;\n out[oi++] = (y00 + x00) | 0;\n out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0;\n out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0;\n out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0;\n out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0;\n out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0;\n out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0;\n out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0;\n out[oi++] = (y15 + x15) | 0;\n}\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.\n */\nexport const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// Pad to digest size with zeros\nconst updatePadded = (h, msg) => {\n h.update(msg);\n const leftover = msg.length % 16;\n if (leftover)\n h.update(ZEROS16.subarray(leftover));\n};\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(fn, key, nonce, ciphertext, AAD) {\n if (AAD !== undefined)\n abytes(AAD, undefined, \"AAD\");\n const authKey = fn(key, nonce, ZEROS32);\n const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);\n // Methods below can be replaced with\n // return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD)\n const h = poly1305.create(authKey);\n if (AAD)\n updatePadded(h, AAD);\n updatePadded(h, ciphertext);\n h.update(lengths);\n const res = h.digest();\n clean(authKey, lengths);\n return res;\n}\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them, but it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead = (xorStream) => (key, nonce, AAD) => {\n const tagLength = 16;\n return {\n encrypt(plaintext, output) {\n const plength = plaintext.length;\n output = getOutput(plength + tagLength, output, false);\n output.set(plaintext);\n const oPlain = output.subarray(0, -tagLength);\n // Actual encryption\n xorStream(key, nonce, oPlain, oPlain, 1);\n const tag = computeTag(xorStream, key, nonce, oPlain, AAD);\n output.set(tag, plength); // append tag\n clean(tag);\n return output;\n },\n decrypt(ciphertext, output) {\n output = getOutput(ciphertext.length - tagLength, output, false);\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n if (!equalBytes(passedTag, tag))\n throw new Error(\"invalid tag\");\n output.set(ciphertext.subarray(0, -tagLength));\n // Actual decryption\n xorStream(key, nonce, output, output, 1); // start stream with i=1\n clean(tag);\n return output;\n },\n };\n};\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n *\n * Unsafe to use random nonces under the same key, due to collision chance.\n * Prefer XChaCha instead.\n */\nexport const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, _poly1305_aead(chacha20));\n","import { ExportError, INPUT_LENGTH_LIMIT, InvalidParamError, toArrayBuffer, } from \"@hpke/common\";\nimport { emitNotSupported } from \"./utils/emitNotSupported.js\";\n// b\"sec\"\nconst LABEL_SEC = new Uint8Array([115, 101, 99]);\nexport class ExporterContextImpl {\n constructor(api, kdf, exporterSecret) {\n Object.defineProperty(this, \"_api\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"exporterSecret\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_kdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._api = api;\n this._kdf = kdf;\n this.exporterSecret = exporterSecret;\n }\n async seal(_data, _aad) {\n return await emitNotSupported();\n }\n async open(_data, _aad) {\n return await emitNotSupported();\n }\n async export(exporterContext, len) {\n const rawExporterContext = toArrayBuffer(exporterContext);\n if (rawExporterContext.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long exporter context\");\n }\n try {\n return await this._kdf.labeledExpand(this.exporterSecret, LABEL_SEC, new Uint8Array(rawExporterContext), len);\n }\n catch (e) {\n throw new ExportError(e);\n }\n }\n}\nexport class RecipientExporterContextImpl extends ExporterContextImpl {\n}\nexport class SenderExporterContextImpl extends ExporterContextImpl {\n constructor(api, kdf, exporterSecret, enc) {\n super(api, kdf, exporterSecret);\n Object.defineProperty(this, \"enc\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.enc = enc;\n return;\n }\n}\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _Mutex_locked;\nexport class Mutex {\n constructor() {\n _Mutex_locked.set(this, Promise.resolve());\n }\n async lock() {\n let releaseLock;\n const nextLock = new Promise((resolve) => {\n releaseLock = resolve;\n });\n const previousLock = __classPrivateFieldGet(this, _Mutex_locked, \"f\");\n __classPrivateFieldSet(this, _Mutex_locked, nextLock, \"f\");\n await previousLock;\n return releaseLock;\n }\n}\n_Mutex_locked = new WeakMap();\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _RecipientContextImpl_mutex;\nimport { EMPTY, OpenError, toArrayBuffer } from \"@hpke/common\";\nimport { EncryptionContextImpl } from \"./encryptionContext.js\";\nimport { Mutex } from \"./mutex.js\";\nexport class RecipientContextImpl extends EncryptionContextImpl {\n constructor() {\n super(...arguments);\n _RecipientContextImpl_mutex.set(this, void 0);\n }\n async open(data, aad = EMPTY.buffer) {\n __classPrivateFieldSet(this, _RecipientContextImpl_mutex, __classPrivateFieldGet(this, _RecipientContextImpl_mutex, \"f\") ?? new Mutex(), \"f\");\n const release = await __classPrivateFieldGet(this, _RecipientContextImpl_mutex, \"f\").lock();\n let pt;\n try {\n pt = await this._ctx.key.open(this.computeNonce(this._ctx), toArrayBuffer(data), toArrayBuffer(aad));\n }\n catch (e) {\n throw new OpenError(e);\n }\n finally {\n release();\n }\n this.incrementSeq(this._ctx);\n return pt;\n }\n}\n_RecipientContextImpl_mutex = new WeakMap();\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _SenderContextImpl_mutex;\nimport { EMPTY, SealError, toArrayBuffer } from \"@hpke/common\";\nimport { EncryptionContextImpl } from \"./encryptionContext.js\";\nimport { Mutex } from \"./mutex.js\";\nexport class SenderContextImpl extends EncryptionContextImpl {\n constructor(api, kdf, params, enc) {\n super(api, kdf, params);\n Object.defineProperty(this, \"enc\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n _SenderContextImpl_mutex.set(this, void 0);\n this.enc = enc;\n }\n async seal(data, aad = EMPTY.buffer) {\n __classPrivateFieldSet(this, _SenderContextImpl_mutex, __classPrivateFieldGet(this, _SenderContextImpl_mutex, \"f\") ?? new Mutex(), \"f\");\n const release = await __classPrivateFieldGet(this, _SenderContextImpl_mutex, \"f\").lock();\n let ct;\n try {\n ct = await this._ctx.key.seal(this.computeNonce(this._ctx), toArrayBuffer(data), toArrayBuffer(aad));\n }\n catch (e) {\n throw new SealError(e);\n }\n finally {\n release();\n }\n this.incrementSeq(this._ctx);\n return ct;\n }\n}\n_SenderContextImpl_mutex = new WeakMap();\n","import { AeadId, EMPTY, i2Osp, INFO_LENGTH_LIMIT, INPUT_LENGTH_LIMIT, InvalidParamError, MINIMUM_PSK_LENGTH, Mode, NativeAlgorithm, toUint8Array, } from \"@hpke/common\";\nimport { RecipientExporterContextImpl, SenderExporterContextImpl, } from \"./exporterContext.js\";\nimport { RecipientContextImpl } from \"./recipientContext.js\";\nimport { SenderContextImpl } from \"./senderContext.js\";\n// b\"base_nonce\"\n// deno-fmt-ignore\nconst LABEL_BASE_NONCE = new Uint8Array([\n 98, 97, 115, 101, 95, 110, 111, 110, 99, 101,\n]);\n// b\"exp\"\nconst LABEL_EXP = new Uint8Array([101, 120, 112]);\n// b\"info_hash\"\n// deno-fmt-ignore\nconst LABEL_INFO_HASH = new Uint8Array([\n 105, 110, 102, 111, 95, 104, 97, 115, 104,\n]);\n// b\"key\"\nconst LABEL_KEY = new Uint8Array([107, 101, 121]);\n// b\"psk_id_hash\"\n// deno-fmt-ignore\nconst LABEL_PSK_ID_HASH = new Uint8Array([\n 112, 115, 107, 95, 105, 100, 95, 104, 97, 115, 104,\n]);\n// b\"secret\"\nconst LABEL_SECRET = new Uint8Array([115, 101, 99, 114, 101, 116]);\n// b\"HPKE\"\n// deno-fmt-ignore\nconst SUITE_ID_HEADER_HPKE = new Uint8Array([\n 72, 80, 75, 69, 0, 0, 0, 0, 0, 0,\n]);\n/**\n * The Hybrid Public Key Encryption (HPKE) ciphersuite,\n * which is implemented using only\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n *\n * This is the super class of {@link CipherSuite} and the same as\n * {@link https://jsr.io/@hpke/core/doc/~/CipherSuite | @hpke/core#CipherSuite} as follows:\n * which supports only the ciphersuites that can be implemented on the native\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n * Therefore, the following cryptographic algorithms are not supported for now:\n * - DHKEM(X25519, HKDF-SHA256)\n * - DHKEM(X448, HKDF-SHA512)\n * - ChaCha20Poly1305\n *\n * In addtion, the HKDF functions contained in this class can only derive\n * keys of the same length as the `hashSize`.\n *\n * If you want to use the unsupported cryptographic algorithms\n * above or derive keys longer than the `hashSize`,\n * please use {@link CipherSuite}.\n *\n * This class provides following functions:\n *\n * - Creates encryption contexts both for senders and recipients.\n * - {@link createSenderContext}\n * - {@link createRecipientContext}\n * - Provides single-shot encryption API.\n * - {@link seal}\n * - {@link open}\n *\n * The calling of the constructor of this class is the starting\n * point for HPKE operations for both senders and recipients.\n *\n * @example Use only ciphersuites supported by Web Cryptography API.\n *\n * ```ts\n * import {\n * Aes128Gcm,\n * DhkemP256HkdfSha256,\n * HkdfSha256,\n * CipherSuite,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemP256HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n *\n * @example Use a ciphersuite which is currently not supported by Web Cryptography API.\n *\n * ```ts\n * import { Aes128Gcm, HkdfSha256, CipherSuite } from \"@hpke/core\";\n * // Use an extension module.\n * import { DhkemX25519HkdfSha256 } from \"@hpke/dhkem-x25519\";\n *\n * const suite = new CipherSuite({\n * kem: new DhkemX25519HkdfSha256(),\n * kdf: new HkdfSha256(),\n * aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class CipherSuiteNative extends NativeAlgorithm {\n /**\n * @param params A set of parameters for building a cipher suite.\n *\n * If the error occurred, throws {@link InvalidParamError}.\n *\n * @throws {@link InvalidParamError}\n */\n constructor(params) {\n super();\n Object.defineProperty(this, \"_kem\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_kdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_aead\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_suiteId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n // KEM\n if (typeof params.kem === \"number\") {\n throw new InvalidParamError(\"KemId cannot be used\");\n }\n this._kem = params.kem;\n // KDF\n if (typeof params.kdf === \"number\") {\n throw new InvalidParamError(\"KdfId cannot be used\");\n }\n this._kdf = params.kdf;\n // AEAD\n if (typeof params.aead === \"number\") {\n throw new InvalidParamError(\"AeadId cannot be used\");\n }\n this._aead = params.aead;\n this._suiteId = new Uint8Array(SUITE_ID_HEADER_HPKE);\n this._suiteId.set(i2Osp(this._kem.id, 2), 4);\n this._suiteId.set(i2Osp(this._kdf.id, 2), 6);\n this._suiteId.set(i2Osp(this._aead.id, 2), 8);\n this._kdf.init(this._suiteId);\n }\n /**\n * Gets the KEM context of the ciphersuite.\n */\n get kem() {\n return this._kem;\n }\n /**\n * Gets the KDF context of the ciphersuite.\n */\n get kdf() {\n return this._kdf;\n }\n /**\n * Gets the AEAD context of the ciphersuite.\n */\n get aead() {\n return this._aead;\n }\n /**\n * Creates an encryption context for a sender.\n *\n * If the error occurred, throws {@link DecapError} | {@link ValidationError}.\n *\n * @param params A set of parameters for the sender encryption context.\n * @returns A sender encryption context.\n * @throws {@link EncapError}, {@link ValidationError}\n */\n async createSenderContext(params) {\n this._validateInputLength(params);\n await this._setup();\n const dh = await this._kem.encap(params);\n let mode;\n if (params.psk !== undefined) {\n mode = params.senderKey !== undefined ? Mode.AuthPsk : Mode.Psk;\n }\n else {\n mode = params.senderKey !== undefined ? Mode.Auth : Mode.Base;\n }\n return await this._keyScheduleS(mode, dh.sharedSecret, dh.enc, params);\n }\n /**\n * Creates an encryption context for a recipient.\n *\n * If the error occurred, throws {@link DecapError}\n * | {@link DeserializeError} | {@link ValidationError}.\n *\n * @param params A set of parameters for the recipient encryption context.\n * @returns A recipient encryption context.\n * @throws {@link DecapError}, {@link DeserializeError}, {@link ValidationError}\n */\n async createRecipientContext(params) {\n this._validateInputLength(params);\n await this._setup();\n const sharedSecret = await this._kem.decap(params);\n let mode;\n if (params.psk !== undefined) {\n mode = params.senderPublicKey !== undefined ? Mode.AuthPsk : Mode.Psk;\n }\n else {\n mode = params.senderPublicKey !== undefined ? Mode.Auth : Mode.Base;\n }\n return await this._keyScheduleR(mode, sharedSecret, params);\n }\n /**\n * Encrypts a message to a recipient.\n *\n * If the error occurred, throws `EncapError` | `MessageLimitReachedError` | `SealError` | `ValidationError`.\n *\n * @param params A set of parameters for building a sender encryption context.\n * @param pt A plain text as bytes to be encrypted.\n * @param aad Additional authenticated data as bytes fed by an application.\n * @returns A cipher text and an encapsulated key as bytes.\n * @throws {@link EncapError}, {@link MessageLimitReachedError}, {@link SealError}, {@link ValidationError}\n */\n async seal(params, pt, aad = EMPTY.buffer) {\n const ctx = await this.createSenderContext(params);\n return {\n ct: await ctx.seal(pt, aad),\n enc: ctx.enc,\n };\n }\n /**\n * Decrypts a message from a sender.\n *\n * If the error occurred, throws `DecapError` | `DeserializeError` | `OpenError` | `ValidationError`.\n *\n * @param params A set of parameters for building a recipient encryption context.\n * @param ct An encrypted text as bytes to be decrypted.\n * @param aad Additional authenticated data as bytes fed by an application.\n * @returns A decrypted plain text as bytes.\n * @throws {@link DecapError}, {@link DeserializeError}, {@link OpenError}, {@link ValidationError}\n */\n async open(params, ct, aad = EMPTY.buffer) {\n const ctx = await this.createRecipientContext(params);\n return await ctx.open(ct, aad);\n }\n // private verifyPskInputs(mode: Mode, params: KeyScheduleParams) {\n // const gotPsk = (params.psk !== undefined);\n // const gotPskId = (params.psk !== undefined && params.psk.id.byteLength > 0);\n // if (gotPsk !== gotPskId) {\n // throw new Error('Inconsistent PSK inputs');\n // }\n // if (gotPsk && (mode === Mode.Base || mode === Mode.Auth)) {\n // throw new Error('PSK input provided when not needed');\n // }\n // if (!gotPsk && (mode === Mode.Psk || mode === Mode.AuthPsk)) {\n // throw new Error('Missing required PSK input');\n // }\n // return;\n // }\n async _keySchedule(mode, sharedSecret, params) {\n // Currently, there is no point in executing this function\n // because this hpke library does not allow users to explicitly specify the mode.\n //\n // this.verifyPskInputs(mode, params);\n const pskId = params.psk === undefined\n ? EMPTY\n : toUint8Array(params.psk.id);\n const pskIdHash = await this._kdf.labeledExtract(EMPTY, LABEL_PSK_ID_HASH, pskId);\n const info = params.info === undefined ? EMPTY : toUint8Array(params.info);\n const infoHash = await this._kdf.labeledExtract(EMPTY, LABEL_INFO_HASH, info);\n const keyScheduleContext = new Uint8Array(1 + pskIdHash.byteLength + infoHash.byteLength);\n keyScheduleContext.set(new Uint8Array([mode]), 0);\n keyScheduleContext.set(new Uint8Array(pskIdHash), 1);\n keyScheduleContext.set(new Uint8Array(infoHash), 1 + pskIdHash.byteLength);\n const psk = params.psk === undefined ? EMPTY : toUint8Array(params.psk.key);\n const ikm = this._kdf.buildLabeledIkm(LABEL_SECRET, psk);\n const exporterSecretInfo = this._kdf.buildLabeledInfo(LABEL_EXP, keyScheduleContext, this._kdf.hashSize);\n const exporterSecret = await this._kdf.extractAndExpand(sharedSecret, ikm, exporterSecretInfo, this._kdf.hashSize);\n if (this._aead.id === AeadId.ExportOnly) {\n return { aead: this._aead, exporterSecret: exporterSecret };\n }\n const keyInfo = this._kdf.buildLabeledInfo(LABEL_KEY, keyScheduleContext, this._aead.keySize);\n const key = await this._kdf.extractAndExpand(sharedSecret, ikm, keyInfo, this._aead.keySize);\n const baseNonceInfo = this._kdf.buildLabeledInfo(LABEL_BASE_NONCE, keyScheduleContext, this._aead.nonceSize);\n const baseNonce = await this._kdf.extractAndExpand(sharedSecret, ikm, baseNonceInfo, this._aead.nonceSize);\n return {\n aead: this._aead,\n exporterSecret: exporterSecret,\n key: key,\n baseNonce: new Uint8Array(baseNonce),\n seq: 0,\n };\n }\n async _keyScheduleS(mode, sharedSecret, enc, params) {\n const res = await this._keySchedule(mode, sharedSecret, params);\n if (res.key === undefined) {\n return new SenderExporterContextImpl(this._api, this._kdf, res.exporterSecret, enc);\n }\n return new SenderContextImpl(this._api, this._kdf, res, enc);\n }\n async _keyScheduleR(mode, sharedSecret, params) {\n const res = await this._keySchedule(mode, sharedSecret, params);\n if (res.key === undefined) {\n return new RecipientExporterContextImpl(this._api, this._kdf, res.exporterSecret);\n }\n return new RecipientContextImpl(this._api, this._kdf, res);\n }\n _validateInputLength(params) {\n if (params.info !== undefined &&\n params.info.byteLength > INFO_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long info\");\n }\n if (params.psk !== undefined) {\n if (params.psk.key.byteLength < MINIMUM_PSK_LENGTH) {\n throw new InvalidParamError(`PSK must have at least ${MINIMUM_PSK_LENGTH} bytes`);\n }\n if (params.psk.key.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long psk.key\");\n }\n if (params.psk.id.byteLength > INPUT_LENGTH_LIMIT) {\n throw new InvalidParamError(\"Too long psk.id\");\n }\n }\n return;\n }\n}\n","import { base64UrlToBytes, DeriveKeyPairError, DeserializeError, EMPTY, KEM_USAGES, LABEL_DKP_PRK, LABEL_SK, NativeAlgorithm, NotSupportedError, SerializeError, toArrayBuffer, } from \"@hpke/common\";\nconst ALG_NAME = \"X25519\";\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_X25519 = new Uint8Array([\n 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,\n 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20,\n]);\nconst BASE_POINT_X25519 = /* @__PURE__ */ (() => {\n const p = new Uint8Array(32);\n p[0] = 9;\n return p;\n})();\nexport class X25519 extends NativeAlgorithm {\n constructor(hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._alg = { name: ALG_NAME };\n this._hkdf = hkdf;\n this._nPk = 32;\n this._nSk = 32;\n this._nDh = 32;\n this._pkcs8AlgId = PKCS8_ALG_ID_X25519;\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(ALG_NAME, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const rawIkm = toArrayBuffer(ikm);\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY, LABEL_DKP_PRK, new Uint8Array(rawIkm));\n const rawSk = await this._hkdf.labeledExpand(dkpPrk, LABEL_SK, EMPTY, this._nSk);\n const rawSkBytes = new Uint8Array(rawSk);\n const sk = await this._deserializePkcs8Key(rawSkBytes);\n rawSkBytes.fill(0);\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch {\n try {\n // Firefox fails to export JWK from some imported X25519 private keys.\n const bp = await this._api.importKey(\"raw\", BASE_POINT_X25519.buffer, this._alg, true, []);\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: bp,\n }, key, this._nPk * 8);\n return await this._api.importKey(\"raw\", bits, this._alg, true, []);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n }\n async dh(sk, pk) {\n await this._setup();\n try {\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.kty === \"undefined\" || key.kty !== \"OKP\") {\n throw new Error(`Invalid kty: ${key.crv}`);\n }\n if (typeof key.crv === \"undefined\" || key.crv !== ALG_NAME) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n}\n","import { base64UrlToBytes, DeriveKeyPairError, DeserializeError, EMPTY, KEM_USAGES, LABEL_DKP_PRK, LABEL_SK, NativeAlgorithm, NotSupportedError, SerializeError, toArrayBuffer, } from \"@hpke/common\";\nconst ALG_NAME = \"X448\";\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_X448 = new Uint8Array([\n 0x30, 0x46, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,\n 0x03, 0x2b, 0x65, 0x6f, 0x04, 0x3a, 0x04, 0x38,\n]);\nconst BASE_POINT_X448 = /* @__PURE__ */ (() => {\n const p = new Uint8Array(56);\n p[0] = 5;\n return p;\n})();\nexport class X448 extends NativeAlgorithm {\n constructor(hkdf) {\n super();\n Object.defineProperty(this, \"_hkdf\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_alg\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nPk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nSk\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_nDh\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"_pkcs8AlgId\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this._alg = { name: ALG_NAME };\n this._hkdf = hkdf;\n this._nPk = 56;\n this._nSk = 56;\n this._nDh = 56;\n this._pkcs8AlgId = PKCS8_ALG_ID_X448;\n }\n async serializePublicKey(key) {\n await this._setup();\n try {\n return await this._api.exportKey(\"raw\", key);\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePublicKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), true);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async serializePrivateKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n if (!(\"d\" in jwk)) {\n throw new Error(\"Not private key\");\n }\n return base64UrlToBytes(jwk[\"d\"]).buffer;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async deserializePrivateKey(key) {\n await this._setup();\n try {\n return await this._importRawKey(toArrayBuffer(key), false);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async importKey(format, key, isPublic) {\n await this._setup();\n try {\n if (format === \"raw\") {\n return await this._importRawKey(key, isPublic);\n }\n // jwk\n if (key instanceof ArrayBuffer) {\n throw new Error(\"Invalid jwk key format\");\n }\n return await this._importJWK(key, isPublic);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n async generateKeyPair() {\n await this._setup();\n try {\n return await this._api.generateKey(ALG_NAME, true, KEM_USAGES);\n }\n catch (e) {\n throw new NotSupportedError(e);\n }\n }\n async deriveKeyPair(ikm) {\n await this._setup();\n try {\n const rawIkm = toArrayBuffer(ikm);\n const dkpPrk = await this._hkdf.labeledExtract(EMPTY, LABEL_DKP_PRK, new Uint8Array(rawIkm));\n const rawSk = await this._hkdf.labeledExpand(dkpPrk, LABEL_SK, EMPTY, this._nSk);\n const rawSkBytes = new Uint8Array(rawSk);\n const sk = await this._deserializePkcs8Key(rawSkBytes);\n rawSkBytes.fill(0);\n return {\n privateKey: sk,\n publicKey: await this.derivePublicKey(sk),\n };\n }\n catch (e) {\n throw new DeriveKeyPairError(e);\n }\n }\n async derivePublicKey(key) {\n await this._setup();\n try {\n const jwk = await this._api.exportKey(\"jwk\", key);\n delete jwk[\"d\"];\n delete jwk[\"key_ops\"];\n return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n }\n catch {\n try {\n // Some runtimes cannot export JWK from imported X448 private keys.\n const bp = await this._api.importKey(\"raw\", BASE_POINT_X448.buffer, this._alg, true, []);\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: bp,\n }, key, this._nPk * 8);\n return await this._api.importKey(\"raw\", bits, this._alg, true, []);\n }\n catch (e) {\n throw new DeserializeError(e);\n }\n }\n }\n async dh(sk, pk) {\n await this._setup();\n try {\n const bits = await this._api.deriveBits({\n name: ALG_NAME,\n public: pk,\n }, sk, this._nDh * 8);\n return bits;\n }\n catch (e) {\n throw new SerializeError(e);\n }\n }\n async _importRawKey(key, isPublic) {\n if (isPublic && key.byteLength !== this._nPk) {\n throw new Error(\"Invalid public key for the ciphersuite\");\n }\n if (!isPublic && key.byteLength !== this._nSk) {\n throw new Error(\"Invalid private key for the ciphersuite\");\n }\n if (isPublic) {\n return await this._api.importKey(\"raw\", key, this._alg, true, []);\n }\n return await this._deserializePkcs8Key(new Uint8Array(key));\n }\n async _importJWK(key, isPublic) {\n if (typeof key.kty === \"undefined\" || key.kty !== \"OKP\") {\n throw new Error(`Invalid kty: ${key.crv}`);\n }\n if (typeof key.crv === \"undefined\" || key.crv !== ALG_NAME) {\n throw new Error(`Invalid crv: ${key.crv}`);\n }\n if (isPublic) {\n if (typeof key.d !== \"undefined\") {\n throw new Error(\"Invalid key: `d` should not be set\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n }\n if (typeof key.d === \"undefined\") {\n throw new Error(\"Invalid key: `d` not found\");\n }\n return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n }\n async _deserializePkcs8Key(k) {\n const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n pkcs8Key.set(this._pkcs8AlgId, 0);\n pkcs8Key.set(k, this._pkcs8AlgId.length);\n return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n }\n}\n","import type { HttpClient } from './http.js';\nimport type { ProjectConfig } from './types.js';\n\nconst CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes\n\nexport class ConfigFetcher {\n protected readonly httpClient: HttpClient;\n private cachedConfig: ProjectConfig | null = null;\n private cacheTimestamp = 0;\n\n constructor(httpClient: HttpClient) {\n this.httpClient = httpClient;\n }\n\n async getConfig(): Promise<ProjectConfig | null> {\n const now = Date.now();\n\n if (this.cachedConfig && now - this.cacheTimestamp < CACHE_TTL_MS) {\n return this.cachedConfig;\n }\n\n try {\n const response = await this.httpClient.request<ProjectConfig>('GET', '/v1/config');\n\n if (response.error || !response.data) {\n return null;\n }\n\n this.cachedConfig = response.data;\n this.cacheTimestamp = now;\n\n return this.cachedConfig;\n } catch {\n return null;\n }\n }\n}\n","export class PalbaseError extends Error {\n readonly code: string;\n readonly status: number;\n readonly details?: unknown;\n\n constructor(code: string, message: string, status: number, details?: unknown) {\n super(message);\n this.name = 'PalbaseError';\n this.code = code;\n this.status = status;\n this.details = details;\n }\n}\n","export type Platform = 'browser' | 'node' | 'react-native' | 'deno' | 'bun';\n\ndeclare const Deno: unknown;\n\nexport function detectPlatform(): Platform {\n if (typeof Deno !== 'undefined') {\n return 'deno';\n }\n\n const runtime = globalThis as typeof globalThis & { process?: { versions?: Record<string, string> } };\n if (runtime.process?.versions) {\n if ('bun' in runtime.process.versions) {\n return 'bun';\n }\n if ('node' in runtime.process.versions) {\n return 'node';\n }\n }\n\n if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {\n return 'react-native';\n }\n\n return 'browser';\n}\n\n/**\n * The platform word this SDK puts on the wire (`X-Platform`), which the server\n * reads to target flags and to label telemetry.\n *\n * It is NOT `detectPlatform()`'s value verbatim: that reports the JS host\n * (\"browser\"), while the wire wants the platform. iOS sends \"ios\", not the name\n * of its runtime, and a condition author writes `client.platform == 'web'` —\n * the word every other flag vendor uses too. Server hosts keep their own names,\n * where the distinction is the useful part.\n */\nexport function wirePlatform(): string {\n const host = detectPlatform();\n return host === 'browser' ? 'web' : host;\n}\n","// Proof-of-work: the bot gate in front of /auth/signup and /auth/login.\n//\n// The server answers an unsolved request with 403 and a challenge in the body:\n//\n// { \"error\": \"pow_required\", \"challenge\": { \"id\", \"prefix\", \"difficulty\" } }\n//\n// A client finds any nonce whose SHA-256(prefix + nonce) begins with\n// `difficulty` zero bits, then repeats the request carrying the id and nonce as\n// headers. The work is the point: a person signing up pays it once and does not\n// notice, a script signing up ten thousand times pays it ten thousand times.\n//\n// # Why this lives in core, and not one layer up\n//\n// Until 2026-08-14 nothing shipped could solve it: the gate was written with the\n// server and its own integration harness, and every real client sent requests\n// without the headers and got 403. It was then solved in @palbase/web's own\n// request path — which covers `pb.call` and the module facades and NOT\n// `pb.auth.*`, because those go through @palbase/auth's client and from there\n// into core's HttpClient. So the fix landed everywhere except the two endpoints\n// the gate actually guards, and `npm i @palbase/web` still could not sign a\n// person in. Measured 2026-08-18 against a real stack, on the published 7.3.0.\n//\n// The lesson is where a retry belongs: at the layer that ISSUES the request.\n// Core owns fetch for every client in this repo, so core owns the challenge.\n//\n// WebCrypto rather than a hashing dependency: `crypto.subtle` is present in\n// browsers and in Node 18+, which is the same floor the rest of the SDK sets.\n// Measured at the server's default difficulty of 16: ~330ms, ~65k digests.\n\n/** The challenge a `pow_required` response carries. */\nexport interface PowChallenge {\n id: string;\n prefix: string;\n difficulty: number;\n}\n\n/** Header names the retry must carry. Mirrors the server's constants. */\nexport const POW_CHALLENGE_ID_HEADER = 'X-PoW-Challenge-ID';\nexport const POW_NONCE_HEADER = 'X-PoW-Nonce';\n\n/**\n * Reads a challenge out of an error envelope, or returns null when the envelope\n * is not a `pow_required` one.\n *\n * The whole wire envelope is stored on the error, so the challenge arrives\n * without the HTTP layer having to know about proof-of-work at all.\n */\nexport function asPowChallenge(details: unknown): PowChallenge | null {\n if (typeof details !== 'object' || details === null) return null;\n const env = details as Record<string, unknown>;\n if (env.error !== 'pow_required') return null;\n const c = env.challenge;\n if (typeof c !== 'object' || c === null) return null;\n const { id, prefix, difficulty } = c as Record<string, unknown>;\n if (typeof id !== 'string' || typeof prefix !== 'string') return null;\n if (typeof difficulty !== 'number' || !Number.isInteger(difficulty) || difficulty < 0) return null;\n return { id, prefix, difficulty };\n}\n\nconst encoder = new TextEncoder();\n\n/**\n * One SHA-256, by the fastest route this runtime offers.\n *\n * Awaiting `crypto.subtle.digest` once per nonce is what made this expensive,\n * and the cost is the await rather than the hashing. Measured on one machine,\n * 200k digests of a 40-byte input:\n *\n *\tawaited crypto.subtle.digest 105,597 digests/s\n *\tsync node:crypto createHash 1,324,503 digests/s — 12.5x\n *\n * That is the difference between difficulty 24 taking 159 seconds and taking\n * 13. Node, Bun and Deno all have the sync one; a browser has only WebCrypto,\n * and there it stays async.\n *\n * The specifier is assembled at runtime so a browser bundler does not try to\n * resolve `node:crypto` and fail the build over a branch that never runs there.\n */\ntype Hasher = (input: string) => Uint8Array | Promise<Uint8Array>;\n\nlet hasher: Hasher | null = null;\n\nasync function digester(): Promise<Hasher> {\n if (hasher) return hasher;\n // Read off globalThis with an inline shape rather than by naming `process`,\n // which needs @types/node — a dependency this package does not have and should\n // not grow for one branch. It typechecked locally only because those types\n // were hoisted into node_modules by a sibling package; the publish workflow's\n // clean checkout is what said so, which is exactly what it is for.\n const runtime = globalThis as {\n process?: { versions?: { node?: string; bun?: string } };\n };\n const nodeish =\n runtime.process?.versions?.node !== undefined ||\n runtime.process?.versions?.bun !== undefined;\n if (nodeish) {\n try {\n const mod = (await import(/* @vite-ignore */ `${'node:'}crypto`)) as {\n createHash?: (alg: string) => { update(s: string): { digest(): Uint8Array } };\n };\n if (typeof mod.createHash === 'function') {\n const createHash = mod.createHash;\n hasher = (input: string) => new Uint8Array(createHash('sha256').update(input).digest());\n return hasher;\n }\n } catch {\n // No node:crypto here. WebCrypto below is not a fallback in the apologetic\n // sense — it is the only hash a browser has, and it is correct.\n }\n }\n hasher = async (input: string) =>\n new Uint8Array(await crypto.subtle.digest('SHA-256', encoder.encode(input)));\n return hasher;\n}\n\n/** Monotonic where it exists, wall-clock where it does not. */\nconst now = (): number =>\n typeof performance !== 'undefined' && typeof performance.now === 'function'\n ? performance.now()\n : Date.now();\n\n/** Counts leading zero bits, stopping at the first byte that has a one. */\nfunction leadingZeroBits(hash: Uint8Array): number {\n let bits = 0;\n for (const byte of hash) {\n if (byte === 0) {\n bits += 8;\n continue;\n }\n // clz32 counts across 32 bits; a byte occupies the low 8, so the first 24\n // are always zero and get subtracted back off.\n return bits + Math.clz32(byte) - 24;\n }\n return bits;\n}\n\n/**\n * The hardest challenge this client will attempt.\n *\n * Not a taste: it is the server's own ceiling. palauth maps a risk score to a\n * difficulty and its worst case is 24 (`DifficultyForRisk`, bot/pow.go:156-166).\n * Anything above that cannot have come from a stack behaving as designed, and\n * the cost of humouring it falls entirely on this side — each step up DOUBLES\n * the work, so difficulty 30 is sixty-four times a legitimate worst case and, on\n * the web, sixty-four times a frozen main thread. Refused immediately, by name.\n */\nexport const MAX_POW_DIFFICULTY = 24;\n\n/**\n * Finds a nonce satisfying the challenge and returns the headers a retry needs.\n *\n * THE BUDGET SCALES WITH THE CHALLENGE, and the first version of this did not.\n * It bounded the search at a flat `1 << 24` — which is not a generous bound for\n * difficulty 24, it is the EXPECTED number of attempts. Finding a nonce is a\n * geometric process: the chance of needing more than 2^d attempts is 1/e, so a\n * flat 2^24 would have failed roughly 37% of legitimate hardest-risk challenges,\n * and failed them for precisely the users the gate exists to slow down — who\n * would have been unable to sign in at all rather than made to wait.\n *\n * Eight times expected puts that at e^-8, about three in ten thousand, while\n * leaving the common case (the server's default 16, and 12 for an unremarkable\n * caller) exactly as cheap as it was.\n *\n * `powBudget` is exported and separate so the RELATIONSHIP can be asserted\n * directly. A test that only watches a cheap challenge succeed cannot tell this\n * budget from the flat one it replaced — measured: reinstating `1 << 24` left\n * such a test green.\n */\nexport function powBudget(difficulty: number): number {\n return 8 * 2 ** difficulty;\n}\n\n/**\n * The longest a solve may be ALLOWED to take, and the difference from a\n * deadline is the whole point.\n *\n * The first version of this was a flat 120s deadline, and it was measured to be\n * worse than the flat iteration budget it was meant to backstop: at ~105k\n * digests/s, difficulty 24 EXPECTS 159 seconds, so a 120s clock killed the\n * majority of legitimate hardest-risk solves — reintroducing, larger, exactly\n * the class of defect that replacing `1 << 24` had removed. Guessing a number\n * for an unknown machine cannot work: the same difficulty is 13 seconds on a\n * runtime with a sync hasher and 159 on one without.\n *\n * So the machine is MEASURED, and the decision moves to the front. A short\n * calibration gives the rate this process actually hashes at; if the whole\n * iteration budget cannot fit in this window at that rate, the solve is refused\n * IMMEDIATELY, naming the numbers. A caller then learns in milliseconds that\n * this difficulty is unpayable here, instead of after two minutes of work\n * thrown away.\n *\n * What remains after that is a guarantee rather than a gamble: a solve that\n * starts can always finish inside its budget, so the only failure left is the\n * budget's own e^-8.\n */\nexport const POW_TIME_BUDGET_MS = 120_000;\n\n/**\n * The window the rate is measured over, and the warm-up it deliberately skips.\n *\n * All of these are REAL attempts — the search starts at nonce 0 and never\n * restarts — so calibration costs nothing but the reading. The first 1024 are\n * excluded from the timing because they include this loop's own JIT warm-up:\n * measured, timing from zero reported 747k digests/s on a machine whose steady\n * rate is 1.32M, and the decision below would have refused a difficulty this\n * machine can pay in half the allowance.\n */\nconst CALIBRATION_WARMUP = 1024;\nconst CALIBRATION_END = 9216;\n\nexport async function solvePowChallenge(\n challenge: PowChallenge,\n maxIterations = powBudget(challenge.difficulty),\n // The caller's AbortSignal, honoured INSIDE the loop rather than only around\n // the fetch it precedes — for the callers that have one. `pb.auth.signIn` does\n // NOT: it reaches the network through @palbase/auth's client, which takes\n // credentials and nothing else. So it is the extra a caller can opt into, and\n // POW_TIME_BUDGET_MS below is what actually bounds the work.\n signal?: AbortSignal,\n): Promise<Record<string, string>> {\n if (challenge.difficulty > MAX_POW_DIFFICULTY) {\n throw new Error(\n `proof-of-work: refusing difficulty ${challenge.difficulty}; this client attempts at most ${MAX_POW_DIFFICULTY}, which is the highest a Palbase stack issues`,\n );\n }\n\n const digest = await digester();\n let warmedAt = 0;\n let calibrated = false;\n // Armed by the calibration below, never before it: until the rate is known\n // there is no honest number to put here.\n let deadline = Number.POSITIVE_INFINITY;\n\n for (let nonce = 0; nonce < maxIterations; nonce++) {\n // Checked in batches: reading them is cheap but not free, and a\n // 1024-digest granularity bounds the delay at a few milliseconds.\n if ((nonce & 1023) === 0) {\n if (signal?.aborted) {\n throw new DOMException('proof-of-work solve aborted', 'AbortError');\n }\n if (now() > deadline) {\n throw new Error(\n `proof-of-work: gave up on difficulty ${challenge.difficulty} after ${POW_TIME_BUDGET_MS / 1000}s ` +\n `and ${nonce.toLocaleString()} attempts — the tail this run drew is longer than the allowance`,\n );\n }\n }\n\n // THE DECISION, TAKEN ONCE AND TAKEN EARLY.\n //\n // After CALIBRATION_DIGESTS real attempts the rate of THIS process is\n // known, so the question \"can this machine pay this difficulty\" has an\n // answer instead of an assumption. If the whole budget cannot fit in the\n // time budget, refuse here — milliseconds in, with the numbers — rather\n // than spend two minutes and throw them away. If it fits, everything after\n // this point is guaranteed to finish inside the window, so the only\n // remaining failure is the budget's own e^-8.\n if (nonce === CALIBRATION_WARMUP) {\n warmedAt = now();\n }\n if (!calibrated && nonce === CALIBRATION_END) {\n calibrated = true;\n const elapsed = Math.max(now() - warmedAt, 0.001);\n const rate = (CALIBRATION_END - CALIBRATION_WARMUP) / (elapsed / 1000);\n // EXPECTED, not worst case, and the difference is the whole judgement.\n //\n // Finding a nonce is geometric: 2^difficulty attempts on average, with a\n // long tail the 8x budget covers. Refusing because the TAIL will not fit\n // would turn away work whose expected cost is seventeen seconds — measured\n // exactly that on this machine at difficulty 24. Refusing on the EXPECTED\n // cost turns away only what is genuinely unpayable here, and what it lets\n // through is then cut by the clock with probability e^-(budget/expected):\n // at 120s against a 17s expectation that is one run in a thousand, and at\n // difficulty 20 on a browser it is one in a hundred and fifty thousand.\n const expectedMs = (2 ** challenge.difficulty / rate) * 1000;\n if (expectedMs > POW_TIME_BUDGET_MS) {\n throw new Error(\n `proof-of-work: difficulty ${challenge.difficulty} needs about ${Math.round(expectedMs / 1000)}s here ` +\n `(${Math.round(rate).toLocaleString()} digests/s) and this client allows ${POW_TIME_BUDGET_MS / 1000}s; ` +\n `refusing before spending the time rather than after`,\n );\n }\n deadline = now() + (POW_TIME_BUDGET_MS - (now() - warmedAt));\n }\n\n const hash = await digest(challenge.prefix + nonce);\n if (leadingZeroBits(hash) >= challenge.difficulty) {\n return {\n [POW_CHALLENGE_ID_HEADER]: challenge.id,\n [POW_NONCE_HEADER]: String(nonce),\n };\n }\n }\n throw new Error(\n `proof-of-work: no nonce found for difficulty ${challenge.difficulty} within ${maxIterations} attempts`,\n );\n}\n","import { Chacha20Poly1305 } from '@hpke/chacha20poly1305';\nimport { CipherSuite, HkdfSha256 } from '@hpke/core';\nimport { DhkemX25519HkdfSha256 } from '@hpke/dhkem-x25519';\nimport { PalbaseError } from './errors.js';\nimport { fromBase64, toBase64 } from './sealed-json.js';\nimport type { SealingKey } from './sealed-keys.js';\n\nexport const SEALED_CONTENT_TYPE = 'application/palbase-sealed+json';\nexport const SEALED_HEADER = 'X-Palbase-Sealed';\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder('utf-8', { fatal: true });\nconst responseLabel = 'palbase-sealed/response/v1';\n\nexport function sealingRequired(path: string): boolean {\n // Mirrors v2/internal/server/sealed.go. Tenant/runtime routes cannot unseal.\n return new URL(path, 'https://unused.invalid').pathname.startsWith('/auth/');\n}\n\nexport function requestAAD(\n host: string,\n method: string,\n path: string,\n ict: string,\n ts: number,\n idem: string,\n): Uint8Array<ArrayBuffer> {\n const fields = [host, method, path, ict, idem].map((field) => encoder.encode(field));\n const bytes = new Uint8Array(fields.reduce((size, field) => size + 4 + field.length, 8));\n const view = new DataView(bytes.buffer);\n let offset = 0;\n for (const [index, field] of fields.entries()) {\n if (index === 4) {\n view.setBigUint64(offset, BigInt(ts));\n offset += 8;\n }\n view.setUint32(offset, field.length);\n offset += 4;\n bytes.set(field, offset);\n offset += field.length;\n }\n return bytes;\n}\n\nexport function sealingSuite(): CipherSuite {\n return new CipherSuite({\n kem: new DhkemX25519HkdfSha256(),\n kdf: new HkdfSha256(),\n aead: new Chacha20Poly1305(),\n });\n}\n\nexport async function sealRequest(\n key: SealingKey,\n url: string,\n init: RequestInit,\n): Promise<Uint8Array<ArrayBuffer>> {\n const suite = sealingSuite();\n const sender = await suite.createSenderContext({\n recipientPublicKey: await suite.kem.importKey('raw', key.publicKey.buffer),\n });\n const headers = new Headers(init.headers);\n const ict = headers.get('content-type') ?? 'application/json';\n const ts = Math.floor(Date.now() / 1000);\n const target = new URL(url);\n const method = init.method ?? 'GET';\n // Go binds r.URL.Path (decoded, without the query), not RequestURI.\n const aad = requestAAD(\n target.host,\n method,\n decodeURIComponent(target.pathname),\n ict,\n ts,\n headers.get('idempotency-key') ?? '',\n );\n const ct = await sender.seal(encoder.encode(typeof init.body === 'string' ? init.body : ''), aad);\n const envelope = JSON.stringify({\n v: 2,\n kid: key.kid,\n enc: toBase64(new Uint8Array(sender.enc)),\n ct: toBase64(new Uint8Array(ct)),\n ict,\n ts,\n });\n if (method === 'GET' || method === 'HEAD' || init.body === undefined) {\n headers.set(\n SEALED_HEADER,\n toBase64(encoder.encode(envelope)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, ''),\n );\n delete init.body;\n } else {\n headers.delete(SEALED_HEADER);\n headers.set('Content-Type', SEALED_CONTENT_TYPE);\n init.body = envelope;\n }\n headers.delete('Content-Length');\n init.headers = Object.fromEntries(headers.entries());\n // Do not redirect a credential-bearing envelope to a different endpoint.\n init.redirect = 'error';\n return new Uint8Array(await sender.export(encoder.encode(responseLabel), 32));\n}\n\nexport async function openSealedResponse(\n response: Response,\n exporter: Uint8Array | undefined,\n method: string,\n): Promise<Response> {\n if (\n response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() !==\n SEALED_CONTENT_TYPE\n ) {\n // Edge/middleware errors are plaintext. A successful auth result cannot be.\n if (exporter && response.ok && method !== 'HEAD') {\n throw new PalbaseError(\n 'sealed_response_invalid',\n 'The server returned an unencrypted response.',\n response.status,\n );\n }\n return response;\n }\n // HTTP HEAD has no response body, including when the handler sealed it.\n if (method === 'HEAD') return response;\n try {\n if (!exporter) throw new Error('No sealing context');\n const envelope = (await response.json()) as {\n v: number;\n n: string;\n ct: string;\n ict: string;\n st: number;\n };\n if (\n envelope.v !== 2 ||\n !Number.isInteger(envelope.st) ||\n envelope.st < 200 ||\n envelope.st > 599 ||\n typeof envelope.ict !== 'string'\n ) {\n throw new Error('Invalid response envelope');\n }\n const plaintext = await new Chacha20Poly1305()\n .createEncryptionContext(exporter)\n .open(\n fromBase64(envelope.n),\n fromBase64(envelope.ct),\n encoder.encode(`${responseLabel}\\n${envelope.ict}\\n${envelope.st}`),\n );\n const headers = new Headers(response.headers);\n headers.set('Content-Type', envelope.ict);\n headers.delete('Content-Length');\n headers.delete('Content-Encoding');\n // The outer status is always 200; auth failures and PoW live inside the seal.\n return new Response([204, 205, 304].includes(envelope.st) ? null : decoder.decode(plaintext), {\n status: envelope.st,\n headers,\n });\n } catch {\n throw new PalbaseError(\n 'sealed_response_invalid',\n 'The encrypted server response could not be verified.',\n response.status,\n );\n }\n}\n","// Signatures cover the original JSON bytes, not JSON.stringify(JSON.parse(raw)).\n// Go's encoder preserves struct field order and escapes characters differently.\nexport function rawObjectFields(raw: string): Map<string, string> {\n const parsed: unknown = JSON.parse(raw);\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('Expected a JSON object');\n }\n const fields = new Map<string, string>();\n let i = 0;\n const space = () => {\n while (/\\s/.test(raw[i] ?? '') && i < raw.length) i++;\n };\n const stringEnd = (start: number) => {\n let end = start + 1;\n while (end < raw.length) {\n if (raw[end] === '\\\\') end += 2;\n else if (raw[end++] === '\"') return end;\n }\n throw new Error('Unterminated JSON string');\n };\n space();\n i++; // opening object, already validated by JSON.parse\n while (true) {\n space();\n if (raw[i] === '}') return fields;\n const nameEnd = stringEnd(i);\n const name = JSON.parse(raw.slice(i, nameEnd)) as string;\n i = nameEnd;\n space();\n i++; // colon\n space();\n const start = i;\n if (raw[i] === '\"') i = stringEnd(i);\n else if (raw[i] === '{' || raw[i] === '[') {\n let depth = 0;\n do {\n const c = raw[i];\n if (c === '\"') {\n i = stringEnd(i);\n continue;\n }\n if (c === '{' || c === '[') depth++;\n if (c === '}' || c === ']') depth--;\n i++;\n } while (depth > 0 && i < raw.length);\n } else {\n while (i < raw.length && !/[\\s,}]/.test(raw[i] ?? '')) i++;\n }\n // A first-match slice and JSON.parse's last-match value must never disagree.\n if (fields.has(name)) throw new Error('Duplicate JSON field');\n fields.set(name, raw.slice(start, i));\n space();\n if (raw[i] === ',') i++;\n }\n}\n\nexport function fromBase64(value: string): Uint8Array<ArrayBuffer> {\n return Uint8Array.from(atob(value), (c) => c.charCodeAt(0));\n}\n\nexport function toBase64(bytes: Uint8Array): string {\n // Avoid a spread: envelopes can exceed the engine's argument-count limit.\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n","import { ed25519 } from '@noble/curves/ed25519.js';\nimport { PalbaseError } from './errors.js';\nimport { fromBase64, rawObjectFields } from './sealed-json.js';\nimport { endpointUrl } from './url.js';\nimport type { HttpClientOptions } from './types.js';\n\nexport const SEALED_KEYSET_PATH = '/palbase-sealed-keys.json';\nexport const SEALED_SUITE = 'DHKEM-X25519-HKDF-SHA256/HKDF-SHA256/ChaCha20Poly1305';\n// Fleet PUBLIC key, identical to the iOS SDK pin. Never learned from a response.\nconst FLEET_ROOT = 'mRDTIWzhW0JCk0e2Jvkn679VeZBB38zOOfPTMO6vBpU=';\nconst REFRESH_MS = 5 * 60_000;\nconst FAILURE_COOLDOWN_MS = 60_000;\nconst encoder = new TextEncoder();\n\nexport interface SealingKey {\n kid: string;\n publicKey: Uint8Array<ArrayBuffer>;\n expires: number;\n version: number;\n}\n\nexport function expectedSealedStack(baseUrl: string, apiKey: string): string {\n // Fleet tenant hosts name the stack even when a legacy key says pb_project_.\n // Apex/custom/self-host URLs instead need the key's ref (or an explicit pin).\n const host = new URL(baseUrl).hostname;\n return (\n /^([a-z0-9]{4,24})\\.(?:(?:dev|staging)\\.)?palbase\\.studio$/.exec(host)?.[1] ??\n /^pb_([^_]+)_/.exec(apiKey)?.[1] ??\n ''\n );\n}\n\nfunction record(raw: string | undefined): Record<string, unknown> {\n if (!raw) throw new Error('Missing signed object');\n rawObjectFields(raw); // also refuses duplicate fields\n return JSON.parse(raw) as Record<string, unknown>;\n}\n\nfunction string(value: unknown): string {\n if (typeof value !== 'string' || !value) throw new Error('Missing string');\n return value;\n}\n\nfunction integer(value: unknown): number {\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new Error('Invalid integer');\n }\n return value;\n}\n\nfunction verifySignature(raw: string, signed: Record<string, unknown>, publicKey: Uint8Array) {\n if (\n signed.alg !== 'ed25519' ||\n publicKey.length !== 32 ||\n !ed25519.verify(fromBase64(string(signed.sig)), encoder.encode(raw), publicKey, {\n zip215: false,\n })\n )\n throw new Error('Invalid sealed key signature');\n}\n\n/** Verify fleet → expected stack → keyset, retaining the exact signed bytes. */\nexport function verifySealingKey(\n raw: string,\n expectedRef: string,\n root: string,\n lastVersion: number,\n now: number,\n): SealingKey {\n const fields = rawObjectFields(raw);\n const signed = record(raw);\n const statementRaw = fields.get('binding');\n const statement = record(statementRaw);\n const bindingRaw = rawObjectFields(statementRaw ?? '').get('binding');\n if (!bindingRaw || statement.rootKid !== 'sealed-root-v1') {\n throw new Error('Unknown sealed trust root');\n }\n verifySignature(bindingRaw, statement, fromBase64(root));\n const binding = record(bindingRaw);\n if (\n binding.v !== 1 ||\n !expectedRef ||\n string(binding.stackRef).trim().toLowerCase() !== expectedRef.toLowerCase()\n ) {\n throw new Error('Sealed binding belongs to another stack');\n }\n const bindingExpiry = integer(binding.expires);\n if (bindingExpiry * 1000 <= now) throw new Error('Expired sealed binding');\n const keysetRaw = fields.get('keyset');\n if (!keysetRaw) throw new Error('Missing sealed keyset');\n verifySignature(keysetRaw, signed, fromBase64(string(binding.signingKey)));\n const keyset = record(keysetRaw);\n const version = integer(keyset.version);\n const expires = Math.min(integer(keyset.expires), bindingExpiry);\n if (version < lastVersion) throw new Error('Sealed keyset version went backwards');\n if (expires * 1000 <= now) throw new Error('Expired sealed keyset');\n if (keyset.v !== 1 || !Array.isArray(keyset.keys)) throw new Error('Invalid sealed keyset');\n for (const item of keyset.keys) {\n if (item === null || typeof item !== 'object') continue;\n const entry = item as Record<string, unknown>;\n if (entry.alg !== SEALED_SUITE) continue;\n const publicKey = fromBase64(string(entry.pub));\n if (publicKey.length !== 32) throw new Error('Invalid sealing public key');\n return { kid: string(entry.kid), publicKey, expires, version };\n }\n throw new Error('No supported sealing key');\n}\n\nexport class SealedKeyStore {\n private cached?: SealingKey;\n private pending?: Promise<SealingKey>;\n private fetchedAt = 0;\n private retryAfter = 0;\n private lastVersion = 0;\n private lastError?: PalbaseError;\n private rotationRefreshAt = 0;\n\n constructor(\n private readonly baseUrl: string,\n private readonly apiKey: string,\n private readonly options?: Exclude<HttpClientOptions['sealed'], false>,\n ) {}\n\n async current(signal?: AbortSignal, rotate = false): Promise<SealingKey> {\n signal?.throwIfAborted();\n const now = Date.now();\n const valid = this.cached && this.cached.expires * 1000 > now ? this.cached : undefined;\n if (this.pending) return this.waitFor(this.pending, signal);\n // A forged unknown-kid response cannot turn every request into a key fetch.\n if (rotate && now - this.rotationRefreshAt >= FAILURE_COOLDOWN_MS) {\n this.fetchedAt = 0;\n this.retryAfter = 0;\n this.rotationRefreshAt = now;\n }\n if (valid && now - this.fetchedAt < REFRESH_MS) return valid;\n if (now < this.retryAfter) {\n if (valid) return valid;\n throw this.lastError;\n }\n const pending = this.fetchKey()\n .then((key) => {\n this.cached = key;\n this.lastVersion = key.version;\n this.fetchedAt = Date.now();\n this.retryAfter = 0;\n return key;\n })\n .catch((error: unknown) => {\n this.retryAfter = Date.now() + FAILURE_COOLDOWN_MS;\n this.lastError =\n error instanceof PalbaseError\n ? error\n : new PalbaseError(\n 'sealed_key_unavailable',\n 'The server encryption key could not be verified. Please try again later.',\n 0,\n );\n // A transient refresh failure may reuse a verified, unexpired key only.\n if (this.cached && this.cached.expires * 1000 > Date.now()) return this.cached;\n throw this.lastError;\n })\n .finally(() => {\n this.pending = undefined;\n });\n this.pending = pending;\n return this.waitFor(pending, signal);\n }\n\n private async fetchKey(): Promise<SealingKey> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), 15_000);\n try {\n const response = await fetch(endpointUrl(this.baseUrl, SEALED_KEYSET_PATH), {\n headers: this.apiKey ? { apikey: this.apiKey } : {},\n signal: controller.signal,\n cache: 'no-store',\n redirect: 'error',\n });\n if (!response.ok) throw new Error('Sealed keyset unavailable');\n const raw = await response.text();\n if (raw.length > 64 * 1024) throw new Error('Sealed keyset too large');\n const expectedRef = this.options?.stackRef ?? expectedSealedStack(this.baseUrl, this.apiKey);\n return verifySealingKey(\n raw,\n expectedRef,\n this.options?.root ?? FLEET_ROOT,\n this.lastVersion,\n Date.now(),\n );\n } finally {\n clearTimeout(timer);\n }\n }\n\n // One caller's cancellation must not abort a shared key fetch for other calls.\n private waitFor(pending: Promise<SealingKey>, signal?: AbortSignal): Promise<SealingKey> {\n if (!signal) return pending;\n return new Promise((resolve, reject) => {\n const aborted = () => reject(signal.reason);\n signal.addEventListener('abort', aborted, { once: true });\n pending.then(resolve, reject).finally(() => signal.removeEventListener('abort', aborted));\n if (signal.aborted) aborted();\n });\n }\n}\n","/**\n * Join the configured base URL with an SDK path.\n *\n * A BASE URL MAY CARRY A PATH, NOT JUST AN ORIGIN — a self-host published\n * under `https://api.example.com/palbase`, or an app that routes the browser\n * through its own server (`<origin>/pb`, rewritten upstream) because the\n * Environment's edge does not answer its origin with CORS headers.\n *\n * `new URL('/palbase-sealed-keys.json', base)` reads as the careful way to do\n * this and is the one form that DROPS that path: the leading slash makes the\n * path absolute against the base's ORIGIN. The sealed key store used it while\n * every ordinary request concatenated, so one request in the client asked a\n * different server than all the others — measured live 2026-09-11, the keyset\n * fetch landed on the app's own 404 page and every sealed call failed with\n * `sealed_key_unavailable`. The other two SDK surfaces never had the split:\n * iOS appends (`SealedKeyStore.swift`), Android concatenates onto a\n * slash-trimmed base (`SealedKeyStore.kt`) — this is their shape.\n */\nexport function endpointUrl(base: string, path: string): string {\n return `${base.replace(/\\/+$/, '')}${path}`;\n}\n","import { PalbaseError } from './errors.js';\nimport { wirePlatform } from './platform.js';\nimport { asPowChallenge, solvePowChallenge } from './pow.js';\nimport { openSealedResponse, sealingRequired, sealRequest } from './sealed.js';\nimport { SealedKeyStore } from './sealed-keys.js';\nimport type { TokenManager } from './token.js';\nimport { endpointUrl } from './url.js';\nimport type { HttpClientOptions, PalbaseResponse, RequestOptions } from './types.js';\n\n/**\n * Default production host. Dev / staging / local callers override via\n * `options.url`. Apex-style routing is the only supported production path;\n * Kong resolves Environment identity from the API key.\n */\nconst PALBASE_DEFAULT_HOST = 'api.palbase.studio';\n\n/**\n * Parse the Environment ref from a Palbase API key.\n *\n * Canonical shape: `pb_{environment_ref}_c{random}`, where the Environment ref\n * is 4-24 lowercase ASCII alphanumeric characters and random is AT LEAST 20\n * base62 chars.\n *\n * The length is a floor, not an equality. The stack's own minter writes 20\n * (v2/cmd/palsvc/initenv.go) and the cloud control plane writes 32\n * (cloud/platform/server/services/keys.ts), and the door that admits the\n * request refuses to rule on the difference: *\"a shorter or longer secret is\n * not a security property this door can rule on\"*\n * (v2/internal/platform/identitymw.go: parseAPIKey). A client that is stricter\n * than the server does not add safety — it just refuses working keys, which is\n * exactly what this one did to every cloud project until 2026-08-25.\n *\n * Returns the Environment ref on match; `null` otherwise.\n */\nconst API_KEY_RE = /^pb_([a-z0-9]{4,24})_c[A-Za-z0-9]{20,}$/;\n\nfunction parseEnvironmentRef(apiKey: string): string | null {\n return API_KEY_RE.exec(apiKey)?.[1] ?? null;\n}\nconst MAX_RETRIES = 3;\nconst INITIAL_BACKOFF_MS = 200;\n/**\n * Upper bound on a single 429 retry sleep. A server may return a long\n * Retry-After (a locked account can send minutes/hours); honoring it verbatim\n * would HANG the request for that whole window. Cap each retry at 10s — after\n * MAX_RETRIES the 429 envelope surfaces to the caller (fail fast, don't sleep\n * minutes). The clamp never skips a retry; it only bounds how long each waits.\n */\nconst MAX_RETRY_DELAY_MS = 10_000;\n\n/**\n * Carry a 429's retry hint into the error envelope when only the header has it.\n *\n * A REFUSAL FROM THE EDGE CARRIES NOTHING BUT THE HEADER. Envoy and the\n * gateway limiter answer before any Palbase service is reached, so their 429\n * has no `retry_after` and no `data.retryAfter` — and every reader above this\n * layer (`@palbase/web`'s BackendError, the iOS SDK) looks in the BODY. The\n * seconds were on the wire and unreachable to all of them.\n *\n * Lifted under `retry_after`, the platform's own name for it (palauth's\n * rate-limit envelope), never overwriting a hint the service itself sent — a\n * service knows its window, the edge only knows its own.\n */\nfunction withRetryHint(\n body: Record<string, unknown> | undefined,\n response: Response,\n): Record<string, unknown> | undefined {\n if (response.status !== 429) return body;\n const data = body?.data;\n const alreadyStated =\n typeof body?.retry_after === 'number' ||\n (typeof data === 'object' && data !== null && 'retryAfter' in data);\n if (alreadyStated) return body;\n const seconds = Number.parseInt(response.headers.get('Retry-After') ?? '', 10);\n if (Number.isNaN(seconds) || seconds <= 0) return body;\n return { ...body, retry_after: seconds };\n}\n\n/**\n * Request interceptor. Runs before every HTTP request.\n * Can modify headers, body, or reject the request.\n */\nexport type RequestInterceptor = (request: {\n headers: Record<string, string>;\n method: string;\n path: string;\n}) => void | Promise<void>;\n\nexport class HttpClient {\n protected readonly apiKey: string;\n protected readonly options?: HttpClientOptions;\n\n tokenManager: TokenManager | null = null;\n\n /**\n * Admin JWT used for platform admin endpoints (/admin/*).\n * When set, takes precedence over tokenManager access token in the\n * Authorization header.\n */\n adminToken: string | null = null;\n\n private readonly interceptors: RequestInterceptor[] = [];\n private readonly forbiddenListeners = new Set<(body: Record<string, unknown>) => void>();\n private sealedKeys?: SealedKeyStore;\n\n constructor(apiKey: string, options?: HttpClientOptions) {\n this.apiKey = apiKey;\n this.options = options;\n }\n\n /** Set (or clear) the admin JWT used on admin endpoints. */\n setAdminToken(token: string | null): void {\n this.adminToken = token;\n }\n\n /**\n * Called with the RAW body of every 403 this client receives (FR-010). Core\n * does not know the envelope's fields — the layer that does (palbe) reads\n * `required` out of it. Nothing is retried or swallowed: the error still\n * returns to the caller.\n */\n onForbidden(handler: (body: Record<string, unknown>) => void): () => void {\n this.forbiddenListeners.add(handler);\n return () => {\n this.forbiddenListeners.delete(handler);\n };\n }\n\n /**\n * Create a scoped HttpClient that adds the given extra headers to every\n * request. The returned client shares the admin token and token manager\n * with the parent at runtime — later changes on the parent propagate to\n * the scope and vice versa.\n *\n * Typical use: adding an Environment-routing header for an admin call.\n */\n withHeaders(extra: Record<string, string>): HttpClient {\n const mergedHeaders = { ...(this.options?.headers ?? {}), ...extra };\n\n const scoped: HttpClient = new HttpClient(this.apiKey, {\n ...this.options,\n headers: mergedHeaders,\n });\n scoped.tokenManager = this.tokenManager;\n // Delegate adminToken reads + writes to the parent so the scope always\n // sees the latest token, and setAdminToken on the scope affects the parent.\n // The scope shares the parent's 403 listeners: a refusal is a refusal\n // whichever header set the request carried.\n Object.defineProperty(scoped, 'forbiddenListeners', {\n get: () => this.forbiddenListeners,\n });\n Object.defineProperty(scoped, 'adminToken', {\n get: () => this.adminToken,\n set: (v: string | null) => {\n this.adminToken = v;\n },\n configurable: true,\n });\n Object.defineProperty(scoped, 'sealedKeys', {\n get: () => this.sealedKeys,\n set: (v: SealedKeyStore | undefined) => {\n this.sealedKeys = v;\n },\n });\n return scoped;\n }\n\n /** Add a request interceptor. Runs before every request. */\n addInterceptor(interceptor: RequestInterceptor): void {\n this.interceptors.push(interceptor);\n }\n\n async request<T>(\n method: string,\n path: string,\n options?: RequestOptions,\n ): Promise<PalbaseResponse<T>> {\n // If token is expired and refresh is available, refresh before making the request\n if (\n !options?.skipSessionRefresh &&\n this.tokenManager?.isExpired() &&\n this.tokenManager.getRefreshToken() &&\n this.tokenManager.refreshFunction\n ) {\n try {\n await this.tokenManager.refreshSession();\n } catch (e) {\n const status = e instanceof PalbaseError ? e.status : 0;\n if (status === 400 || status === 401 || status === 403) {\n // Terminal: the refresh token is dead (revoked/expired/forbidden).\n // Clear the session (listeners persist the sign-out) and proceed\n // unauthenticated — the endpoint will 401 into the normal error\n // envelope instead of bricking every subsequent call including\n // the recovery sign-in.\n this.tokenManager.clearSession();\n } else {\n throw e; // network/5xx: transient, stay loud\n }\n }\n }\n\n return this.executeWithRetry<T>(method.toUpperCase(), path, options, 0);\n }\n\n /**\n * A response read as it arrives, for `text/event-stream` routes.\n *\n * Deliberately NOT `executeWithRetry`: a retry replays the request, and a\n * stream the caller has already begun reading cannot be replayed — the frames\n * it handed over would arrive a second time. A stream that fails to open fails\n * to the caller, once, with its status.\n *\n * The buffered path's headers, base URL and interceptors are reused verbatim,\n * so a streaming call is authenticated exactly like every other call; only the\n * body handling differs. `Accept` says what the caller wants, and the status\n * is returned beside the body because the CALLER decides what a non-2xx means\n * (an error envelope arrives as an ordinary buffered body).\n */\n async requestStream(\n method: string,\n path: string,\n options?: RequestOptions,\n ): Promise<{ status: number; body: ReadableStream<Uint8Array> | null; contentType: string }> {\n method = method.toUpperCase();\n if (\n !options?.skipSessionRefresh &&\n this.tokenManager?.isExpired() &&\n this.tokenManager.getRefreshToken() &&\n this.tokenManager.refreshFunction\n ) {\n try {\n await this.tokenManager.refreshSession();\n } catch (e) {\n const status = e instanceof PalbaseError ? e.status : 0;\n if (status === 400 || status === 401 || status === 403) {\n this.tokenManager.clearSession();\n } else {\n throw e;\n }\n }\n }\n\n const url = endpointUrl(this.getBaseUrl(), path);\n const headers = { ...this.buildHeaders(options), Accept: 'text/event-stream' };\n for (const interceptor of this.interceptors) {\n await interceptor({ headers, method, path });\n }\n\n const fetchOptions: RequestInit = { method, headers, signal: options?.signal };\n if (options?.body !== undefined) fetchOptions.body = JSON.stringify(options.body);\n const exporter = await this.prepareSealed(url, path, fetchOptions);\n\n const response = await openSealedResponse(await fetch(url, fetchOptions), exporter, method);\n return {\n status: response.status,\n body: response.body,\n contentType: response.headers.get('content-type') ?? '',\n };\n }\n\n private async prepareSealed(\n url: string,\n path: string,\n init: RequestInit,\n ): Promise<Uint8Array<ArrayBuffer> | undefined> {\n if (this.options?.sealed === false || !sealingRequired(path)) return undefined;\n this.sealedKeys ??= new SealedKeyStore(this.getBaseUrl(), this.apiKey, this.options?.sealed);\n const key = await this.sealedKeys.current(init.signal ?? undefined);\n init.signal?.throwIfAborted();\n try {\n return await sealRequest(key, url, init);\n } catch (error) {\n init.signal?.throwIfAborted();\n if (error instanceof PalbaseError) throw error;\n throw new PalbaseError('sealed_request_failed', 'The request could not be encrypted.', 0);\n }\n }\n\n private getBaseUrl(): string {\n // Explicit URL always wins (local dev, staging, test rigs).\n if (this.options?.url) {\n return this.options.url;\n }\n\n // Validate the key shape up front so apex-routed callers still\n // fail loud on a malformed key instead of hitting the gateway\n // with bad credentials.\n if (this.apiKey && parseEnvironmentRef(this.apiKey) === null) {\n throw new PalbaseError(\n 'invalid_api_key',\n 'Invalid API key format. Expected pb_{environment_ref}_c{at least 20 base62 chars}. For dev/staging pass `url: \"https://api.dev.palbase.studio\"` via options.',\n 0,\n );\n }\n\n return `https://${PALBASE_DEFAULT_HOST}`;\n }\n\n private buildHeaders(options?: RequestOptions): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n // Client identity, the web counterpart of the iOS SDK's\n // ClientInfo.augment(). The server reads these to resolve flag targeting\n // conditions and to label telemetry, so an app declares nothing and calls\n // nothing — whatever the SDK can know, it sends.\n 'X-Platform': wirePlatform(),\n };\n // The host app's own version is not knowable on the web (no bundle to read\n // it from), so it is opt-in; when given it fills the same header iOS fills\n // from CFBundleShortVersionString.\n const appVersion = this.options?.appVersion?.trim();\n if (appVersion) {\n headers['X-Palbase-Client-Version'] = appVersion;\n }\n\n // Palbase Environment keys live in the `apikey` header — never in\n // `Authorization` — because Kong's key-auth resolves them on that\n // header and the gateway's pre-function plugin stamps the downstream\n // identity.\n const effectiveKey = this.apiKey;\n if (effectiveKey) {\n headers['apikey'] = effectiveKey;\n }\n\n // User session token, if any. Kong's pre-function plugin strips\n // Authorization on /v1/* routes anyway (PostgREST has no JWT\n // secret and would crash on a Bearer it can't decode), but\n // sending it preserves the contract for /auth/* endpoints that\n // do consume the bearer (e.g. session refresh).\n const token = this.tokenManager?.getAccessToken();\n if (token) {\n headers['Authorization'] = `Bearer ${token}`;\n }\n\n // adminToken (platform admin JWT) takes precedence — used by the\n // @palbase/admin internal flows that hit /admin/* routes; those\n // routes verify the bearer themselves and aren't subject to the\n // /v1/* Authorization-strip rule.\n if (this.adminToken) {\n headers['Authorization'] = `Bearer ${this.adminToken}`;\n }\n\n // Merge global custom headers\n if (this.options?.headers) {\n Object.assign(headers, this.options.headers);\n }\n\n // Merge per-request headers\n if (options?.headers) {\n Object.assign(headers, options.headers);\n }\n\n return headers;\n }\n\n private async executeWithRetry<T>(\n method: string,\n path: string,\n options: RequestOptions | undefined,\n attempt: number,\n // Headers a PREVIOUS attempt earned and this one has to carry. Today that\n // is only the solved proof-of-work pair; it is a parameter rather than a\n // field because it belongs to one request's second try, and a field would\n // leak it onto every later call made through this client.\n earned?: Record<string, string>,\n rotated = false,\n ): Promise<PalbaseResponse<T>> {\n const url = endpointUrl(this.getBaseUrl(), path);\n const headers = { ...this.buildHeaders(options), ...earned };\n\n // Run interceptors\n for (const interceptor of this.interceptors) {\n await interceptor({ headers, method, path });\n }\n\n const fetchOptions: RequestInit = {\n method,\n headers,\n signal: options?.signal,\n };\n\n if (options?.body !== undefined) {\n fetchOptions.body = JSON.stringify(options.body);\n }\n // A fresh HPKE encapsulation on EVERY attempt: reusing an envelope trips\n // the server replay guard, even when the first response was lost.\n const exporter = await this.prepareSealed(url, path, fetchOptions);\n\n let response: Response;\n try {\n response = await fetch(url, fetchOptions);\n } catch (error) {\n options?.signal?.throwIfAborted();\n // Network error — retry with backoff\n if (options?.retry !== false && attempt < MAX_RETRIES - 1) {\n const backoff = INITIAL_BACKOFF_MS * 2 ** attempt;\n await this.delay(backoff);\n // WITHOUT `earned`, and that is the whole point of this line.\n //\n // A network error means the response was lost, not that the request\n // was. If it reached the server, the challenge is already SPENT —\n // palauth's VerifyChallenge reads and deletes in one step\n // (bot/pow.go:96-104), deliberately, because a proof presented twice is\n // not proof. Replaying the nonce would then answer `pow_invalid`, and\n // the one-solve guard below would refuse to try again: a request one\n // fresh solve away from succeeding, failed. Dropping it costs nothing\n // in the other case — if the server never saw the request, a fresh\n // challenge works exactly as well as the old one.\n return this.executeWithRetry<T>(method, path, options, attempt + 1, undefined, rotated);\n }\n\n // All retries exhausted — throw PalbaseError\n throw new PalbaseError(\n 'network_error',\n error instanceof Error ? error.message : 'Network request failed',\n 0,\n );\n }\n response = await openSealedResponse(response, exporter, method);\n\n // Handle 429 Too Many Requests — retry with Retry-After or backoff;\n // if retries exhausted, fall through to normal error response handling below\n if (response.status === 429) {\n if (options?.retry !== false && attempt < MAX_RETRIES - 1) {\n const retryAfter = response.headers.get('Retry-After');\n const parsed = retryAfter ? Number.parseInt(retryAfter, 10) : Number.NaN;\n // Clamp the server-requested wait: a long Retry-After (locked account)\n // must not hang the request — cap each sleep, exhaust MAX_RETRIES, then\n // fall through to surface the 429 envelope below.\n const delayMs = Number.isNaN(parsed)\n ? INITIAL_BACKOFF_MS * 2 ** attempt\n : Math.min(parsed * 1000, MAX_RETRY_DELAY_MS);\n await this.delay(delayMs);\n // WITH `earned`, unlike the network path above: a 429 is a refusal the\n // server issued INSTEAD of doing the work, so the challenge was never\n // consumed. The edge's rate limiter answers before palsvc, and on the\n // auth routes palauth's own limiter runs BEFORE the proof-of-work\n // middleware (auth/internal/server/server.go: rl.LoginByIP, then powMW).\n return this.executeWithRetry<T>(method, path, options, attempt + 1, earned, rotated);\n }\n }\n\n // Parse response body\n let data: T | null = null;\n let errorBody:\n | { error?: string; error_description?: string; status?: number; required?: string }\n | undefined;\n\n // HEAD responses have no body by spec — skip parsing.\n const contentType = response.headers.get('Content-Type');\n if (\n method !== 'HEAD' &&\n ![204, 205, 304].includes(response.status) &&\n contentType?.includes('json')\n ) {\n const body = (await response.json()) as Record<string, unknown>;\n if (response.ok) {\n data = body as T;\n } else {\n errorBody = body as typeof errorBody;\n }\n }\n\n if (\n exporter &&\n !rotated &&\n response.status === 400 &&\n errorBody?.error === 'sealed_unknown_kid'\n ) {\n await this.sealedKeys?.current(options?.signal, true);\n return this.executeWithRetry<T>(method, path, options, attempt, earned, true);\n }\n\n // Proof-of-work: /auth/signup and /auth/token sit behind a bot gate that\n // answers an unsolved request with 403 and the challenge in the body. Solve\n // it and repeat the request carrying the two headers; the caller never\n // learns the gate is there.\n //\n // HERE, in core, because this is the layer that issues the request for every\n // client in the repo — @palbase/auth's sign-in, @palbase/web's facades, the\n // server SDK. The same retry lived one layer up in @palbase/web until\n // 2026-08-18 and covered everything EXCEPT `pb.auth.*`, which reaches the\n // network through this method; so the gate stayed unsatisfiable on exactly\n // the two endpoints it guards.\n //\n // ONE retry, and only when the body really carries a challenge: `earned`\n // being set already means this IS the second try. A 403 that says\n // pow_required without a challenge is a server the client cannot satisfy,\n // and looping on it would turn a broken gate into a hang.\n if (response.status === 403 && !earned) {\n const challenge = asPowChallenge(errorBody);\n if (challenge) {\n return this.executeWithRetry<T>(\n method,\n path,\n options,\n attempt,\n await solvePowChallenge(challenge, undefined, options?.signal),\n rotated,\n );\n }\n }\n\n if (!response.ok) {\n if (response.status === 403 && errorBody !== undefined) {\n const body: Record<string, unknown> = errorBody;\n for (const listener of this.forbiddenListeners) {\n try {\n listener(body);\n } catch {\n // A consumer's handler must not turn a well-formed refusal into a\n // thrown error, nor stop the listeners after it (same rule as\n // internal.ts' configured listeners).\n }\n }\n }\n return {\n data: null,\n error: new PalbaseError(\n errorBody?.error ?? 'unknown_error',\n errorBody?.error_description ?? response.statusText,\n response.status,\n withRetryHint(errorBody, response),\n ),\n status: response.status,\n };\n }\n\n // Parse PostgREST Content-Range for count queries (e.g. \"0-9/42\" or \"*/42\").\n const contentRange = response.headers.get('Content-Range');\n let count: number | undefined;\n if (contentRange) {\n const slash = contentRange.lastIndexOf('/');\n if (slash >= 0) {\n const totalPart = contentRange.slice(slash + 1);\n if (totalPart !== '*') {\n const parsed = Number.parseInt(totalPart, 10);\n if (!Number.isNaN(parsed)) {\n count = parsed;\n }\n }\n }\n }\n\n // Header names are case-insensitive and `Headers.get` already honours that;\n // the wire spells this one lowercase.\n const etag = response.headers.get('etag');\n\n return {\n data,\n error: null,\n status: response.status,\n ...(count !== undefined ? { count } : {}),\n ...(etag ? { etag } : {}),\n };\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n","import type { AuthStateCallback, Session, Unsubscribe } from './types.js';\n\nexport class TokenManager {\n private session: Session | null = null;\n private listeners: Set<AuthStateCallback> = new Set();\n private refreshPromise: Promise<void> | null = null;\n private refreshing = false;\n\n refreshFunction: ((refreshToken: string) => Promise<Session>) | null = null;\n\n setSession(session: Session): void {\n this.session = session;\n this.notify('SESSION_SET', session);\n }\n\n getAccessToken(): string | null {\n return this.session?.accessToken ?? null;\n }\n\n getRefreshToken(): string | null {\n return this.session?.refreshToken ?? null;\n }\n\n clearSession(): void {\n this.session = null;\n this.notify('SESSION_CLEARED', null);\n }\n\n isExpired(): boolean {\n if (!this.session) return true;\n return Date.now() >= this.session.expiresAt;\n }\n\n async refreshSession(): Promise<void> {\n if (!this.session?.refreshToken || !this.refreshFunction) {\n return;\n }\n\n // Collapse concurrent refresh calls into a single request\n if (this.refreshPromise) {\n return this.refreshPromise;\n }\n\n // Re-entrancy guard: the wired refreshFunction issues its own HTTP request\n // (POST /auth/token/refresh) through HttpClient, whose pre-flight calls\n // refreshSession() again SYNCHRONOUSLY — before `refreshPromise` below is\n // assigned (the whole chain runs before the first real await). Without\n // this flag that recursion is unbounded (stack overflow). Returning early\n // lets the refresh request itself proceed unauthenticated — it carries\n // the refresh token in its body, not the Bearer header.\n if (this.refreshing) {\n return;\n }\n\n this.refreshing = true;\n this.refreshPromise = this.executeRefresh(this.session.refreshToken);\n\n try {\n await this.refreshPromise;\n } finally {\n this.refreshPromise = null;\n this.refreshing = false;\n }\n }\n\n onAuthStateChange(callback: AuthStateCallback): Unsubscribe {\n this.listeners.add(callback);\n return () => {\n this.listeners.delete(callback);\n };\n }\n\n private async executeRefresh(refreshToken: string): Promise<void> {\n if (!this.refreshFunction) return;\n const startedSession = this.session;\n try {\n const newSession = await this.refreshFunction(refreshToken);\n // Sign-out, a new sign-in, or another session adoption takes precedence\n // over a refresh that started against an older session.\n if (this.session === startedSession) this.setSession(newSession);\n } catch (error) {\n // The caller would clear its session on a terminal refresh error. An\n // error from an older session must not clear a newer one.\n if (this.session === startedSession) throw error;\n }\n }\n\n private notify(event: 'SESSION_SET' | 'SESSION_CLEARED', session: Session | null): void {\n for (const listener of this.listeners) {\n listener(event, session);\n }\n }\n}\n","/** The client a tenant's tests use to call their own backend.\n *\n * These tests run against a REAL deployment — the release the deploy just built,\n * serving from the same Environment as production, with the same database, the\n * same secrets and the same gateway in front of it. So this client is a plain\n * HTTP client, not a simulation: every call crosses the gateway, the API key\n * check, the auth rail, the zod validation at the boundary, and row-level\n * security, exactly as a shipped app's call does.\n *\n * There is deliberately no schema knowledge here. The tenant already wrote their\n * types — `import type { TodoSchema } from \"../models/todos/shared.js\"` — so a\n * test types its own call (`api.get<TodoSchema[]>(\"/todos\")`) and can validate it\n * with the same zod schema the endpoint declares. A second generated client would\n * be a second thing to keep in step.\n */\n\nimport { asPowChallenge, solvePowChallenge } from \"@palbase/core\";\n\n/** How to reach the release under test. Supplied by the deploy, never guessed. */\nexport interface TestApiConfig {\n baseUrl: string;\n apiKey: string;\n /** This deploy's secret. Without it the request is served the LIVE release.\n *\n * OPTIONAL against a stack running on this machine: a local stack serves one\n * version — the directory `palbase start` mounted — so there is no candidate\n * to select. Required everywhere else. */\n candidateToken?: string;\n /** The run's minted logins, keyed by the name declared in config/test-users.ts. */\n identities?: Record<string, TestIdentity>;\n /** The fetch to use. Injected by tests of this client; production passes none. */\n fetch?: typeof fetch;\n}\n\n/** One login the deploy minted for this run.\n *\n * `accessToken` is the session issued when the identity was created, and is what\n * `signInAs` uses. The credentials come along for a test that wants to exercise\n * the login rail itself — but a suite that switches users repeatedly must not be\n * signing in each time: those calls come from one address and trip the login rate\n * limiter, failing tests for a reason that has nothing to do with the code\n * under test.\n */\nexport interface TestIdentity {\n id?: string;\n email: string;\n password: string;\n accessToken?: string;\n}\n\n/** One call the suite made, in the order it was made. */\nexport interface RecordedRequest {\n method: string;\n path: string;\n status: number;\n ms: number;\n}\n\n/** A non-2xx answer, carrying the platform's error envelope.\n *\n * The envelope is the contract every Palbase endpoint answers with, so a test\n * asserts on `status`/`error`/`data` rather than parsing a message. The message\n * exists for the human reading a failed deploy.\n */\nexport class TestApiError extends Error {\n readonly status: number;\n readonly error: string;\n /** Payload of an error your code threw — `new BadRequest({ fields })` arrives here. */\n readonly data: unknown;\n /** The whole envelope, exactly as the server sent it. */\n readonly body: ErrorEnvelope;\n\n constructor(method: string, path: string, status: number, body: unknown) {\n const envelope = (body ?? {}) as ErrorEnvelope;\n const code = envelope.error ?? String(status);\n super(`${method} ${path} → ${status} ${code}${envelope.error_description ? `: ${envelope.error_description}` : \"\"}`);\n this.name = \"TestApiError\";\n this.status = status;\n this.error = code;\n this.data = envelope.data;\n this.body = envelope;\n }\n}\n\n/** A Palbase error response.\n *\n * `data` carries the payload of an error your code threw. Validation refused at\n * the boundary — before your handler runs — answers with `details` instead, one\n * entry per field. The index signature is deliberate: whatever the server sends\n * is readable from a test, so no assertion is ever blocked on this type being\n * exhaustive.\n */\nexport interface ErrorEnvelope {\n error?: string;\n error_description?: string;\n status?: number;\n request_id?: string;\n data?: unknown;\n details?: Array<{ field: string; message: string }>;\n [key: string]: unknown;\n}\n\nexport interface CallOptions {\n headers?: Record<string, string>;\n}\n\nexport interface TestApi {\n get<T = unknown>(path: string, opts?: CallOptions): Promise<T>;\n post<T = unknown>(path: string, body?: unknown, opts?: CallOptions): Promise<T>;\n patch<T = unknown>(path: string, body?: unknown, opts?: CallOptions): Promise<T>;\n put<T = unknown>(path: string, body?: unknown, opts?: CallOptions): Promise<T>;\n delete<T = unknown>(path: string, opts?: CallOptions): Promise<T>;\n /** HTTP QUERY (RFC 10008): a safe, idempotent read whose filter travels in the body. */\n query<T = unknown>(path: string, body?: unknown, opts?: CallOptions): Promise<T>;\n /** Sign in with credentials you supply. */\n signIn(credentials: { email: string; password: string }): Promise<{ id: string; email?: string }>;\n /**\n * Sign in as one of the identities this run was given, by the name you\n * declared it under in `config/test-users.ts`.\n *\n * Each is minted by the platform for the length of ONE deploy, seeded with the\n * data that declaration describes, and retired after — which is why this works\n * on every Environment including production, where a committed fixture password\n * is refused on purpose.\n */\n signInAs(name: string): Promise<{ id: string; email?: string }>;\n signOut(): Promise<void>;\n /** Drop the bearer without calling the server — the anonymous caller. */\n asAnonymous(): void;\n /** Every call made, in order. Printed for the failing test in a red deploy. */\n readonly requests: readonly RecordedRequest[];\n}\n\nfunction required(value: string, envName: string): string {\n if (!value) {\n throw new Error(\n `${envName} is not set — the test client has nowhere to send requests. ` +\n `This is set by the deploy that runs your tests; if you are running them by hand, set it yourself.`,\n );\n }\n return value;\n}\n\n/** A stack running on this machine. There is exactly ONE version there — the\n * directory `palbase start` mounted — so there is no candidate to select, and\n * demanding a token for one made local runs invent a value to satisfy a header\n * nothing reads. */\nfunction isLocalTarget(baseUrl: string): boolean {\n try {\n const { hostname } = new URL(baseUrl);\n return hostname === \"127.0.0.1\" || hostname === \"localhost\" || hostname === \"[::1]\" || hostname === \"::1\";\n } catch {\n return false;\n }\n}\n\n/** Seconds until a JWT's `exp`, or null when the token carries no readable one.\n * Read WITHOUT verifying: this is a diagnosis, never a decision — the server\n * remains the only authority on whether a token is good. */\nfunction secondsUntilExpiry(token: string): number | null {\n const body = token.split(\".\")[1];\n if (!body) return null;\n try {\n const claims = JSON.parse(Buffer.from(body, \"base64url\").toString(\"utf8\")) as { exp?: unknown };\n return typeof claims.exp === \"number\" ? claims.exp - Math.floor(Date.now() / 1000) : null;\n } catch {\n return null;\n }\n}\n\nexport function createTestApi(config: TestApiConfig): TestApi {\n const baseUrl = required(config.baseUrl, \"PALBASE_TEST_BASE_URL\").replace(/\\/$/, \"\");\n const apiKey = required(config.apiKey, \"PALBASE_TEST_API_KEY\");\n const local = isLocalTarget(baseUrl);\n // Local stacks serve one version, so there is nothing to select. Everywhere\n // else the token stays REQUIRED: without it the gateway serves the LIVE\n // release and the suite would grade code that is not under test.\n const candidateToken = local ? (config.candidateToken ?? \"\") : required(config.candidateToken ?? \"\", \"PALBASE_TEST_CANDIDATE\");\n const doFetch = config.fetch ?? fetch;\n\n const requests: RecordedRequest[] = [];\n let bearer: string | null = null;\n\n async function call<T>(method: string, path: string, body: unknown, opts: CallOptions = {}): Promise<T> {\n const headers: Record<string, string> = {\n apikey: apiKey,\n // Selects the release under test. Omit it and the gateway serves the LIVE\n // one, which would make the whole suite grade the wrong code. Absent only\n // against a local stack, which has a single version.\n ...(candidateToken ? { \"x-palbase-candidate\": candidateToken } : {}),\n ...opts.headers,\n };\n if (bearer) headers.authorization = `Bearer ${bearer}`;\n if (body !== undefined) headers[\"content-type\"] = \"application/json\";\n\n const startedAt = Date.now();\n const res = await doFetch(`${baseUrl}${path}`, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n const text = await res.text();\n const parsed: unknown = text ? safeParse(text) : undefined;\n\n requests.push({ method, path, status: res.status, ms: Date.now() - startedAt });\n\n if (!res.ok) {\n // A 401 on a token that has simply RUN OUT is the most likely 401 a suite\n // sees, and the least legible: the mint issues ~30 minutes, so a file of\n // credentials written yesterday answers `401 unauthorized` with nothing to\n // act on. Measured on a customer run: the next step taken was to blame the\n // credentials rather than their age.\n if (res.status === 401 && bearer) {\n const left = secondsUntilExpiry(bearer);\n if (left !== null && left <= 0) {\n throw new TestApiError(method, path, res.status, {\n error: \"access_token_expired\",\n error_description:\n `this run's access token EXPIRED ${Math.abs(left)}s ago — a test identity is minted for the ` +\n `length of ONE deploy, so a saved token does not survive to the next run. Re-mint it ` +\n \"(`palbase test-user create --json`, or let `palbase test` do it) and run again.\",\n });\n }\n }\n throw new TestApiError(method, path, res.status, parsed);\n }\n return parsed as T;\n }\n\n return {\n requests,\n get: (path, opts) => call(\"GET\", path, undefined, opts),\n post: (path, body, opts) => call(\"POST\", path, body, opts),\n patch: (path, body, opts) => call(\"PATCH\", path, body, opts),\n put: (path, body, opts) => call(\"PUT\", path, body, opts),\n delete: (path, opts) => call(\"DELETE\", path, undefined, opts),\n query: (path, body, opts) => call(\"QUERY\", path, body, opts),\n\n async signInAs(name) {\n const identity = (config.identities ?? {})[name];\n if (!identity) {\n const declared = Object.keys(config.identities ?? {});\n throw new Error(\n `no test identity named ${JSON.stringify(name)} — the deploy mints one per user declared in ` +\n `config/test-users.ts` +\n (declared.length\n ? `; this run has: ${declared.join(\", \")}`\n : // Not \"you declared none\": from here the two causes are\n // indistinguishable, and blaming the customer's config for a\n // platform failure sends them to look in the wrong file. The\n // deploy log names which one it was.\n \", and this run has none — either your config declares no users \" +\n \"or the deploy could not mint them; the deploy log says which\"),\n );\n }\n // The session the mint already issued — no network call, so switching\n // users is free and the login rail never sees this run.\n if (identity.accessToken) {\n bearer = identity.accessToken;\n return { id: identity.id ?? \"\", email: identity.email };\n }\n return this.signIn(identity);\n },\n\n async signIn(credentials) {\n // PROOF-OF-WORK IS PART OF LOGGING IN, so a client that cannot solve one\n // cannot log in at all. The web SDK has solved it since bot protection\n // shipped; this harness went straight to `fetch` and therefore answered\n // `403 pow_required` on every password login — which made the whole\n // credentials path DEAD on a stack with the gate on, exactly when a\n // suite falls back to it because its minted token ran out.\n //\n // One retry, and only when the refusal really carries a challenge: a 403\n // saying pow_required without one is a server this client cannot satisfy,\n // and looping would turn a broken gate into a hang. Same rule as\n // @palbase/core's own retry.\n const attempt = async (extra?: Record<string, string>) =>\n call<{ access_token: string; user?: { id: string; email?: string } }>(\n \"POST\",\n \"/auth/login\",\n credentials,\n extra ? { headers: extra } : {},\n );\n\n let result: { access_token: string; user?: { id: string; email?: string } };\n try {\n result = await attempt();\n } catch (e) {\n const refusal = e as { status?: number; body?: unknown };\n const challenge = refusal.status === 403 ? asPowChallenge(refusal.body) : null;\n if (!challenge) throw e;\n result = await attempt(await solvePowChallenge(challenge));\n }\n bearer = result.access_token;\n return result.user ?? { id: \"\" };\n },\n async signOut() {\n await call(\"POST\", \"/auth/logout\", undefined);\n bearer = null;\n },\n asAnonymous() {\n bearer = null;\n },\n };\n}\n\n/** The run's identities, as the deploy passed them. Absent is not an error: a\n * project that declares none still runs every test that needs no login. */\nfunction parseIdentities(raw: string | undefined): Record<string, TestIdentity> {\n if (!raw) return {};\n try {\n return JSON.parse(raw) as Record<string, TestIdentity>;\n } catch {\n return {};\n }\n}\n\nfunction safeParse(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/** The client the deploy configured, from the environment it set.\n *\n * Constructed lazily so importing this module outside a test run — a typecheck,\n * an editor — does not fail on absent configuration.\n */\nlet configured: TestApi | null = null;\n\nexport const api: TestApi = new Proxy({} as TestApi, {\n get(_target, prop) {\n configured ??= createTestApi({\n baseUrl: process.env.PALBASE_TEST_BASE_URL ?? \"\",\n apiKey: process.env.PALBASE_TEST_API_KEY ?? \"\",\n candidateToken: process.env.PALBASE_TEST_CANDIDATE ?? \"\",\n identities: parseIdentities(process.env.PALBASE_TEST_IDENTITIES),\n });\n return Reflect.get(configured, prop, configured);\n },\n});\n","import \"reflect-metadata\";\n\nimport type { Token } from \"../container.js\";\n\nexport interface IsolatedContainer {\n /** Substitutes a token. Chainable; the last write for a token wins. */\n with<T>(t: Token<T>, v: T): IsolatedContainer;\n get<T>(t: Token<T>): T;\n}\n\n/**\n * How a test replaces a dependency.\n *\n * Rebuilds the graph with the overrides in place and never touches the process\n * singleton cache, so the next test in the same process does not meet a doubled\n * instance left behind by this one. Substitution is DEEP: `Report` asks for\n * `Money` and gets whatever the graph was rebuilt with, however many hops down.\n *\n * Substitution is by `with` alone — there is no separate platform map, because\n * platform services are ambient rather than injected (FR-005).\n *\n * Module boundaries are NOT enforced here, deliberately. They are a build-time\n * rule about the shipped application; making a unit test fail on them would\n * force every test to restate a module layout it is not testing. What a test\n * gets is a graph, not a second opinion about the architecture.\n */\nexport function isolated(): IsolatedContainer {\n const over = new Map<Token, unknown>();\n const local = new Map<Token, unknown>();\n\n const make = (c: Token): unknown => {\n if (over.has(c)) return over.get(c);\n const hit = local.get(c);\n if (hit !== undefined) return hit;\n const meta = (Reflect.getMetadata(\"design:paramtypes\", c) as unknown[] | undefined) ?? [];\n const inst = new (c as unknown as new (...a: unknown[]) => unknown)(\n ...meta.map((d) => make(d as Token)),\n );\n local.set(c, inst);\n return inst;\n };\n\n const api: IsolatedContainer = {\n with<T>(t: Token<T>, v: T): IsolatedContainer {\n over.set(t as Token, v);\n return api;\n },\n get<T>(t: Token<T>): T {\n return make(t as Token) as T;\n },\n };\n return api;\n}\n","export interface InsertManyOptions<Key extends string = string> {\n onConflict?: readonly Key[];\n /** Defaults to ignore when onConflict is supplied. */\n action?: \"ignore\" | \"update\";\n /** false returns the affected row count and skips row serialization. */\n returning?: boolean;\n}\n\nexport function validateInsertManyOptions(opts: InsertManyOptions | undefined): void {\n if (!opts) return;\n if (opts.returning !== undefined && typeof opts.returning !== \"boolean\") throw new Error(\"insertMany returning must be a boolean\");\n if (opts.action !== undefined && opts.action !== \"ignore\" && opts.action !== \"update\") throw new Error(\"insertMany action must be ignore or update\");\n if (opts.onConflict !== undefined && (!Array.isArray(opts.onConflict) || opts.onConflict.some(c => typeof c !== \"string\" || c.length === 0))) {\n throw new Error(\"insertMany onConflict must be an array of column names\");\n }\n if (opts.action !== undefined && !opts.onConflict?.length) throw new Error(\"insertMany action requires nonempty onConflict columns\");\n}\n","/**\n * The refusals a Database call gets BEFORE any SQL exists — written once, so the\n * engine and the test double cannot disagree about them.\n *\n * WHY THIS FILE EXISTS. `fakeDatabase()` is a second implementation of the same\n * surface (`__tests__/helpers/mock-db.ts`), and it never touched `compileWhere`\n * or `asBindParams`. Measured against the published 24.1.0: all four of the\n * calls that release had just started refusing went through the fake SILENTLY —\n * `update{title:undefined}`, `insert{title:undefined}`, `findMany{done:{}}`,\n * `deleteMany{owner,created_at:{}}`.\n *\n * The scaffold tells authors to test the service layer against exactly that\n * fake. So a test went green on a call production would throw on, and the\n * author found out in production instead — the same \"the surface does not match\n * the engine\" shape these refusals exist to end, arriving through the door the\n * SDK hands people for testing.\n *\n * These are pure and SQL-free on purpose: an in-memory store can run them as\n * easily as the driver path can.\n */\n\n/**\n * İşaretçilerin MARKASI — `col()` ve `sqlFragment()` ürünlerini bu süreçte\n * üretilmiş olmakla tanımlar.\n *\n * NEDEN ŞEKİL DEĞİL DE MARKA (gözcü W2-A/C1 ve W2-B/C3, ikisi de ÖLÇTÜ):\n * şekil kontrolü, işaretçiyi güvenilmeyen bir istek gövdesinden UYDURULABİLİR\n * kılıyordu. Ölçülen iki sonuç:\n *\n * findMany(\"docs\", { owner_id: JSON.parse('{\"$col\":\"owner_id\"}') })\n * → WHERE true AND t.\"owner_id\" = t.\"owner_id\" ← kiracılık predikatı totoloji\n * findMany(\"todos\", JSON.parse('{\"$sql\":{\"text\":[\"1=1 -- pwned\"],\"values\":[]}}'))\n * → WHERE true AND 1=1 -- pwned ← saldırganın metni SQL'e HARFİYEN\n *\n * `{ where: { tenant_id: tid, ...req.body.filter } }` bu SDK'nın öğrettiği\n * desen; T010/T014 öncesinde aynı anahtarlar \"bilinmeyen operatör\" diye\n * REDDEDİLİYORDU. Marka o reddi geri getiriyor.\n *\n * Sembol GLOBAL kayıttan (`Symbol.for`) ve ENUMERABLE DEĞİL. İkisi de kasıtlı:\n * global kayıt paketin iki kopyası arasında da eşleşir; enumerable olmaması ise\n * `JSON.stringify` ve `{...ref, gt: 5}` yayılımının markayı DÜŞÜRMESİNİ sağlar —\n * yani telden geçen ya da elle karıştırılan hiçbir şey işaretçi sayılmaz.\n * Kardeş özellik (`increment`) zaten `Symbol.for(\"palbase.tx.expr\")` kullanıyor;\n * bu onun aynısı.\n */\nconst REF_BRAND = Symbol.for(\"palbase.db.ref\");\n\n/** İşaretçiyi markalar. Yalnız `col()` ve `sqlFragment()` çağırır. */\nexport function brandRef<T extends object>(v: T, kind: \"col\" | \"sql\" | \"ref\"): T {\n Object.defineProperty(v, REF_BRAND, { value: kind, enumerable: false });\n return v;\n}\n\nfunction brandOf(v: unknown): unknown {\n if (typeof v !== \"object\" || v === null) return undefined;\n // KENDİ özelliği olmalı, prototip zincirinden MİRAS ALINMIŞ değil:\n // `Object.create(col(\"x\"))` markayı zincirden okuyup işaretçi sayılıyordu\n // (gözcü ölçtü). Telden erişilemez — JSON `__proto__` üstünden sembol\n // yazamaz — ama daraltmak bedava ve \"işaretçi bu süreçte ÜRETİLDİ\"\n // iddiasının tam karşılığı budur.\n return Object.hasOwn(v, REF_BRAND) ? (v as Record<symbol, unknown>)[REF_BRAND] : undefined;\n}\n\n/**\n * Bir değer, MARKASIZ bir işaretçi taklidi mi? (`{$col:…}` / `{$sql:…}`)\n *\n * Üst düzeyde bunlar zaten \"bilinmeyen operatör\" diye reddediliyor. Ama\n * operatörün SAĞINDA — `{ amount: { gt: {\"$col\":\"other\"} } }` — sessizce\n * PARAMETRE olarak bağlanıyorlardı: sayısal kolonda sürücünün 22P02'si,\n * jsonb/text kolonunda ise HİÇBİR SATIR, hatasız (gözcü ölçtü).\n *\n * `in` listesindeki aynı kusur adıyla reddediliyor; bu onun bir seviye\n * yanındaki hâli ve aynı cevabı hak ediyor.\n */\nexport function looksLikeUnbrandedRef(v: unknown): \"col\" | \"sql\" | \"expr\" | null {\n if (typeof v !== \"object\" || v === null) return null;\n if (brandOf(v) !== undefined) return null; // gerçek işaretçi\n if (isColumnExpr(v)) return null; // gerçek ifade tutamağı (kendi markası var)\n const o = v as { $col?: unknown; $sql?: unknown; $expr?: unknown };\n if (typeof o.$col === \"string\") return \"col\";\n if (o.$sql !== undefined && typeof o.$sql === \"object\" && o.$sql !== null) return \"sql\";\n // `$expr` `now()`/`increment()`'in TEL BİÇİMİ. `now()` filtrede geçerli bir\n // değer olduğu andan itibaren bu şekil de uydurulabilir hâle geldi: ÖLÇÜLDÜ,\n // gövdeden gelen `{\"$expr\":{\"fn\":\"now\"}}` sessizce PARAMETRE olarak bağlanıp\n // sorguyu hatasız biçimde boş sonuca çeviriyordu. `$col`/`$sql`/`$ref` ile\n // aynı kapı, aynı gerekçe.\n if (o.$expr !== undefined && typeof o.$expr === \"object\" && o.$expr !== null) return \"expr\";\n return null;\n}\n\n/**\n * `col()` ürünü mü? (FR-011)\n *\n * Burada, çünkü bu dosya \"iki uygulamanın da okuduğu kurallar\" dosyası: motor,\n * `fakeDatabase` ve guard AYNI cevabı vermek zorunda.\n */\nexport function isColRef(v: unknown): v is { readonly $col: string } {\n return brandOf(v) === \"col\" && typeof (v as { $col?: unknown }).$col === \"string\";\n}\n\n/**\n * `sqlFragment` ürünü mü? (FR-018)\n *\n * `isColRef` ile aynı gerekçeyle burada: motor, guard ve `fakeDatabase` üçü de\n * aynı cevabı vermek zorunda — biri fragment'i \"kolon haritası\" sanarsa filtre\n * sessizce düşer.\n */\n/**\n * Plan REFERANSI mı? (`{ $ref: { op, field } }`)\n *\n * `$ref` bu dilin MARKASIZ KALAN TEK işaretçisiydi — `engine/db.ts` onu\n * `\"$ref\" in v` diye tanıyordu — ve SDK'nın öğrettiği desen\n * `{ where: { tenant_id: tid, ...req.body.filter } }`. Ölçüldü (gözcü):\n * istek gövdesinden gelen `{\"id\":{\"$ref\":{\"op\":0,\"field\":\"id\"}}}` filtreyi\n * ÖNCEKİ bir işlemin satır değeriyle karşılaştırtıyor —\n * DELETE … WHERE t.\"tenant_id\" = $1 AND t.\"id\" = $2 PRM [\"t1\",\"SIZAN_DEGER\"]\n * gövdenin hiç görmediği bir değer. Enjeksiyon değil (değerler bound) ama bir\n * ORACLE: `op`/`field` seçip `rows_affected`'tan o değeri öğrenmek.\n *\n * Marka `Symbol.for` olduğu için SDK'nın İKİ KOPYASI arasında da eşleşiyor —\n * kontrolcü bundle'ı kendi kopyasını inline ediyor, planı çalıştıran ise\n * runtime'ınki. Ve plan gövdesi JSON'lanmıyor: tek üretim `txPlan` uygulaması\n * süreç içi (`engine/db.ts`), doğrulandı.\n */\nexport function isPlanRef(v: unknown): v is { readonly $ref: { op: number; field: string } } {\n if (brandOf(v) !== \"ref\") return false;\n const r = (v as { $ref?: { op?: unknown; field?: unknown } }).$ref;\n return r !== undefined && typeof r.op === \"number\" && typeof r.field === \"string\";\n}\n\n/** Markasız bir `{ $ref: … }` taklidi mi? Adıyla reddedilmesi için. */\nexport function looksLikeUnbrandedPlanRef(v: unknown): boolean {\n if (typeof v !== \"object\" || v === null || brandOf(v) !== undefined) return false;\n const r = (v as { $ref?: unknown }).$ref;\n return r !== undefined && typeof r === \"object\" && r !== null;\n}\n\nexport function isSqlFragment(v: unknown): v is { readonly $sql: { text: string[]; values: unknown[] } } {\n if (brandOf(v) !== \"sql\") return false;\n const f = (v as { $sql?: { text?: unknown; values?: unknown } }).$sql;\n return f !== undefined && Array.isArray(f.text) && Array.isArray(f.values);\n}\n\n/**\n * İFADE TUTAMAĞI DEĞER DEĞİLDİR — değer bekleyen yollarda adıyla reddedilir.\n *\n * `increment()` / `decrement()` / `now()` bir Proxy döndürür ve yalnız\n * `updateMany` ile plan yolunun `updateWhere`'i onu SQL'e derler. `insert` /\n * `update` / `put` / `supersede` derlemez; oralarda tutamak bound parametre\n * olarak sürücüye gidiyordu ve reddi SÜRÜCÜ veriyordu (\"Unknown object is not\n * a valid PostgreSQL type\") — yazarın yazdığı hiçbir şeyi adlandırmayan bir\n * mesaj (inceleme I-2/I8, ölçüldü). Plan yolu aynı hatayı kendi diliyle\n * reddediyor; bu, doğrudan yolun karşılığı.\n *\n * Sembol `tx-plan.ts`'in markasıyla AYNI global kayıttan okunuyor; bu dosya\n * kural dosyası olduğu için oraya bağımlılık kurmuyor.\n */\nconst TX_EXPR = Symbol.for(\"palbase.tx.expr\");\n\n/**\n * `now()` — SUNUCU SAATİ, karşılaştırma değeri olarak.\n *\n * `increment()`/`decrement()` bir YAZMA ifadesidir ve filtrede anlamsızdır;\n * `now()` öyle değil: `expires_at > now()` sıradan bir karşılaştırma ve her\n * backend'in en sık yazdığı yüklemlerden biri. Filtrede TÜM ifade tutamaklarını\n * reddetmek, yazarı bunun için `sqlFragment`e düşürüyordu — yani sorgunun\n * içine giren parça, en sıradan koşul için gerekiyordu.\n *\n * Ayrım MARKAYLA: bir istek gövdesinden gelen `{\"$expr\":{\"fn\":\"now\"}}` bu\n * süreçte `now()` ile üretilmediği için marka taşımaz ve reddedilir.\n */\nexport function isNowExpr(v: unknown): boolean {\n if (!isColumnExpr(v)) return false;\n try {\n const e = (v as Record<symbol, unknown>)[TX_EXPR];\n return typeof e === \"object\" && e !== null && (e as { fn?: unknown }).fn === \"now\";\n } catch {\n return false;\n }\n}\n\nexport function isColumnExpr(v: unknown): boolean {\n if (typeof v !== \"object\" && typeof v !== \"function\") return false;\n if (v === null) return false;\n try {\n return (v as Record<symbol, unknown>)[TX_EXPR] !== undefined;\n } catch {\n // Tutamak bir Proxy; bilinmeyen bir prop'ta trap fırlatabilir.\n return false;\n }\n}\n\n/**\n * Değer bekleyen bir yazma yolunda ifade tutamağı ya da `col()` var mı?\n *\n * Motor ve `fakeDatabase` AYNI cevabı vermek zorunda: fake tutamağı satıra\n * YAZIYORDU (`row[k] = proxy`) ve satır artık JSON'a bile çevrilemiyordu, motor\n * ise sürücüde patlıyordu. İki farklı yanlış, tek doğru.\n */\nexport function assertNoExpressionHandles(\n caller: string,\n table: string,\n cols: readonly string[],\n data: Record<string, unknown>,\n): void {\n for (const c of cols) {\n const v = data[c];\n // `now()` ile sayaç ifadeleri AYRI cevaplar hak ediyor: ikisinin de\n // çalışan alternatifi var ama farklı (P6 — hata çalışan bir alternatifi\n // ADIYLA söyler). Tek bir \"ifade tutamağı\" mesajı, `now()` yazan kişiye\n // `increment()` öneriyordu.\n if (isNowExpr(v)) {\n throw new Error(\n `${caller}(${table}): \"${c}\" now() aldı — bu yolda değer beklenir. ` +\n `Satır EKLENİRKEN sunucu saatini yazmanın yolu kolonu defaultNow() ile ` +\n `bildirmek (varsayılan kolonun yanında durur, her çağrıda tekrarlanmaz); ` +\n `var olan bir satırı damgalamak için updateMany({ where, set: { ${c}: now() } }) ` +\n `ya da $transaction içinde tx.public.${table}.updateWhere(where, { ${c}: now() }).`,\n );\n }\n if (isColumnExpr(v)) {\n throw new Error(\n `${caller}(${table}): \"${c}\" bir ifade tutamağı aldı (increment()/decrement()). ` +\n `Bu yolda değer beklenir. Sayaç artışı için updateMany({ where, set: { ${c}: increment(n) } }) ` +\n `ya da $transaction içinde tx.public.${table}.updateWhere(where, { ${c}: increment(n) }) kullanın.`,\n );\n }\n if (isColRef(v)) {\n throw new Error(\n `${caller}(${table}): \"${c}\" bir col() aldı. Kolon referansı yalnız FİLTREDE durabilir; ` +\n `bir kolonun değerini başka bir kolona yazmak için $query kullanın.`,\n );\n }\n }\n}\n\n/** The comparison operators a filter value may carry. Kept here because the\n * guard has to tell an operator object from a plain value. */\nconst KNOWN_OPS = new Set([\n \"gt\", \"gte\", \"lt\", \"lte\", \"neq\", \"in\",\n // K1 metin operatörleri (FR-005) ve null testi (FR-006). Bu küme\n // `fakeDatabase()` ile ORTAK kaynaktır: fake bir çağrıyı motorun reddettiği\n // yerde kabul ederse, yazarın testi üretimde patlayan koda karşı yeşil verir.\n \"contains\", \"icontains\", \"startsWith\", \"endsWith\", \"isNull\",\n]);\n\n/**\n * `eq` ADIYLA reddedilir, ve reddi buradadır çünkü guard'ı motor da fake de\n * okuyor.\n *\n * Eşitliğin yazımı ÇIPLAK DEĞERDİR: `{ owner: \"u1\" }`. `eq`'i ikinci bir yazım\n * olarak eklemek, bu run'ın kapatmak için var olduğu şeyi — aynı iş için iki\n * uyumsuz yazım — filtre dilinin İÇİNDE yeniden açardı. Ve eskiden kabul eden\n * ile reddeden ayrışıyordu: guard `eq`'i geçiriyor, derleyici\n * `bilinmeyen operatör \"eq\"` diyordu (gözcü ölçtü).\n */\nconst REFUSED_OPS: Record<string, string> = {\n eq: 'eşitlik ÇIPLAK yazılır: { <kolon>: <değer> } (ya da kolon karşılaştırması için { <kolon>: col(\"…\") })',\n};\n\n/**\n * Refuse a filter that would compile to something other than what it reads like.\n *\n * Three shapes, each measured in production before it was closed:\n *\n * `{ col: undefined }` binds NULL; `= NULL` matches no row, so the query\n * answered \"no records\" and said nothing.\n * `{ col: {} }` produces no term at all — every row on the read\n * path, a dropped condition on the write path.\n * `{ col: { gte: undefined } }` and an `undefined` inside `in`: the same NULL,\n * one level down.\n */\nexport function assertUsableFilter(\n caller: string,\n table: string,\n where: Record<string, unknown> | undefined,\n): void {\n // Bileşim anahtarları (FR-007) bir KOLON adı değildir; kolon doğrulamasından\n // ve operatör kontrolünden muaftır, kendi dalları özyinelemeli olarak aynı\n // kurallardan geçer.\n const COMPOSITES = new Set([\"OR\", \"AND\", \"NOT\"]);\n\n if (!where) return;\n // Fragment bir kolon haritası DEĞİLDİR (FR-018): içeriği SQL'dir, kolon\n // doğrulaması ona uygulanamaz. Değerleri zaten bound gidiyor.\n if (isSqlFragment(where)) return;\n for (const [col, cond] of Object.entries(where)) {\n // Bileşim anahtarları (FR-007) kolon DEĞİLDİR: dalları aynı kurallardan\n // özyinelemeli geçer, ama kendileri operatör kontrolüne girmez.\n if (COMPOSITES.has(col)) {\n const branches = col === \"NOT\" ? [cond] : cond;\n if (!Array.isArray(branches) && col !== \"NOT\") {\n throw new Error(`${caller}(${table}): where.${col} bir dizi olmalı`);\n }\n for (const b of branches as unknown[]) {\n if (b === null || typeof b !== \"object\") {\n throw new Error(`${caller}(${table}): where.${col} dalları filtre nesnesi olmalı`);\n }\n assertUsableFilter(caller, table, b as Record<string, unknown>);\n }\n continue;\n }\n // `has` de kolon DEĞİLDİR: anahtarları İLİŞKİ adları, değerleri BİR TABLO\n // ÖTESİNİN filtresi. İç filtre aynı kurallardan geçiyor — `has` ikinci bir\n // filtre dili değil, aynı dilin bir tablo ötesi.\n //\n // İlişki ADI burada doğrulanMIYOR: grafiği yalnız motor tanıyor (ve tip,\n // derleme anında). Guard'ın onu bilmesi ilişki grafiğinin İKİNCİ bir\n // yorumcusu demekti — `buildRelations`'ın yorumunun adıyla yasakladığı şey.\n if (col === \"has\") {\n if (cond === null || typeof cond !== \"object\" || Array.isArray(cond)) {\n throw new Error(`${caller}(${table}): where.has bir ilişki haritası olmalı ({ <ilişki>: { … } })`);\n }\n for (const [rel, inner] of Object.entries(cond as Record<string, unknown>)) {\n if (inner === null || typeof inner !== \"object\" || Array.isArray(inner)) {\n throw new Error(`${caller}(${table}): where.has.${rel} bir filtre nesnesi olmalı`);\n }\n assertUsableFilter(caller, table, inner as Record<string, unknown>);\n }\n continue;\n }\n if (cond === undefined) {\n throw new Error(\n `${caller}(${table}): where.${col} değeri undefined — bu bir filtre değeri değil. ` +\n `Bağlanınca NULL olur ve '= NULL' hiçbir satıra uymaz, yani sorgu sessizce ` +\n `boş sonuç dönerdi. Değer yoksa anahtarı filtreye hiç koymayın.`,\n );\n }\n if (cond === null || typeof cond !== \"object\" || Array.isArray(cond)) continue;\n // `col()` ürünü bir DEĞER'dir, operatör nesnesi değil (FR-011). Ayırt\n // edilmezse `{ $col: \"x\" }` bir operatör haritası sanılır ve \"bilinmeyen\n // operatör $col\" diye reddedilirdi.\n if (isColRef(cond)) continue;\n // `now()` de bir DEĞER'dir, aynı gerekçeyle — ve tutamak bir Proxy olduğu\n // için `Object.entries` BOŞ döner: ayırt edilmezse \"boş operatör nesnesi\"\n // diye reddedilirdi, yani doğru yazım yanlış bir hatayla karşılanırdı.\n if (isNowExpr(cond)) continue;\n\n const entries = Object.entries(cond as Record<string, unknown>);\n if (entries.length === 0) {\n throw new Error(\n `${caller}(${table}): where.${col} boş bir operatör nesnesi ({}) — hiçbir koşul ` +\n `üretmez, yani bu alan filtreden sessizce DÜŞERDİ. Koşul kurulmayacaksa ` +\n `anahtarı filtreye hiç koymayın (D-21).`,\n );\n }\n for (const [op, v] of entries) {\n if (op === \"in\") {\n if (!Array.isArray(v)) throw new Error(`${caller}(${table}): where.${col}.in bir dizi olmalı`);\n if (v.some((x) => x === undefined)) {\n throw new Error(\n `${caller}(${table}): where.${col}.in listesinde undefined var — sessizce NULL'a ` +\n `bağlanır ve o eleman hiçbir satırla eşleşmez. Listeyi kurarken eleyin.`,\n );\n }\n continue;\n }\n // Sağ tarafta kolon durabilir: `{ total: { gt: col(\"amount_paid\") } }`.\n // Değer kontrolleri (undefined) ona da uygulanır, ama `in` gibi şekil\n // kontrolleri değil — o dal aşağıda zaten ayrı.\n if (REFUSED_OPS[op] !== undefined) {\n // Bilinmeyen değil — BİLİNEREK reddedilen. Hata çalışan yazımı söylüyor.\n throw new Error(`${caller}(${table}): where.${col}.${op} bu filtre dilinde yok — ${REFUSED_OPS[op]}`);\n }\n if (!KNOWN_OPS.has(op)) {\n throw new Error(\n `${caller}(${table}): where.${col} bilinmeyen operatör \"${op}\" (gt/gte/lt/lte/neq/in/contains/icontains/startsWith/endsWith/isNull)`,\n );\n }\n if (v === undefined) {\n throw new Error(\n `${caller}(${table}): where.${col}.${op} değeri undefined — karşılaştırmanın ` +\n `sağ tarafı NULL olur ve sonuç hiçbir satıra uymaz. Koşulu kurmayın.`,\n );\n }\n }\n }\n}\n\n/**\n * Refuse a write whose value never arrived.\n *\n * `{ title: req.body.title }` with no `title` in the body bound NULL and\n * answered 200 — the column was ERASED. `null` is untouched, and the difference\n * is the whole point: null is an author SAYING \"empty this column\"; undefined is\n * nobody saying anything.\n */\nexport function assertUsableWriteValues(\n caller: string,\n table: string,\n cols: readonly string[],\n data: Record<string, unknown>,\n): void {\n for (const c of cols) {\n if (data[c] === undefined) {\n throw new Error(\n `${caller}(${table}): \"${c}\" değeri undefined — bu bir yazma değeri değil. ` +\n `Kolonu boşaltmak istiyorsan null yaz; kolonu değiştirmek istemiyorsan nesneye hiç koyma ` +\n `(bir eksik istek alanı sessizce NULL yazıyordu — FR-016).`,\n );\n }\n }\n}\n","/**\n * tx-plan.ts — `Database.$transaction()` as a PLAN, not a pinned session.\n *\n * A transaction used to be a conversation: BEGIN, then one network round trip\n * per operation, then COMMIT. Each of those round trips cost ~4 ms and, because\n * the pooler runs in transaction mode, an open transaction pinned a Postgres\n * backend for the whole conversation. A 121-operation statement upload pinned\n * one backend for ~490 ms.\n *\n * So the callback no longer TALKS to the database. It DESCRIBES what should\n * happen; the description is serialised and sent once; the broker runs the whole\n * thing inside one transaction and answers once. Committing on return and\n * rolling back on throw is unchanged — that is the only property tenant code\n * actually asked for.\n *\n * The consequences, stated plainly, because they are the whole design:\n *\n * - The callback is SYNCHRONOUS. There is nothing to await: no statement has\n * run yet when it returns. `async` on the callback and `await` inside it are\n * both compile errors (see {@link TxPlan} and {@link NotAwaitable}).\n * - `insert()` does not hand back a row, it hands back {@link TxRows}. Reading\n * a field requires `.expectOne(err)` first, which makes \"what if the row\n * isn't there\" a question you cannot route around: it is the argument.\n * - A field read from a row is a {@link Ref} — a PROMISE OF A VALUE THE SERVER\n * WILL PRODUCE, not the value. It can be written into a later operation and\n * it can be returned from the callback (it is substituted for the real value\n * before `transaction()` resolves). It cannot be branched on. See the\n * \"Truthiness\" note below — this is the sharp edge of the whole design.\n * - Control flow that needs a real value must move OUT of the callback: read\n * before the transaction, or express the condition as a guard\n * (`updateWhere({ id, accepted_at: null }, …).expectOne(new Conflict(…))`)\n * which the server evaluates and which rolls the whole plan back.\n *\n * # Truthiness — the hole this file CANNOT close\n *\n * JavaScript does not let a Proxy trap truthiness. `if (ref)` takes the true\n * branch, always, for every Ref, and no `get` handler ever runs. `tsc` is silent\n * because a Ref is a perfectly good object. So:\n *\n * const pot = tx.tables.pots.select({ id }, { limit: 1 }).expectOne(e);\n * if (!pot.balance) { … } // ← ALWAYS false. Silently wrong data.\n *\n * What this file does close: coercion (`Symbol.toPrimitive`/`valueOf`/\n * `toString`), awaiting (`then` is a callable member with a non-thenable\n * signature, which is a *compile* error), serialisation (`toJSON`), and nesting\n * a Ref inside a literal value where the server would store it as data. What it\n * cannot close is a bare truthiness test. The real defence is the build-time\n * static analysis (`tx_analysis.js`, phase P4); until that ships, this hole is\n * open and this comment is the only warning.\n *\n * # Wire contract\n *\n * The JSON this file emits is consumed by\n * the plan executor in `engine/db.ts`. That executor rejects\n * unknown fields at every level, so an op carries EXACTLY the fields its kind\n * takes. Everything here that looks like a needless restriction is one of the\n * server's rules made visible early:\n *\n * - `$ref` only points BACKWARDS, and only at an op statically known to yield\n * at most one row (insert, or a `one`/`atMost 1` guard, or `select limit 1`).\n * `.expectOne()` is what this file uses to satisfy that, always.\n * - `$expr` is a closed set: `inc`/`dec` (update only — they read the column's\n * current value) and `now()`.\n * - `update`/`delete` require a `where`; `insert` refuses one.\n * - `insertMany` rows must all set the same columns.\n * - ≤1000 ops, ≤5000 rows per insertMany, ≤8 MiB of JSON.\n *\n * Column keys are emitted SORTED, so the same callback always produces byte-\n * identical JSON. That is what lets the Go decoder be locked to golden files\n * this SDK emits (`testdata/tx_plan_golden/`).\n */\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\n/**\n * A plan handle was used as if it were a value: awaited, coerced to a string or\n * number, serialised, or nested inside another value.\n *\n * Thrown while the callback is still BUILDING the plan, so nothing has been sent\n * and nothing has been written.\n */\n// TİP-ONLY, ve döngü kasıtlı: `typed-db.ts` bu dosyadan tip alıyor, bu dosya\n// ondan `WhereOp` alıyor. Çalışma zamanında hiçbir şey ithal edilmiyor (import\n// type), yani modül döngüsü yok — paylaşılan olan şey TEK FİLTRE DİLİ, ve onu\n// iki yerde ayrı ayrı tanımlamak bu run'ın kapattığı \"iki yazım\"ın tipteki\n// hâli olurdu.\nimport type { WhereOpWith, ColRefOf, HasOnly, SqlFragment } from \"./typed-db.js\";\nimport { isColRef, isSqlFragment, brandRef, isNowExpr } from \"./input-guards.js\";\n\nexport class TxRefError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TxRefError\";\n }\n}\n\n/**\n * The plan the callback described cannot be sent: it breaks a rule the server\n * would reject, and rejecting it here names the line that wrote it instead of\n * returning a 400 about an op index.\n */\nexport class TxPlanError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TxPlanError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Wire types — mirror the plan executor in `engine/db.ts` exactly.\n// ---------------------------------------------------------------------------\n\n/** A backwards reference to an earlier op's single-row result. */\nexport interface TxWireRef {\n $ref: { op: number; field: string };\n}\n\n/** A call from the server's closed function set. */\nexport interface TxWireExpr {\n $expr: { fn: \"inc\" | \"dec\"; by: number | string } | { fn: \"now\" };\n}\n\n/** One value in a `values`/`set`/`where` map: a literal, a `$ref` or a `$expr`. */\nexport type TxWireValue = TxWireRef | TxWireExpr | unknown;\n\n/** The tenant's declared expectation about an op's row count. `slot` indexes the\n * client-side error table — the error OBJECT never travels. */\nexport interface TxWireGuard {\n kind: \"one\" | \"none\" | \"atLeast\" | \"atMost\";\n n: number;\n slot: number;\n}\n\n/** One operation in the wire plan. Fields are omitted, never null: the decoder\n * rejects a field that does not belong to the op's kind. */\nexport interface TxWireOp {\n /** upsert and insertMany: the columns Postgres matches on. */\n onConflict?: readonly string[];\n /** insertMany only: what a collision does. Absent means no ON CONFLICT clause\n * at all, which is what every insertMany did before this option existed. */\n action?: \"ignore\" | \"update\";\n op: \"insert\" | \"insertMany\" | \"upsert\" | \"update\" | \"delete\" | \"select\";\n table: string;\n values?: Record<string, TxWireValue>;\n rows?: Record<string, TxWireValue>[];\n set?: Record<string, TxWireValue>;\n where?: Record<string, TxWireValue>;\n limit?: number;\n lock?: \"update\";\n guard?: TxWireGuard;\n}\n\n/** The plan the engine executes on the request's own transaction. */\nexport interface TxPlanBody {\n ops: TxWireOp[];\n}\n\n/** One op's outcome, positionally matched to the plan's ops. */\nexport interface TxPlanOpResult {\n rows: Record<string, unknown>[];\n rows_affected: number;\n}\n\n/** One result per op, in plan order. */\nexport interface TxPlanResponse {\n results: TxPlanOpResult[];\n}\n\n/**\n * The fields the runtime must copy from the broker's error envelope onto the\n * rejection it throws out of {@link DBClient.txPlan}.\n *\n * `slot` is the whole point: on a guard failure the server answers with the\n * INDEX of the expectation that did not hold, never with an error message of its\n * own, and this SDK maps that index back to the `Error` the callback handed to\n * `.expectOne(…)`. Without `slot` a guard failure degrades to a generic 409.\n */\nexport interface TxPlanRejection {\n status?: number;\n /** `tx_plan_invalid` | `tx_guard_failed` | `tx_ref_unresolved` | a pg class. */\n error_code?: string;\n /** Present only for `tx_guard_failed`: the client-side error table index. */\n slot?: number;\n /** Present on a database error: which op failed. */\n op?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Handle types\n// ---------------------------------------------------------------------------\n\ndeclare const refBrand: unique symbol;\ndeclare const rowBrand: unique symbol;\ndeclare const rowsBrand: unique symbol;\n\n/**\n * Makes a handle a compile error to `await`.\n *\n * `then` is declared as a CALLABLE member whose signature is not `PromiseLike`,\n * which is precisely the shape TypeScript rejects: `await handle` is TS1320 and\n * `async () => handle` is TS1058. A non-callable `then` would not do it — the\n * compiler simply ignores those.\n */\nexport interface NotAwaitable {\n /** Not a promise. Nothing here has run yet; there is nothing to await. */\n then(doNotAwaitAPlanHandle: \"a transaction plan is built synchronously\"): never;\n}\n\n/**\n * A value the SERVER will produce, standing in for a column of a row this plan\n * writes or reads.\n *\n * Legal uses: write it into a later operation's `values`/`set`/`where`, or\n * return it from the callback (it is replaced by the real value before\n * `transaction()` resolves).\n *\n * Illegal, and caught: `await`, `String(ref)`, `` `${ref}` ``, `ref + 1`,\n * `JSON.stringify(ref)`, burying it inside a jsonb object.\n *\n * Illegal, and NOT caught: `if (ref)`. See the truthiness note at the top.\n */\nexport interface Ref<T> extends NotAwaitable {\n readonly [refBrand]: T;\n}\n\n/** The brand carried by a single-row handle, and the seam `Materialized` reads\n * to turn `return st` into the whole row. */\nexport interface TxRowHandle<Row> extends NotAwaitable {\n readonly [rowBrand]: Row;\n}\n\n/**\n * A row this plan is known to produce exactly one of. Every property is a\n * {@link Ref}; returning the handle itself yields the whole row.\n *\n * Only `.expectOne(err)` produces one — which is the design: a row you can read\n * fields from is a row whose absence you have already answered for.\n */\nexport type TxRow<Row> = { readonly [K in keyof Row]: Ref<Row[K]> } & TxRowHandle<Row>;\n\n/**\n * The result of one operation, before any expectation is declared about it.\n *\n * Deliberately not a row and not a list: an operation's row count is not known\n * until the server runs it, so the only thing that can be said about it here is\n * an EXPECTATION. Declaring one is also the only way to get a readable row.\n *\n * At most one expectation per operation — the wire carries one guard per op, and\n * a second call throws rather than silently dropping the first.\n */\nexport interface TxRows<Row> extends NotAwaitable {\n readonly [rowsBrand]: Row;\n /**\n * Require exactly one row, and read it. On any other count the server rolls\n * the whole transaction back and this `error` is thrown to the caller.\n *\n * This is the only way to reach a row's fields, and the only shape a `$ref`\n * may point at.\n */\n expectOne(error: Error): TxRow<Row>;\n /** Require zero rows (e.g. \"this membership must not already exist\"). */\n expectNone(error: Error): void;\n /** Require at least `n` rows. */\n expectAtLeast(n: number, error: Error): void;\n /** Require at most `n` rows. */\n expectAtMost(n: number, error: Error): void;\n}\n\n/** `now()` — the server's clock, usable wherever a value is. */\nexport interface TxNow extends NotAwaitable {\n readonly $expr: { fn: \"now\" };\n}\n\n/** `inc(n)` / `dec(n)` — read the column's CURRENT value and write it back\n * changed. Only meaningful in an update's `set`, which is where the types allow\n * it and where the server allows it. */\nexport interface TxColumnExpr extends NotAwaitable {\n readonly $expr: { fn: \"inc\" | \"dec\"; by: number | string };\n}\n\n/**\n * Resolve a callback's return type against what actually comes back: every\n * {@link Ref} becomes its value, every {@link TxRow} becomes its row, and\n * anything else keeps its shape.\n *\n * A {@link TxRows} resolves to an explanatory string type rather than a row\n * list: it has no single answer to give, and saying so in the type is louder\n * than a runtime throw.\n */\nexport type Materialized<T> = T extends Ref<infer U>\n ? U\n : T extends TxRowHandle<infer R>\n ? R\n : T extends TxRows<unknown>\n ? \"a TxRows cannot leave the transaction callback — read a row with .expectOne(err) first\"\n : T extends Date\n ? T\n : T extends object\n ? { [K in keyof T]: Materialized<T[K]> }\n : T;\n\n// ---------------------------------------------------------------------------\n// Author-facing value types\n// ---------------------------------------------------------------------------\n\n/** A value written by an INSERT: a literal, an earlier row's field, or `now()`.\n * `inc`/`dec` are absent on purpose — they read a current value, and an inserted\n * row has none. */\nexport type TxInsertValue<V> = V | Ref<V> | TxNow;\n\n/** A value written by an UPDATE's `set`: everything an insert takes, plus the\n * read-modify-write expressions. */\n/**\n * TEK KURAL: ifade tutamağı yalnız sayısal-benzeri kolonlarda.\n *\n * Bu tip KOŞULSUZDU ve doğrudan yolun `SetValue<V>`'si koşulluydu, yani aynı\n * nesne için İKİ tip kuralı vardı: `tx.tables.todos.updateWhere({id}, { done:\n * increment(1) })` (boolean kolon!) DERLENİYOR, `updateMany`'nin aynısı derleme\n * hatası veriyordu. Bu run'ın kapatmak için var olduğu şey \"aynı iş için iki\n * uyumsuz yazım\"dı; tip kuralı ikinci yazımın kendisi olmuştu (gözcü I6/I-1).\n */\nexport type TxSetValue<V> =\n | V\n | Ref<V>\n | TxNow\n | (NonNullable<V> extends number | string ? TxColumnExpr : never);\n\n/** An insert payload: the table's insert shape, with refs and `now()` allowed. */\nexport type TxInsertShape<Insert> = { [K in keyof Insert]: TxInsertValue<Insert[K]> };\n\n/** An update's `set`: any subset of the insert shape, with expressions allowed. */\nexport type TxSetShape<Insert> = { [K in keyof Insert]?: TxSetValue<Insert[K]> };\n\n/**\n * A filter. Every entry is an equality test and they are AND-ed; a `null`\n * becomes `IS NULL`, which is what makes `{ accepted_at: null }` a usable\n * \"not yet accepted\" guard rather than a clause that matches nothing.\n */\n/**\n * Plan filtresinin tipi — `WhereFilter<Row>` ile AYNI sözlük, artı `Ref`.\n *\n * Eskiden yalnız eşitlikti (`Row[K] | Ref<Row[K]>`), ve iki şeye mal oluyordu:\n * FR-014'ün amiral deseni (`{ balance: { gte: amount } }`) `$transaction`\n * İÇİNDE yazılamıyordu — koşullu bir yazmayı plana koyamayan yazar `$query`'ye\n * düşüyordu — ve motor tarafında tip atlandığında aynı nesne SESSİZCE parametre\n * olarak bağlanıyordu.\n *\n * `Ref` fazladan üye ve öyle kalmalı: bir plan filtresi ÖNCEKİ bir işlemin\n * döndürdüğü değere bakabilir, `findMany` bakamaz — plan dışında böyle bir\n * \"önceki işlem\" yok.\n */\ntype TxWhereField<Row, K extends keyof Row> = WhereOpWith<\n Row[K],\n // `Ref` KOLON REFERANSININ YANINDA duruyor, `V`'nin içinde DEĞİL: `V`'ye\n // eklenseydi `TextOps<V>`'nin `V extends string` sorusu HAYIR olur ve\n // `contains`/`startsWith` sessizce kaybolurdu (ölçüldü).\n ColRefOf<Row, Row[K]> | Ref<Row[K]>\n>;\n\nexport type TxWhere<Row, Rels = unknown> = {\n [K in keyof Row]?: TxWhereField<Row, K>;\n} & {\n // Düz op'lardaki `WhereFilter` ile AYNI: dal bir `sqlFragment` de olabilir.\n // İki filtre dilinin bir dalda ayrışması, \"tek dil\" iddiasını tam da bileşim\n // anında boşa çıkarırdı — ve motor plan yolunda da fragment'i derliyor\n // (ölçüldü: `SELECT t.* FROM \"crew\" t WHERE true AND (((a > 1)) AND (…))`).\n OR?: (TxWhere<Row, Rels> | SqlFragment)[];\n AND?: (TxWhere<Row, Rels> | SqlFragment)[];\n NOT?: TxWhere<Row, Rels> | SqlFragment;\n} & HasOnly<Rels>;\n\n/** Options for a plan `select`. */\nexport interface TxSelectOptions {\n /** Cap the rows read. */\n limit?: number;\n /** Take a real `FOR UPDATE` row lock for the rest of the transaction. */\n lock?: \"update\";\n}\n\n/** One table, as the plan sees it. */\nexport interface TxTable<Row, Insert, Rels = unknown> {\n /** Insert one row. Returns a handle — call `.expectOne(err)` to read fields. */\n insert(values: TxInsertShape<Insert>): TxRows<Row>;\n /**\n * Insert many rows in ONE statement. Every row must set the same columns\n * (a row that omits one would silently take the column's default).\n *\n * An empty list writes nothing and sends nothing.\n */\n /**\n * Insert many rows in ONE statement, optionally choosing what a collision does.\n *\n * Without `opts` this is a plain multi-row INSERT and a collision aborts the\n * transaction — the behaviour every call had before the option existed.\n *\n * `action: \"ignore\"` emits `ON CONFLICT DO NOTHING`, which is how \"insert the\n * ones that are new\" becomes one round-trip instead of one per row with a\n * 23505 caught around each. **The returned rows are the ones actually\n * INSERTED**: a row that collided is skipped, so it is absent from the result\n * — Postgres does not return what it did not write.\n *\n * `action: \"update\"` emits `ON CONFLICT DO UPDATE`, setting every non-conflict\n * column from the incoming row, and every row comes back.\n */\n insertMany(\n rows: readonly TxInsertShape<Insert>[],\n opts?: {\n onConflict: readonly Extract<keyof Row, string>[];\n action?: \"ignore\" | \"update\";\n },\n ): TxRows<Row>;\n /**\n * Satırı yaz, `onConflict` kolonlarında çakışırsa üzerine yaz — planın\n * savepoint'i içinde, `Database.<şema>.<tablo>.put()` ile AYNI anlamda.\n *\n * Adı bilerek aynı: aynı iş için transaction içinde ve dışında iki farklı\n * yazım, bu run'ın kapatmak için var olduğu şeydir (P1). TEL şekli\n * (`op: \"upsert\"`) değişmedi — o iç sözleşme, yazarın gördüğü ad değil.\n *\n * Bir operasyon olmasının sebebi: alternatifi burada yazılamaz — başarısız\n * bir insert tüm transaction'ı abort eder, yani \"dene, sonra geri düş\" iki\n * plan adımı olamaz.\n */\n put(\n values: TxInsertShape<Insert>,\n options: { onConflict: readonly Extract<keyof Row, string>[] },\n ): TxRows<Row>;\n /**\n * Update every row matching `where`. The filter comes first because it is the\n * dangerous half: an update whose `where` you got wrong rewrites rows you\n * never looked at. The server refuses an update with no `where` at all.\n */\n updateWhere(where: TxWhere<Row, Rels>, set: TxSetShape<Insert>): TxRows<Row>;\n /** Delete every row matching `where`. The server refuses an unfiltered delete. */\n deleteWhere(where: TxWhere<Row, Rels>): TxRows<Row>;\n /** Read rows, optionally locking them for the rest of the transaction. */\n select(where?: TxWhere<Row, Rels>, options?: TxSelectOptions): TxRows<Row>;\n}\n\n/**\n * The handle a transaction callback receives.\n *\n * It carries tables and nothing else: no `query`, no `findById`, no `asService`.\n * A read whose value the plan does not write belongs OUTSIDE the transaction,\n * where it costs one round trip and can be branched on like an ordinary value.\n */\nexport interface TxPlanHandle<TTables> {\n /**\n * @deprecated `tx.public` kullanın. Bu ad public'in takma adı olarak DURUYOR\n * (göç notu onu öğretiyor ve her mevcut çağrı onu kullanıyor), ama ARTIK\n * ÖĞRETİLMİYOR: doğrudan yüzeyde `Database.tables` FR-001 ile kaldırıldı, ve\n * plan yüzeyinin onu öğretmeye devam etmesi yazarı bir yüzeyde çalışıp\n * diğerinde derlenmeyen bir yazıma alıştırıyordu (gözcü M-6).\n */\n tables: TTables;\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — expressions\n// ---------------------------------------------------------------------------\n\n/** Internal marker read by the serialiser. */\nconst EXPR = Symbol.for(\"palbase.tx.expr\");\nconst REF = Symbol.for(\"palbase.tx.ref\");\nconst ROW = Symbol.for(\"palbase.tx.row\");\nconst ROWS = Symbol.for(\"palbase.tx.rows\");\n\ninterface RefDescriptor {\n op: number;\n field: string;\n}\n\n/** Property reads that must not silently produce a value on a plan handle.\n * `then` is the one that matters for correctness (it makes `await` a compile\n * error AND stops a handle from being adopted by a promise); the rest turn a\n * silent wrong answer — `\"[object Object]\"`, `NaN`, `{}` — into a thrown one. */\nconst TRAPPED_PROPS: readonly (string | symbol)[] = [\n \"then\",\n \"valueOf\",\n \"toString\",\n \"toJSON\",\n Symbol.toPrimitive,\n];\n\nfunction trap(prop: string | symbol, what: string, hint: string): never {\n const name = typeof prop === \"symbol\" ? prop.description ?? String(prop) : prop;\n throw new TxRefError(\n `${what} was used as a value (via \\`${name}\\`). Nothing in a transaction ` +\n `callback has run yet, so there is no value to read. ${hint}`,\n );\n}\n\n/** The server's `now()`. */\nexport function now(): TxNow {\n return makeExpr({ fn: \"now\" }) as TxNow;\n}\n\n/** Add `by` to the column's current value. Only valid in an update's `set`. */\nexport function increment(by: number | string): TxColumnExpr {\n assertAmount(by, \"increment\");\n return makeExpr({ fn: \"inc\", by }) as TxColumnExpr;\n}\n\n/**\n * `increment`'in eski adı. AYNI fabrikadır — iki uygulama değil, iki ad.\n *\n * @deprecated `increment()` kullanın; bu ad geriye dönük uyumluluk için duruyor.\n */\nexport const inc = increment;\n\n/** Subtract `by` from the column's current value. Only valid in an update's `set`. */\nexport function decrement(by: number | string): TxColumnExpr {\n assertAmount(by, \"decrement\");\n return makeExpr({ fn: \"dec\", by }) as TxColumnExpr;\n}\n\n/**\n * `decrement`'in eski adı. AYNI fabrikadır.\n *\n * @deprecated `decrement()` kullanın.\n */\nexport const dec = decrement;\n\n/**\n * Miktarın taşınabilir olduğunu doğrular.\n *\n * String kabul edilir ve KASITLIDIR (D-007): `numeric` bir kolonda miktar JS\n * `number`'a uğrarsa 0.1 + 0.2 orada 0.30000000000000004'tür ve para hesabı\n * sessizce kayar. String hem burada hem `renderValue`'da bound parametre olarak\n * taşınır — Postgres onu tam ondalık olarak okur.\n */\nfunction assertAmount(by: number | string, fn: string): void {\n if (typeof by === \"string\") {\n // Metin SQL'e girmiyor (bound parametre), ama şekli yine de doğrulanır:\n // \"abc\" bind edilirse hata Postgres'ten gelir, çağıranın diliyle değil.\n if (!/^-?\\d+(\\.\\d+)?$/.test(by)) {\n throw new TxPlanError(\n `${fn}() ondalık bir sayı metni bekliyor, \"${by}\" aldı — kabul edilen biçim: \"12\", \"-12\", \"12.50\"`,\n );\n }\n } else if (typeof by !== \"number\" || !Number.isFinite(by)) {\n // JSON has no NaN/Infinity: they would serialise to `null` and the server\n // would reject the plan with an unhelpful decode error.\n throw new TxPlanError(`${fn}() needs a finite number, got ${String(by)}`);\n }\n // NEGATİF MİKTAR REDDEDİLİR — ve bu şekil kontrolünden çok daha fazlası.\n // `decrement(\"-5\")` `SET c = c - $1` derliyordu, `$1 = -5`, yani beş EKLİYORDU.\n // FR-014'ün amiral deseninde (`where: { balance: { gte: amount } }`) miktar\n // istek gövdesinden geliyorsa `balance >= -5` her zaman doğru: hesap\n // KREDİLENDİRİLİR ve çağrı bunu 1 satırla \"başarı\" diye raporlar. Guard\n // okunduğunda işaret kontrol edilmiş gibi duruyordu (gözcü I9, ölçüldü).\n const negative = typeof by === \"string\" ? by.trimStart().startsWith(\"-\") : by < 0;\n if (negative) {\n const other = fn === \"increment\" ? \"decrement\" : \"increment\";\n throw new TxPlanError(\n `${fn}() negatif miktar almaz (\"${String(by)}\"). Ters yön için ${other}() kullanın — ` +\n `işaretin miktarda saklanması, yönü okuyan hiçbir kod tarafından görülmezdi.`,\n );\n }\n}\n\n/**\n * Bir değer `increment()`/`decrement()` ürünü mü? Öyleyse tel şekli.\n *\n * DOĞRUDAN yol (`updateMany`) da bu ifadeyi anlamak zorunda: aynı nesnenin iki\n * yerde çalışması, \"kolona ekle\"nin tek yazımı olmasının şartı (P1).\n */\nexport function columnExprOf(v: unknown): TxWireExpr[\"$expr\"] | null {\n return exprOf(v);\n}\n\nfunction makeExpr(expr: TxWireExpr[\"$expr\"]): unknown {\n return new Proxy(\n { [EXPR]: expr } as Record<string | symbol, unknown>,\n {\n get(target, prop) {\n if (prop === EXPR) return target[EXPR];\n if (TRAPPED_PROPS.includes(prop)) {\n trap(prop, \"A plan expression\", \"Write it into an operation instead.\");\n }\n return undefined;\n },\n },\n );\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — refs and row handles\n// ---------------------------------------------------------------------------\n\nfunction makeRef(op: number, field: string): unknown {\n const target: Record<string | symbol, unknown> = { [REF]: { op, field } satisfies RefDescriptor };\n return new Proxy(target, {\n get(t, prop) {\n if (prop === REF) return t[REF];\n if (TRAPPED_PROPS.includes(prop)) {\n trap(\n prop,\n `\\`${field}\\` of a row this transaction has not written yet`,\n \"Pass it to another operation in the same plan, or return it from the \" +\n \"callback and read it after `transaction()` resolves.\",\n );\n }\n return undefined;\n },\n });\n}\n\nfunction makeRowHandle(op: number): unknown {\n const target: Record<string | symbol, unknown> = { [ROW]: op };\n return new Proxy(target, {\n get(t, prop) {\n if (prop === ROW) return t[ROW];\n if (TRAPPED_PROPS.includes(prop)) {\n trap(\n prop,\n \"A row this transaction has not written yet\",\n \"Read one of its columns to reference it, or return the row from the \" +\n \"callback and read it after `transaction()` resolves.\",\n );\n }\n if (typeof prop === \"symbol\") return undefined;\n return makeRef(op, prop);\n },\n });\n}\n\nfunction refDescriptor(v: unknown): RefDescriptor | null {\n if (typeof v !== \"object\" || v === null) return null;\n const d = (v as Record<symbol, unknown>)[REF];\n return isRefDescriptor(d) ? d : null;\n}\n\nfunction isRefDescriptor(d: unknown): d is RefDescriptor {\n return (\n typeof d === \"object\" &&\n d !== null &&\n typeof (d as RefDescriptor).op === \"number\" &&\n typeof (d as RefDescriptor).field === \"string\"\n );\n}\n\nfunction rowOpIndex(v: unknown): number | null {\n if (typeof v !== \"object\" || v === null) return null;\n const op = (v as Record<symbol, unknown>)[ROW];\n return typeof op === \"number\" ? op : null;\n}\n\nfunction exprOf(v: unknown): TxWireExpr[\"$expr\"] | null {\n if (typeof v !== \"object\" || v === null) return null;\n const e = (v as Record<symbol, unknown>)[EXPR];\n return typeof e === \"object\" && e !== null ? (e as TxWireExpr[\"$expr\"]) : null;\n}\n\nfunction isRowsHandle(v: unknown): boolean {\n return typeof v === \"object\" && v !== null && (v as Record<symbol, unknown>)[ROWS] !== undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — value encoding\n// ---------------------------------------------------------------------------\n\n/**\n * Encode one value of a `values`/`set`/`where` map.\n *\n * The nesting check is not defensive tidiness. The server treats `$ref` as a\n * tagged value only at the TOP of a column's value; a ref buried inside a jsonb\n * payload is just data, and would be stored as the literal object\n * `{\"$ref\":{...}}` — a write that succeeds, commits, and is wrong. So a nested\n * handle is a hard error here, where the line that wrote it is still on the\n * stack.\n */\nfunction encodeValue(value: unknown, column: string, allowColumnExpr: boolean): TxWireValue {\n const ref = refDescriptor(value);\n if (ref) return brandRef({ $ref: { op: ref.op, field: ref.field } }, \"ref\") satisfies TxWireRef;\n\n // `now()` bir KARŞILAŞTIRMA değeri olarak geçer — sunucu saati. Diğer\n // ifadeler (increment/decrement) yazma ifadesidir ve aşağıda adıyla\n // reddediliyor. Düz op yolu ile aynı ayrım, aynı gerekçe.\n if (isNowExpr(value)) return { $expr: { fn: \"now\" } };\n const expr = exprOf(value);\n if (expr) {\n if (expr.fn !== \"now\" && !allowColumnExpr) {\n throw new TxPlanError(\n `\\`${column}\\`: ${expr.fn}() reads the column's current value, so it is ` +\n `only valid in updateWhere(where, set).`,\n );\n }\n return { $expr: expr } satisfies TxWireExpr;\n }\n\n if (rowOpIndex(value) !== null) {\n throw new TxPlanError(\n `\\`${column}\\`: a row handle is not a value. Read the column you meant ` +\n `(e.g. \\`row.id\\`).`,\n );\n }\n if (isRowsHandle(value)) {\n throw new TxPlanError(\n `\\`${column}\\`: an operation result is not a value. Declare an expectation ` +\n `first (\\`.expectOne(err)\\`) and read a column from the row.`,\n );\n }\n\n assertNoNestedHandles(value, column);\n return value;\n}\n\n/**\n * Encode a FİLTRE — `values`/`set` ile AYNI kodlayıcı değil, ve olmaması bir\n * düzeltme.\n *\n * `encodeValue` bir `$ref`'i yalnız kolonun EN ÜSTÜNDE kabul ediyor, çünkü bir\n * insert değerinin İÇİNE gömülü ref sunucuda çözülmez, literal JSON olarak\n * SAKLANIR — \"başarıyla commit olan ve yanlış olan bir yazma\". O kural DEĞER\n * yolu için doğru.\n *\n * FİLTREDE öyle değil: motorun `resolveRefsDeep`'i bir ref'i filtrenin HER\n * yerinde çözüyor — operatörün sağında, `OR`/`AND`/`NOT` dallarının içinde. Ama\n * kodlayıcı hâlâ değer kuralını uyguluyordu, yani üç katman üç farklı cevap\n * veriyordu (gözcü C-2): tip kabul, motor çözüyor, kodlayıcı REDDEDİYOR — ve\n * reddin metni değer-yuvalama vakasını anlatıyor, filtrede olmayan bir şeyi.\n *\n * İFADE TUTAMAĞI ve SATIR TUTAMAĞI filtrede HÂLÂ reddediliyor: onları motor\n * filtrede çözmüyor ve çözmemeli — `increment()` bir yazma ifadesi, bir\n * karşılaştırma değil.\n */\nfunction encodeFilterValue(value: unknown, column: string): unknown {\n const ref = refDescriptor(value);\n if (ref) return brandRef({ $ref: { op: ref.op, field: ref.field } }, \"ref\") satisfies TxWireRef;\n\n const expr = exprOf(value);\n if (expr) {\n throw new TxPlanError(\n `\\`${column}\\`: ${expr.fn}() bir YAZMA ifadesi, karşılaştırma değil — ` +\n `filtrede kullanılamaz. Kolonu bir değerle ya da col() ile karşılaştırın.`,\n );\n }\n if (rowOpIndex(value) !== null) {\n throw new TxPlanError(\n `\\`${column}\\`: a row handle is not a value. Read the column you meant (e.g. \\`row.id\\`).`,\n );\n }\n if (isRowsHandle(value)) {\n throw new TxPlanError(\n `\\`${column}\\`: an operation result is not a value. Declare an expectation ` +\n `first (\\`.expectOne(err)\\`) and read a column from the row.`,\n );\n }\n if (Array.isArray(value)) return value.map((v) => encodeFilterValue(v, column));\n // `col()` ve `sqlFragment` OLDUĞU GİBİ geçer: markaları süreç içinde korunur\n // ve derleyici ikisini de kendi tanıyor.\n if (value !== null && typeof value === \"object\" && !(value instanceof Date) && !isColRef(value) && !isSqlFragment(value)) {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n out[k] = encodeFilterValue(v, column);\n }\n return out;\n }\n return value;\n}\n\n/** Filtre haritası — anahtarlar SIRALI (aynı geri çağrı bayt-özdeş JSON üretsin). */\nfunction encodeFilterMap(map: Record<string, unknown>): Record<string, TxWireValue> {\n const out: Record<string, TxWireValue> = {};\n for (const key of Object.keys(map).sort()) {\n const value = map[key];\n if (value === undefined) continue;\n out[key] = encodeFilterValue(value, key) as TxWireValue;\n }\n return out;\n}\n\nfunction assertNoNestedHandles(value: unknown, column: string): void {\n if (typeof value !== \"object\" || value === null) return;\n if (value instanceof Date) return;\n if (refDescriptor(value) || exprOf(value) || rowOpIndex(value) !== null || isRowsHandle(value)) {\n throw new TxPlanError(\n `\\`${column}\\`: a plan handle is nested inside a value. The server would ` +\n `store it as literal JSON, not resolve it. Put the reference directly in ` +\n `the column.`,\n );\n }\n if (Array.isArray(value)) {\n for (const item of value) assertNoNestedHandles(item, column);\n return;\n }\n for (const item of Object.values(value as Record<string, unknown>)) {\n assertNoNestedHandles(item, column);\n }\n}\n\n/**\n * Encode a column map, dropping `undefined` and emitting keys SORTED.\n *\n * Sorting is what makes the same callback produce byte-identical JSON every\n * time, which is what lets the Go decoder be locked to goldens this SDK emits.\n * Dropping `undefined` mirrors what `JSON.stringify` would do anyway, but does\n * it where the resulting column list is still checkable.\n */\nfunction encodeMap(\n map: Record<string, unknown>,\n allowColumnExpr: boolean,\n): Record<string, TxWireValue> {\n const out: Record<string, TxWireValue> = {};\n for (const key of Object.keys(map).sort()) {\n const value = map[key];\n // AÇIK `undefined` REDDEDİLİR (D-017 kapandı).\n //\n // \"Kolon varsayılanını al\" demenin yolu anahtarı HİÇ KOYMAMAK; bu döngü\n // zaten yalnız var olan anahtarları geziyor, yani o niyet bozulmadan\n // çalışıyor. Ayırt edilen şey başka: anahtarın DURDUĞU ama değerinin\n // `undefined` olduğu hâl — yani `{ title: req.body.title }` gövdede\n // `title` yokken. O ölçülmüş bir olaydı: kolon sessizce yazılmadı ve\n // istek 200 döndü.\n //\n // Doğrudan yol bunu baştan beri adıyla reddediyordu; plan yolu sessizce\n // düşürüyordu. Aynı girdiye zıt iki cevap, \"tek filtre dili, tek cevap\"\n // iddiasını yazma tarafında boşa çıkarıyordu.\n if (value === undefined) {\n throw new TxPlanError(\n `${key} değeri undefined — bu bir yazma değeri değil. Anahtar duruyor ` +\n `ama değeri yok, yani kolon sessizce YAZILMAZDI (istek gövdesinden ` +\n `gelen bir alanın eksik olması bu şekilde görünür). Kolon ` +\n `varsayılanını istiyorsanız anahtarı hiç koymayın; NULL yazmak ` +\n `istiyorsanız açıkça null yazın.`,\n );\n }\n out[key] = encodeValue(value, key, allowColumnExpr);\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — the builder\n// ---------------------------------------------------------------------------\n\n/** How many rows an op can produce, as far as the CLIENT can tell before it\n * runs. Only the empty `insertMany` is knowable, and knowing it is what lets a\n * doomed expectation fail on the line that declared it. */\nconst SKIPPED_OP = -1;\n\nclass TxRowsImpl<Row> implements TxRows<Row> {\n // Present so `isRowsHandle` recognises the object; never read for its value.\n readonly [ROWS] = true;\n // Phantom: the type brand that stops a bare object passing as a TxRows. Never\n // present at run time, which is what `declare` says.\n declare readonly [rowsBrand]: Row;\n private guarded = false;\n\n constructor(\n private readonly builder: TxPlanBuilder,\n private readonly opIndex: number,\n private readonly what: string,\n ) {}\n\n // The type-level `await` guard made real: TS rejects `await rows` at compile\n // time, and reaching this means someone called `.then(...)` by hand.\n then(): never {\n throw new TxRefError(\n `${this.what} cannot be awaited: a transaction callback builds a plan, it ` +\n `does not run statements. Remove the \\`await\\`.`,\n );\n }\n\n expectOne(error: Error): TxRow<Row> {\n this.declareGuard(\"one\", 1, error);\n if (this.opIndex === SKIPPED_OP) throw error;\n return makeRowHandle(this.opIndex) as TxRow<Row>;\n }\n\n expectNone(error: Error): void {\n this.declareGuard(\"none\", 0, error);\n }\n\n expectAtLeast(n: number, error: Error): void {\n assertGuardCount(n, \"expectAtLeast\");\n this.declareGuard(\"atLeast\", n, error);\n if (this.opIndex === SKIPPED_OP && n > 0) throw error;\n }\n\n expectAtMost(n: number, error: Error): void {\n assertGuardCount(n, \"expectAtMost\");\n this.declareGuard(\"atMost\", n, error);\n }\n\n private declareGuard(kind: TxWireGuard[\"kind\"], n: number, error: Error): void {\n if (!(error instanceof Error)) {\n // The error object is the ONLY thing that describes this failure to the\n // caller — the server sends back an index, never a message.\n throw new TxPlanError(\n `${this.what}: an expectation needs the Error to throw when it does not ` +\n `hold (e.g. \\`.expect…(new Conflict(\"already accepted\"))\\`).`,\n );\n }\n if (this.guarded) {\n throw new TxPlanError(\n `${this.what} already has an expectation. One operation carries one ` +\n `expectation; declare the second one on its own operation.`,\n );\n }\n this.guarded = true;\n if (this.opIndex === SKIPPED_OP) return;\n this.builder.attachGuard(this.opIndex, kind, n, error);\n }\n}\n\nfunction assertGuardCount(n: number, fn: string): void {\n if (!Number.isInteger(n) || n < 0) {\n throw new TxPlanError(`${fn}(n) needs a non-negative integer, got ${String(n)}`);\n }\n}\n\n/** Bounds mirrored from the plan executor so an over-sized plan is named here rather\n * than rejected as an opaque 400 after it has crossed the network. */\nconst MAX_OPS = 1000;\nconst MAX_ROWS = 5000;\n\n/**\n * Accumulates ops and the client-side error table while the callback runs.\n *\n * Exported for the runtime and for tests that need the serialised plan without\n * a server; author code never sees it.\n */\nexport class TxPlanBuilder {\n private readonly ops: TxWireOp[] = [];\n /** Errors handed to expectations, indexed by the `slot` the server echoes. */\n private readonly slots: Error[] = [];\n\n /** The table surface handed to the callback. Untyped here; the public\n * `transaction()` signatures put the schema types on top. */\n table(name: string): TxTable<Record<string, unknown>, Record<string, unknown>> {\n return {\n insert: (values) => {\n const encoded = encodeMap(values as Record<string, unknown>, false);\n if (Object.keys(encoded).length === 0) {\n throw new TxPlanError(`${name}.insert() needs at least one column`);\n }\n return this.push({ op: \"insert\", table: name, values: encoded }, `${name}.insert()`);\n },\n\n put: (values, options) => {\n const encoded = encodeMap(values as Record<string, unknown>, false);\n if (Object.keys(encoded).length === 0) {\n throw new TxPlanError(`${name}.put() needs at least one column`);\n }\n if (options.onConflict.length === 0) {\n throw new TxPlanError(`${name}.put() needs at least one onConflict column`);\n }\n return this.push(\n { op: \"upsert\", table: name, values: encoded, onConflict: options.onConflict },\n `${name}.upsert()`,\n );\n },\n\n insertMany: (rows, opts) => {\n if (rows.length === 0) {\n // Nothing to write. Emitting an op would be a guaranteed 400 (the\n // server requires rows), and refusing outright would punish the\n // ordinary \"filtered every candidate out\" case.\n return new TxRowsImpl(this, SKIPPED_OP, `${name}.insertMany()`);\n }\n if (rows.length > MAX_ROWS) {\n throw new TxPlanError(\n `${name}.insertMany() has ${rows.length} rows; the limit is ${MAX_ROWS}. ` +\n `Split the write across requests.`,\n );\n }\n const encoded = rows.map((row) => encodeMap(row as Record<string, unknown>, false));\n assertUniformRows(encoded, name);\n if (opts !== undefined && opts.onConflict.length === 0) {\n throw new TxPlanError(\n `${name}.insertMany() was given a conflict action with no onConflict ` +\n `columns. Postgres matches a collision on columns, so name them.`,\n );\n }\n return this.push(\n {\n op: \"insertMany\",\n table: name,\n rows: encoded,\n // Omitted entirely when no options were given, so the op a plain\n // insertMany produces is byte-identical to the one it produced\n // before this option existed.\n ...(opts !== undefined\n ? { onConflict: opts.onConflict, action: opts.action ?? \"ignore\" }\n : {}),\n },\n `${name}.insertMany()`,\n );\n },\n\n updateWhere: (where, set) => {\n const encodedWhere = encodeFilterMap(where as Record<string, unknown>);\n const encodedSet = encodeMap(set as Record<string, unknown>, true);\n if (Object.keys(encodedWhere).length === 0) {\n throw new TxPlanError(\n `${name}.updateWhere() needs a filter. An update with no filter ` +\n `rewrites the whole table.`,\n );\n }\n if (Object.keys(encodedSet).length === 0) {\n throw new TxPlanError(`${name}.updateWhere() needs at least one column to set`);\n }\n return this.push(\n { op: \"update\", table: name, set: encodedSet, where: encodedWhere },\n `${name}.updateWhere()`,\n );\n },\n\n deleteWhere: (where) => {\n const encodedWhere = encodeFilterMap(where as Record<string, unknown>);\n if (Object.keys(encodedWhere).length === 0) {\n throw new TxPlanError(\n `${name}.deleteWhere() needs a filter. A delete with no filter empties ` +\n `the table.`,\n );\n }\n return this.push(\n { op: \"delete\", table: name, where: encodedWhere },\n `${name}.deleteWhere()`,\n );\n },\n\n select: (where, options) => {\n const op: TxWireOp = { op: \"select\", table: name };\n const encodedWhere = encodeFilterMap((where ?? {}) as Record<string, unknown>);\n if (Object.keys(encodedWhere).length > 0) op.where = encodedWhere;\n if (options?.limit !== undefined) {\n if (!Number.isInteger(options.limit) || options.limit < 0) {\n throw new TxPlanError(\n `${name}.select(): limit needs a non-negative integer, got ${String(options.limit)}`,\n );\n }\n op.limit = options.limit;\n }\n if (options?.lock !== undefined) op.lock = options.lock;\n return this.push(op, `${name}.select()`);\n },\n };\n }\n\n private push(op: TxWireOp, what: string): TxRows<Record<string, unknown>> {\n if (this.ops.length >= MAX_OPS) {\n throw new TxPlanError(\n `this transaction has ${MAX_OPS} operations, which is the limit. Use ` +\n `insertMany() for bulk writes, or split the work across requests.`,\n );\n }\n const index = this.ops.length;\n this.ops.push(op);\n return new TxRowsImpl(this, index, what);\n }\n\n /** Attach an expectation to an op and record its error in the slot table. */\n attachGuard(opIndex: number, kind: TxWireGuard[\"kind\"], n: number, error: Error): void {\n const op = this.ops[opIndex];\n // Unreachable: the index came from `push`. A loud failure beats a silently\n // unguarded write if that ever stops being true.\n if (!op) throw new TxPlanError(`internal: expectation on unknown operation ${opIndex}`);\n const slot = this.slots.length;\n this.slots.push(error);\n op.guard = { kind, n, slot };\n }\n\n /** The serialisable plan. Empty when the callback described no writes. */\n body(): TxPlanBody {\n return { ops: this.ops };\n }\n\n /** The error the server's `slot` selects, or `null` when it names one this\n * plan never declared (a server/client disagreement, not a tenant error). */\n errorForSlot(slot: number): Error | null {\n return this.slots[slot] ?? null;\n }\n}\n\nfunction assertUniformRows(rows: Record<string, TxWireValue>[], table: string): void {\n const first = rows[0];\n if (!first) return;\n const want = Object.keys(first);\n const wantKey = want.join(\",\");\n for (let i = 1; i < rows.length; i++) {\n const got = Object.keys(rows[i] as Record<string, TxWireValue>);\n if (got.join(\",\") !== wantKey) {\n // One statement, one column list. A ragged row would take the DB default\n // for the column it omitted — a write that succeeds and is wrong.\n throw new TxPlanError(\n `${table}.insertMany(): every row must set the same columns. Row 0 sets ` +\n `[${want.join(\", \")}] but row ${i} sets [${got.join(\", \")}]. ` +\n `(A property set to \\`undefined\\` counts as absent — use \\`null\\`.)`,\n );\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — materialisation\n// ---------------------------------------------------------------------------\n\n/**\n * Replace every handle in the callback's return value with what the server\n * actually produced.\n *\n * Walks arrays and PLAIN objects only. Class instances (a Date, a Zod schema, a\n * domain object) are returned untouched — recursing into them would rebuild them\n * as bare objects, and nothing inside one can be a handle that this SDK created.\n */\nexport function materializeResult(value: unknown, results: TxPlanOpResult[]): unknown {\n const ref = refDescriptor(value);\n if (ref) {\n const row = rowOf(results, ref.op, `\\`${ref.field}\\``);\n if (!(ref.field in row)) {\n throw new TxPlanError(\n `the transaction's operation ${ref.op} returned no column \\`${ref.field}\\`.`,\n );\n }\n return row[ref.field];\n }\n\n const rowOp = rowOpIndex(value);\n if (rowOp !== null) return rowOf(results, rowOp, \"a row\");\n\n if (isRowsHandle(value)) {\n throw new TxPlanError(\n \"an operation result cannot be returned from a transaction callback: its \" +\n \"row count is not known until the plan runs. Declare an expectation \" +\n \"(`.expectOne(err)`) and return the row, or a column of it.\",\n );\n }\n\n if (Array.isArray(value)) return value.map((item) => materializeResult(item, results));\n\n if (isPlainObject(value)) {\n const out: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) out[key] = materializeResult(item, results);\n return out;\n }\n\n return value;\n}\n\nfunction rowOf(results: TxPlanOpResult[], opIndex: number, what: string): Record<string, unknown> {\n const result = results[opIndex];\n if (!result) {\n throw new TxPlanError(\n `the transaction returned no result for operation ${opIndex}, so ${what} ` +\n `cannot be read.`,\n );\n }\n const row = result.rows[0];\n if (!row) {\n // Unreachable through the public API: a handle only exists behind an\n // `expectOne`, and the server rolls back rather than answering 200 with a\n // guard unmet. Loud, because the alternative is `undefined` in tenant data.\n throw new TxPlanError(\n `the transaction's operation ${opIndex} returned no row, so ${what} cannot ` +\n `be read.`,\n );\n }\n return row;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n// ---------------------------------------------------------------------------\n// Runtime — the driver\n// ---------------------------------------------------------------------------\n\n/** What {@link runTxPlan} needs from the runtime: one call, one transaction. */\nexport interface TxPlanTransport {\n txPlan(plan: TxPlanBody): Promise<TxPlanResponse>;\n}\n\n/**\n * Build the plan, send it, and resolve the callback's return value.\n *\n * A callback that throws never reaches the network: there is nothing to roll\n * back because nothing was sent. A callback that describes no writes also skips\n * the round trip entirely.\n *\n * The RETURN type is `unknown` here on purpose. `Materialized<T>` is a compile-\n * time rewrite of the callback's return type, and it belongs on the public\n * `transaction()` signatures where `T` is inferred from the author's callback;\n * threading it through this driver as well would mean inferring `T` twice, from\n * two different positions, and reconciling them. The public wrappers narrow\n * once, at the seam where the value types were erased anyway.\n */\nexport async function runTxPlan<THandle>(\n transport: TxPlanTransport,\n // TUTAMAĞIN TAMAMI, yalnız `tables` DEĞİL. Tutamak artık şema yüzeyini de\n // taşıyor (`tx.public.x`, `tx.<şema>.x`), ve onu BURADA `{ tables }` diye\n // yeniden kurmak o yüzeyi sessizce düşürürdü.\n handle: THandle,\n builder: TxPlanBuilder,\n fn: (tx: THandle) => unknown,\n): Promise<unknown> {\n const returned = fn(handle);\n const body = builder.body();\n if (body.ops.length === 0) {\n return materializeResult(returned, []);\n }\n\n let response: TxPlanResponse;\n try {\n response = await transport.txPlan(body);\n } catch (err) {\n throw translateRejection(err, builder);\n }\n return materializeResult(returned, response.results);\n}\n\n/**\n * Turn the broker's rejection back into the tenant's own error.\n *\n * The server never sees the `Error` an expectation was given — only its slot\n * index — so this is the only place the intended error can be produced. A\n * rejection this SDK does not recognise passes through untouched: inventing an\n * error for it would hide the real failure.\n */\nfunction translateRejection(err: unknown, builder: TxPlanBuilder): unknown {\n if (typeof err !== \"object\" || err === null) return err;\n const rejection = err as TxPlanRejection;\n if (rejection.error_code !== \"tx_guard_failed\" || typeof rejection.slot !== \"number\") {\n return err;\n }\n return builder.errorForSlot(rejection.slot) ?? err;\n}\n","import type { DBClient, DBOps } from \"../../endpoint.js\";\nimport { validateInsertManyOptions, type InsertManyOptions } from \"../../db/bulk.js\";\n// The SAME refusals the engine applies. Without these the fake accepted every\n// call the driver path had just started rejecting, and the scaffold points\n// authors at this fake to test their services — so the test went green and\n// production threw. Measured against the published 24.1.0.\nimport { assertUsableFilter, assertUsableWriteValues, assertNoExpressionHandles, isColRef, isSqlFragment, isNowExpr, isColumnExpr } from \"../../db/input-guards.js\";\n\n/**\n * `sqlFragment` sahte veritabanında ÇALIŞTIRILAMAZ — ve sessizce yok sayılamaz.\n *\n * Fake'in bir SQL değerlendiricisi yok. Fragment'i görmezden gelmek, filtreyi\n * hiç uygulamamak demektir: test TÜM satırları görür, üretim ise süzülmüş\n * satırları. Yazarın testi o gün yeşil, üretim yanlış olur — bu dosyanın var\n * olma sebebi tam olarak o sınıf hata. O yüzden adıyla reddediliyor, ve hata\n * çalışan bir alternatif söylüyor (P6).\n */\nfunction refuseFragment(caller: string, table: string, where: unknown): void {\n if (isSqlFragment(where)) {\n throw new Error(\n `${caller}(${table}): fakeDatabase bir sqlFragment'i değerlendiremez — sahte depo SQL çalıştırmaz. ` +\n `Filtreyi tipli filtre diliyle kurun (gt/gte/lt/lte/neq/in/contains/isNull, OR/AND/NOT), ` +\n `ya da bu testi gerçek bir Postgres'e karşı yazın.`,\n );\n }\n // İÇ İÇE de reddedilir. Yalnız ÜST DÜZEYE bakmak, { OR: [ sqlFragment tag, … ] }\n // filtresini fake'te SESSİZCE boş sonuca çeviriyordu; motor onu derliyor\n // (W2-B/C5, ölçüldü). Reddin de bileşim dallarını dolaşması gerekiyor.\n if (where === null || typeof where !== \"object\") return;\n for (const [k, v] of Object.entries(where as Record<string, unknown>)) {\n if (k === \"OR\" || k === \"AND\") {\n for (const branch of (Array.isArray(v) ? v : [])) refuseFragment(caller, table, branch);\n } else if (k === \"NOT\") {\n refuseFragment(caller, table, v);\n }\n }\n}\n\n/**\n * Sayaç aritmetiği — motorun döndürdüğü ALANDA.\n *\n * Postgres `numeric` kolonu STRING döndürür ve toplamayı tam yapar. Fake\n * `Number()` ile hesaplıyordu; ölçülen sonuçlar: `\"0.10\" + \"0.20\"` →\n * `0.30000000000000004`, `\"12345678901234567890\" + 1` →\n * `12345678901234567000`, ve satırın tipi string'den number'a KAYIYORDU.\n * D-007'nin (string miktar) var olma sebebi tam olarak bu kayıptı; fake onu\n * geri getiriyordu (inceleme I-4/I-3).\n *\n * `null` + n = `null`: Postgres'te de öyle, satır değişmez.\n */\nfunction addDecimal(cell: unknown, by: number | string, sign: 1 | -1): unknown {\n if (cell === null || cell === undefined) return null;\n if (typeof cell === \"number\" && typeof by === \"number\") return cell + sign * by;\n const a = String(cell);\n const b = String(by);\n const parse = (x: string): { unit: bigint; scale: number } | null => {\n const m = /^([+-]?)(\\d*)(?:\\.(\\d*))?$/.exec(x.trim());\n if (m === null || (m[2] === \"\" && (m[3] ?? \"\") === \"\")) return null;\n const frac = m[3] ?? \"\";\n const unit = BigInt(`${m[1] === \"-\" ? \"-\" : \"\"}${m[2] === \"\" ? \"0\" : m[2]}${frac}`);\n return { unit, scale: frac.length };\n };\n const pa = parse(a);\n const pb = parse(b);\n if (pa === null || pb === null) {\n // Motor bu durumda Postgres'e sorar ve `operator does not exist:\n // text + integer` alır. Sessizce NaN yazmak yerine ADIYLA reddediyoruz.\n throw new Error(\n `fakeDatabase: increment()/decrement() sayısal olmayan bir değere uygulandı (\"${a}\") — ` +\n `Postgres bunu \"operator does not exist\" ile reddeder.`,\n );\n }\n const scale = Math.max(pa.scale, pb.scale);\n const lift = (v: { unit: bigint; scale: number }): bigint =>\n v.unit * 10n ** BigInt(scale - v.scale);\n const total = lift(pa) + BigInt(sign) * lift(pb);\n if (scale === 0) return typeof cell === \"number\" ? Number(total) : total.toString();\n const neg = total < 0n;\n const digits = (neg ? -total : total).toString().padStart(scale + 1, \"0\");\n const out = `${neg ? \"-\" : \"\"}${digits.slice(0, -scale)}.${digits.slice(-scale)}`;\n return typeof cell === \"number\" ? Number(out) : out;\n}\nimport { columnExprOf } from \"../../db/tx-plan.js\";\nimport type {\n TxPlanBody,\n TxPlanOpResult,\n TxPlanRejection,\n TxPlanResponse,\n TxWireGuard,\n TxWireOp,\n TxWireValue,\n} from \"../../db/tx-plan.js\";\n\n/** Tracked records for assertions. */\ninterface TrackedRecords {\n inserted: Map<string, Record<string, unknown>[]>;\n updated: Map<string, Record<string, unknown>[]>;\n deleted: Map<string, string[]>;\n}\n\n/** Mock DB client with tracking and seed data support. */\n/**\n * TEK EŞLEŞTİRİCİ — `findMany`, `updateMany`, `deleteMany` ve `count` bunu\n * kullanır.\n *\n * Motorda tek bir `compileWhereBare` var; fake'te DÖRT ayrı eşleştirici vardı\n * ve üçü yalnız katı eşitliğe bakıyordu. Ölçülen sonuç (inceleme C3/C6/I2):\n * `updateMany({ id, balance: { gte: \"5.00\" } }, …)` fake'te HİÇBİR satır\n * eşleştirmiyordu, yani FR-014'ün doc'unun ÖĞRETTİĞİ \"yetersiz bakiye\" deseni\n * fake'e karşı HER ZAMAN başarısız dala düşüyor — yazar başarı yolunu hiç test\n * edemiyor, üretimde para gerçekten çekiliyor.\n */\nfunction rowMatchesFilter(\n caller: string,\n table: string,\n row: Record<string, unknown>,\n f: Record<string, unknown>,\n): boolean {\n return Object.entries(f).every(([k, c]) => {\n if (k === \"OR\") return (c as Record<string, unknown>[]).some((b) => rowMatchesFilter(caller, table, row, b));\n if (k === \"AND\") return (c as Record<string, unknown>[]).every((b) => rowMatchesFilter(caller, table, row, b));\n if (k === \"NOT\") return !rowMatchesFilter(caller, table, row, c as Record<string, unknown>);\n // `has` ilişki GRAFİĞİ ister ve sahte deponun grafiği YOK — tablolar bir\n // Map'te, aralarındaki yabancı anahtarlar hiçbir yerde. Sessizce yok saymak\n // filtreyi hiç uygulamamak olurdu: test TÜM satırları görür, üretim\n // süzülmüş satırları. Bu dosyanın var olma sebebi tam olarak o sınıf.\n if (k === \"has\") {\n throw new Error(\n `${caller}(${table}): fakeDatabase bir \\`has\\` filtresini çözemez — ilişki grafiği ` +\n `bildirimden türetiliyor ve sahte deponun bildirimi yok. Bu testi gerçek bir Postgres'e ` +\n `karşı yazın, ya da ilişkiyi filtrede AÇIKÇA kurun (önce ilişki tablosunu okuyup ` +\n `{ id: { in: [...] } } ile süzün).`,\n );\n }\n return matchesCell(caller, table, row, k, c);\n });\n}\n\n/**\n * SQL'in üç değerli mantığı: NULL taşıyan karşılaştırma UNKNOWN'dır, yani satır\n * EŞLEŞMEZ. Fake `===` kullanıyordu ve iki NULL kolonu EŞİT sayıyordu — motorun\n * her yerde uyguladığı FR-006 doktrininin tersi (inceleme I3, ölçüldü).\n */\nfunction cmp(a: unknown, b: unknown, op: string): boolean {\n if (a === null || a === undefined || b === null || b === undefined) return false;\n const l = a instanceof Date ? a.getTime() : a;\n const r = b instanceof Date ? b.getTime() : b;\n switch (op) {\n case \"eq\": return l === r;\n case \"neq\": return l !== r;\n case \"gt\": return (l as number) > (r as number);\n case \"gte\": return (l as number) >= (r as number);\n case \"lt\": return (l as number) < (r as number);\n case \"lte\": return (l as number) <= (r as number);\n default: return false;\n }\n}\n\nfunction matchesCell(\n caller: string,\n table: string,\n row: Record<string, unknown>,\n key: string,\n cond: unknown,\n): boolean {\n // Kolon-kolon karşılaştırma (FR-011) — motorla PARİTE. Fake `col()`'u\n // tanımasaydı `{ $col: \"x\" }` nesnesini DEĞER sanıp eşitlik kurar, hiçbir\n // satır dönmez ve yazarın testi sessizce boş sonuca geçerdi.\n if (isColRef(cond)) return cmp(row[key], row[cond.$col], \"eq\");\n // `now()` — motorla PARİTE. Tutamak bir Proxy, yani `Object.entries` BOŞ\n // döner ve `.every()` boş listede TRUE'dur: ayırt edilmezse koşul HER SATIRLA\n // eşleşirdi. Yani \"süresi geçmemişler\" filtresi testte süresi geçenleri de\n // döndürür, test yeşil kalır ve üretimde davranış AYRIŞIRDI.\n if (isNowExpr(cond)) return cmp(row[key], new Date().toISOString(), \"eq\");\n if (cond !== null && typeof cond === \"object\" && !Array.isArray(cond)) {\n return Object.entries(cond as Record<string, unknown>).every(([op, v]) => {\n const cell = row[key];\n if (isNowExpr(v)) {\n if (![\"neq\", \"gt\", \"gte\", \"lt\", \"lte\"].includes(op)) {\n throw new Error(`${caller}(${table}): where.${key}.${op} now() ile kullanılamaz`);\n }\n return cmp(cell, new Date().toISOString(), op);\n }\n if (isColumnExpr(v)) {\n throw new Error(\n `${caller}(${table}): where.${key}.${op} bir YAZMA ifadesi aldı (increment/decrement) — ` +\n `karşılaştırma değeri değil. Sunucu saati için now() kullanın.`,\n );\n }\n if (isColRef(v)) {\n if (![\"neq\", \"gt\", \"gte\", \"lt\", \"lte\"].includes(op)) {\n throw new Error(`${caller}(${table}): where.${key}.${op} col() ile kullanılamaz`);\n }\n return cmp(cell, row[v.$col], op);\n }\n switch (op) {\n case \"in\":\n if (!Array.isArray(v)) throw new Error(`${caller}(${table}): where.${key}.in bir dizi olmalı`);\n if (v.some(isColRef)) {\n throw new Error(\n `${caller}(${table}): where.${key}.in col() ile kullanılamaz — kolon karşılaştırması için gt/gte/lt/lte/neq kullanın`,\n );\n }\n return v.includes(cell);\n case \"neq\": case \"gt\": case \"gte\": case \"lt\": case \"lte\":\n return cmp(cell, v, op);\n // K1 metin operatörleri (FR-005) ve null testi (FR-006). Bunlar BURADA\n // da olmak zorunda: guard onları KABUL ettiği anda fake sessizce yanlış\n // cevap verir ve yazarın testi, üretimde farklı davranan koda karşı\n // yeşil verirdi (input-guards.ts'in uyardığı tam sınıf).\n case \"isNull\":\n if (typeof v !== \"boolean\") throw new Error(`${caller}(${table}): where.${key}.isNull bir boolean olmalı`);\n return v ? cell == null : cell != null;\n case \"contains\": case \"icontains\": case \"startsWith\": case \"endsWith\": {\n if (typeof v !== \"string\") throw new Error(`${caller}(${table}): where.${key}.${op} bir string olmalı`);\n if (typeof cell !== \"string\") return false;\n if (op === \"contains\") return cell.includes(v);\n if (op === \"icontains\") return cell.toLowerCase().includes(v.toLowerCase());\n if (op === \"startsWith\") return cell.startsWith(v);\n return cell.endsWith(v);\n }\n default:\n throw new Error(`${caller}(${table}): where.${key} bilinmeyen operatör \"${op}\"`);\n }\n });\n }\n return row[key] === cond;\n}\n\nexport interface MockDBClient extends DBClient {\n /** Get records inserted into a table. */\n inserted(table: string): Record<string, unknown>[];\n /** Get records updated in a table. */\n updated(table: string): Record<string, unknown>[];\n /** Get IDs deleted from a table. */\n deleted(table: string): string[];\n /** Pre-seed data into a table for findById/findMany. */\n seed(table: string, data: Record<string, unknown>[]): void;\n}\n\n/** Create a mock DB client with in-memory tracking. */\nexport function createMockDB(): MockDBClient {\n const store = new Map<string, Record<string, unknown>[]>();\n const tracked: TrackedRecords = {\n inserted: new Map(),\n updated: new Map(),\n deleted: new Map(),\n };\n\n function rowsOf(table: string): Record<string, unknown>[] {\n let rows = store.get(table);\n if (!rows) {\n rows = [];\n store.set(table, rows);\n }\n return rows;\n }\n\n function track(\n map: Map<string, Record<string, unknown>[]>,\n table: string,\n row: Record<string, unknown>,\n ): void {\n const list = map.get(table);\n if (list) list.push(row);\n else map.set(table, [row]);\n }\n\n/**\n * EKLEME yolunda değerleri motorun yaptığı gibi çöz — `now()` sunucu saati,\n * sayaç ifadesi adıyla ret.\n *\n * Fake bunu bilmeseydi `assertNoExpressionHandles` `now()`'ı reddeder, test\n * kırmızı olur ve yazar ÇALIŞAN bir çağrıyı bozuk sanırdı. Sürüm 28'de motor\n * beş ekleme kurucusunun hepsinde `now()` derliyor.\n */\nfunction resolveInsertValues(\n caller: string,\n table: string,\n data: Record<string, unknown>,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(data)) {\n const expr = columnExprOf(v);\n if (expr !== null && expr.fn === \"now\") {\n out[k] = new Date().toISOString();\n continue;\n }\n if (expr !== null) {\n throw new Error(\n `${caller}(${table}): \"${k}\" ${expr.fn === \"inc\" ? \"increment()\" : \"decrement()\"} aldı — ` +\n `satır HENÜZ YOK, yani \"kolonun şu anki değeri\" diye bir şey yok.`,\n );\n }\n out[k] = v;\n }\n return out;\n}\n\n // Build the op surface first (the six string-keyed ops). `txPlan` below\n // interprets a whole plan against the SAME in-memory store and tracking maps,\n // so a transaction's writes are visible to later assertions exactly as a\n // direct write would be.\n const ops: DBOps = {\n diagnostics: () => null,\n // The bulk ops and count run against the SAME in-memory store the direct\n // ops write to, so a test that writes three rows and counts them gets 3 —\n // a mock that answered 0 would make the surface look broken in exactly the\n // tests meant to prove it works.\n async updateMany(\n table: string,\n where: Record<string, unknown>,\n set: Record<string, unknown>,\n opts?: { returning?: boolean },\n ) {\n if (Object.keys(where).length === 0) throw new Error(`updateMany(${table}): boş filtre`);\n assertUsableFilter(\"updateMany\", table, where);\n refuseFragment(\"updateMany\", table, where);\n assertUsableWriteValues(\"updateMany\", table, Object.keys(set), set);\n const hit = (store.get(table) ?? []).filter((r) =>\n rowMatchesFilter(\"updateMany\", table, r, where),\n );\n // increment()/decrement() (FR-012) — motorla PARİTE. Fake ifadeyi DEĞER\n // sanıp yazsaydı, sayaç kolonu bir proxy nesnesine dönerdi ve yazarın\n // testi \"artış oldu\" diye değil, sessizce bozuk veriyle geçerdi.\n for (const row of hit) {\n for (const [k, v] of Object.entries(set)) {\n const expr = columnExprOf(v);\n if (expr !== null && expr.fn === \"now\") {\n // Motor `SET col = now()` derliyor; fake'in karşılığı bir zaman damgası.\n row[k] = new Date();\n continue;\n }\n if (expr !== null) {\n row[k] = addDecimal(row[k], expr.by as number | string, expr.fn === \"inc\" ? 1 : -1);\n continue;\n }\n row[k] = v;\n }\n }\n // HER YAZMA `updated()`'a DÜŞER. `update` ve tx-plan'ın update op'u zaten\n // kaydediyordu; `updateMany` kaydetmiyordu, yani defter YARI KÖRDÜ:\n // servisini `updateMany` ile yazan bir tüketici\n // `expect(fake.updated(\"accounts\")).toEqual([])` yazar ve yazma GERÇEKTEN\n // olduğu hâlde yeşil alırdı — FR-008'in aynadaki hâli.\n for (const row of hit) track(tracked.updated, table, row);\n\n // `returning: false` SAYI döndürür, dizi değil — motor gibi\n // (engine/db.ts) ve tipli yüzeyin daralttığı gibi (db/typed-db.ts).\n // Sahte daima dizi döndürdüğü sürece\n // const n = await db.updateMany(t, w, s, { returning: false });\n // if (n === 0) throw new Conflict(...)\n // guard'ı testte HİÇ çalışmaz ([] === 0 değil), üretimde çalışır: test\n // yeşil, canlıda 409. `update`→null ile aynı sınıf yalan.\n return opts?.returning === false ? hit.length : hit;\n },\n async deleteMany(table: string, where: Record<string, unknown>) {\n if (Object.keys(where).length === 0) throw new Error(`deleteMany(${table}): boş filtre`);\n assertUsableFilter(\"deleteMany\", table, where);\n refuseFragment(\"deleteMany\", table, where);\n const list = store.get(table) ?? [];\n const keep = list.filter((r) => !rowMatchesFilter(\"deleteMany\", table, r, where));\n store.set(table, keep);\n return list.length - keep.length;\n },\n async count(table: string, where: Record<string, unknown> = {}) {\n assertUsableFilter(\"count\", table, where);\n // `refuseFragment` burada ATLANMIŞTI: fragment'li count fake'te sessizce\n // 0 döndürüyordu, motor gerçek sayıyı (W2-B/C4).\n refuseFragment(\"count\", table, where);\n return (store.get(table) ?? []).filter((r) =>\n rowMatchesFilter(\"count\", table, r, where),\n ).length;\n },\n async search(_table: string, _params?: Record<string, unknown>) {\n return [];\n },\n async facets(_table: string, _params?: Record<string, unknown>) {\n return {};\n },\n async similar() {\n return [];\n },\n async recommend() {\n return [];\n },\n async supersede(_table: string, _id: string, row: Record<string, unknown>) {\n return { id: crypto.randomUUID(), ...row };\n },\n async query(_sql: string, _params?: unknown[]) {\n return [];\n },\n\n async insert(table: string, raw: Record<string, unknown>) {\n const data = resolveInsertValues(\"insert\", table, raw);\n assertUsableWriteValues(\"insert\", table, Object.keys(data), data);\n // Motorla PARİTE: ifade tutamağı bu yolda değer değildir. Fake onu\n // satıra YAZIYORDU; satır artık JSON'a bile çevrilemiyordu.\n assertNoExpressionHandles(\"insert\", table, Object.keys(data), data);\n const record = { id: crypto.randomUUID(), ...data };\n rowsOf(table).push(record);\n track(tracked.inserted, table, record);\n return record;\n },\n\n /**\n * `insertMany` — motorla PARİTE, ANAHTAR KÜMESİ kuralı dahil.\n *\n * Fake bu kuralı bilmeseydi farklı şekilli satırları kabul eder, test yeşil\n * kalır, üretimde motor adıyla reddederdi — yani fake, sürüm atlamayı\n * kolaylaştırmak yerine gizlerdi.\n */\n /**\n * `aggregate` — motorla PARİTE, PARA KESİNLİĞİ dahil.\n *\n * Fake toplamayı JS `number` ile yapsaydı test yeşil kalır ve üretimde\n * `numeric` kesinliği kaybolurdu — yani fake tam da korunması gereken şeyi\n * gizlerdi. `addDecimal` BigInt ölçekli toplama yapıyor, motorun\n * `sum(numeric)::text`'inin karşılığı.\n */\n async aggregate(table: string, q: Parameters<DBOps[\"aggregate\"]>[1]) {\n const rows = (store.get(table) ?? []).filter((r) =>\n q.where === undefined || rowMatchesFilter(\"aggregate\", table, r, q.where),\n );\n const groups = q.groupBy ?? [];\n const shape = (bucket: Record<string, unknown>[]): Record<string, unknown> => {\n const out: Record<string, unknown> = {};\n for (const c of q.sum ?? []) {\n const vals = bucket.map((r) => r[c]).filter((v) => v !== null && v !== undefined);\n ((out[\"sum\"] ??= {}) as Record<string, unknown>)[c] =\n vals.length === 0 ? null : String(vals.reduce<string | number>((a, v) => addDecimal(a, v as string | number, 1) as string, \"0\"));\n }\n for (const c of q.avg ?? []) {\n const vals = bucket.map((r) => r[c]).filter((v) => v !== null && v !== undefined);\n ((out[\"avg\"] ??= {}) as Record<string, unknown>)[c] =\n vals.length === 0\n ? null\n : String(Number(vals.reduce<string | number>((a, v) => addDecimal(a, v as string | number, 1) as string, \"0\")) / vals.length);\n }\n for (const [fn, pick] of [[\"min\", -1], [\"max\", 1]] as const) {\n for (const c of q[fn] ?? []) {\n const vals = bucket.map((r) => r[c]).filter((v) => v !== null && v !== undefined);\n ((out[fn] ??= {}) as Record<string, unknown>)[c] =\n vals.length === 0\n ? null\n : vals.reduce((a, v) => (cmp(v, a, pick === 1 ? \"gt\" : \"lt\") ? v : a));\n }\n }\n if (q.count === true) out[\"count\"] = bucket.length;\n return out;\n };\n if (groups.length === 0) return shape(rows);\n const byKey = new Map<string, Record<string, unknown>[]>();\n for (const r of rows) {\n const k = JSON.stringify(groups.map((c) => r[c]));\n byKey.set(k, [...(byKey.get(k) ?? []), r]);\n }\n return [...byKey.values()].map((bucket) => {\n const out = shape(bucket);\n for (const c of groups) out[c] = bucket[0]![c];\n return out;\n });\n },\n\n insertMany: (async function(table: string, rows: readonly Record<string, unknown>[], opts?: InsertManyOptions) {\n validateInsertManyOptions(opts);\n if (opts?.onConflict?.length) throw new Error(\"fakeDatabase insertMany cannot enforce PostgreSQL unique constraints; use an integration test for onConflict\");\n if (rows.length === 0) return opts?.returning === false ? 0 : [];\n const cols = Object.keys(rows[0]!);\n for (let i = 1; i < rows.length; i++) {\n const missing = cols.filter((c) => !(c in rows[i]!));\n const extra = Object.keys(rows[i]!).filter((k) => !cols.includes(k));\n if (missing.length > 0 || extra.length > 0) {\n throw new Error(\n `insertMany(${table}): ${i}. satırın kolonları ilk satırla aynı değil` +\n (missing.length > 0 ? ` (eksik: ${missing.join(\", \")})` : \"\") +\n (extra.length > 0 ? ` (fazla: ${extra.join(\", \")})` : \"\") +\n `. Eksikler için null yazın, ya da farklı şekilli satırları ayrı çağrılarda ekleyin.`,\n );\n }\n }\n const out: Record<string, unknown>[] = [];\n for (const rawRow of rows) {\n const data = resolveInsertValues(\"insertMany\", table, rawRow);\n assertUsableWriteValues(\"insertMany\", table, cols, data);\n assertNoExpressionHandles(\"insertMany\", table, cols, data);\n const record = { id: crypto.randomUUID(), ...data };\n rowsOf(table).push(record);\n track(tracked.inserted, table, record);\n out.push(record);\n }\n return opts?.returning === false ? out.length : out;\n }) as DBOps[\"insertMany\"],\n\n /**\n * `claim` — motorla PARİTE (FR-033).\n *\n * Fake bunu sunmasaydı `claim` ile yazılmış bir servis, iskelenin yazarlara\n * önerdiği test yolunda `undefined is not a function` verirdi; sunup da\n * FARKLI davransaydı (ör. hep `inserted: true`) idempotency testi üretimde\n * çalışmayan koda karşı yeşil olurdu.\n *\n * Anahtar ZATEN VARSA var olan satır dönüyor ve hiçbir şey yazılmıyor —\n * motorun 23505 dalının aynısı.\n */\n /**\n * `lockRows` — sahte depoda kilit YOKTUR, ama çağrı da patlamamalı.\n *\n * Motorla parite burada \"aynı SQL\" değil, \"aynı SÖZLEŞME\": boş liste\n * no-op, tekrar edenler tekilleşir, ve PK'sı olmayan tablo adıyla\n * reddedilir. Kilidin kendisi tek işlemli bir sahte depoda anlamsız —\n * ama sözleşmeyi bozan bir çağrı burada da hata almalı.\n */\n async lockRows(table: string, ids: readonly string[]) {\n if (ids.length === 0) return;\n const rows = store.get(table) ?? [];\n const unique = [...new Set(ids)].sort();\n const missing = unique.filter((id) => !rows.some((r) => r[\"id\"] === id));\n if (missing.length > 0 && rows.length > 0) {\n // Sessiz geçmek, testin \"kilitledim\" sanmasına yol açardı.\n throw new Error(\n `lockRows(${table}): şu id'ler yok: ${missing.join(\", \")} — kilitlenecek satır bulunamadı.`,\n );\n }\n },\n\n /**\n * `lockRowsWhere` — `lockRows` ile AYNI gerekçe, aynı parite seviyesi.\n *\n * Kilit tek işlemli bir sahte depoda anlamsız, ama motorun REDDETTİĞİ bir\n * çağrı burada da reddedilmeli: boş filtre (bütün tabloyu kilitlemek) ve\n * tanınmayan bir kilit modu. Fake bunları geçirseydi, yazarın testi\n * üretimde patlayan bir çağrıya karşı yeşil olurdu.\n */\n async lockRowsWhere(\n table: string,\n where: Record<string, unknown>,\n opts?: { mode?: \"update\" | \"share\" | \"noKeyUpdate\" },\n ) {\n const mode = opts?.mode ?? \"update\";\n if (mode !== \"update\" && mode !== \"share\" && mode !== \"noKeyUpdate\") {\n throw new Error(\n `lockRowsWhere(${table}): bilinmeyen mode \"${String(mode)}\" — \"update\", \"share\" ya da \"noKeyUpdate\".`,\n );\n }\n if (Object.keys(where).length === 0) throw new Error(`lockRowsWhere(${table}): boş filtre`);\n assertUsableFilter(\"lockRowsWhere\", table, where);\n refuseFragment(\"lockRowsWhere\", table, where);\n // Eşleşen satırlar OKUNUYOR: filtre fake'in kendi eşleştiricisinden\n // geçmezse (ör. tanınmayan operatör) çağıran bunu burada öğrenir.\n (store.get(table) ?? []).filter((r) => rowMatchesFilter(\"lockRowsWhere\", table, r, where));\n },\n\n /** Sahte depoda kilit yok; sözleşme (çağrı patlamaz) korunuyor. */\n async advisoryXactLock(_key: string) {\n return undefined;\n },\n\n async claim(\n table: string,\n unique: Record<string, unknown>,\n extra: Record<string, unknown> = {},\n ) {\n const keyCols = Object.keys(unique);\n if (keyCols.length === 0) {\n throw new Error(\n `claim(${table}): benzersiz alan verilmedi. claim, bir anahtarı sahiplenmektir; ` +\n `anahtar yoksa sahiplenecek bir şey de yok — insert(${table}, …) kullanın.`,\n );\n }\n assertUsableWriteValues(\"claim\", table, keyCols, unique);\n const existing = (store.get(table) ?? []).find((r) =>\n keyCols.every((c) => r[c] === unique[c]),\n );\n if (existing) return { inserted: false, row: existing };\n const data = resolveInsertValues(\"claim\", table, { ...unique, ...extra });\n assertUsableWriteValues(\"claim\", table, Object.keys(data), data);\n assertNoExpressionHandles(\"claim\", table, Object.keys(data), data);\n const record = { id: crypto.randomUUID(), ...data };\n rowsOf(table).push(record);\n track(tracked.inserted, table, record);\n return { inserted: true, row: record };\n },\n\n // Same semantics the engine's SQL has: match on the conflict columns, update\n // everything else, and return the resulting row either way.\n async put(\n table: string,\n rawData: Record<string, unknown>,\n opts: { onConflict: readonly string[] },\n ) {\n if (opts.onConflict.length === 0) {\n throw new Error(`put into ${table}: onConflict en az bir kolon adı ister`);\n }\n const data = resolveInsertValues(\"put\", table, rawData);\n assertUsableWriteValues(\"upsert\", table, Object.keys(data), data);\n // Motorla PARİTE: ifade tutamağı bu yolda değer değildir. Fake onu\n // satıra YAZIYORDU; satır artık JSON'a bile çevrilemiyordu.\n assertNoExpressionHandles(\"upsert\", table, Object.keys(data), data);\n const rows = rowsOf(table);\n const existing = rows.find((r) => opts.onConflict.every((c) => r[c] === data[c]));\n if (existing) {\n for (const [k, v] of Object.entries(data)) {\n if (!opts.onConflict.includes(k)) existing[k] = v;\n }\n return existing;\n }\n const record = { id: crypto.randomUUID(), ...data };\n rows.push(record);\n track(tracked.inserted, table, record);\n return record;\n },\n\n async update(table: string, id: string, data: Record<string, unknown>) {\n assertUsableWriteValues(\"update\", table, Object.keys(data), data);\n const rows = store.get(table) ?? [];\n const idx = rows.findIndex((r) => r[\"id\"] === id);\n // 28'de motor `update(id)` ile `updateMany`'nin SET kurucusunu PAYLAŞIYOR,\n // yani `now()` ve sayaç ifadeleri burada da geçerli. Fake eskisi gibi\n // reddetseydi, ÇALIŞAN bir çağrı testte kırmızı olurdu — fake'in var olma\n // amacının tam tersi.\n const current = idx >= 0 ? rows[idx]! : {};\n const applied: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(data)) {\n const expr = columnExprOf(v);\n if (expr !== null && expr.fn === \"now\") {\n applied[k] = new Date();\n continue;\n }\n if (expr !== null) {\n applied[k] = addDecimal(current[k], expr.by, expr.fn === \"inc\" ? 1 : -1);\n continue;\n }\n applied[k] = v;\n }\n assertNoExpressionHandles(\"update\", table, Object.keys(applied), applied);\n // 0 SATIR → NULL, motorun KENDİSİ gibi (engine/db.ts:\n // `rows[0] ? asTableRow(table, rows[0]) : null`).\n //\n // Eskiden eşleşme yokken `{ id, ...applied }` UYDURULUYOR ve o uydurma\n // satır `updated()`'a da yazılıyordu. İki sonucu vardı: eşleşmeyen bir\n // update'i test eden kod SESSİZCE geçiyor ama üretimde `null` alıp\n // patlıyordu; ve \"0 satır → null\" sözleşmesi bu harness'la hiç\n // doğrulanamıyordu — bir tüketici projesi iddiayı yazamayıp yorum olarak\n // bırakmak zorunda kaldı (FR-007, FR-008).\n if (idx < 0) return null;\n const updated = { ...rows[idx], ...applied };\n rows[idx] = updated;\n track(tracked.updated, table, updated);\n return updated;\n },\n\n async delete(table: string, id: string) {\n const rows = store.get(table) ?? [];\n const idx = rows.findIndex((r) => r[\"id\"] === id);\n // EŞLEŞME YOKSA DEFTERE YAZILMAZ — `update` ile aynı kural (FR-008).\n // Eskiden eşleşmeyen bir `delete` de `deleted()`'a düşüyordu: silme\n // GERÇEKLEŞMEDİĞİ hâlde `expect(fake.deleted(\"x\")).toEqual([\"yok\"])`\n // yeşil oluyordu, yani defter olmayan bir yazmayı rapor ediyordu.\n if (idx < 0) return;\n rows.splice(idx, 1);\n const list = tracked.deleted.get(table);\n if (list) list.push(id);\n else tracked.deleted.set(table, [id]);\n },\n\n async findUnique() {\n throw new Error(\"MockDB.findUnique cannot verify declared PostgreSQL unique constraints; use a PostgreSQL integration test\");\n },\n async findById(table: string, id: string) {\n const rows = store.get(table) ?? [];\n return rows.find((r) => r[\"id\"] === id) ?? null;\n },\n\n // The SAME filter language the engine compiles to SQL: a plain value is\n // equality, an object is an operator set. A fake that understood less would\n // pass a service test that the live database then fails — which is the one\n // thing a stand-in must never do.\n async page() {\n throw new Error(\"fakeDatabase cannot reproduce PostgreSQL cursor ordering, collations or RLS; use a PostgreSQL integration test or inject an explicit page response\");\n },\n async findMany(\n table: string,\n query?: Record<string, unknown>,\n opts?: {\n orderBy?:\n | { column: string; direction?: \"asc\" | \"desc\"; nulls?: \"first\" | \"last\" }\n | { column: string; direction?: \"asc\" | \"desc\"; nulls?: \"first\" | \"last\" }[];\n select?: string[];\n with?: Record<string, unknown>;\n limit?: number;\n offset?: number;\n },\n ) {\n assertUsableFilter(\"findMany\", table, query);\n refuseFragment(\"findMany\", table, query);\n const { limit, offset } = opts ?? {};\n if (limit !== undefined && (!Number.isInteger(limit) || limit < 0)) {\n throw new Error(`findMany: limit bir negatif olmayan tam sayı olmalı (geldi: ${String(limit)})`);\n }\n if (offset !== undefined) {\n if (!Number.isInteger(offset) || offset < 0) {\n throw new Error(`findMany: offset bir negatif olmayan tam sayı olmalı (geldi: ${String(offset)})`);\n }\n if (limit === undefined) {\n throw new Error(\n \"findMany: offset yalnız limit ile birlikte verilir — limitsiz offset bir sayfa değil, sınırsız bir kuyruğun kaydırılmışıdır\",\n );\n }\n }\n // `with` — fake'in ilişki grafiği YOK, ve olsaydı ikinci bir yorumcu\n // olurdu (motorunki `buildRelations`'tan geliyor). Sessizce YOK SAYMAK\n // en kötüsü olurdu: yazar `rows[0].orders` yazar, `undefined` gelir ve\n // test motorun döndürdüğünden BAŞKA bir şeyi doğrular.\n if (opts?.with !== undefined && Object.keys(opts.with).length > 0) {\n throw new Error(\n `findMany(${table}): fakeDatabase \\`with\\` desteklemiyor — ilişki grafiği ` +\n `yabancı anahtarlardan TÜRETİLİYOR ve fake şemayı okumuyor. İlişkili ` +\n `satırları ölçen bir test gerçek motoru kullanmalı; fake ile ölçmek ` +\n `istiyorsanız ilgili satırları \\`seed\\` ile ayrı koyup ayrı sorgulayın.`,\n );\n }\n const rows = store.get(table) ?? [];\n let out = query\n ? rows.filter((row) => rowMatchesFilter(\"findMany\", table, row, query))\n : [...rows];\n // Çoklu sıralama ve NULL yeri — motorla PARİTE (FR-008). Tek obje de\n // kabul edilir; liste hâline getirilip aynı yoldan geçer.\n const orderSpecs = opts?.orderBy === undefined\n ? []\n : Array.isArray(opts.orderBy) ? opts.orderBy : [opts.orderBy];\n if (orderSpecs.length > 0) {\n out = [...out].sort((a, b) => {\n for (const o of orderSpecs) {\n const dir = o.direction === \"desc\" ? -1 : 1;\n const x = a[o.column];\n const y = b[o.column];\n const xNull = x === null || x === undefined;\n const yNull = y === null || y === undefined;\n if (xNull || yNull) {\n if (xNull && yNull) continue;\n // Verilmezse Postgres varsayılanı: ASC'de NULLS LAST, DESC'te FIRST.\n const nullsFirst = o.nulls === undefined ? dir === -1 : o.nulls === \"first\";\n return (xNull ? 1 : -1) * (nullsFirst ? -1 : 1);\n }\n if (x === y) continue;\n return ((x as never) < (y as never) ? -1 : 1) * dir;\n }\n return 0;\n });\n }\n const start = offset ?? 0;\n const page = limit === undefined ? out : out.slice(start, start + limit);\n // Projeksiyon (FR-009) — motorla PARİTE. Fake tam satır döndürürse, `select`\n // ile yazılmış bir kod sahte veritabanında seçilmemiş kolonu okur ve GEÇER;\n // gerçek motorda o kolon SQL'e hiç girmediği için `undefined` olur.\n const cols = opts?.select;\n if (cols === undefined || cols.length === 0) return page;\n return page.map((row) => Object.fromEntries(cols.map((c) => [c, row[c]])));\n },\n };\n\n /**\n * Interpret a whole plan, atomically.\n *\n * The rollback is the point. A test that asserts \"the second write failed, so\n * the first one is not there\" must be able to FAIL — a mock that applied ops\n * and left them applied would pass that test while the real broker rolled the\n * transaction back, or the other way round. So the store and the tracking maps\n * are snapshotted, and any failure restores both before rejecting.\n *\n * The rejection carries the same envelope fields the runtime copies off the\n * broker's response (`error_code`, `slot`), because the SDK maps `slot` back\n * to the caller's own Error — a mock that rejected with a bare Error would\n * make every guard in every tenant test look like a generic failure.\n */\n async function txPlan(plan: TxPlanBody): Promise<TxPlanResponse> {\n const snapshot = new Map<string, Record<string, unknown>[]>();\n for (const [table, rows] of store) snapshot.set(table, [...rows]);\n const trackedSnapshot: TrackedRecords = {\n inserted: cloneTracked(tracked.inserted),\n updated: cloneTracked(tracked.updated),\n deleted: new Map([...tracked.deleted].map(([k, v]) => [k, [...v]])),\n };\n\n const results: TxPlanOpResult[] = [];\n try {\n for (const op of plan.ops) {\n const result = applyOp(op, results);\n results.push(result);\n const failure = guardFailure(op.guard, result.rows.length);\n if (failure) throw failure;\n }\n } catch (err) {\n store.clear();\n for (const [table, rows] of snapshot) store.set(table, rows);\n tracked.inserted = trackedSnapshot.inserted;\n tracked.updated = trackedSnapshot.updated;\n tracked.deleted = trackedSnapshot.deleted;\n throw err;\n }\n return { results };\n }\n\n function applyOp(op: TxWireOp, results: TxPlanOpResult[]): TxPlanOpResult {\n switch (op.op) {\n case \"upsert\": {\n const values = resolveMap(op.values ?? {}, results, null);\n const conflict = op.onConflict ?? [];\n const rows = rowsOf(op.table);\n const hit = rows.find((r) => conflict.every((c) => r[c] === values[c]));\n if (hit) {\n for (const [key, value] of Object.entries(values)) {\n if (!conflict.includes(key)) hit[key] = value;\n }\n return { rows: [hit], rows_affected: 1 };\n }\n const created = { id: crypto.randomUUID(), ...values };\n rows.push(created);\n track(tracked.inserted, op.table, created);\n return { rows: [created], rows_affected: 1 };\n }\n case \"insert\": {\n const record = { id: crypto.randomUUID(), ...resolveMap(op.values ?? {}, results, null) };\n rowsOf(op.table).push(record);\n track(tracked.inserted, op.table, record);\n return { rows: [record], rows_affected: 1 };\n }\n case \"insertMany\": {\n const written = (op.rows ?? []).map((row) => {\n const record = { id: crypto.randomUUID(), ...resolveMap(row, results, null) };\n rowsOf(op.table).push(record);\n track(tracked.inserted, op.table, record);\n return record;\n });\n return { rows: written, rows_affected: written.length };\n }\n case \"update\": {\n const rows = rowsOf(op.table);\n const where = resolveMap(op.where ?? {}, results, null);\n const written: Record<string, unknown>[] = [];\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n if (!row || !matches(row, where)) continue;\n const next = { ...row, ...resolveMap(op.set ?? {}, results, row) };\n rows[i] = next;\n track(tracked.updated, op.table, next);\n written.push(next);\n }\n return { rows: written, rows_affected: written.length };\n }\n case \"delete\": {\n const rows = rowsOf(op.table);\n const where = resolveMap(op.where ?? {}, results, null);\n const removed = rows.filter((row) => matches(row, where));\n for (const row of removed) {\n rows.splice(rows.indexOf(row), 1);\n const id = row[\"id\"];\n const list = tracked.deleted.get(op.table);\n const key = typeof id === \"string\" ? id : String(id);\n if (list) list.push(key);\n else tracked.deleted.set(op.table, [key]);\n }\n return { rows: removed, rows_affected: removed.length };\n }\n case \"select\": {\n const where = resolveMap(op.where ?? {}, results, null);\n let found = rowsOf(op.table).filter((row) => matches(row, where));\n if (op.limit !== undefined) found = found.slice(0, op.limit);\n return { rows: found, rows_affected: found.length };\n }\n }\n }\n\n const client: MockDBClient = {\n ...ops,\n async command(plan, options) {\n if (options?.mode === \"compiled\") throw new Error(\"fakeDatabase does not run the PostgreSQL command executor; verify compiled mode against PostgreSQL\");\n return client.txPlan(plan);\n },\n\n async atomic() {\n throw new Error(\"fakeDatabase cannot verify physical transaction isolation, COMMIT or retry; test $atomic against PostgreSQL or inject a transaction test double explicitly\");\n },\n\n // No real savepoint in memory: the fake runs the callback against the SAME\n // store. An assertion about rollback here would be asserting the fake.\n attempt: <T,>(fn: (tx: DBOps) => Promise<T>): Promise<T> => fn(ops),\n\n txPlan,\n\n // In tests there is no real DB role; `asService()` returns the same\n // in-memory client so RLS-bypass code paths still hit the same store and\n // tracking maps. The omitted `asService` matches the contract (no\n // double-bypass), so callers can't recurse.\n asService(): Omit<DBClient, \"asService\"> {\n return client;\n },\n\n inserted(table: string) {\n return tracked.inserted.get(table) ?? [];\n },\n\n updated(table: string) {\n return tracked.updated.get(table) ?? [];\n },\n\n deleted(table: string) {\n return tracked.deleted.get(table) ?? [];\n },\n\n seed(table: string, data: Record<string, unknown>[]) {\n store.set(table, [...data]);\n },\n };\n\n return client;\n}\n\nfunction cloneTracked(\n map: Map<string, Record<string, unknown>[]>,\n): Map<string, Record<string, unknown>[]> {\n return new Map([...map].map(([k, v]) => [k, [...v]]));\n}\n\n/** Resolve one plan value: a `$ref` into an earlier result, a `$expr`, or a\n * literal. `current` is the row being updated, which is what `inc`/`dec` read. */\nfunction resolveValue(\n value: TxWireValue,\n results: TxPlanOpResult[],\n current: Record<string, unknown> | null,\n column: string,\n): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n const tagged = value as { $ref?: { op: number; field: string }; $expr?: Record<string, unknown> };\n\n if (tagged.$ref) {\n const row = results[tagged.$ref.op]?.rows[0];\n if (!row) {\n throw txRejection(409, \"tx_ref_unresolved\", {\n message: `operation ${tagged.$ref.op} produced no row to reference`,\n });\n }\n return row[tagged.$ref.field];\n }\n\n if (tagged.$expr) {\n const fn = tagged.$expr[\"fn\"];\n if (fn === \"now\") return new Date().toISOString();\n const by = Number(tagged.$expr[\"by\"]);\n const base = Number(current?.[column] ?? 0);\n return fn === \"dec\" ? base - by : base + by;\n }\n\n return value;\n}\n\nfunction resolveMap(\n map: Record<string, TxWireValue>,\n results: TxPlanOpResult[],\n current: Record<string, unknown> | null,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(map)) {\n out[key] = resolveValue(value, results, current, key);\n }\n return out;\n}\n\n/** Equality filter, with `null` meaning IS NULL — the broker's rule, so a\n * `{ accepted_at: null }` guard behaves the same in a test as in production. */\nfunction matches(row: Record<string, unknown>, where: Record<string, unknown>): boolean {\n return Object.entries(where).every(([key, value]) =>\n value === null ? row[key] === null || row[key] === undefined : row[key] === value,\n );\n}\n\nfunction guardFailure(guard: TxWireGuard | undefined, count: number): unknown {\n if (!guard) return null;\n const ok =\n guard.kind === \"one\"\n ? count === 1\n : guard.kind === \"none\"\n ? count === 0\n : guard.kind === \"atLeast\"\n ? count >= guard.n\n : count <= guard.n;\n if (ok) return null;\n return txRejection(409, \"tx_guard_failed\", {\n slot: guard.slot,\n message: `expected ${guard.kind} ${guard.n} row(s), got ${count}`,\n });\n}\n\n/** Build a rejection shaped like the one the runtime throws for a broker error:\n * an Error carrying the envelope's `status`/`error_code`/`slot`. */\nfunction txRejection(\n status: number,\n code: string,\n extra: { slot?: number; message: string },\n): Error & TxPlanRejection {\n const err = new Error(extra.message) as Error & TxPlanRejection;\n err.status = status;\n err.error_code = code;\n if (extra.slot !== undefined) err.slot = extra.slot;\n return err;\n}\n","/**\n * runtime.ts — request-scoped service singletons.\n *\n * The backend SDK no longer threads a `ctx` god-object through every handler.\n * Instead, controller methods import PascalCase service singletons directly:\n *\n * import { Controller, Post, Body, Database } from \"@palbase/backend\";\n *\n * \\@Controller(\"/todos\")\n * export default class TodosController {\n * \\@Post(\"\") create(\\@Body(CreateTodoBody) body: CreateTodoBody): unknown {\n * return Database.public.todos.insert({ title: body.title });\n * }\n * }\n *\n * The singletons are thin Proxies. Every property access forwards to the live\n * client for the CURRENT request scope, resolved through {@link __getRuntime}.\n *\n * # Request-scope resolution (persistent app-server)\n *\n * The runtime is a long-running Node process that serves many concurrent\n * requests on one event loop (NOT a fresh subprocess per request). A single\n * module-global slot would let one in-flight request's services bleed into\n * another's. So the services are carried in an {@link AsyncLocalStorage} store\n * ({@link __requestALS}) that the runtime sets per request with\n * {@link __runWithRuntime}; every async continuation of that request reads its\n * own store. `__getRuntime` reads the ALS store first; the module-global slot\n * (set by {@link __setRuntime}) is only a fallback for callers that run OUTSIDE\n * an ALS scope (dev-server, unit tests, the legacy single-shot path). Because\n * each `br-<ref>` pod is single-tenant, there is no cross-tenant leakage; the\n * ALS store is what prevents cross-REQUEST leakage within the shared process.\n *\n * The seam that makes `import { Database } from \"@palbase/backend\"` resolve to\n * the runtime-injected client: `@palbase/backend` is marked esbuild-EXTERNAL\n * when the tenant bundle is built, and the package is installed globally in the\n * pod (NODE_PATH=/usr/local/lib/node_modules). So worker.js's\n * `require('@palbase/backend')` and the bundle's `import` resolve to ONE shared\n * module instance — the ALS store and `__setRuntime` slot on that instance are\n * visible to the singletons the bundle imported.\n */\n\nimport type { PalbaseFlagKey } from \"./stack.js\";\nimport type { Buckets, BucketTypes, Schemas } from \"./db/env.js\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type {\n DBClient,\n AtomicClient,\n DBOps,\n CacheClient,\n Logger,\n PalbaseDocsClient,\n SecretsService,\n} from \"./endpoint.js\";\nimport type {\n PalbaseAuthAdminClient,\n PalbaseStorageClient,\n PalbaseBucketClient,\n PalbaseNotificationsClient,\n PalbaseFlagsClient,\n PalbaseFlagsServiceClient,\n PalbaseFlagContext,\n PalbaseFlagVariant,\n PalbaseFlag,\n PalbaseFlagValue,\n PalbaseSetOverrideResult,\n PalbaseRealtimeClient,\n} from \"./clients.js\";\nimport type { PalbaseResult } from \"./endpoint.js\";\nimport type {\n EnvTypedDatabase,\n EnvServiceDatabase,\n AtomicDatabase,\n EnvTables,\n TxPlan,\n TxTables,\n} from \"./db/typed-db.js\";\nimport type { Materialized } from \"./db/tx-plan.js\";\nimport { TxPlanBuilder, runTxPlan } from \"./db/tx-plan.js\";\nimport { assertPlanRetry, type AtomicOptions } from \"./db/transaction-options.js\";\nimport { qualifiedTableKey } from \"./db/schema-json.js\";\nimport type { DollarOps } from \"./db/typed-db.js\";\n\n/** The set of live clients the runtime injects per request scope.\n *\n * Realtime is BROADCAST-ONLY here (a stateless handler can push an event but\n * cannot hold a subscription socket — `subscribe()` lives on the client SDK).\n *\n * EXCLUDED on purpose: Functions, Links, Analytics. They are not exposed as\n * backend handler singletons — out of scope for backend endpoints. `Auth` is\n * here in its ROLE-ASSIGNMENT shape only: signing in is the client SDK's job,\n * but granting a role is an operator verb the tenant's own handler needs\n * (FR-009). */\nexport interface RuntimeServices {\n Database: DBClient;\n Auth: PalbaseAuthAdminClient;\n Secrets: SecretsService;\n Documents: PalbaseDocsClient;\n Storage: PalbaseStorageClient;\n Cache: CacheClient;\n Log: Logger;\n Notifications: PalbaseNotificationsClient;\n Flags: PalbaseFlagsClient;\n Realtime: PalbaseRealtimeClient;\n}\n\n/**\n * The per-request ALS box.\n *\n * `runtime` is the service bundle. `userId` is the request's authenticated user\n * id, written by the runtime immediately after it assembles the request object\n * (worker.js: `requestALS.getStore().userId = pbReq.user?.id || null`) and\n * `null` on an anonymous request. It was already being written there for the\n * Flags client's auto-bind; declaring it here makes the existing contract typed\n * instead of implicit, which is what lets `currentSubjectId()` read a\n * server-owned identity rather than trusting anything the caller sent.\n */\nexport interface RequestStore {\n runtime: RuntimeServices;\n userId?: string | null;\n /** This request's id (`req_…`), written by the runtime. Used as the spend\n * idempotency scope when the caller supplied no `Idempotency-Key`. */\n requestId?: string;\n /** The caller's `Idempotency-Key` header, or `null` when absent. What makes a\n * client's retry replay its first result instead of charging twice. */\n idempotencyKey?: string | null;\n}\n\n/**\n * Per-request store. The persistent runtime runs each request inside\n * {@link __runWithRuntime}, so every async continuation of that request reads\n * its OWN `runtime` (and any other request-scoped fields the runtime adds).\n *\n * Exported with a `__` prefix so the runtime (worker.js) shares the SAME ALS\n * instance across the one module instance — two ALS instances would silently\n * not see each other's stores. NOT part of the public author-facing API.\n */\n/**\n * The per-request store — ON globalThis under a well-known Symbol, for the same\n * reason `lifecycleHooks` and the controller registry are.\n *\n * MEASURED, through the production package gate: `tsup` emits `dist/index.cjs`\n * and `dist/test/index.cjs` as SEPARATE bundles and each inlines this module.\n * With a module-local `AsyncLocalStorage`, `withServices` (which ships from the\n * `/test` subpath) opened a scope in ITS copy while the `Database` singleton\n * (which ships from the root) read the OTHER copy's — and the ambient service a\n * test had just installed was invisible:\n *\n * Error: Palbase services accessed outside a request scope.\n *\n * The unit tests could not see it: inside the package there is only ever one\n * copy. It took calling the built artifact the way a consumer does. Same class\n * as the defect `@Module`'s slot comment describes — two module-local values\n * where the two halves of one contract must agree.\n *\n * SÜRÜMSÜZ, VE BU BİLİNÇLİ. Anahtar `…requestALS@32` gibi sürümlenseydi iki\n * major aynı süreçte ALS'i paylaşmayı BIRAKIRDI — yani yukarıda anlatılan kusur\n * sürüm sınırında geri gelirdi. Bedeli de gerçek ve burada yazılı:\n * `RequestStore.runtime` zorunlu bir `RuntimeServices` ve o küme büyüyor\n * (30.0.0 `Auth` ile 9→10). Eski bir majorün yazdığı kutuyu yeni bir major\n * okursa yeni alan `undefined` gelir.\n *\n * Bu pakette YEDİ well-known Symbol var ve hepsi sürümsüz (`httpError`,\n * `engineRaised`, `channels`, `errorRegistry`, `declarationRefusal`,\n * `lifecycleHooks`, ve bu). Yalnız BİRİNİ sürümlemek tutarsızlıktan başka bir\n * şey üretmez: karar paket geneli olmalı ve `RequestStore`'un şekil\n * sözleşmesiyle birlikte alınmalı (sapma defteri D-05).\n */\nconst REQUEST_ALS: unique symbol = Symbol.for(\"palbase.backend.requestALS\") as never;\n\nexport const __requestALS: AsyncLocalStorage<RequestStore> = ((): AsyncLocalStorage<RequestStore> => {\n const g = globalThis as unknown as Record<symbol, AsyncLocalStorage<RequestStore> | undefined>;\n return (g[REQUEST_ALS] ??= new AsyncLocalStorage<RequestStore>());\n})();\n\n/** Process-global fallback slot. Used only OUTSIDE an ALS scope (dev-server,\n * unit tests, legacy single-shot worker). Inside the persistent server every\n * request runs in {@link __requestALS}, which takes precedence. */\nlet runtime: RuntimeServices | null = null;\n\n/** Install the live clients in the process-global fallback slot.\n *\n * Persistent-server requests should use {@link __runWithRuntime} instead; this\n * remains for dev-server / tests / the legacy single-shot path that run without\n * an ALS scope. NOT part of the public author-facing API. */\nexport function __setRuntime(services: RuntimeServices): void {\n runtime = services;\n}\n\n/** Run `fn` with `services` bound as the request-scoped runtime.\n *\n * The persistent worker calls this once per request so concurrent requests\n * never share a services slot. NOT part of the public author-facing API. */\nexport function __runWithRuntime<T>(services: RuntimeServices, fn: () => T): T {\n return __requestALS.run({ runtime: services }, fn);\n}\n\n/** Read the live clients, throwing if accessed outside a request scope.\n *\n * Resolves the ALS store first (persistent server, per-request), then the\n * process-global fallback (dev-server / tests). NOT part of the public\n * author-facing API — used by the runtime and the singleton Proxies. */\n/**\n * Bir kutunun TAŞIMASI GEREKEN servisler.\n *\n * `withServices`'in listesiyle aynı gerçeği söylüyor ama BURADA yaşamak\n * zorunda: `test/` yalnız test yüzeyinde, bu kontrol ise her isteğin yolunda.\n * İkisi de `satisfies` ile `RuntimeServices`'a pinli, yani biri eksik kalırsa\n * derleme durur.\n */\nconst REQUIRED_SERVICES = [\n \"Database\",\n \"Auth\",\n \"Secrets\",\n \"Documents\",\n \"Storage\",\n \"Cache\",\n \"Log\",\n \"Notifications\",\n \"Flags\",\n \"Realtime\",\n] as const satisfies readonly (keyof RuntimeServices)[];\n\n/**\n * ÇAPRAZ-MAJOR KUTUYU ADIYLA REDDET (sapma defteri D-05).\n *\n * `__requestALS` sürümSÜZ bir `Symbol.for` altında ve bu bilinçli: iki bundle\n * (`dist/index.cjs` ve `dist/test/index.cjs`) ambient kapsamı ancak öyle\n * paylaşır. Bedeli de gerçek — tek süreçte iki major varsa ESKİ olanın yazdığı\n * kutuyu YENİ olan okur, ve servis kümesi büyümüşse (30.0.0'da 9→10, `Auth`)\n * yeni alan `undefined` gelir.\n *\n * `undefined` bir servis, erişildiğinde `Reflect.get called on non-object`\n * verir: ne eksik olanın adı, ne sebebi. Bu kontrol o sessizliği bir cümleye\n * çevirir. Maliyeti istek başına on `in` kontrolü.\n */\nfunction refuseIncompleteBox(services: RuntimeServices): RuntimeServices {\n const missing = REQUIRED_SERVICES.filter((k) => services[k] === undefined);\n if (missing.length > 0) {\n throw new Error(\n `the request scope is missing ${missing.join(\", \")} — this box was most likely written by a ` +\n `DIFFERENT @palbase/backend major sharing the same process (the request store is a ` +\n `process-wide well-known Symbol, deliberately, so two bundles of ONE version can share it). ` +\n `Align the versions, or pass every service when building the scope yourself.`,\n );\n }\n return services;\n}\n\nexport function __getRuntime(): RuntimeServices {\n const scoped = __requestALS.getStore();\n if (scoped) return refuseIncompleteBox(scoped.runtime);\n if (runtime === null) {\n throw new Error(\n \"Palbase services accessed outside a request scope. The Database/Documents/… \" +\n \"singletons are only available inside an endpoint handler (or after the \" +\n \"runtime has called __runWithRuntime / __setRuntime).\",\n );\n }\n return runtime;\n}\n\n// ─── lifecycle: where a long-lived resource lives (FR-013) ─────────────────\n//\n// `Resource` was removed in 23.0.0 and nothing replaced the LIFECYCLE half of\n// it. What that left behind is measurable: a connection pool (the driver in\n// `docs/resources.md`'s own example was Neo4j) had no documented place to be\n// opened and NO WAY AT ALL to be closed, so every deploy left the pool it\n// opened behind. These two hooks are that half — and only that half. The\n// secret-distribution half does not come back: a handler reads `Secrets.get`,\n// and a start hook, which runs before any request scope exists, reads the\n// `process.env` the runtime mirrors the vault into at boot.\n\n/** A lifecycle hook. Sync or async; the runtime awaits what it returns. */\nexport type LifecycleHook = () => void | Promise<void>;\n\n/** Runs one release's shutdown hooks. Handed back by {@link __runStartHooks}\n * and called by the engine's `app.shutdown()`. Idempotent. */\nexport type ShutdownRunner = () => Promise<void>;\n\ninterface DeclaredHook {\n name: string;\n run: LifecycleHook;\n}\n\ninterface DeclaredLifecycle {\n start: DeclaredHook[];\n shutdown: DeclaredHook[];\n}\n\n/**\n * What has been DECLARED and not yet claimed by an app.\n *\n * On globalThis under a well-known Symbol for the reason the controller\n * registry is (`decorators/controller.ts`): a deployed bundle inlines its own\n * copy of this package, and the engine that has to RUN these hooks holds the\n * other copy. Two module-local arrays would mean the engine reads the empty one\n * and every declared hook is silently never run — which is exactly how\n * `Resource`'s `init(env)` died.\n */\nconst LIFECYCLE: unique symbol = Symbol.for(\"palbase.backend.lifecycleHooks\") as never;\n\nfunction declaredLifecycle(): DeclaredLifecycle {\n const g = globalThis as unknown as Record<symbol, DeclaredLifecycle | undefined>;\n return (g[LIFECYCLE] ??= { start: [], shutdown: [] });\n}\n\n/**\n * Run `hook` ONCE while the application comes up, before it serves anything.\n *\n * Call it at MODULE SCOPE in a file the application imports — the same rule\n * `defineDefaultAuth` and `@Controller` follow, and for the same reason: the\n * declaration is claimed when the app boots, which is after module loading and\n * before the first request. `name` is not decoration: a hook that throws is\n * reported by that name and the boot is REFUSED, so it is what tells an\n * operator which resource did not come up.\n *\n * There is no request scope yet, so the `Database`/`Secrets`/… singletons are\n * NOT available inside a start hook. A secret is read from `process.env` here\n * (the runtime mirrors the vault into it at boot).\n *\n * @example\n * // resources/graph.ts\n * import neo4j from \"neo4j-driver\";\n * import { onStart, onShutdown } from \"@palbase/backend\";\n *\n * export let graph: Driver;\n * onStart(\"graph\", () => {\n * graph = neo4j.driver(process.env.NEO4J_URL!, neo4j.auth.basic(\"neo4j\", process.env.NEO4J_PASSWORD!));\n * });\n * onShutdown(\"graph\", () => graph.close());\n */\nexport function onStart(name: string, hook: LifecycleHook): void {\n declaredLifecycle().start.push({ name, run: hook });\n}\n\n/**\n * Run `hook` while the application shuts down — the place a pool opened in\n * {@link onStart} is closed.\n *\n * Shutdown is BEST-EFFORT by design: a hook that throws is reported by name and\n * the rest still run. A drain that abandoned the remaining hooks on the first\n * failure would leak exactly what this exists to release, and the process is\n * leaving anyway.\n *\n * Hooks run in REVERSE declaration order, so a resource is released before what\n * it was built on.\n */\nexport function onShutdown(name: string, hook: LifecycleHook): void {\n declaredLifecycle().shutdown.push({ name, run: hook });\n}\n\nfunction reason(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/** Best-effort drain: every hook runs, a failure is reported, none is silent. */\nasync function drain(hooks: DeclaredHook[]): Promise<void> {\n for (const h of [...hooks].reverse()) {\n try {\n await h.run();\n } catch (err) {\n console.error(`[palbase] shutdown hook \"${h.name}\" failed: ${reason(err)}`, err);\n }\n }\n}\n\n/**\n * CLAIM what has been declared, run the start hooks, and hand back the runner\n * for this release's shutdown hooks. Called by the engine's `createApp`; the\n * `App.shutdown()` it builds calls what comes back. NOT part of the public\n * author-facing API.\n *\n * IT CLAIMS RATHER THAN READS, which is what makes it correct in this runtime:\n * a candidate release is loaded BESIDE the live one in one process\n * (`v2/runtime/src/registry-scope.ts`), and both bundles append to the one\n * shared slot above. If each app read the whole list, the live app's shutdown\n * would close the candidate's pool and the candidate's would close the live\n * app's. Taking the declarations leaves each app holding exactly its own.\n *\n * A start hook that throws REFUSES THE BOOT — with the hook's name in the\n * message — after releasing whatever the earlier hooks already opened. Serving\n * from a half-initialised app is the silence this whole surface replaces, and a\n * boot that dies holding an open pool is the leak it replaces.\n */\nexport async function __runStartHooks(): Promise<ShutdownRunner> {\n const slot = declaredLifecycle();\n const start = slot.start.splice(0);\n const shutdown = slot.shutdown.splice(0);\n\n for (const h of start) {\n try {\n await h.run();\n } catch (err) {\n await drain(shutdown);\n throw new Error(`[palbase] start hook \"${h.name}\" failed: ${reason(err)}`, { cause: err });\n }\n }\n\n let drained = false;\n return async () => {\n // SIGTERM racing a redeploy asks twice; a pool is closed once.\n if (drained) return;\n drained = true;\n await drain(shutdown);\n };\n}\n\n/** Drop every declaration. For tests, which declare repeatedly in one process.\n * NOT part of the public author-facing API. */\nexport function __resetLifecycleHooks(): void {\n const g = globalThis as unknown as Record<symbol, DeclaredLifecycle | undefined>;\n delete g[LIFECYCLE];\n}\n\n/**\n * Build a Proxy singleton that forwards every property access to the live\n * client named `key` on the current runtime.\n *\n * The single `as RuntimeServices[K]` is the only contained cast in the surface:\n * `Reflect.get` on a typed object returns `unknown` for a `string | symbol`\n * key, but `prop` is constrained to keys of the client interface at the call\n * sites (the exported singletons are typed below), so the forward is sound.\n */\nfunction makeServiceProxy<K extends keyof RuntimeServices>(key: K): RuntimeServices[K] {\n const handler: ProxyHandler<RuntimeServices[K]> = {\n get(_target, prop, receiver) {\n const client = __getRuntime()[key];\n const value = Reflect.get(client as object, prop, receiver) as unknown;\n // Bind methods to their owning client so `this` stays correct when the\n // author destructures or calls `Database.query(...)`.\n return typeof value === \"function\" ? value.bind(client) : value;\n },\n };\n // The Proxy target is irrelevant (all access goes through `get`); the cast\n // names the surface type the singleton presents to authors.\n return new Proxy({} as RuntimeServices[K], handler);\n}\n\n/**\n * Build the `.tables` accessor for the top-level `Database`. Each\n * `tables.<name>` access returns a small object that forwards the five CRUD ops\n * to the underlying client using `name` as the string table identifier. The\n * shapes are typed against the generated `palbase-env.d.ts` (`EnvTables`); at\n * runtime they are plain string-keyed calls, so no schema value is needed here.\n *\n * Returns `EnvTables` — TS cannot infer the mapped type through the Proxy, so\n * a single structural narrowing names the surface (the proxy returns a\n * correctly-shaped accessor for whatever string member is read).\n */\n/** T018 (C-8): similar/recommend'in string-keyed yüzü. DBOps'a (endpoint.ts)\n * BİLEREK eklenmedi — search-param imza üçlüsü (engine/db + typed-db +\n * endpoint) büyümesin: proxy dispatch runtime'da engine ops'una zaten ulaşır,\n * derleme güvenliğini typed yüzey (EnvTypedTable) verir. */\nexport interface RecoOps {\n similar(table: string, id: string, params?: Record<string, unknown>): Promise<Record<string, unknown>[]>;\n recommend(table: string, params: Record<string, unknown>): Promise<Record<string, unknown>[]>;\n}\n\n/**\n * The Proxy behind EVERY `.tables` map — public's and every other schema's.\n *\n * `prefix` is what the wire name is built from: `\"\"` for `public`, so its tables\n * stay BARE, and `\"<schema>.\"` for any other, so `schema(\"billing\").tables\n * .invoices` reaches the broker as `billing.invoices` (D-10 — the same\n * schema-qualified key `toSchemaJSON` and the generated `relations` use).\n *\n * One trap for both surfaces: two copies would be two op lists that can drift,\n * and the one that forgets an op does not complain — it answers `undefined`.\n */\nfunction makeTableProxy(ops: () => DBOps & RecoOps, prefix: string): object {\n return new Proxy(\n {},\n {\n get(_t, prop: string | symbol) {\n if (typeof prop !== \"string\") return undefined;\n const name = `${prefix}${prop}`;\n return {\n insert: (data: Record<string, unknown>) => ops().insert(name, data),\n // DÖRDÜNCÜ FİİL, aynı gerekçeyle: tip söz veriyor, ops katmanı\n // uyguluyor, ve bir handler'ın gerçekten dokunduğu yer BURASI.\n // `runtime-table-verbs` kapısı bunu adıyla saydı.\n aggregate: (q: Parameters<DBOps[\"aggregate\"]>[1]) => ops().aggregate(name, q),\n insertMany: (\n rows: readonly Record<string, unknown>[],\n opts?: import(\"./db/bulk.js\").InsertManyOptions,\n ) => ops().insertMany(name, rows, opts),\n update: (q: { where: { id: string }; set: Record<string, unknown> }) =>\n ops().update(name, q.where.id, q.set),\n delete: (id: string) => ops().delete(name, id),\n findById: (id: string) => ops().findById(name, id),\n findUnique: (q: { where: Record<string, unknown>; select?: readonly string[]; with?: Record<string, unknown> }) =>\n ops().findUnique(name, q.where, { select: q.select, with: q.with }),\n page: (q?: Record<string, unknown>) => {\n const { where, ...opts } = q ?? {};\n return ops().page(name, where as Record<string, unknown> | undefined, opts as import(\"./db/page.js\").RawPageOptions);\n },\n findMany: (q?: Record<string, unknown>) => {\n // `where` AYIKLANIR; kalan alanlar (orderBy/limit/offset) ham op'un\n // ikinci parametresine gider. Tümünü geçirmek `where`'i tel üstünde\n // ikinci kez gönderirdi — `typed-db.test.ts` bunu yakalıyor.\n const { where, ...opts } = q ?? {};\n return ops().findMany(\n name,\n where as Record<string, unknown> | undefined,\n opts as Parameters<DBOps[\"findMany\"]>[2],\n );\n },\n put: (q: { data: Record<string, unknown>; onConflict: readonly string[] }) =>\n ops().put(name, q.data, { onConflict: q.onConflict }),\n // THREE VERBS THE TYPE PROMISED AND THIS PROXY DID NOT EMIT.\n //\n // `EnvTypedTableBase` declares `updateMany`, `deleteMany` and `count`\n // (typed-db.ts) and the ops layer implements all three — only this\n // proxy, which is what a handler actually touches, left them out. So\n // the type said the verb exists, autocomplete offered it, and the call\n // answered `undefined is not a function`.\n //\n // Older than this run, but the run rewrote this proxy for\n // `Database.schema(name).tables.*` and would have carried the gap onto\n // the new surface too.\n updateMany: (q: { where: Record<string, unknown>; set: Record<string, unknown>; returning?: boolean }) =>\n ops().updateMany(name, q.where, q.set, q.returning === undefined ? undefined : { returning: q.returning }),\n deleteMany: (q: { where: Record<string, unknown> }) => ops().deleteMany(name, q.where),\n count: (q?: { where?: Record<string, unknown> }) => ops().count(name, q?.where),\n search: (params?: Record<string, unknown>) => ops().search(name, params),\n similar: (id: string, params?: Record<string, unknown>) => ops().similar(name, id, params),\n recommend: (params: Record<string, unknown>) => ops().recommend(name, params),\n facets: (params: { facets: string[] } & Record<string, unknown>) => ops().facets(name, params),\n supersede: (id: string, row: Record<string, unknown>) => ops().supersede(name, id, row),\n claim: (unique: Record<string, unknown>, extra?: Record<string, unknown>) =>\n ops().claim(name, unique, extra),\n };\n },\n },\n );\n}\n\n\n/** The raw string-keyed `DBClient` for the current request scope. */\nconst rawDatabase: DBClient = makeServiceProxy(\"Database\");\n\n/**\n * Wrap a raw `DBClient` into the typed `{ ...ops, tables, transaction }`\n * surface. The five string ops forward straight through; `tables` is the\n * env-typed accessor; `transaction` yields typed tables. Reused for both the\n * default (RLS-enforced) `Database` and the `asService()` sibling — each is\n * fed its own raw client (the default proxy vs `rawDatabase.asService()`).\n *\n * The `satisfies` pins the op surface so a missing/renamed op is a compile\n * error; the assembled object carries `tables`/`transaction` alongside.\n */\n/**\n * PACKAGE-INTERNAL, and deliberately NOT re-exported from `index.ts`.\n *\n * `test/fake-db.ts` builds the fake's surface with the SAME constructor\n * production uses, so the two cannot drift: the day a `$op` is added here, the\n * fake grows it in the same commit. Exporting it from the public index instead\n * would put a runtime-assembly detail on the author-facing API (FR-006).\n */\nexport function makeTypedSurface(raw: AtomicClient & Partial<Pick<DBClient, \"atomic\">>): EnvServiceDatabase {\n // Proxy dispatch her üyeyi taşır; RecoOps tipi DBClient'a eklenmediğinden\n // (yukarıdaki karar) similar/recommend erişimi bu daraltmadan geçer.\n const reco = raw as Omit<DBClient, \"asService\"> & RecoOps;\n // `$` ÖNEKİ AÇIKÇA YAZILIR, dinamik üretilmez.\n //\n // Bir tur `Object.fromEntries(Object.entries(ops).map(…))` ile üretilmişti ve\n // `database.test.ts`'in sayımı onu göremedi: sayım DEKLARASYONLARI okuyor,\n // string literal'leri değil. Görünmeyen bir yüzey denetlenemez — ve o testin\n // varlık sebebi tam olarak budur (FR-044: yüzeyde bağlantı bilgisi olmadığını\n // kanıtlamak, ama önce yüzeye gerçekten ULAŞTIĞINI kanıtlamak).\n const ops = {\n $query: (sql: string, params?: unknown[]) => raw.query(sql, params),\n $diagnostics: () => raw.diagnostics(),\n $insert: (table: string, data: Record<string, unknown>) => raw.insert(table, data),\n $update: (table: string, id: string, data: Record<string, unknown>) =>\n raw.update(table, id, data),\n $delete: (table: string, id: string) => raw.delete(table, id),\n $findById: (table: string, id: string) => raw.findById(table, id),\n $findUnique: (table: string, where: Record<string, unknown>, opts?: Parameters<DBOps[\"findUnique\"]>[2]) => raw.findUnique(table, where, opts),\n $page: (table: string, query?: Record<string, unknown>, opts?: import(\"./db/page.js\").RawPageOptions) => raw.page(table, query, opts),\n $findMany: (table: string, query?: Record<string, unknown>, opts?: Parameters<DBOps[\"findMany\"]>[2]) =>\n raw.findMany(table, query, opts),\n $put: (table: string, data: Record<string, unknown>, opts: { onConflict: readonly string[] }) =>\n raw.put(table, data, opts),\n // `opts` İLETİLİR. Düşürüldüğü sürece `Database.$updateMany(t, w, s,\n // { returning: false })` sessizce SATIRLARI döndürüyordu, sayıyı değil —\n // ve `if (n === 0) throw new Conflict(...)` guard'ı HİÇ çalışmıyordu,\n // çünkü `[] === 0` yanlıştır. Komşu forwarder'lar (`$findMany`, `$put`)\n // kendi opsiyonlarını zaten iletiyordu; bu biri unutulmuştu.\n $updateMany: (\n table: string,\n where: Record<string, unknown>,\n set: Record<string, unknown>,\n opts?: Parameters<DBOps[\"updateMany\"]>[3],\n ) => raw.updateMany(table, where, set, opts),\n $deleteMany: (table: string, where: Record<string, unknown>) => raw.deleteMany(table, where),\n $count: (table: string, where?: Record<string, unknown>) => raw.count(table, where),\n $search: (table: string, params?: Record<string, unknown>) => raw.search(table, params),\n $similar: (table: string, id: string, params?: Record<string, unknown>) =>\n reco.similar(table, id, params),\n $recommend: (table: string, params: Record<string, unknown>) => reco.recommend(table, params),\n $facets: (table: string, params: { facets: string[] } & Record<string, unknown>) => reco.facets(table, params),\n $claim: (table: string, unique: Record<string, unknown>, extra?: Record<string, unknown>) =>\n reco.claim(table, unique, extra),\n $lockRows: (table: string, ids: readonly string[]) => reco.lockRows(table, ids),\n $lockRowsWhere: (\n table: string,\n where: Record<string, unknown>,\n opts?: Parameters<DBOps[\"lockRowsWhere\"]>[2],\n ) => reco.lockRowsWhere(table, where, opts),\n $advisoryXactLock: (key: string) => reco.advisoryXactLock(key),\n $aggregate: (table: string, q: Parameters<DBOps[\"aggregate\"]>[1]) => raw.aggregate(table, q),\n $insertMany: ((\n table: string,\n rows: readonly Record<string, unknown>[],\n opts?: import(\"./db/bulk.js\").InsertManyOptions,\n ) => raw.insertMany(table, rows, opts)) as DBOps[\"insertMany\"],\n $supersede: (table: string, id: string, row: Record<string, unknown>) =>\n raw.supersede(table, id, row),\n } satisfies DollarOps<Omit<DBOps & RecoOps, \"attempt\">>;\n // `ops` DOĞRUDAN verilir, spread edilmez: sayım (`database.test.ts`) nesneyi\n // deklarasyonundan takip ediyor ve bir spread onu kaybettiriyor. Görünmeyen\n // yüzey denetlenemez.\n const base = Object.assign(ops as unknown as Record<string, unknown>, {\n $atomic<T>(fn: (tx: AtomicDatabase) => Promise<T>, options?: AtomicOptions): Promise<T> {\n if (typeof raw.atomic !== \"function\") {\n throw new Error(\"This Database handle cannot open a root transaction; nested $atomic is not supported\");\n }\n // ALS.run scopes only this callback and its continuations, never another\n // Promise.all branch. Calls made by ordinary services through Database\n // therefore share the callback's physical transaction and identity.\n const parent = __requestALS.getStore();\n let runtime: RuntimeServices | undefined;\n try { runtime = __getRuntime(); } catch { /* Direct typed engine handles need no ambient runtime. */ }\n return raw.atomic(async (tx) => {\n const typed = makeTypedSurface(tx);\n const invoke = () => fn(typed);\n if (!runtime) return invoke();\n const refuse = (): never => { throw new Error(\"Database.$atomic owns one transaction and identity; nested roots and $asService are not allowed\"); };\n const ambient = Object.assign({}, tx, { atomic: refuse, asService: refuse });\n return __requestALS.run({ ...parent, runtime: { ...runtime, Database: ambient } }, invoke);\n }, options);\n },\n // Both surfaces get it: a savepoint on the service transaction is as useful\n // as one on the request's, and each is bound to its own connection.\n $attempt: <T,>(fn: (tx: DBOps) => Promise<T>) => raw.attempt(fn),\n $transaction<T>(\n fn: (tx: TxPlan) => T extends Promise<unknown> ? never : T,\n opts?: { retry?: number },\n ): Promise<Materialized<T>> {\n // A FRESH builder per call: it holds this transaction's ops and its error\n // slot table, and the runtime serves concurrent requests on one event loop.\n // A shared builder would splice one request's writes into another's plan.\n //\n assertPlanRetry(opts);\n const builder = new TxPlanBuilder();\n return runTxPlan(raw, makeTxPlanHandle(builder), builder, fn) as Promise<Materialized<T>>;\n },\n $command<T>(fn: (tx: TxPlan) => T extends Promise<unknown> ? never : T, options?: import(\"./db/command.js\").CommandOptions): Promise<Materialized<T>> {\n const builder = new TxPlanBuilder();\n return runTxPlan({ txPlan: plan => raw.command(plan, options) }, makeTxPlanHandle(builder), builder, fn) as Promise<Materialized<T>>;\n },\n });\n // ŞEMA ERİŞİMİ BİR PROXY'DİR, çünkü hangi şemaların bildirildiğini yalnız TİP\n // bilir — runtime'da `Database.billing` diye bir üye yoktur, o ada dokunulduğu\n // anda üretilir. `$`'la başlamayan her ad bir ŞEMA adıdır; ayrım tam olarak\n // budur ve tip tarafındaki DollarOps ile aynı kuralı uygular.\n return new Proxy(base, {\n get(target, prop, receiver) {\n // `tables` DOĞRUDAN YÜZEYDE DE public'in takma adı.\n //\n // Plan tutamağı `tx.tables.todos`'u öğretiyor (göç notu da öyle), ama\n // `Database.public.todos` aynı kelimeyi ADI `tables` OLAN BİR ŞEMA sanıp\n // tele `tables.todos` yazıyordu. Tip onu reddettiği için derlenen kodda\n // erişilemezdi — ama `as any` ya da düz JS ile geçen biri sessizce\n // olmayan bir şemaya gidiyordu, ve iki yüzeyin aynı kelimeye zıt cevap\n // vermesi bu run'ın kapattığı sınıfın kendisi (gözcü M-6).\n if (prop === \"tables\") return makeTableProxy(() => reco, \"\");\n if (typeof prop === \"string\" && !prop.startsWith(\"$\") && !(prop in target)) {\n // Nitelikli tablo anahtarının kuralı BURADA TEKRARLANMAZ (FR-058): tek\n // yazıcı `qualifiedTableKey` ve `table-key-single-source.test.ts` ikinci\n // bir yazıcıyı reddediyor. Prefix ondan türetilir — boş tablo adıyla\n // çağrıldığında geriye ya \"\" (public) ya \"<şema>.\" kalır.\n return makeTableProxy(() => reco, qualifiedTableKey(prop, \"\"));\n }\n return Reflect.get(target, prop, receiver);\n },\n }) as unknown as EnvServiceDatabase;\n}\n\n/**\n * `makeTableProxy`'nin plan ikizi: `tables.<name>` yields the\n * table's PLAN operations, recorded into `builder` instead of sent one by one.\n *\n * Same Proxy shape and same reason for the single narrowing — TS cannot infer a\n * mapped type through a Proxy, so the cast names what the trap returns.\n */\nfunction makeTxTablesAccessor(builder: TxPlanBuilder, prefix = \"\"): TxTables {\n const tablesProxy = new Proxy(\n {},\n {\n get(_t, prop: string | symbol) {\n if (typeof prop !== \"string\") return undefined;\n return builder.table(prefix + prop);\n },\n },\n );\n return tablesProxy as TxTables;\n}\n\n/**\n * Plan tutamağı — `Database` ile AYNI şekil: `tx.public.x`, `tx.<şema>.x`, ve\n * geriye dönük `tx.tables.x`.\n *\n * Şema adı tablo adının ÖNÜNE geçiyor (`billing.invoices`), tıpkı doğrudan\n * yüzeyin `makeTypedSurface` proxy'sinin yaptığı gibi — ve motor artık onu\n * `quoteTable` ile İKİ parça hâlinde tırnaklıyor. Bu ikisi olmadan `billing`\n * şemasındaki iki tabloyu tek atomik planda yazmak imkânsızdı.\n *\n * `tables` ve `public` DIŞINDAKİ HER ad şema kabul edilir ve altındaki tablolar\n * `<ad>.<tablo>` diye adlanır. Yanlış bir şema adı TİPTE yakalanıyor\n * (`keyof Schemas`) — `tx.constructor.x` ve `tx.toString.x` dahil, ölçüldü.\n *\n * TİPTEN KAÇAN bir ad için savunma `quoteTable`'ın KAÇIŞIDIR, başka bir şey\n * değil: `runPlanOp` `op.table`'ı doğrulamadan ona veriyor ve `quoteTable`\n * tırnak ikizleyerek tek bir tanımlayıcı üretiyor. Ölçüldü: `a\"; DROP TABLE t; --`\n * → `\"a\"\"; DROP TABLE t; --\"`, yani enjeksiyon değil, `relation does not exist`.\n * (Bu yorum bir zamanlar `validateSchemaIdentifier`'a atıf yapıyordu — o\n * fonksiyon Go tarafında yaşıyor ve BU yolu hiç görmüyor; gözcü yakaladı.)\n */\nfunction makeTxPlanHandle(builder: TxPlanBuilder): TxPlan {\n const publicTables = makeTxTablesAccessor(builder);\n return new Proxy(\n {},\n {\n get(_t, prop: string | symbol) {\n if (typeof prop !== \"string\") return undefined;\n if (prop === \"tables\") return publicTables;\n // ÖNEK TEK YAZICIDAN (FR-058): `qualifiedTableKey`. Bu kuralı burada\n // elle yazmıştım — public'i çıplak bırakıp diğerine nokta ekleyen bir\n // if/return çifti — ve FR-058 kapısı onu GÖRMEDİ, çünkü kapı yalnız\n // ternary arıyordu. (Kural burada KELİMEYLE anlatılıyor, kod biçiminde\n // DEĞİL: kapı metni tarıyor ve bir yorumdaki kopya da onu tetikler.)\n // İkinci bir yazıcı, kapının var olma sebebi olan sınıfın kendisi:\n // `env-gen.ts`'in kendi kopyası bir public FK'yi başka bir şemanın\n // tablosuna etiketlemişti ve hiçbir şey bunu söylememişti.\n // Boş tablo adıyla çağrılınca geriye ya \"\" (public) ya \"<şema>.\" kalır.\n return makeTxTablesAccessor(builder, qualifiedTableKey(prop, \"\"));\n },\n },\n ) as TxPlan;\n}\n\n/**\n * The project's own Postgres (pgx, schema `env_<envId>`).\n *\n * Typed by default: `Database.public.<name>.insert({...})` is typed against\n * the project's generated `palbase-env.d.ts` with NO import and NO generic.\n * The raw string ops (`Database.$query`/`$insert`/`$update`/`$delete`/\n * `$findById`/`$findMany`) are also available for read-only SQL and for a table\n * name only known at runtime — which the typed surface cannot express past\n * seven tables (see `db/tx-union-key.test-d.ts`).\n *\n * RLS is enforced by default (the runtime runs each op as `authenticated` with\n * the verified user's claims). To bypass RLS, call `Database.$asService()` —\n * explicit and greppable — which runs as the `service_role` (BYPASSRLS).\n *\n * @example\n * import { Database } from \"@palbase/backend\";\n *\n * const todo = await Database.public.todos.insert({ title: req.input.title });\n * todo.id; // string ✓\n * const rows = await Database.$query(\"SELECT id FROM todos WHERE done = $1\", [false]);\n * const all = await Database.$asService().public.todos.findMany({}); // RLS bypass\n */\nexport const Database: EnvTypedDatabase = Object.assign(makeTypedSurface(rawDatabase), {\n /**\n * Lazily resolve the runtime's service-role sibling on each call. We do NOT\n * cache it: `rawDatabase.asService()` reads the CURRENT request scope through\n * the runtime proxy, and the per-request runtime injects a service client\n * bound to that request's identity headers — caching would leak one request's\n * sibling into another concurrent request.\n */\n $asService(): EnvServiceDatabase {\n return makeTypedSurface(rawDatabase.asService());\n },\n}) as unknown as EnvTypedDatabase;\n\n/** Firestore-like document client (PalDocs). */\nexport const Documents: PalbaseDocsClient = makeServiceProxy(\"Documents\");\n\n/**\n * `buckets.<name>` — the storage twin of `Database.public.<name>`, and the same\n * mechanism: `config/storage.ts` generates a `Buckets` augmentation into\n * `palbase-env.d.ts`, so a bucket name is a property with no import and no\n * generic, and a typo is a compile error.\n *\n * The intermediate `.buckets` is there for the reason `.tables` is: bucket\n * names must not share a namespace with the client's own methods, or the day\n * somebody declares a bucket called `bucket` the surface breaks.\n */\nexport type EnvBuckets = {\n [K in keyof Buckets]: TypedBucketClient<Buckets[K] extends BucketTypes ? Buckets[K] : BucketTypes>;\n};\n\n/** One bucket, with its declared variant names in the type. */\nexport interface TypedBucketClient<B extends BucketTypes> extends Omit<PalbaseBucketClient, \"getPublicUrl\"> {\n /** The public URL for the object, or for one of THIS bucket's declared\n * renditions. A name the bucket does not declare is a compile error. */\n getPublicUrl(path: string, options?: { variant?: B[\"variants\"] }): string;\n}\n\nfunction makeBucketsAccessor(storage: () => PalbaseStorageClient): EnvBuckets {\n return new Proxy(\n {},\n {\n get(_t, prop: string | symbol) {\n if (typeof prop !== \"string\") return undefined;\n return storage().bucket(prop);\n },\n },\n ) as EnvBuckets;\n}\n\nconst rawStorage: PalbaseStorageClient = makeServiceProxy(\"Storage\");\n\n/**\n * Object storage: buckets, objects, renditions and signed URLs.\n *\n * `Storage.buckets.posts.upload(...)` is the typed path. `Storage.bucket(name)`\n * remains for a name computed at runtime — rare, and it gives up the typing,\n * which is the honest trade rather than a second blessed way to do it.\n */\nexport const Storage: PalbaseStorageClient & { buckets: EnvBuckets } = Object.assign(\n {\n // FORWARDED explicitly, not assigned onto the service proxy.\n //\n // `Object.assign(rawStorage, {buckets})` writes onto the proxy's TARGET, and\n // the proxy's only trap is `get`, which forwards every read to the module\n // client — so the property landed somewhere nothing reads and\n // `Storage.buckets.docs` was `undefined` in a deployed handler. It\n // typechecked, every test passed, and the live call answered\n // \"TypeError: undefined is not an object\". `Database` never had the bug\n // because it builds a plain surface the same way this now does.\n bucket: (name: string) => rawStorage.bucket(name),\n },\n { buckets: makeBucketsAccessor(() => rawStorage) },\n);\n\n/** JSON-typed cache (get/set/incr/getOrSet). */\nexport const Cache: CacheClient = makeServiceProxy(\"Cache\");\n\n\n/**\n * This tenant's secrets — API keys, provider credentials, signing material the\n * BACKEND owns.\n *\n * `await Secrets.get(\"STRIPE_KEY\")` in a handler. There is no `.env` to read\n * and no file to mount: a secret is written through the vault's authenticated\n * API (or the CLI/MCP that calls it), and this is how the deployed code reads\n * it back. A name this tenant has not set answers null — as does every name\n * the STACK holds, because no route returns a platform secret's value at all.\n */\nexport const Secrets: SecretsService = makeServiceProxy(\"Secrets\");\n\n/**\n * Role assignment, as an operator — `Auth.assignRole(userId, \"agent\")`.\n *\n * The half of auth a SERVER owns. Signing in, MFA and device attestation are a\n * person acting on their own account and live on the client SDK; granting a\n * role is the tenant's product doing something to somebody else, which is\n * exactly what a handler is for. It writes with the service-role credential,\n * because an end user who could write their own assignment would make every\n * permission underneath it meaningless.\n *\n * The write is visible to the very next request: authority is read from the\n * table on each call, never carried on a token.\n */\nexport const Auth: PalbaseAuthAdminClient = makeServiceProxy(\"Auth\");\n\n/** Structured logger. */\nexport const Log: Logger = makeServiceProxy(\"Log\");\n\n/** Push / email / SMS / in-app notifications. */\nexport const Notifications: PalbaseNotificationsClient = makeServiceProxy(\"Notifications\");\n\n\n/**\n * The raw runtime Flags client for the current request scope. Carries the\n * default-surface reads + `setOverride` AND the runtime's `asService()` sibling\n * (the br-pod's `buildFlagsClient` returns both). The default `Flags` singleton\n * below forwards reads + `setOverride` through here; `Flags.$asService()`\n * forwards to this client's own `asService()`.\n */\nconst rawFlags: PalbaseFlagsClient = makeServiceProxy(\"Flags\");\n\n/**\n * Feature flags.\n *\n * Mirrors the `Database` / `Database.$asService()` model. The default surface is\n * RLS-equivalent for flags: reads resolve against the CURRENT request user and\n * `Flags.setOverride(key, value)` writes an override for that same signed-in\n * user (no userId argument, no admin power). Cross-user admin writes\n * (`setOverrideForUser`, …) live behind `Flags.$asService()` — explicit and\n * greppable, just like `Database.$asService()`.\n *\n * @example\n * import { Flags } from \"@palbase/backend\";\n *\n * if (await Flags.isEnabled(\"new_checkout\")) { ... } // current user\n * await Flags.setOverride(\"new_checkout\", true); // current user\n * await Flags.$asService().setOverrideForUser(\"u_9\", \"x\", true); // cross-user\n */\n/**\n * The ambient `Flags` singleton's own surface — NOT the raw client's.\n *\n * MEASURED, as a consumer, against the built tarball: annotating the singleton\n * as `PalbaseFlagsClient` ERASED the `$asService` that `Object.assign` adds, so\n * `Flags.$asService()` did not exist for anyone outside this package —\n *\n * TS2551: Property '$asService' does not exist on type 'PalbaseFlagsClient'.\n * Did you mean 'asService'?\n *\n * — while the only path that DID compile (`asService()`) throws by design. The\n * feature was written and unreachable, which is the defect class this surface\n * exists to remove.\n *\n * `Database` never had the problem because its singleton carries its OWN type\n * (`EnvTypedDatabase`) rather than the raw client's (`DBClient`). This is that,\n * for `Flags`. The raw `PalbaseFlagsClient.asService()` is untouched (FR-023) —\n * it is the seam this forwards to.\n */\nexport type PalbaseFlagsAmbient = Omit<PalbaseFlagsClient, \"asService\"> & {\n /** RLS'i aşan, kullanıcılar arası yazma yüzeyi. */\n $asService(): PalbaseFlagsServiceClient;\n /** 31.0.0 öncesinin adı — SESSİZCE çalışmaz, yerini söyleyerek fırlatır. */\n asService(): never;\n};\n\nexport const Flags: PalbaseFlagsAmbient = Object.assign(\n {\n isEnabled(\n flagName: PalbaseFlagKey,\n context?: PalbaseFlagContext,\n ): Promise<PalbaseResult<boolean>> {\n return rawFlags.isEnabled(flagName, context);\n },\n getVariant(\n flagName: PalbaseFlagKey,\n context?: PalbaseFlagContext,\n ): Promise<PalbaseResult<PalbaseFlagVariant>> {\n return rawFlags.getVariant(flagName, context);\n },\n getAll(context?: PalbaseFlagContext): Promise<PalbaseResult<PalbaseFlag[]>> {\n return rawFlags.getAll(context);\n },\n /**\n * Resolve a flag's value, with an optional fallback.\n *\n * FORWARDED as of 2026-08-15. This surface is written out by hand, method\n * by method, and `get` was missing from it — so the client implemented it,\n * thirty assertions covered it, and `Flags.get(\"x\")` was `undefined` in a\n * deployed handler. Exactly the shape of the `Storage.buckets` defect found\n * the same day: a hand-maintained forwarding list is a list somebody has to\n * remember to update.\n */\n get(\n flagName: PalbaseFlagKey,\n defaultOrContext?: PalbaseFlagValue | PalbaseFlagContext,\n maybeContext?: PalbaseFlagContext,\n ): Promise<PalbaseResult<PalbaseFlagValue>> {\n return rawFlags.get(flagName, defaultOrContext, maybeContext);\n },\n setOverride(\n key: PalbaseFlagKey,\n value: PalbaseFlagValue,\n ): Promise<PalbaseResult<PalbaseSetOverrideResult>> {\n return rawFlags.setOverride(key, value);\n },\n },\n {\n /**\n * Lazily resolve the runtime's cross-user sibling on each call. We do NOT\n * cache it: `rawFlags.asService()` reads the CURRENT request scope through\n * the runtime proxy, so caching would leak one request's sibling into\n * another concurrent request. Mirrors `Database.$asService()`.\n */\n $asService(): PalbaseFlagsServiceClient {\n return rawFlags.asService();\n },\n /**\n * The name this member carried before 32.0.0.\n *\n * It does NOT work silently. A retired member that quietly keeps returning\n * is how a rename becomes a mystery: the old call site goes on compiling,\n * the new name never spreads, and the two live side by side until somebody\n * greps for one and misses half the codebase. `Database` made this split\n * first (`$asService`), and this JSDoc promised \"exactly like\n * Database.$asService()\" while the promise went unkept.\n */\n asService(): never {\n throw new Error(\n \"Flags.asService() was renamed to Flags.$asService() in 32.0.0 — system members carry the `$` prefix, like Database.$asService().\",\n );\n },\n },\n);\n\n/**\n * The Realtime broadcast singleton for the current request scope. Backend-side\n * Realtime is BROADCAST-ONLY (a stateless handler can push but not subscribe —\n * `subscribe()` lives on the client SDK's `pb.realtime`). Fire-and-forget:\n * `broadcast` resolves once accepted (or with an `error`), never blocking the\n * handler on subscribers.\n *\n * @example\n * import { Realtime } from \"@palbase/backend\";\n *\n * await Realtime.broadcast(\"room:42\", \"message\", { text, from: user.id });\n */\nexport const Realtime: PalbaseRealtimeClient = makeServiceProxy(\"Realtime\");\n","/** A PostgreSQL isolation level supported by the explicit root transaction. */\nexport type TransactionIsolation = \"read committed\" | \"repeatable read\" | \"serializable\";\n\nexport interface AtomicOptions {\n /** Each retry opens a fresh transaction and reruns the complete callback.\n * Defaults to zero. Keep external effects outside it; persist an outbox instead. */\n retry?: number;\n isolation?: TransactionIsolation;\n readOnly?: boolean;\n /** Maximum wait for a PostgreSQL lock. Defaults to 5000 ms. */\n lockTimeoutMs?: number;\n /** PostgreSQL statement timeout; applies to every statement in this scope. */\n statementTimeoutMs?: number;\n /** Total work deadline including queueing and retries. Active Bun queries are\n * cancelled; rollback settles before release. An in-flight COMMIT is awaited. */\n timeoutMs?: number;\n signal?: AbortSignal;\n\n}\n\nexport function retryBudget(value: number | undefined): number {\n const n = value ?? 0;\n if (!Number.isInteger(n) || n < 0 || n > 10) {\n throw new Error(\"transaction retry must be an integer between 0 and 10\");\n }\n return n;\n}\n\nexport function validateAtomicOptions(options: AtomicOptions): void {\n retryBudget(options.retry);\n if (options.isolation !== undefined && ![\"read committed\", \"repeatable read\", \"serializable\"].includes(options.isolation)) {\n throw new Error(\"transaction isolation must be read committed, repeatable read or serializable\");\n }\n if (options.readOnly !== undefined && typeof options.readOnly !== \"boolean\") {\n throw new Error(\"transaction readOnly must be a boolean\");\n }\n for (const name of [\"lockTimeoutMs\", \"statementTimeoutMs\", \"timeoutMs\"] as const) {\n const n = options[name];\n if (n !== undefined && (!Number.isInteger(n) || n < 1 || n > 2_147_483_647)) {\n throw new Error(`transaction ${name} must be a positive integer in milliseconds`);\n }\n }\n if (options.signal !== undefined && (typeof options.signal.aborted !== \"boolean\" || typeof options.signal.addEventListener !== \"function\")) {\n throw new Error(\"transaction signal must be an AbortSignal\");\n }\n}\n\n/** A savepoint cannot replace the enclosing transaction's snapshot or retry COMMIT. */\nexport function assertPlanRetry(options: { retry?: number } | undefined): void {\n if (retryBudget(options?.retry) !== 0) {\n throw new Error(\n \"Database.$transaction is a savepoint plan on the request transaction and cannot retry its snapshot or COMMIT. \" +\n \"Use Database.$atomic(async tx => { ... }, { retry, isolation }) and put all decision reads and writes inside that callback.\",\n );\n }\n}\n","// The wire shape of a declared schema — what the deploy reads.\n//\n// `defineSchema(...)` produces a value full of builders and phantom types, which\n// is the right shape for authoring and the wrong shape for anything outside this\n// process. The deploy is Go: it introspects the live database, diffs it against\n// the declaration, and applies the difference. So the declaration has to leave\n// TypeScript as data, and this file is where that happens.\n//\n// It lives in the SDK because the SDK owns the DSL. The alternative — a script\n// beside the deploy that reaches into `._def` — is a second reading of a private\n// shape, and it drifts the moment a column gains a property: the DSL keeps\n// working, the emitter silently omits it, and the database is missing something\n// nobody can see in the source.\n//\n// The field names below are a CONTRACT with Go's `schema.SchemaJSON`. Renaming\n// one here without renaming it there produces a declaration that parses to\n// something emptier than it was — the failure mode being a column, a policy, or\n// a whole table that quietly never gets created.\n// Politika ifadesinin tel şekli `policy.ts`'te TEK kez bildiriliyor. İki kopya\n// olsaydı biri `exists` düğümünü alır, diğeri almaz ve fark ancak Go tarafı\n// bilmediği bir `kind` gördüğünde ortaya çıkardı.\nimport type { PolicyExpr as PolicyExprJSON } from \"./policy.js\";\nexport type { PolicyExpr as PolicyExprJSON } from \"./policy.js\";\nimport type { ColumnBuilder, ColumnDef } from \"./columns.js\";\nimport type { PolicyDef } from \"./policy.js\";\nimport type { MemoryDecl, SchemaDef, SearchDecl, TableDef } from \"./schema.js\";\n\n/** One column, flattened. Mirrors Go's `schema.ColumnJSON`. */\nexport interface ColumnJSON {\n type: string;\n nullable: boolean;\n primaryKey: boolean;\n defaultValue?: unknown;\n defaultRandom?: boolean;\n defaultNow?: boolean;\n renamedFrom?: string;\n /** See Go's `schema.ColumnJSON.Ignored` — the contraction gate's only signal. */\n ignored?: boolean;\n owns?: boolean;\n references?: { table: string; column: string };\n onDeleteAction?: string;\n /** FR-044: türev FK index'i kapatılmışsa `false`. Bildirilmemişse alan YOK. */\n index?: boolean;\n /** FR-049: kolon increment() ile güncelleniyorsa `true`. Aksi hâlde alan YOK. */\n counter?: boolean;\n enumName?: string;\n enumValues?: string[];\n unique?: boolean;\n dimensions?: number;\n}\n\n/** One RLS policy. Mirrors Go's `schema.PolicyJSON`. */\nexport interface PolicyJSON {\n name: string;\n command: string;\n roles: string[];\n /**\n * `USING (...)` — ham string (kaçış kapağı, FR-028) ya da YAPI (FR-022).\n *\n * Go tarafı ikisini de okur: string olan verbatim emit edilir, yapı olan\n * `generator.go`'da SQL'e çevrilir (C-6). Yapı hâli InitPlan sarmalamasını\n * ve `TO <rol>` daraltmasını GÜVENLE yapılabilir kılan şey — string üstünde\n * regex'le denemek yorum içindeki bir `auth.uid()`'yi de sarmalardı.\n */\n using: string | PolicyExprJSON | null;\n withCheck: string | PolicyExprJSON | null;\n permissive: boolean;\n}\n\n\n/** One table. Mirrors Go's `schema.TableJSON`. */\nexport interface TableJSON {\n /**\n * The schema this table lives in. `public` unless declared otherwise.\n *\n * The table carries it because the diff iterates over KEYS but passes the\n * VALUE around: a bare name inside a qualified key space writes the migration\n * into the wrong schema, silently.\n */\n schema: string;\n name: string;\n columns: Record<string, ColumnJSON>;\n rls: boolean;\n policies: PolicyJSON[];\n primaryKey?: string[];\n uniqueConstraints?: { name: string; columns: string[] }[];\n rawConstraints?: { name: string; up: string }[];\n checks?: { name: string; expr: string }[];\n indexes?: IndexJSON[];\n /** Canlıdan düşürülecek constraint adları (FR-008). Sıfır değerde OMIT. */\n dropConstraints?: string[];\n /** Tablo düzeyi çok sütunlu FOREIGN KEY'ler (FR-001). Sıfır değerde OMIT. */\n foreignKeys?: ForeignKeyJSON[];\n /** Koşullu FK'lar — donan demetler (FR-012). Sıfır değerde OMIT. */\n freeze?: FreezeJSON[];\n /** Guard'lar — bildirimsel kısıtın yetişemediği yazma redleri (FR-015). Sıfır değerde OMIT. */\n guards?: GuardJSON[];\n /** Bir kez koşacak veri düzeltmeleri (FR-033). Sıfır değerde OMIT. */\n backfills?: BackfillJSON[];\n /**\n * appendOnly (FR-030): tablo yalnız INSERT kabul eder. Sıfır değerde OMIT —\n * bildirmeyen tablolar wire'da bayt-aynı kalır.\n */\n appendOnly?: boolean;\n search?: SearchJSON;\n memory?: MemoryJSON;\n}\n\n/**\n * Bir index'in wire şekli — Go'nun `IndexJSON`'ıyla ALAN-ADI SÖZLEŞMESİ.\n *\n * `name` + `columns` bugünkü hâl; kalanı FR-041…043'ün taşıyıcısı. Hepsi sıfır\n * değerde OMIT edilir: bildirmeyen bir index wire'da eskisiyle bayt-aynı kalır,\n * yoksa dokunulmamış her şema diff'te değişmiş görünür ve her deploy churn üretir.\n */\nexport interface IndexJSON {\n name: string;\n /** `CREATE UNIQUE INDEX` (FR-007). Sıfır değerde OMIT. */\n unique?: boolean;\n columns: string[];\n /** Partial index koşulu (FR-042) — filtre şekli `WhereFilter` ile aynı. */\n where?: unknown;\n /** İfade index'i (FR-043), ör. `lower(email)`. `columns` ile birlikte kullanılmaz. */\n expression?: string;\n /** Kolon sırası (FR-043). */\n sort?: \"asc\" | \"desc\";\n /** NULL sırası (FR-043). */\n nulls?: \"first\" | \"last\";\n /** Covering index — `INCLUDE (...)` (FR-043). */\n include?: string[];\n}\n\n/**\n * Tablo düzeyi çok sütunlu FOREIGN KEY'in wire şekli — Go'nun `ForeignKeyJSON`'ı\n * ile ALAN-ADI SÖZLEŞMESİ (FR-001). Bir ad değişirse wire sessizce kopar.\n *\n * `onUpdate`/`onDelete`/`match` sıfır değerinde OMIT: bildirmeyen bir FK\n * Postgres'in varsayılanını (NO ACTION / MATCH SIMPLE) alır ve telde yer\n * kaplamaz (NFR-006).\n */\nexport interface ForeignKeyJSON {\n name: string;\n columns: string[];\n refTable: string;\n refColumns: string[];\n onUpdate?: string;\n onDelete?: string;\n match?: string;\n}\n\n/**\n * Koşullu FK'nın (\"donan demet\") wire şekli — Go'nun `FreezeJSON`'ı ile\n * ALAN-ADI SÖZLEŞMESİ (C-8, FR-012).\n *\n * `when` politika ifade yapısının ta kendisi — `IndexJSON.where` ile aynı\n * duruş: üçüncü bir yüklem lehçesi açmak, aynı sorunun iki yazımı demekti.\n * Alanların hiçbiri opsiyonel değil: bir freeze'in koşulu, donan sütunları ve\n * hedefi olmadan anlamı yok ve `toFreezeDef` bunları bildirim anında şart\n * koşuyor. Sıfır değerde OMIT edilen şey DİZİNİN KENDİSİ (`TableJSON.freeze`).\n */\nexport interface FreezeJSON {\n name: string;\n when: unknown;\n columns: string[];\n refTable: string;\n refColumns: string[];\n}\n\n/**\n * Bir guard'ın wire şekli — Go'nun `GuardJSON`'ı ile ALAN-ADI SÖZLEŞMESİ\n * (C-4/C-8, FR-015).\n *\n * `when` ile `exists` AYRI alanlar: Postgres bir trigger'ın `WHEN` yan\n * tümcesinde alt sorguya izin vermiyor (`cannot use subquery in trigger WHEN\n * condition`), yani çapraz satır yüklemi gövdedeki `EXISTS` bloğuna inmek\n * zorunda (FR-019). Ayrımı emitter'ın yükleme bakıp tahmin etmesi yerine wire'da\n * taşımak, o kuralı bildirimin kendi şekline yazar.\n *\n * `detail`/`hint`/`column` sıfır değerde OMIT — bildirmeyen bir guard telde yer\n * kaplamaz (NFR-006). `message` her zaman var: reddin kullanıcıya ulaşan tek\n * çıktısı o.\n */\nexport interface GuardJSON {\n name: string;\n event: string;\n when?: unknown;\n exists?: unknown;\n message: string;\n detail?: string;\n hint?: string;\n column?: string;\n}\n\n/**\n * Bir backfill'in wire şekli — Go'nun `BackfillJSON`'ı ile ALAN-ADI SÖZLEŞMESİ\n * (C-8, FR-033).\n *\n * `name` kimliğin TAMAMI: \"koştu mu\" sorusu ona göre cevaplanıyor, `sql`'e göre\n * değil. Aynı adın altında değişen bir gövde ikinci bir koşu üretmez.\n */\nexport interface BackfillJSON {\n name: string;\n sql: string;\n}\n\n/** C-11 wire şekli — Go'nun MemoryJSON'ıyla alan-adı sözleşmesi (D-019).\n * Beyansız tablolarda alan OMIT — eski şemalar bayt-aynı (NFR-B1). */\nexport interface MemoryJSON {\n from: string[];\n into: string;\n subject?: string;\n extract: { provider: string; model: string };\n}\n\n/** A whole declaration. Mirrors Go's `schema.SchemaJSON`. */\nexport interface SchemaJSON {\n tables: Record<string, TableJSON>;\n extensions: string[];\n /**\n * Every declared schema, with its HTTP reachability.\n *\n * The flag has nowhere else to live: `/v1/db` must know which schemas are\n * reachable, and introspection must know which schemas the project DECLARED —\n * a live database also contains internal module schemas that are none of the\n * diff's business.\n */\n schemas: SchemaMetaJSON[];\n}\n\nexport interface SchemaMetaJSON {\n name: string;\n exposed: boolean;\n}\n\n/** The definition behind a column, whichever side of the builder it arrives on. */\nfunction defOf(column: ColumnBuilder | ColumnDef): ColumnDef {\n return \"_def\" in column ? column._def : column;\n}\n\nfunction columnToJSON(column: ColumnBuilder | ColumnDef): ColumnJSON {\n const def = defOf(column);\n const out: ColumnJSON = {\n type: def.type,\n nullable: def.nullable,\n primaryKey: def.primaryKey,\n };\n // Every optional field is omitted rather than emitted as undefined: Go\n // distinguishes \"absent\" from \"present and empty\" on several of these, and a\n // `defaultValue: null` is a real default that says NULL.\n if (def.defaultValue !== undefined) out.defaultValue = def.defaultValue;\n if (def.defaultRandom === true) out.defaultRandom = true;\n if (def.defaultNow === true) out.defaultNow = true;\n if (def.renamedFrom !== undefined) out.renamedFrom = def.renamedFrom;\n // Go'daki schema.ColumnJSON'un aynası. `omitempty` karşılığı: yalnız TRUE ise yazılır,\n // böylece işaretsiz bir şemanın JSON'u bu alandan önceki hâliyle byte-eş kalır.\n if (def.ignored === true) out.ignored = true;\n // OWNERSHIP HAS TO CROSS THE WIRE, because the gate that enforces it is on the\n // other side. `ownedByUser()` sets `owns` on the column, and Go's\n // `validateOwnership` reads `ColumnJSON.Owns` to refuse a table that declares\n // two owners — but nothing was carrying the flag between them.\n //\n // Measured on the live cluster: a table with TWO `ownedByUser()` columns\n // pushed clean and both foreign keys landed on `auth.users` ON DELETE CASCADE.\n // The rule existed in the DSL and in the generator; the wire in between said\n // nothing, so the generator saw ZERO ownership columns and had nothing to\n // refuse. A flag with a reader and no writer is a dead wire.\n if (def.owns === true) out.owns = true;\n if (def.references !== undefined) {\n out.references = { table: def.references.table, column: def.references.column };\n }\n if (def.onDeleteAction !== undefined) out.onDeleteAction = def.onDeleteAction;\n // Yalnız `false` taşınıyor: \"bildirilmedi\" ile \"açık\" aynı şey ve wire'a\n // yazmak bildirmeyen her kolonu diff'te değişmiş gösterirdi.\n if (def.index === false) out.index = false;\n if (def.counter === true) out.counter = true;\n if (def.enumName !== undefined) out.enumName = def.enumName;\n if (def.enumValues !== undefined) out.enumValues = [...def.enumValues];\n if (def.unique === true) out.unique = true;\n if (def.dimensions !== undefined) out.dimensions = def.dimensions;\n return out;\n}\n\nfunction policyToJSON(policy: PolicyDef): PolicyJSON {\n return {\n name: policy.name,\n command: policy.command ?? \"all\",\n roles: policy.roles ? [...policy.roles] : [],\n // null rather than omitted: a policy with no USING clause is a different\n // thing from one whose clause the emitter forgot, and Go reads the\n // difference.\n using: policy.using ?? null,\n withCheck: policy.withCheck ?? null,\n permissive: policy.permissive !== false,\n };\n}\n\n/** C-4 wire şekli — Go'nun SearchJSON'ıyla ALAN ADI sözleşmesi (C-5).\n * `mode`/`chunks` yalnız yeni-biçim chunk-modunda emit edilir (D-010);\n * satır-modu ve eski biçim bayt-aynı kalır (NFR-B1). */\nexport interface SearchJSON {\n text?: { columns: string[] };\n vector?: {\n column?: string;\n metric: string;\n embed?: { provider: string; model: string; from: string[]; apiKeyName?: string; dimensions?: number; baseURL?: string };\n staleness?: \"null\" | \"keep\";\n mode?: \"row\" | \"chunks\";\n chunks?: { sizeChars?: number; overlapChars?: number };\n }[];\n /** FR-026: sorgu-yeniden-yazımı haritası — beyan yoksa OMIT (NFR-B1). */\n synonyms?: Record<string, string[]>;\n /** C-1: sonuç yeniden-sıralama beyanı — beyan yoksa OMIT. */\n /** FR-029: geçerlilik türevleri — beyan yoksa OMIT. */\n validity?: boolean;\n}\n\n/** T020 (C-1): iki biçimin de üst-düzey ortak alanları — beyan yoksa OMIT,\n * boş synonyms haritası da OMIT (NFR-B1 baytları kımıldamaz). */\nfunction commonSearchFields(search: SearchDecl, out: SearchJSON): void {\n if (search.synonyms !== undefined && Object.keys(search.synonyms).length > 0) {\n out.synonyms = Object.fromEntries(\n Object.entries(search.synonyms).map(([word, alts]) => [word, [...alts]]),\n );\n }\n if (search.validity === true) out.validity = true;\n}\n\n/** Beyanı normalize eder: vector her zaman DİZİ, metric her zaman dolu (vars. cosine),\n * authoring'deki `from`/`model` wire'da `embed` altında toplanır. Alan yoksa OMIT —\n * search'süz şema bayt-aynı kalır (NFR-006). */\nfunction searchToJSON(search: SearchDecl, vectorColumn: string | undefined): SearchJSON {\n if (search.from !== undefined && search.model !== undefined) {\n // YENİ biçim (D-007): from tek listedir — FTS'i de embed'i de besler.\n // Mod ŞEMADAN türer (D-010): tabloda vector kolonu varsa satır-modu\n // (column yazılır, mode OMIT — eski davranışla aynı wire), yoksa\n // chunk-modu (mode:\"chunks\", column yok — vektörler türev tabloda).\n const out: SearchJSON = {};\n const textCols =\n search.text === false ? undefined : Array.isArray(search.text) && search.text.length > 0 ? search.text : search.from;\n if (textCols !== undefined) out.text = { columns: [...textCols] };\n const v: NonNullable<SearchJSON[\"vector\"]>[number] = { metric: search.metric ?? \"cosine\" };\n if (vectorColumn !== undefined) v.column = vectorColumn;\n v.embed = {\n provider: search.model.provider,\n model: search.model.model,\n from: [...search.from],\n ...(search.model.apiKeyName !== undefined ? { apiKeyName: search.model.apiKeyName } : {}),\n ...(search.model.dimensions !== undefined ? { dimensions: search.model.dimensions } : {}),\n ...(search.model.baseURL !== undefined ? { baseURL: search.model.baseURL } : {}),\n };\n if (search.staleness !== undefined) v.staleness = search.staleness;\n if (vectorColumn === undefined) {\n v.mode = \"chunks\";\n if (search.chunks !== undefined) {\n const c: NonNullable<typeof v.chunks> = {};\n if (search.chunks.size !== undefined && search.chunks.size > 0) c.sizeChars = search.chunks.size;\n if (search.chunks.overlap !== undefined && search.chunks.overlap > 0) c.overlapChars = search.chunks.overlap;\n if (Object.keys(c).length > 0) v.chunks = c;\n }\n }\n out.vector = [v];\n commonSearchFields(search, out);\n return out;\n }\n const out: SearchJSON = {};\n // Eski biçimde text yalnız dizi olabilir (boolean'ı defineSchema zaten\n // reddediyor); Array.isArray hem tipi daraltır hem o sözleşmeyi belgeler.\n if (Array.isArray(search.text) && search.text.length > 0) out.text = { columns: [...search.text] };\n const legs = search.vector === undefined ? []\n : Array.isArray(search.vector) ? search.vector : [search.vector];\n if (legs.length > 0) {\n out.vector = legs.map((leg) => {\n const v: NonNullable<SearchJSON[\"vector\"]>[number] = { metric: leg.metric ?? \"cosine\" };\n if (leg.column !== undefined) v.column = leg.column;\n if (leg.staleness !== undefined) v.staleness = leg.staleness;\n if (leg.model !== undefined) {\n v.embed = {\n provider: leg.model.provider,\n model: leg.model.model,\n from: [...(leg.from ?? [])],\n ...(leg.model.apiKeyName !== undefined ? { apiKeyName: leg.model.apiKeyName } : {}),\n ...(leg.model.dimensions !== undefined ? { dimensions: leg.model.dimensions } : {}),\n ...(leg.model.baseURL !== undefined ? { baseURL: leg.model.baseURL } : {}),\n };\n }\n return v;\n });\n }\n commonSearchFields(search, out);\n return out;\n}\n\nfunction memoryToJSON(m: MemoryDecl): MemoryJSON {\n return {\n from: [...m.from],\n into: m.into,\n ...(m.subject !== undefined ? { subject: m.subject } : {}),\n extract: { provider: m.extract.provider, model: m.extract.model },\n };\n}\n\nfunction tableToJSON(table: TableDef, schemaName: string): TableJSON {\n const columns: Record<string, ColumnJSON> = {};\n for (const [name, column] of Object.entries(table.columns)) {\n columns[name] = columnToJSON(column);\n }\n\n const out: TableJSON = {\n name: table.name,\n schema: schemaName,\n columns,\n // Read, not re-derived. `defineSchema` already resolves the fail-closed\n // default (RLS on unless the author wrote `rls: false`, and forced on by any\n // policy), and a second copy of a SECURITY default is exactly the thing that\n // drifts — the direction it drifted last time was \"expose everything\", and\n // the live proof was one user reading another's rows.\n rls: table.rls,\n // KOŞAN SÜRÜMÜN SÖZÜ TELE ÇIKAR — yoksa daralma kapısı onu göremez.\n // `ColumnJSON.ignored` ile aynı sözleşme: işaretlenmemişse alan YOK.\n ...(table.ignored === true ? { ignored: true } : {}),\n policies: (table.policies ?? []).map(policyToJSON),\n };\n\n if (table.primaryKey !== undefined && table.primaryKey.length > 0) {\n out.primaryKey = [...table.primaryKey];\n }\n if (table.unique !== undefined && table.unique.length > 0) {\n out.uniqueConstraints = table.unique.map((u) => ({ name: u.name, columns: [...u.columns] }));\n }\n if (table.raw !== undefined && table.raw.length > 0) {\n out.rawConstraints = table.raw.map((r) => ({ name: r.name, up: r.up }));\n }\n if (table.checks !== undefined && table.checks.length > 0) {\n out.checks = table.checks.map((c) => ({ name: c.name, expr: c.expr }));\n }\n if (table.indexes !== undefined && table.indexes.length > 0) {\n out.indexes = table.indexes.map((i) => {\n // `columns` expression-index'te YOKTUR (ikisi birbirinin alternatifi).\n // Boş dizi ile taşınır: Go tarafı `expression` doluysa onu kullanır.\n const ix: IndexJSON = { name: i.name, columns: i.columns ? [...i.columns] : [] };\n if (i.unique === true) ix.unique = true;\n if (i.where !== undefined) ix.where = i.where;\n if (i.expression !== undefined) ix.expression = i.expression;\n if (i.sort !== undefined) ix.sort = i.sort;\n if (i.nulls !== undefined) ix.nulls = i.nulls;\n if (i.include !== undefined) ix.include = [...i.include];\n return ix;\n });\n }\n if (table.dropConstraints !== undefined && table.dropConstraints.length > 0) {\n out.dropConstraints = [...table.dropConstraints];\n }\n if (table.foreignKeys !== undefined && table.foreignKeys.length > 0) {\n out.foreignKeys = table.foreignKeys.map((fk) => {\n const j: ForeignKeyJSON = {\n name: fk.name,\n columns: [...fk.columns],\n refTable: fk.refTable,\n refColumns: [...fk.refColumns],\n };\n if (fk.onUpdate !== undefined) j.onUpdate = fk.onUpdate;\n if (fk.onDelete !== undefined) j.onDelete = fk.onDelete;\n if (fk.match !== undefined) j.match = fk.match;\n return j;\n });\n }\n if (table.freeze !== undefined && table.freeze.length > 0) {\n out.freeze = table.freeze.map((f) => ({\n name: f.name,\n when: f.when,\n columns: [...f.columns],\n refTable: f.refTable,\n refColumns: [...f.refColumns],\n }));\n }\n if (table.guards !== undefined && table.guards.length > 0) {\n out.guards = table.guards.map((g) => ({\n name: g.name,\n event: g.event,\n ...(g.when !== undefined ? { when: g.when } : {}),\n ...(g.exists !== undefined ? { exists: g.exists } : {}),\n message: g.message,\n ...(g.detail !== undefined ? { detail: g.detail } : {}),\n ...(g.hint !== undefined ? { hint: g.hint } : {}),\n ...(g.column !== undefined ? { column: g.column } : {}),\n }));\n }\n if (table.backfills !== undefined && table.backfills.length > 0) {\n out.backfills = table.backfills.map((b) => ({ name: b.name, sql: b.sql }));\n }\n // Sıfır değerde YAZILMAZ: `appendOnly: false` ile \"bildirilmemiş\" wire'da\n // ayırt edilemez olmalı, yoksa her eski şema diff'te değişmiş görünür.\n if (table.appendOnly === true) out.appendOnly = true;\n if (table.search !== undefined) {\n // D-010 mod kararının tek girdisi: tabloda dimensions'lı (vector) kolon\n // adı. Birden çoksa ilkini yazmak YANLIŞ olurdu — o durum eski biçimin\n // işidir ve yeni biçim + çoklu vector kolonu apply'da reddedilir.\n const vectorColumn = Object.entries(columns).find(([, c]) => c.dimensions !== undefined)?.[0];\n const sj = searchToJSON(table.search, vectorColumn);\n if (sj.text !== undefined || sj.vector !== undefined) out.search = sj;\n }\n if (table.memory !== undefined) {\n out.memory = memoryToJSON(table.memory);\n }\n return out;\n}\n\n/**\n * The key a table answers to in `SchemaJSON.tables`.\n *\n * A public table is BARE, anything else is schema-qualified. This is not a new\n * convention: `RefJSON.Table` already carries `auth.users`, and introspection\n * already returns a public referent bare and a non-public one qualified. Adding\n * a second key space would make two interpreters of the same database.\n */\nexport function qualifiedTableKey(schemaName: string, tableName: string): string {\n // An ABSENT schema means public, exactly as Go's `isPublicSchema` says. This\n // branch used to be missing here and present in the engine's private copy, so\n // the two writers of one rule answered DIFFERENTLY for `\"\"`: one qualified it\n // into a schema literally named the empty string, the other left it bare.\n return schemaName === \"\" || schemaName === \"public\" ? tableName : `${schemaName}.${tableName}`;\n}\n\n/**\n * Serialize declared schemas into the JSON the deploy applies.\n *\n * Takes every schema the project declares — one file per schema — because a\n * cross-schema foreign key can only be checked when both ends are in hand.\n */\nexport function toSchemaJSON(schemas: readonly SchemaDef[]): SchemaJSON {\n const tables: Record<string, TableJSON> = {};\n const extensions: string[] = [];\n const meta: SchemaMetaJSON[] = [];\n const seen = new Set<string>();\n for (const schema of schemas) {\n if (seen.has(schema.name)) {\n throw new Error(`two schemas declare the name \"${schema.name}\" — schema names must be unique`);\n }\n seen.add(schema.name);\n for (const table of Object.values(schema.tables)) {\n const json = tableToJSON(table, schema.name);\n tables[qualifiedTableKey(schema.name, json.name)] = json;\n }\n extensions.push(...(schema.extensions ?? []));\n // The schema list travels because the flag has nowhere else to live: without\n // it /v1/db cannot know which schemas are reachable over HTTP, and nothing\n // downstream can read the DECLARED schema set that introspection needs.\n meta.push({ name: schema.name, exposed: schema.exposed });\n }\n return { tables, extensions: [...new Set(extensions)], schemas: meta };\n}\n","/**\n * `fakeDatabase()` — the in-memory `Database` a SERVICE-LAYER test runs against.\n *\n * WHY IT IS PUBLIC. The scaffold's own AGENTS.md tells authors to \"test the\n * service layer… the test passes a stand-in\", and the SDK shipped no stand-in to\n * pass. So every project wrote its own: a measured customer run carried two — a\n * hand-written `MembershipDb` interface for one service, and a bare `{ query }`\n * object in the tests of another. Both are guesses at this SDK's own surface,\n * and both stop compiling the moment the surface grows.\n *\n * The engine already had exactly this object; it just lived under `__tests__/`\n * where only this package could reach it.\n *\n * WHAT IT IS NOT. It does not interpret SQL. `query()` records what it was asked\n * and answers no rows, because a fake that parsed SQL would be a second, worse\n * Postgres — and a test that passed against it would prove nothing about the\n * real one. Assert on `queries` when the SQL is the thing under test, and put\n * anything that depends on what SQL RETURNS in a live test (`palbase test`).\n */\nimport { createMockDB } from \"../__tests__/helpers/mock-db.js\";\nimport type { DBClient } from \"../endpoint.js\";\nimport { makeTypedSurface } from \"../runtime.js\";\nimport type { EnvServiceDatabase } from \"../db/typed-db.js\";\n\n/** One `Database.$query(...)` call, as the service made it. */\nexport interface RecordedQuery {\n sql: string;\n params: unknown[];\n}\n\n/** What a service-layer test is handed. */\nexport interface FakeDatabase {\n /** Pass this where the service expects `Database`.\n *\n * Built with the SAME constructor the production `Database` uses\n * (`makeTypedSurface`), so the fake's surface cannot drift from the real one\n * — including the `$`-prefixed raw ops and the typed `public` schema surface. */\n db: EnvServiceDatabase;\n /**\n * The RAW `DBClient` behind {@link FakeDatabase.db} (FR-028).\n *\n * `RuntimeServices.Database` is the raw client — the ambient `Database`\n * singleton is what WRAPS it with `makeTypedSurface`. So a test that installs\n * the fake as the ambient runtime passes THIS:\n *\n * withServices({ Database: fake.raw }, () => …)\n *\n * Passing `db` there would wrap an already-wrapped surface and every `$op`\n * would miss (measured). Two fields because there are two call sites: `db`\n * goes straight to a service, `raw` goes into the runtime.\n */\n raw: DBClient;\n /** Every `query()` call, in order. */\n queries: readonly RecordedQuery[];\n /** Put rows in a table before the code under test runs. */\n seed(table: string, rows: Record<string, unknown>[]): void;\n /** Rows inserted into a table, for asserting a write happened. */\n inserted(table: string): Record<string, unknown>[];\n /** Rows updated in a table. */\n updated(table: string): Record<string, unknown>[];\n /** Ids deleted from a table. */\n deleted(table: string): string[];\n}\n\nexport function fakeDatabase(): FakeDatabase {\n const mock = createMockDB();\n const queries: RecordedQuery[] = [];\n\n // The recorder wraps `query` and leaves every other op alone, so the fake's\n // behaviour is the engine's mock plus one observation.\n const db: DBClient = Object.assign(Object.create(Object.getPrototypeOf(mock) as object) as DBClient, mock, {\n query: async (sql: string, params: unknown[] = []) => {\n queries.push({ sql, params });\n return mock.query(sql, params);\n },\n });\n\n return {\n db: makeTypedSurface(db),\n raw: db,\n queries,\n seed: (table, rows) => mock.seed(table, rows),\n inserted: (table) => mock.inserted(table),\n updated: (table) => mock.updated(table),\n deleted: (table) => mock.deleted(table),\n };\n}\n","/**\n * `withServices()` — run code with only the platform services a test supplies.\n *\n * WHY IT IS PUBLIC. `isolated()` substitutes CONSTRUCTOR dependencies, and its\n * own documentation says why it cannot help here: \"platform services are\n * ambient rather than injected\". So the repository layer — the one place that\n * really does `import { Database } from \"@palbase/backend\"` — had no supported\n * way to be unit-tested, while `__runWithRuntime` demands EVERY service. A\n * measured consumer project wrote this helper by hand, exploding proxies\n * included, and 30.0.0 then added a tenth required service (`Auth`) which broke\n * that hand-written copy. Shipping it here is what stops that from recurring.\n *\n * WHAT IS ABSENT IS LOUD. An unsupplied service is neither `undefined` nor a\n * silent no-op: touching it throws and NAMES itself, so a test that quietly\n * grew a dependency on `Cache` fails saying \"Cache\", not \"cannot read\n * properties of undefined\".\n *\n * SCOPE IS THE REQUEST ALS, never the process-global slot. Two tests in one\n * file must not be able to see each other's services, and a helper that wrote\n * the global slot would leak the first test's fake into the second.\n *\n * EKSİKSİZLİK DERLEYİCİYE SORULUR, BİR LİSTEYE DEĞİL. İlk yazımı servis\n * adlarını bir diziye koyup `satisfies readonly (keyof RuntimeServices)[]` ile\n * pinliyordu — ama `satisfies` yalnız \"her ELEMAN bir anahtar mı\" diye bakar,\n * \"her ANAHTAR listede mi\" diye BAKMAZ. Ölçüldü: `RuntimeServices`'a on birinci\n * bir servis eklenip liste dokunulmadan bırakıldığında `tsc --strict` TEMİZ\n * derliyor, ve eksik servise erişen tüketici `TypeError: Reflect.get called on\n * non-object` alıyor — ne servisin adı, ne çaresi. Yani bu dosyanın var olma\n * sebebi olan kusurun ta kendisi, bu dosya tarafından üretiliyordu.\n *\n * Şimdi `filled` düz bir `RuntimeServices` nesne literali: bir alan eksik\n * kalırsa TypeScript `TS2741: Property '<ad>' is missing` diyor ve derleme\n * durur. `as unknown as` yok.\n */\nimport { __runWithRuntime, __requestALS, type RuntimeServices } from \"../runtime.js\";\n\n/**\n * A stand-in that refuses every read by NAME.\n *\n * The Proxy target is irrelevant (all access goes through `get`); the single\n * narrowing names the surface the caller expects — the same one-point cast\n * `makeServiceProxy` already uses for exactly this shape.\n */\nfunction absent<K extends keyof RuntimeServices>(name: K): RuntimeServices[K] {\n return new Proxy({} as RuntimeServices[K], {\n get(_target, prop) {\n throw new Error(\n `${String(name)}.${String(prop)} was read, but this test did not provide ${String(name)}. ` +\n `Pass it: withServices({ ${String(name)}: … }, () => …)`,\n );\n },\n });\n}\n\n/** The supplied service, or one that names itself when touched. */\nfunction pick<K extends keyof RuntimeServices>(\n services: Partial<RuntimeServices>,\n key: K,\n): RuntimeServices[K] {\n return services[key] ?? absent(key);\n}\n\nexport function withServices<T>(services: Partial<RuntimeServices>, fn: () => T): T {\n // Nesne LİTERALİ, üretilmiş bir kayıt değil: eksik bir alan burada derleme\n // hatasıdır (ölçüldü: TS2741), bir çalışma zamanı sürprizi değil.\n const filled: RuntimeServices = {\n Database: pick(services, \"Database\"),\n Auth: pick(services, \"Auth\"),\n Secrets: pick(services, \"Secrets\"),\n Documents: pick(services, \"Documents\"),\n Storage: pick(services, \"Storage\"),\n Cache: pick(services, \"Cache\"),\n Log: pick(services, \"Log\"),\n Notifications: pick(services, \"Notifications\"),\n Flags: pick(services, \"Flags\"),\n Realtime: pick(services, \"Realtime\"),\n };\n // `userId`'yi MOTORUN yazdığı gibi yaz. Motor `runWithRuntime`'ın hemen\n // ardından kutuya `userId ?? null` koyuyor ve `RequestStore`'un sözleşmesi\n // \"anonim istekte null\" diyor. Yalnız `{ runtime }` yazmak `undefined`\n // bırakırdı; `undefined` ile `null`'ı ayıran her dal testte bir yol,\n // üretimde başka bir yol koşardı — testin yeşilliği üretim hakkında yalan\n // söylerdi.\n return __requestALS.run({ runtime: filled, userId: null }, fn);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;ACAA,IAAMA,aAAa,CAAC;AACb,IAAMC,gBAAgBC,iBAAiBC,YAAYH,UAAAA;AAC1D,SAASE,iBAAiBE,SAASC,QAAM;AACrC,SAAO,IAAIC,MAAMF,SAAS;IACtBG,IAAIC,SAASC,MAAMC,WAAS;AACxB,UAA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C,UAAU,OAAA;IACtBc,UAAUf,KAAKC,UAAU,UAAA;EAC3B;AAOA,SAAOe,aAAaC,IAAI;IAAEC,SAASb;IAAQc,QAAQ;EAAK,GAAGf,EAAAA;AAC7D;AAtBgBD;","names":["dntGlobals","dntGlobalThis","createMergeProxy","globalThis","baseObj","extObj","Proxy","get","_target","prop","_receiver","set","value","deleteProperty","success","ownKeys","baseKeys","Reflect","extKeys","extKeysSet","Set","filter","k","has","defineProperty","desc","getOwnPropertyDescriptor","N_0","EC_P_521_PARAMS","p","b","gx","gy","coordinateSize","isBytes","a","Uint8Array","ArrayBuffer","isView","name","anumber","n","title","Number","isSafeInteger","prefix","Error","abytes","value","length","bytes","len","needsLen","undefined","ofLen","got","aexists","instance","checkFinished","destroyed","finished","aoutput","out","min","outputLen","u32","arr","Uint32Array","buffer","byteOffset","Math","floor","byteLength","clean","arrays","i","length","fill","_endianTestBuffer","_endianTestBytes","Uint8Array","isLE","createView","arr","DataView","buffer","byteOffset","byteLength","numberToBigint","num","anumber","n","out","N_0","bit","Math","floor","copyBytes","bytes","Uint8Array","from","ahash","h","create","Error","anumber","outputLen","blockLen","_HMAC","hash","key","Object","defineProperty","enumerable","configurable","writable","value","ahash","abytes","undefined","iHash","create","update","Error","blockLen","outputLen","pad","Uint8Array","set","length","digest","i","oHash","clean","buf","aexists","digestInto","out","finished","destroy","_cloneInto","to","getPrototypeOf","destroyed","clone","hmac","message","U32_MASK64","_32n","fromBig","n","le","h","Number","l","split","lst","len","length","Ah","Uint32Array","Al","i","_0n","_1n","_2n","_7n","_256n","_0x71n","SHA3_PI","SHA3_ROTL","_SHA3_IOTA","round","R","x","y","push","t","j","BigInt","IOTAS","split","SHA3_IOTA_H","SHA3_IOTA_L","abool","b","Error","wrapCipher","params","constructor","wrappedCipher","key","args","abytes","undefined","isLE","Error","nonceLength","nonce","varSizeNonce","tagl","tagLength","cipher","checkOutput","fnLength","output","called","wrCipher","encrypt","data","length","decrypt","Object","assign","checkOpts","defaults","opts","merged","equalBytes","a","b","diff","i","getOutput","expectedLength","out","onlyAligned","Uint8Array","isAligned32","u64Lengths","dataLength","aadLength","abool","num","view","createView","setBigUint64","numberToBigint","bytes","byteOffset","_utf8ToBytes","str","Uint8Array","from","split","map","c","charCodeAt","sigma16","sigma32","sigma16_32","u32","sigma32_32","rotl","a","b","isAligned32","byteOffset","BLOCK_LEN","BLOCK_LEN32","MAX_COUNTER","U32_EMPTY","Uint32Array","of","runCipher","core","sigma","key","nonce","data","output","counter","rounds","len","length","block","b32","isAligned","d32","o32","pos","Error","take","Math","min","pos32","j","posj","createCipher","opts","allowShortKeys","extendNonceFn","counterLength","counterRight","checkOpts","anumber","abool","abytes","undefined","toClean","l","k","push","copyBytes","set","k32","subarray","nonceNcLen","nc","n32","clean","u8to16","a","i","Poly1305","key","Object","defineProperty","enumerable","configurable","writable","value","Uint8Array","Uint16Array","copyBytes","abytes","t0","t1","t2","t3","t4","t5","t6","t7","r","pad","process","data","offset","isLast","hibit","h","r0","r1","r2","r3","r4","r5","r6","r7","r8","r9","h0","h1","h2","h3","h4","h5","h6","h7","h8","h9","c","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","finalize","g","mask","f","clean","update","aexists","buffer","blockLen","len","length","pos","take","Math","min","set","subarray","destroy","digestInto","out","aoutput","finished","opos","digest","outputLen","res","slice","wrapConstructorWithKey","hashCons","hashC","msg","tmp","create","poly1305","chachaCore","s","k","n","out","cnt","rounds","y00","y01","y02","y03","y04","y05","y06","y07","y08","y09","y10","y11","y12","y13","y14","y15","x00","x01","x02","x03","x04","x05","x06","x07","x08","x09","x10","x11","x12","x13","x14","x15","r","rotl","oi","chacha20","createCipher","counterRight","counterLength","allowShortKeys","ZEROS16","Uint8Array","updatePadded","h","msg","update","leftover","length","subarray","ZEROS32","computeTag","fn","key","nonce","ciphertext","AAD","undefined","abytes","authKey","lengths","u64Lengths","poly1305","create","res","digest","clean","_poly1305_aead","xorStream","tagLength","encrypt","plaintext","output","plength","getOutput","set","oPlain","tag","decrypt","data","passedTag","equalBytes","Error","chacha20poly1305","wrapCipher","blockSize","nonceLength","LABEL_SEC","Uint8Array","_Mutex_locked","_Mutex_locked","WeakMap","_RecipientContextImpl_mutex","_RecipientContextImpl_mutex","WeakMap","_SenderContextImpl_mutex","_SenderContextImpl_mutex","WeakMap","LABEL_BASE_NONCE","Uint8Array","LABEL_EXP","LABEL_INFO_HASH","LABEL_KEY","LABEL_PSK_ID_HASH","LABEL_SECRET","SUITE_ID_HEADER_HPKE","PKCS8_ALG_ID_X25519","Uint8Array","PKCS8_ALG_ID_X448","Uint8Array","runtime","mod","encoder","encoder","TestApiError","Error","status","error","data","body","method","path","envelope","code","String","error_description","name","required","value","envName","isLocalTarget","baseUrl","hostname","URL","secondsUntilExpiry","token","split","claims","JSON","parse","Buffer","from","toString","exp","Math","floor","Date","now","createTestApi","config","replace","apiKey","local","candidateToken","doFetch","fetch","requests","bearer","call","opts","headers","apikey","authorization","undefined","startedAt","res","stringify","text","parsed","safeParse","push","ms","ok","left","abs","get","post","patch","put","delete","query","signInAs","identity","identities","declared","Object","keys","length","join","accessToken","id","email","signIn","credentials","attempt","extra","result","e","refusal","challenge","asPowChallenge","solvePowChallenge","access_token","user","signOut","asAnonymous","parseIdentities","raw","configured","api","Proxy","_target","prop","process","env","PALBASE_TEST_BASE_URL","PALBASE_TEST_API_KEY","PALBASE_TEST_CANDIDATE","PALBASE_TEST_IDENTITIES","Reflect","isolated","over","Map","local","make","c","has","get","hit","undefined","meta","Reflect","getMetadata","inst","map","d","set","api","with","t","v","validateInsertManyOptions","opts","returning","undefined","Error","action","onConflict","Array","isArray","some","c","length","REF_BRAND","Symbol","for","brandRef","v","kind","Object","defineProperty","value","enumerable","brandOf","undefined","hasOwn","isColRef","v","brandOf","$col","isSqlFragment","v","brandOf","f","$sql","undefined","Array","isArray","text","values","TX_EXPR","Symbol","for","isNowExpr","isColumnExpr","e","fn","assertNoExpressionHandles","caller","table","cols","data","c","Error","isColRef","KNOWN_OPS","Set","REFUSED_OPS","eq","assertUsableFilter","where","COMPOSITES","col","cond","Object","entries","has","branches","b","rel","inner","length","op","some","x","assertUsableWriteValues","TxRefError","Error","message","name","TxPlanError","EXPR","Symbol","for","REF","ROW","ROWS","TRAPPED_PROPS","toPrimitive","trap","prop","what","hint","description","String","columnExprOf","v","exprOf","makeRef","op","field","target","REF","Proxy","get","t","prop","TRAPPED_PROPS","includes","trap","undefined","makeRowHandle","ROW","refDescriptor","v","d","isRefDescriptor","rowOpIndex","exprOf","e","EXPR","isRowsHandle","ROWS","encodeValue","value","column","allowColumnExpr","ref","brandRef","$ref","isNowExpr","$expr","fn","expr","TxPlanError","assertNoNestedHandles","encodeFilterValue","Array","isArray","map","Date","isColRef","isSqlFragment","out","k","Object","entries","encodeFilterMap","key","keys","sort","item","values","encodeMap","SKIPPED_OP","TxRowsImpl","guarded","builder","opIndex","what","then","TxRefError","expectOne","error","declareGuard","expectNone","expectAtLeast","n","assertGuardCount","expectAtMost","kind","Error","attachGuard","Number","isInteger","String","MAX_OPS","MAX_ROWS","TxPlanBuilder","ops","slots","table","name","insert","encoded","length","push","put","options","onConflict","insertMany","rows","opts","row","assertUniformRows","action","updateWhere","where","set","encodedWhere","encodedSet","deleteWhere","select","limit","lock","index","slot","guard","body","errorForSlot","first","want","wantKey","join","i","got","materializeResult","results","rowOf","rowOp","isPlainObject","result","proto","getPrototypeOf","prototype","runTxPlan","transport","handle","returned","response","txPlan","err","translateRejection","rejection","error_code","refuseFragment","caller","table","where","isSqlFragment","Error","k","v","Object","entries","branch","Array","isArray","addDecimal","cell","by","sign","undefined","a","String","b","parse","x","m","exec","trim","frac","unit","BigInt","scale","length","pa","pb","Math","max","lift","total","Number","toString","neg","digits","padStart","out","slice","rowMatchesFilter","row","f","every","c","some","matchesCell","cmp","op","l","Date","getTime","r","key","cond","isColRef","$col","isNowExpr","toISOString","includes","isColumnExpr","toLowerCase","startsWith","endsWith","createMockDB","store","Map","tracked","inserted","updated","deleted","rowsOf","rows","get","set","track","map","list","push","resolveInsertValues","data","expr","columnExprOf","fn","ops","diagnostics","updateMany","opts","keys","assertUsableFilter","assertUsableWriteValues","hit","filter","returning","deleteMany","keep","count","search","_table","_params","facets","similar","recommend","supersede","_id","id","crypto","randomUUID","query","_sql","insert","raw","assertNoExpressionHandles","record","aggregate","q","groups","groupBy","shape","bucket","sum","vals","reduce","avg","pick","byKey","JSON","stringify","values","insertMany","validateInsertManyOptions","onConflict","cols","i","missing","extra","join","rawRow","lockRows","ids","unique","Set","sort","lockRowsWhere","mode","advisoryXactLock","_key","claim","keyCols","existing","find","put","rawData","update","idx","findIndex","current","applied","delete","splice","findUnique","findById","page","findMany","limit","offset","isInteger","with","orderSpecs","orderBy","o","dir","direction","column","y","xNull","yNull","nullsFirst","nulls","start","select","fromEntries","txPlan","plan","snapshot","trackedSnapshot","cloneTracked","results","result","applyOp","failure","guardFailure","guard","err","clear","resolveMap","conflict","value","rows_affected","created","written","matches","next","removed","indexOf","found","client","command","options","atomic","attempt","asService","seed","resolveValue","tagged","$ref","txRejection","message","field","$expr","base","ok","kind","n","slot","status","code","error_code","retryBudget","value","n","Number","isInteger","Error","assertPlanRetry","options","retryBudget","retry","Error","qualifiedTableKey","schemaName","tableName","REQUEST_ALS","Symbol","for","__requestALS","g","globalThis","AsyncLocalStorage","runtime","REQUIRED_SERVICES","refuseIncompleteBox","services","missing","filter","k","undefined","length","Error","join","__getRuntime","scoped","__requestALS","getStore","runtime","makeServiceProxy","key","handler","get","_target","prop","receiver","client","__getRuntime","value","Reflect","bind","Proxy","makeTableProxy","ops","prefix","_t","undefined","name","insert","data","aggregate","q","insertMany","rows","opts","update","where","id","set","delete","findById","findUnique","select","with","page","findMany","put","onConflict","updateMany","returning","deleteMany","count","search","params","similar","recommend","facets","supersede","row","claim","unique","extra","rawDatabase","makeTypedSurface","raw","reco","$query","sql","query","$diagnostics","diagnostics","$insert","table","$update","$delete","$findById","$findUnique","$page","$findMany","$put","$updateMany","$deleteMany","$count","$search","$similar","$recommend","$facets","$claim","$lockRows","ids","lockRows","$lockRowsWhere","lockRowsWhere","$advisoryXactLock","advisoryXactLock","$aggregate","$insertMany","$supersede","base","Object","assign","$atomic","fn","options","atomic","Error","parent","__requestALS","getStore","runtime","tx","typed","invoke","refuse","ambient","asService","run","Database","$attempt","attempt","$transaction","assertPlanRetry","builder","TxPlanBuilder","runTxPlan","makeTxPlanHandle","$command","txPlan","plan","command","target","startsWith","qualifiedTableKey","makeTxTablesAccessor","tablesProxy","publicTables","$asService","Documents","makeBucketsAccessor","storage","bucket","rawStorage","Storage","buckets","Cache","Secrets","Auth","Log","Notifications","rawFlags","Flags","isEnabled","flagName","context","getVariant","getAll","defaultOrContext","maybeContext","setOverride","Realtime","fakeDatabase","mock","createMockDB","queries","db","Object","assign","create","getPrototypeOf","query","sql","params","push","makeTypedSurface","raw","seed","table","rows","inserted","updated","deleted","absent","name","Proxy","get","_target","prop","Error","String","pick","services","key","withServices","fn","filled","Database","Auth","Secrets","Documents","Storage","Cache","Log","Notifications","Flags","Realtime","__requestALS","run","runtime","userId"]}
|