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.
Files changed (80) hide show
  1. package/README.md +11 -0
  2. package/dist/chunk-3RVNT2HA.js +54 -0
  3. package/dist/chunk-3RVNT2HA.js.map +1 -0
  4. package/dist/chunk-5C24F2ZN.js +113 -0
  5. package/dist/chunk-5C24F2ZN.js.map +1 -0
  6. package/dist/chunk-B6FITBWN.js +384 -0
  7. package/dist/chunk-B6FITBWN.js.map +1 -0
  8. package/dist/chunk-BJQJGLOB.js +160 -0
  9. package/dist/chunk-BJQJGLOB.js.map +1 -0
  10. package/dist/chunk-DDWYTOX4.js +565 -0
  11. package/dist/chunk-DDWYTOX4.js.map +1 -0
  12. package/dist/chunk-DUIJ5DTV.js +170 -0
  13. package/dist/chunk-DUIJ5DTV.js.map +1 -0
  14. package/dist/chunk-E5VH4BQX.js +326 -0
  15. package/dist/chunk-E5VH4BQX.js.map +1 -0
  16. package/dist/chunk-EYYLDI5J.js +195 -0
  17. package/dist/chunk-EYYLDI5J.js.map +1 -0
  18. package/dist/chunk-GVARYUL3.js +28 -0
  19. package/dist/chunk-GVARYUL3.js.map +1 -0
  20. package/dist/chunk-KMO5GGGC.js +185 -0
  21. package/dist/chunk-KMO5GGGC.js.map +1 -0
  22. package/dist/chunk-LT4JP3IF.js +119 -0
  23. package/dist/chunk-LT4JP3IF.js.map +1 -0
  24. package/dist/chunk-NMN5YGNP.js +72 -0
  25. package/dist/chunk-NMN5YGNP.js.map +1 -0
  26. package/dist/chunk-OHA2M7QR.js +264 -0
  27. package/dist/chunk-OHA2M7QR.js.map +1 -0
  28. package/dist/chunk-OYM64FMD.js +63 -0
  29. package/dist/chunk-OYM64FMD.js.map +1 -0
  30. package/dist/chunk-PLXDG4B5.js +134 -0
  31. package/dist/chunk-PLXDG4B5.js.map +1 -0
  32. package/dist/chunk-PNPOOAHF.js +393 -0
  33. package/dist/chunk-PNPOOAHF.js.map +1 -0
  34. package/dist/chunk-RYDA7PQF.js +97 -0
  35. package/dist/chunk-RYDA7PQF.js.map +1 -0
  36. package/dist/chunk-V3DLUVOE.js +112 -0
  37. package/dist/chunk-V3DLUVOE.js.map +1 -0
  38. package/dist/ci-ZQZ6RBUJ.js +16 -0
  39. package/dist/ci-ZQZ6RBUJ.js.map +1 -0
  40. package/dist/create-AEJVXN25.js +18 -0
  41. package/dist/create-AEJVXN25.js.map +1 -0
  42. package/dist/dev-W2JGUV2A.js +11 -0
  43. package/dist/dev-W2JGUV2A.js.map +1 -0
  44. package/dist/doctor-D3KOGOX6.js +14 -0
  45. package/dist/doctor-D3KOGOX6.js.map +1 -0
  46. package/dist/holdout-BWVTTLEY.js +44 -0
  47. package/dist/holdout-BWVTTLEY.js.map +1 -0
  48. package/dist/index.js +94 -2240
  49. package/dist/index.js.map +1 -1
  50. package/dist/init-UBUDSJBD.js +15 -0
  51. package/dist/init-UBUDSJBD.js.map +1 -0
  52. package/dist/lifecycle-ZLZUTASA.js +12 -0
  53. package/dist/lifecycle-ZLZUTASA.js.map +1 -0
  54. package/dist/login-TIIX5V4O.js +18 -0
  55. package/dist/login-TIIX5V4O.js.map +1 -0
  56. package/dist/menu-S3WDS4JY.js +163 -0
  57. package/dist/menu-S3WDS4JY.js.map +1 -0
  58. package/dist/plan-G2A55FR7.js +135 -0
  59. package/dist/plan-G2A55FR7.js.map +1 -0
  60. package/dist/push-OJX4F2BH.js +16 -0
  61. package/dist/push-OJX4F2BH.js.map +1 -0
  62. package/dist/refs-RY7H3J7L.js +44 -0
  63. package/dist/refs-RY7H3J7L.js.map +1 -0
  64. package/dist/remove-EQQCDJRU.js +54 -0
  65. package/dist/remove-EQQCDJRU.js.map +1 -0
  66. package/dist/report-6WNO576N.js +69 -0
  67. package/dist/report-6WNO576N.js.map +1 -0
  68. package/dist/results-ZDOCWN6U.js +21 -0
  69. package/dist/results-ZDOCWN6U.js.map +1 -0
  70. package/dist/review-7E7JVMMV.js +34 -0
  71. package/dist/review-7E7JVMMV.js.map +1 -0
  72. package/dist/ship-MRBHWFZR.js +450 -0
  73. package/dist/ship-MRBHWFZR.js.map +1 -0
  74. package/dist/skills-JJOKGNO5.js +13 -0
  75. package/dist/skills-JJOKGNO5.js.map +1 -0
  76. package/dist/status-SATP23WK.js +12 -0
  77. package/dist/status-SATP23WK.js.map +1 -0
  78. package/dist/update-67QDJ6GF.js +37 -0
  79. package/dist/update-67QDJ6GF.js.map +1 -0
  80. package/package.json +22 -5
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/create.ts"],"sourcesContent":["import * as p from '@clack/prompts';\nimport { mvtVariants, type ExperimentKind, type ExperimentStatus } from '@splithub/core';\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { ensureLayer, hasExperiment, insertExperiment, loadConfig, readSource, writeConfigChecked, type NewExperiment } from '../config-file';\nimport { fail, printJson } from '../errors';\nimport { requireConfig } from '../project';\nimport { componentVariantTemplate } from '../templates';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\nconst KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;\n\nfunction str(v: unknown): string | undefined {\n return typeof v === 'string' && v.length > 0 ? v : undefined;\n}\nfunction list(v: unknown): string[] {\n if (Array.isArray(v)) return v.map(String);\n if (typeof v === 'string') return [v];\n return [];\n}\nfunction parsePairs(items: string[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const item of items) {\n const i = item.indexOf('=');\n if (i > 0) out[item.slice(0, i).trim()] = item.slice(i + 1);\n }\n return out;\n}\nfunction pascal(s: string): string {\n return s.replace(/(^|[-_])([a-z0-9])/g, (_, __, ch: string) => ch.toUpperCase());\n}\n\nasync function ask<T>(promise: Promise<T | symbol>): Promise<T> {\n const v = await promise;\n if (p.isCancel(v)) {\n p.cancel('Cancelled.');\n process.exit(0);\n }\n return v as T;\n}\n\nexport async function create(flags: Flags): Promise<void> {\n const json = Boolean(flags.json);\n const yes = Boolean(flags.yes);\n const project = requireConfig();\n const config = await loadConfig(project.configFile);\n const source = readSource(project.configFile);\n const interactive = !yes && !json;\n\n if (interactive) p.intro(c.bold('splithub create'));\n\n let kind = str(flags.kind) as ExperimentKind | undefined;\n if (!kind) {\n if (!interactive) fail('USAGE', 'Which kind? Pass --kind value|component|redirect|mvt.');\n kind = await ask(\n p.select<ExperimentKind>({\n message: 'What changes between variants?',\n options: [\n { value: 'value', label: 'Text, image URL, number', hint: 'no new components' },\n { value: 'component', label: 'Layout / structure', hint: 'one component per variant' },\n { value: 'redirect', label: 'A whole page', hint: 'needs @splithub/next middleware' },\n { value: 'mvt', label: 'Several things at once', hint: 'multivariate: every combination, each factor read on its own' },\n ],\n })\n );\n }\n\n let id = str(flags.id);\n if (!id) {\n if (!interactive) fail('USAGE', 'Which id? Pass --id <key>, e.g. --id hero-title.');\n id = await ask(\n p.text({\n message: 'Experiment id',\n placeholder: 'hero-title',\n validate: (v) => (!KEY.test(v) ? 'lowercase a-z 0-9 - _ only' : hasExperiment(source, v) ? 'already exists' : undefined),\n })\n );\n }\n if (!['value', 'component', 'redirect', 'mvt'].includes(kind)) fail('INVALID_FLAG', `Unknown kind \"${kind}\".`, 'Use --kind value, component, redirect or mvt.');\n if (!KEY.test(id)) fail('INVALID_FLAG', `\"${id}\" isn't a valid id.`, 'Use lowercase a-z, 0-9, - and _, at most 64 characters.');\n if (hasExperiment(source, id) || config.experiments.some((e) => e.key === id)) fail('EXPERIMENT_EXISTS', `There's already an experiment \"${id}\".`, 'Pick another id: an old id keeps its history.');\n const limits = parseLimits(flags);\n\n // Multivariate: --factor headline=old:Old,new:New (repeatable); the variants are the combinations.\n const factors: Record<string, Record<string, string>> = {};\n if (kind === 'mvt') {\n for (const raw of list(flags.factor)) {\n const eq = raw.indexOf('=');\n if (eq <= 0) fail('INVALID_FLAG', `--factor expects name=level:value,level:value, got \"${raw}\".`);\n const name = raw.slice(0, eq).trim();\n const levels: Record<string, string> = {};\n for (const part of raw.slice(eq + 1).split(',')) {\n const colon = part.indexOf(':');\n const level = (colon >= 0 ? part.slice(0, colon) : part).trim();\n if (!level) continue;\n levels[level] = colon >= 0 ? part.slice(colon + 1).trim() : level;\n }\n factors[name] = levels;\n }\n while (interactive && Object.keys(factors).length === 0) {\n const name = await ask(p.text({ message: 'Factor name (what changes), e.g. headline', validate: (v) => (!KEY.test(v) ? 'lowercase a-z 0-9 - _ only' : undefined) }));\n const levelsRaw = await ask(p.text({ message: `Levels of \"${name}\" as key:value, comma separated (first = control)`, placeholder: 'old:Old headline, new:New headline' }));\n const levels: Record<string, string> = {};\n for (const part of levelsRaw.split(',')) {\n const colon = part.indexOf(':');\n const level = (colon >= 0 ? part.slice(0, colon) : part).trim();\n if (level) levels[level] = colon >= 0 ? part.slice(colon + 1).trim() : level;\n }\n factors[name] = levels;\n while (await ask(p.confirm({ message: 'Add another factor?', initialValue: false }))) {\n const more = await ask(p.text({ message: 'Factor name', validate: (v) => (!KEY.test(v) ? 'lowercase a-z 0-9 - _ only' : undefined) }));\n const moreRaw = await ask(p.text({ message: `Levels of \"${more}\" as key:value, comma separated`, placeholder: 'blue:#2563eb, green:#16a34a' }));\n const moreLevels: Record<string, string> = {};\n for (const part of moreRaw.split(',')) {\n const colon = part.indexOf(':');\n const level = (colon >= 0 ? part.slice(0, colon) : part).trim();\n if (level) moreLevels[level] = colon >= 0 ? part.slice(colon + 1).trim() : level;\n }\n factors[more] = moreLevels;\n }\n }\n if (Object.keys(factors).length === 0) fail('USAGE', 'An mvt experiment needs factors.', 'Pass --factor name=level:value,level:value once per factor.');\n if (flags.variants || flags.weights) fail('INVALID_FLAG', 'An mvt experiment takes --factor, not --variants or --weights.', 'Its variants are every combination of the factor levels, split equally.');\n }\n let mvt: ReturnType<typeof mvtVariants> | null = null;\n try {\n mvt = kind === 'mvt' ? mvtVariants(id, factors) : null;\n } catch (error) {\n fail('INVALID_FLAG', error instanceof Error ? error.message : String(error), 'At most 4 factors × 4 levels, 16 combinations.');\n }\n\n let variantKeys = mvt ? mvt.variants.map((v) => v.key) : str(flags.variants)?.split(',').map((s) => s.trim()).filter(Boolean);\n if (!variantKeys || variantKeys.length < 2) {\n if (!interactive) variantKeys = ['control', 'b'];\n else {\n const v = await ask(p.text({ message: 'Variant keys, comma separated (first = control)', initialValue: 'control, b' }));\n variantKeys = v.split(',').map((s) => s.trim()).filter(Boolean);\n }\n }\n for (const k of variantKeys) if (!KEY.test(k)) fail('INVALID_FLAG', `\"${k}\" isn't a valid variant key.`, 'Use lowercase a-z, 0-9, - and _.');\n if (variantKeys.length < 2) fail('INVALID_FLAG', 'An experiment needs at least 2 variants.', 'Pass --variants control,b.');\n if (new Set(variantKeys).size !== variantKeys.length) fail('INVALID_FLAG', 'Two variants have the same key.');\n\n const weights = mvt ? variantKeys.map(() => 1) : parseWeights(str(flags.weights), variantKeys.length);\n\n const values = parsePairs(list(flags.value));\n const tos = parsePairs(list(flags.to));\n if (kind === 'value' && interactive) {\n for (const k of variantKeys) {\n if (values[k] === undefined) values[k] = await ask(p.text({ message: `Value for \"${k}\"`, placeholder: k === variantKeys[0] ? 'current text' : 'new text' }));\n }\n }\n let match = str(flags.match);\n if (kind === 'redirect') {\n if (!match) {\n if (!interactive) fail('USAGE', 'A redirect experiment needs the path it runs on.', 'Pass --match /path.');\n match = await ask(p.text({ message: 'Path to run the redirect test on', initialValue: '/' }));\n }\n for (const k of variantKeys) {\n if (tos[k] === undefined) {\n if (!interactive) tos[k] = k === variantKeys[0] ? match : `${match.replace(/\\/$/, '')}/${k}`;\n else tos[k] = await ask(p.text({ message: `URL for \"${k}\"`, initialValue: k === variantKeys[0] ? match : '' }));\n }\n }\n }\n\n let goal = str(flags.goal);\n const goals = config.goals.map((g) => g.key);\n if (!goal) {\n if (!interactive) goal = goals[0];\n else if (goals.length > 0) {\n goal = await ask(\n p.select<string>({\n message: 'Goal (conversion) to optimise',\n options: [...goals.map((g) => ({ value: g, label: g })), { value: '', label: 'none yet (add later)' }],\n })\n );\n if (!goal) goal = undefined;\n }\n }\n if (goal && !goals.includes(goal)) fail('GOAL_NOT_FOUND', `There's no goal \"${goal}\" in the config.`, `Declared goals: ${goals.join(', ') || 'none'}. Add it to goals first.`);\n const extras = parseExtras(flags, goals, goal);\n\n // Running by default: the test goes live with the deploy that ships its code, first page views included.\n const status = (str(flags.status) as ExperimentStatus | undefined) ?? 'running';\n if (!['draft', 'running', 'paused'].includes(status)) fail('INVALID_FLAG', `A new experiment can't be \"${status}\".`, 'Use --status running or --status draft.');\n const description = str(flags.description);\n\n const experiment: NewExperiment = {\n key: id,\n kind,\n status,\n goal,\n match,\n description,\n variants: mvt ? mvt.variants.map((v) => ({ key: v.key, weight: v.weight })) : variantKeys.map((k, i) => ({ key: k, weight: weights[i]!, value: values[k], to: tos[k] })),\n ...(mvt ? { factors } : {}),\n ...limits,\n ...extras,\n };\n\n await writeConfigChecked(project.configFile, source, insertExperiment(extras.layer ? ensureLayer(source, extras.layer.key) : source, experiment), (loaded) => {\n const e = loaded.experiments.find((x) => x.key === id);\n if (!e) return `\"${id}\" is not in the file after the write`;\n if (e.status !== status) return `\"${id}\" loads as ${e.status}, not ${status}`;\n if (limits.minDays !== undefined && e.minDays !== limits.minDays) return `\"${id}\" loads with minDays ${e.minDays ?? 'unset'}, not ${limits.minDays}`;\n if (limits.goodSample !== undefined && e.goodSample !== limits.goodSample) return `\"${id}\" loads with goodSample ${e.goodSample ?? 'unset'}, not ${limits.goodSample}`;\n return null;\n });\n\n const files: string[] = [];\n const componentNames: Record<string, string> = {};\n if (kind === 'component') {\n const dir = join(project.root, project.hasSrc ? 'src/splithub' : 'splithub', id);\n mkdirSync(dir, { recursive: true });\n for (const k of variantKeys) {\n const name = `${pascal(id)}${pascal(k)}`;\n componentNames[k] = name;\n const file = join(dir, `${pascal(k)}.tsx`);\n if (!existsSync(file)) {\n writeFileSync(file, componentVariantTemplate(name, id, k), 'utf8');\n files.push(relative(project.root, file));\n }\n }\n }\n\n const snippet =\n kind === 'mvt'\n ? `const { ${Object.keys(factors).join(', ')} } = useValue<{ ${Object.keys(factors).map((f) => `${f}: string`).join('; ')} }>('${id}');`\n : kind === 'value'\n ? `const value = useValue<string>('${id}');`\n : kind === 'component'\n ? `<Experiment id=\"${id}\">\\n${variantKeys.map((k) => ` <Variant name=\"${k}\"><${componentNames[k]} /></Variant>`).join('\\n')}\\n</Experiment>`\n : `// handled by @splithub/next middleware on ${match}; no code needed`;\n\n const result = { experiment: id, kind, status, variants: experiment.variants, goal: goal ?? null, traffic: limits.traffic ?? 1, maxVisitors: limits.maxExposures ?? null, minDays: limits.minDays ?? null, goodSample: limits.goodSample ?? null, schedule: limits.schedule ?? null, configFile: relative(project.root, project.configFile), files, snippet };\n if (json) {\n const cloudMode = /mode\\s*:\\s*['\"]cloud['\"]/.test(readSource(project.configFile));\n // Agents read this JSON: the hand-off line makes sure the human learns the test is not live yet.\n const handoff =\n status === 'draft'\n ? `${id} is a draft: visitors do not see it and nothing is recorded until it is started. Tell the user and ask whether to start it now (npx splithub start ${id}).`\n : `${id} is running in the config: it goes live for visitors when this code is deployed${cloudMode ? ' and pushed; local development never sends events to the cloud' : ''}. Tell the user, and that npx splithub pause ${id} or Pause in the dashboard holds it.`;\n const nextStep = cloudMode ? `npx splithub push # the cloud does not know about ${id} until you push` : status === 'draft' ? `npx splithub start ${id}` : 'deploy the app';\n printJson({ ...result, nextStep, handoff });\n return;\n }\n p.note(snippet, kind === 'redirect' ? 'Nothing to wire' : 'Wire it in your code');\n if (files.length) p.note(files.join('\\n'), 'Scaffolded');\n const cloud = /mode\\s*:\\s*['\"]cloud['\"]/.test(readSource(project.configFile));\n if (cloud) p.log.warn(`Cloud mode: the cloud does not know about it until you run ${c.cyan('npx splithub push')}.`);\n if (status === 'draft') p.log.warn(`${c.bold(id)} is a draft: visitors do not see it and nothing is recorded until you start it.`);\n if (status === 'running') p.log.info(`${c.bold(id)} goes live when you deploy this code. Check it first with ${c.cyan(`?sh_force=${id}:<variant>`)}; ${c.cyan(`npx splithub pause ${id}`)} holds it.`);\n if (status === 'draft') p.log.info(`See it before you start it: ${c.cyan('runDraftsInDev: true')} in the config serves drafts in development, ${c.cyan(`?sh_force=${id}:<variant>`)} shows one variant anywhere.`);\n p.outro(`Added ${c.bold(id)} (${status}) to ${relative(project.root, project.configFile)}. ${status === 'running' ? '' : `Start it with ${c.cyan(`npx splithub start ${id}`)}. `}${cloud ? `Then ${c.cyan('npx splithub push')}.` : ''}`);\n}\n\n/** --weights 50,50: one non-negative number per variant, not all zero. Equal weights when absent. */\nexport function parseWeights(raw: string | undefined, count: number): number[] {\n if (!raw) return Array.from({ length: count }, () => 1);\n const weights = raw.split(',').map((w) => Number(w.trim()));\n if (weights.length !== count) fail('INVALID_FLAG', `--weights has ${weights.length} numbers for ${count} variants.`, 'Give one weight per variant, in the same order: --weights 50,50.');\n if (weights.some((w) => !Number.isFinite(w) || w < 0)) fail('INVALID_FLAG', `--weights \"${raw}\" has a value that isn't a number of 0 or more.`);\n if (weights.every((w) => w === 0)) fail('INVALID_FLAG', 'All weights are 0, so nobody would see the test.');\n return weights;\n}\n\nexport interface Limits {\n traffic?: number;\n maxExposures?: number;\n minDays?: number;\n goodSample?: number;\n schedule?: { startAt: string | null; endAt: string | null };\n}\n\n/** --traffic (percent, 0 < t <= 100), --max-visitors (whole number > 0), --min-days (whole number 0..30), --good-sample (whole number 100..10,000,000), --start / --end (dates, start before end). */\nexport function parseLimits(flags: Flags): Limits {\n const out: Limits = {};\n const traffic = str(flags.traffic);\n if (traffic !== undefined) {\n const t = Number(traffic.replace(/%$/, ''));\n if (!Number.isFinite(t) || t <= 0 || t > 100) fail('INVALID_FLAG', `--traffic \"${traffic}\" must be a percent between 0 and 100.`, 'For example --traffic 50 puts half of the visitors in the test.');\n if (t !== 100) out.traffic = Math.round(t * 100) / 10000;\n }\n const max = str(flags['max-visitors']);\n if (max !== undefined) {\n const m = Number(max);\n if (!Number.isInteger(m) || m <= 0) fail('INVALID_FLAG', `--max-visitors \"${max}\" must be a whole number above 0.`);\n out.maxExposures = m;\n }\n const minDays = str(flags['min-days']);\n if (minDays !== undefined) {\n const d = Number(minDays);\n if (!Number.isInteger(d) || d < 0 || d > 30) fail('INVALID_FLAG', `--min-days \"${minDays}\" must be a whole number from 0 to 30.`, 'It is the fewest days before a verdict; 0 means none, the default.');\n out.minDays = d;\n }\n const good = str(flags['good-sample']);\n if (good !== undefined) {\n const g = Number(good);\n if (!Number.isInteger(g) || g < 100 || g > 10_000_000) fail('INVALID_FLAG', `--good-sample \"${good}\" must be a whole number from 100 to 10,000,000.`, 'It is the total visitors at which the sample counts as good; the default is 5000.');\n out.goodSample = g;\n }\n const date = (name: 'start' | 'end'): string | null => {\n const v = str(flags[name]);\n if (v === undefined) return null;\n const ms = Date.parse(v);\n if (Number.isNaN(ms)) fail('INVALID_FLAG', `--${name} \"${v}\" isn't a date.`, 'Use an ISO date like 2026-11-01 or 2026-11-01T09:00:00Z.');\n return new Date(ms).toISOString();\n };\n const startAt = date('start');\n const endAt = date('end');\n if (startAt && endAt && Date.parse(endAt) <= Date.parse(startAt)) fail('INVALID_FLAG', '--end must be after --start.');\n if (startAt || endAt) out.schedule = { startAt, endAt };\n return out;\n}\n\n/**\n * --secondary a,b (goals to watch) · --guardrail refunds:higher,errors (goals that must not get worse;\n * :higher when a rise is bad, default :lower) · --layer key:0-50 (mutual exclusion, buckets [start, end)).\n */\nexport function parseExtras(flags: Flags, goals: string[], primary: string | undefined): Pick<NewExperiment, 'metrics' | 'layer'> {\n const out: Pick<NewExperiment, 'metrics' | 'layer'> = {};\n const split = (v: unknown) => list(v).flatMap((x) => x.split(',')).map((x) => x.trim()).filter(Boolean);\n const secondary = split(flags.secondary);\n const guardrails = split(flags.guardrail).map((g) => {\n const [goal = '', worse] = g.split(':');\n if (worse !== undefined && worse !== 'lower' && worse !== 'higher') fail('INVALID_FLAG', `--guardrail \"${g}\": after the colon comes lower or higher.`, 'refunds:higher means more refunds is worse; signups (or signups:lower) means fewer is worse.');\n return worse === 'higher' ? { goal, worse: 'higher' as const } : goal;\n });\n const named = [...secondary, ...guardrails.map((g) => (typeof g === 'string' ? g : g.goal))];\n if (named.length) {\n if (!primary) fail('USAGE', 'Secondary metrics and guardrails need a primary goal.', 'Pass --goal too.');\n for (const g of named) if (!goals.includes(g)) fail('GOAL_NOT_FOUND', `There's no goal \"${g}\" in the config.`, `Declared goals: ${goals.join(', ') || 'none'}. Add it to goals first.`);\n const all = [primary, ...named];\n if (new Set(all).size !== all.length) fail('INVALID_FLAG', 'A goal is listed twice across --goal, --secondary and --guardrail.');\n out.metrics = { ...(secondary.length ? { secondary } : {}), ...(guardrails.length ? { guardrails } : {}) };\n }\n const layer = str(flags.layer);\n if (layer) {\n const m = /^([a-z0-9][a-z0-9_-]{0,63}):(\\d{1,3})-(\\d{1,3})$/.exec(layer);\n const start = Number(m?.[2]);\n const end = Number(m?.[3]);\n if (!m || !(start < end) || end > 100) fail('INVALID_FLAG', `--layer \"${layer}\" must look like key:start-end with 0 <= start < end <= 100.`, 'For example --layer checkout:0-50; another test in checkout:50-100 never shares a visitor.');\n out.layer = { key: m[1]!, range: [start, end] };\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,YAAY,OAAO;AACnB,SAAS,mBAA+D;AACxE,SAAS,YAAY,WAAW,qBAAqB;AACrD,SAAS,MAAM,gBAAgB;AAQ/B,IAAM,MAAM;AAEZ,SAAS,IAAI,GAAgC;AAC3C,SAAO,OAAO,MAAM,YAAY,EAAE,SAAS,IAAI,IAAI;AACrD;AACA,SAAS,KAAK,GAAsB;AAClC,MAAI,MAAM,QAAQ,CAAC,EAAG,QAAO,EAAE,IAAI,MAAM;AACzC,MAAI,OAAO,MAAM,SAAU,QAAO,CAAC,CAAC;AACpC,SAAO,CAAC;AACV;AACA,SAAS,WAAW,OAAyC;AAC3D,QAAM,MAA8B,CAAC;AACrC,aAAW,QAAQ,OAAO;AACxB,UAAM,IAAI,KAAK,QAAQ,GAAG;A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CAAC,OAAO,GAAG,EAAE;AAAA,EAChD;AACA,SAAO;AACT;","names":[]}
@@ -0,0 +1,195 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ detectProject
4
+ } from "./chunk-PLXDG4B5.js";
5
+ import {
6
+ c,
7
+ printJson
8
+ } from "./chunk-V3DLUVOE.js";
9
+
10
+ // src/commands/ci.ts
11
+ import { existsSync, mkdirSync, writeFileSync } from "fs";
12
+ import { dirname, join, relative } from "path";
13
+ var CLI = "npx -y splithub@latest";
14
+ function gitRoot(from) {
15
+ let dir = from;
16
+ for (; ; ) {
17
+ if (existsSync(join(dir, ".git"))) return dir;
18
+ const up = dirname(dir);
19
+ if (up === dir) return from;
20
+ dir = up;
21
+ }
22
+ }
23
+ function workflowTemplate(workingDirectory) {
24
+ const wd = workingDirectory === "" ? "." : workingDirectory;
25
+ const configGlob = wd === "." ? "splithub.config.*" : `${wd}/splithub.config.*`;
26
+ return `# SplitHub: checks experiments on pull requests that touch the config, and keeps
27
+ # a results comment up to date on weekday mornings. Needs the SPLITHUB_API_KEY
28
+ # secret (dashboard, Settings, API keys) for results and cloud comparisons.
29
+ name: SplitHub
30
+
31
+ on:
32
+ pull_request:
33
+ paths:
34
+ - '${configGlob}'
35
+ schedule:
36
+ - cron: '0 8 * * 1-5'
37
+ workflow_dispatch:
38
+
39
+ permissions:
40
+ contents: read
41
+ pull-requests: write
42
+ issues: write
43
+
44
+ jobs:
45
+ splithub:
46
+ runs-on: ubuntu-latest
47
+ defaults:
48
+ run:
49
+ shell: bash
50
+ working-directory: ${wd}
51
+ env:
52
+ SPLITHUB_API_KEY: \${{ secrets.SPLITHUB_API_KEY }}
53
+ GH_TOKEN: \${{ github.token }}
54
+ NO_COLOR: '1'
55
+ # check on a pull request (doctor + push --dry-run), report otherwise (results tables)
56
+ MODE: \${{ github.event_name == 'pull_request' && 'check' || 'report' }}
57
+ PR_NUMBER: \${{ github.event.pull_request.number }}
58
+ ISSUE_TITLE: SplitHub results
59
+ OUT: \${{ runner.temp }}/splithub
60
+ steps:
61
+ - uses: actions/checkout@v4
62
+ - uses: actions/setup-node@v4
63
+ with:
64
+ node-version: 20
65
+
66
+ - name: Install dependencies
67
+ run: |
68
+ # The config imports @splithub/core; the lockfile may live at the repository root.
69
+ dir="$PWD"
70
+ while [ "$dir" != "/" ] && [ ! -f "$dir/pnpm-lock.yaml" ] && [ ! -f "$dir/yarn.lock" ] && [ ! -f "$dir/package-lock.json" ] && [ ! -f "$dir/bun.lockb" ] && [ ! -f "$dir/bun.lock" ]; do dir="$(dirname "$dir")"; done
71
+ cd "$dir"
72
+ if [ -f pnpm-lock.yaml ]; then corepack enable && pnpm install --frozen-lockfile
73
+ elif [ -f yarn.lock ]; then corepack enable && (yarn install --frozen-lockfile || yarn install --immutable)
74
+ elif [ -f bun.lockb ] || [ -f bun.lock ]; then npm i -g bun && bun install --frozen-lockfile
75
+ elif [ -f package-lock.json ]; then npm ci
76
+ else npm install; fi
77
+
78
+ - name: Run SplitHub
79
+ id: run
80
+ run: |
81
+ mkdir -p "$OUT"
82
+ ok=true
83
+ if [ "$MODE" = "check" ]; then
84
+ ${CLI} doctor --json > "$OUT/doctor.json" || ok=false
85
+ ${CLI} push --dry-run --json > "$OUT/push.json" || ok=false
86
+ elif [ -z "$SPLITHUB_API_KEY" ]; then
87
+ echo '{"error":"Add the SPLITHUB_API_KEY secret (dashboard, Settings, API keys) to post results."}' > "$OUT/report.json"
88
+ else
89
+ ${CLI} report --json > "$OUT/report.json" || ok=false
90
+ fi
91
+ echo "ok=$ok" >> "$GITHUB_OUTPUT"
92
+
93
+ - name: Write the comment
94
+ run: |
95
+ node - <<'JS'
96
+ const fs = require('fs');
97
+ const path = require('path');
98
+ const out = process.env.OUT;
99
+ const read = (name) => {
100
+ try {
101
+ const lines = fs.readFileSync(path.join(out, name), 'utf8').trim().split('\\n');
102
+ return JSON.parse(lines[lines.length - 1]);
103
+ } catch {
104
+ return null;
105
+ }
106
+ };
107
+ const hint = (r) => (r.hint ? ' ' + r.hint : '');
108
+ const lines = [];
109
+ if (process.env.MODE === 'check') {
110
+ const doctor = read('doctor.json');
111
+ const push = read('push.json');
112
+ lines.push('### SplitHub check', '');
113
+ if (!doctor) lines.push('Doctor did not run.');
114
+ else if (doctor.error) lines.push('\u2716 ' + doctor.error + hint(doctor));
115
+ else {
116
+ lines.push(doctor.ok ? '\u2714 No problems found.' : '\u2716 ' + doctor.errors + ' problem(s) to fix.', '');
117
+ for (const c of doctor.checks.filter((c) => c.level !== 'ok')) lines.push('- ' + (c.level === 'error' ? '\u2716' : '!') + ' ' + c.message);
118
+ }
119
+ lines.push('');
120
+ if (!push) lines.push('The config check did not run.');
121
+ else if (push.error) lines.push('\u2716 Config: ' + push.error + hint(push));
122
+ else if (!push.diff) lines.push('Config loads: ' + push.experiments.length + ' experiment(s). ' + (push.cloud === 'self mode' ? 'Self-hosted, nothing to push.' : 'Add the SPLITHUB_API_KEY secret to compare it with the cloud.'));
123
+ else {
124
+ const d = push.diff;
125
+ if (!d.added.length && !d.removed.length && !d.changed.length) lines.push('The cloud already has this config.');
126
+ else {
127
+ lines.push('After merge, \`npx splithub push\` changes:', '');
128
+ for (const k of d.added) lines.push('- added \`' + k + '\`');
129
+ for (const k of d.removed) lines.push('- removed \`' + k + '\`');
130
+ for (const c of d.changed) lines.push('- \`' + c.experiment + '\`: ' + c.fields.join(', '));
131
+ }
132
+ }
133
+ } else {
134
+ const report = read('report.json');
135
+ lines.push(!report ? 'SplitHub report did not run.' : report.error ? '### SplitHub\\n\\n' + report.error : report.markdown);
136
+ lines.push('', '<sub>Updated ' + new Date().toISOString().slice(0, 16).replace('T', ' ') + ' UTC</sub>');
137
+ }
138
+ fs.writeFileSync(path.join(out, 'body.md'), '<!-- splithub:' + process.env.MODE + ' -->\\n' + lines.join('\\n') + '\\n');
139
+ JS
140
+
141
+ - name: Post the sticky comment
142
+ run: |
143
+ marker="<!-- splithub:$MODE -->"
144
+ number="$PR_NUMBER"
145
+ if [ -z "$number" ]; then
146
+ number="$(gh issue list --repo "$GITHUB_REPOSITORY" --state open --search "$ISSUE_TITLE in:title" --json number,title --jq '.[] | [.number, .title] | @tsv' | awk -F '\\t' -v t="$ISSUE_TITLE" '$2 == t { print $1; exit }')"
147
+ fi
148
+ if [ -z "$number" ]; then
149
+ url="$(gh issue create --repo "$GITHUB_REPOSITORY" --title "$ISSUE_TITLE" --body 'A/B test results from SplitHub, refreshed by the SplitHub workflow.')"
150
+ number="\${url##*/}"
151
+ fi
152
+ id="$(gh api --paginate "repos/$GITHUB_REPOSITORY/issues/$number/comments" --jq '.[] | [.id, (.body | split("\\n") | .[0])] | @tsv' | awk -F '\\t' -v m="$marker" '$2 == m { print $1; exit }')"
153
+ if [ -n "$id" ]; then
154
+ gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$id" -F body=@"$OUT/body.md" > /dev/null
155
+ else
156
+ gh api "repos/$GITHUB_REPOSITORY/issues/$number/comments" -F body=@"$OUT/body.md" > /dev/null
157
+ fi
158
+
159
+ - name: Fail on problems
160
+ if: steps.run.outputs.ok != 'true' && env.MODE == 'check'
161
+ run: |
162
+ echo "SplitHub found problems: see the comment on the pull request."
163
+ exit 1
164
+ `;
165
+ }
166
+ function writeWorkflow(root, force = false) {
167
+ const repo = gitRoot(root);
168
+ const file = join(repo, ".github", "workflows", "splithub.yml");
169
+ const workingDirectory = relative(repo, root).replace(/\\/g, "/") || ".";
170
+ const written = force || !existsSync(file);
171
+ if (written) {
172
+ mkdirSync(dirname(file), { recursive: true });
173
+ writeFileSync(file, workflowTemplate(workingDirectory), "utf8");
174
+ }
175
+ return { file: relative(root, file).replace(/\\/g, "/"), written, workingDirectory, secret: "SPLITHUB_API_KEY" };
176
+ }
177
+ async function ciInit(flags) {
178
+ const project = detectProject();
179
+ const result = writeWorkflow(project.root, Boolean(flags.force));
180
+ const next = "Add the SPLITHUB_API_KEY secret in GitHub (Settings, Secrets and variables, Actions), then commit the workflow.";
181
+ if (flags.json) {
182
+ printJson({ ...result, next });
183
+ return;
184
+ }
185
+ console.log(result.written ? `${c.green("\u2714")} wrote ${result.file}` : c.dim(`${result.file} is already there; --force replaces it`));
186
+ console.log(c.dim(next));
187
+ }
188
+
189
+ export {
190
+ CLI,
191
+ workflowTemplate,
192
+ writeWorkflow,
193
+ ciInit
194
+ };
195
+ //# sourceMappingURL=chunk-EYYLDI5J.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/ci.ts"],"sourcesContent":["// `splithub ci init` (also `init --github-action`): write a GitHub workflow that\n// checks experiments on pull requests and posts results on a schedule.\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\nimport { printJson } from '../errors';\nimport { detectProject } from '../project';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\n/** The CLI as the workflow runs it: always the published package, never a private action. */\nexport const CLI = 'npx -y splithub@latest';\n\n/** The repository root: the closest folder with .git, else the project itself. */\nfunction gitRoot(from: string): string {\n let dir = from;\n for (;;) {\n if (existsSync(join(dir, '.git'))) return dir;\n const up = dirname(dir);\n if (up === dir) return from;\n dir = up;\n }\n}\n\n/**\n * A self-contained workflow: plain `run:` steps with the published CLI and the `gh`\n * that every GitHub runner has, plus actions/checkout and actions/setup-node only.\n * One sticky comment per mode, found again by its hidden marker and edited in place.\n */\nexport function workflowTemplate(workingDirectory: string): string {\n const wd = workingDirectory === '' ? '.' : workingDirectory;\n const configGlob = wd === '.' ? 'splithub.config.*' : `${wd}/splithub.config.*`;\n return `# SplitHub: checks experiments on pull requests that touch the config, and keeps\n# a results comment up to date on weekday mornings. Needs the SPLITHUB_API_KEY\n# secret (dashboard, Settings, API keys) for results and cloud comparisons.\nname: SplitHub\n\non:\n pull_request:\n paths:\n - '${configGlob}'\n schedule:\n - cron: '0 8 * * 1-5'\n workflow_dispatch:\n\npermissions:\n contents: read\n pull-requests: write\n issues: write\n\njobs:\n splithub:\n runs-on: ubuntu-latest\n defaults:\n run:\n shell: bash\n working-directory: ${wd}\n env:\n SPLITHUB_API_KEY: \\${{ secrets.SPLITHUB_API_KEY }}\n GH_TOKEN: \\${{ github.token }}\n NO_COLOR: '1'\n # check on a pull request (doctor + push --dry-run), report otherwise (results tables)\n MODE: \\${{ github.event_name == 'pull_request' && 'check' || 'report' }}\n PR_NUMBER: \\${{ github.event.pull_request.number }}\n ISSUE_TITLE: SplitHub results\n OUT: \\${{ runner.temp }}/splithub\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-node@v4\n with:\n node-version: 20\n\n - name: Install dependencies\n run: |\n # The config imports @splithub/core; the lockfile may live at the repository root.\n dir=\"$PWD\"\n while [ \"$dir\" != \"/\" ] && [ ! -f \"$dir/pnpm-lock.yaml\" ] && [ ! -f \"$dir/yarn.lock\" ] && [ ! -f \"$dir/package-lock.json\" ] && [ ! -f \"$dir/bun.lockb\" ] && [ ! -f \"$dir/bun.lock\" ]; do dir=\"$(dirname \"$dir\")\"; done\n cd \"$dir\"\n if [ -f pnpm-lock.yaml ]; then corepack enable && pnpm install --frozen-lockfile\n elif [ -f yarn.lock ]; then corepack enable && (yarn install --frozen-lockfile || yarn install --immutable)\n elif [ -f bun.lockb ] || [ -f bun.lock ]; then npm i -g bun && bun install --frozen-lockfile\n elif [ -f package-lock.json ]; then npm ci\n else npm install; fi\n\n - name: Run SplitHub\n id: run\n run: |\n mkdir -p \"$OUT\"\n ok=true\n if [ \"$MODE\" = \"check\" ]; then\n ${CLI} doctor --json > \"$OUT/doctor.json\" || ok=false\n ${CLI} push --dry-run --json > \"$OUT/push.json\" || ok=false\n elif [ -z \"$SPLITHUB_API_KEY\" ]; then\n echo '{\"error\":\"Add the SPLITHUB_API_KEY secret (dashboard, Settings, API keys) to post results.\"}' > \"$OUT/report.json\"\n else\n ${CLI} report --json > \"$OUT/report.json\" || ok=false\n fi\n echo \"ok=$ok\" >> \"$GITHUB_OUTPUT\"\n\n - name: Write the comment\n run: |\n node - <<'JS'\n const fs = require('fs');\n const path = require('path');\n const out = process.env.OUT;\n const read = (name) => {\n try {\n const lines = fs.readFileSync(path.join(out, name), 'utf8').trim().split('\\\\n');\n return JSON.parse(lines[lines.length - 1]);\n } catch {\n return null;\n }\n };\n const hint = (r) => (r.hint ? ' ' + r.hint : '');\n const lines = [];\n if (process.env.MODE === 'check') {\n const doctor = read('doctor.json');\n const push = read('push.json');\n lines.push('### SplitHub check', '');\n if (!doctor) lines.push('Doctor did not run.');\n else if (doctor.error) lines.push('✖ ' + doctor.error + hint(doctor));\n else {\n lines.push(doctor.ok ? '✔ No problems found.' : '✖ ' + doctor.errors + ' problem(s) to fix.', '');\n for (const c of doctor.checks.filter((c) => c.level !== 'ok')) lines.push('- ' + (c.level === 'error' ? '✖' : '!') + ' ' + c.message);\n }\n lines.push('');\n if (!push) lines.push('The config check did not run.');\n else if (push.error) lines.push('✖ Config: ' + push.error + hint(push));\n else if (!push.diff) lines.push('Config loads: ' + push.experiments.length + ' experiment(s). ' + (push.cloud === 'self mode' ? 'Self-hosted, nothing to push.' : 'Add the SPLITHUB_API_KEY secret to compare it with the cloud.'));\n else {\n const d = push.diff;\n if (!d.added.length && !d.removed.length && !d.changed.length) lines.push('The cloud already has this config.');\n else {\n lines.push('After merge, \\`npx splithub push\\` changes:', '');\n for (const k of d.added) lines.push('- added \\`' + k + '\\`');\n for (const k of d.removed) lines.push('- removed \\`' + k + '\\`');\n for (const c of d.changed) lines.push('- \\`' + c.experiment + '\\`: ' + c.fields.join(', '));\n }\n }\n } else {\n const report = read('report.json');\n lines.push(!report ? 'SplitHub report did not run.' : report.error ? '### SplitHub\\\\n\\\\n' + report.error : report.markdown);\n lines.push('', '<sub>Updated ' + new Date().toISOString().slice(0, 16).replace('T', ' ') + ' UTC</sub>');\n }\n fs.writeFileSync(path.join(out, 'body.md'), '<!-- splithub:' + process.env.MODE + ' -->\\\\n' + lines.join('\\\\n') + '\\\\n');\n JS\n\n - name: Post the sticky comment\n run: |\n marker=\"<!-- splithub:$MODE -->\"\n number=\"$PR_NUMBER\"\n if [ -z \"$number\" ]; then\n number=\"$(gh issue list --repo \"$GITHUB_REPOSITORY\" --state open --search \"$ISSUE_TITLE in:title\" --json number,title --jq '.[] | [.number, .title] | @tsv' | awk -F '\\\\t' -v t=\"$ISSUE_TITLE\" '$2 == t { print $1; exit }')\"\n fi\n if [ -z \"$number\" ]; then\n url=\"$(gh issue create --repo \"$GITHUB_REPOSITORY\" --title \"$ISSUE_TITLE\" --body 'A/B test results from SplitHub, refreshed by the SplitHub workflow.')\"\n number=\"\\${url##*/}\"\n fi\n id=\"$(gh api --paginate \"repos/$GITHUB_REPOSITORY/issues/$number/comments\" --jq '.[] | [.id, (.body | split(\"\\\\n\") | .[0])] | @tsv' | awk -F '\\\\t' -v m=\"$marker\" '$2 == m { print $1; exit }')\"\n if [ -n \"$id\" ]; then\n gh api -X PATCH \"repos/$GITHUB_REPOSITORY/issues/comments/$id\" -F body=@\"$OUT/body.md\" > /dev/null\n else\n gh api \"repos/$GITHUB_REPOSITORY/issues/$number/comments\" -F body=@\"$OUT/body.md\" > /dev/null\n fi\n\n - name: Fail on problems\n if: steps.run.outputs.ok != 'true' && env.MODE == 'check'\n run: |\n echo \"SplitHub found problems: see the comment on the pull request.\"\n exit 1\n`;\n}\n\nexport interface CiResult {\n file: string;\n written: boolean;\n workingDirectory: string;\n secret: string;\n}\n\nexport function writeWorkflow(root: string, force = false): CiResult {\n const repo = gitRoot(root);\n const file = join(repo, '.github', 'workflows', 'splithub.yml');\n const workingDirectory = relative(repo, root).replace(/\\\\/g, '/') || '.';\n const written = force || !existsSync(file);\n if (written) {\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, workflowTemplate(workingDirectory), 'utf8');\n }\n return { file: relative(root, file).replace(/\\\\/g, '/'), written, workingDirectory, secret: 'SPLITHUB_API_KEY' };\n}\n\nexport async function ciInit(flags: Flags): Promise<void> {\n const project = detectProject();\n const result = writeWorkflow(project.root, Boolean(flags.force));\n const next = 'Add the SPLITHUB_API_KEY secret in GitHub (Settings, Secrets and variables, Actions), then commit the workflow.';\n if (flags.json) {\n printJson({ ...result, next });\n return;\n }\n console.log(result.written ? `${c.green('✔')} wrote ${result.file}` : c.dim(`${result.file} is already there; --force replaces it`));\n console.log(c.dim(next));\n}\n"],"mappings":";;;;;;;;;;AAEA,SAAS,YAAY,WAAW,qBAAqB;AACrD,SAAS,SAAS,MAAM,gBAAgB;AAOjC,IAAM,MAAM;AAGnB,SAAS,QAAQ,MAAsB;AACrC,MAAI,MAAM;AACV,aAAS;AACP,QAAI,WAAW,KAAK,KAAK,MAAM,CAAC,EAAG,QAAO;AAC1C,UAAM,KAAK,QAAQ,GAAG;AACtB,QAAI,OAAO,IAAK,QAAO;AACvB,UAAM;AAAA,EACR;AACF;AAOO,SAAS,iBAAiB,kBAAkC;AACjE,QAAM,KAAK,qBAAqB,KAAK,MAAM;AAC3C,QAAM,aAAa,OAAO,MAAM,sBAAsB,GAAG,EAAE;AAC3D,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,WAQE,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,6BAgBQ,EAAE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,cAkCjB,GAAG;AAAA,cACH,GAAG;AAAA;AAAA;AAAA;AAAA,cAIH,GAAG;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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chunk-PLXDG4B5.js";
7
+
8
+ // src/refs.ts
9
+ var CONFIG_FILE = /(^|\/)splithub\.config\.[mc]?[jt]s$/;
10
+ function findRefs(root, config, id, files = listSourceFiles(root)) {
11
+ const exp = config?.experiments.find((e) => e.key === id);
12
+ const goal = exp?.goal ?? null;
13
+ const goalShared = Boolean(goal && config?.experiments.some((e) => e.key !== id && e.goal === goal));
14
+ const code = files.filter((f) => !CONFIG_FILE.test(f.replace(/\\/g, "/")));
15
+ const refs = grepLines(root, code, quoted(id)).map(({ needle: _n, ...hit }) => ({ ...hit, match: "experiment" }));
16
+ if (goal) {
17
+ for (const { needle: _n, ...hit } of grepLines(root, code, quoted(goal))) {
18
+ if (!refs.some((r) => r.file === hit.file && r.line === hit.line)) refs.push({ ...hit, match: "goal" });
19
+ }
20
+ }
21
+ refs.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
22
+ return { experiment: id, goal, goalShared, refs };
23
+ }
24
+
25
+ export {
26
+ findRefs
27
+ };
28
+ //# sourceMappingURL=chunk-GVARYUL3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/refs.ts"],"sourcesContent":["// Where an experiment and its goal appear in the project's code. Shared by\n// `doctor` (is it wired?), `refs` (what to touch) and `ship` (what is left).\nimport type { SplitHubConfig } from '@splithub/core';\nimport { grepLines, listSourceFiles, quoted, type LineHit } from './project';\n\nexport interface Ref extends Omit<LineHit, 'needle'> {\n /** experiment: the id in quotes · goal: the goal key in quotes. */\n match: 'experiment' | 'goal';\n}\n\nexport interface RefsResult {\n experiment: string;\n goal: string | null;\n /** True when another experiment measures the same goal: keep its track() calls. */\n goalShared: boolean;\n refs: Ref[];\n}\n\nconst CONFIG_FILE = /(^|\\/)splithub\\.config\\.[mc]?[jt]s$/;\n\nexport function findRefs(root: string, config: SplitHubConfig | null, id: string, files = listSourceFiles(root)): RefsResult {\n const exp = config?.experiments.find((e) => e.key === id);\n const goal = exp?.goal ?? null;\n const goalShared = Boolean(goal && config?.experiments.some((e) => e.key !== id && e.goal === goal));\n const code = files.filter((f) => !CONFIG_FILE.test(f.replace(/\\\\/g, '/')));\n const refs: Ref[] = grepLines(root, code, quoted(id)).map(({ needle: _n, ...hit }) => ({ ...hit, match: 'experiment' as const }));\n if (goal) {\n for (const { needle: _n, ...hit } of grepLines(root, code, quoted(goal))) {\n if (!refs.some((r) => r.file === hit.file && r.line === hit.line)) refs.push({ ...hit, match: 'goal' });\n }\n }\n refs.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);\n return { experiment: id, goal, goalShared, refs };\n}\n"],"mappings":";;;;;;;;AAkBA,IAAM,cAAc;AAEb,SAAS,SAAS,MAAc,QAA+B,IAAY,QAAQ,gBAAgB,IAAI,GAAe;AAC3H,QAAM,MAAM,QAAQ,YAAY,KAAK,CAAC,MAAM,EAAE,QAAQ,EAAE;AACxD,QAAM,OAAO,KAAK,QAAQ;AAC1B,QAAM,aAAa,QAAQ,QAAQ,QAAQ,YAAY,KAAK,CAAC,MAAM,EAAE,QAAQ,MAAM,EAAE,SAAS,IAAI,CAAC;AACnG,QAAM,OAAO,MAAM,OAAO,CAAC,MAAM,CAAC,YAAY,KAAK,EAAE,QAAQ,OAAO,GAAG,CAAC,CAAC;AACzE,QAAM,OAAc,UAAU,MAAM,MAAM,OAAO,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE,QAAQ,IAAI,GAAG,IAAI,OAAO,EAAE,GAAG,KAAK,OAAO,aAAsB,EAAE;AAChI,MAAI,MAAM;AACR,eAAW,EAAE,QAAQ,IAAI,GAAG,IAAI,KAAK,UAAU,MAAM,MAAM,OAAO,IAAI,CAAC,GAAG;AACxE,UAAI,CAAC,KAAK,KAAK,CAAC,MAAM,EAAE,SAAS,IAAI,QAAQ,EAAE,SAAS,IAAI,IAAI,EAAG,MAAK,KAAK,EAAE,GAAG,KAAK,OAAO,OAAO,CAAC;AAAA,IACxG;AAAA,EACF;AACA,OAAK,KAAK,CAAC,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,IAAI,KAAK,EAAE,OAAO,EAAE,IAAI;AACnE,SAAO,EAAE,YAAY,IAAI,MAAM,YAAY,KAAK;AAClD;","names":[]}
@@ -0,0 +1,185 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ hasExperiment,
4
+ insertExperiment,
5
+ loadConfig,
6
+ readSource,
7
+ writeConfigChecked
8
+ } from "./chunk-B6FITBWN.js";
9
+ import {
10
+ apiError,
11
+ cloudTarget,
12
+ requireCloudToken
13
+ } from "./chunk-BJQJGLOB.js";
14
+ import {
15
+ detectProject,
16
+ requireConfig
17
+ } from "./chunk-PLXDG4B5.js";
18
+ import {
19
+ c,
20
+ fail,
21
+ printJson
22
+ } from "./chunk-V3DLUVOE.js";
23
+
24
+ // src/commands/push.ts
25
+ import { relative } from "path";
26
+ function factorsOf(e) {
27
+ const out = {};
28
+ for (const f of e.factors ?? []) {
29
+ out[f.key] = {};
30
+ for (const level of f.levels) {
31
+ const combo = e.variants.find((v) => v.levels?.[f.key] === level);
32
+ const value = combo?.value?.[f.key];
33
+ out[f.key][level] = typeof value === "string" ? value : value === void 0 ? level : JSON.stringify(value);
34
+ }
35
+ }
36
+ return out;
37
+ }
38
+ async function adoptCloudExperiments(file, cloudOnly) {
39
+ if (!cloudOnly || cloudOnly.length === 0) return [];
40
+ const original = readSource(file);
41
+ let source = original;
42
+ const written = [];
43
+ for (const e of cloudOnly) {
44
+ if (hasExperiment(source, e.key)) continue;
45
+ const total = e.variants.reduce((s, v) => s + v.weight, 0) || 1;
46
+ source = insertExperiment(source, {
47
+ key: e.key,
48
+ kind: e.kind,
49
+ status: e.status,
50
+ goal: e.goal ?? void 0,
51
+ match: e.match ?? void 0,
52
+ description: e.description ?? void 0,
53
+ flow: e.flow ?? void 0,
54
+ traffic: e.traffic,
55
+ maxExposures: e.maxExposures ?? void 0,
56
+ minDays: e.minDays ?? void 0,
57
+ goodSample: e.goodSample ?? void 0,
58
+ schedule: e.schedule ?? void 0,
59
+ variants: e.variants.map((v) => ({ key: v.key, weight: Math.round(v.weight / total * 100), value: typeof v.value === "string" ? v.value : v.value === void 0 ? void 0 : JSON.stringify(v.value), to: v.to })),
60
+ ...e.kind === "mvt" && e.factors ? { factors: factorsOf(e) } : {}
61
+ });
62
+ written.push(e.key);
63
+ }
64
+ if (written.length) {
65
+ await writeConfigChecked(file, original, source, (config) => {
66
+ const missing = written.filter((k) => !config.experiments.some((x) => x.key === k));
67
+ return missing.length ? `${missing.join(", ")} did not load back` : null;
68
+ });
69
+ }
70
+ return written;
71
+ }
72
+ function configDiff(local, cloud) {
73
+ const added = local.filter((e) => !cloud.some((x) => x.key === e.key)).map((e) => e.key);
74
+ const removed = cloud.filter((x) => x.origin !== "dashboard" && !local.some((e) => e.key === x.key)).map((x) => x.key);
75
+ const changed = [];
76
+ for (const e of local) {
77
+ const x = cloud.find((y) => y.key === e.key);
78
+ if (!x) continue;
79
+ const fields = [];
80
+ if (x.status !== e.status) fields.push("status");
81
+ if ((x.goal ?? null) !== (e.goal ?? null)) fields.push("goal");
82
+ if (x.kind !== e.kind) fields.push("kind");
83
+ if (x.variants.map((v) => `${v.key}:${v.weight}`).join() !== e.variants.map((v) => `${v.key}:${v.weight}`).join()) fields.push("variants");
84
+ if ((x.traffic ?? 1) !== (e.traffic ?? 1)) fields.push("traffic");
85
+ if (fields.length) changed.push({ experiment: e.key, fields });
86
+ }
87
+ return { added, removed, changed };
88
+ }
89
+ async function cloudFetch(url, init) {
90
+ try {
91
+ return await fetch(url, init);
92
+ } catch (error) {
93
+ fail("UNREACHABLE", `Can't reach ${url}: ${error instanceof Error ? error.message : String(error)}.`, "Check your connection, or --api / SPLITHUB_API.");
94
+ }
95
+ }
96
+ async function push(flags) {
97
+ const project = requireConfig();
98
+ const config = await loadConfig(project.configFile);
99
+ if (flags["dry-run"]) return dryRun(flags, config);
100
+ if (config.storage.mode !== "cloud") {
101
+ fail("NOT_CLOUD", `This project stores events itself (storage.mode is "${config.storage.mode}"), so there's nothing to push.`, "Set storage: { mode: 'cloud' } in splithub.config.ts to use SplitHub Cloud.");
102
+ }
103
+ const target = requireCloudToken(flags);
104
+ const res = await cloudFetch(`${target.url}/config`, {
105
+ method: "PUT",
106
+ headers: { authorization: `Bearer ${target.token}`, "content-type": "application/json" },
107
+ body: JSON.stringify({ config })
108
+ });
109
+ const body = await res.json().catch(() => ({}));
110
+ if (!res.ok) throw apiError(res.status, body, `${target.url}/config responded ${res.status}`);
111
+ let keyWritten = false;
112
+ if (body.publicKey && !config.storage.key) {
113
+ const source = readSource(project.configFile);
114
+ const updated = source.replace(/(mode\s*:\s*['"]cloud['"]\s*)(,?)(\s*\})/, (_m, a, _comma, b) => `${a}, key: '${body.publicKey}'${b}`);
115
+ if (updated !== source) {
116
+ await writeConfigChecked(project.configFile, source, updated, (loaded) => loaded.storage.mode === "cloud" && loaded.storage.key === body.publicKey ? null : "storage.key did not load back");
117
+ keyWritten = true;
118
+ }
119
+ }
120
+ const adopted = await adoptCloudExperiments(project.configFile, body.cloudOnly);
121
+ const out = { ...body, configFile: relative(project.root, project.configFile), keyWritten, adopted };
122
+ if (flags.json) {
123
+ printJson(out);
124
+ return;
125
+ }
126
+ console.log(`${c.green("\u2714")} pushed ${c.bold(String(body.project))} v${body.version} \xB7 ${body.experiments} experiment(s) \u2192 ${target.url}`);
127
+ if (adopted.length) console.log(`${c.green("\u2714")} written into ${out.configFile} from the dashboard: ${adopted.join(", ")} (wire them in code if they are value/component experiments)`);
128
+ if (body.publicKey) {
129
+ console.log(keyWritten ? `${c.green("\u2714")} public key written to ${out.configFile}` : `${c.dim("public key:")} ${body.publicKey}`);
130
+ if (!keyWritten && !config.storage.key) console.log(c.yellow(`Add it to splithub.config.ts: storage: { mode: 'cloud', key: '${body.publicKey}' }`));
131
+ }
132
+ }
133
+ async function dryRun(flags, config) {
134
+ const experiments = config.experiments.map((e) => ({ experiment: e.key, kind: e.kind, status: e.status, goal: e.goal ?? null }));
135
+ let diff = null;
136
+ let cloud = config.storage.mode === "cloud" ? "not connected" : "self mode";
137
+ if (config.storage.mode === "cloud") {
138
+ const target = cloudTarget(flags);
139
+ if (target.token) {
140
+ const res = await cloudFetch(`${target.url}/config`, { headers: { authorization: `Bearer ${target.token}` } });
141
+ const body = await res.json().catch(() => ({}));
142
+ if (res.status === 404 || res.status === 409) diff = configDiff(config.experiments, []);
143
+ else if (!res.ok) throw apiError(res.status, body, `${target.url}/config responded ${res.status}`);
144
+ else diff = configDiff(config.experiments, body.config?.experiments ?? []);
145
+ cloud = "compared";
146
+ }
147
+ }
148
+ const out = { ok: true, dryRun: true, mode: config.storage.mode, project: config.project, experiments, cloud, diff };
149
+ if (flags.json) {
150
+ printJson(out);
151
+ return;
152
+ }
153
+ console.log(`${c.green("\u2714")} config loads \xB7 ${experiments.length} experiment(s) \xB7 ${config.storage.mode} mode`);
154
+ if (!diff) console.log(c.dim(cloud === "self mode" ? "Self mode: nothing to push." : "Not connected, so nothing to compare. Run npx splithub login."));
155
+ else if (!diff.added.length && !diff.removed.length && !diff.changed.length) console.log(c.dim("The cloud already has this config."));
156
+ else {
157
+ for (const k of diff.added) console.log(`${c.green("+")} ${k}`);
158
+ for (const k of diff.removed) console.log(`${c.red("-")} ${k}`);
159
+ for (const ch of diff.changed) console.log(`${c.yellow("~")} ${ch.experiment} ${c.dim(`(${ch.fields.join(", ")})`)}`);
160
+ }
161
+ }
162
+ async function pull(flags) {
163
+ const target = requireCloudToken(flags);
164
+ const res = await cloudFetch(`${target.url}/config`, { headers: { authorization: `Bearer ${target.token}` } });
165
+ const body = await res.json().catch(() => ({}));
166
+ if (!res.ok) throw apiError(res.status, body, `${target.url}/config responded ${res.status}`);
167
+ const project = detectProject();
168
+ const dashboardOnes = (body.config?.experiments ?? []).filter((e) => e.origin === "dashboard");
169
+ const adopted = project.configFile ? await adoptCloudExperiments(project.configFile, dashboardOnes) : [];
170
+ if (flags.json) {
171
+ printJson({ ...body, adopted });
172
+ return;
173
+ }
174
+ console.log(`${c.bold("cloud config")} v${body.version} ${c.dim(`pushed ${body.pushedAt}`)} \xB7 public key ${body.publicKey}`);
175
+ if (adopted.length) console.log(`${c.green("\u2714")} written into ${relative(project.root, project.configFile ?? "")}: ${adopted.join(", ")}`);
176
+ else if (dashboardOnes.length) console.log(c.dim(`dashboard experiments already present locally: ${dashboardOnes.map((e) => e.key).join(", ")}`));
177
+ else console.log(c.dim("no dashboard-created experiments to pull"));
178
+ }
179
+
180
+ export {
181
+ configDiff,
182
+ push,
183
+ pull
184
+ };
185
+ //# sourceMappingURL=chunk-KMO5GGGC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/push.ts"],"sourcesContent":["import type { SplitHubConfig } from '@splithub/core';\nimport { relative } from 'node:path';\nimport { apiError, cloudTarget, requireCloudToken } from '../api';\nimport { hasExperiment, insertExperiment, loadConfig, readSource, writeConfigChecked } from '../config-file';\nimport { fail, printJson } from '../errors';\nimport { detectProject, requireConfig } from '../project';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\ninterface CloudExperiment {\n key: string;\n kind: 'component' | 'value' | 'redirect' | 'mvt';\n status: 'draft' | 'running' | 'paused' | 'finished';\n goal: string | null;\n match: string | null;\n description: string | null;\n variants: Array<{ key: string; weight: number; value?: unknown; to?: string; levels?: Record<string, string> }>;\n /** Multivariate: the factors whose combinations the variants are. */\n factors?: Array<{ key: string; levels: string[] }>;\n flow?: unknown;\n traffic?: number;\n maxExposures?: number | null;\n minDays?: number | null;\n goodSample?: number | null;\n schedule?: { startAt?: string | null; endAt?: string | null } | null;\n}\n\ninterface PushResponse {\n ok: boolean;\n project: string;\n version: number;\n pushedAt: string;\n publicKey: string;\n experiments: number;\n /** Experiments created in the dashboard that the local file does not have yet. */\n cloudOnly?: CloudExperiment[];\n}\n\n/** Write dashboard-created experiments into the local config file. Returns the keys written. */\n/** Factor → level → value, read back from the combinations the cloud generated. */\nfunction factorsOf(e: CloudExperiment): Record<string, Record<string, string>> {\n const out: Record<string, Record<string, string>> = {};\n for (const f of e.factors ?? []) {\n out[f.key] = {};\n for (const level of f.levels) {\n const combo = e.variants.find((v) => v.levels?.[f.key] === level);\n const value = (combo?.value as Record<string, unknown> | undefined)?.[f.key];\n out[f.key]![level] = typeof value === 'string' ? value : value === undefined ? level : JSON.stringify(value);\n }\n }\n return out;\n}\n\nasync function adoptCloudExperiments(file: string, cloudOnly: CloudExperiment[] | undefined): Promise<string[]> {\n if (!cloudOnly || cloudOnly.length === 0) return [];\n const original = readSource(file);\n let source = original;\n const written: string[] = [];\n for (const e of cloudOnly) {\n if (hasExperiment(source, e.key)) continue;\n const total = e.variants.reduce((s, v) => s + v.weight, 0) || 1;\n source = insertExperiment(source, {\n key: e.key,\n kind: e.kind,\n status: e.status,\n goal: e.goal ?? undefined,\n match: e.match ?? undefined,\n description: e.description ?? undefined,\n flow: e.flow ?? undefined,\n traffic: e.traffic,\n maxExposures: e.maxExposures ?? undefined,\n minDays: e.minDays ?? undefined,\n goodSample: e.goodSample ?? undefined,\n schedule: e.schedule ?? undefined,\n variants: e.variants.map((v) => ({ key: v.key, weight: Math.round((v.weight / total) * 100), value: typeof v.value === 'string' ? v.value : v.value === undefined ? undefined : JSON.stringify(v.value), to: v.to })),\n ...(e.kind === 'mvt' && e.factors ? { factors: factorsOf(e) } : {}),\n });\n written.push(e.key);\n }\n if (written.length) {\n await writeConfigChecked(file, original, source, (config) => {\n const missing = written.filter((k) => !config.experiments.some((x) => x.key === k));\n return missing.length ? `${missing.join(', ')} did not load back` : null;\n });\n }\n return written;\n}\n\ntype LocalExperiment = SplitHubConfig['experiments'][number];\n\nexport interface ConfigDiff {\n added: string[];\n removed: string[];\n changed: Array<{ experiment: string; fields: string[] }>;\n}\n\n/** What a push would change in the cloud, by experiment key. */\nexport function configDiff(local: LocalExperiment[], cloud: Array<CloudExperiment & { origin?: string }>): ConfigDiff {\n const added = local.filter((e) => !cloud.some((x) => x.key === e.key)).map((e) => e.key);\n const removed = cloud.filter((x) => x.origin !== 'dashboard' && !local.some((e) => e.key === x.key)).map((x) => x.key);\n const changed: ConfigDiff['changed'] = [];\n for (const e of local) {\n const x = cloud.find((y) => y.key === e.key);\n if (!x) continue;\n const fields: string[] = [];\n if (x.status !== e.status) fields.push('status');\n if ((x.goal ?? null) !== (e.goal ?? null)) fields.push('goal');\n if (x.kind !== e.kind) fields.push('kind');\n if (x.variants.map((v) => `${v.key}:${v.weight}`).join() !== e.variants.map((v) => `${v.key}:${v.weight}`).join()) fields.push('variants');\n if ((x.traffic ?? 1) !== (e.traffic ?? 1)) fields.push('traffic');\n if (fields.length) changed.push({ experiment: e.key, fields });\n }\n return { added, removed, changed };\n}\n\nasync function cloudFetch(url: string, init: RequestInit): Promise<Response> {\n try {\n return await fetch(url, init);\n } catch (error) {\n fail('UNREACHABLE', `Can't reach ${url}: ${error instanceof Error ? error.message : String(error)}.`, 'Check your connection, or --api / SPLITHUB_API.');\n }\n}\n\n/**\n * `splithub push`: upload the normalized splithub.config.ts to SplitHub Cloud.\n * Needs a project API key (sk_...) via --token or SPLITHUB_API_KEY. The first\n * push returns the public key (pk_...) which is written into the config's\n * `storage.key` when it is still empty. `--dry-run` only checks and compares.\n */\nexport async function push(flags: Flags): Promise<void> {\n const project = requireConfig();\n const config = await loadConfig(project.configFile);\n if (flags['dry-run']) return dryRun(flags, config);\n if (config.storage.mode !== 'cloud') {\n fail('NOT_CLOUD', `This project stores events itself (storage.mode is \"${config.storage.mode}\"), so there's nothing to push.`, \"Set storage: { mode: 'cloud' } in splithub.config.ts to use SplitHub Cloud.\");\n }\n const target = requireCloudToken(flags);\n\n const res = await cloudFetch(`${target.url}/config`, {\n method: 'PUT',\n headers: { authorization: `Bearer ${target.token}`, 'content-type': 'application/json' },\n body: JSON.stringify({ config }),\n });\n const body = (await res.json().catch(() => ({}))) as Partial<PushResponse> & { error?: string };\n if (!res.ok) throw apiError(res.status, body, `${target.url}/config responded ${res.status}`);\n\n // Write the public key into the config when it is missing.\n let keyWritten = false;\n if (body.publicKey && !config.storage.key) {\n const source = readSource(project.configFile);\n const updated = source.replace(/(mode\\s*:\\s*['\"]cloud['\"]\\s*)(,?)(\\s*\\})/, (_m, a: string, _comma: string, b: string) => `${a}, key: '${body.publicKey}'${b}`);\n if (updated !== source) {\n await writeConfigChecked(project.configFile, source, updated, (loaded) => (loaded.storage.mode === 'cloud' && loaded.storage.key === body.publicKey ? null : 'storage.key did not load back'));\n keyWritten = true;\n }\n }\n\n const adopted = await adoptCloudExperiments(project.configFile, body.cloudOnly);\n const out = { ...body, configFile: relative(project.root, project.configFile), keyWritten, adopted };\n if (flags.json) {\n printJson(out);\n return;\n }\n console.log(`${c.green('✔')} pushed ${c.bold(String(body.project))} v${body.version} · ${body.experiments} experiment(s) → ${target.url}`);\n if (adopted.length) console.log(`${c.green('✔')} written into ${out.configFile} from the dashboard: ${adopted.join(', ')} (wire them in code if they are value/component experiments)`);\n if (body.publicKey) {\n console.log(keyWritten ? `${c.green('✔')} public key written to ${out.configFile}` : `${c.dim('public key:')} ${body.publicKey}`);\n if (!keyWritten && !config.storage.key) console.log(c.yellow(`Add it to splithub.config.ts: storage: { mode: 'cloud', key: '${body.publicKey}' }`));\n }\n}\n\n/** `push --dry-run`: the config loads; when connected, what a push would change. Writes nothing. */\nasync function dryRun(flags: Flags, config: SplitHubConfig): Promise<void> {\n const experiments = config.experiments.map((e) => ({ experiment: e.key, kind: e.kind, status: e.status, goal: e.goal ?? null }));\n let diff: ConfigDiff | null = null;\n let cloud: 'compared' | 'not connected' | 'self mode' = config.storage.mode === 'cloud' ? 'not connected' : 'self mode';\n if (config.storage.mode === 'cloud') {\n const target = cloudTarget(flags);\n if (target.token) {\n const res = await cloudFetch(`${target.url}/config`, { headers: { authorization: `Bearer ${target.token}` } });\n const body = (await res.json().catch(() => ({}))) as { config?: { experiments?: CloudExperiment[] } };\n if (res.status === 404 || res.status === 409) diff = configDiff(config.experiments, []);\n else if (!res.ok) throw apiError(res.status, body, `${target.url}/config responded ${res.status}`);\n else diff = configDiff(config.experiments, body.config?.experiments ?? []);\n cloud = 'compared';\n }\n }\n const out = { ok: true, dryRun: true, mode: config.storage.mode, project: config.project, experiments, cloud, diff };\n if (flags.json) {\n printJson(out);\n return;\n }\n console.log(`${c.green('✔')} config loads · ${experiments.length} experiment(s) · ${config.storage.mode} mode`);\n if (!diff) console.log(c.dim(cloud === 'self mode' ? 'Self mode: nothing to push.' : 'Not connected, so nothing to compare. Run npx splithub login.'));\n else if (!diff.added.length && !diff.removed.length && !diff.changed.length) console.log(c.dim('The cloud already has this config.'));\n else {\n for (const k of diff.added) console.log(`${c.green('+')} ${k}`);\n for (const k of diff.removed) console.log(`${c.red('-')} ${k}`);\n for (const ch of diff.changed) console.log(`${c.yellow('~')} ${ch.experiment} ${c.dim(`(${ch.fields.join(', ')})`)}`);\n }\n}\n\n/** `splithub pull`: print the config stored in the cloud (for inspection or recovery). */\nexport async function pull(flags: Flags): Promise<void> {\n const target = requireCloudToken(flags);\n const res = await cloudFetch(`${target.url}/config`, { headers: { authorization: `Bearer ${target.token}` } });\n const body = (await res.json().catch(() => ({}))) as { error?: string; config?: { experiments?: Array<CloudExperiment & { origin?: string }> }; version?: number; pushedAt?: string; publicKey?: string };\n if (!res.ok) throw apiError(res.status, body, `${target.url}/config responded ${res.status}`);\n const project = detectProject();\n const dashboardOnes = (body.config?.experiments ?? []).filter((e) => e.origin === 'dashboard');\n const adopted = project.configFile ? await adoptCloudExperiments(project.configFile, dashboardOnes) : [];\n if (flags.json) {\n printJson({ ...body, adopted });\n return;\n }\n console.log(`${c.bold('cloud config')} v${body.version} ${c.dim(`pushed ${body.pushedAt}`)} · public key ${body.publicKey}`);\n if (adopted.length) console.log(`${c.green('✔')} written into ${relative(project.root, project.configFile ?? '')}: ${adopted.join(', ')}`);\n else if (dashboardOnes.length) console.log(c.dim(`dashboard experiments already present locally: ${dashboardOnes.map((e) => e.key).join(', ')}`));\n else console.log(c.dim('no dashboard-created experiments to pull'));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;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