@gusto/baerly-storage 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +29 -0
- package/README.md +176 -70
- package/dist/API.md +213 -139
- package/dist/CHANGELOG.md +434 -0
- package/dist/RECIPES.md +125 -0
- package/dist/THIRD-PARTY-LICENSES.txt +238 -0
- package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-DyiFK3_k.d.ts} +55 -11
- package/dist/app-config.d.ts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/auth.js +301 -301
- package/dist/auth.js.map +1 -1
- package/dist/aws4fetch.esm-p7eEzLCs.js +1702 -0
- package/dist/aws4fetch.esm-p7eEzLCs.js.map +1 -0
- package/dist/baerly.js +35 -15
- package/dist/baerly.js.map +1 -1
- package/dist/baerly.spec.json +342 -0
- package/dist/bytes-BXdamO3L.js.map +1 -1
- package/dist/{client-DYZfoZb9.d.ts → client-Fe8CwB73.d.ts} +10 -10
- package/dist/client-react.d.ts +3 -3
- package/dist/client-react.js +4 -4
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +4 -4
- package/dist/client.js +3 -3
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-CINJPKCW.js → cloudflare-DzKBrUlg.js} +178 -2
- package/dist/cloudflare-DzKBrUlg.js.map +1 -0
- package/dist/cloudflare.d.ts +49 -6
- package/dist/cloudflare.js +59 -26
- package/dist/cloudflare.js.map +1 -1
- package/dist/config-1tv0-Yzm.js +2693 -0
- package/dist/config-1tv0-Yzm.js.map +1 -0
- package/dist/constants-CfeMWQWk.js +222 -0
- package/dist/constants-CfeMWQWk.js.map +1 -0
- package/dist/context-DRZ3tZ5l.js.map +1 -1
- package/dist/{cost-CQt1YRkA.js → cost-DSMIVqzL.js} +43 -42
- package/dist/cost-DSMIVqzL.js.map +1 -0
- package/dist/current-json-C6nhPOm1.js +190 -0
- package/dist/current-json-C6nhPOm1.js.map +1 -0
- package/dist/{db-BM3y2JQw.d.ts → db-DsPkOVEH.d.ts} +26 -108
- package/dist/{deploy-CrAbfgCq.js → deploy-DonTr-CV.js} +12 -5
- package/dist/deploy-DonTr-CV.js.map +1 -0
- package/dist/dev-vite.d.ts +11 -7
- package/dist/dev-vite.js +7 -6
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-Db-hzPmE.js → doctor-DSIyCDg_.js} +14 -136
- package/dist/doctor-DSIyCDg_.js.map +1 -0
- package/dist/{dump-BYA55NLP.js → dump-Bh5k26VQ.js} +10 -31
- package/dist/dump-Bh5k26VQ.js.map +1 -0
- package/dist/{errors-DOdL95kK.js → errors-Dfa3p78c.js} +25 -5
- package/dist/errors-Dfa3p78c.js.map +1 -0
- package/dist/{export-Bhbz90-z.js → export-DtF5tDIM.js} +11 -32
- package/dist/{export-Bhbz90-z.js.map → export-DtF5tDIM.js.map} +1 -1
- package/dist/{fsck-CPPZWt9p.js → fsck-D_djMO5D.js} +28 -39
- package/dist/fsck-D_djMO5D.js.map +1 -0
- package/dist/{http-Cw8p6y5b.js → http-DxM9MflO.js} +151 -79
- package/dist/http-DxM9MflO.js.map +1 -0
- package/dist/http.d.ts +42 -26
- package/dist/http.js +3 -2
- package/dist/{index-DwDTWPSU.d.ts → index-0rZcMBwy.d.ts} +10 -7
- package/dist/{index-C3JAH1Yo.d.ts → index-B6oexfOB.d.ts} +9 -9
- package/dist/{index-cUY-36AN.d.ts → index-BNRh23K9.d.ts} +21 -5
- package/dist/{index-DSvwEUeF.d.ts → index-BYk9oCNf.d.ts} +240 -202
- package/dist/index.d.ts +6 -6
- package/dist/index.js +5 -5
- package/dist/{indexes-DAu2AkTW.d.ts → indexes-Dn9hbGQG.d.ts} +2 -2
- package/dist/{inspect-Bdbzvi-_.js → inspect-6WZ-pC7-.js} +21 -36
- package/dist/inspect-6WZ-pC7-.js.map +1 -0
- package/dist/key-Di6yyxFu.js +35 -0
- package/dist/key-Di6yyxFu.js.map +1 -0
- package/dist/{snapshot-SS8USDUF.js → log-tail-D98U1JBo.js} +179 -84
- package/dist/log-tail-D98U1JBo.js.map +1 -0
- package/dist/{maintenance-ClzBC1Vv.js → maintenance-B4Dki6Ig.js} +438 -176
- package/dist/maintenance-B4Dki6Ig.js.map +1 -0
- package/dist/{maintenance-BRrThz8V.d.ts → maintenance-B_e0T99L.d.ts} +114 -26
- package/dist/{maintenance-BvOv6BMM.js → maintenance-C7coQp4c.js} +217 -94
- package/dist/maintenance-C7coQp4c.js.map +1 -0
- package/dist/maintenance.d.ts +3 -2
- package/dist/maintenance.js +3 -2
- package/dist/node.d.ts +176 -68
- package/dist/node.js +3 -2
- package/dist/{normalize-XWY25_sG.js → normalize-rjnZLwS4.js} +2 -2
- package/dist/normalize-rjnZLwS4.js.map +1 -0
- package/dist/{observability-CpOiEN0k.js → observability-wzs3-BL_.js} +279 -109
- package/dist/observability-wzs3-BL_.js.map +1 -0
- package/dist/observability.d.ts +3 -3
- package/dist/observability.js +1 -1
- package/dist/{plan-DOTl21vq.js → plan-a7PJHBCy.js} +7 -4
- package/dist/plan-a7PJHBCy.js.map +1 -0
- package/dist/{query-BmiQy328.js → query-rAtXNQQB.js} +1063 -1202
- package/dist/query-rAtXNQQB.js.map +1 -0
- package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-BVzQSZlm.js} +10 -32
- package/dist/rebuild-index-BVzQSZlm.js.map +1 -0
- package/dist/{request-BEF_OvMh.js → request-u0M51mhJ.js} +3 -3
- package/dist/{request-BEF_OvMh.js.map → request-u0M51mhJ.js.map} +1 -1
- package/dist/restore-R-4rbciV.js +778 -0
- package/dist/restore-R-4rbciV.js.map +1 -0
- package/dist/runtime-spec-qL3_lTTU.js +391 -0
- package/dist/runtime-spec-qL3_lTTU.js.map +1 -0
- package/dist/s3-http-B-z8th6O.d.ts +60 -0
- package/dist/s3.d.ts +47 -0
- package/dist/s3.js +45 -0
- package/dist/s3.js.map +1 -0
- package/dist/{shared-secret-BJdSwpgw.js → shared-secret-DgEicd3x.js} +13 -5
- package/dist/shared-secret-DgEicd3x.js.map +1 -0
- package/dist/src-BG20LZs7.js +2271 -0
- package/dist/src-BG20LZs7.js.map +1 -0
- package/dist/{src-zhEAmmF7.js → src-CYHFDrKz.js} +82 -99
- package/dist/src-CYHFDrKz.js.map +1 -0
- package/dist/{src-QQ7jDeL2.js → src-DYZ4H1aF.js} +44 -23
- package/dist/src-DYZ4H1aF.js.map +1 -0
- package/dist/subcommand-DoDA-K7d.js +197 -0
- package/dist/subcommand-DoDA-K7d.js.map +1 -0
- package/dist/time-DUqvFMHq.js +119 -0
- package/dist/time-DUqvFMHq.js.map +1 -0
- package/dist/{usage-CLjirdD-.js → usage-DBV1eQHC.js} +7 -22
- package/dist/usage-DBV1eQHC.js.map +1 -0
- package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
- package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
- package/dist/wire-izfGZDvr.js.map +1 -1
- package/package.json +77 -42
- package/dist/cloudflare-CINJPKCW.js.map +0 -1
- package/dist/config-DVfDGyw1.js +0 -278
- package/dist/config-DVfDGyw1.js.map +0 -1
- package/dist/cost-CQt1YRkA.js.map +0 -1
- package/dist/current-json-C-EyJqs0.js +0 -354
- package/dist/current-json-C-EyJqs0.js.map +0 -1
- package/dist/deploy-CrAbfgCq.js.map +0 -1
- package/dist/doctor-Db-hzPmE.js.map +0 -1
- package/dist/dump-BYA55NLP.js.map +0 -1
- package/dist/errors-DOdL95kK.js.map +0 -1
- package/dist/fsck-CPPZWt9p.js.map +0 -1
- package/dist/http-Cw8p6y5b.js.map +0 -1
- package/dist/inspect-Bdbzvi-_.js.map +0 -1
- package/dist/maintenance-BvOv6BMM.js.map +0 -1
- package/dist/maintenance-ClzBC1Vv.js.map +0 -1
- package/dist/normalize-XWY25_sG.js.map +0 -1
- package/dist/observability-CpOiEN0k.js.map +0 -1
- package/dist/plan-DOTl21vq.js.map +0 -1
- package/dist/query-BmiQy328.js.map +0 -1
- package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
- package/dist/restore-C6IcmLeA.js +0 -771
- package/dist/restore-C6IcmLeA.js.map +0 -1
- package/dist/shared-secret-BJdSwpgw.js.map +0 -1
- package/dist/snapshot-SS8USDUF.js.map +0 -1
- package/dist/src-DU1sCMlr.js +0 -6236
- package/dist/src-DU1sCMlr.js.map +0 -1
- package/dist/src-QQ7jDeL2.js.map +0 -1
- package/dist/src-zhEAmmF7.js.map +0 -1
- package/dist/subcommand-DZcHcsYp.js +0 -5122
- package/dist/subcommand-DZcHcsYp.js.map +0 -1
- package/dist/usage-CLjirdD-.js.map +0 -1
- /package/dist/{chunk-EAsCxrDo.js → rolldown-runtime-EAsCxrDo.js} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cloudflare-CINJPKCW.js","names":["parse","parser.parse","parseR2Bindings","parseR2BindingsFromSource"],"sources":["../packages/cli/src/runner.ts","../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js","../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/string-intern.js","../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js","../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js","../packages/cli/src/wrangler-patch.ts","../packages/cli/src/deploy/cloudflare.ts"],"sourcesContent":["/**\n * `ProcessRunner` interface + default `node:child_process.spawn`-backed\n * implementation. Shared by `baerly deploy` and `baerly doctor`, both of\n * which shell out to Wrangler.\n *\n * Tests inject a mock; production uses {@link defaultRunner}. Pass\n * `{ tee: true }` to also write the child's stdout/stderr to the parent\n * process — `baerly deploy` does this so the operator sees Wrangler's\n * progress in real time; `baerly doctor` captures silently for parsing.\n */\n\nimport { spawn } from \"node:child_process\";\n\nexport interface ProcessRunner {\n /**\n * Run `cmd` with `args` in `cwd`. Returns the integer exit code plus\n * captured stdout/stderr. Captured output is also tee'd to the host\n * process's stdout/stderr when the runner was constructed with\n * `{ tee: true }`.\n */\n run(\n cmd: string,\n args: readonly string[],\n cwd: string,\n ): Promise<{ readonly code: number; readonly stdout: string; readonly stderr: string }>;\n}\n\n/**\n * Default `node:child_process.spawn`-backed runner. Inherits stdin and\n * captures stdout/stderr. With `tee: true` the captured bytes are also\n * forwarded to the parent process so the user sees the child's progress\n * in real time.\n */\nexport const defaultRunner = (opts: { readonly tee?: boolean } = {}): ProcessRunner => {\n const tee = opts.tee === true;\n return {\n run: (cmd, args, cwd) =>\n new Promise((res, rej) => {\n const child = spawn(cmd, args as string[], {\n cwd,\n stdio: [\"inherit\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout?.on(\"data\", (b: Buffer) => {\n stdout += b.toString(\"utf8\");\n if (tee) {\n process.stdout.write(b);\n }\n });\n child.stderr?.on(\"data\", (b: Buffer) => {\n stderr += b.toString(\"utf8\");\n if (tee) {\n process.stderr.write(b);\n }\n });\n child.on(\"error\", rej);\n child.on(\"close\", (code) => res({ code: code ?? 1, stdout, stderr }));\n }),\n };\n};\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\n/**\n * Creates a JSON scanner on the given text.\n * If ignoreTrivia is set, whitespaces or comments are ignored.\n */\nexport function createScanner(text, ignoreTrivia = false) {\n const len = text.length;\n let pos = 0, value = '', tokenOffset = 0, token = 16 /* SyntaxKind.Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* ScanError.None */;\n function scanHexDigits(count, exact) {\n let digits = 0;\n let value = 0;\n while (digits < count || !exact) {\n let ch = text.charCodeAt(pos);\n if (ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */) {\n value = value * 16 + ch - 48 /* CharacterCodes._0 */;\n }\n else if (ch >= 65 /* CharacterCodes.A */ && ch <= 70 /* CharacterCodes.F */) {\n value = value * 16 + ch - 65 /* CharacterCodes.A */ + 10;\n }\n else if (ch >= 97 /* CharacterCodes.a */ && ch <= 102 /* CharacterCodes.f */) {\n value = value * 16 + ch - 97 /* CharacterCodes.a */ + 10;\n }\n else {\n break;\n }\n pos++;\n digits++;\n }\n if (digits < count) {\n value = -1;\n }\n return value;\n }\n function setPosition(newPosition) {\n pos = newPosition;\n value = '';\n tokenOffset = 0;\n token = 16 /* SyntaxKind.Unknown */;\n scanError = 0 /* ScanError.None */;\n }\n function scanNumber() {\n let start = pos;\n if (text.charCodeAt(pos) === 48 /* CharacterCodes._0 */) {\n pos++;\n }\n else {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n }\n if (pos < text.length && text.charCodeAt(pos) === 46 /* CharacterCodes.dot */) {\n pos++;\n if (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n }\n else {\n scanError = 3 /* ScanError.UnexpectedEndOfNumber */;\n return text.substring(start, pos);\n }\n }\n let end = pos;\n if (pos < text.length && (text.charCodeAt(pos) === 69 /* CharacterCodes.E */ || text.charCodeAt(pos) === 101 /* CharacterCodes.e */)) {\n pos++;\n if (pos < text.length && text.charCodeAt(pos) === 43 /* CharacterCodes.plus */ || text.charCodeAt(pos) === 45 /* CharacterCodes.minus */) {\n pos++;\n }\n if (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n end = pos;\n }\n else {\n scanError = 3 /* ScanError.UnexpectedEndOfNumber */;\n }\n }\n return text.substring(start, end);\n }\n function scanString() {\n let result = '', start = pos;\n while (true) {\n if (pos >= len) {\n result += text.substring(start, pos);\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n const ch = text.charCodeAt(pos);\n if (ch === 34 /* CharacterCodes.doubleQuote */) {\n result += text.substring(start, pos);\n pos++;\n break;\n }\n if (ch === 92 /* CharacterCodes.backslash */) {\n result += text.substring(start, pos);\n pos++;\n if (pos >= len) {\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n const ch2 = text.charCodeAt(pos++);\n switch (ch2) {\n case 34 /* CharacterCodes.doubleQuote */:\n result += '\\\"';\n break;\n case 92 /* CharacterCodes.backslash */:\n result += '\\\\';\n break;\n case 47 /* CharacterCodes.slash */:\n result += '/';\n break;\n case 98 /* CharacterCodes.b */:\n result += '\\b';\n break;\n case 102 /* CharacterCodes.f */:\n result += '\\f';\n break;\n case 110 /* CharacterCodes.n */:\n result += '\\n';\n break;\n case 114 /* CharacterCodes.r */:\n result += '\\r';\n break;\n case 116 /* CharacterCodes.t */:\n result += '\\t';\n break;\n case 117 /* CharacterCodes.u */:\n const ch3 = scanHexDigits(4, true);\n if (ch3 >= 0) {\n result += String.fromCharCode(ch3);\n }\n else {\n scanError = 4 /* ScanError.InvalidUnicode */;\n }\n break;\n default:\n scanError = 5 /* ScanError.InvalidEscapeCharacter */;\n }\n start = pos;\n continue;\n }\n if (ch >= 0 && ch <= 0x1f) {\n if (isLineBreak(ch)) {\n result += text.substring(start, pos);\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n else {\n scanError = 6 /* ScanError.InvalidCharacter */;\n // mark as error but continue with string\n }\n }\n pos++;\n }\n return result;\n }\n function scanNext() {\n value = '';\n scanError = 0 /* ScanError.None */;\n tokenOffset = pos;\n lineStartOffset = lineNumber;\n prevTokenLineStartOffset = tokenLineStartOffset;\n if (pos >= len) {\n // at the end\n tokenOffset = len;\n return token = 17 /* SyntaxKind.EOF */;\n }\n let code = text.charCodeAt(pos);\n // trivia: whitespace\n if (isWhiteSpace(code)) {\n do {\n pos++;\n value += String.fromCharCode(code);\n code = text.charCodeAt(pos);\n } while (isWhiteSpace(code));\n return token = 15 /* SyntaxKind.Trivia */;\n }\n // trivia: newlines\n if (isLineBreak(code)) {\n pos++;\n value += String.fromCharCode(code);\n if (code === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) {\n pos++;\n value += '\\n';\n }\n lineNumber++;\n tokenLineStartOffset = pos;\n return token = 14 /* SyntaxKind.LineBreakTrivia */;\n }\n switch (code) {\n // tokens: []{}:,\n case 123 /* CharacterCodes.openBrace */:\n pos++;\n return token = 1 /* SyntaxKind.OpenBraceToken */;\n case 125 /* CharacterCodes.closeBrace */:\n pos++;\n return token = 2 /* SyntaxKind.CloseBraceToken */;\n case 91 /* CharacterCodes.openBracket */:\n pos++;\n return token = 3 /* SyntaxKind.OpenBracketToken */;\n case 93 /* CharacterCodes.closeBracket */:\n pos++;\n return token = 4 /* SyntaxKind.CloseBracketToken */;\n case 58 /* CharacterCodes.colon */:\n pos++;\n return token = 6 /* SyntaxKind.ColonToken */;\n case 44 /* CharacterCodes.comma */:\n pos++;\n return token = 5 /* SyntaxKind.CommaToken */;\n // strings\n case 34 /* CharacterCodes.doubleQuote */:\n pos++;\n value = scanString();\n return token = 10 /* SyntaxKind.StringLiteral */;\n // comments\n case 47 /* CharacterCodes.slash */:\n const start = pos - 1;\n // Single-line comment\n if (text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) {\n pos += 2;\n while (pos < len) {\n if (isLineBreak(text.charCodeAt(pos))) {\n break;\n }\n pos++;\n }\n value = text.substring(start, pos);\n return token = 12 /* SyntaxKind.LineCommentTrivia */;\n }\n // Multi-line comment\n if (text.charCodeAt(pos + 1) === 42 /* CharacterCodes.asterisk */) {\n pos += 2;\n const safeLength = len - 1; // For lookahead.\n let commentClosed = false;\n while (pos < safeLength) {\n const ch = text.charCodeAt(pos);\n if (ch === 42 /* CharacterCodes.asterisk */ && text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) {\n pos += 2;\n commentClosed = true;\n break;\n }\n pos++;\n if (isLineBreak(ch)) {\n if (ch === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) {\n pos++;\n }\n lineNumber++;\n tokenLineStartOffset = pos;\n }\n }\n if (!commentClosed) {\n pos++;\n scanError = 1 /* ScanError.UnexpectedEndOfComment */;\n }\n value = text.substring(start, pos);\n return token = 13 /* SyntaxKind.BlockCommentTrivia */;\n }\n // just a single slash\n value += String.fromCharCode(code);\n pos++;\n return token = 16 /* SyntaxKind.Unknown */;\n // numbers\n case 45 /* CharacterCodes.minus */:\n value += String.fromCharCode(code);\n pos++;\n if (pos === len || !isDigit(text.charCodeAt(pos))) {\n return token = 16 /* SyntaxKind.Unknown */;\n }\n // found a minus, followed by a number so\n // we fall through to proceed with scanning\n // numbers\n case 48 /* CharacterCodes._0 */:\n case 49 /* CharacterCodes._1 */:\n case 50 /* CharacterCodes._2 */:\n case 51 /* CharacterCodes._3 */:\n case 52 /* CharacterCodes._4 */:\n case 53 /* CharacterCodes._5 */:\n case 54 /* CharacterCodes._6 */:\n case 55 /* CharacterCodes._7 */:\n case 56 /* CharacterCodes._8 */:\n case 57 /* CharacterCodes._9 */:\n value += scanNumber();\n return token = 11 /* SyntaxKind.NumericLiteral */;\n // literals and unknown symbols\n default:\n // is a literal? Read the full word.\n while (pos < len && isUnknownContentCharacter(code)) {\n pos++;\n code = text.charCodeAt(pos);\n }\n if (tokenOffset !== pos) {\n value = text.substring(tokenOffset, pos);\n // keywords: true, false, null\n switch (value) {\n case 'true': return token = 8 /* SyntaxKind.TrueKeyword */;\n case 'false': return token = 9 /* SyntaxKind.FalseKeyword */;\n case 'null': return token = 7 /* SyntaxKind.NullKeyword */;\n }\n return token = 16 /* SyntaxKind.Unknown */;\n }\n // some\n value += String.fromCharCode(code);\n pos++;\n return token = 16 /* SyntaxKind.Unknown */;\n }\n }\n function isUnknownContentCharacter(code) {\n if (isWhiteSpace(code) || isLineBreak(code)) {\n return false;\n }\n switch (code) {\n case 125 /* CharacterCodes.closeBrace */:\n case 93 /* CharacterCodes.closeBracket */:\n case 123 /* CharacterCodes.openBrace */:\n case 91 /* CharacterCodes.openBracket */:\n case 34 /* CharacterCodes.doubleQuote */:\n case 58 /* CharacterCodes.colon */:\n case 44 /* CharacterCodes.comma */:\n case 47 /* CharacterCodes.slash */:\n return false;\n }\n return true;\n }\n function scanNextNonTrivia() {\n let result;\n do {\n result = scanNext();\n } while (result >= 12 /* SyntaxKind.LineCommentTrivia */ && result <= 15 /* SyntaxKind.Trivia */);\n return result;\n }\n return {\n setPosition: setPosition,\n getPosition: () => pos,\n scan: ignoreTrivia ? scanNextNonTrivia : scanNext,\n getToken: () => token,\n getTokenValue: () => value,\n getTokenOffset: () => tokenOffset,\n getTokenLength: () => pos - tokenOffset,\n getTokenStartLine: () => lineStartOffset,\n getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,\n getTokenError: () => scanError,\n };\n}\nfunction isWhiteSpace(ch) {\n return ch === 32 /* CharacterCodes.space */ || ch === 9 /* CharacterCodes.tab */;\n}\nfunction isLineBreak(ch) {\n return ch === 10 /* CharacterCodes.lineFeed */ || ch === 13 /* CharacterCodes.carriageReturn */;\n}\nfunction isDigit(ch) {\n return ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */;\n}\nvar CharacterCodes;\n(function (CharacterCodes) {\n CharacterCodes[CharacterCodes[\"lineFeed\"] = 10] = \"lineFeed\";\n CharacterCodes[CharacterCodes[\"carriageReturn\"] = 13] = \"carriageReturn\";\n CharacterCodes[CharacterCodes[\"space\"] = 32] = \"space\";\n CharacterCodes[CharacterCodes[\"_0\"] = 48] = \"_0\";\n CharacterCodes[CharacterCodes[\"_1\"] = 49] = \"_1\";\n CharacterCodes[CharacterCodes[\"_2\"] = 50] = \"_2\";\n CharacterCodes[CharacterCodes[\"_3\"] = 51] = \"_3\";\n CharacterCodes[CharacterCodes[\"_4\"] = 52] = \"_4\";\n CharacterCodes[CharacterCodes[\"_5\"] = 53] = \"_5\";\n CharacterCodes[CharacterCodes[\"_6\"] = 54] = \"_6\";\n CharacterCodes[CharacterCodes[\"_7\"] = 55] = \"_7\";\n CharacterCodes[CharacterCodes[\"_8\"] = 56] = \"_8\";\n CharacterCodes[CharacterCodes[\"_9\"] = 57] = \"_9\";\n CharacterCodes[CharacterCodes[\"a\"] = 97] = \"a\";\n CharacterCodes[CharacterCodes[\"b\"] = 98] = \"b\";\n CharacterCodes[CharacterCodes[\"c\"] = 99] = \"c\";\n CharacterCodes[CharacterCodes[\"d\"] = 100] = \"d\";\n CharacterCodes[CharacterCodes[\"e\"] = 101] = \"e\";\n CharacterCodes[CharacterCodes[\"f\"] = 102] = \"f\";\n CharacterCodes[CharacterCodes[\"g\"] = 103] = \"g\";\n CharacterCodes[CharacterCodes[\"h\"] = 104] = \"h\";\n CharacterCodes[CharacterCodes[\"i\"] = 105] = \"i\";\n CharacterCodes[CharacterCodes[\"j\"] = 106] = \"j\";\n CharacterCodes[CharacterCodes[\"k\"] = 107] = \"k\";\n CharacterCodes[CharacterCodes[\"l\"] = 108] = \"l\";\n CharacterCodes[CharacterCodes[\"m\"] = 109] = \"m\";\n CharacterCodes[CharacterCodes[\"n\"] = 110] = \"n\";\n CharacterCodes[CharacterCodes[\"o\"] = 111] = \"o\";\n CharacterCodes[CharacterCodes[\"p\"] = 112] = \"p\";\n CharacterCodes[CharacterCodes[\"q\"] = 113] = \"q\";\n CharacterCodes[CharacterCodes[\"r\"] = 114] = \"r\";\n CharacterCodes[CharacterCodes[\"s\"] = 115] = \"s\";\n CharacterCodes[CharacterCodes[\"t\"] = 116] = \"t\";\n CharacterCodes[CharacterCodes[\"u\"] = 117] = \"u\";\n CharacterCodes[CharacterCodes[\"v\"] = 118] = \"v\";\n CharacterCodes[CharacterCodes[\"w\"] = 119] = \"w\";\n CharacterCodes[CharacterCodes[\"x\"] = 120] = \"x\";\n CharacterCodes[CharacterCodes[\"y\"] = 121] = \"y\";\n CharacterCodes[CharacterCodes[\"z\"] = 122] = \"z\";\n CharacterCodes[CharacterCodes[\"A\"] = 65] = \"A\";\n CharacterCodes[CharacterCodes[\"B\"] = 66] = \"B\";\n CharacterCodes[CharacterCodes[\"C\"] = 67] = \"C\";\n CharacterCodes[CharacterCodes[\"D\"] = 68] = \"D\";\n CharacterCodes[CharacterCodes[\"E\"] = 69] = \"E\";\n CharacterCodes[CharacterCodes[\"F\"] = 70] = \"F\";\n CharacterCodes[CharacterCodes[\"G\"] = 71] = \"G\";\n CharacterCodes[CharacterCodes[\"H\"] = 72] = \"H\";\n CharacterCodes[CharacterCodes[\"I\"] = 73] = \"I\";\n CharacterCodes[CharacterCodes[\"J\"] = 74] = \"J\";\n CharacterCodes[CharacterCodes[\"K\"] = 75] = \"K\";\n CharacterCodes[CharacterCodes[\"L\"] = 76] = \"L\";\n CharacterCodes[CharacterCodes[\"M\"] = 77] = \"M\";\n CharacterCodes[CharacterCodes[\"N\"] = 78] = \"N\";\n CharacterCodes[CharacterCodes[\"O\"] = 79] = \"O\";\n CharacterCodes[CharacterCodes[\"P\"] = 80] = \"P\";\n CharacterCodes[CharacterCodes[\"Q\"] = 81] = \"Q\";\n CharacterCodes[CharacterCodes[\"R\"] = 82] = \"R\";\n CharacterCodes[CharacterCodes[\"S\"] = 83] = \"S\";\n CharacterCodes[CharacterCodes[\"T\"] = 84] = \"T\";\n CharacterCodes[CharacterCodes[\"U\"] = 85] = \"U\";\n CharacterCodes[CharacterCodes[\"V\"] = 86] = \"V\";\n CharacterCodes[CharacterCodes[\"W\"] = 87] = \"W\";\n CharacterCodes[CharacterCodes[\"X\"] = 88] = \"X\";\n CharacterCodes[CharacterCodes[\"Y\"] = 89] = \"Y\";\n CharacterCodes[CharacterCodes[\"Z\"] = 90] = \"Z\";\n CharacterCodes[CharacterCodes[\"asterisk\"] = 42] = \"asterisk\";\n CharacterCodes[CharacterCodes[\"backslash\"] = 92] = \"backslash\";\n CharacterCodes[CharacterCodes[\"closeBrace\"] = 125] = \"closeBrace\";\n CharacterCodes[CharacterCodes[\"closeBracket\"] = 93] = \"closeBracket\";\n CharacterCodes[CharacterCodes[\"colon\"] = 58] = \"colon\";\n CharacterCodes[CharacterCodes[\"comma\"] = 44] = \"comma\";\n CharacterCodes[CharacterCodes[\"dot\"] = 46] = \"dot\";\n CharacterCodes[CharacterCodes[\"doubleQuote\"] = 34] = \"doubleQuote\";\n CharacterCodes[CharacterCodes[\"minus\"] = 45] = \"minus\";\n CharacterCodes[CharacterCodes[\"openBrace\"] = 123] = \"openBrace\";\n CharacterCodes[CharacterCodes[\"openBracket\"] = 91] = \"openBracket\";\n CharacterCodes[CharacterCodes[\"plus\"] = 43] = \"plus\";\n CharacterCodes[CharacterCodes[\"slash\"] = 47] = \"slash\";\n CharacterCodes[CharacterCodes[\"formFeed\"] = 12] = \"formFeed\";\n CharacterCodes[CharacterCodes[\"tab\"] = 9] = \"tab\";\n})(CharacterCodes || (CharacterCodes = {}));\n","export const cachedSpaces = new Array(20).fill(0).map((_, index) => {\n return ' '.repeat(index);\n});\nconst maxCachedValues = 200;\nexport const cachedBreakLinesWithSpaces = {\n ' ': {\n '\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\n' + ' '.repeat(index);\n }),\n '\\r': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r' + ' '.repeat(index);\n }),\n '\\r\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r\\n' + ' '.repeat(index);\n }),\n },\n '\\t': {\n '\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\n' + '\\t'.repeat(index);\n }),\n '\\r': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r' + '\\t'.repeat(index);\n }),\n '\\r\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r\\n' + '\\t'.repeat(index);\n }),\n }\n};\nexport const supportedEols = ['\\n', '\\r', '\\r\\n'];\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport { createScanner } from './scanner';\nvar ParseOptions;\n(function (ParseOptions) {\n ParseOptions.DEFAULT = {\n allowTrailingComma: false\n };\n})(ParseOptions || (ParseOptions = {}));\n/**\n * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.\n */\nexport function getLocation(text, position) {\n const segments = []; // strings or numbers\n const earlyReturnException = new Object();\n let previousNode = undefined;\n const previousNodeInst = {\n value: {},\n offset: 0,\n length: 0,\n type: 'object',\n parent: undefined\n };\n let isAtPropertyKey = false;\n function setPreviousNode(value, offset, length, type) {\n previousNodeInst.value = value;\n previousNodeInst.offset = offset;\n previousNodeInst.length = length;\n previousNodeInst.type = type;\n previousNodeInst.colonOffset = undefined;\n previousNode = previousNodeInst;\n }\n try {\n visit(text, {\n onObjectBegin: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n isAtPropertyKey = position > offset;\n segments.push(''); // push a placeholder (will be replaced)\n },\n onObjectProperty: (name, offset, length) => {\n if (position < offset) {\n throw earlyReturnException;\n }\n setPreviousNode(name, offset, length, 'property');\n segments[segments.length - 1] = name;\n if (position <= offset + length) {\n throw earlyReturnException;\n }\n },\n onObjectEnd: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.pop();\n },\n onArrayBegin: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.push(0);\n },\n onArrayEnd: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.pop();\n },\n onLiteralValue: (value, offset, length) => {\n if (position < offset) {\n throw earlyReturnException;\n }\n setPreviousNode(value, offset, length, getNodeType(value));\n if (position <= offset + length) {\n throw earlyReturnException;\n }\n },\n onSeparator: (sep, offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n if (sep === ':' && previousNode && previousNode.type === 'property') {\n previousNode.colonOffset = offset;\n isAtPropertyKey = false;\n previousNode = undefined;\n }\n else if (sep === ',') {\n const last = segments[segments.length - 1];\n if (typeof last === 'number') {\n segments[segments.length - 1] = last + 1;\n }\n else {\n isAtPropertyKey = true;\n segments[segments.length - 1] = '';\n }\n previousNode = undefined;\n }\n }\n });\n }\n catch (e) {\n if (e !== earlyReturnException) {\n throw e;\n }\n }\n return {\n path: segments,\n previousNode,\n isAtPropertyKey,\n matches: (pattern) => {\n let k = 0;\n for (let i = 0; k < pattern.length && i < segments.length; i++) {\n if (pattern[k] === segments[i] || pattern[k] === '*') {\n k++;\n }\n else if (pattern[k] !== '**') {\n return false;\n }\n }\n return k === pattern.length;\n }\n };\n}\n/**\n * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n * Therefore always check the errors list to find out if the input was valid.\n */\nexport function parse(text, errors = [], options = ParseOptions.DEFAULT) {\n let currentProperty = null;\n let currentParent = [];\n const previousParents = [];\n function onValue(value) {\n if (Array.isArray(currentParent)) {\n currentParent.push(value);\n }\n else if (currentProperty !== null) {\n currentParent[currentProperty] = value;\n }\n }\n const visitor = {\n onObjectBegin: () => {\n const object = {};\n onValue(object);\n previousParents.push(currentParent);\n currentParent = object;\n currentProperty = null;\n },\n onObjectProperty: (name) => {\n currentProperty = name;\n },\n onObjectEnd: () => {\n currentParent = previousParents.pop();\n },\n onArrayBegin: () => {\n const array = [];\n onValue(array);\n previousParents.push(currentParent);\n currentParent = array;\n currentProperty = null;\n },\n onArrayEnd: () => {\n currentParent = previousParents.pop();\n },\n onLiteralValue: onValue,\n onError: (error, offset, length) => {\n errors.push({ error, offset, length });\n }\n };\n visit(text, visitor, options);\n return currentParent[0];\n}\n/**\n * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n */\nexport function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {\n let currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root\n function ensurePropertyComplete(endOffset) {\n if (currentParent.type === 'property') {\n currentParent.length = endOffset - currentParent.offset;\n currentParent = currentParent.parent;\n }\n }\n function onValue(valueNode) {\n currentParent.children.push(valueNode);\n return valueNode;\n }\n const visitor = {\n onObjectBegin: (offset) => {\n currentParent = onValue({ type: 'object', offset, length: -1, parent: currentParent, children: [] });\n },\n onObjectProperty: (name, offset, length) => {\n currentParent = onValue({ type: 'property', offset, length: -1, parent: currentParent, children: [] });\n currentParent.children.push({ type: 'string', value: name, offset, length, parent: currentParent });\n },\n onObjectEnd: (offset, length) => {\n ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onArrayBegin: (offset, length) => {\n currentParent = onValue({ type: 'array', offset, length: -1, parent: currentParent, children: [] });\n },\n onArrayEnd: (offset, length) => {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onLiteralValue: (value, offset, length) => {\n onValue({ type: getNodeType(value), offset, length, parent: currentParent, value });\n ensurePropertyComplete(offset + length);\n },\n onSeparator: (sep, offset, length) => {\n if (currentParent.type === 'property') {\n if (sep === ':') {\n currentParent.colonOffset = offset;\n }\n else if (sep === ',') {\n ensurePropertyComplete(offset);\n }\n }\n },\n onError: (error, offset, length) => {\n errors.push({ error, offset, length });\n }\n };\n visit(text, visitor, options);\n const result = currentParent.children[0];\n if (result) {\n delete result.parent;\n }\n return result;\n}\n/**\n * Finds the node at the given path in a JSON DOM.\n */\nexport function findNodeAtLocation(root, path) {\n if (!root) {\n return undefined;\n }\n let node = root;\n for (let segment of path) {\n if (typeof segment === 'string') {\n if (node.type !== 'object' || !Array.isArray(node.children)) {\n return undefined;\n }\n let found = false;\n for (const propertyNode of node.children) {\n if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {\n node = propertyNode.children[1];\n found = true;\n break;\n }\n }\n if (!found) {\n return undefined;\n }\n }\n else {\n const index = segment;\n if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {\n return undefined;\n }\n node = node.children[index];\n }\n }\n return node;\n}\n/**\n * Gets the JSON path of the given JSON DOM node\n */\nexport function getNodePath(node) {\n if (!node.parent || !node.parent.children) {\n return [];\n }\n const path = getNodePath(node.parent);\n if (node.parent.type === 'property') {\n const key = node.parent.children[0].value;\n path.push(key);\n }\n else if (node.parent.type === 'array') {\n const index = node.parent.children.indexOf(node);\n if (index !== -1) {\n path.push(index);\n }\n }\n return path;\n}\n/**\n * Evaluates the JavaScript object of the given JSON DOM node\n */\nexport function getNodeValue(node) {\n switch (node.type) {\n case 'array':\n return node.children.map(getNodeValue);\n case 'object':\n const obj = Object.create(null);\n for (let prop of node.children) {\n const valueNode = prop.children[1];\n if (valueNode) {\n obj[prop.children[0].value] = getNodeValue(valueNode);\n }\n }\n return obj;\n case 'null':\n case 'string':\n case 'number':\n case 'boolean':\n return node.value;\n default:\n return undefined;\n }\n}\nexport function contains(node, offset, includeRightBound = false) {\n return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));\n}\n/**\n * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.\n */\nexport function findNodeAtOffset(node, offset, includeRightBound = false) {\n if (contains(node, offset, includeRightBound)) {\n const children = node.children;\n if (Array.isArray(children)) {\n for (let i = 0; i < children.length && children[i].offset <= offset; i++) {\n const item = findNodeAtOffset(children[i], offset, includeRightBound);\n if (item) {\n return item;\n }\n }\n }\n return node;\n }\n return undefined;\n}\n/**\n * Parses the given text and invokes the visitor functions for each object, array and literal reached.\n */\nexport function visit(text, visitor, options = ParseOptions.DEFAULT) {\n const _scanner = createScanner(text, false);\n // Important: Only pass copies of this to visitor functions to prevent accidental modification, and\n // to not affect visitor functions which stored a reference to a previous JSONPath\n const _jsonPath = [];\n // Depth of onXXXBegin() callbacks suppressed. onXXXEnd() decrements this if it isn't 0 already.\n // Callbacks are only called when this value is 0.\n let suppressedCallbacks = 0;\n function toNoArgVisit(visitFunction) {\n return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;\n }\n function toOneArgVisit(visitFunction) {\n return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;\n }\n function toOneArgVisitWithPath(visitFunction) {\n return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;\n }\n function toBeginVisit(visitFunction) {\n return visitFunction ?\n () => {\n if (suppressedCallbacks > 0) {\n suppressedCallbacks++;\n }\n else {\n let cbReturn = visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice());\n if (cbReturn === false) {\n suppressedCallbacks = 1;\n }\n }\n }\n : () => true;\n }\n function toEndVisit(visitFunction) {\n return visitFunction ?\n () => {\n if (suppressedCallbacks > 0) {\n suppressedCallbacks--;\n }\n if (suppressedCallbacks === 0) {\n visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());\n }\n }\n : () => true;\n }\n const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);\n const disallowComments = options && options.disallowComments;\n const allowTrailingComma = options && options.allowTrailingComma;\n function scanNext() {\n while (true) {\n const token = _scanner.scan();\n switch (_scanner.getTokenError()) {\n case 4 /* ScanError.InvalidUnicode */:\n handleError(14 /* ParseErrorCode.InvalidUnicode */);\n break;\n case 5 /* ScanError.InvalidEscapeCharacter */:\n handleError(15 /* ParseErrorCode.InvalidEscapeCharacter */);\n break;\n case 3 /* ScanError.UnexpectedEndOfNumber */:\n handleError(13 /* ParseErrorCode.UnexpectedEndOfNumber */);\n break;\n case 1 /* ScanError.UnexpectedEndOfComment */:\n if (!disallowComments) {\n handleError(11 /* ParseErrorCode.UnexpectedEndOfComment */);\n }\n break;\n case 2 /* ScanError.UnexpectedEndOfString */:\n handleError(12 /* ParseErrorCode.UnexpectedEndOfString */);\n break;\n case 6 /* ScanError.InvalidCharacter */:\n handleError(16 /* ParseErrorCode.InvalidCharacter */);\n break;\n }\n switch (token) {\n case 12 /* SyntaxKind.LineCommentTrivia */:\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n if (disallowComments) {\n handleError(10 /* ParseErrorCode.InvalidCommentToken */);\n }\n else {\n onComment();\n }\n break;\n case 16 /* SyntaxKind.Unknown */:\n handleError(1 /* ParseErrorCode.InvalidSymbol */);\n break;\n case 15 /* SyntaxKind.Trivia */:\n case 14 /* SyntaxKind.LineBreakTrivia */:\n break;\n default:\n return token;\n }\n }\n }\n function handleError(error, skipUntilAfter = [], skipUntil = []) {\n onError(error);\n if (skipUntilAfter.length + skipUntil.length > 0) {\n let token = _scanner.getToken();\n while (token !== 17 /* SyntaxKind.EOF */) {\n if (skipUntilAfter.indexOf(token) !== -1) {\n scanNext();\n break;\n }\n else if (skipUntil.indexOf(token) !== -1) {\n break;\n }\n token = scanNext();\n }\n }\n }\n function parseString(isValue) {\n const value = _scanner.getTokenValue();\n if (isValue) {\n onLiteralValue(value);\n }\n else {\n onObjectProperty(value);\n // add property name afterwards\n _jsonPath.push(value);\n }\n scanNext();\n return true;\n }\n function parseLiteral() {\n switch (_scanner.getToken()) {\n case 11 /* SyntaxKind.NumericLiteral */:\n const tokenValue = _scanner.getTokenValue();\n let value = Number(tokenValue);\n if (isNaN(value)) {\n handleError(2 /* ParseErrorCode.InvalidNumberFormat */);\n value = 0;\n }\n onLiteralValue(value);\n break;\n case 7 /* SyntaxKind.NullKeyword */:\n onLiteralValue(null);\n break;\n case 8 /* SyntaxKind.TrueKeyword */:\n onLiteralValue(true);\n break;\n case 9 /* SyntaxKind.FalseKeyword */:\n onLiteralValue(false);\n break;\n default:\n return false;\n }\n scanNext();\n return true;\n }\n function parseProperty() {\n if (_scanner.getToken() !== 10 /* SyntaxKind.StringLiteral */) {\n handleError(3 /* ParseErrorCode.PropertyNameExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n return false;\n }\n parseString(false);\n if (_scanner.getToken() === 6 /* SyntaxKind.ColonToken */) {\n onSeparator(':');\n scanNext(); // consume colon\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n }\n else {\n handleError(5 /* ParseErrorCode.ColonExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n _jsonPath.pop(); // remove processed property name\n return true;\n }\n function parseObject() {\n onObjectBegin();\n scanNext(); // consume open brace\n let needsComma = false;\n while (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {\n if (!needsComma) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n if (_scanner.getToken() === 2 /* SyntaxKind.CloseBraceToken */ && allowTrailingComma) {\n break;\n }\n }\n else if (needsComma) {\n handleError(6 /* ParseErrorCode.CommaExpected */, [], []);\n }\n if (!parseProperty()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n needsComma = true;\n }\n onObjectEnd();\n if (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */) {\n handleError(7 /* ParseErrorCode.CloseBraceExpected */, [2 /* SyntaxKind.CloseBraceToken */], []);\n }\n else {\n scanNext(); // consume close brace\n }\n return true;\n }\n function parseArray() {\n onArrayBegin();\n scanNext(); // consume open bracket\n let isFirstElement = true;\n let needsComma = false;\n while (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {\n if (!needsComma) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n if (_scanner.getToken() === 4 /* SyntaxKind.CloseBracketToken */ && allowTrailingComma) {\n break;\n }\n }\n else if (needsComma) {\n handleError(6 /* ParseErrorCode.CommaExpected */, [], []);\n }\n if (isFirstElement) {\n _jsonPath.push(0);\n isFirstElement = false;\n }\n else {\n _jsonPath[_jsonPath.length - 1]++;\n }\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [4 /* SyntaxKind.CloseBracketToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n needsComma = true;\n }\n onArrayEnd();\n if (!isFirstElement) {\n _jsonPath.pop(); // remove array index\n }\n if (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */) {\n handleError(8 /* ParseErrorCode.CloseBracketExpected */, [4 /* SyntaxKind.CloseBracketToken */], []);\n }\n else {\n scanNext(); // consume close bracket\n }\n return true;\n }\n function parseValue() {\n switch (_scanner.getToken()) {\n case 3 /* SyntaxKind.OpenBracketToken */:\n return parseArray();\n case 1 /* SyntaxKind.OpenBraceToken */:\n return parseObject();\n case 10 /* SyntaxKind.StringLiteral */:\n return parseString(true);\n default:\n return parseLiteral();\n }\n }\n scanNext();\n if (_scanner.getToken() === 17 /* SyntaxKind.EOF */) {\n if (options.allowEmptyContent) {\n return true;\n }\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n return false;\n }\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n return false;\n }\n if (_scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n handleError(9 /* ParseErrorCode.EndOfFileExpected */, [], []);\n }\n return true;\n}\n/**\n * Takes JSON with JavaScript-style comments and remove\n * them. Optionally replaces every none-newline character\n * of comments with a replaceCharacter\n */\nexport function stripComments(text, replaceCh) {\n let _scanner = createScanner(text), parts = [], kind, offset = 0, pos;\n do {\n pos = _scanner.getPosition();\n kind = _scanner.scan();\n switch (kind) {\n case 12 /* SyntaxKind.LineCommentTrivia */:\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n case 17 /* SyntaxKind.EOF */:\n if (offset !== pos) {\n parts.push(text.substring(offset, pos));\n }\n if (replaceCh !== undefined) {\n parts.push(_scanner.getTokenValue().replace(/[^\\r\\n]/g, replaceCh));\n }\n offset = _scanner.getPosition();\n break;\n }\n } while (kind !== 17 /* SyntaxKind.EOF */);\n return parts.join('');\n}\nexport function getNodeType(value) {\n switch (typeof value) {\n case 'boolean': return 'boolean';\n case 'number': return 'number';\n case 'string': return 'string';\n case 'object': {\n if (!value) {\n return 'null';\n }\n else if (Array.isArray(value)) {\n return 'array';\n }\n return 'object';\n }\n default: return 'null';\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport * as formatter from './impl/format';\nimport * as edit from './impl/edit';\nimport * as scanner from './impl/scanner';\nimport * as parser from './impl/parser';\n/**\n * Creates a JSON scanner on the given text.\n * If ignoreTrivia is set, whitespaces or comments are ignored.\n */\nexport const createScanner = scanner.createScanner;\nexport var ScanError;\n(function (ScanError) {\n ScanError[ScanError[\"None\"] = 0] = \"None\";\n ScanError[ScanError[\"UnexpectedEndOfComment\"] = 1] = \"UnexpectedEndOfComment\";\n ScanError[ScanError[\"UnexpectedEndOfString\"] = 2] = \"UnexpectedEndOfString\";\n ScanError[ScanError[\"UnexpectedEndOfNumber\"] = 3] = \"UnexpectedEndOfNumber\";\n ScanError[ScanError[\"InvalidUnicode\"] = 4] = \"InvalidUnicode\";\n ScanError[ScanError[\"InvalidEscapeCharacter\"] = 5] = \"InvalidEscapeCharacter\";\n ScanError[ScanError[\"InvalidCharacter\"] = 6] = \"InvalidCharacter\";\n})(ScanError || (ScanError = {}));\nexport var SyntaxKind;\n(function (SyntaxKind) {\n SyntaxKind[SyntaxKind[\"OpenBraceToken\"] = 1] = \"OpenBraceToken\";\n SyntaxKind[SyntaxKind[\"CloseBraceToken\"] = 2] = \"CloseBraceToken\";\n SyntaxKind[SyntaxKind[\"OpenBracketToken\"] = 3] = \"OpenBracketToken\";\n SyntaxKind[SyntaxKind[\"CloseBracketToken\"] = 4] = \"CloseBracketToken\";\n SyntaxKind[SyntaxKind[\"CommaToken\"] = 5] = \"CommaToken\";\n SyntaxKind[SyntaxKind[\"ColonToken\"] = 6] = \"ColonToken\";\n SyntaxKind[SyntaxKind[\"NullKeyword\"] = 7] = \"NullKeyword\";\n SyntaxKind[SyntaxKind[\"TrueKeyword\"] = 8] = \"TrueKeyword\";\n SyntaxKind[SyntaxKind[\"FalseKeyword\"] = 9] = \"FalseKeyword\";\n SyntaxKind[SyntaxKind[\"StringLiteral\"] = 10] = \"StringLiteral\";\n SyntaxKind[SyntaxKind[\"NumericLiteral\"] = 11] = \"NumericLiteral\";\n SyntaxKind[SyntaxKind[\"LineCommentTrivia\"] = 12] = \"LineCommentTrivia\";\n SyntaxKind[SyntaxKind[\"BlockCommentTrivia\"] = 13] = \"BlockCommentTrivia\";\n SyntaxKind[SyntaxKind[\"LineBreakTrivia\"] = 14] = \"LineBreakTrivia\";\n SyntaxKind[SyntaxKind[\"Trivia\"] = 15] = \"Trivia\";\n SyntaxKind[SyntaxKind[\"Unknown\"] = 16] = \"Unknown\";\n SyntaxKind[SyntaxKind[\"EOF\"] = 17] = \"EOF\";\n})(SyntaxKind || (SyntaxKind = {}));\n/**\n * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.\n */\nexport const getLocation = parser.getLocation;\n/**\n * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n * Therefore, always check the errors list to find out if the input was valid.\n */\nexport const parse = parser.parse;\n/**\n * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n */\nexport const parseTree = parser.parseTree;\n/**\n * Finds the node at the given path in a JSON DOM.\n */\nexport const findNodeAtLocation = parser.findNodeAtLocation;\n/**\n * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.\n */\nexport const findNodeAtOffset = parser.findNodeAtOffset;\n/**\n * Gets the JSON path of the given JSON DOM node\n */\nexport const getNodePath = parser.getNodePath;\n/**\n * Evaluates the JavaScript object of the given JSON DOM node\n */\nexport const getNodeValue = parser.getNodeValue;\n/**\n * Parses the given text and invokes the visitor functions for each object, array and literal reached.\n */\nexport const visit = parser.visit;\n/**\n * Takes JSON with JavaScript-style comments and remove\n * them. Optionally replaces every none-newline character\n * of comments with a replaceCharacter\n */\nexport const stripComments = parser.stripComments;\nexport var ParseErrorCode;\n(function (ParseErrorCode) {\n ParseErrorCode[ParseErrorCode[\"InvalidSymbol\"] = 1] = \"InvalidSymbol\";\n ParseErrorCode[ParseErrorCode[\"InvalidNumberFormat\"] = 2] = \"InvalidNumberFormat\";\n ParseErrorCode[ParseErrorCode[\"PropertyNameExpected\"] = 3] = \"PropertyNameExpected\";\n ParseErrorCode[ParseErrorCode[\"ValueExpected\"] = 4] = \"ValueExpected\";\n ParseErrorCode[ParseErrorCode[\"ColonExpected\"] = 5] = \"ColonExpected\";\n ParseErrorCode[ParseErrorCode[\"CommaExpected\"] = 6] = \"CommaExpected\";\n ParseErrorCode[ParseErrorCode[\"CloseBraceExpected\"] = 7] = \"CloseBraceExpected\";\n ParseErrorCode[ParseErrorCode[\"CloseBracketExpected\"] = 8] = \"CloseBracketExpected\";\n ParseErrorCode[ParseErrorCode[\"EndOfFileExpected\"] = 9] = \"EndOfFileExpected\";\n ParseErrorCode[ParseErrorCode[\"InvalidCommentToken\"] = 10] = \"InvalidCommentToken\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfComment\"] = 11] = \"UnexpectedEndOfComment\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfString\"] = 12] = \"UnexpectedEndOfString\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfNumber\"] = 13] = \"UnexpectedEndOfNumber\";\n ParseErrorCode[ParseErrorCode[\"InvalidUnicode\"] = 14] = \"InvalidUnicode\";\n ParseErrorCode[ParseErrorCode[\"InvalidEscapeCharacter\"] = 15] = \"InvalidEscapeCharacter\";\n ParseErrorCode[ParseErrorCode[\"InvalidCharacter\"] = 16] = \"InvalidCharacter\";\n})(ParseErrorCode || (ParseErrorCode = {}));\nexport function printParseErrorCode(code) {\n switch (code) {\n case 1 /* ParseErrorCode.InvalidSymbol */: return 'InvalidSymbol';\n case 2 /* ParseErrorCode.InvalidNumberFormat */: return 'InvalidNumberFormat';\n case 3 /* ParseErrorCode.PropertyNameExpected */: return 'PropertyNameExpected';\n case 4 /* ParseErrorCode.ValueExpected */: return 'ValueExpected';\n case 5 /* ParseErrorCode.ColonExpected */: return 'ColonExpected';\n case 6 /* ParseErrorCode.CommaExpected */: return 'CommaExpected';\n case 7 /* ParseErrorCode.CloseBraceExpected */: return 'CloseBraceExpected';\n case 8 /* ParseErrorCode.CloseBracketExpected */: return 'CloseBracketExpected';\n case 9 /* ParseErrorCode.EndOfFileExpected */: return 'EndOfFileExpected';\n case 10 /* ParseErrorCode.InvalidCommentToken */: return 'InvalidCommentToken';\n case 11 /* ParseErrorCode.UnexpectedEndOfComment */: return 'UnexpectedEndOfComment';\n case 12 /* ParseErrorCode.UnexpectedEndOfString */: return 'UnexpectedEndOfString';\n case 13 /* ParseErrorCode.UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber';\n case 14 /* ParseErrorCode.InvalidUnicode */: return 'InvalidUnicode';\n case 15 /* ParseErrorCode.InvalidEscapeCharacter */: return 'InvalidEscapeCharacter';\n case 16 /* ParseErrorCode.InvalidCharacter */: return 'InvalidCharacter';\n }\n return '<unknown ParseErrorCode>';\n}\n/**\n * Computes the edit operations needed to format a JSON document.\n *\n * @param documentText The input text\n * @param range The range to format or `undefined` to format the full content\n * @param options The formatting options\n * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\nexport function format(documentText, range, options) {\n return formatter.format(documentText, range, options);\n}\n/**\n * Computes the edit operations needed to modify a value in the JSON document.\n *\n * @param documentText The input text\n * @param path The path of the value to change. The path represents either to the document root, a property or an array item.\n * If the path points to an non-existing property or item, it will be created.\n * @param value The new value for the specified property or item. If the value is undefined,\n * the property or item will be removed.\n * @param options Options\n * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\nexport function modify(text, path, value, options) {\n return edit.setProperty(text, path, value, options);\n}\n/**\n * Applies edits to an input string.\n * @param text The input text\n * @param edits Edit operations following the format described in {@linkcode EditResult}.\n * @returns The text with the applied edits.\n * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}.\n */\nexport function applyEdits(text, edits) {\n let sortedEdits = edits.slice(0).sort((a, b) => {\n const diff = a.offset - b.offset;\n if (diff === 0) {\n return a.length - b.length;\n }\n return diff;\n });\n let lastModifiedOffset = text.length;\n for (let i = sortedEdits.length - 1; i >= 0; i--) {\n let e = sortedEdits[i];\n if (e.offset + e.length <= lastModifiedOffset) {\n text = edit.applyEdit(text, e);\n }\n else {\n throw new Error('Overlapping edit');\n }\n lastModifiedOffset = e.offset;\n }\n return text;\n}\n","/**\n * Surgical wrangler.jsonc helpers used by `baerly deploy` and the\n * `@gusto/create-baerly-storage` bolt-on flow. All functions are pure (no I/O) —\n * callers do the file read/write. Built on `jsonc-parser` so\n * comments and trailing commas survive round-trips.\n */\n\nimport { parse, modify, applyEdits, type ParseError, type FormattingOptions } from \"jsonc-parser\";\nimport { BaerlyError } from \"@baerly/protocol\";\n\n/**\n * Declared R2 binding extracted from a `wrangler.jsonc` source.\n * Subset of the wrangler schema — we only consume `binding` and\n * `bucket_name`, not the optional preview/jurisdiction fields.\n */\nexport interface R2BindingDeclaration {\n readonly binding: string;\n readonly bucket_name: string;\n}\n\n/**\n * Parse declared `r2_buckets[]` from a `wrangler.jsonc` source\n * string. Tolerates comments + trailing commas via `jsonc-parser`.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — malformed JSONC or\n * invalid `r2_buckets` shape.\n */\nexport const parseR2Bindings = (source: string): readonly R2BindingDeclaration[] => {\n const errors: ParseError[] = [];\n const obj = parse(source, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { r2_buckets?: unknown }\n | undefined;\n if (errors.length > 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `wrangler.jsonc parse error at offset ${errors[0]!.offset}: ${errors[0]!.error}`,\n );\n }\n if (obj === undefined || typeof obj !== \"object\") {\n throw new BaerlyError(\"InvalidConfig\", `wrangler.jsonc did not parse to an object`);\n }\n const buckets = obj.r2_buckets;\n if (buckets === undefined) {\n return [];\n }\n if (!Array.isArray(buckets)) {\n throw new BaerlyError(\"InvalidConfig\", `wrangler.jsonc: r2_buckets must be an array`);\n }\n const out: R2BindingDeclaration[] = [];\n for (const b of buckets) {\n if (b === null || typeof b !== \"object\") {\n throw new BaerlyError(\"InvalidConfig\", `wrangler.jsonc: r2_buckets entry must be an object`);\n }\n const entry = b as { binding?: unknown; bucket_name?: unknown };\n if (typeof entry.binding !== \"string\" || entry.binding.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `wrangler.jsonc: r2_buckets[].binding must be a non-empty string`,\n );\n }\n if (typeof entry.bucket_name !== \"string\" || entry.bucket_name.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `wrangler.jsonc: r2_buckets[].bucket_name must be a non-empty string`,\n );\n }\n out.push({ binding: entry.binding, bucket_name: entry.bucket_name });\n }\n return out;\n};\n\n/**\n * Input spec for a single R2 binding to add or verify in\n * `wrangler.jsonc`. Mirrors `R2BindingDeclaration` in shape but\n * represents caller intent rather than a parsed declaration.\n */\nexport interface R2BindingSpec {\n readonly binding: string;\n readonly bucket_name: string;\n}\n\n/**\n * Flat string→string map of `vars` entries to merge into\n * `wrangler.jsonc`. Existing keys are never overwritten (user wins).\n */\nexport interface VarsSpec {\n readonly [key: string]: string;\n}\n\n/**\n * Result returned by `patchWranglerJsonc`. `text` is the updated\n * JSONC source; `changes` is a human-readable summary of what was\n * added (empty when the file was already up to date).\n */\nexport interface PatchResult {\n readonly text: string;\n readonly changes: readonly string[];\n}\n\n/**\n * Read the `name` field from a `wrangler.jsonc` source string.\n * Returns `undefined` on malformed JSONC or when the field is absent.\n * Never throws — designed for caller-friendly inspection.\n */\nexport const readWranglerName = (source: string): string | undefined => {\n const errors: ParseError[] = [];\n const parsed = parse(source, errors, { allowTrailingComma: true }) as\n | { name?: unknown }\n | undefined;\n if (errors.length > 0 || typeof parsed?.name !== \"string\") {\n return undefined;\n }\n return parsed.name;\n};\n\n/**\n * Read the `main` field from a `wrangler.jsonc` source string.\n * Returns `undefined` on malformed JSONC or when the field is absent.\n * Never throws — designed for caller-friendly inspection.\n */\nexport const readWranglerMain = (source: string): string | undefined => {\n const errors: ParseError[] = [];\n const parsed = parse(source, errors, { allowTrailingComma: true }) as\n | { main?: unknown }\n | undefined;\n if (errors.length > 0 || typeof parsed?.main !== \"string\") {\n return undefined;\n }\n return parsed.main;\n};\n\n// Sniff the indent style of a JSONC source by scanning for the first\n// indented line and inspecting its leading whitespace. The stock\n// `pnpm create cloudflare` template uses tabs; older / hand-rolled\n// `wrangler.jsonc` files commonly use 2- or 4-space indents. Falls\n// back to 2-space when the file has no indented content (e.g. `{}`).\nconst detectIndent = (source: string): FormattingOptions => {\n for (const line of source.split(\"\\n\")) {\n if (line.length === 0 || line.startsWith(\"{\") || line.startsWith(\"}\")) {\n continue;\n }\n const first = line.charAt(0);\n if (first === \"\\t\") {\n return { insertSpaces: false, tabSize: 2, eol: \"\\n\" };\n }\n if (first === \" \") {\n let count = 0;\n while (count < line.length && line.charAt(count) === \" \") {\n count += 1;\n }\n return { insertSpaces: true, tabSize: count, eol: \"\\n\" };\n }\n }\n return { insertSpaces: true, tabSize: 2, eol: \"\\n\" };\n};\n\n/**\n * Idempotently patch a `wrangler.jsonc` source string:\n *\n * - Appends an R2 binding to `r2_buckets[]` unless an entry with\n * the same `binding` name already exists (user wins).\n * - Merges `vars` keys, skipping any key already present (user wins).\n *\n * Comments and trailing commas are preserved by `jsonc-parser`.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — malformed JSONC or\n * invalid `r2_buckets` / `vars` shape.\n */\nexport const patchWranglerJsonc = (\n source: string,\n binding: R2BindingSpec,\n vars: VarsSpec,\n): PatchResult => {\n const existingBindings = parseR2Bindings(source);\n\n const errors: ParseError[] = [];\n const entry = parse(source, errors, { allowTrailingComma: true }) as\n | { vars?: unknown }\n | undefined;\n\n const rawVars = entry?.vars;\n if (rawVars !== undefined) {\n if (typeof rawVars !== \"object\" || rawVars === null || Array.isArray(rawVars)) {\n throw new BaerlyError(\"InvalidConfig\", \"wrangler.jsonc: vars must be an object\");\n }\n }\n const existingVars = (rawVars ?? {}) as Record<string, unknown>;\n\n const formattingOptions = detectIndent(source);\n const changes: string[] = [];\n let text = source;\n\n const bindingAlreadyDeclared = existingBindings.some((b) => b.binding === binding.binding);\n if (!bindingAlreadyDeclared) {\n const edits = modify(text, [\"r2_buckets\", -1], binding, { formattingOptions });\n text = applyEdits(text, edits);\n changes.push(`added r2 binding ${binding.binding} → ${binding.bucket_name}`);\n }\n\n const addedVarKeys: string[] = [];\n for (const [key, value] of Object.entries(vars)) {\n if (!(key in existingVars)) {\n const edits = modify(text, [\"vars\", key], value, { formattingOptions });\n text = applyEdits(text, edits);\n addedVarKeys.push(key);\n }\n }\n if (addedVarKeys.length > 0) {\n changes.push(`merged vars: ${addedVarKeys.join(\", \")}`);\n }\n\n return { text, changes };\n};\n","/**\n * `baerly deploy --target=cloudflare` — one-command Cloudflare\n * Workers deploy.\n *\n * Behavior:\n * 1. Locate `wrangler.jsonc` at the package root.\n * 2. Sniff `wrangler deploy --help` for the `--x-provision` flag.\n * 3. When present, invoke\n * `wrangler deploy --x-provision --x-auto-create` and rely on\n * Wrangler to auto-create the declared R2 buckets.\n * 4. When absent, parse `wrangler.jsonc` for declared\n * `r2_buckets[]`, ensure each bucket exists (creating with\n * `wrangler r2 bucket create` when missing), then run\n * `wrangler deploy` without the experimental flag.\n * 5. Warn (non-fatal) on any `requiredSecret` not present in the\n * Wrangler-reported secret list.\n *\n * No `wrangler secret put` is invoked — that requires interactive\n * stdin and Wrangler is the authority on the user's secret store.\n * Missing secrets surface as actionable hints printed to stderr.\n *\n * Tests inject a {@link ProcessRunner} mock; production uses the\n * default `node:child_process.spawn`-backed implementation.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport type { AppConfig } from \"../config.ts\";\nimport { defaultRunner, type ProcessRunner } from \"../runner.ts\";\nimport {\n parseR2Bindings as parseR2BindingsFromSource,\n type R2BindingDeclaration,\n} from \"../wrangler-patch.ts\";\n\nexport type { ProcessRunner };\n\nexport type { R2BindingDeclaration };\n\n/** Path to `wrangler.jsonc` at the package root. */\nconst wranglerPathFor = (repoRoot: string): string => resolve(repoRoot, \"wrangler.jsonc\");\n\n/**\n * Parse the declared `r2_buckets[]` array from a `wrangler.jsonc`\n * file. Tolerates comments + trailing commas via `jsonc-parser`.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — file missing, parse\n * error, or any entry missing `binding` / `bucket_name`.\n */\nexport const parseR2Bindings = (wranglerPath: string): readonly R2BindingDeclaration[] => {\n if (!existsSync(wranglerPath)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly deploy: ${wranglerPath} missing. Expected wrangler.jsonc at the package root.`,\n );\n }\n return parseR2BindingsFromSource(readFileSync(wranglerPath, \"utf8\"));\n};\n\n/**\n * Walk the declared R2 bindings; for each, run `wrangler r2 bucket\n * info <name>` and, on non-zero exit, `wrangler r2 bucket create\n * <name>`. Used as the fallback when `wrangler --x-provision` is\n * unavailable, and directly invoked by `baerly doctor\n * --target=cloudflare --fix`.\n *\n * @throws BaerlyError code=\"NetworkError\" — bucket creation\n * reported a non-zero exit (Wrangler's own error already on\n * stderr).\n */\nexport const ensureBindings = async (\n runner: ProcessRunner,\n cwd: string,\n wranglerPath: string,\n): Promise<void> => {\n const declared = parseR2Bindings(wranglerPath);\n for (const { bucket_name } of declared) {\n const info = await runner.run(\"wrangler\", [\"r2\", \"bucket\", \"info\", bucket_name], cwd);\n if (info.code === 0) {\n continue;\n }\n process.stderr.write(`baerly deploy: creating R2 bucket ${bucket_name}\\n`);\n const created = await runner.run(\"wrangler\", [\"r2\", \"bucket\", \"create\", bucket_name], cwd);\n if (created.code !== 0) {\n throw new BaerlyError(\n \"NetworkError\",\n `baerly deploy: failed to create R2 bucket ${bucket_name} (exit ${created.code})`,\n );\n }\n }\n};\n\n/**\n * Best-effort secret check. `wrangler secret list` emits a JSON\n * array of `{ name, type }` when stdout is piped (Wrangler 4.x\n * default). We parse, diff against `required`, and print\n * actionable hints for each missing secret. Non-fatal — a missing\n * secret blocks the Verifier at runtime, not at deploy time.\n */\nconst warnOnMissingSecrets = async (\n runner: ProcessRunner,\n cwd: string,\n required: readonly string[],\n): Promise<void> => {\n const r = await runner.run(\"wrangler\", [\"secret\", \"list\"], cwd);\n if (r.code !== 0) {\n process.stderr.write(\"baerly deploy: could not list secrets; skipping check\\n\");\n return;\n }\n let configured: readonly string[];\n try {\n const parsed = JSON.parse(r.stdout) as unknown;\n if (!Array.isArray(parsed)) {\n return;\n }\n configured = parsed\n .map((s) =>\n s !== null && typeof s === \"object\" ? (s as { name?: unknown }).name : undefined,\n )\n .filter((n): n is string => typeof n === \"string\");\n } catch {\n return;\n }\n for (const name of required) {\n if (!configured.includes(name)) {\n process.stderr.write(\n `baerly deploy: secret ${name} is required but unset. ` +\n `Run: wrangler secret put ${name}\\n`,\n );\n }\n }\n};\n\n/**\n * Deploy a baerly app to Cloudflare Workers. Returns the integer\n * exit code from the underlying `wrangler deploy` invocation.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `wrangler.jsonc`\n * missing or unparseable.\n * @throws BaerlyError code=\"NetworkError\" — the fallback path\n * could not create a declared R2 bucket.\n */\nexport const deployCloudflare = async (\n config: AppConfig,\n opts: { readonly runner?: ProcessRunner; readonly cwd?: string } = {},\n): Promise<number> => {\n const runner = opts.runner ?? defaultRunner({ tee: true });\n const repoRoot = opts.cwd ?? config.repoRoot;\n const wranglerPath = wranglerPathFor(repoRoot);\n if (!existsSync(wranglerPath)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly deploy: ${wranglerPath} missing. Expected wrangler.jsonc at the package root.`,\n );\n }\n\n // Sniff Wrangler for --x-provision support.\n const help = await runner.run(\"wrangler\", [\"deploy\", \"--help\"], repoRoot);\n const hasXProvision = help.code === 0 && help.stdout.includes(\"--x-provision\");\n\n await warnOnMissingSecrets(runner, repoRoot, config.requiredSecrets ?? [\"SHARED_SECRET\"]);\n\n if (hasXProvision) {\n const r = await runner.run(\n \"wrangler\",\n [\"deploy\", \"--x-provision\", \"--x-auto-create\"],\n repoRoot,\n );\n return r.code;\n }\n\n // Fallback: provision via the doctor path then deploy.\n process.stderr.write(\n \"baerly deploy: wrangler --x-provision unavailable; falling back to manual provisioning\\n\",\n );\n await ensureBindings(runner, repoRoot, wranglerPath);\n const r = await runner.run(\"wrangler\", [\"deploy\"], repoRoot);\n return r.code;\n};\n"],"x_google_ignoreList":[1,2,3,4],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiCA,MAAa,iBAAiB,OAAmC,CAAC,MAAqB;CACrF,MAAM,MAAM,KAAK,QAAQ;CACzB,OAAO,EACL,MAAM,KAAK,MAAM,QACf,IAAI,SAAS,KAAK,QAAQ;EACxB,MAAM,QAAQ,MAAM,KAAK,MAAkB;GACzC;GACA,OAAO;IAAC;IAAW;IAAQ;GAAM;EACnC,CAAC;EACD,IAAI,SAAS;EACb,IAAI,SAAS;EACb,MAAM,QAAQ,GAAG,SAAS,MAAc;GACtC,UAAU,EAAE,SAAS,MAAM;GAC3B,IAAI,KACF,QAAQ,OAAO,MAAM,CAAC;EAE1B,CAAC;EACD,MAAM,QAAQ,GAAG,SAAS,MAAc;GACtC,UAAU,EAAE,SAAS,MAAM;GAC3B,IAAI,KACF,QAAQ,OAAO,MAAM,CAAC;EAE1B,CAAC;EACD,MAAM,GAAG,SAAS,GAAG;EACrB,MAAM,GAAG,UAAU,SAAS,IAAI;GAAE,MAAM,QAAQ;GAAG;GAAQ;EAAO,CAAC,CAAC;CACtE,CAAC,EACL;AACF;;;;;;;ACnDA,SAAgB,cAAc,MAAM,eAAe,OAAO;CACtD,MAAM,MAAM,KAAK;CACjB,IAAI,MAAM,GAAG,QAAQ,IAAI,cAAc,GAAG,QAAQ,IAA6B,aAAa,GAAG,kBAAkB,GAAG,uBAAuB,GAAG,2BAA2B,GAAG,YAAY;CACxL,SAAS,cAAc,OAAO,OAAO;EACjC,IAAI,SAAS;EACb,IAAI,QAAQ;EACZ,OAAO,SAAS,SAAS,CAAC,OAAO;GAC7B,IAAI,KAA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AIF,MAAM,OAAO,MAAM,OAAO,IAAI,YAAY,CAAC,UAAU,QAAQ,GAAG,QAAQ;CACxE,MAAM,gBAAgB,KAAK,SAAS,KAAK,KAAK,OAAO,SAAS,eAAe;CAE7E,MAAM,qBAAqB,QAAQ,UAAU,OAAO,mBAAmB,CAAC,eAAe,CAAC;CAExF,IAAI,eAMF,QAAO,MALS,OAAO,IACrB,YACA;EAAC;EAAU;EAAiB;CAAiB,GAC7C,QACF,GACS;CAIX,QAAQ,OAAO,MACb,0FACF;CACA,MAAM,eAAe,QAAQ,UAAU,YAAY;CAEnD,QAAO,MADS,OAAO,IAAI,YAAY,CAAC,QAAQ,GAAG,QAAQ,GAClD;AACX"}
|
package/dist/config-DVfDGyw1.js
DELETED
|
@@ -1,278 +0,0 @@
|
|
|
1
|
-
import { o as BaerlyError } from "./baerly.js";
|
|
2
|
-
import { readFile } from "node:fs/promises";
|
|
3
|
-
import { resolve } from "node:path";
|
|
4
|
-
import { existsSync } from "node:fs";
|
|
5
|
-
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
|
-
//#region ../protocol/src/constants.ts
|
|
7
|
-
/**
|
|
8
|
-
* Backoff (in milliseconds) inserted between LIST attempts when S3
|
|
9
|
-
* returns 429 (rate-limited).
|
|
10
|
-
*/
|
|
11
|
-
const RATE_LIMIT_BACKOFF_MILLIS = 1e3;
|
|
12
|
-
/**
|
|
13
|
-
* MIME type written for `current.json` PUTs. S3 round-trips this on
|
|
14
|
-
* subsequent GETs; useful for diagnostics when staring at a bucket
|
|
15
|
-
* via the AWS console.
|
|
16
|
-
*
|
|
17
|
-
* @see packages/protocol/src/coordination/current-json.ts
|
|
18
|
-
*/
|
|
19
|
-
const CURRENT_JSON_CONTENT_TYPE = "application/json";
|
|
20
|
-
/**
|
|
21
|
-
* MIME type written for `gc/pending.json` PUTs.
|
|
22
|
-
*
|
|
23
|
-
* @see packages/protocol/src/coordination/gc-pending.ts
|
|
24
|
-
*/
|
|
25
|
-
const GC_PENDING_CONTENT_TYPE = "application/json";
|
|
26
|
-
/**
|
|
27
|
-
* Default grace period between "marking" a key for GC and "sweeping"
|
|
28
|
-
* (deleting) it. 7 days, chosen to span the worst plausible writer-
|
|
29
|
-
* retry window (a paused-process writer that resumes hours later
|
|
30
|
-
* should still find its idempotency anchor on the bucket). The
|
|
31
|
-
* `runGc()` function accepts an override for tests.
|
|
32
|
-
*
|
|
33
|
-
* Why 7 days specifically:
|
|
34
|
-
* - **1 day is too aggressive for batch workloads.** Worker isolate
|
|
35
|
-
* scheduling pauses, cross-region replication lag, and
|
|
36
|
-
* {@link RATE_LIMIT_BACKOFF_MILLIS} retry cascades can plausibly
|
|
37
|
-
* exceed an hour under pathological conditions.
|
|
38
|
-
* - **30 days is conservative beyond the worst plausible pause.**
|
|
39
|
-
* Doubles `gc/pending.json` size at steady state and slows
|
|
40
|
-
* visibility into "did GC actually run?" by 4×.
|
|
41
|
-
* - **7 days spans the realistic upper bound** — long-running batch
|
|
42
|
-
* jobs, multi-region propagation delays, queue backlogs, and
|
|
43
|
-
* downstream outages the writer is retrying through. The protocol
|
|
44
|
-
* is unaffected by the choice of value within the [hours, weeks]
|
|
45
|
-
* range; this constant is the operator-tunable knob.
|
|
46
|
-
*
|
|
47
|
-
* Production code MUST NOT call `runGc` with `graceMillis` below the
|
|
48
|
-
* default outside maintenance windows — going below the longest
|
|
49
|
-
* plausible writer-retry latency risks deleting an anchor a writer
|
|
50
|
-
* is about to find on retry. Test code that sets `graceMillis: 0` is
|
|
51
|
-
* exercising the sweep path deliberately, not modelling production.
|
|
52
|
-
*
|
|
53
|
-
* @see packages/server/src/gc.ts
|
|
54
|
-
*/
|
|
55
|
-
const GC_GRACE_PERIOD_MILLIS = 10080 * 60 * 1e3;
|
|
56
|
-
/**
|
|
57
|
-
* Cap on candidates kept in `gc/pending.json` to bound the size of
|
|
58
|
-
* the file. The compactor marks at most this many candidates per
|
|
59
|
-
* pass; subsequent passes pick up the rest. Larger collections will
|
|
60
|
-
* lag GC by one pass per `GC_MAX_PENDING_CANDIDATES` orphans, which
|
|
61
|
-
* is acceptable.
|
|
62
|
-
*
|
|
63
|
-
* @see packages/server/src/gc.ts
|
|
64
|
-
*/
|
|
65
|
-
const GC_MAX_PENDING_CANDIDATES = 1e3;
|
|
66
|
-
/**
|
|
67
|
-
* Floor for the ratio denominator — avoid div-by-tiny on a fresh collection. Also
|
|
68
|
-
* sets the first-fold threshold: until a snapshot exists, fold fires at tail ≈ this.
|
|
69
|
-
*
|
|
70
|
-
* @see packages/server/src/maintenance.ts
|
|
71
|
-
*/
|
|
72
|
-
const MAINTENANCE_MIN_LIVE_BYTES = 64 * 1024;
|
|
73
|
-
/**
|
|
74
|
-
* SNAPSHOT-rebuild ceiling `C` (the unsliceable axis — Decision 3a), memory. Default sized
|
|
75
|
-
* ~5.5 ms under CF-free ~10 ms. Raise via BAERLY_MAINTENANCE_MAX_FOLD_BYTES on capable
|
|
76
|
-
* hosts. Auto-maintained snapshot ceiling S_max = C. NOT snapshot+tail (tail is sliced).
|
|
77
|
-
*
|
|
78
|
-
* @see docs/about/graduation.md
|
|
79
|
-
* @see packages/server/src/maintenance.ts
|
|
80
|
-
*/
|
|
81
|
-
const MAINTENANCE_MAX_FOLD_BYTES_DEFAULT = 512 * 1024;
|
|
82
|
-
/**
|
|
83
|
-
* SNAPSHOT-rebuild ceiling `E`, per-entry CPU axis: gates `snapshot_rows` (per-entry
|
|
84
|
-
* parse/merge/serialize is ~half of fold CPU and scales with ROW COUNT not bytes, VLDB 2021
|
|
85
|
-
* Sarkar — a tiny-doc snapshot can blow CPU under C). PROVISIONAL — calibrate via the
|
|
86
|
-
* Task 3 bench, pin in graduation.md.
|
|
87
|
-
*
|
|
88
|
-
* @see docs/about/graduation.md
|
|
89
|
-
* @see packages/server/src/maintenance.ts
|
|
90
|
-
*/
|
|
91
|
-
const MAINTENANCE_MAX_FOLD_ROWS = 2048;
|
|
92
|
-
/**
|
|
93
|
-
* Rate-limit the defer-warn off SHARED current.json.last_warned_seq (not per-isolate
|
|
94
|
-
* memory — CF recycles isolates). ~once per this many writes.
|
|
95
|
-
*
|
|
96
|
-
* @see packages/protocol/src/coordination/current-json.ts
|
|
97
|
-
* @see packages/server/src/maintenance.ts
|
|
98
|
-
*/
|
|
99
|
-
const MAINTENANCE_WARN_INTERVAL_WRITES = 1e3;
|
|
100
|
-
/**
|
|
101
|
-
* Canonical auth posture identifiers consumed by `BaerlyAppConfig.auth`,
|
|
102
|
-
* the adapter resolution path (`packages/adapter-cloudflare/src/worker.ts`,
|
|
103
|
-
* `packages/adapter-node/src/baerly-node.ts`), and `baerly doctor`.
|
|
104
|
-
*
|
|
105
|
-
* - `"none"` — no header check; pin every request to `config.tenant`.
|
|
106
|
-
* For local dev, intranet, CLI tools — contexts where the network
|
|
107
|
-
* seam itself is the trust boundary.
|
|
108
|
-
* - `"shared-secret"` — bearer-token check; reads `SHARED_SECRET` from
|
|
109
|
-
* the runtime env and pins every request to `config.tenant`.
|
|
110
|
-
*
|
|
111
|
-
* Custom verifiers (`cloudflareAccess`, `bearerJwt`, SigV4, …) bypass
|
|
112
|
-
* this enum — pass a `Verifier` to the adapter factory's `verifier:`
|
|
113
|
-
* option instead.
|
|
114
|
-
*/
|
|
115
|
-
const AUTH_CONFIG_VALUES = ["none", "shared-secret"];
|
|
116
|
-
/**
|
|
117
|
-
* Locked error wording for `auth: "shared-secret"` + missing env var.
|
|
118
|
-
* Same pinning rationale as {@link NO_AUTH_CONFIGURED_MESSAGE}.
|
|
119
|
-
*/
|
|
120
|
-
const SHARED_SECRET_MISSING_MESSAGE = "baerly: auth=\"shared-secret\" but SHARED_SECRET env is empty/unset. Cloudflare: `wrangler secret put SHARED_SECRET`, or add to .dev.vars for local dev. Node: set in process env.";
|
|
121
|
-
//#endregion
|
|
122
|
-
//#region src/config.ts
|
|
123
|
-
/**
|
|
124
|
-
* `baerly.config.ts` loader for `baerly deploy` / `baerly doctor`.
|
|
125
|
-
*
|
|
126
|
-
* Mirrors the shape of `BaerlyAppConfig` from `@gusto/baerly-storage/config`
|
|
127
|
-
* but lives in `@baerly/cli` so the validator/loader doesn't depend on
|
|
128
|
-
* the rolldown'd umbrella bundle. The scaffolder emits the config file;
|
|
129
|
-
* the CLI reads it. Both sides agree on the wire shape (informally —
|
|
130
|
-
* the duplication is small and intentional).
|
|
131
|
-
*
|
|
132
|
-
* Resolution order:
|
|
133
|
-
* 1. `<cwd>/baerly.config.ts`
|
|
134
|
-
* 2. `<cwd>/baerly.config.js`
|
|
135
|
-
* 3. `<cwd>/baerly.config.mjs`
|
|
136
|
-
* 4. `<cwd>/baerly.config.json`
|
|
137
|
-
*
|
|
138
|
-
* The `.ts` form requires the user to have a TS-aware Node entry
|
|
139
|
-
* point (`tsx`, `--experimental-strip-types`, or a build step that
|
|
140
|
-
* produced the `.js` alongside). If `import()` throws on the `.ts`
|
|
141
|
-
* file, we re-wrap as `InvalidConfig` with a hint pointing at the
|
|
142
|
-
* `.js` / `.json` fallbacks.
|
|
143
|
-
*/
|
|
144
|
-
const CONFIG_BASENAMES = [
|
|
145
|
-
"baerly.config.ts",
|
|
146
|
-
"baerly.config.js",
|
|
147
|
-
"baerly.config.mjs",
|
|
148
|
-
"baerly.config.json"
|
|
149
|
-
];
|
|
150
|
-
/**
|
|
151
|
-
* Locate the first `baerly.config.*` file under `cwd`. Returns the
|
|
152
|
-
* absolute path or `null` if none exists.
|
|
153
|
-
*
|
|
154
|
-
* Exported so the collection-aware loader (and future consumers) can
|
|
155
|
-
* reuse the same resolution order without re-implementing it.
|
|
156
|
-
*/
|
|
157
|
-
const locateConfig = (cwd) => {
|
|
158
|
-
for (const base of CONFIG_BASENAMES) {
|
|
159
|
-
const abs = resolve(cwd, base);
|
|
160
|
-
if (existsSync(abs)) return abs;
|
|
161
|
-
}
|
|
162
|
-
return null;
|
|
163
|
-
};
|
|
164
|
-
/**
|
|
165
|
-
* Load `baerly.config.{ts,js,mjs,json}` from `cwd` (defaults to
|
|
166
|
-
* `process.cwd()`). Validates the required fields and the
|
|
167
|
-
* locked-shape optionals; returns an `AppConfig` decorated with the
|
|
168
|
-
* `repoRoot` it was loaded from.
|
|
169
|
-
*
|
|
170
|
-
* @throws BaerlyError code="InvalidConfig" — file missing, default
|
|
171
|
-
* export missing, or any field has the wrong shape / type.
|
|
172
|
-
*/
|
|
173
|
-
const loadAppConfig = async (cwd = process.cwd()) => {
|
|
174
|
-
const cfgPath = locateConfig(cwd);
|
|
175
|
-
if (cfgPath === null) throw new BaerlyError("InvalidConfig", `baerly: no baerly.config.{ts,js,mjs,json} at ${cwd}. Are you in a baerly app directory?`);
|
|
176
|
-
let raw;
|
|
177
|
-
if (cfgPath.endsWith(".json")) {
|
|
178
|
-
let text;
|
|
179
|
-
try {
|
|
180
|
-
text = await readFile(cfgPath, "utf8");
|
|
181
|
-
} catch (error) {
|
|
182
|
-
throw new BaerlyError("InvalidConfig", `baerly: failed to read ${cfgPath}: ${error.message}`, error);
|
|
183
|
-
}
|
|
184
|
-
try {
|
|
185
|
-
raw = JSON.parse(text);
|
|
186
|
-
} catch (error) {
|
|
187
|
-
throw new BaerlyError("InvalidConfig", `baerly: failed to parse ${cfgPath}: ${error.message}`, error);
|
|
188
|
-
}
|
|
189
|
-
} else {
|
|
190
|
-
let mod;
|
|
191
|
-
try {
|
|
192
|
-
mod = await import(pathToFileURL(cfgPath).href);
|
|
193
|
-
} catch (error) {
|
|
194
|
-
const hint = cfgPath.endsWith(".ts") ? " (Node cannot import .ts directly without a TS loader — point at the compiled .js or use a .json config)" : "";
|
|
195
|
-
throw new BaerlyError("InvalidConfig", `baerly: failed to load ${cfgPath}: ${error.message}${hint}`, error);
|
|
196
|
-
}
|
|
197
|
-
raw = mod.default;
|
|
198
|
-
}
|
|
199
|
-
if (raw === void 0 || typeof raw !== "object" || raw === null) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath} must default-export a BaerlyAppConfig object`);
|
|
200
|
-
const obj = raw;
|
|
201
|
-
const app = obj["app"];
|
|
202
|
-
const tenant = obj["tenant"];
|
|
203
|
-
const target = obj["target"];
|
|
204
|
-
if (typeof app !== "string" || app.length === 0) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`app\` must be a non-empty string`);
|
|
205
|
-
if (typeof tenant !== "string" || tenant.length === 0) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`tenant\` must be a non-empty string`);
|
|
206
|
-
if (target !== "cloudflare" && target !== "node") throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`target\` must be "cloudflare" or "node" (got ${JSON.stringify(target)})`);
|
|
207
|
-
const authRaw = obj["auth"];
|
|
208
|
-
if (typeof authRaw !== "string" || !AUTH_CONFIG_VALUES.includes(authRaw)) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`auth\` is required and must be one of ${JSON.stringify(AUTH_CONFIG_VALUES)} (got ${JSON.stringify(authRaw)})`);
|
|
209
|
-
const auth = authRaw;
|
|
210
|
-
const domainRaw = obj["domain"];
|
|
211
|
-
if (domainRaw !== void 0 && typeof domainRaw !== "string") throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`domain\` must be a string when set`);
|
|
212
|
-
const secretsRaw = obj["requiredSecrets"];
|
|
213
|
-
let requiredSecrets;
|
|
214
|
-
if (secretsRaw !== void 0) {
|
|
215
|
-
if (!Array.isArray(secretsRaw) || !secretsRaw.every((s) => typeof s === "string")) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`requiredSecrets\` must be an array of strings`);
|
|
216
|
-
requiredSecrets = secretsRaw;
|
|
217
|
-
}
|
|
218
|
-
const cfaRaw = obj["cloudflareAccess"];
|
|
219
|
-
let cloudflareAccess;
|
|
220
|
-
if (cfaRaw !== void 0) {
|
|
221
|
-
if (typeof cfaRaw !== "object" || cfaRaw === null) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`cloudflareAccess\` must be an object when set`);
|
|
222
|
-
const cfa = cfaRaw;
|
|
223
|
-
const td = cfa["teamDomain"];
|
|
224
|
-
const aud = cfa["audienceTag"];
|
|
225
|
-
if (typeof td !== "string" || td.length === 0) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`cloudflareAccess.teamDomain\` must be a non-empty string`);
|
|
226
|
-
if (typeof aud !== "string" || aud.length === 0) throw new BaerlyError("InvalidConfig", `baerly: ${cfgPath}: \`cloudflareAccess.audienceTag\` must be a non-empty string`);
|
|
227
|
-
cloudflareAccess = {
|
|
228
|
-
teamDomain: td,
|
|
229
|
-
audienceTag: aud
|
|
230
|
-
};
|
|
231
|
-
}
|
|
232
|
-
return {
|
|
233
|
-
app,
|
|
234
|
-
tenant,
|
|
235
|
-
target,
|
|
236
|
-
auth,
|
|
237
|
-
...domainRaw !== void 0 && { domain: domainRaw },
|
|
238
|
-
...requiredSecrets !== void 0 && { requiredSecrets },
|
|
239
|
-
...cloudflareAccess !== void 0 && { cloudflareAccess },
|
|
240
|
-
repoRoot: cwd
|
|
241
|
-
};
|
|
242
|
-
};
|
|
243
|
-
/**
|
|
244
|
-
* Load the declared `IndexDefinition[]` for a single collection from a
|
|
245
|
-
* `baerly.config.{js,mjs,json}`. Used by `baerly inspect` (key-count
|
|
246
|
-
* probes) and `baerly admin rebuild-index` (resolving the `on` field).
|
|
247
|
-
*
|
|
248
|
-
* `.ts` configs are rejected — Node can't `import` them without a TS
|
|
249
|
-
* loader; point at the compiled `.js` output instead.
|
|
250
|
-
*
|
|
251
|
-
* `commandName` is woven into thrown error messages so the operator
|
|
252
|
-
* sees the calling command name in the prefix.
|
|
253
|
-
*
|
|
254
|
-
* @throws BaerlyError code="InvalidConfig" — `.ts` extension, JSON
|
|
255
|
-
* parse error, missing default export, or missing
|
|
256
|
-
* `collections[collection]`.
|
|
257
|
-
*/
|
|
258
|
-
const loadCollectionIndexes = async (configPath, collection, commandName) => {
|
|
259
|
-
if (configPath.endsWith(".ts")) throw new BaerlyError("InvalidConfig", `${commandName}: --config must point at compiled JS / JSON (got .ts: ${JSON.stringify(configPath)})`);
|
|
260
|
-
let cfg;
|
|
261
|
-
if (configPath.endsWith(".json")) {
|
|
262
|
-
const text = await readFile(configPath, "utf8");
|
|
263
|
-
try {
|
|
264
|
-
cfg = JSON.parse(text);
|
|
265
|
-
} catch (error) {
|
|
266
|
-
throw new BaerlyError("InvalidConfig", `${commandName}: --config JSON parse error in ${JSON.stringify(configPath)}: ${error.message}`);
|
|
267
|
-
}
|
|
268
|
-
} else {
|
|
269
|
-
const mod = await import(pathToFileURL(configPath.startsWith("file://") ? fileURLToPath(configPath) : resolve(configPath)).href);
|
|
270
|
-
if (mod.default === void 0) throw new BaerlyError("InvalidConfig", `${commandName}: --config ${JSON.stringify(configPath)} has no default export`);
|
|
271
|
-
cfg = mod.default;
|
|
272
|
-
}
|
|
273
|
-
return cfg.collections?.[collection]?.indexes ?? [];
|
|
274
|
-
};
|
|
275
|
-
//#endregion
|
|
276
|
-
export { GC_MAX_PENDING_CANDIDATES as a, MAINTENANCE_MAX_FOLD_ROWS as c, RATE_LIMIT_BACKOFF_MILLIS as d, SHARED_SECRET_MISSING_MESSAGE as f, GC_GRACE_PERIOD_MILLIS as i, MAINTENANCE_MIN_LIVE_BYTES as l, loadCollectionIndexes as n, GC_PENDING_CONTENT_TYPE as o, CURRENT_JSON_CONTENT_TYPE as r, MAINTENANCE_MAX_FOLD_BYTES_DEFAULT as s, loadAppConfig as t, MAINTENANCE_WARN_INTERVAL_WRITES as u };
|
|
277
|
-
|
|
278
|
-
//# sourceMappingURL=config-DVfDGyw1.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"config-DVfDGyw1.js","names":[],"sources":["../packages/protocol/src/constants.ts","../packages/cli/src/config.ts"],"sourcesContent":["/**\n * Half-window (in milliseconds) within which a `LogEntry`'s embedded\n * `commit_ts` must agree with wall-clock time for downstream consumers\n * to accept the entry as causally ordered. Bound on tolerated\n * client/server clock skew across the protocol.\n *\n * 5 s is the protocol's tolerance for client/server clock skew.\n * Tightening this can cause spurious rejections on machines that\n * haven't synced NTP; loosening it widens the window during which\n * causal ordering can be disturbed by skew.\n *\n * @see docs/spec/sync-protocol.md\n * @see packages/protocol/src/storage/types.ts (`Storage` JSDoc)\n */\nexport const LAG_WINDOW_MILLIS: number = 5000;\n\n/**\n * Bit width of the base-32 timestamp prefix encoded into every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`, minted in\n * `Writer.commit`). 42 bits gives ~139 years of millisecond\n * precision, which is enough for the protocol's lifetime.\n *\n * Changing this is a protocol-breaking change — it would re-shape\n * every emitted LSN.\n *\n * @see packages/protocol/src/time.ts (`timestamp`)\n * @see packages/server/src/writer.ts (`Writer.commit`)\n * @see docs/spec/sync-protocol.md\n */\nexport const TIMESTAMP_BIT_WIDTH: number = 42;\n\n/**\n * Length of the random-prefix `session` segment embedded in every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`). 6 hex chars\n * from `crypto.randomUUID()` give 16⁶ ≈ 1.7 × 10⁷ distinct sessions;\n * birthday-collision rate at N=100 is ~3 × 10⁻⁴, comfortably below\n * the 1 % bound asserted in `tests/regressions.test.ts`. Collisions\n * within a single commit's writer set are also disambiguated by the\n * trailing `<seq>` counter.\n *\n * @see packages/server/src/writer.ts (`Writer.commit` —\n * `session = uuid().slice(0, SESSION_ID_LENGTH)`)\n */\nexport const SESSION_ID_LENGTH: number = 6;\n\n/**\n * Maximum attempts `S3HttpStorage.list` will make per page when the\n * server replies 429 (rate-limited). After this many in a row, it\n * gives up with `NetworkError`. Separate from the inner transient-\n * failure budget so a single hot page can't burn the whole retry\n * allowance.\n */\nexport const LIST_OBJECT_MAX_RETRIES: number = 10;\n\n/**\n * Backoff (in milliseconds) inserted between LIST attempts when S3\n * returns 429 (rate-limited).\n */\nexport const RATE_LIMIT_BACKOFF_MILLIS: number = 1000;\n\n/**\n * Upper clamp on a server-provided `Retry-After` hint, in seconds.\n * RFC 7231 §7.1.3 allows arbitrary delta-seconds or HTTP-dates, but a\n * client that blindly honours a multi-hour hint hands a misbehaving\n * proxy a denial-of-service primitive. 60s covers any plausible S3-\n * compatible throttle while keeping the worst-case bounded.\n *\n * @see packages/protocol/src/storage/s3-http.ts (`parseRetryAfter`)\n */\nexport const RETRY_AFTER_MAX_SECONDS: number = 60;\n\n/**\n * Default retry budget for `S3HttpStorage.retry` (the wrapper around\n * each of the four `Storage` methods). Bounded so that permanent\n * failures (CORS misconfig, NXDOMAIN, persistent 5xx) surface to\n * callers as rejected promises instead of retrying forever and\n * leaving `Writer.commit()` permanently pending.\n *\n * 8 attempts at the existing 100ms→×1.5→10s schedule covers ~30s of\n * transient turbulence, which is enough to ride out a leader election\n * or a brief network blip without papering over a real outage.\n */\nexport const S3_REQUEST_MAX_RETRIES: number = 8;\n\n/**\n * Maximum concurrent log-entry GETs issued by a single `walkLogRange`\n * call. Bounds Class-B fan-out per read and per CAS attempt — without\n * a bound, a reader on a collection whose compactor has fallen behind\n * fans out one GET per live-tail entry (typically 50-100 on the free-\n * tier profile), and a contended writer multiplies that by the CAS\n * retry budget ({@link S3_REQUEST_MAX_RETRIES}).\n *\n * 16 keeps the worst-case under retry to `16 * 8 = 128` concurrent\n * GETs — comfortably under the Workers subrequest cap (50 concurrent\n * / 1000 total) and leaving headroom for the writer's content / index\n * / log / CAS PUTs sharing the same isolate.\n *\n * @see packages/server/src/log-walk.ts (`walkLogRange`)\n */\nexport const MAX_PARALLEL_LOG_READS: number = 16;\n\n/**\n * Current major version of the `current.json` control-object schema.\n * Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `CurrentJson` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_SCHEMA_VERSION = 2 as const;\n\n/**\n * MIME type written for `current.json` PUTs. S3 round-trips this on\n * subsequent GETs; useful for diagnostics when staring at a bucket\n * via the AWS console.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_CONTENT_TYPE: string = \"application/json\";\n\n/**\n * Current major version of the `gc/pending.json` control-object\n * schema. Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `GcPending` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_SCHEMA_VERSION = 1 as const;\n\n/**\n * MIME type written for `gc/pending.json` PUTs.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_CONTENT_TYPE: string = \"application/json\";\n\n/**\n * Default grace period between \"marking\" a key for GC and \"sweeping\"\n * (deleting) it. 7 days, chosen to span the worst plausible writer-\n * retry window (a paused-process writer that resumes hours later\n * should still find its idempotency anchor on the bucket). The\n * `runGc()` function accepts an override for tests.\n *\n * Why 7 days specifically:\n * - **1 day is too aggressive for batch workloads.** Worker isolate\n * scheduling pauses, cross-region replication lag, and\n * {@link RATE_LIMIT_BACKOFF_MILLIS} retry cascades can plausibly\n * exceed an hour under pathological conditions.\n * - **30 days is conservative beyond the worst plausible pause.**\n * Doubles `gc/pending.json` size at steady state and slows\n * visibility into \"did GC actually run?\" by 4×.\n * - **7 days spans the realistic upper bound** — long-running batch\n * jobs, multi-region propagation delays, queue backlogs, and\n * downstream outages the writer is retrying through. The protocol\n * is unaffected by the choice of value within the [hours, weeks]\n * range; this constant is the operator-tunable knob.\n *\n * Production code MUST NOT call `runGc` with `graceMillis` below the\n * default outside maintenance windows — going below the longest\n * plausible writer-retry latency risks deleting an anchor a writer\n * is about to find on retry. Test code that sets `graceMillis: 0` is\n * exercising the sweep path deliberately, not modelling production.\n *\n * @see packages/server/src/gc.ts\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const GC_GRACE_PERIOD_MILLIS: number = 7 * 24 * 60 * 60 * 1000;\n\n/**\n * Cap on candidates kept in `gc/pending.json` to bound the size of\n * the file. The compactor marks at most this many candidates per\n * pass; subsequent passes pick up the rest. Larger collections will\n * lag GC by one pass per `GC_MAX_PENDING_CANDIDATES` orphans, which\n * is acceptable.\n *\n * @see packages/server/src/gc.ts\n */\nexport const GC_MAX_PENDING_CANDIDATES: number = 1000;\n\n/**\n * Fold-trigger ratio: fold fires at tail ≥ R×snapshot. Pure READ-AMP / fold-frequency\n * knob — with the ceiling on the snapshot axis (Decision 3a, tail sliced) the\n * auto-maintained snapshot ceiling is S_max = C, NOT C/(1+R). R=1.0 caps steady-state\n * read-amp at ~2× and keeps compaction write-amp (≈1+1/R) moderate. See\n * docs/about/graduation.md for the derivation.\n *\n * @see docs/about/graduation.md\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_TARGET_RATIO: number = 1;\n\n/**\n * Floor for the ratio denominator — avoid div-by-tiny on a fresh collection. Also\n * sets the first-fold threshold: until a snapshot exists, fold fires at tail ≈ this.\n *\n * @see packages/server/src/maintenance.ts\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const MAINTENANCE_MIN_LIVE_BYTES: number = 64 * 1024;\n\n/**\n * Per-tick GC budget — these are DEFAULTS (= the most-constrained tier, CF free, reusing\n * the TESTED `CLOUDFLARE_FREE_TIER` values in maintenance.ts / maintenance.budget.test.ts).\n * The adapter THREADS per-tier overrides into the context (§8.4); Node/CF-paid raise them.\n * NOT universal constants — a Node-sized value here would silently kill every CF-free fold\n * (round-4 Tier-1). gc pass ≈ 6 + maxMarks + maxSweeps subrequests (both GET/DELETE the\n * bucket — §3.1). Cadence is BOUNDARY-CROSSING (§3.1), not modulo.\n *\n * @see packages/server/src/maintenance.ts\n * @see packages/server/src/maintenance.budget.test.ts\n */\nexport const WRITE_TICK_GC_INTERVAL: number = 4; // tuned so maxSweeps/interval ≥ p (§7.1)\n\n/**\n * Fold-starvation guard (critique A): on `phasesPerTick:\"single\"`, every Nth GC-interval is a\n * HARD GC boundary the fold may NOT preempt, so a long fold-heavy drain can't starve GC to zero.\n * Stateless (seq-derived) — no per-isolate preemption counter (CF recycles isolates). At 4 a\n * sustained drain still yields ~1 GC tick per 4 GC-intervals.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const GC_STARVATION_GUARD: number = 4;\n\n/**\n * Maximum GC marks per write-tick pass (M in 6+M+S; GETs the live tail to hash).\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_GC_MAX_MARKS: number = 20;\n\n/**\n * Maximum GC sweeps per write-tick pass (S in 6+M+S; DELETE subrequests).\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_GC_MAX_SWEEPS: number = 10;\n\n/**\n * Per-pass tail SLICE default — compact()'s maxEntriesPerRun. Fold ≤ this+3 subrequests, so\n * a large tail drains incrementally over write-ticks (Decision 3). Adapter-overridable.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_FOLD_ENTRIES_PER_PASS: number = 20;\n\n/**\n * compact()'s minEntriesToCompact, set EXPLICITLY by the runner so it agrees with Gate 1\n * rather than inheriting compact()'s silent default 100 (which would contradict the 64 KB\n * first-fold story — round-4 Tier-3). Adapter-overridable; CF-free value.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_MIN_ENTRIES_TO_COMPACT: number = 50;\n\n/**\n * Node-tier write-tick maintenance caps — a MODERATE multiple of the CF-free `WRITE_TICK_*`\n * defaults, threaded into the per-request observability context by `baerlyNode` /\n * `createFetchHandler` (§8.4). Node v1 runs maintenance INLINE on the commit path (no\n * `waitUntil`), so the cap is NOT the CF subrequest wall — it's the worst-case single-write\n * added latency. A maintenance tick only fires on a ratio/boundary trip (rare), and when it\n * does it costs ~`maxFoldEntriesPerPass` + (6 + `gcMaxMarks` + `gcMaxSweeps`) storage\n * round-trips against a co-located S3/R2 — sub-second on the occasional boundary write at a\n * 10× multiple. These are deliberately BOUNDED (10× CF-free), NOT unbounded: the deleted\n * scheduled full-tail sweep folded the entire live tail in one shot, which a 100× multiple here\n * would reintroduce as multi-second commit stalls. Raise the snapshot ceiling separately via\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`; these caps slice the per-pass work, not the ceiling.\n *\n * @see packages/adapter-node/src/server.ts\n * @see packages/server/src/maintenance.ts\n * @see docs/about/graduation.md\n */\nexport const NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS: number = 200;\n\n/** Node-tier GC marks per pass (M in 6+M+S). 10× CF-free. @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS} */\nexport const NODE_MAINTENANCE_GC_MAX_MARKS: number = 200;\n\n/** Node-tier GC sweeps per pass (S in 6+M+S). 10× CF-free. @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS} */\nexport const NODE_MAINTENANCE_GC_MAX_SWEEPS: number = 100;\n\n/**\n * Node-tier GC cadence (boundary-crossing). Shorter than the CF-free `WRITE_TICK_GC_INTERVAL`\n * (4) so the per-write sweep budget keeps up: `gcMaxSweeps / gcInterval = 100 / 2 = 50`\n * comfortably clears the garbage-per-write rate `p` (the `maxSweeps/interval ≥ p` invariant,\n * §7.1) with a wide margin.\n *\n * @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS}\n */\nexport const NODE_MAINTENANCE_GC_INTERVAL: number = 2;\n\n/**\n * SNAPSHOT-rebuild ceiling `C` (the unsliceable axis — Decision 3a), memory. Default sized\n * ~5.5 ms under CF-free ~10 ms. Raise via BAERLY_MAINTENANCE_MAX_FOLD_BYTES on capable\n * hosts. Auto-maintained snapshot ceiling S_max = C. NOT snapshot+tail (tail is sliced).\n *\n * @see docs/about/graduation.md\n * @see packages/server/src/maintenance.ts\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const MAINTENANCE_MAX_FOLD_BYTES_DEFAULT: number = 512 * 1024;\n\n/**\n * The largest snapshot a Cloudflare **free-tier** isolate can safely\n * rebuild in ONE fold under the ~10 ms CPU budget. This is the WARN\n * THRESHOLD, not a runtime cap: an operator who raises\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` ABOVE this value on a free Worker\n * risks a snapshot rebuild that exceeds the ~10 ms CPU limit and gets\n * CPU-killed MID-REBUILD — the CAS never lands, so the fold silently\n * never advances `log_seq_start` and the tail grows unbounded.\n *\n * Sized at 2× {@link MAINTENANCE_MAX_FOLD_BYTES_DEFAULT}. The default\n * (512 KiB) rebuilds in ~5.5 ms under the CF-free ~10 ms budget\n * (constants.ts default JSDoc); linear-extrapolating, ~1 MiB is the\n * point where one-shot rebuild fills the budget with little margin, so\n * anything strictly larger is no longer free-tier-safe. On CF **paid**\n * (raised CPU limits), Node, or once §11 chunked snapshots land, a\n * larger ceiling is fine — hence this is a one-time `console.warn` at\n * handler init, NOT a hard rejection.\n *\n * @see packages/adapter-cloudflare/src/worker.ts\n * @see packages/server/src/maintenance.ts\n * @see docs/about/graduation.md\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const CF_FREE_MAX_SAFE_FOLD_BYTES: number = 1024 * 1024;\n\n/**\n * SNAPSHOT-rebuild ceiling `E`, per-entry CPU axis: gates `snapshot_rows` (per-entry\n * parse/merge/serialize is ~half of fold CPU and scales with ROW COUNT not bytes, VLDB 2021\n * Sarkar — a tiny-doc snapshot can blow CPU under C). PROVISIONAL — calibrate via the\n * Task 3 bench, pin in graduation.md.\n *\n * @see docs/about/graduation.md\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_MAX_FOLD_ROWS: number = 2048;\n\n/**\n * Rate-limit the defer-warn off SHARED current.json.last_warned_seq (not per-isolate\n * memory — CF recycles isolates). ~once per this many writes.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_WARN_INTERVAL_WRITES: number = 1000;\n\n/**\n * Placeholder for `CurrentJson.snapshot === null` in the\n * `_meta.manifest_pointer` cursor emitted on read responses. The\n * wire format is `\"<snapshot>@<next_seq>\"`, and `null` snapshots\n * serialise as this literal so the cursor is never empty and stays\n * byte-stable when destructured by operators.\n *\n * @see packages/server/src/contract.ts (HttpOkMeta)\n */\nexport const MANIFEST_POINTER_EMPTY_SNAPSHOT: string = \"none\";\n\n/**\n * Keys that must never propagate through {@link merge}: assigning to\n * them on a plain object pollutes the prototype chain. The literal\n * `{ __proto__: ... }` syntax is a prototype-setter (not an own key)\n * and bypasses `Object.keys`, but `JSON.parse('{\"__proto__\":...}')`\n * produces a real own property — which is exactly how a malicious\n * HTTP PATCH body would arrive on the wire.\n *\n * Lifted to a constant so every iteration path that touches a\n * caller-supplied object can re-use the same defence without\n * duplicating the keyword list.\n *\n * @see packages/protocol/src/json.ts (merge)\n * @see docs/spec/json-merge-patch.md\n */\nexport const FORBIDDEN_MERGE_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/**\n * Architecturally-enforced ceiling: storage ops per logical write.\n *\n * Three Class A ops: PUT content, PUT log entry, CAS-advance\n * `current.json`. The cost-model page derives the free-tier write\n * budget from this multiplier; the phase-5 end-to-end test asserts it\n * at CI time. Changing this constant is a cost-model-breaking change.\n *\n * @see docs/about/cost-model.md §\"Cost ceiling\"\n * @see tests/integration/phase5-end-to-end.test.ts\n */\nexport const STORAGE_OPS_PER_LOGICAL_WRITE: number = 3;\n\n/**\n * Canonical auth posture identifiers consumed by `BaerlyAppConfig.auth`,\n * the adapter resolution path (`packages/adapter-cloudflare/src/worker.ts`,\n * `packages/adapter-node/src/baerly-node.ts`), and `baerly doctor`.\n *\n * - `\"none\"` — no header check; pin every request to `config.tenant`.\n * For local dev, intranet, CLI tools — contexts where the network\n * seam itself is the trust boundary.\n * - `\"shared-secret\"` — bearer-token check; reads `SHARED_SECRET` from\n * the runtime env and pins every request to `config.tenant`.\n *\n * Custom verifiers (`cloudflareAccess`, `bearerJwt`, SigV4, …) bypass\n * this enum — pass a `Verifier` to the adapter factory's `verifier:`\n * option instead.\n */\nexport const AUTH_CONFIG_VALUES = [\"none\", \"shared-secret\"] as const;\n\n/**\n * Locked error wording for the \"no auth configured\" failure mode. The\n * adapter throws this when neither `config.auth` nor `verifier:`\n * resolves a real `Verifier`. Pinned via a regression test so future\n * refactors do not drift the operator-facing wording.\n *\n * Consumed by:\n * - `packages/adapter-cloudflare/src/worker.ts` (first-fetch throw)\n * - `packages/adapter-node/src/server.ts` (first-fetch throw)\n * - `packages/cli/src/doctor/cloudflare.ts` (FAIL finding mirrors it)\n */\nexport const NO_AUTH_CONFIGURED_MESSAGE: string =\n 'baerly: no auth configured. Set `auth` in baerly.config.ts (\"none\", \"shared-secret\") or pass `verifier` on the adapter factory.';\n\n/**\n * Locked error wording for `auth: \"shared-secret\"` + missing env var.\n * Same pinning rationale as {@link NO_AUTH_CONFIGURED_MESSAGE}.\n */\nexport const SHARED_SECRET_MISSING_MESSAGE: string =\n 'baerly: auth=\"shared-secret\" but SHARED_SECRET env is empty/unset. Cloudflare: `wrangler secret put SHARED_SECRET`, or add to .dev.vars for local dev. Node: set in process env.';\n","/**\n * `baerly.config.ts` loader for `baerly deploy` / `baerly doctor`.\n *\n * Mirrors the shape of `BaerlyAppConfig` from `@gusto/baerly-storage/config`\n * but lives in `@baerly/cli` so the validator/loader doesn't depend on\n * the rolldown'd umbrella bundle. The scaffolder emits the config file;\n * the CLI reads it. Both sides agree on the wire shape (informally —\n * the duplication is small and intentional).\n *\n * Resolution order:\n * 1. `<cwd>/baerly.config.ts`\n * 2. `<cwd>/baerly.config.js`\n * 3. `<cwd>/baerly.config.mjs`\n * 4. `<cwd>/baerly.config.json`\n *\n * The `.ts` form requires the user to have a TS-aware Node entry\n * point (`tsx`, `--experimental-strip-types`, or a build step that\n * produced the `.js` alongside). If `import()` throws on the `.ts`\n * file, we re-wrap as `InvalidConfig` with a hint pointing at the\n * `.js` / `.json` fallbacks.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport {\n AUTH_CONFIG_VALUES,\n type AuthConfig,\n type BaerlyConfig,\n BaerlyError,\n type IndexDefinition,\n} from \"@baerly/protocol\";\n\nexport interface AppConfig {\n readonly app: string;\n readonly tenant: string;\n readonly target: \"cloudflare\" | \"node\";\n /**\n * Required. See `AuthConfig` for the per-value semantics. The loader\n * throws `BaerlyError(\"InvalidConfig\", ...)` when `auth` is missing or\n * not a member of `AUTH_CONFIG_VALUES`.\n */\n readonly auth: AuthConfig;\n readonly domain?: string;\n readonly requiredSecrets?: readonly string[];\n readonly cloudflareAccess?: {\n readonly teamDomain: string;\n readonly audienceTag: string;\n };\n /** Absolute path to the repo root that contained the config. */\n readonly repoRoot: string;\n}\n\nconst CONFIG_BASENAMES: readonly string[] = [\n \"baerly.config.ts\",\n \"baerly.config.js\",\n \"baerly.config.mjs\",\n \"baerly.config.json\",\n];\n\n/**\n * Locate the first `baerly.config.*` file under `cwd`. Returns the\n * absolute path or `null` if none exists.\n *\n * Exported so the collection-aware loader (and future consumers) can\n * reuse the same resolution order without re-implementing it.\n */\nexport const locateConfig = (cwd: string): string | null => {\n for (const base of CONFIG_BASENAMES) {\n const abs = resolve(cwd, base);\n if (existsSync(abs)) {\n return abs;\n }\n }\n return null;\n};\n\n/**\n * Load `baerly.config.{ts,js,mjs,json}` from `cwd` (defaults to\n * `process.cwd()`). Validates the required fields and the\n * locked-shape optionals; returns an `AppConfig` decorated with the\n * `repoRoot` it was loaded from.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — file missing, default\n * export missing, or any field has the wrong shape / type.\n */\nexport const loadAppConfig = async (cwd: string = process.cwd()): Promise<AppConfig> => {\n const cfgPath = locateConfig(cwd);\n if (cfgPath === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: no baerly.config.{ts,js,mjs,json} at ${cwd}. Are you in a baerly app directory?`,\n );\n }\n\n let raw: unknown;\n if (cfgPath.endsWith(\".json\")) {\n let text: string;\n try {\n text = await readFile(cfgPath, \"utf8\");\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to read ${cfgPath}: ${(error as Error).message}`,\n error,\n );\n }\n try {\n raw = JSON.parse(text) as unknown;\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to parse ${cfgPath}: ${(error as Error).message}`,\n error,\n );\n }\n } else {\n let mod: { default?: unknown };\n try {\n mod = (await import(pathToFileURL(cfgPath).href)) as { default?: unknown };\n } catch (error) {\n const hint = cfgPath.endsWith(\".ts\")\n ? \" (Node cannot import .ts directly without a TS loader — point at the compiled .js or use a .json config)\"\n : \"\";\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to load ${cfgPath}: ${(error as Error).message}${hint}`,\n error,\n );\n }\n raw = mod.default;\n }\n\n if (raw === undefined || typeof raw !== \"object\" || raw === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath} must default-export a BaerlyAppConfig object`,\n );\n }\n\n const obj = raw as Record<string, unknown>;\n const app = obj[\"app\"];\n const tenant = obj[\"tenant\"];\n const target = obj[\"target\"];\n if (typeof app !== \"string\" || app.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`app\\` must be a non-empty string`,\n );\n }\n if (typeof tenant !== \"string\" || tenant.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`tenant\\` must be a non-empty string`,\n );\n }\n if (target !== \"cloudflare\" && target !== \"node\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`target\\` must be \"cloudflare\" or \"node\" (got ${JSON.stringify(target)})`,\n );\n }\n\n // `auth` is a required typed posture as of the graduated-auth\n // redesign. The widening cast to `readonly string[]` is needed\n // because `.includes` on a tuple narrows its parameter to the\n // tuple's element type; widening locally is the standard idiom.\n const authRaw = obj[\"auth\"];\n if (typeof authRaw !== \"string\" || !(AUTH_CONFIG_VALUES as readonly string[]).includes(authRaw)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`auth\\` is required and must be one of ${JSON.stringify(AUTH_CONFIG_VALUES)} (got ${JSON.stringify(authRaw)})`,\n );\n }\n const auth = authRaw as AuthConfig;\n\n const domainRaw = obj[\"domain\"];\n if (domainRaw !== undefined && typeof domainRaw !== \"string\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`domain\\` must be a string when set`,\n );\n }\n\n const secretsRaw = obj[\"requiredSecrets\"];\n let requiredSecrets: readonly string[] | undefined;\n if (secretsRaw !== undefined) {\n if (!Array.isArray(secretsRaw) || !secretsRaw.every((s) => typeof s === \"string\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`requiredSecrets\\` must be an array of strings`,\n );\n }\n requiredSecrets = secretsRaw as readonly string[];\n }\n\n const cfaRaw = obj[\"cloudflareAccess\"];\n let cloudflareAccess: AppConfig[\"cloudflareAccess\"];\n if (cfaRaw !== undefined) {\n if (typeof cfaRaw !== \"object\" || cfaRaw === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess\\` must be an object when set`,\n );\n }\n const cfa = cfaRaw as Record<string, unknown>;\n const td = cfa[\"teamDomain\"];\n const aud = cfa[\"audienceTag\"];\n if (typeof td !== \"string\" || td.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess.teamDomain\\` must be a non-empty string`,\n );\n }\n if (typeof aud !== \"string\" || aud.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess.audienceTag\\` must be a non-empty string`,\n );\n }\n cloudflareAccess = { teamDomain: td, audienceTag: aud };\n }\n\n return {\n app,\n tenant,\n target,\n auth,\n ...(domainRaw !== undefined && { domain: domainRaw }),\n ...(requiredSecrets !== undefined && { requiredSecrets }),\n ...(cloudflareAccess !== undefined && { cloudflareAccess }),\n repoRoot: cwd,\n };\n};\n\n/**\n * Lightweight per-collection index reflection. Mirrors the shape the\n * runtime `BaerlyConfig` carries, but only the fields the doctor needs.\n *\n * `indexes` is an empty array when the collection declared none.\n */\nexport interface LoadedCollection {\n readonly name: string;\n readonly indexes: readonly IndexDefinition[];\n}\n\n/**\n * Load `baerly.config.{ts,js,mjs,json}` AND return the parsed\n * `collections[*]` shape alongside the narrow {@link AppConfig}. Lets\n * the doctor reflect on declared indexes without forcing every consumer\n * to widen `AppConfig`. Returns `undefined` for `collections` when the\n * config doesn't declare any (the doctor downgrades the drift check to\n * a no-op `info` finding in that case).\n *\n * Re-uses {@link loadAppConfig}'s parse/validate path, so the\n * `AppConfig` invariants are still enforced.\n */\nexport const loadAppConfigWithCollections = async (\n cwd: string = process.cwd(),\n): Promise<{\n readonly config: AppConfig;\n readonly collections: readonly LoadedCollection[] | undefined;\n}> => {\n const config = await loadAppConfig(cwd);\n const cfgPath = locateConfig(cwd);\n if (cfgPath === null) {\n return { config, collections: undefined };\n }\n\n // Re-parse the raw default-export to pluck `collections[*]`. We\n // don't validate the inner shape here — at the doctor surface,\n // anything that isn't an object is reported as \"no filtered\n // indexes\" rather than throwing, so a partially-typed config\n // doesn't fail the whole check.\n let raw: unknown;\n if (cfgPath.endsWith(\".json\")) {\n let text: string;\n try {\n text = await readFile(cfgPath, \"utf8\");\n } catch {\n return { config, collections: undefined };\n }\n try {\n raw = JSON.parse(text);\n } catch {\n return { config, collections: undefined };\n }\n } else {\n try {\n const mod = (await import(pathToFileURL(cfgPath).href)) as { default?: unknown };\n raw = mod.default;\n } catch {\n // Node can't `import` a .ts file without a TS loader. The\n // narrow `loadAppConfig` already surfaced the InvalidConfig if\n // that path was unreadable; here we silently downgrade to\n // \"no collections\" rather than re-throw.\n return { config, collections: undefined };\n }\n }\n\n if (raw === undefined || raw === null || typeof raw !== \"object\") {\n return { config, collections: undefined };\n }\n const colsRaw = (raw as { collections?: unknown }).collections;\n if (colsRaw === undefined || colsRaw === null || typeof colsRaw !== \"object\") {\n return { config, collections: undefined };\n }\n\n const out: LoadedCollection[] = [];\n for (const [name, decl] of Object.entries(colsRaw as Record<string, unknown>)) {\n if (decl === null || typeof decl !== \"object\") {\n continue;\n }\n const indexes = (decl as { indexes?: unknown }).indexes;\n if (!Array.isArray(indexes)) {\n out.push({ name, indexes: [] });\n continue;\n }\n // Pass-through cast: the runtime IndexDefinition validation\n // lives in `@baerly/server`; the doctor only reads `name`, `on`,\n // and `predicate`, so a partial shape still gives an actionable\n // finding rather than a SchemaError throw at config-load time.\n out.push({ name, indexes: indexes as readonly IndexDefinition[] });\n }\n return { config, collections: out };\n};\n\n/**\n * Load the declared `IndexDefinition[]` for a single collection from a\n * `baerly.config.{js,mjs,json}`. Used by `baerly inspect` (key-count\n * probes) and `baerly admin rebuild-index` (resolving the `on` field).\n *\n * `.ts` configs are rejected — Node can't `import` them without a TS\n * loader; point at the compiled `.js` output instead.\n *\n * `commandName` is woven into thrown error messages so the operator\n * sees the calling command name in the prefix.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `.ts` extension, JSON\n * parse error, missing default export, or missing\n * `collections[collection]`.\n */\nexport const loadCollectionIndexes = async (\n configPath: string,\n collection: string,\n commandName: string,\n): Promise<readonly IndexDefinition[]> => {\n if (configPath.endsWith(\".ts\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${commandName}: --config must point at compiled JS / JSON (got .ts: ${JSON.stringify(configPath)})`,\n );\n }\n let cfg: BaerlyConfig;\n if (configPath.endsWith(\".json\")) {\n const text = await readFile(configPath, \"utf8\");\n try {\n cfg = JSON.parse(text) as BaerlyConfig;\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${commandName}: --config JSON parse error in ${JSON.stringify(configPath)}: ${(error as Error).message}`,\n );\n }\n } else {\n const abs = configPath.startsWith(\"file://\") ? fileURLToPath(configPath) : resolve(configPath);\n const mod = (await import(pathToFileURL(abs).href)) as { default?: BaerlyConfig };\n if (mod.default === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${commandName}: --config ${JSON.stringify(configPath)} has no default export`,\n );\n }\n cfg = mod.default;\n }\n return cfg.collections?.[collection]?.indexes ?? [];\n};\n"],"mappings":";;;;;;;;;;AA0DA,MAAa,4BAAoC;;;;;;;;AA+DjD,MAAa,4BAAoC;;;;;;AAoBjD,MAAa,0BAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgC/C,MAAa,yBAAiC,QAAc,KAAK;;;;;;;;;;AAWjE,MAAa,4BAAoC;;;;;;;AAqBjD,MAAa,6BAAqC,KAAK;;;;;;;;;AAoGvD,MAAa,qCAA6C,MAAM;;;;;;;;;;AAoChE,MAAa,4BAAoC;;;;;;;;AASjD,MAAa,mCAA2C;;;;;;;;;;;;;;;;AA8DxD,MAAa,qBAAqB,CAAC,QAAQ,eAAe;;;;;AAoB1D,MAAa,gCACX;;;;;;;;;;;;;;;;;;;;;;;;AC3XF,MAAM,mBAAsC;CAC1C;CACA;CACA;CACA;AACF;;;;;;;;AASA,MAAa,gBAAgB,QAA+B;CAC1D,KAAK,MAAM,QAAQ,kBAAkB;EACnC,MAAM,MAAM,QAAQ,KAAK,IAAI;EAC7B,IAAI,WAAW,GAAG,GAChB,OAAO;CAEX;CACA,OAAO;AACT;;;;;;;;;;AAWA,MAAa,gBAAgB,OAAO,MAAc,QAAQ,IAAI,MAA0B;CACtF,MAAM,UAAU,aAAa,GAAG;CAChC,IAAI,YAAY,MACd,MAAM,IAAI,YACR,iBACA,gDAAgD,IAAI,qCACtD;CAGF,IAAI;CACJ,IAAI,Q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