splithub 0.1.9 → 0.2.1
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/README.md +11 -0
- package/dist/chunk-3RVNT2HA.js +54 -0
- package/dist/chunk-3RVNT2HA.js.map +1 -0
- package/dist/chunk-5C24F2ZN.js +113 -0
- package/dist/chunk-5C24F2ZN.js.map +1 -0
- package/dist/chunk-B6FITBWN.js +384 -0
- package/dist/chunk-B6FITBWN.js.map +1 -0
- package/dist/chunk-BJQJGLOB.js +160 -0
- package/dist/chunk-BJQJGLOB.js.map +1 -0
- package/dist/chunk-DDWYTOX4.js +565 -0
- package/dist/chunk-DDWYTOX4.js.map +1 -0
- package/dist/chunk-DUIJ5DTV.js +170 -0
- package/dist/chunk-DUIJ5DTV.js.map +1 -0
- package/dist/chunk-E5VH4BQX.js +326 -0
- package/dist/chunk-E5VH4BQX.js.map +1 -0
- package/dist/chunk-EYYLDI5J.js +195 -0
- package/dist/chunk-EYYLDI5J.js.map +1 -0
- package/dist/chunk-GVARYUL3.js +28 -0
- package/dist/chunk-GVARYUL3.js.map +1 -0
- package/dist/chunk-KMO5GGGC.js +185 -0
- package/dist/chunk-KMO5GGGC.js.map +1 -0
- package/dist/chunk-LT4JP3IF.js +119 -0
- package/dist/chunk-LT4JP3IF.js.map +1 -0
- package/dist/chunk-NMN5YGNP.js +72 -0
- package/dist/chunk-NMN5YGNP.js.map +1 -0
- package/dist/chunk-OHA2M7QR.js +264 -0
- package/dist/chunk-OHA2M7QR.js.map +1 -0
- package/dist/chunk-OYM64FMD.js +63 -0
- package/dist/chunk-OYM64FMD.js.map +1 -0
- package/dist/chunk-PLXDG4B5.js +134 -0
- package/dist/chunk-PLXDG4B5.js.map +1 -0
- package/dist/chunk-PNPOOAHF.js +393 -0
- package/dist/chunk-PNPOOAHF.js.map +1 -0
- package/dist/chunk-RYDA7PQF.js +97 -0
- package/dist/chunk-RYDA7PQF.js.map +1 -0
- package/dist/chunk-V3DLUVOE.js +112 -0
- package/dist/chunk-V3DLUVOE.js.map +1 -0
- package/dist/ci-ZQZ6RBUJ.js +16 -0
- package/dist/ci-ZQZ6RBUJ.js.map +1 -0
- package/dist/create-AEJVXN25.js +18 -0
- package/dist/create-AEJVXN25.js.map +1 -0
- package/dist/dev-W2JGUV2A.js +11 -0
- package/dist/dev-W2JGUV2A.js.map +1 -0
- package/dist/doctor-D3KOGOX6.js +14 -0
- package/dist/doctor-D3KOGOX6.js.map +1 -0
- package/dist/holdout-BWVTTLEY.js +44 -0
- package/dist/holdout-BWVTTLEY.js.map +1 -0
- package/dist/index.js +94 -2240
- package/dist/index.js.map +1 -1
- package/dist/init-UBUDSJBD.js +15 -0
- package/dist/init-UBUDSJBD.js.map +1 -0
- package/dist/lifecycle-ZLZUTASA.js +12 -0
- package/dist/lifecycle-ZLZUTASA.js.map +1 -0
- package/dist/login-TIIX5V4O.js +18 -0
- package/dist/login-TIIX5V4O.js.map +1 -0
- package/dist/menu-S3WDS4JY.js +163 -0
- package/dist/menu-S3WDS4JY.js.map +1 -0
- package/dist/plan-G2A55FR7.js +135 -0
- package/dist/plan-G2A55FR7.js.map +1 -0
- package/dist/push-OJX4F2BH.js +16 -0
- package/dist/push-OJX4F2BH.js.map +1 -0
- package/dist/refs-RY7H3J7L.js +44 -0
- package/dist/refs-RY7H3J7L.js.map +1 -0
- package/dist/remove-EQQCDJRU.js +54 -0
- package/dist/remove-EQQCDJRU.js.map +1 -0
- package/dist/report-6WNO576N.js +69 -0
- package/dist/report-6WNO576N.js.map +1 -0
- package/dist/results-ZDOCWN6U.js +21 -0
- package/dist/results-ZDOCWN6U.js.map +1 -0
- package/dist/review-7E7JVMMV.js +34 -0
- package/dist/review-7E7JVMMV.js.map +1 -0
- package/dist/ship-MRBHWFZR.js +450 -0
- package/dist/ship-MRBHWFZR.js.map +1 -0
- package/dist/skills-JJOKGNO5.js +13 -0
- package/dist/skills-JJOKGNO5.js.map +1 -0
- package/dist/status-SATP23WK.js +12 -0
- package/dist/status-SATP23WK.js.map +1 -0
- package/dist/update-67QDJ6GF.js +37 -0
- package/dist/update-67QDJ6GF.js.map +1 -0
- package/package.json +22 -5
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config-file.ts"],"sourcesContent":["import { isSplitHubConfig, type ExperimentKind, type ExperimentStatus, type SplitHubConfig } from '@splithub/core';\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { CliError, fail } from './errors';\n\n/** Load splithub.config.ts (TypeScript or JS) through jiti. CONFIG_PARSE when it does not load. */\nexport async function loadConfig(file: string): Promise<SplitHubConfig> {\n let mod: unknown;\n try {\n const { createJiti } = await import('jiti');\n const jiti = createJiti(pathToFileURL(file).href, { fsCache: false, moduleCache: false });\n mod = await jiti.import(file, { default: true });\n } catch (error) {\n fail('CONFIG_PARSE', `${basename(file)} doesn't load: ${error instanceof Error ? error.message.split('\\n')[0] : String(error)}`, 'Fix the error in the file, then run npx splithub doctor.');\n }\n if (!isSplitHubConfig(mod)) {\n fail('CONFIG_PARSE', `${basename(file)} must \\`export default defineConfig({...})\\` from @splithub/core.`);\n }\n return mod;\n}\n\n// ---------------------------------------------------------------------------\n// Source scanning. Edits work on a \"masked\" copy of the file where string\n// contents, template literals, regex literals and comments are blanked out\n// (same length, newlines kept), so braces and quotes inside them never count.\n// ---------------------------------------------------------------------------\n\nconst REGEX_BEFORE = new Set(['', '(', ',', '=', ':', '[', '!', '&', '|', '?', '{', '}', ';', '+', '-', '*', '%', '<', '>', '~', '^']);\n\n/** Copy of `source` with strings (contents), templates, regexes and comments blanked. */\nexport function maskSource(source: string): string {\n const out = source.split('');\n const blank = (from: number, to: number) => {\n for (let j = from; j < to && j < out.length; j++) if (out[j] !== '\\n' && out[j] !== '\\r') out[j] = ' ';\n };\n let lastCode = '';\n let i = 0;\n while (i < source.length) {\n const ch = source[i]!;\n const next = source[i + 1];\n if (ch === '/' && next === '/') {\n const end = source.indexOf('\\n', i);\n const stop = end < 0 ? source.length : end;\n blank(i, stop);\n i = stop;\n continue;\n }\n if (ch === '/' && next === '*') {\n const end = source.indexOf('*/', i + 2);\n const stop = end < 0 ? source.length : end + 2;\n blank(i, stop);\n i = stop;\n continue;\n }\n if (ch === \"'\" || ch === '\"') {\n let j = i + 1;\n while (j < source.length && source[j] !== ch && source[j] !== '\\n') j += source[j] === '\\\\' ? 2 : 1;\n blank(i + 1, j);\n i = j + 1;\n lastCode = ch;\n continue;\n }\n if (ch === '`') {\n let j = i + 1;\n let depth = 0;\n while (j < source.length) {\n const c = source[j]!;\n if (c === '\\\\') {\n j += 2;\n continue;\n }\n if (depth === 0 && c === '`') break;\n if (c === '$' && source[j + 1] === '{') {\n depth++;\n j += 2;\n continue;\n }\n if (depth > 0 && c === '{') depth++;\n else if (depth > 0 && c === '}') depth--;\n j++;\n }\n blank(i + 1, j);\n i = j + 1;\n lastCode = '`';\n continue;\n }\n if (ch === '/' && REGEX_BEFORE.has(lastCode)) {\n let j = i + 1;\n let inClass = false;\n while (j < source.length && source[j] !== '\\n') {\n const c = source[j]!;\n if (c === '\\\\') {\n j += 2;\n continue;\n }\n if (c === '[') inClass = true;\n else if (c === ']') inClass = false;\n else if (c === '/' && !inClass) break;\n j++;\n }\n blank(i + 1, j);\n i = j + 1;\n lastCode = '/';\n continue;\n }\n if (!/\\s/.test(ch)) lastCode = /[\\w$)\\]]/.test(ch) ? 'x' : ch;\n i++;\n }\n return out.join('');\n}\n\n/** Index of the bracket closing the one at `open` in masked text, or null. */\nfunction matchingClose(masked: string, open: number): number | null {\n let depth = 0;\n for (let i = open; i < masked.length; i++) {\n const ch = masked[i]!;\n if (ch === '{' || ch === '(' || ch === '[') depth++;\n else if (ch === '}' || ch === ')' || ch === ']') {\n depth--;\n if (depth === 0) return i;\n }\n }\n return null;\n}\n\nexport interface Entry {\n /** Property name; null for spreads and computed keys. */\n key: string | null;\n /** object: `key: { ... }` · expr: any other value (identifier, call, shorthand) · spread: `...x` · computed: `[k]: v`. */\n kind: 'object' | 'expr' | 'spread' | 'computed';\n start: number;\n valueStart: number;\n /** Exclusive end of the value (trailing whitespace excluded). */\n valueEnd: number;\n /** After the trailing comma when there is one, else `valueEnd`. */\n end: number;\n}\n\n/** Top-level properties of the object literal between `open` and `close` (its braces). */\nexport function objectEntries(source: string, masked: string, open: number, close: number): Entry[] {\n const entries: Entry[] = [];\n let i = open + 1;\n const ws = () => {\n while (i < close && /[\\s,]/.test(masked[i]!)) i++;\n };\n // A value runs to the next comma at depth 0 (or the closing brace).\n const valueTo = (from: number): number => {\n let j = from;\n while (j < close) {\n const ch = masked[j]!;\n if (ch === ',') break;\n if (ch === '{' || ch === '(' || ch === '[') {\n const m = matchingClose(masked, j);\n j = m === null ? close : m + 1;\n continue;\n }\n j++;\n }\n return j;\n };\n for (;;) {\n ws();\n if (i >= close) break;\n const start = i;\n let key: string | null = null;\n let kind: Entry['kind'] = 'expr';\n if (masked.startsWith('...', i)) {\n kind = 'spread';\n i += 3;\n } else {\n const ch = masked[i]!;\n if (ch === \"'\" || ch === '\"') {\n const end = masked.indexOf(ch, i + 1);\n key = source.slice(i + 1, end).replace(/\\\\(.)/g, '$1');\n i = end + 1;\n } else if (ch === '[') {\n kind = 'computed';\n const m = matchingClose(masked, i);\n i = m === null ? close : m + 1;\n } else {\n const m = /^[\\w$-]+/.exec(masked.slice(i, close));\n if (!m) break;\n key = m[0];\n i += m[0].length;\n }\n while (i < close && /\\s/.test(masked[i]!)) i++;\n if (masked[i] === ':') i++;\n }\n while (i < close && /\\s/.test(masked[i]!)) i++;\n const valueStart = i;\n const stop = valueTo(i);\n let valueEnd = stop;\n while (valueEnd > valueStart && /\\s/.test(masked[valueEnd - 1]!)) valueEnd--;\n if (kind === 'expr' && masked[valueStart] === '{' && matchingClose(masked, valueStart) === valueEnd - 1) kind = 'object';\n const end = masked[stop] === ',' ? stop + 1 : valueEnd;\n entries.push({ key, kind, start, valueStart, valueEnd, end });\n i = stop;\n }\n return entries;\n}\n\ninterface Located {\n masked: string;\n open: number;\n close: number;\n entries: Entry[];\n}\n\n/** The `experiments: { ... }` object of the config, with its entries. */\nfunction locateExperiments(source: string): Located {\n const masked = maskSource(source);\n let open = -1;\n // Prefer the object passed to defineConfig({ ... }) / export default { ... }.\n const root = /defineConfig\\s*\\(\\s*\\{|export\\s+default\\s+\\{/.exec(masked);\n if (root) {\n const rootOpen = root.index + root[0].length - 1;\n const rootClose = matchingClose(masked, rootOpen);\n if (rootClose !== null) {\n const exp = objectEntries(source, masked, rootOpen, rootClose).find((e) => e.key === 'experiments');\n if (exp && exp.kind !== 'object') {\n fail('CONFIG_UNSAFE', '`experiments` in the config is not written inline, so the CLI cannot edit it safely.', 'Edit the experiments where they are defined, or write them inline as experiments: { ... }.');\n }\n if (exp) open = exp.valueStart;\n }\n }\n if (open < 0) {\n const m = /\\bexperiments\\s*:\\s*\\{/.exec(masked);\n if (!m) fail('CONFIG_UNSAFE', \"Couldn't find `experiments: {` in the config file.\", 'Add experiments: {} to defineConfig({...}) and retry.');\n open = m.index + m[0].length - 1;\n }\n const close = matchingClose(masked, open);\n if (close === null) fail('CONFIG_PARSE', 'The braces after `experiments: {` are not balanced.');\n return { masked, open, close, entries: objectEntries(source, masked, open, close) };\n}\n\nfunction unsafeHint(key: string): string {\n return `Edit \"${key}\" where it is defined (it comes from a spread or an imported constant), then run npx splithub doctor.`;\n}\n\n/** The literal `key: { ... }` entry of an experiment. Throws when it can't be edited safely. */\nfunction experimentEntry(source: string, key: string): Located & { entry: Entry } {\n const loc = locateExperiments(source);\n const entry = loc.entries.find((e) => e.key === key);\n if (!entry) {\n if (loc.entries.some((e) => e.kind === 'spread' || e.kind === 'computed')) {\n fail('CONFIG_UNSAFE', `\"${key}\" isn't written inline in the config (the experiments use a spread), so the CLI can't edit it safely.`, unsafeHint(key));\n }\n fail('EXPERIMENT_NOT_FOUND', `There's no experiment \"${key}\" in the config.`, 'See the ids with npx splithub status.');\n }\n return { ...loc, entry };\n}\n\nexport function hasExperiment(source: string, key: string): boolean {\n try {\n return locateExperiments(source).entries.some((e) => e.key === key);\n } catch {\n return false;\n }\n}\n\n/** Indentation of the line holding `index`. */\nfunction indentAt(source: string, index: number): string {\n const lineStart = source.lastIndexOf('\\n', index - 1) + 1;\n return /^[ \\t]*/.exec(source.slice(lineStart))?.[0] ?? '';\n}\n\n/**\n * Append `render(indent)` as the last property of the object `open..close`,\n * adding the comma the previous property may be missing.\n */\nfunction appendProperty(source: string, masked: string, open: number, close: number, render: (indent: string) => string): string {\n const outerIndent = indentAt(source, open);\n const indent = outerIndent + ' ';\n let last = close - 1;\n while (last > open && /\\s/.test(masked[last]!)) last--;\n const needsComma = last > open && masked[last] !== ',';\n const lineStart = source.lastIndexOf('\\n', close - 1) + 1;\n const closeOnOwnLine = source.slice(lineStart, close).trim() === '';\n const block = `${indent}${render(indent)},\\n`;\n const at = closeOnOwnLine && lineStart > last ? lineStart : close;\n const text = at === close ? `\\n${block}${outerIndent}` : block;\n const comma = needsComma ? ',' : '';\n // Inline object (`{ a: 1 }`): the whitespace before `}` gives way to the new line.\n const head = at === close ? source.slice(0, last + 1) + comma : source.slice(0, last + 1) + comma + source.slice(last + 1, at);\n return head + text + source.slice(at);\n}\n\nexport interface NewExperiment {\n key: string;\n kind: ExperimentKind;\n status: ExperimentStatus;\n variants: Array<{ key: string; weight: number; value?: string; to?: string }>;\n /** Multivariate: factor → level → value; the variants are derived and not written. */\n factors?: Record<string, Record<string, string>>;\n goal?: string;\n match?: string;\n description?: string;\n /** Targeting graph from the dashboard, written verbatim as JSON. */\n flow?: unknown;\n traffic?: number;\n maxExposures?: number;\n /** Days before a verdict (0..30); absent means the default of 0 (none). */\n minDays?: number;\n /** Total visitors for a good sample (100..10,000,000); absent means the default of 5000. */\n goodSample?: number;\n schedule?: { startAt?: string | null; endAt?: string | null };\n /** Secondary goals to watch, and guardrails that must not get worse. */\n metrics?: { secondary?: string[]; guardrails?: Array<string | { goal: string; worse: 'lower' | 'higher' }> };\n /** Mutual exclusion layer and its bucket range [start, end). */\n layer?: { key: string; range: [number, number] };\n}\n\n/** Single-quoted string literal. */\nfunction q(s: string): string {\n return `'${s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\").replace(/\\n/g, '\\\\n')}'`;\n}\n\n/** Object key: bare when it is a valid identifier, quoted otherwise. */\nfunction k(s: string): string {\n return /^[a-z_$][\\w$]*$/i.test(s) ? s : q(s);\n}\n\n/** Render an experiment entry. Every line after the first carries its own indentation. */\nexport function renderExperiment(e: NewExperiment, indent = ' '): string {\n const i2 = indent + ' ';\n const i3 = i2 + ' ';\n const lines: string[] = [`${k(e.key)}: {`];\n lines.push(`${i2}kind: ${q(e.kind)},`);\n lines.push(`${i2}status: ${q(e.status)},`);\n if (e.match) lines.push(`${i2}match: ${q(e.match)},`);\n if (e.kind === 'mvt') {\n lines.push(`${i2}factors: {`);\n for (const [factor, levels] of Object.entries(e.factors ?? {})) {\n lines.push(`${i3}${k(factor)}: { ${Object.entries(levels).map(([l, v]) => `${k(l)}: ${q(v)}`).join(', ')} },`);\n }\n lines.push(`${i2}},`);\n } else if (e.kind === 'component') {\n lines.push(`${i2}variants: { ${e.variants.map((v) => `${k(v.key)}: ${v.weight}`).join(', ')} },`);\n } else {\n lines.push(`${i2}variants: {`);\n for (const v of e.variants) {\n const extra = e.kind === 'value' ? `value: ${q(v.value ?? '')}` : `to: ${q(v.to ?? '/')}`;\n lines.push(`${i3}${k(v.key)}: { weight: ${v.weight}, ${extra} },`);\n }\n lines.push(`${i2}},`);\n }\n if (e.goal) lines.push(`${i2}goal: ${q(e.goal)},`);\n if (e.traffic !== undefined && e.traffic !== 1) lines.push(`${i2}traffic: ${e.traffic},`);\n if (e.maxExposures) lines.push(`${i2}maxExposures: ${e.maxExposures},`);\n if (e.minDays !== undefined) lines.push(`${i2}minDays: ${e.minDays},`);\n if (e.goodSample !== undefined) lines.push(`${i2}goodSample: ${e.goodSample},`);\n if (e.schedule && (e.schedule.startAt || e.schedule.endAt)) lines.push(`${i2}schedule: { ${[e.schedule.startAt ? `startAt: ${q(e.schedule.startAt)}` : null, e.schedule.endAt ? `endAt: ${q(e.schedule.endAt)}` : null].filter(Boolean).join(', ')} },`);\n if (e.metrics && (e.metrics.secondary?.length || e.metrics.guardrails?.length)) {\n const parts: string[] = [];\n if (e.metrics.secondary?.length) parts.push(`secondary: [${e.metrics.secondary.map(q).join(', ')}]`);\n if (e.metrics.guardrails?.length) parts.push(`guardrails: [${e.metrics.guardrails.map((g) => (typeof g === 'string' ? q(g) : `{ goal: ${q(g.goal)}, worse: ${q(g.worse)} }`)).join(', ')}]`);\n lines.push(`${i2}metrics: { ${parts.join(', ')} },`);\n }\n if (e.layer) lines.push(`${i2}layer: { key: ${q(e.layer.key)}, range: [${e.layer.range[0]}, ${e.layer.range[1]}] },`);\n if (e.description) lines.push(`${i2}description: ${q(e.description)},`);\n if (e.flow) {\n const json = JSON.stringify(e.flow, null, 2).split('\\n');\n lines.push(`${i2}// targeting graph from the dashboard; edit it there or by hand\\n${i2}flow: ${json.map((l, n) => (n === 0 ? l : i2 + l)).join('\\n')},`);\n }\n lines.push(`${indent}}`);\n return lines.join('\\n');\n}\n\n/** Append a new experiment at the end of the `experiments: { ... }` object. */\nexport function insertExperiment(source: string, e: NewExperiment): string {\n const { masked, open, close, entries } = locateExperiments(source);\n if (entries.some((x) => x.key === e.key)) fail('EXPERIMENT_EXISTS', `There's already an experiment \"${e.key}\".`, 'Pick another id: an old id keeps its history.');\n return appendProperty(source, masked, open, close, (indent) => renderExperiment(e, indent));\n}\n\nexport function setExperimentStatus(source: string, key: string, status: ExperimentStatus): string {\n const { masked, entry } = experimentEntry(source, key);\n if (entry.kind !== 'object') fail('CONFIG_UNSAFE', `\"${key}\" points to a value defined elsewhere, so the CLI can't edit it safely.`, unsafeHint(key));\n const inner = objectEntries(source, masked, entry.valueStart, entry.valueEnd - 1);\n const field = inner.filter((x) => x.key === 'status').pop();\n if (field) {\n const raw = masked.slice(field.valueStart, field.valueEnd);\n if (!/^(['\"])\\s*\\1$/.test(raw)) fail('CONFIG_UNSAFE', `The status of \"${key}\" isn't a plain string, so the CLI can't change it safely.`, `Set status: '${status}' by hand.`);\n const quote = raw[0]!;\n return source.slice(0, field.valueStart) + `${quote}${status}${quote}` + source.slice(field.valueEnd);\n }\n // No status written (or only through a spread): append one, so it wins over any spread.\n return appendProperty(source, masked, entry.valueStart, entry.valueEnd - 1, () => `status: ${q(status)}`);\n}\n\n/** Remove an experiment's entry (and its line) from the config source. */\nexport function removeExperiment(source: string, key: string): string {\n return removeEntry(source, experimentEntry(source, key).entry);\n}\n\n/** Remove a property, its whole line when it stands alone. */\nfunction removeEntry(source: string, entry: Entry): string {\n const lineStart = source.lastIndexOf('\\n', entry.start - 1) + 1;\n const from = source.slice(lineStart, entry.start).trim() === '' ? lineStart : entry.start;\n let to = entry.end;\n const lineEnd = source.indexOf('\\n', to);\n const rest = source.slice(to, lineEnd < 0 ? source.length : lineEnd);\n if (rest.trim() === '' && from === lineStart) to = lineEnd < 0 ? source.length : lineEnd + 1;\n return source.slice(0, from) + source.slice(to);\n}\n\n/** The object passed to defineConfig({ ... }) / export default { ... }. */\nfunction locateRoot(source: string): Located {\n const masked = maskSource(source);\n const root = /defineConfig\\s*\\(\\s*\\{|export\\s+default\\s+\\{/.exec(masked);\n if (!root) fail('CONFIG_UNSAFE', \"Couldn't find defineConfig({ ... }) in the config file.\", 'Make the change by hand in splithub.config.ts.');\n const open = root.index + root[0].length - 1;\n const close = matchingClose(masked, open);\n if (close === null) fail('CONFIG_PARSE', 'The braces of defineConfig({ ... }) are not balanced.');\n return { masked, open, close, entries: objectEntries(source, masked, open, close) };\n}\n\n/** Set a top-level config property (`holdout: { ... }`), replacing it when it is there. */\nexport function setTopLevel(source: string, name: string, valueText: string | null): string {\n const { masked, open, close, entries } = locateRoot(source);\n const entry = entries.find((e) => e.key === name);\n if (valueText === null) return entry ? removeEntry(source, entry) : source;\n if (entry) return source.slice(0, entry.valueStart) + valueText + source.slice(entry.valueEnd);\n return appendProperty(source, masked, open, close, () => `${k(name)}: ${valueText}`);\n}\n\n/** Make sure `layers: { <key>: {} }` declares a layer. */\nexport function ensureLayer(source: string, key: string): string {\n const { masked, open, close, entries } = locateRoot(source);\n const layers = entries.find((e) => e.key === 'layers');\n if (!layers) return appendProperty(source, masked, open, close, () => `layers: { ${k(key)}: {} }`);\n if (layers.kind !== 'object') fail('CONFIG_UNSAFE', '`layers` in the config is not written inline.', `Add ${key}: {} to layers by hand.`);\n if (objectEntries(source, masked, layers.valueStart, layers.valueEnd - 1).some((e) => e.key === key)) return source;\n return appendProperty(source, masked, layers.valueStart, layers.valueEnd - 1, () => `${k(key)}: {}`);\n}\n\nexport function readSource(file: string): string {\n return readFileSync(file, 'utf8');\n}\n\nexport function writeSource(file: string, source: string): void {\n writeFileSync(file, source, 'utf8');\n}\n\n/**\n * Write the config, load it back and check the change landed. On any problem the\n * original file is restored and CONFIG_WRITE is thrown: the CLI never leaves a broken config.\n */\nexport async function writeConfigChecked(file: string, original: string, updated: string, verify: (config: SplitHubConfig) => string | null): Promise<SplitHubConfig> {\n writeSource(file, updated);\n let problem: string | null = null;\n let config: SplitHubConfig | null = null;\n try {\n config = await loadConfig(file);\n problem = verify(config);\n } catch (error) {\n problem = error instanceof CliError || error instanceof Error ? error.message : String(error);\n }\n if (problem || !config) {\n writeSource(file, original);\n fail('CONFIG_WRITE', `Couldn't update ${basename(file)}: ${problem ?? 'it did not load'}. The file is back as it was.`, 'Make the change by hand in the config, then run npx splithub doctor.');\n }\n return config;\n}\n"],"mappings":";;;;;;;AAAA,SAAS,wBAAyF;AAClG,SAAS,cAAc,qBAAqB;AAC5C,SAAS,gBAAgB;AACzB,SAAS,qBAAqB;AAI9B,eAAsB,WAAW,MAAuC;AACtE,MAAI;AACJ,MAAI;AACF,UAAM,EAAE,WAAW,IAAI,MAAM,OAAO,MAAM;AAC1C,UAAM,OAAO,WAAW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,cAAY,MAAM,OAAO;AACzB,MAAI,UAAyB;AAC7B,MAAI,SAAgC;AACpC,MAAI;AACF,aAAS,MAAM,WAAW,IAAI;AAC9B,cAAU,OAAO,MAAM;AAAA,EACzB,SAAS,OAAO;AACd,cAAU,iBAAiB,YAAY,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,EAC9F;AACA,MAAI,WAAW,CAAC,QAAQ;AACtB,gBAAY,MAAM,QAAQ;AAC1B,SAAK,gBAAgB,mBAAmB,SAAS,IAAI,CAAC,KAAK,WAAW,iBAAiB,iCAAiC,sEAAsE;AAAA,EAChM;AACA,SAAO;AACT;","names":["end"]}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
CliError,
|
|
4
|
+
fail
|
|
5
|
+
} from "./chunk-V3DLUVOE.js";
|
|
6
|
+
|
|
7
|
+
// src/credentials.ts
|
|
8
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
9
|
+
import { homedir } from "os";
|
|
10
|
+
import { join, resolve } from "path";
|
|
11
|
+
function credentialsFile() {
|
|
12
|
+
const base = process.env.XDG_CONFIG_HOME || (process.platform === "win32" ? process.env.APPDATA || join(homedir(), "AppData", "Roaming") : join(homedir(), ".config"));
|
|
13
|
+
return join(base, "splithub", "credentials.json");
|
|
14
|
+
}
|
|
15
|
+
function read() {
|
|
16
|
+
const file = credentialsFile();
|
|
17
|
+
if (!existsSync(file)) return {};
|
|
18
|
+
try {
|
|
19
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
20
|
+
} catch {
|
|
21
|
+
return {};
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function loadCredential(api, root = process.cwd()) {
|
|
25
|
+
return read()[api]?.[resolve(root)] ?? null;
|
|
26
|
+
}
|
|
27
|
+
function saveCredential(api, root, cred) {
|
|
28
|
+
const file = credentialsFile();
|
|
29
|
+
const store = read();
|
|
30
|
+
store[api] = { ...store[api] ?? {}, [resolve(root)]: cred };
|
|
31
|
+
mkdirSync(join(file, ".."), { recursive: true });
|
|
32
|
+
writeFileSync(file, JSON.stringify(store, null, 2) + "\n", { mode: 384 });
|
|
33
|
+
return file;
|
|
34
|
+
}
|
|
35
|
+
function listCredentials(api) {
|
|
36
|
+
const store = read();
|
|
37
|
+
const out = [];
|
|
38
|
+
for (const [a, dirs] of Object.entries(store)) {
|
|
39
|
+
if (api && a !== api) continue;
|
|
40
|
+
for (const [root, cred] of Object.entries(dirs)) out.push({ api: a, root, cred });
|
|
41
|
+
}
|
|
42
|
+
return out.sort((x, y) => y.cred.savedAt.localeCompare(x.cred.savedAt));
|
|
43
|
+
}
|
|
44
|
+
function removeCredential(api, root = process.cwd()) {
|
|
45
|
+
const store = read();
|
|
46
|
+
const key = resolve(root);
|
|
47
|
+
if (!store[api]?.[key]) return false;
|
|
48
|
+
delete store[api][key];
|
|
49
|
+
writeFileSync(credentialsFile(), JSON.stringify(store, null, 2) + "\n", { mode: 384 });
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// src/api.ts
|
|
54
|
+
import { readFileSync as readFileSync2 } from "fs";
|
|
55
|
+
var CLOUD_API = "https://go.splithub.io/v1";
|
|
56
|
+
function storageFromConfig(project) {
|
|
57
|
+
const fallback = { mode: "self", endpoint: "/api/splithub" };
|
|
58
|
+
if (!project?.configFile) return fallback;
|
|
59
|
+
try {
|
|
60
|
+
const src = readFileSync2(project.configFile, "utf8");
|
|
61
|
+
const mode = /mode\s*:\s*['"](cloud|self)['"]/.exec(src)?.[1];
|
|
62
|
+
const endpoint = /endpoint\s*:\s*['"]([^'"]+)['"]/.exec(src)?.[1];
|
|
63
|
+
return { mode: mode ?? "self", endpoint: endpoint ?? "/api/splithub" };
|
|
64
|
+
} catch {
|
|
65
|
+
return fallback;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function cloudTarget(flags) {
|
|
69
|
+
const url = typeof flags.api === "string" && flags.api || process.env.SPLITHUB_API || CLOUD_API;
|
|
70
|
+
const base = url.replace(/\/+$/, "");
|
|
71
|
+
const token = typeof flags.token === "string" && flags.token || process.env.SPLITHUB_API_KEY || loadCredential(base)?.apiKey || void 0;
|
|
72
|
+
return { url: base, token };
|
|
73
|
+
}
|
|
74
|
+
function resolveTarget(flags, project) {
|
|
75
|
+
const explicit = typeof flags.url === "string" && flags.url || process.env.SPLITHUB_URL;
|
|
76
|
+
const storage = storageFromConfig(project);
|
|
77
|
+
if (!explicit && storage.mode === "cloud") return cloudTarget(flags);
|
|
78
|
+
const port = project?.framework === "next" ? 3e3 : 5173;
|
|
79
|
+
const url = explicit || `http://localhost:${port}${storage.endpoint}`;
|
|
80
|
+
const token = typeof flags.token === "string" && flags.token || process.env.SPLITHUB_ADMIN_TOKEN || void 0;
|
|
81
|
+
return { url: url.replace(/\/+$/, ""), token };
|
|
82
|
+
}
|
|
83
|
+
function apiErrorMessage(status, body, fallback) {
|
|
84
|
+
const error = body?.error;
|
|
85
|
+
const text = typeof error === "string" ? error : typeof error?.message === "string" ? error.message : fallback;
|
|
86
|
+
return status === 401 ? `${text} This folder is not signed in: run npx splithub login (or set SPLITHUB_API_KEY).` : text;
|
|
87
|
+
}
|
|
88
|
+
function apiError(status, body, fallback, experiment) {
|
|
89
|
+
const message = apiErrorMessage(status, body, fallback);
|
|
90
|
+
if (status === 401) return new CliError("NOT_LOGGED_IN", message, "Run npx splithub login (or set SPLITHUB_API_KEY), then retry.");
|
|
91
|
+
const b = body;
|
|
92
|
+
if (status === 403 && b?.code === "insufficient_scope") return new CliError("INSUFFICIENT_SCOPE", message, `This API key lacks the "${typeof b.needed === "string" ? b.needed : "write"}" scope. Create one with it in the dashboard (Settings, API keys) or run npx splithub login --yes.`);
|
|
93
|
+
if (status === 404 && experiment) return new CliError("EXPERIMENT_NOT_FOUND", message, `Check the id with npx splithub status. In cloud mode, push the config first.`);
|
|
94
|
+
return new CliError("API_ERROR", message);
|
|
95
|
+
}
|
|
96
|
+
async function request(target, path, init = {}, experiment) {
|
|
97
|
+
const headers = { ...init.headers ?? {} };
|
|
98
|
+
if (target.token) headers.authorization = `Bearer ${target.token}`;
|
|
99
|
+
if (init.body) headers["content-type"] = "application/json";
|
|
100
|
+
let res;
|
|
101
|
+
try {
|
|
102
|
+
res = await fetch(`${target.url}${path}`, { ...init, headers });
|
|
103
|
+
} catch (error) {
|
|
104
|
+
throw new CliError("UNREACHABLE", `Can't reach ${target.url}: ${error instanceof Error ? error.message : String(error)}.`, "Is your app running? Set --url or SPLITHUB_URL.");
|
|
105
|
+
}
|
|
106
|
+
const body = await res.json().catch(() => ({}));
|
|
107
|
+
if (!res.ok) throw apiError(res.status, body, `${target.url}${path} responded ${res.status}`, experiment);
|
|
108
|
+
return body;
|
|
109
|
+
}
|
|
110
|
+
function requireCloudToken(flags) {
|
|
111
|
+
const target = cloudTarget(flags);
|
|
112
|
+
if (!target.token) fail("NOT_LOGGED_IN", "This folder is not connected to SplitHub Cloud.", "Run npx splithub login, or pass --token sk_... / SPLITHUB_API_KEY.");
|
|
113
|
+
return target;
|
|
114
|
+
}
|
|
115
|
+
function putOverride(target, experiment, body) {
|
|
116
|
+
return request(target, `/overrides/${encodeURIComponent(experiment)}`, { method: "PUT", body: JSON.stringify(body) }, experiment);
|
|
117
|
+
}
|
|
118
|
+
async function applyLiveStatus(flags, experiment, status) {
|
|
119
|
+
const target = cloudTarget(flags);
|
|
120
|
+
if (!target.token) return "no API key (run npx splithub login or set SPLITHUB_API_KEY to apply it without a deploy)";
|
|
121
|
+
try {
|
|
122
|
+
await putOverride(target, experiment, { status });
|
|
123
|
+
return "applied";
|
|
124
|
+
} catch (error) {
|
|
125
|
+
return `cloud refused: ${error instanceof Error ? error.message : String(error)}`;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
async function archiveLive(flags, experiment) {
|
|
129
|
+
const target = cloudTarget(flags);
|
|
130
|
+
if (!target.token) return "no API key (run npx splithub login or set SPLITHUB_API_KEY to archive it in the cloud)";
|
|
131
|
+
try {
|
|
132
|
+
await request(target, `/archive/${encodeURIComponent(experiment)}`, { method: "PUT", body: "{}" });
|
|
133
|
+
return "archived";
|
|
134
|
+
} catch (error) {
|
|
135
|
+
if (error instanceof CliError && (error.code === "EXPERIMENT_NOT_FOUND" || error.code === "API_ERROR")) {
|
|
136
|
+
const finished = await applyLiveStatus(flags, experiment, "finished");
|
|
137
|
+
return finished === "applied" ? "finished" : finished;
|
|
138
|
+
}
|
|
139
|
+
return `cloud refused: ${error instanceof Error ? error.message : String(error)}`;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
var fetchStatus = (t) => request(t, "/status");
|
|
143
|
+
var fetchResults = (t, key) => request(t, `/results/${encodeURIComponent(key)}`, {}, key);
|
|
144
|
+
|
|
145
|
+
export {
|
|
146
|
+
credentialsFile,
|
|
147
|
+
loadCredential,
|
|
148
|
+
saveCredential,
|
|
149
|
+
listCredentials,
|
|
150
|
+
removeCredential,
|
|
151
|
+
cloudTarget,
|
|
152
|
+
resolveTarget,
|
|
153
|
+
apiError,
|
|
154
|
+
requireCloudToken,
|
|
155
|
+
applyLiveStatus,
|
|
156
|
+
archiveLive,
|
|
157
|
+
fetchStatus,
|
|
158
|
+
fetchResults
|
|
159
|
+
};
|
|
160
|
+
//# sourceMappingURL=chunk-BJQJGLOB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/credentials.ts","../src/api.ts"],"sourcesContent":["// Credentials saved by `splithub login`: ~/.config/splithub/credentials.json\n// { \"<api base>\": { \"<project root>\": { apiKey, projectId, projectName, savedAt } } }\n// `cloudTarget` falls back to the entry for the current directory when neither\n// --token nor SPLITHUB_API_KEY is set.\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\n\nexport interface SavedCredential {\n apiKey: string;\n projectId: string | null;\n projectName: string | null;\n /** Public key of the project (pk_...), written into splithub.config.ts by init. */\n publicKey?: string | null;\n savedAt: string;\n}\n\ntype Store = Record<string, Record<string, SavedCredential>>;\n\nexport function credentialsFile(): string {\n const base = process.env.XDG_CONFIG_HOME || (process.platform === 'win32' ? process.env.APPDATA || join(homedir(), 'AppData', 'Roaming') : join(homedir(), '.config'));\n return join(base, 'splithub', 'credentials.json');\n}\n\nfunction read(): Store {\n const file = credentialsFile();\n if (!existsSync(file)) return {};\n try {\n return JSON.parse(readFileSync(file, 'utf8')) as Store;\n } catch {\n return {};\n }\n}\n\nexport function loadCredential(api: string, root = process.cwd()): SavedCredential | null {\n return read()[api]?.[resolve(root)] ?? null;\n}\n\nexport function saveCredential(api: string, root: string, cred: SavedCredential): string {\n const file = credentialsFile();\n const store = read();\n store[api] = { ...(store[api] ?? {}), [resolve(root)]: cred };\n mkdirSync(join(file, '..'), { recursive: true });\n writeFileSync(file, JSON.stringify(store, null, 2) + '\\n', { mode: 0o600 });\n return file;\n}\n\n/** Every saved credential on this machine: which directory is connected to which project. */\nexport function listCredentials(api?: string): Array<{ api: string; root: string; cred: SavedCredential }> {\n const store = read();\n const out: Array<{ api: string; root: string; cred: SavedCredential }> = [];\n for (const [a, dirs] of Object.entries(store)) {\n if (api && a !== api) continue;\n for (const [root, cred] of Object.entries(dirs)) out.push({ api: a, root, cred });\n }\n return out.sort((x, y) => y.cred.savedAt.localeCompare(x.cred.savedAt));\n}\n\nexport function removeCredential(api: string, root = process.cwd()): boolean {\n const store = read();\n const key = resolve(root);\n if (!store[api]?.[key]) return false;\n delete store[api][key];\n writeFileSync(credentialsFile(), JSON.stringify(store, null, 2) + '\\n', { mode: 0o600 });\n return true;\n}\n","import type { ExperimentResults, StatusRow } from '@splithub/node';\nimport { readFileSync } from 'node:fs';\nimport { loadCredential } from './credentials';\nimport { CliError, fail } from './errors';\nimport type { ProjectInfo } from './project';\n\nexport interface Target {\n url: string;\n token?: string;\n}\n\nexport const CLOUD_API = 'https://go.splithub.io/v1';\n\n/** Storage settings from splithub.config.ts, read textually to avoid loading the config. */\nfunction storageFromConfig(project?: ProjectInfo): { mode: 'self' | 'cloud'; endpoint: string } {\n const fallback = { mode: 'self' as const, endpoint: '/api/splithub' };\n if (!project?.configFile) return fallback;\n try {\n const src = readFileSync(project.configFile, 'utf8');\n const mode = /mode\\s*:\\s*['\"](cloud|self)['\"]/.exec(src)?.[1] as 'self' | 'cloud' | undefined;\n const endpoint = /endpoint\\s*:\\s*['\"]([^'\"]+)['\"]/.exec(src)?.[1];\n return { mode: mode ?? 'self', endpoint: endpoint ?? '/api/splithub' };\n } catch {\n return fallback;\n }\n}\n\n/** Cloud API base + project API key (sk_...). */\nexport function cloudTarget(flags: Record<string, unknown>): Target {\n const url = (typeof flags.api === 'string' && flags.api) || process.env.SPLITHUB_API || CLOUD_API;\n const base = url.replace(/\\/+$/, '');\n const token = (typeof flags.token === 'string' && flags.token) || process.env.SPLITHUB_API_KEY || loadCredential(base)?.apiKey || undefined;\n return { url: base, token };\n}\n\n/**\n * Where to read results from:\n * - --url / SPLITHUB_URL always win;\n * - cloud mode → the cloud API with the project API key;\n * - self mode → the local dev server (3000 for Next.js, 5173 for Vite) + the endpoint from the config.\n */\nexport function resolveTarget(flags: Record<string, unknown>, project?: ProjectInfo): Target {\n const explicit = (typeof flags.url === 'string' && flags.url) || process.env.SPLITHUB_URL;\n const storage = storageFromConfig(project);\n if (!explicit && storage.mode === 'cloud') return cloudTarget(flags);\n const port = project?.framework === 'next' ? 3000 : 5173;\n const url = explicit || `http://localhost:${port}${storage.endpoint}`;\n const token = (typeof flags.token === 'string' && flags.token) || process.env.SPLITHUB_ADMIN_TOKEN || undefined;\n return { url: url.replace(/\\/+$/, ''), token };\n}\n\n/**\n * Readable message from an API error body. Most routes answer `{ error: 'text' }`; the auth layer\n * answers `{ success: false, error: { code, message } }`. Without this the CLI printed \"[object Object]\".\n */\nexport function apiErrorMessage(status: number, body: unknown, fallback: string): string {\n const error = (body as { error?: unknown } | null)?.error;\n const text = typeof error === 'string' ? error : typeof (error as { message?: unknown } | undefined)?.message === 'string' ? (error as { message: string }).message : fallback;\n return status === 401 ? `${text} This folder is not signed in: run npx splithub login (or set SPLITHUB_API_KEY).` : text;\n}\n\n/** CliError for a failed API response: 401 → NOT_LOGGED_IN, 404 on an experiment → EXPERIMENT_NOT_FOUND. */\nexport function apiError(status: number, body: unknown, fallback: string, experiment?: string): CliError {\n const message = apiErrorMessage(status, body, fallback);\n if (status === 401) return new CliError('NOT_LOGGED_IN', message, 'Run npx splithub login (or set SPLITHUB_API_KEY), then retry.');\n const b = body as { code?: unknown; needed?: unknown } | null;\n if (status === 403 && b?.code === 'insufficient_scope') return new CliError('INSUFFICIENT_SCOPE', message, `This API key lacks the \"${typeof b.needed === 'string' ? b.needed : 'write'}\" scope. Create one with it in the dashboard (Settings, API keys) or run npx splithub login --yes.`);\n if (status === 404 && experiment) return new CliError('EXPERIMENT_NOT_FOUND', message, `Check the id with npx splithub status. In cloud mode, push the config first.`);\n return new CliError('API_ERROR', message);\n}\n\nasync function request<T>(target: Target, path: string, init: RequestInit = {}, experiment?: string): Promise<T> {\n const headers: Record<string, string> = { ...((init.headers as Record<string, string> | undefined) ?? {}) };\n if (target.token) headers.authorization = `Bearer ${target.token}`;\n if (init.body) headers['content-type'] = 'application/json';\n let res: Response;\n try {\n res = await fetch(`${target.url}${path}`, { ...init, headers });\n } catch (error) {\n throw new CliError('UNREACHABLE', `Can't reach ${target.url}: ${error instanceof Error ? error.message : String(error)}.`, 'Is your app running? Set --url or SPLITHUB_URL.');\n }\n const body: unknown = await res.json().catch(() => ({}));\n if (!res.ok) throw apiError(res.status, body, `${target.url}${path} responded ${res.status}`, experiment);\n return body as T;\n}\n\n/** Cloud target that must carry an API key. */\nexport function requireCloudToken(flags: Record<string, unknown>): Target & { token: string } {\n const target = cloudTarget(flags);\n if (!target.token) fail('NOT_LOGGED_IN', 'This folder is not connected to SplitHub Cloud.', 'Run npx splithub login, or pass --token sk_... / SPLITHUB_API_KEY.');\n return target as Target & { token: string };\n}\n\n/** PUT /overrides/<experiment>: live status, traffic or weights without a deploy. */\nexport function putOverride(target: Target, experiment: string, body: Record<string, unknown>): Promise<unknown> {\n return request<unknown>(target, `/overrides/${encodeURIComponent(experiment)}`, { method: 'PUT', body: JSON.stringify(body) }, experiment);\n}\n\n/**\n * Apply a status live in cloud mode. Never throws: the config file already changed,\n * so a refused or unreachable cloud is reported, not fatal.\n */\nexport async function applyLiveStatus(flags: Record<string, unknown>, experiment: string, status: string): Promise<string> {\n const target = cloudTarget(flags);\n if (!target.token) return 'no API key (run npx splithub login or set SPLITHUB_API_KEY to apply it without a deploy)';\n try {\n await putOverride(target, experiment, { status });\n return 'applied';\n } catch (error) {\n return `cloud refused: ${error instanceof Error ? error.message : String(error)}`;\n }\n}\n\n/** daysToVerdict: days until a verdict at the current traffic; null when unknown (older servers omit it). */\n/**\n * Archive an experiment in the cloud (PUT /archive/<id>): it stops, keeps its numbers and leaves the\n * active list. Older servers without the route get it finished instead. Never throws.\n */\nexport async function archiveLive(flags: Record<string, unknown>, experiment: string): Promise<string> {\n const target = cloudTarget(flags);\n if (!target.token) return 'no API key (run npx splithub login or set SPLITHUB_API_KEY to archive it in the cloud)';\n try {\n await request<unknown>(target, `/archive/${encodeURIComponent(experiment)}`, { method: 'PUT', body: '{}' });\n return 'archived';\n } catch (error) {\n // 404 from a server without the route (or any non-auth refusal): finishing still stops the test.\n if (error instanceof CliError && (error.code === 'EXPERIMENT_NOT_FOUND' || error.code === 'API_ERROR')) {\n const finished = await applyLiveStatus(flags, experiment, 'finished');\n return finished === 'applied' ? 'finished' : finished;\n }\n return `cloud refused: ${error instanceof Error ? error.message : String(error)}`;\n }\n}\n\nexport type ResultsWithPlan = ExperimentResults & { daysToVerdict?: number | null; visitorsPerDay?: number | null };\n/** `sample` is optional: older servers omit it. */\nexport type StatusRowWithPlan = Omit<StatusRow, 'sample' | 'stars'> & { sample?: StatusRow['sample']; stars?: StatusRow['stars']; daysToVerdict?: number | null };\n\nexport const fetchStatus = (t: Target) => request<{ project: string; experiments: StatusRowWithPlan[] }>(t, '/status');\nexport const fetchResults = (t: Target, key: string) => request<ResultsWithPlan>(t, `/results/${encodeURIComponent(key)}`, {}, key);\n"],"mappings":";;;;;;;AAIA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AAavB,SAAS,kBAA0B;AACxC,QAAM,OAAO,QAAQ,IAAI,oBAAoB,QAAQ,aAAa,UAAU,QAAQ,IAAI,WAAW,KAAK,QAAQ,GAAG,WAAW,SAAS,IAAI,KAAK,QAAQ,GAAG,SAAS;AACpK,SAAO,KAAK,MAAM,YAAY,kBAAkB;AAClD;AAEA,SAAS,OAAc;AACrB,QAAM,OAAO,gBAAgB;AAC7B,MAAI,CAAC,WAAW,IAAI,EAAG,QAAO,CAAC;AAC/B,MAAI;AACF,WAAO,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;AAAA,EAC9C,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AAEO,SAAS,eAAe,KAAa,OAAO,QAAQ,IAAI,GAA2B;AACxF,SAAO,KAAK,EAAE,GAAG,IAAI,QAAQ,IAAI,CAAC,KAAK;AACzC;AAEO,SAAS,eAAe,KAAa,MAAc,MAA+B;AACvF,QAAM,OAAO,gBAAgB;AAC7B,QAAM,QAAQ,KAAK;AACnB,QAAM,GAAG,IAAI,EAAE,GAAI,MAAM,GAAG,KAAK,CAAC,GAAI,CAAC,QAAQ,IAAI,CAAC,GAAG,KAAK;AAC5D,YAAU,KAAK,MAAM,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAC/C,gBAAc,MAAM,KAAK,UAAU,OAAO,MAAM,CAAC,IAAI,MAAM,EAAE,MAAM,IAAM,CAAC;AAC1E,SAAO;AACT;AAGO,SAAS,gBAAgB,KAA2E;AACzG,QAAM,QAAQ,KAAK;AACnB,QAAM,MAAmE,CAAC;AAC1E,aAAW,CAA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