splithub 0.5.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/dist/{alerts-RXUG22S7.js → alerts-WOWJ3MZV.js} +4 -4
- package/dist/{analytics-3TFARFQE.js → analytics-ZGLVQDIL.js} +5 -5
- package/dist/{chunk-5UN2NKIF.js → chunk-3V6SD74H.js} +9 -9
- package/dist/chunk-3V6SD74H.js.map +1 -0
- package/dist/{chunk-5Y6HUYA6.js → chunk-4AZ2EOIY.js} +3 -3
- package/dist/chunk-4AZ2EOIY.js.map +1 -0
- package/dist/{chunk-5JKDO4IN.js → chunk-4DPMTGNP.js} +3 -3
- package/dist/chunk-4DPMTGNP.js.map +1 -0
- package/dist/{chunk-JZH4ZC2R.js → chunk-5R6543RT.js} +6 -6
- package/dist/chunk-5R6543RT.js.map +1 -0
- package/dist/{chunk-RBV5NIMY.js → chunk-7ADMC5F3.js} +3 -3
- package/dist/chunk-7ADMC5F3.js.map +1 -0
- package/dist/{chunk-OXQZJCAC.js → chunk-BDCKWKJB.js} +37 -37
- package/dist/chunk-BDCKWKJB.js.map +1 -0
- package/dist/{chunk-CAFWOX3S.js → chunk-BLEJ5DOY.js} +2 -2
- package/dist/chunk-BLEJ5DOY.js.map +1 -0
- package/dist/{chunk-XTHEBWKY.js → chunk-DOPSOUUT.js} +7 -7
- package/dist/chunk-DOPSOUUT.js.map +1 -0
- package/dist/{chunk-YZPQK4N7.js → chunk-GWWJHAH4.js} +4 -4
- package/dist/chunk-GWWJHAH4.js.map +1 -0
- package/dist/{chunk-4OQEIP33.js → chunk-H5GMGCOT.js} +3 -3
- package/dist/chunk-H5GMGCOT.js.map +1 -0
- package/dist/{chunk-YRHCGHV7.js → chunk-I5YYG3NU.js} +3 -3
- package/dist/chunk-I5YYG3NU.js.map +1 -0
- package/dist/{chunk-FCV7PQN6.js → chunk-IIX2EISO.js} +4 -4
- package/dist/chunk-IIX2EISO.js.map +1 -0
- package/dist/{chunk-G2URJ423.js → chunk-ISEVDVKJ.js} +3 -3
- package/dist/chunk-ISEVDVKJ.js.map +1 -0
- package/dist/{chunk-Q4W6H7XO.js → chunk-JFRRGBZU.js} +6 -6
- package/dist/chunk-JFRRGBZU.js.map +1 -0
- package/dist/{chunk-WQETHW5W.js → chunk-JQA3WWEQ.js} +4 -4
- package/dist/chunk-JQA3WWEQ.js.map +1 -0
- package/dist/{chunk-Z2LTGGUG.js → chunk-KWL6EUML.js} +3 -3
- package/dist/chunk-KWL6EUML.js.map +1 -0
- package/dist/{chunk-LWJSVUMI.js → chunk-LF4ZI43E.js} +2 -2
- package/dist/{chunk-WV6RNTIM.js → chunk-NZ4RSQ56.js} +3 -3
- package/dist/{chunk-WV6RNTIM.js.map → chunk-NZ4RSQ56.js.map} +1 -1
- package/dist/{chunk-ZHM47JI5.js → chunk-PWLTCKEC.js} +6 -6
- package/dist/chunk-PWLTCKEC.js.map +1 -0
- package/dist/{chunk-SXFGWWE7.js → chunk-Q5LYYWYC.js} +15 -15
- package/dist/chunk-Q5LYYWYC.js.map +1 -0
- package/dist/{chunk-56WHXKGA.js → chunk-VMYL36BP.js} +2 -2
- package/dist/{chunk-NFZZSF4M.js → chunk-XT7Z5GY2.js} +2 -2
- package/dist/{ci-W72GPWEB.js → ci-G4IQPM5K.js} +2 -2
- package/dist/{connect-SHXP65T2.js → connect-BICSF6XG.js} +11 -11
- package/dist/connect-BICSF6XG.js.map +1 -0
- package/dist/{create-HRROFCS2.js → create-7VLV2H67.js} +3 -3
- package/dist/{dev-4O4ZVVKH.js → dev-3CPW4LTF.js} +3 -3
- package/dist/{doctor-GCAMTBJG.js → doctor-L7NTDL2E.js} +4 -4
- package/dist/domains-J5SKVM6S.js +10 -0
- package/dist/{experiment-reports-WMODMYBX.js → experiment-reports-AN4S7PYS.js} +5 -5
- package/dist/index.js +32 -32
- package/dist/index.js.map +1 -1
- package/dist/init-Q234CCOT.js +19 -0
- package/dist/{lifecycle-C6RF5MC6.js → lifecycle-RROP7JMK.js} +3 -3
- package/dist/{links-JWPXODYS.js → links-DYSFIVRV.js} +4 -4
- package/dist/{login-OT77MNKL.js → login-JIH5576K.js} +3 -3
- package/dist/{menu-XMAEYJNC.js → menu-TCO6OVKR.js} +26 -26
- package/dist/menu-TCO6OVKR.js.map +1 -0
- package/dist/{notes-QN5XW2TI.js → notes-KHLQUNEF.js} +4 -4
- package/dist/{plan-UHBAQXRB.js → plan-BYRG2YK6.js} +3 -3
- package/dist/plan-BYRG2YK6.js.map +1 -0
- package/dist/{push-UJHOXRO3.js → push-6MOHROGS.js} +3 -3
- package/dist/{remove-MSEG2USQ.js → remove-C65D4VDA.js} +2 -2
- package/dist/{report-E6EJECSP.js → report-Z5XHK5D6.js} +4 -4
- package/dist/report-Z5XHK5D6.js.map +1 -0
- package/dist/{results-OJJKMZ4O.js → results-3UYAU4OP.js} +6 -6
- package/dist/{review-GIYBPVP3.js → review-FOE4IIXA.js} +2 -2
- package/dist/{ship-6A6EWZEX.js → ship-6HWSIA2E.js} +2 -2
- package/dist/{skills-4G73YN3S.js → skills-RBRC7UWI.js} +4 -4
- package/dist/status-RLKOX6NA.js +17 -0
- package/package.json +4 -4
- package/dist/chunk-4OQEIP33.js.map +0 -1
- package/dist/chunk-5JKDO4IN.js.map +0 -1
- package/dist/chunk-5UN2NKIF.js.map +0 -1
- package/dist/chunk-5Y6HUYA6.js.map +0 -1
- package/dist/chunk-CAFWOX3S.js.map +0 -1
- package/dist/chunk-FCV7PQN6.js.map +0 -1
- package/dist/chunk-G2URJ423.js.map +0 -1
- package/dist/chunk-JZH4ZC2R.js.map +0 -1
- package/dist/chunk-OXQZJCAC.js.map +0 -1
- package/dist/chunk-Q4W6H7XO.js.map +0 -1
- package/dist/chunk-RBV5NIMY.js.map +0 -1
- package/dist/chunk-SXFGWWE7.js.map +0 -1
- package/dist/chunk-WQETHW5W.js.map +0 -1
- package/dist/chunk-XTHEBWKY.js.map +0 -1
- package/dist/chunk-YRHCGHV7.js.map +0 -1
- package/dist/chunk-YZPQK4N7.js.map +0 -1
- package/dist/chunk-Z2LTGGUG.js.map +0 -1
- package/dist/chunk-ZHM47JI5.js.map +0 -1
- package/dist/connect-SHXP65T2.js.map +0 -1
- package/dist/domains-CR34APOD.js +0 -10
- package/dist/init-X2D3YAMU.js +0 -19
- package/dist/menu-XMAEYJNC.js.map +0 -1
- package/dist/plan-UHBAQXRB.js.map +0 -1
- package/dist/report-E6EJECSP.js.map +0 -1
- package/dist/status-SDXLN4SE.js +0 -17
- /package/dist/{alerts-RXUG22S7.js.map → alerts-WOWJ3MZV.js.map} +0 -0
- /package/dist/{analytics-3TFARFQE.js.map → analytics-ZGLVQDIL.js.map} +0 -0
- /package/dist/{chunk-LWJSVUMI.js.map → chunk-LF4ZI43E.js.map} +0 -0
- /package/dist/{chunk-56WHXKGA.js.map → chunk-VMYL36BP.js.map} +0 -0
- /package/dist/{chunk-NFZZSF4M.js.map → chunk-XT7Z5GY2.js.map} +0 -0
- /package/dist/{ci-W72GPWEB.js.map → ci-G4IQPM5K.js.map} +0 -0
- /package/dist/{create-HRROFCS2.js.map → create-7VLV2H67.js.map} +0 -0
- /package/dist/{dev-4O4ZVVKH.js.map → dev-3CPW4LTF.js.map} +0 -0
- /package/dist/{doctor-GCAMTBJG.js.map → doctor-L7NTDL2E.js.map} +0 -0
- /package/dist/{domains-CR34APOD.js.map → domains-J5SKVM6S.js.map} +0 -0
- /package/dist/{experiment-reports-WMODMYBX.js.map → experiment-reports-AN4S7PYS.js.map} +0 -0
- /package/dist/{init-X2D3YAMU.js.map → init-Q234CCOT.js.map} +0 -0
- /package/dist/{lifecycle-C6RF5MC6.js.map → lifecycle-RROP7JMK.js.map} +0 -0
- /package/dist/{links-JWPXODYS.js.map → links-DYSFIVRV.js.map} +0 -0
- /package/dist/{login-OT77MNKL.js.map → login-JIH5576K.js.map} +0 -0
- /package/dist/{notes-QN5XW2TI.js.map → notes-KHLQUNEF.js.map} +0 -0
- /package/dist/{push-UJHOXRO3.js.map → push-6MOHROGS.js.map} +0 -0
- /package/dist/{remove-MSEG2USQ.js.map → remove-C65D4VDA.js.map} +0 -0
- /package/dist/{results-OJJKMZ4O.js.map → results-3UYAU4OP.js.map} +0 -0
- /package/dist/{review-GIYBPVP3.js.map → review-FOE4IIXA.js.map} +0 -0
- /package/dist/{ship-6A6EWZEX.js.map → ship-6HWSIA2E.js.map} +0 -0
- /package/dist/{skills-4G73YN3S.js.map → skills-RBRC7UWI.js.map} +0 -0
- /package/dist/{status-SDXLN4SE.js.map → status-RLKOX6NA.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
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 'Experiment 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;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C;AACnI,UAAQ,IAAI,EAAE,IAAI,IAAI,CAAC;AACzB;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
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\nexport interface 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 name?: string;\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 /** Experiments from an earlier push that the file lacks, left in the cloud as they are; `--prune` removes them. */\n kept?: string[];\n /** The file's analytics properties were not applied: the key or member lacks analytics:write. */\n propertiesSkipped?: boolean;\n hint?: string;\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 name: e.name,\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 /** In the cloud only; a push without `--prune` leaves them. */\n kept: 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 }>, prune = false): ConfigDiff {\n const added = local.filter((e) => !cloud.some((x) => x.key === e.key)).map((e) => e.key);\n const missing = cloud.filter((x) => x.origin !== 'dashboard' && !local.some((e) => e.key === x.key)).map((x) => x.key);\n const removed = prune ? missing : [];\n const kept = prune ? [] : missing;\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, kept, changed };\n}\n\ninterface KeyConflict {\n key: string;\n reason: 'dashboard' | 'old_data';\n exposures?: number;\n}\n\nconst keyList = (v: Flags[string]): string[] => (typeof v === 'string' ? v.split(',').map((k) => k.trim()).filter(Boolean) : []);\n\n/** The cloud already has another test under a pushed key: say which, and the two ways on. */\nfunction keyConflict(conflicts: KeyConflict[]): never {\n const why = conflicts.map((k) => (k.reason === 'dashboard' ? `${k.key} (a different experiment made in the dashboard)` : `${k.key} (an earlier experiment, ${(k.exposures ?? 0).toLocaleString('en-US')} visitors)`));\n const keys = conflicts.map((k) => k.key).join(',');\n fail(\n 'KEY_CONFLICT',\n `These keys already belong to another experiment in the cloud: ${why.join('; ')}. Nothing was pushed.`,\n `New experiment: rename its key, or run npx splithub push --replace ${keys} (the old numbers are cleared). Same experiment: npx splithub push --same ${keys}.`\n );\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 * Experiments the cloud has from an earlier push that the file lacks are kept\n * unless `--prune`.\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, replace: keyList(flags.replace), same: keyList(flags.same), prune: Boolean(flags.prune) }),\n });\n const body = (await res.json().catch(() => ({}))) as Partial<PushResponse> & { error?: string; code?: string; conflicts?: KeyConflict[] };\n if (res.status === 409 && body.code === 'key_conflict' && body.conflicts?.length) keyConflict(body.conflicts);\n if (res.status === 409 && body.code === 'key_deleted') fail('KEY_DELETED', `${body.error ?? 'A deleted experiment used one of these keys'}. Nothing was pushed.`, 'Give the experiment a new key in splithub.config.ts and push again.');\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 // The key goes into a file that is executed; anything but a plain pk_ key stays out.\n if (body.publicKey && /^pk_[A-Za-z0-9_]+$/.test(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 (body.kept?.length) console.log(c.yellow(`! kept in the cloud, not in ${out.configFile}: ${body.kept.join(', ')}. They go on as they are; npx splithub push --prune removes them.`));\n if (body.propertiesSkipped) console.log(c.yellow(`! ${body.hint ?? 'Analytics properties were left as they are: changing them needs analytics:write.'}`));\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 const prune = Boolean(flags.prune);\n if (res.status === 404 || res.status === 409) diff = configDiff(config.experiments, [], prune);\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 ?? [], prune);\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.kept.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 for (const k of diff.kept) console.log(c.dim(`= ${k} (in the cloud only: kept; --prune removes it)`));\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":";;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,gBAAgB;AA6CzB,SAAS,UAAU,GAA4D;AAC7E,QAAM,MAA8C,CAAC;AACrD,aAAW,KAAK,EAAE,WAAW,CAAC,GAAG;AAC/B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AAK,QAAQ,EAAE,CAAC,oBAAiB,KAAK,SAAS,EAAE;AAC3H,MAAI,QAAQ,OAAQ,SAAQ,IAAI,GAAG,EAAE,MAAM,QAAG,CAAC,iBAAiB,SAAS,QAAQ,MAAM,QAAQ,cAAc,EAAE,CAAC,KAAK,QAAQ,KAAK,IAAI,CAAC,EAAE;AAAA,WAChI,cAAc,OAAQ,SAAQ,IAAI,EAAE,IAAI,kDAAkD,cAAc,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,KAAK,IAAI,CAAC,EAAE,CAAC;AAAA,MAC3I,SAAQ,IAAI,EAAE,IAAI,0CAA0C,CAAC;AACpE;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/domains.ts"],"sourcesContent":["// splithub domains — which origins may send events, per test and per analytics property.\n//\n// splithub domains every allowed domain and where it applies\n// splithub domains set test <id> example.com [...] replace a test's list\n// splithub domains set property <id> example.com replace a property's list\n// splithub domains clear test|property <id> accept any origin again\n//\n// A test or property without domains accepts events from anywhere. SplitHub Cloud only.\n\nimport { request, requireCloudToken } from '../api';\nimport { fail, printJson } from '../errors';\nimport { c, table } from '../ui';\nimport type { Flags } from './init';\n\ninterface DomainsData {\n entries: Array<{ kind: 'experiment' | 'property'; key: string; host: string }>;\n entities: Array<{ kind: 'experiment' | 'property'; key: string; name: string | null; status: string }>;\n observed: Array<{ host: string; events: number; lastSeen: number; allowedIn: Array<{ kind: string; key: string }> }>;\n}\n\nconst KINDS: Record<string, 'experiment' | 'property'> = { test: 'experiment', experiment: 'experiment', property: 'property' };\nconst label = (kind: string) => (kind === 'experiment' ? 'experiment' : 'property');\n\nexport async function domains(args: string[], flags: Flags): Promise<void> {\n const target = requireCloudToken(flags);\n const [action, kindArg, key, ...hosts] = args;\n if (!action) {\n const data = await request<DomainsData>(target, '/domains');\n if (flags.json) return printJson(data);\n const byHost = new Map<string, string[]>();\n for (const e of data.entries) byHost.set(e.host, [...(byHost.get(e.host) ?? []), `${label(e.kind)} ${e.key}`]);\n if (byHost.size === 0) console.log(c.dim('No experiment or property limits its origins: events are accepted from anywhere.'));\n else console.log(table(['DOMAIN', 'ALLOWED FOR'], [...byHost].map(([host, where]) => [c.bold(host), where.join(', ')])));\n const open = data.entities.filter((e) => !data.entries.some((x) => x.kind === e.kind && x.key === e.key));\n if (open.length && byHost.size) console.log(`\\n${c.dim(`Any origin: ${open.map((e) => `${label(e.kind)} ${e.key}`).join(', ')}`)}`);\n if (data.observed.length) {\n console.log(`\\n${c.bold('Seen sending events')}`);\n console.log(table(['ORIGIN', 'EVENTS', 'ALLOWED FOR'], data.observed.slice(0, 15).map((o) => [o.host, o.events.toLocaleString('en-US'), o.allowedIn.length ? o.allowedIn.map((a) => `${label(a.kind)} ${a.key}`).join(', ') : c.dim('–')])));\n }\n return;\n }\n if (action !== 'set' && action !== 'clear') fail('USAGE', `Unknown action \"${action}\". Use npx splithub domains set experiment <id> <domain...> or domains clear experiment <id>.`);\n const kind = KINDS[kindArg ?? ''];\n if (!kind || !key) fail('USAGE', `npx splithub domains ${action} experiment|property <id>${action === 'set' ? ' <domain...>' : ''}`);\n if (action === 'set' && hosts.length === 0) fail('USAGE', 'Which domains? npx splithub domains set experiment <id> example.com app.example.com (subdomains are included).');\n const out = await request<{ kind: string; key: string; hosts: string[] }>(target, `/domains/${kind}/${encodeURIComponent(key)}`, { method: 'PUT', body: JSON.stringify({ hosts: action === 'clear' ? [] : hosts }) });\n if (flags.json) return printJson(out);\n if (out.hosts.length === 0) console.log(`${c.green('✔')} ${label(kind)} ${c.bold(key)} accepts events from any origin`);\n else console.log(`${c.green('✔')} ${label(kind)} ${c.bold(key)} accepts events from ${out.hosts.join(', ')} ${c.dim('(and their subdomains; live within 60s)')}`);\n}\n"],"mappings":";;;;;;;;;;;;;AAoBA,IAAM,QAAmD,EAAE,MAAM,cAAc,YAAY,cAAc,UAAU,WAAW;AAC9H,IAAM,QAAQ,CAAC,SAAkB,SAAS,eAAe,eAAe;A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,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,eAAe,OAAO,GAAG,EAAE,UAAU,SAAS,EAAE,UAAU,IAAI,CAAC,MAAM,GAAG,MAAM,EAAE,IAAI,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,KAAK,IAAI,IAAI,EAAE,IAAI,QAAG,CAAC,CAAC,CAAC,CAAC;AAAA,IAC7O;AACA;AAAA,EACF;AACA,MAAI,WAAW,SAAS,WAAW,QAAS,MAAK,SAAS,mBAAmB,MAAM,+FAA+F;AAClL,QAAM,OAAO,MAAM,WAAW,EAAE;AAChC,MAAI,CAAC,QAAQ,CAAC,IAAK,MAAK,SAAS,wBAAwB,MAAM,4BAA4B,WAAW,QAAQ,iBAAiB,EAAE,EAAE;AACnI,MAAI,WAAW,SAAS,MAAM,WAAW,EAAG,MAAK,SAAS,gHAAgH;AAC1K,QAAM,MAAM,MAAM,QAAwD,QAAQ,YAAY,IAAI,IAAI,mBAAmB,GAAG,CAAC,IAAI,EAAE,QAAQ,OAAO,MAAM,KAAK,UAAU,EAAE,OAAO,WAAW,UAAU,CAAC,IAAI,MAAM,CAAC,EAAE,CAAC;AACpN,MAAI,MAAM,KAAM,QAAO,UAAU,GAAG;AACpC,MAAI,IAAI,MAAM,WAAW,EAAG,SAAQ,IAAI,GAAG,EAAE,MAAM,QAAG,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,EAAE,KAAK,GAAG,CAAC,iCAAiC;AAAA,MACjH,SAAQ,IAAI,GAAG,EAAE,MAAM,QAAG,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,EAAE,KAAK,GAAG,CAAC,wBAAwB,IAAI,MAAM,KAAK,IAAI,CAAC,IAAI,EAAE,IAAI,yCAAyC,CAAC,EAAE;AAClK;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/experiment-reports.ts"],"sourcesContent":["// One experiment, read closer (SplitHub Cloud only: a self-hosted endpoint keeps raw counts).\n//\n// splithub results <id> [--from --to] [--filter country=DE ...] the verdict on a slice: first-exposure days, visitor filters\n// splithub results <id> --by <dimension> every segment's variants against the control there\n// splithub results <id> --timeline visitors and conversions per day and variant\n// splithub results <id> --engagement bounce, visit length, pages per visit per variant\n// splithub results <id> --events every goal and event per variant, lift vs control\n// splithub results <id> --export --by <dimension> > file.csv the breakdown as CSV\n// splithub events --experiment <id> [--type exposure|goal] [--limit 50] [--before <ms>] the raw tail\n//\n// Every view takes --from / --to (YYYY-MM-DD, first-exposure days in the project time zone) and --filter.\n\nimport { request, requestText, type Target } from '../api';\nimport { fail, printJson } from '../errors';\nimport { c, pct, table } from '../ui';\nimport { cloudOnly, filterFlags, n, reportQuery, str } from './analytics-reports';\nimport type { Flags } from './init';\nimport { noteKind } from './notes';\n\n/** Visitor columns an experiment report can be filtered by (`--filter <key>=a,b`); `page` is analytics' word for `landing`. */\nexport const EXPERIMENT_FILTERS = ['country', 'region', 'city', 'device', 'os', 'browser', 'language', 'host', 'platform', 'app_version', 'source', 'channel', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'landing', 'page'] as const;\n/** Dimensions a breakdown splits visitors by (`--by`); `page` is analytics' word for `url`. */\nexport const EXPERIMENT_BY = ['country', 'region', 'city', 'device', 'os', 'browser', 'language', 'host', 'platform', 'app_version', 'page', 'url', 'referrer', 'source', 'channel', 'landing', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'] as const;\n\n/** Column title of a dimension: `url` reads \"page\", as in analytics and the dashboard. */\nexport const dimensionLabel = (by: string): string => (by === 'url' ? 'page' : by);\n\nconst DAY = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst enc = encodeURIComponent;\nconst RAW_HINT = 'Read the raw counts with npx splithub results <id>.';\n\nexport interface Scope {\n filtered: boolean;\n range: { from: string; to: string } | null;\n filters: Record<string, string | string[]>;\n note?: string;\n}\n\n/** True when the flags ask for more than the plain all-time results. */\nexport function wantsSlice(flags: Flags): boolean {\n return Boolean(str(flags.from) || str(Array.isArray(flags.to) ? flags.to[0] : flags.to) || Number(flags.days) > 0 || (Array.isArray(flags.filter) ? flags.filter.length : flags.filter));\n}\n\n/** `?from=&to=&country=DE…` for an experiment report; refuses dates and filters the server can't read. */\nexport function experimentQuery(flags: Flags, extra: Record<string, string> = {}): string {\n for (const [name, v] of [['from', flags.from], ['to', Array.isArray(flags.to) ? flags.to[0] : flags.to]] as const) {\n const day = str(v);\n if (day && !DAY.test(day)) fail('INVALID_FLAG', `--${name} ${day}: use a day like 2026-10-01.`);\n }\n for (const k of Object.keys(filterFlags(flags))) {\n if (!(EXPERIMENT_FILTERS as readonly string[]).includes(k)) fail('INVALID_FLAG', `--filter ${k}: experiments filter by ${EXPERIMENT_FILTERS.join(', ')}.`);\n }\n return reportQuery(flags, extra);\n}\n\n/** \"first seen 2026-10-01 → 2026-10-15 · country=DE\", or null for the whole experiment. */\nexport function describeScope(scope: Scope | undefined): string | null {\n if (!scope || (!scope.filtered && !scope.range)) return null;\n const parts: string[] = [];\n if (scope.range) parts.push(`first seen ${scope.range.from} → ${scope.range.to}`);\n for (const [k, v] of Object.entries(scope.filters ?? {})) parts.push(`${k}=${Array.isArray(v) ? v.join(',') : v}`);\n return parts.join(' · ');\n}\n\n/** The slice banner printed above a filtered or ranged report. */\nexport function printScope(scope: Scope | undefined): void {\n const what = describeScope(scope);\n if (!what) return;\n console.log(c.yellow(`Filtered slice: ${what}`));\n if (scope?.note) console.log(c.dim(scope.note));\n console.log();\n}\n\nconst target = (flags: Flags, what: string): Target => cloudOnly(flags, what, true, RAW_HINT);\n\n// ---------------------------------------------------------------------------\n// Results on a slice\n// ---------------------------------------------------------------------------\n\n/** GET /results/<id> with a range and filters; the caller prints it like the whole-experiment results. */\nexport async function fetchSlice<T>(key: string, flags: Flags): Promise<T> {\n const t = target(flags, 'Filtered results');\n return request<T>(t, `/results/${enc(key)}${experimentQuery(flags)}`, {}, key);\n}\n\n// ---------------------------------------------------------------------------\n// Breakdown\n// ---------------------------------------------------------------------------\n\ninterface SegmentRow {\n dim: string;\n cells: Array<{ variant: string; exposures: number; conversions: number } | null>;\n comparisons: Array<{ variant: string; lift: number | null; pValue: number; significant: boolean; better: boolean }>;\n total: number;\n small: boolean;\n}\nexport interface BreakdownData {\n experiment: string;\n by: string;\n goal: string | null;\n order: string[];\n segments: SegmentRow[];\n scope?: Scope;\n}\n\nfunction byFlag(flags: Flags): string {\n const by = str(flags.by);\n if (!by) return fail('USAGE', 'Split by what? Add --by country (or device, source, channel, landing, …).');\n if (!(EXPERIMENT_BY as readonly string[]).includes(by)) fail('INVALID_FLAG', `--by ${by}: use one of ${EXPERIMENT_BY.join(', ')}.`);\n return by;\n}\n\n/** A lift cell: green ✔ / red ✖ when the difference is clear, plain otherwise. */\nfunction liftCell(cmp: SegmentRow['comparisons'][number] | undefined): string {\n if (!cmp || cmp.lift === null) return c.dim('–');\n const text = pct(cmp.lift, true);\n if (!cmp.significant) return text;\n return cmp.better ? c.green(`${text} ✔`) : c.red(`${text} ✖`);\n}\n\nexport function breakdownTable(data: BreakdownData, limit = 20): string {\n const [control, ...others] = data.order;\n const rows = data.segments.slice(0, limit).map((s) => {\n const name = s.dim === '' || s.dim === '(none)' ? c.dim('(none)') : s.small ? c.dim(s.dim) : s.dim;\n const rates = data.order.map((_, i) => {\n const cell = s.cells[i];\n return cell && cell.exposures > 0 ? `${pct(cell.conversions / cell.exposures)} ${c.dim(`of ${n(cell.exposures)}`)}` : c.dim('–');\n });\n return [name, n(s.total), ...rates, ...others.map((v) => liftCell(s.comparisons.find((x) => x.variant === v)))];\n });\n const head = [dimensionLabel(data.by).toUpperCase(), 'VISITORS', ...data.order.map((v) => (v === control ? `${v} (control)` : v)), ...others.map((v) => `LIFT ${v}`)];\n return table(head, rows);\n}\n\nexport async function breakdown(key: string, flags: Flags): Promise<void> {\n const by = byFlag(flags);\n const t = target(flags, 'Breakdowns');\n const data = await request<BreakdownData>(t, `/experiments/${enc(key)}/breakdown/${enc(by)}${experimentQuery(flags)}`, {}, key);\n if (flags.json) return printJson({ ...data, experiment: key, view: 'breakdown' });\n console.log(`${c.bold(key)} ${c.dim(`· by ${dimensionLabel(by)} · goal: ${data.goal ?? 'none'}`)}\\n`);\n printScope(data.scope);\n if (data.segments.length === 0) return void console.log(c.dim('No visitors in this slice yet.'));\n console.log(breakdownTable(data, Number(flags.limit) || 20));\n console.log(c.dim(`\\nLift is against the control inside each segment; ✔ and ✖ mark a clear difference, dim rows have too few visitors.`));\n console.log(c.dim('Segments are for exploring: the verdict is on the whole experiment.'));\n}\n\nexport async function breakdownCsv(key: string, flags: Flags): Promise<void> {\n const by = byFlag(flags);\n const t = target(flags, 'Exports');\n const csv = await requestText(t, `/experiments/${enc(key)}/export.breakdown.csv${experimentQuery(flags, { by })}`);\n if (flags.json) return printJson({ experiment: key, by, csv });\n process.stdout.write(csv.replace(/\\r\\n/g, '\\n'));\n}\n\n// ---------------------------------------------------------------------------\n// Timeline\n// ---------------------------------------------------------------------------\n\ninterface DayRow {\n day: string;\n variant: string;\n n: number;\n}\nexport interface TimelineData {\n experiment: string;\n goal: string | null;\n mode?: string;\n exposures: DayRow[];\n conversions: DayRow[];\n notes?: Array<{ day: string; kind?: string; text: string }>;\n scope?: Scope;\n}\n\nexport function timelineTable(data: TimelineData): string {\n const variants = [...new Set([...data.exposures, ...data.conversions].map((r) => r.variant))];\n const days = [...new Set([...data.exposures, ...data.conversions].map((r) => r.day))].sort();\n const count = (rows: DayRow[]) => new Map(rows.map((r) => [`${r.day}|${r.variant}`, r.n]));\n const seen = count(data.exposures);\n const conv = count(data.conversions);\n const head = ['DAY', ...variants.flatMap((v) => [v, 'CONV', 'RATE'])];\n const rows = days.map((d) => [\n d,\n ...variants.flatMap((v) => {\n const x = seen.get(`${d}|${v}`) ?? 0;\n const y = conv.get(`${d}|${v}`) ?? 0;\n return [n(x), n(y), x > 0 ? pct(y / x) : c.dim('–')];\n }),\n ]);\n return table(head, rows);\n}\n\nexport async function timeline(key: string, flags: Flags): Promise<void> {\n const t = target(flags, 'Timelines');\n const data = await request<TimelineData>(t, `/experiments/${enc(key)}/timeline${experimentQuery(flags)}`, {}, key);\n if (flags.json) return printJson({ ...data, experiment: key, view: 'timeline' });\n console.log(`${c.bold(key)} ${c.dim(`· per day · goal: ${data.goal ?? 'none'}`)}\\n`);\n printScope(data.scope);\n if (data.exposures.length === 0) return void console.log(c.dim('No visitors in this slice yet.'));\n console.log(timelineTable(data));\n if (data.mode !== 'goal_day') console.log(c.dim(\"\\nA day counts the visitors first seen that day and how many of them converted, whenever they did.\"));\n if (data.notes?.length) {\n console.log(`\\n${c.bold('Notes')}`);\n for (const a of data.notes.slice(-5)) console.log(`${c.dim(a.day)} ${a.kind && a.kind !== 'note' ? `${noteKind(a.kind)} ` : ''}${a.text}`);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Engagement (from the analytics property collecting on the same visitors)\n// ---------------------------------------------------------------------------\n\nexport interface EngagementData {\n property: string | null;\n variants: Array<{ variant: string; visitors: number; sessions: number; pageviews: number; bounces: number; duration: number; pagesPerVisit: number; bounceRate: number; avgVisit: number }>;\n scope?: Scope;\n}\n\n/** Milliseconds as `42s` or `3m 05s`. */\nexport function visitLength(ms: number): string {\n if (!Number.isFinite(ms) || ms <= 0) return '0s';\n const s = Math.round(ms / 1000);\n return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, '0')}s`;\n}\n\nexport async function engagement(key: string, flags: Flags): Promise<void> {\n const t = target(flags, 'Engagement by variant');\n const data = await request<EngagementData>(t, `/experiments/${enc(key)}/engagement${experimentQuery(flags, str(flags.property) ? { property: str(flags.property)! } : {})}`, {}, key);\n if (flags.json) return printJson({ ...data, experiment: key, view: 'engagement' });\n if (!data.property || data.variants.length === 0) {\n console.log(c.dim('No analytics on these visitors yet. Name a property on the provider (or sh.js) to see visits per variant.'));\n return;\n }\n console.log(`${c.bold(key)} ${c.dim(`· engagement from ${data.property}`)}\\n`);\n printScope(data.scope);\n console.log(\n table(\n ['VARIANT', 'VISITORS', 'VISITS', 'PAGES / VISIT', 'BOUNCE', 'AVG VISIT'],\n data.variants.map((v, i) => [i === 0 ? `${v.variant} ${c.dim('(control)')}` : v.variant, n(v.visitors), n(v.sessions), v.sessions ? v.pagesPerVisit.toFixed(2) : c.dim('–'), v.sessions ? pct(v.bounceRate) : c.dim('–'), v.sessions ? visitLength(v.avgVisit) : c.dim('–')])\n )\n );\n console.log(c.dim('\\nCounts to read next to the verdict, not a verdict.'));\n}\n\n// ---------------------------------------------------------------------------\n// Events by variant: every goal and event of the experiment's visitors\n// ---------------------------------------------------------------------------\n\nexport interface EventsByVariantData {\n experiment: string;\n goal: string | null;\n property: string | null;\n variants: string[];\n visitors: Record<string, number>;\n rows: Array<{\n name: string;\n goalKey: string | null;\n isGoal: boolean;\n measured: 'goal' | 'metric' | 'guardrail' | null;\n perVariant: Record<string, { visitors: number; count: number | null; rate: number | null; revenue: number }>;\n comparisons: SegmentRow['comparisons'];\n small: boolean;\n }>;\n scope?: Scope;\n}\n\nconst ROLE: Record<string, string> = { goal: 'goal', metric: 'metric', guardrail: 'guardrail' };\n\nexport function eventsTable(data: EventsByVariantData, limit = 30): string {\n const [control, ...others] = data.variants;\n const rows = data.rows.slice(0, limit).map((r) => {\n const role = r.measured ? ROLE[r.measured] : r.isGoal ? 'goal' : '';\n const label = r.goalKey && r.goalKey !== r.name ? `${r.name} ${c.dim(r.goalKey)}` : r.name;\n const cells = data.variants.map((v) => {\n const x = r.perVariant[v];\n return x && x.rate !== null ? `${n(x.visitors)} ${c.dim(`· ${pct(x.rate)}`)}` : c.dim('–');\n });\n return [r.small ? c.dim(r.name) : label, role ? c.dim(role) : '', ...cells, ...others.map((v) => (r.small ? c.dim('–') : liftCell(r.comparisons.find((x) => x.variant === v))))];\n });\n const head = ['EVENT', 'ROLE', ...data.variants.map((v) => (v === control ? `${v} (control)` : v)), ...others.map((v) => `LIFT ${v}`)];\n return table(head, rows);\n}\n\nexport async function eventsByVariant(key: string, flags: Flags): Promise<void> {\n const t = target(flags, 'Events by variant');\n const data = await request<EventsByVariantData>(t, `/experiments/${enc(key)}/events-summary${experimentQuery(flags, str(flags.property) ? { property: str(flags.property)! } : {})}`, {}, key);\n if (flags.json) return printJson({ ...data, experiment: key, view: 'events' });\n console.log(`${c.bold(key)} ${c.dim(`· events by variant${data.property ? ` · from ${data.property}` : ''}`)}\\n`);\n printScope(data.scope);\n if (data.rows.length === 0) return void console.log(c.dim('No goals or events from these visitors yet.'));\n console.log(eventsTable(data, Number(flags.limit) || 30));\n console.log(c.dim('\\nVisitors who did it · their rate; lift is against the control, ✔ and ✖ mark a clear difference, dim rows have too few visitors.'));\n if (!data.property) console.log(c.dim('Only goals so far: other events show up once an analytics property runs on the same site.'));\n console.log(c.dim('The verdict is on the experiment goal; the other rows are for exploring.'));\n}\n\nexport async function eventsByVariantCsv(key: string, flags: Flags): Promise<void> {\n const t = target(flags, 'Exports');\n const csv = await requestText(t, `/experiments/${enc(key)}/export.events-summary.csv${experimentQuery(flags)}`);\n if (flags.json) return printJson({ experiment: key, view: 'events', csv });\n process.stdout.write(csv.replace(/\\r\\n/g, '\\n'));\n}\n\n// ---------------------------------------------------------------------------\n// Raw events\n// ---------------------------------------------------------------------------\n\ninterface RawEvent {\n id: string;\n type: string;\n variant: string | null;\n goal: string | null;\n visitorId: string;\n ts: number;\n url: string | null;\n country: string | null;\n}\n\nexport async function experimentEvents(key: string | undefined, flags: Flags): Promise<void> {\n if (!key) fail('USAGE', 'Which experiment? npx splithub events --experiment <id>');\n const type = str(flags.type);\n if (type && type !== 'exposure' && type !== 'goal') fail('INVALID_FLAG', `--type ${type}: use exposure or goal.`);\n const before = str(flags.before);\n if (before && !(Number(before) > 0)) fail('INVALID_FLAG', `--before ${before}: use a time in milliseconds, like the nextBefore of the last page.`);\n const limit = Math.max(1, Math.min(200, Number(flags.limit) || 50));\n const t = target(flags, 'Raw experiment events');\n const extra: Record<string, string> = { limit: String(limit), ...(type ? { type } : {}), ...(before ? { before } : {}) };\n const data = await request<{ events: RawEvent[]; nextBefore: number | null; scope?: Scope }>(t, `/experiments/${enc(key)}/events${experimentQuery(flags, extra)}`, {}, key);\n if (flags.json) return printJson({ ...data, experiment: key });\n if (data.events.length === 0) return void console.log(c.dim('No events in this slice. Raw events stay 7 days (30 on Pro).'));\n console.log(\n table(\n ['TIME', 'TYPE', 'VARIANT / GOAL', 'VISITOR', 'URL', 'COUNTRY'],\n data.events.map((e) => [new Date(Number(e.ts)).toISOString().replace('T', ' ').slice(0, 19), e.type, (e.type === 'exposure' ? e.variant : e.goal) ?? '', String(e.visitorId ?? '').slice(0, 12), e.url ?? '', e.country ?? ''])\n )\n );\n if (data.nextBefore) console.log(c.dim(`\\nOlder: --before ${data.nextBefore}`));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAoBO,IAAM,qBAAqB,CAAC,WAAW,UAAU,QAAQ,UAAU,MAAM,WAAW,YAAY,QAAQ,YAAY,eAAe,UAAU,WAAW,cAAc,cAAc,gBAAgB,YAAY,eAAe,WAAW,MAAM;AAEhP,IAAM,gBAAgB,CAAC,WAAW,UAAU,QAAQ,UAAU,MAAM,WAAW,YAAY,QAAQ,YAAY,eAAe,QAAQ,OAAO,YAAY,UAAU,WAAW,WAAW,cAAc,cAAc,gBAAgB,YAAY,aAAa;AAG9P,IAAM,iBAAiB,CAAC,OAAwB,OAAO,QAAQ,SAAS;AAE/E,IAAM,MAAM;AACZ,IAAM,MAAM;AACZ,IAAM,WAAW;AAUV,SAAS,WAAW,OAAuB;AAChD,SAAO,QAAQ,IAAI,MAAM,IAAI,KAAK,IAAI,MAAM,QAAQ,MAAM,EAAE,IAAI,MAAM,GAAG,CAAC,IAAI,MAAM,EAAE,KAAK,OAAO,MAAM,IAAI,IAAI,MAAM,MAAM,QAAQ,MAAM,MAAM,IAAI,MAAM,OAAO,SAAS,MAAM,OAAO;AACzL;AAGO,SAAS,gBAAgB,OAAc,QAAgC,CAAC,GAAW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@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/notes.ts"],"sourcesContent":["// splithub notes — what happened on a day (\"launched the new pricing page\", \"checkout broke on\n// Safari\"). One list for the project: a note belongs to one experiment, one analytics property, or\n// the whole project (shown on every chart). SplitHub Cloud only.\n//\n// splithub notes [--experiment <key> | --property <id>] [--kind note|issue|win] [--days 30 | --from --to]\n// splithub notes add \"<text>\" [--kind issue|win|note] [--experiment <key> | --property <id>] [--day YYYY-MM-DD]\n// splithub notes edit <id> [\"<new text>\"] [--kind ...] [--day ...]\n// splithub notes delete <id>\n\nimport { request } from '../api';\nimport { fail, printJson } from '../errors';\nimport { c, table } from '../ui';\nimport { cloudOnly, reportQuery, str } from './analytics-reports';\nimport type { Flags } from './init';\n\nexport const NOTE_KINDS = ['note', 'issue', 'win'] as const;\nconst DAY = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst enc = encodeURIComponent;\n\nexport interface Note {\n id: string;\n day: string;\n kind: (typeof NOTE_KINDS)[number];\n text: string;\n experimentKey: string | null;\n propertyKey: string | null;\n createdAt: string;\n author: { name: string | null; email: string | null } | null;\n}\n\nconst KIND_MARK: Record<string, (s: string) => string> = {\n note: c.dim,\n issue: c.red,\n win: c.green,\n};\nexport const noteKind = (k: string) => (KIND_MARK[k] ?? c.dim)(k);\nexport const noteScope = (n: Pick<Note, 'experimentKey' | 'propertyKey'>) => (n.experimentKey ? `experiment ${n.experimentKey}` : n.propertyKey ? `property ${n.propertyKey}` : c.dim('whole project'));\n\nfunction kindFlag(flags: Flags): string | undefined {\n const kind = str(flags.kind);\n if (kind && !(NOTE_KINDS as readonly string[]).includes(kind)) fail('INVALID_FLAG', `--kind ${kind}: use note, issue or win.`);\n return kind;\n}\n\nfunction dayFlag(flags: Flags): string | undefined {\n const day = str(flags.day);\n if (day && !DAY.test(day)) fail('INVALID_FLAG', `--day ${day}: use a day like 2026-10-01.`);\n return day;\n}\n\nexport async function notes(args: string[], flags: Flags): Promise<void> {\n const [action, ...rest] = args;\n const t = cloudOnly(flags, 'Notes', false);\n if (action === 'add') {\n const text = rest.join(' ').trim();\n if (!text) fail('USAGE', 'What happened? npx splithub notes add \"Launched the new pricing page\" [--kind win] [--experiment <key> | --property <id>]');\n const experiment = str(flags.experiment);\n const property = str(flags.property);\n if (experiment && property) fail('USAGE', 'A note belongs to one experiment or one property, not both.');\n const kind = kindFlag(flags);\n const day = dayFlag(flags);\n const body = {\n text,\n ...(kind ? { kind } : {}),\n ...(day ? { day } : {}),\n ...(experiment ? { experimentKey: experiment } : {}),\n ...(property ? { propertyKey: property } : {}),\n };\n const out = await request<{ note: Note }>(t, '/notes', {\n method: 'POST',\n body: JSON.stringify(body),\n });\n if (flags.json) return printJson(out);\n console.log(`${c.green('✔')} noted on ${out.note.day} ${c.dim(`(${out.note.kind}, ${noteScope(out.note)})`)}`);\n return;\n }\n if (action === 'edit') {\n const [id, ...words] = rest;\n if (!id) fail('USAGE', 'Which note? npx splithub notes edit <id> \"New text\" [--kind win] [--day 2026-10-01]');\n const text = words.join(' ').trim();\n const kind = kindFlag(flags);\n const day = dayFlag(flags);\n if (!text && !kind && !day) fail('USAGE', 'Nothing to change: give new text, --kind or --day.');\n const out = await request<{ note: Note }>(t, `/notes/${enc(id)}`, {\n method: 'PATCH',\n body: JSON.stringify({\n ...(text ? { text } : {}),\n ...(kind ? { kind } : {}),\n ...(day ? { day } : {}),\n }),\n });\n if (flags.json) return printJson(out);\n console.log(`${c.green('✔')} note updated ${c.dim(`(${out.note.day}, ${out.note.kind})`)}`);\n return;\n }\n if (action === 'delete' || action === 'remove') {\n const id = rest[0];\n if (!id) fail('USAGE', 'Which note? npx splithub notes delete <id> (ids are in npx splithub notes).');\n await request(t, `/notes/${enc(id)}`, { method: 'DELETE' });\n if (flags.json) return printJson({ ok: true, id });\n console.log(`${c.green('✔')} note deleted`);\n return;\n }\n if (action && action !== 'list') fail('USAGE', `Unknown \"notes ${action}\". Use notes, notes add \"<text>\", notes edit <id> or notes delete <id>.`);\n return listNotes(flags);\n}\n\nasync function listNotes(flags: Flags): Promise<void> {\n const t = cloudOnly(flags, 'Notes', false);\n const q = new URLSearchParams(reportQuery(flags).slice(1));\n for (const k of [...q.keys()]) if (k !== 'from' && k !== 'to') q.delete(k);\n const experiment = str(flags.experiment);\n const property = str(flags.property);\n const kind = kindFlag(flags);\n if (experiment) q.set('experiment', experiment);\n else if (property) q.set('property', property);\n if (kind) q.set('kind', kind);\n const s = q.toString();\n const data = await request<{ notes: Note[] }>(t, `/notes${s ? `?${s}` : ''}`);\n if (flags.json) return printJson(data);\n if (data.notes.length === 0) return void console.log(c.dim('No notes yet. Add one when you ship something: npx splithub notes add \"Launched the new pricing page\"'));\n const rows = data.notes.slice(0, Number(flags.limit) || 50);\n console.log(\n table(\n ['DAY', 'KIND', 'NOTE', 'FOR', 'BY', 'ID'],\n rows.map((n) => [n.day, noteKind(n.kind), n.text.length > 80 ? `${n.text.slice(0, 79)}…` : n.text, noteScope(n), n.author?.name ?? n.author?.email ?? c.dim('–'), c.dim(n.id)])\n )\n );\n if (data.notes.length > rows.length) console.log(c.dim(`\\n${data.notes.length - rows.length} more: --limit ${data.notes.length}, or narrow with --days, --experiment, --property, --kind.`));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAeO,IAAM,aAAa,CAAC,QAAQ,SAAS,KAAK;AACjD,IAAM,MAAM;AACZ,IAAM,MAAM;AAaZ,IAAM,YAAmD;AAAA,EACvD,MAAM,EAAE;AAAA,EACR,OAAO,EAAE;AAAA,EACT,KAAK,EAAE;AACT;AACO,IAAM,WAAW,CAAC,OAAe,UAAU,CAAC,KAAK,EAAE,KAAK,CAAC;AACzD,IAAM,YAAY,CAAC,MAAoD,EAAE,gBAAgB,cAAc,EAAE,aAAa,KAAK,EAAE,cAAc,YAAY,EAAE,WAAW,KAAK,EAAE,IAAI,eAAe;AAErM,SAAS,SAAS,OAAkC;AAClD,QAAM,OAAO,IAAI,MAAM,IAAI;AAC3B,MAAI,QAAQ,CAAE,WAAi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EAAK,KAAK,MAAM,SAAS,KAAK,MAAM,kBAAkB,KAAK,MAAM,MAAM,4DAA4D,CAAC;AAC7L;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/doctor.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { resolveTarget } from '../api';\nimport { loadConfig } from '../config-file';\nimport { printJson } from '../errors';\nimport type { SplitHubConfig } from '@splithub/core';\nimport { ASYNC_STORAGE, isNativeApp, isReactNativeApp, nativeSdkInstalled, nativeSetup, RN_PACKAGE } from '../app-setup';\nimport { detectProject, grepFiles, listSourceFiles, type ProjectInfo } from '../project';\nimport { findRefs } from '../refs';\nimport { c } from '../ui';\nimport { versionReport } from '../update';\nimport type { Flags } from './init';\n\nexport type Level = 'ok' | 'warn' | 'error';\ninterface Check {\n level: Level;\n message: string;\n}\n\nexport async function doctor(flags: Flags): Promise<void> {\n const checks: Check[] = [];\n const add = (level: Level, message: string) => checks.push({ level, message });\n const project = detectProject();\n\n add('ok', `project \"${project.name}\" · ${project.framework} · ${project.packageManager}`);\n await versionChecks(project.root, add);\n\n if (isNativeApp(project.app)) {\n // Native SDKs take experiments from the cloud; there is no config file to check.\n const read = (f: string) => {\n try {\n return readFileSync(f, 'utf8');\n } catch {\n return null;\n }\n };\n const lines = nativeSetup(project.app, null);\n if (nativeSdkInstalled(project.root, project.app, read)) add('ok', `app: ${project.app}, SplitHub SDK in the build files`);\n else add('error', `app: ${project.app}, SplitHub SDK not found in the build files. Add it: ${lines.install.split('\\n')[1]}`);\n add('warn', 'app: create experiments in the dashboard; they reach installed apps through the cloud, no release needed');\n return report(checks, flags);\n }\n if (!project.configFile) {\n add('error', 'splithub.config.ts not found. Run `npx splithub init`.');\n return report(checks, flags);\n }\n add('ok', `config: ${relative(project.root, project.configFile)}`);\n\n let config;\n try {\n config = await loadConfig(project.configFile);\n add('ok', `config loads · ${config.experiments.length} experiment(s) · storage ${config.storage.mode}`);\n } catch (error) {\n add('error', `config does not load: ${error instanceof Error ? error.message : String(error)}`);\n return report(checks, flags);\n }\n\n const files = listSourceFiles(project.root);\n const providerHits = grepFiles(files, 'SplitHubProvider').concat(grepFiles(files, 'SplitHubNextProvider'));\n if (providerHits.length === 0) add('error', 'no <SplitHubProvider> found in source. Wrap your app once.');\n else add('ok', `provider in ${relative(project.root, providerHits[0]!)}`);\n\n if (isReactNativeApp(project.app)) appChecks(project, config, add);\n\n if (project.framework === 'next') {\n const mw = ['middleware.ts', 'src/middleware.ts', 'middleware.js', 'src/middleware.js'].map((f) => join(project.root, f)).find((f) => existsSync(f));\n const hasRedirects = config.experiments.some((e) => e.kind === 'redirect');\n if (!mw) add(hasRedirects ? 'error' : 'warn', 'no middleware.ts: visitor cookie is not set on the server (SSR may flicker)' + (hasRedirects ? '; redirect experiments will not run' : ''));\n else if (!readFileSync(mw, 'utf8').includes('splithubMiddleware')) add('warn', `${relative(project.root, mw)} does not call splithubMiddleware()`);\n else add('ok', `middleware: ${relative(project.root, mw)}`);\n if (config.storage.mode === 'self' && project.appDir) {\n const catchAll = join(project.root, project.appDir, 'api/splithub/[[...path]]/route.ts');\n const plain = join(project.root, project.appDir, 'api/splithub/route.ts');\n if (existsSync(catchAll)) add('ok', `ingest route: ${relative(project.root, catchAll)}`);\n else if (existsSync(plain)) add('error', `${relative(project.root, plain)} only serves POST /api/splithub; move it to api/splithub/[[...path]]/route.ts so /status and /results work`);\n else add('error', `self mode but ${relative(project.root, catchAll)} is missing (ingest endpoint)`);\n }\n }\n\n for (const exp of config.experiments) {\n const label = `${exp.key} (${exp.kind}, ${exp.status})`;\n if (!exp.goal) add(exp.status === 'running' ? 'error' : 'warn', `${label}: no goal; the verdict cannot be computed`);\n if (exp.kind !== 'redirect') {\n const used = findRefs(project.root, config, exp.key, files).refs.filter((r) => r.match === 'experiment').length;\n if (used === 0) add(exp.status === 'running' ? 'error' : 'warn', `${label}: not referenced in code (useValue/useVariant/<Experiment id>)`);\n }\n if (exp.status === 'running' && exp.variants.every((v) => v.weight === 0)) add('error', `${label}: all weights are 0`);\n }\n for (const goal of config.goals) {\n // An event goal is sent as its key or, when it has one, as its event name ('Video Played').\n const names = [goal.key, ...(goal.event ? [goal.event] : [])];\n if (goal.type === 'event' && names.every((n) => grepFiles(files, `'${n}'`).length + grepFiles(files, `\"${n}\"`).length === 0)) {\n add('warn', `goal \"${goal.key}\": track('${goal.event ?? goal.key}') is never called`);\n }\n }\n\n const target = resolveTarget(flags, project);\n try {\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), 2500);\n const res = await fetch(`${target.url}/health`, { signal: ctrl.signal });\n clearTimeout(t);\n add(res.ok ? 'ok' : 'warn', `endpoint ${target.url}/health → ${res.status}`);\n } catch {\n add('warn', `endpoint ${target.url} not reachable (is the dev server running?)`);\n }\n\n return report(checks, flags);\n}\n\n/** React Native / Expo: the package, its storage module, and what the frozen config means for experiments. */\nexport function appChecks(project: Pick<ProjectInfo, 'app' | 'deps'>, config: Pick<SplitHubConfig, 'experiments' | 'storage'>, add: (level: Level, message: string) => void): void {\n if (!project.deps[RN_PACKAGE]) add('error', `app: ${RN_PACKAGE} is not in package.json. Install it: npm install ${RN_PACKAGE}`);\n else add('ok', `app: ${project.app}, ${RN_PACKAGE} ${project.deps[RN_PACKAGE]}`);\n if (!project.deps[ASYNC_STORAGE]) add('error', `app: ${ASYNC_STORAGE} is missing (the visitor id and the offline queue live there). Install it: ${project.app === 'expo' ? 'npx expo install' : 'npm install'} ${ASYNC_STORAGE}`);\n for (const exp of config.experiments) {\n if (exp.kind === 'redirect') add('warn', `${exp.key}: redirect experiments change URLs, so they do nothing in an app. Use a value or component experiment.`);\n }\n if (config.storage.mode === 'self') add('warn', 'app: self-hosted, so experiments only change with a store release (the config is built into the app). SplitHub Cloud starts and changes them live.');\n else add('warn', 'app: splithub.config.ts is frozen into the binary until the next store release. Create new experiments in the dashboard so installed apps get them now; push config changes too.');\n}\n\nasync function versionChecks(root: string, add: (level: Level, message: string) => void): Promise<void> {\n const v = await versionReport(root);\n const list = v.rows.map((r) => `${r.name} ${r.installed ?? 'not installed'}`).join(', ');\n if (v.mismatch) add('warn', `versions differ: ${list}. Update them together: ${v.command}`);\n else add('ok', `versions: ${list}`);\n if (v.offline) add('warn', \"couldn't reach npm, so the latest versions weren't checked\");\n else if (v.outdated.length) {\n const what = v.rows.filter((r) => v.outdated.includes(r.name)).map((r) => `${r.name} ${r.installed} → ${r.latest}`).join(', ');\n add('warn', `updates available: ${what}` + (v.mismatch ? '' : `. Run ${v.command}`));\n }\n}\n\nfunction report(checks: Check[], flags: Flags): void {\n const errors = checks.filter((x) => x.level === 'error').length;\n if (flags.json) {\n printJson({ ok: errors === 0, errors, warnings: checks.filter((x) => x.level === 'warn').length, checks });\n } else {\n for (const x of checks) {\n const icon = x.level === 'ok' ? c.green('✔') : x.level === 'warn' ? c.yellow('!') : c.red('✖');\n console.log(`${icon} ${x.message}`);\n }\n console.log();\n console.log(errors === 0 ? c.green('All good.') : c.red(`${errors} problem(s) to fix.`));\n }\n if (errors > 0) process.exitCode = 1;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,oBAAoB;AACzC,SAAS,MAAM,gBAAgB;AAkB/B,eAAsB,OAAO,OAA6B;AACxD,QAAM,SAAkB,CAAC;AACzB,QAAM,MAAM,CAAC,OAAc,YAAoB,OAAO,KAAK,EAAE,OAAO,QAAQ,CAAC;AAC7E,QAAM,UAAU,cAAc;AAE9B,MAAI,MAAM,YAAY,QAAQ,IAAI,UAAO,QAAQ,SAAS,SAAM,QAAQ,cAAc,EAAE;AACxF,QAAM,cAAc,QAAQ,MAAM,GAAG;AAErC,MAAI,YAAY,QAAQ,GAAG,GAAG;AAE5B,UAAM,OAAO,CAAC,MAAc;AAC1B,UAAI;AACF,eAAO,aAAa,GAAG,MAAM;AAAA,MAC/B,QAAQ;AACN,eAAO;AAAA,MACT;AAAA,I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OAAO;AACL,eAAW,KAAK,QAAQ;AACtB,YAAM,OAAO,EAAE,UAAU,OAAO,EAAE,MAAM,QAAG,IAAI,EAAE,UAAU,SAAS,EAAE,OAAO,GAAG,IAAI,EAAE,IAAI,QAAG;AAC7F,cAAQ,IAAI,GAAG,IAAI,IAAI,EAAE,OAAO,EAAE;AAAA,IACpC;AACA,YAAQ,IAAI;AACZ,YAAQ,IAAI,WAAW,IAAI,EAAE,MAAM,WAAW,IAAI,EAAE,IAAI,GAAG,MAAM,qBAAqB,CAAC;AAAA,EACzF;AACA,MAAI,SAAS,EAAG,SAAQ,WAAW;AACrC;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/skills-self-hosted.ts","../src/skills-ship.ts","../src/skills-analytics.ts","../src/skills-apps.ts","../src/skills.ts","../src/templates.ts"],"sourcesContent":["// Skill: SplitHub with the user's own database (self mode) and reporting from the cloud.\n// Bundled fallback; SplitHub Cloud serves the current text at GET /v1/skills.\nexport const SKILL_SELF_HOSTED = `---\nname: splithub-self-hosted\ndescription: Keep SplitHub events in your own database (self mode): which tables, how to write a Store for Postgres, MySQL, Prisma, Drizzle, Supabase or anything else, where the ingest route lives, how the CLI reads results from it, and how to get cloud data into your own database for reports. Use when the user wants data in their infra or asks about tables, schema or reporting.\n---\n\n# SplitHub with your own database\n\nTwo ways to own the data:\n\n1. **Self mode** — the app hosts the ingest route and the store; nothing leaves your infra.\n \\`splithub.config.ts\\`: \\`storage: { mode: 'self', endpoint: '/api/splithub' }\\`.\n2. **Cloud + export** — events go to SplitHub Cloud; you pull summaries into your warehouse for reports.\n\n## Self mode: the pieces\n\n- Route: \\`app/api/splithub/[[...path]]/route.ts\\` (Next.js) or any fetch-style handler from\n \\`createSplitHubHandler({ config, store, adminToken })\\` in \\`@splithub/node\\`. It accepts\n \\`POST /events\\` from the SDK and answers \\`GET /status\\`, \\`GET /results/<id>\\` for the CLI\n (\\`npx splithub status\\` talks to the local dev server, or \\`--url https://your.app/api/splithub\\`).\n Self-hosted reads are raw numbers per variant (\\`variants[]\\`: visitors, conversions, rate, revenue)\n with \\`analysis: { available: false }\\`. Verdicts, data-quality stars and recommendations come with SplitHub Cloud,\n and so do slices, breakdowns, timelines and raw experiment events (\\`results --from/--filter/--by\\` answer \\`NOT_CLOUD\\` here).\n With an analytics property the SDK sends \\`track()\\` as one \\`event\\` row and a page as one \\`page\\` row; the handler\n stores the goal rows experiments need next to them (goals of the config's experiments only), so the store sees goals as before.\n- Store: an object with three methods (below). Ready-made: \\`@splithub/adapter-sqlite\\`\n (Node 22.13+, \\`node:sqlite\\`, zero setup) and \\`@splithub/adapter-d1\\` (Cloudflare D1).\n \\`npx splithub init --mode self --db postgres|mysql|custom\\` writes \\`splithub/store.ts\\` with a\n working Postgres (pg) or MySQL (mysql2) store, or a documented stub for anything else.\n- Admin token: set \\`SPLITHUB_ADMIN_TOKEN\\` in the app and \\`--token\\` / \\`SPLITHUB_ADMIN_TOKEN\\` for\n the CLI, so results are not public.\n\n## The events table\n\nOne table, one row per event. Column names are yours; the templates use these:\n\n| column | type | meaning |\n|---|---|---|\n| id | text, primary key | client-generated, unique; dedupe on it (retries resend batches) |\n| type | text | \\`exposure\\` or \\`goal\\` |\n| experiment, variant | text | for exposures |\n| goal | text | for goals |\n| visitor_id, session_id | text | \\`sh_vid\\` cookie / session |\n| ts | bigint | client time, unix ms |\n| url | text | page |\n| props | json | goal payload, e.g. \\`{ \"revenue\": 49 }\\` |\n| received_at | bigint | server time, unix ms |\n| host, country, device, browser | text | request metadata (fill from headers if you want breakdowns) |\n\nIndexes: \\`(type, experiment, visitor_id, ts)\\` and \\`(type, goal, visitor_id, ts)\\`.\n\n## The Store interface (\\`@splithub/node\\`)\n\n\\`\\`\\`ts\ninterface Store {\n insertEvents(events: StoredEvent[]): Promise<number>; // skip existing ids, return inserted count\n variantCounts(experiment: string, goal: string): Promise<VariantCounts[]>; // per variant: exposures, conversions, revenue\n summaries(): Promise<ExperimentSummary[]>; // per experiment: exposures, visitors, first/last ts\n close?(): Promise<void> | void;\n}\n\\`\\`\\`\n\nAttribution rule — keep it exactly, so self-hosted results equal the cloud's:\n**a visitor converts for a variant when they sent the goal at or after their first exposure to\nthat variant; exposures and conversions count unique visitors.** The SQL in the generated\n\\`splithub/store.ts\\` implements it (CTE \\`first_exposure\\`, then goals joined with \\`ts >= first_ts\\`).\n\nPrisma / Drizzle: map the table in your schema and write the three methods with the ORM, or run the\none raw query for \\`variantCounts\\`. Supabase: the same SQL as a Postgres function called through\n\\`rpc\\`. Mongo: \\`$group\\` by variant and visitor with \\`$min ts\\`, then \\`$lookup\\` goals.\n\n## Reports from the cloud into your database\n\n- CSV: dashboard → experiment → Export (summary, daily timeline, raw events up to 50k rows).\n- Webhook channel for alerts and the digest: POST JSON to your endpoint when something happens.\n- Scheduled pull: a cron in your app calls \\`GET /v1/status\\` and \\`GET /v1/results/<id>\\` with the\n API key (\\`sk_…\\`) and stores the verdicts. Raw events live 30–90 days in the cloud (plan dependent),\n aggregates a year: pull summaries, not raw rows, for long-term reporting.\n- Need every raw event forever in your infra? Use self mode; one store per project.\n\n## Do not\n\n- Put database credentials in \\`splithub.config.ts\\` (it ships to the browser). They belong in the route's env.\n- Call a winner from raw rates: a higher rate is often noise. Say the numbers as they are; verdicts come with SplitHub Cloud.\n`;\n","// Skills: ship the winner (`splithub ship`) and the full agent loop. Installed next\n// to the other skills by `splithub init` / `splithub skills`.\n\nexport const SKILL_SHIP = `---\nname: splithub-ship\ndescription: Ship the winner of an experiment and remove the experiment from the code: keep only the winning value, component or page, delete the losing variants, finish the experiment and clean splithub.config.ts. Use when an experiment has a verdict and the user says ship it, roll out the winner, remove the experiment, or clean up; and whenever an experiment shows status finished and the user agreed on which variant to keep.\n---\n\n# Shipping the winner\n\nGoal: the app behaves exactly as the kept variant did, with no experiment left in the code or in the config.\n\n## 1. Decide\n\n\\`npx splithub results <id> --json\\` (MCP: \\`splithub_results\\`). Act on \\`verdict.status\\`:\n- \\`winner_found\\`: keep \\`verdict.winner\\`.\n- \\`no_significant_difference\\`: keep the control, or the simpler variant if the user agrees.\n- \\`insufficient_sample\\`: do not ship. Say when to look again: \\`daysToVerdict\\` days at the current traffic.\n- \\`srm_detected\\`: do not ship. The split is broken; fix the setup first.\n- \\`guardrail_breached\\`: do not ship the variant in \\`verdict.guardrailBreached\\`; it made a guardrail worse. Say what broke.\nAsk the user which variant to keep before going on. Never pick from raw rates.\n\n## 2. Preview, then ship\n\n\\`\\`\\`bash\nnpx splithub ship <id> --keep <variant> --dry-run --json # diff + leftovers, nothing written\nnpx splithub ship <id> --keep <variant> --json # apply\n\\`\\`\\`\nMCP: \\`splithub_ship\\` with \\`dryRun: true\\`, then without. It archives the experiment in the cloud (numbers stay readable), removes it from\n\\`splithub.config.ts\\` (checked by reloading the file) and rewrites the code:\n- \\`<Experiment id>\\` → the kept \\`<Variant>\\`'s children; the other variants are dropped.\n- \\`useValue('<id>')\\` / \\`sh.value('<id>')\\` → the kept value as a literal.\n- \\`useVariant('<id>')\\` comparisons, ternaries, \\`&&\\`, \\`if\\` and \\`switch\\` → the kept branch.\n- Unused \\`Experiment\\`, \\`Variant\\`, \\`useVariant\\`, \\`useValue\\` imports go.\n\n## 3. Finish by hand\n\n- \\`leftovers[]\\`: each \\`{ file, line, text, reason }\\` still mentions the experiment; rewrite those yourself.\n- component kind: delete components and files only the losing variants used (e.g. \\`splithub/<id>/\\`).\n- redirect kind: make the kept URL the real page (move the route or add a permanent redirect), delete the other page.\n- Goal: keep \\`track('<goal>')\\` when another experiment measures it (\\`next\\` says so); otherwise ask before removing it.\n- Cloud mode: \\`npx splithub push\\`. Then \\`npx splithub doctor\\` and the project's typecheck and tests.\n- \\`npx splithub refs <id> --json\\` must return \\`count: 0\\` for the experiment.\n\nReport what changed (files, the kept content) and the verdict in one line with its numbers. Never reuse the id.\n`;\n\nexport const SKILL_LOOP = `---\nname: splithub-loop\ndescription: The whole experiment loop for an agent with SplitHub, step by step with the MCP tools and CLI --json fields: plan, create, implement, check, push, read results, finish, ship. Use when the user asks to run an experiment end to end, or to pick up an experiment where it stands.\n---\n\n# The full loop\n\nEach step: MCP tool, or the CLI with \\`--json\\` (one line of JSON; errors are \\`{ error, code, hint }\\`, exit 1).\n\n| step | MCP tool | CLI | read |\n|---|---|---|---|\n| 0. size it | \\`splithub_plan\\` | \\`plan --baseline 0.05 --mde 0.1 [<id>]\\` | \\`perVariant\\`, \\`total\\`, \\`traffic.daysLeft\\` |\n| 1. create | \\`splithub_experiment_create\\` | \\`create --kind … --id … --goal … --yes\\` | \\`snippet\\`, \\`files\\`, \\`nextStep\\`, \\`handoff\\` |\n| 2. implement | (edit code) | | wire \\`snippet\\`; \\`track('<goal>')\\` where it converts |\n| 3. check | \\`splithub_doctor\\`, \\`splithub_refs\\` | \\`doctor\\`, \\`refs <id>\\` | \\`ok\\`, \\`checks[]\\`; \\`refs[]\\` shows the wiring |\n| 4. push (cloud) | \\`splithub_push\\` | \\`push\\` (\\`--dry-run\\` to preview) | \\`adopted\\`, \\`diff\\` |\n| 5. results | \\`splithub_status\\`, \\`splithub_results\\` | \\`status\\`, \\`results <id>\\` | \\`verdict.status\\`, \\`verdict.message\\`, \\`verdict.notes[]\\`, \\`daysToVerdict\\` |\n| 6. finish | \\`splithub_experiment_status\\` | \\`finish <id>\\` | \\`live\\`, \\`next\\` |\n| 7. ship | \\`splithub_ship\\` | \\`ship <id> --keep <v> [--dry-run]\\` | \\`diff\\`, \\`leftovers[]\\`, \\`next\\` |\n\nRules that keep the answer honest:\n- Plan before creating: if \\`traffic.daysLeft\\` is months, try a bigger change or a busier page.\n- \\`create\\` writes a running experiment; it goes live when the code is deployed (and pushed in cloud mode). Tell the user.\n- Verdicts are sequential (always-valid): checking any day is safe. Quote \\`verdict.message\\` and the always-valid\n \\`comparisons[].sequential.pValue\\`, not the fixed-horizon \\`pValue\\` (p = 0.01 there can still be not significant).\n Relay \\`verdict.notes[]\\`. Verdicts depend on sample size, not days. Say \\`verdict.sample.quality\\` (small | ok | good;\n good = every variant has its share of \\`goodSample\\`, default 5000 visitors, \\`create --good-sample\\`) next to the verdict.\n- \\`daysToVerdict\\` is the re-check date: schedule (or tell the user) a look in that many days instead of polling.\n- \\`srm_detected\\`: the split is broken; fix the setup, do not read the numbers.\n- \\`guardrail_breached\\`: don't ship. A variant made a guardrail worse (\\`verdict.guardrailBreached[]\\`), e.g. \"bold wins on\n signups but raises refunds\". \\`verdict.metrics[]\\` has the secondary metrics and guardrails, read like the main table.\n- Guard what matters when creating: \\`--secondary pricing_view --guardrail refunds:higher\\` (MCP: \\`secondary\\`, \\`guardrails\\`).\n Experiments that could clash on one page go in one layer: \\`--layer checkout:0-50\\` and \\`checkout:50-100\\` never share a visitor.\n- \\`splithub holdout set 5\\` keeps 5% of visitors out of every experiment; the \\`__holdout\\` row (\"Holdout: long-term impact\")\n compares them with everyone else.\n- Ask the user which variant to keep before \\`ship\\`; preview with \\`dryRun\\` and show them the diff.\n- Error \\`code\\` → action: \\`NOT_LOGGED_IN\\` → \\`splithub_login\\`, show the link, wait, retry · \\`INSUFFICIENT_SCOPE\\` → the key\n can only read; ask for a key with write scope · \\`NO_CONFIG\\` → \\`splithub_init\\` ·\n \\`EXPERIMENT_NOT_FOUND\\` → \\`splithub_status\\` for ids · \\`CONFIG_UNSAFE\\` → edit the config by hand where the experiment is\n defined · \\`CONFIG_WRITE\\` → the file was restored; edit by hand, then \\`doctor\\`.\n`;\n","// Skill: analytics properties (pageviews and custom events, read as reports).\n\nexport const SKILL_ANALYTICS = `---\nname: splithub-analytics\ndescription: Collect and read web analytics with SplitHub: analytics properties (pageviews, events with track(), identified users, sources, channels, pages, goals and conversions), setting one up in the app (analytics connect), funnels, paths, retention, realtime, event props, CSV export, segments, notes and alerts on traffic, sh.js or the SDK, allowed domains. Use when the user wants traffic numbers, page or source reports, event tracking, funnels, or asks to \"add analytics\" to an app that uses SplitHub or could.\n---\n\n# SplitHub analytics\n\nAn analytics property is a stream of pageviews and custom events, like a site in Google Analytics. It sits next to the\nexperiments: same config file, same CLI, same key, same storage choice (SplitHub Cloud or the app's own database).\nThere are no variants and no verdicts: reports are counts.\n\n## Set it up\n\n1. One step: \\`npx splithub analytics connect --json\\` (or Analytics → Set up in the \\`npx splithub\\` menu) picks the project's\n property (or creates one: \\`--name \"Marketing site\"\\`; a given id is used, \\`connect sh-x1h78w\\`) and adds\n \\`property=\"sh-…\"\\` to the one \\`<SplitHubProvider>\\` / \\`<SplitHubNextProvider>\\` in the code. It answers \\`wired.status\\`:\n added | already | other (another property is named there: ask, then \\`--force\\`) | none | many (add \\`snippets.provider\\`\n or \\`snippets.script\\` yourself), plus \\`snippets.track\\` and \\`next\\`.\n By hand: \\`npx splithub analytics create --name \"Marketing site\" --json\\` writes \\`properties: { 'sh-x1h78w': { name: … } }\\`\n into \\`splithub.config.ts\\` (self-hosted projects keep their properties there). Cloud mode: both also create it in the\n cloud at once (\\`live: applied\\`), so no push is needed; when \\`live\\` names a missing API key, \\`npx splithub login\\` and run it\n again, or \\`npx splithub push\\`. A property made in the dashboard needs no push either; its id is on its page.\n2. Send events. Events go only to a property named by its id, never to a guess:\n - SDK: \\`<SplitHubProvider config={config} property=\"sh-x1h78w\">\\`: a pageview on load and on every client-side route change.\n - Events: one call, \\`const track = useTrack(); track('Video Played', { id: 3 })\\` (or \\`client.track(...)\\`). Names: letters,\n digits, spaces and \\`_ . : / -\\`, up to 64 characters; props: a flat object up to 4 KB. The same call counts for\n experiments whose goal is that event. Only what the app passes to \\`track()\\` is sent.\n - Users: \\`const identify = useIdentify(); identify(user.id, { plan: 'pro' })\\` after sign-in (\\`identify(null)\\` on sign-out;\n sh.js: \\`splithub.identify(id, traits)\\`) ties visits to the app's user; reports then count \\`users\\`. No emails or names in traits.\n - No SDK: \\`<script src=\"https://go.splithub.io/sh.js\" data-key=\"pk_…\" async></script>\\` sends pageviews (SPA navigations\n included) and \\`window.splithub.track(name, props)\\` once the tag has \\`data-property=\"sh-x1h78w\"\\`.\n - One install covers analytics and experiments: the provider (or sh.js) with \\`property\\` collects pageviews and runs\n experiments. Each \\`track()\\` sends one event row and each page one page row; experiments whose goal is that event or\n page count them from those rows, so nothing extra is sent or billed. Never add sh.js and the SDK for the same\n property: when both run on a page, only the first collects pageviews.\n - Servers and other languages: \\`POST /v1/events\\` with \\`{ type: 'page', prop, url, vid, sid, ts, id, title?, ref? }\\` or\n \\`{ type: 'event', prop, name, props?, … }\\` (splithub-api skill).\n3. Development never sends to the cloud (same rule as experiments): check a deploy or \\`vite preview\\`.\n4. Events: any name is recorded, nothing to declare first. A goal is an event marked as one (\\`goals\\` in the config, the\n goal switch on an event in the dashboard, or simply naming the event as an experiment's goal); goals count as\n conversions in every property (a property's \\`goals\\` list narrows that). \\`value\\` is what one conversion is worth\n when the event carries no \\`revenue\\` prop; \\`event: 'Video Played'\\` matches an event name that is not a valid key.\n\n## Read it\n\n- \\`npx splithub analytics --json\\`: every property with visitors, visits, pageviews and bounce for the last 30 days.\n- \\`npx splithub status --json\\` (SplitHub Cloud) also lists every property under \\`properties\\`: the last 7 days against the 7 before\n (visitors, \\`change\\`, goal conversions); \\`npx splithub report\\` adds them as an Analytics table. The digest (Pro, set in the\n dashboard under Alerts) covers properties too: visitors, top sources and pages, goals and events against the period before.\n- \\`npx splithub analytics site --json\\` (\\`--days 7\\`, or \\`--from 2026-10-01 --to 2026-10-31\\`): totals, \\`users\\` (identified),\n goals (conversions = unique visitors who reached the goal in the range, completions, revenue), top pages, top sources, notes.\n- \\`--by page|source|channel|referrer|utm_source|utm_medium|utm_campaign|country|device|browser|os|platform|app_version|entry|exit|event|goal\\`; with a\n visit dimension, \\`--goal signup\\` adds conversions per row; \\`--by variant --experiment hero\\` splits visits by the\n variant each visitor saw, \\`--by trait --key plan\\` by an identify() trait. \\`--filter country=DE,FR --filter source=\"(none)\"\\` narrows any report.\n- \\`npx splithub analytics events site --json\\`: the latest raw pageviews and events, to check tracking right after wiring it.\n- More reports (SplitHub Cloud), each with the same \\`--days\\` / \\`--from --to\\` / \\`--filter\\` flags:\n - \\`analytics funnel site --steps \"page:/,event:Signup,goal:paid\" [--within visit|7d|30d] [--by country]\\`: visitors per step\n in order, \\`conversion\\` (share of step 1) and \\`dropoff\\` (share lost since the step before).\n - \\`analytics funnels site\\`: the funnels saved on the property (its Funnels tab, shared with the team).\n \\`--save Signup --steps \"page:/,goal:signup\" [--within 7d]\\` saves one (a saved name updates it), \\`--delete <id|name>\\`\n removes one, and \\`analytics funnel site --funnel Signup\\` runs it. Save a funnel the user will want to read again.\n - \\`analytics paths site --page /pricing [--prev]\\`: where visits went next (or came from).\n - \\`analytics retention site [--start visit|event:<name>|goal:<key>] [--return visit|event:<name>] [--period day|week]\\`: cohorts\n \\`{ start, users, retained[] }\\`, \\`retained[0]\\` = the cohort period itself; up to 90 days or 26 weeks (\\`clamped\\`).\n - \\`analytics realtime site\\`: visitors in the last 5 minutes, top pages and sources.\n - \\`analytics props site --event Signup [--key plan]\\`: an event's prop names, or one prop's values.\n - \\`analytics export site --by page|day [--raw] > report.csv\\`: CSV to stdout.\n - \\`--compare\\` on a report adds the period right before (\\`previous\\`), \\`--compare year\\` the same days a year earlier, \\`--compare 2026-08-01..2026-08-31\\` chosen days; \\`--segment \"Paid traffic\"\\` applies a saved segment\n (\\`analytics segments\\`, \\`--save <name> country=DE\\`, \\`--delete <id|name>\\`).\n - Notes mark a day on the charts: \\`npx splithub notes add \"Launched new pricing\" [--kind win] [--property site] [--day 2026-10-05]\\`,\n \\`notes --property site\\` lists them; add one when you ship something that may move traffic.\n - Alerts on a property (SplitHub Cloud, Pro): \\`npx splithub alerts add traffic_drop --property site --percent 50\\`, \\`traffic_spike\\`,\n \\`goal_silent --property site --goal signup --hours 24\\`, \\`event_count --property site --event Signup --count 1000 [--repeat]\\`.\n- Words: a visit (\\`sessions\\`) ends after 30 minutes without events; a bounce is a visit with one page and no event;\n \\`source\\` is the UTM source or the referrer's site (Google, Facebook, …), \\`(none)\\` = direct; \\`channel\\` groups them (Direct,\n Organic Search, Paid Social, Email, Referral, …); a conversion is a visitor reaching a goal (once per visitor in the range);\n \\`duration\\` is in milliseconds. Bots are never counted.\n- Self-hosted (\\`mode: 'self'\\`): the same commands give raw counts from the app's database (pageviews, visitors,\n sessions, events by name) for \\`--days\\` or \\`--from --to\\` (UTC days). Filters, \\`--by\\`, \\`--compare\\` and reports with sources,\n pages, visits and conversions come with SplitHub Cloud: say so.\n\n## Manage it\n\n- \\`npx splithub analytics pause site\\` / \\`resume site\\`: live in the cloud within a minute; paused events are dropped and not billed.\n- \\`npx splithub analytics archive site\\` / \\`restore site\\` (SplitHub Cloud): like Archive in the dashboard, it stops collecting and leaves\n the list (\\`archived\\` in it), numbers kept; restored comes back paused.\n- \\`npx splithub analytics remove site\\`: out of the config (push next); a dashboard-made property is deleted with its numbers.\n- Allowed domains are per experiment and per property: \\`npx splithub domains set property site example.com\\` (subdomains included),\n \\`npx splithub domains clear property site\\` (any domain again), \\`npx splithub domains\\` lists them all. An empty list\n accepts every origin. Add localhost too when testing from it.\n- Apps: \\`kind: 'app'\\` on a property (\\`analytics create --kind app\\`, the default in an app project) shows screens, versions and\n retention in the dashboard; screens are page events (the \\`splithub-apps\\` skill).\n- Billing: every pageview and custom event counts like one exposure against the project's allowance.\n\n## Do not\n\n- Put personal data in event props (emails, names, ids from other systems).\n- Fire an event in a render loop or on every scroll: each one is stored and billed.\n- Read analytics counts as an experiment result: use \\`splithub results\\` for experiments.\n`;\n","// Skill: experiments and analytics in mobile and desktop apps (React Native / Expo, iOS, Android).\n\nexport const SKILL_APPS = `---\nname: splithub-apps\ndescription: Run SplitHub experiments and analytics in a mobile or desktop app: React Native and Expo (@splithub/react-native), native iOS (Swift package SplitHub) and Android (io.splithub:splithub). Screens, app_version targeting, retention, and why app experiments are created in the cloud. Use when the project has react-native, expo, an Xcode project or an Android Gradle build, or the user asks to A/B test or measure an app.\n---\n\n# SplitHub in apps\n\nSame experiments, goals and analytics as on the web. Two things differ: an app's config is built into the binary,\nand screens take the place of pages.\n\n## Install\n\n- React Native / Expo: \\`npx splithub init --mode cloud --yes --json\\`. It installs \\`@splithub/react-native\\` (plus\n \\`@react-native-async-storage/async-storage\\`, through \\`npx expo install\\` on Expo) and wraps the entry in\n \\`<SplitHubProvider config={config}>\\`: \\`app/_layout.tsx\\` with Expo Router (adds \\`<ExpoRouterScreens />\\`),\n else \\`App.tsx\\` (adds \\`<NavigationScreens />\\` inside \\`<NavigationContainer>\\` with React Navigation). Both come from\n \\`@splithub/react-native\\`; the hooks \\`useExpoRouterTracking()\\` / \\`useNavigationTracking(ref)\\` do the same by hand.\n Without a config file: \\`<SplitHubProvider publicKey=\"pk_…\" property=\"sh-…\">\\`.\n \\`app.entry.status\\`: added | already | manual (wire \\`nextStep\\` by hand). Hooks are the web ones, imported from\n \\`@splithub/react-native\\`: \\`useValue\\`, \\`useVariant\\`, \\`<Experiment>\\`, \\`useTrack\\`, \\`useIdentify\\`.\n- iOS: Swift package \\`SplitHub\\` (Xcode: File → Add Package Dependencies → \\`https://github.com/splithub-io/splithub-sdk\\`).\n \\`SplitHub.start(publicKey: \"pk_…\", property: \"sh-…\")\\` once at launch; \\`SplitHub.variant(\"id\")\\`, SwiftUI \\`SplitHubExperiment(\"id\") { variant in }\\`.\n- Android: \\`implementation(\"io.splithub:splithub:<version>\")\\` (+ \\`io.splithub:splithub-compose\\` for Compose).\n \\`SplitHub.start(this, \"pk_…\", property = \"sh-…\")\\` in \\`Application.onCreate\\`; \\`SplitHub.variant(\"id\")\\`, Compose \\`Experiment(\"id\") { variant -> }\\`, \\`TrackScreen(\"Home\")\\`.\n- Native apps have no \\`splithub.config.ts\\`: \\`init\\` prints the install lines and a quick start, and experiments come from the cloud.\n- Analytics: \\`npx splithub analytics connect --json\\` names a property on the provider; in an app project it is created with \\`kind: 'app'\\`.\n- \\`npx splithub doctor\\` checks the package, the storage module and the provider.\n\n## Experiments reach apps through the cloud\n\n- The config file ships inside the binary: an experiment added there reaches users only with the next store release,\n and only users who update. Old versions stay on what they were built with.\n- Start new experiments in the dashboard (no release; installed apps get them on the next launch with network). Pause,\n finish, weights and values set in the dashboard or with \\`npx splithub pause|start|finish <id>\\` also apply live.\n- Still \\`npx splithub push\\` after any config change, so the cloud and the file agree. Apps also receive the pushed\n experiments from the cloud (overrides JSON with \\`?all=1\\`), so a pushed experiment reaches an app whose build has its variants.\n- Redirect experiments do nothing in an app: use \\`value\\` (copy, prices, flags as JSON) or \\`component\\`.\n- Assignment is the same local hash on every platform: a visitor gets the same variant on web, iOS and Android.\n\n## Screens, versions, platforms\n\n- A screen is a \\`page\\` event: url \\`/<screen name>\\` (or the route path with Expo Router), title the screen name. Every\n page report, funnel (\\`page:/Checkout\\`) and pageview goal (\\`{ type: 'pageview', path: '/Checkout' }\\`) works on screens.\n- Without a navigation tracker: \\`useScreen('Settings')\\` (React Native), \\`SplitHub.screen(\"Settings\")\\` (iOS, Android).\n- Target app versions in the experiment's flow (dashboard targeting, or by hand):\n \\`{ type: 'condition', conditions: [{ field: 'app_version', op: 'gte', value: '2.4' }], then: 'split', else: 'skip' }\\`.\n \\`gte\\` / \\`lt\\` compare dotted versions part by part (\\`2.10.0\\` ≥ \\`2.9\\`). \\`platform\\` is \\`ios | android | macos | windows | linux | web\\`.\n Gate on the version that ships the variant code, so older builds skip the experiment.\n- Break down or filter by them: \\`results <id> --by platform\\`, \\`--by app_version\\`, \\`--filter platform=ios\\`;\n \\`analytics <property> --by app_version\\`, \\`--filter app_version=2.5.0\\`.\n- Events sent offline are kept on the device and arrive later with their own time: today's numbers can still grow.\n\n## Retention\n\n\\`npx splithub analytics retention <property> [--period day|week] [--from --to] --json\\`: \\`cohorts[] { start, users, retained[] }\\`,\n\\`retained[0]\\` is the cohort period itself, \\`retained[n] / users\\` the share back in period n. Up to 90 days or 26 weeks\n(\\`clamped: true\\` when cut). \\`--start event:Signup\\` and \\`--return event:<name>\\` change who counts. Counts, never a verdict.\n`;\n","// Agent skills installed by `splithub init` / `splithub skills`. One folder per\n// topic under .claude/skills/, so an agent loads only what the task needs:\n// splithub — the library, the config file, the CLI, where things live\n// ab-testing — what a good test is, metrics, sample size, when to stop\n// splithub-api — the HTTP API (keys, endpoints, payloads) for scripts and servers\n// splithub-mcp — the MCP server: tools, how to register it in Claude Code / Cursor\n// splithub-ship — keep a variant and take the test out (`splithub ship`)\n// splithub-loop — the whole loop for an agent, tool by tool\n// splithub-analytics — analytics properties: pageviews, events, reports, allowed domains\n// splithub-apps — React Native / Expo, iOS and Android: install, screens, versions, retention\n// Same text goes to .cursor/rules and the AGENTS.md section points here.\n\nexport interface Skill {\n dir: string;\n body: string;\n}\n\nexport const SKILL_SPLITHUB = `---\nname: splithub\ndescription: Add, change, run or read experiments in an app that uses SplitHub (@splithub/react, splithub.config.ts, the splithub CLI, SplitHub Cloud). Use when the user asks to A/B test a component, headline, image, price, CTA or page, asks which variant is winning, or wants to start, pause or finish an experiment; also for notes on the charts, alert rules (events used, traffic, goals, winners), short links and allowed domains.\n---\n\n# SplitHub for coding agents\n\nThree pieces: \\`splithub.config.ts\\` (the experiments; source of truth when it exists),\n\\`@splithub/react\\` (renders variants), the \\`splithub\\` CLI (creates, pushes, reads results).\nEvents go to the app's own database (self mode) or to SplitHub Cloud (cloud mode).\n\n## Where things live\n\n- Config: \\`splithub.config.ts\\` in the project root. Experiments and goals. Ships to the browser: never put secrets in it.\n- Credentials: \\`npx splithub login\\` (or \\`init --mode cloud\\`) prints a link; the human approves it in the browser; the CLI\n stores a project API key for this folder. Never ask the user to paste keys. CI uses \\`SPLITHUB_API_KEY\\`.\n- The public key (\\`pk_\\`) ends up in \\`storage.key\\` of the config from any of: \\`login\\` (saved credentials), the first\n \\`push\\`, \\`init --key\\`, or \\`SPLITHUB_API_KEY\\` in the environment (init asks the cloud). Missing key = events go nowhere.\n- Cloud: \\`npx splithub push\\` uploads the config. Experiments the cloud has from an earlier push that the file lacks are\n kept (\\`kept\\` in the answer); only \\`npx splithub push --prune\\` removes them, and only when the user asked for that.\n \\`npx splithub pull\\` writes dashboard-created experiments into the file.\n- Results: \\`npx splithub status --json\\` (in the cloud it also has \\`properties\\`: each analytics property's last 7 days), \\`npx splithub results <id> --json\\`. Sizing: \\`npx splithub plan --baseline 0.05 --mde 0.1\\`.\n- Closer reads (cloud): \\`results <id> --from --to --filter country=DE\\` (a slice), \\`--by <dimension>\\`, \\`--timeline\\`, \\`--engagement\\`,\n \\`--events\\`, \\`--export --by <dimension>\\` or \\`--export --events\\` (CSV); \\`npx splithub events --experiment <id>\\` for the raw tail. See \"Read results\".\n- Code that uses an experiment: \\`npx splithub refs <id> --json\\`. Keep a variant and remove the experiment: \\`npx splithub ship <id> --keep <v>\\`.\n- \\`--json\\` prints one line; errors are \\`{ error, code, hint }\\` with exit code 1. \\`INSUFFICIENT_SCOPE\\` adds \\`scope\\`\n (e.g. \\`notes:write\\`): the API key is limited to some areas; ask the user for a key with that scope. The \\`splithub-loop\\` skill has the whole flow.\n- Everything interactive: \\`npx splithub\\`, one menu: Experiments, Analytics, Short links, Alerts, Notes, Allowed domains,\n push / pull, local testing, doctor, agent skills. Everything scriptable: subcommands + \\`--json\\` (\\`npx splithub --help\\`).\n- Web analytics (pageviews, events, sources, pages, funnels) live in analytics properties: \\`npx splithub analytics connect\\`\n sets one up in the app; the \\`splithub-analytics\\` skill has the rest.\n- Apps (React Native, Expo, iOS, Android): the \\`splithub-apps\\` skill. The config is built into the binary, so new\n experiments for an app start in the dashboard; screens are page events; target versions with \\`app_version\\` \\`gte\\`.\n\n## Pick the kind\n\n| kind | use it when | create | read in code |\n|---|---|---|---|\n| \\`value\\` | only data changes: text, number, image URL, price, JSON. The default choice: no new components. | \\`--variants control,bold --value control=\"Old text\" --value bold=\"New text\"\\` | \\`const text = useValue<string>('<id>')\\`; server components: \\`getValue\\` from \\`@splithub/next\\`; no SDK: \\`sh.value('<id>')\\` |\n| \\`component\\` | structure changes: a layout, a section, a flow, a different component per variant | \\`--variants control,bold\\` (the CLI scaffolds \\`splithub/<id>/<Variant>.tsx\\` stubs) | \\`<Experiment id=\"<id>\"><Variant name=\"control\">…</Variant><Variant name=\"bold\">…</Variant></Experiment>\\`, or \\`useVariant('<id>')\\` in a switch |\n| \\`redirect\\` | a whole page changes: another URL per variant | \\`--match / --to control=/ --to v2=/home-v2\\` | nothing: \\`@splithub/next\\` middleware or the drop-in script \\`<script src=\"https://go.splithub.io/sh.js\" data-key=\"pk_…\">\\` sends visitors there |\n| \\`mvt\\` | several things change at once (headline × button × image) and the user wants to know which of them matters; every combination is tested and each factor is read on its own | \\`--factor headline=old:\"Old text\",new:\"New text\" --factor button=blue:#2563eb,green:#16a34a\\` (no \\`--variants\\`; first level = control; at most 4 factors × 4 levels, 16 combinations) | \\`const { headline, button } = useValue<{ headline: string; button: string }>('<id>')\\` |\n\nmvt needs more visitors than a two-variant experiment: every combination must reach the minimum on its own (the results show the\ncombinations and, below them, each factor summed over its combinations). With little traffic, change one thing with \\`value\\`.\n\n## Create an experiment\n\n1. \\`npx splithub create --kind <value|component|redirect|mvt> --id <key> … --goal <event name> --yes --json\\` (see the table).\n The key is the experiment's id for good: never reuse one from an earlier experiment. \\`--name \"Signup button\"\\` adds a human\n name (dashboard, CLI) that can change any time. \\`push\\` fails with \\`KEY_CONFLICT\\` when a key already belongs to\n another experiment: ask the user, then rename the key, or push with \\`--replace <key>\\` (new experiment, old numbers cleared)\n or \\`--same <key>\\` (same experiment). \\`KEY_DELETED\\`: a deleted experiment used the key; pick a new one.\n2. Goal: any event the app sends with \\`track('<name>', props?)\\`, the one call for every event. Nothing to declare\n first: a name not in \\`goals\\` becomes an event goal keyed by its slug (\\`Video Played\\` → \\`video-played\\`) and \\`create\\`\n says so. A goal is just an event marked as one; page visits and clicks are goals declared in \\`goals\\`:\n \\`{ type: 'pageview', path: '/thanks' }\\`, \\`{ type: 'click', selector: '#buy' }\\` (tracked automatically by the SDK and the script).\n With an analytics property on the provider, the same \\`track()\\` and pageviews feed both: one install, one row per action.\n3. Wire it in code. \\`create\\` writes \\`status: 'running'\\`: the experiment goes live for every visitor, first page view\n included, as soon as this code is deployed. Use \\`--status draft\\` only when the user asks to hold it.\n4. Cloud mode: \\`npx splithub push\\` after any config change.\n5. Hand-off, always: end your reply by saying the experiment is **running in the config** and goes live when the user deploys\n this code; nothing is recorded before that, and local development never sends events to the cloud. Tell them how to\n check it locally (\\`?sh_force=<id>:<variant>\\`) and that Pause in the dashboard or \\`npx splithub pause <id>\\` holds it.\n In cloud mode a status set in the dashboard wins over the file for every visitor, first page included.\n For a draft (only if asked): say visitors do not see it and nothing is recorded until \\`npx splithub start <id>\\`.\n\nA draft is invisible to visitors. To check one before starting: \\`runDraftsInDev: true\\` at the top level of the config\nserves drafts like running experiments in development only (\\`NODE_ENV=development\\`: \\`next dev\\`, \\`vite\\`);\n\\`?sh_force=<id>:<variant>\\` shows one variant on any page, draft or not, without recording an exposure;\n\\`?sh_debug=1\\` (or \\`npx splithub dev\\`) logs every decision and opens a panel to switch variants.\nIn development the SDK explains drafts, paused experiments and held-back events in one line each. Vite apps: add \\`splithub()\\`\nfrom \\`@splithub/core/vite\\` to the plugins in vite.config so these lines and a summary of every experiment appear in the\nterminal that runs \\`vite\\`; Next.js server code prints them in its terminal anyway.\n\nKeys: lowercase a-z 0-9 - _, max 64 chars. First variant = control. Weights are relative (50/50, 1/1, 90/10).\nTargeting (country, device, UTM, cookie, time) is a \\`flow\\` graph on the experiment, edited in the dashboard; \\`pull\\` brings it into the file.\n\n## Read results\n\n\\`verdict.status\\` ∈ no_data | insufficient_sample | srm_detected | winner_found | no_significant_difference.\nReport \\`verdict.message\\` verbatim and the numbers behind it (visitors per variant, lift, the always-valid\n\\`comparisons[].sequential.pValue\\` and \\`sequential.ci\\`; the plain \\`pValue\\` is fixed-horizon, for display only) and relay\n\\`verdict.notes[]\\`. Verdicts are sequential and depend on sample size, not days: safe to check any time. \\`verdict.sample.quality\\` is\nsmall (below 100 visitors per variant or 50 conversions), ok, or good (every variant has its share of \\`goodSample\\`, default 5000\nvisitors; \\`create --good-sample\\`); say it next to the verdict. \\`verdict.sample.stars\\` (0..5) scores data quality from\n\\`verdict.sample.checks[]\\`: report the stars and the unmet labels; they never override the verdict. \\`daysToVerdict\\` says when to look again.\nNever declare a winner from raw rates. \\`srm_detected\\` means the split is broken: fix the setup before anything else.\n\n### Slices, breakdowns, timelines (SplitHub Cloud)\n\n- A slice: \\`npx splithub results <id> --from 2026-10-01 --to 2026-10-15 --filter country=DE --filter channel=\"Paid Search\" --json\\`.\n \\`from\\` / \\`to\\` are first-exposure days (project time zone): the visitors who entered the experiment then, with all their\n later conversions. Filters: country, region, city, device, os, browser, language, host, source, channel, utm_source,\n utm_medium, utm_campaign, utm_term, utm_content, landing or page (the page of the first exposure); comma-separated values,\n \\`(none)\\` matches empty. The answer carries \\`scope\\` and its verdict is computed on the slice only: say so and quote\n \\`scope.note\\`. The decision stays with the unfiltered verdict; a slice carries no \\`voice\\` (no advice).\n- One view at a time, same range and filters (\\`--json\\` adds \\`view\\`): \\`--by country|device|source|channel|page|landing|utm_campaign|…\\`\n gives \\`segments[]\\` with each variant's cells and its lift against the control inside the segment (\\`significant\\`, \\`better\\`,\n \\`small\\` = too few visitors); \\`--timeline\\` gives visitors and conversions per day and variant (a day = visitors first seen\n that day); \\`--engagement\\` gives bounce rate, pages per visit and visit length per variant from the analytics property on\n the same visitors (\\`property: null\\` = none); \\`--events\\` gives \\`rows[]\\` for every goal (the experiment's goal, metrics and\n guardrails first, \\`measured\\`) and event of these visitors, each with \\`perVariant\\` visitors and rate and \\`comparisons[]\\` against\n the control (\\`property: null\\` = goals only: other events need analytics on the same site). \\`--export --by <dimension>\\` prints\n the breakdown as CSV, \\`--export --events\\` the events table.\n- \\`npx splithub events --experiment <id> [--type exposure|goal] [--limit 50] [--before <nextBefore>]\\` lists the raw exposures\n and goals (same filters; 7 days, 30 on Pro). Use it to check the wiring.\n- Segments and events are for hypotheses: never call a winner from one segment or one event. With several segments, one will look great by chance.\n A self-hosted endpoint answers none of these (\\`NOT_CLOUD\\`); its results stay raw counts.\n\n## Finish, and what to do when an experiment is finished\n\n\\`npx splithub finish <id>\\` stops the experiment (live within a minute in cloud mode). A finished experiment keeps its numbers for as long\nas it stays in the config; the code still contains every variant until someone removes it.\n\nWhenever you see an experiment with \\`status: finished\\` (in \\`status\\`, \\`results\\`, the MCP tools, or right after you finished it):\n1. Read \\`npx splithub results <id> --json\\` and tell the user the verdict in one line with its numbers.\n2. Ask two questions, do not assume: **which variant to keep** (recommend \\`verdict.winner\\`; with no significant\n difference, the control or the simpler one) and **whether to remove the experiment from the code now**.\n3. On yes, follow the \\`splithub-ship\\` skill: \\`npx splithub ship <id> --keep <variant> --dry-run\\`, show the diff, then run it\n without \\`--dry-run\\`; fix the \\`leftovers\\`, \\`push\\` in cloud mode, run \\`doctor\\` and the project's checks.\n4. On no, leave everything: a finished experiment costs nothing and the user may come back to it.\n\nA \\`paused\\` experiment is not over: say so and ask whether to resume (\\`start\\`) or finish it.\n\n## Around experiments (SplitHub Cloud)\n\n- **Notes**: what happened on a day, marked on experiment timelines and analytics charts. \\`npx splithub notes add \"Launched the\n new pricing page\" [--kind note|issue|win] [--experiment <key> | --property <id>] [--day 2026-10-05]\\` (none = the whole\n project); \\`notes\\` lists them (\\`--experiment\\`, \\`--property\\`, \\`--kind\\`, \\`--days\\`), \\`notes edit <id> \"<text>\"\\`, \\`notes delete <id>\\`.\n Add one when you ship something that may move the numbers.\n- **Alerts** (they fire on Pro; added on another plan they are saved switched off): \\`npx splithub alerts\\` lists rules, progress\n and recent alerts; \\`alerts add <condition>\\`: experiments \\`srm\\`, \\`winner\\`, \\`loser --lift 10\\`, \\`exposures --visitors N\\`,\n \\`conversions --conversions N\\`, \\`duration --days N\\`, \\`no_events --hours 24\\` (\\`--experiment <key>\\`, else every running one;\n \\`--pause\\`, \\`--finish\\`, \\`--drop-loser\\` act on it); account \\`quota --percent 80\\`, \\`usage --every 1000\\` (each time this month's\n events cross another 1,000); analytics \\`traffic_drop|traffic_spike --property <id> --percent 50\\`, \\`goal_silent --property <id>\n --goal <key> --hours 24\\`, \\`event_count --property <id> [--event <name>] --count 500 [--repeat]\\`. \\`alerts enable|disable|delete|test <id>\\`\n (\\`test\\` = what would fire now, nothing sent). Channels (email, Slack, Discord, webhook) are set in the dashboard.\n- **Short links**: \\`npx splithub links create https://example.com/spring [--slug spring] [--name \"Spring\"]\\`; several URLs with\n \\`--weights 70,30\\` split visitors between pages. \\`links\\` lists them with clicks, \\`links <slug>\\` shows one link's clicks,\n \\`links pause|resume|delete <slug>\\`.\n- **Allowed domains**: \\`npx splithub domains set experiment <key> example.com\\` (subdomains included), \\`domains clear experiment <key>\\`,\n \\`domains\\` lists them. No list = any origin.\n\n## Do not\n\n- Nest an \\`<Experiment>\\` inside a \\`<Variant>\\` of the same id; call hooks conditionally.\n- Change \\`seed\\`, weights or variants of a running experiment (reshuffles visitors). Create a new experiment instead.\n- Edit in the dashboard what the config file owns: file experiments are read-only there (pause/finish still work).\n- Run more than 2-3 experiments on one page of a low-traffic site.\n- Put secrets, API keys or database credentials in the config or in the browser. \\`pk_\\` is public, \\`sk_\\` is not.\n`;\n\nexport const SKILL_AB_TESTING = `---\nname: ab-testing\ndescription: How to design, run and read an experiment correctly: hypothesis, control, primary metric, sample size, significance, SRM, peeking, when to stop. Use before creating an experiment or when interpreting results, with any tool.\n---\n\n# A/B testing, the parts that matter\n\nAn experiment splits visitors at random into variants and compares one metric. It answers one question:\n\"does this change move this metric?\" Everything below exists to keep that answer honest.\n\n## Before creating an experiment\n\n1. **One hypothesis, one primary metric.** \"A shorter signup form raises signup completion.\" The metric is a goal\n (event, page visit or click) that happens after the exposure. Pick it before looking at data.\n2. **Control first.** The first variant is what exists today. Change one thing per variant; several unrelated changes\n in one variant cannot be attributed.\n3. **Traffic reality.** Rough rule: to detect a relative lift L on a baseline rate p you need about\n \\`16 · p(1-p) / (p·L)²\\` visitors per variant (95% confidence, 80% power).\n Examples: baseline 5%, lift 20% → ~7,600 per variant; baseline 2%, lift 10% → ~78,000 per variant.\n If the site cannot reach that in 2-4 weeks, try a bigger change or a higher-traffic page.\n4. **Few experiments per page.** Interactions between simultaneous experiments on the same page muddy both.\n\n## While it runs\n\n- **Do not peek and stop early.** Checking daily and stopping at the first \"significant\" moment inflates false\n positives several times. Decide the sample or the duration up front; run whole weeks (weekday/weekend cycles).\n- **SRM (sample ratio mismatch).** If the split is 50/50 and you see 60/40, the assignment or the tracking is broken\n (bots, caching, redirect loops, a variant that errors). Fix first; results from an SRM run are meaningless.\n- **Keep variants frozen.** Changing copy, weights or targeting mid-run reshuffles who saw what. Start a new experiment.\n- **Watch the guardrails.** A variant that wins the primary metric but breaks revenue, errors or latency is not a win.\n\n## Reading results\n\n- Significance (p < 0.05 after correction for several variants) says the difference is unlikely to be noise;\n the confidence interval says how big it plausibly is. A \"winner\" with a CI that touches 0 is a weak win.\n- \"No significant difference\" with a sample smaller than needed means **keep running**, not \"no effect\".\n With enough sample it means the change does not matter: ship whichever is cheaper or cleaner.\n- Relative lift is on the baseline rate: 5% → 6% is +20% relative, +1 point absolute. Report both.\n- Attribution: conversions count only after the visitor's first exposure, per unique visitor.\n- Segments (country, device) are for hypotheses, not verdicts: slicing after the fact finds noise.\n\n## When to stop\n\n- Winner found with the planned sample → ship it, finish the experiment, remove the losing code.\n- Planned sample reached, no difference → ship the simpler variant, finish.\n- SRM or broken tracking → stop, fix, restart as a new experiment.\n- The business moved on → finish; do not leave experiments running forever (they cost events and split traffic).\n\n## Vocabulary\n\nexposure = a visitor saw a variant · conversion = the goal happened after exposure · lift = relative change in rate ·\np-value = chance of seeing this difference by luck · CI = range the true difference likely lies in ·\nSRM = the split differs from the configured weights · guardrail = a metric that must not get worse.\n`;\n\nexport const SKILL_SPLITHUB_API = `---\nname: splithub-api\ndescription: Use the SplitHub Cloud HTTP API directly: public key event ingest, API-key endpoints for config, status, results, overrides, analytics reports, notes, short links and alert rules. Use when writing a server, a script, a non-JS client, or when the CLI is not available.\n---\n\n# SplitHub Cloud API\n\nBase URL: \\`https://go.splithub.io\\`. JSON in, JSON out (no envelope under \\`/v1/*\\`). Two credentials:\n\n- **Public key \\`pk_…\\`**: identifies the project to browsers and SDKs. Safe to ship. Can only send events and read\n the public overrides JSON.\n- **API key \\`sk_…\\`**: project-scoped secret for servers, CI and the CLI (\\`npx splithub login\\` mints one through a\n browser approval; or Settings → API keys in the dashboard). Never in client code. It can be limited to some areas:\n see API keys and scopes below.\n\n## Send events (public key)\n\n\\`\\`\\`http\nPOST /v1/events\nAuthorization: Bearer pk_live_…\nContent-Type: application/json\n\n{ \"project\": \"my-app\", \"sdk\": \"custom/1.0\", \"events\": [\n { \"id\": \"e_01h…\", \"type\": \"exposure\", \"exp\": \"hero-cta\", \"var\": \"bold\", \"vid\": \"v_abc\", \"sid\": \"s_1\", \"ts\": 1760000000000, \"url\": \"/\" },\n { \"id\": \"g_01h…\", \"type\": \"goal\", \"goal\": \"signup\", \"vid\": \"v_abc\", \"sid\": \"s_1\", \"ts\": 1760000010000, \"props\": { \"revenue\": 49 } }\n] }\n\\`\\`\\`\n\n- Analytics properties take two more types: \\`{ \"type\": \"page\", \"prop\": \"site\", \"url\": \"/pricing\", \"title\"?, \"ref\"?, … }\\`\n (\\`ref\\` = document.referrer) and \\`{ \"type\": \"event\", \"prop\": \"site\", \"name\": \"Video Played\", \"props\"?: { … }, … }\\`.\n Both are billed like one exposure each; events of a property that is paused or unknown are dropped.\n An \\`event\\` row also converts the experiments whose goal is that event, and a \\`page\\` row the page-visit goals its path\n matches (not billed again): send one row per action, not a goal row next to it (one within 1 s is counted once).\n \\`{ \"type\": \"identify\", \"prop\": \"site\", \"uid\": \"user_42\", \"traits\"?: { \"plan\": \"pro\" }, … }\\` ties the visitor to your user\n (not billed). Requests from bots are dropped.\n- \\`id\\`: unique per event (8-64 chars, [a-z0-9_-]); duplicates are ignored. \\`vid\\`: stable visitor id (cookie \\`sh_vid\\`).\n- Reply \\`202 { ok, received, inserted, dropped }\\`. A project with nothing running or no config yet answers\n \\`202 { ok, inserted: 0, idle: 'no_running' | 'no_config' }\\`: nothing stored, not an error. \\`429\\` with \\`code\\` ∈\n quota_exceeded | deleted: back off for \\`Retry-After\\` seconds; nothing was stored. Allowed domains are set per experiment and per\n property: events from another origin are dropped, and \\`403 origin_not_allowed\\` comes back when nothing in the batch was allowed.\n- Exposures for experiments that are not running are dropped and not billed. Goals are never billed.\n\n## API keys and scopes\n\nA key can do everything (\\`*\\`, the default) or only some areas, each with read or write (write includes read).\nPick them in Settings → API keys when creating the key.\n\n| Area | Covers |\n|---|---|\n| \\`experiments\\` | status, results, report, config push, overrides, archive, reviews |\n| \\`analytics\\` | properties, their reports, segments, the event catalog |\n| \\`events\\` | read: raw events and \\`export.csv?raw=1\\`; write: send events from your server with this key |\n| \\`notes\\`, \\`links\\`, \\`alerts\\`, \\`domains\\` | those endpoints |\n\nScope strings: \\`<area>:read\\` / \\`<area>:write\\` (e.g. \\`notes:write\\`, \\`analytics:read\\`), \\`read\\` / \\`write\\` for every area,\n\\`*\\` for everything. Keys made before scopes existed have \\`*\\`.\n\nServer-side sending: a key with \\`events:write\\` can post to \\`POST /v1/events\\` instead of the public key. It is trusted,\nso there is no origin check; keep it on the server.\n\n\\`\\`\\`bash\ncurl -X POST https://go.splithub.io/v1/events \\\\\n -H \"Authorization: Bearer $SPLITHUB_API_KEY\" -H \"Content-Type: application/json\" \\\\\n -d '{ \"sdk\": \"server/1.0\", \"events\": [\n { \"id\": \"g_order_1042\", \"type\": \"goal\", \"goal\": \"purchase\", \"vid\": \"v_abc\", \"ts\": 1760000010000, \"props\": { \"revenue\": 49 } },\n { \"id\": \"e_order_1042\", \"type\": \"event\", \"prop\": \"site\", \"name\": \"Order Paid\", \"vid\": \"v_abc\", \"ts\": 1760000010000 }\n ] }'\n\\`\\`\\`\n\n\\`vid\\` is the visitor's \\`sh_vid\\` cookie, so the goal lands on the variant they saw. A request the key may not make\nanswers \\`403 { code: 'insufficient_scope', scope: 'notes:write', error, hint }\\`: \\`scope\\` names the missing one, and the CLI\nshows it (\\`--json\\` adds \\`scope\\`). Ask the user for a key with that scope; don't retry with another key.\n\n## Live config for clients (public key)\n\n\\`GET /v1/overrides/<pk>.json\\` (apps add \\`?all=1\\`: \\`added\\` then also carries the pushed experiments) → \\`{ version, experiments: { <id>: { status?, traffic?, weights?, values? } }, added: [ …hosted experiments… ], goals: [...], ctx: { country, region, city } }\\`.\nPoll it at most once a minute; the SDK caches it in localStorage. \\`ctx\\` is the visitor's geo for targeting.\n\n## Project endpoints (API key)\n\n\\`\\`\\`http\nGET /v1/status every experiment: status, visitors, days, verdict headline\nGET /v1/results/<experiment> full verdict: sample, comparisons (lift, p-value, CI, P(beat)), srm, winner\n ?from=&to= (first-exposure days) &country=DE&channel=…: the verdict on that slice, with scope { filtered, range, filters, note }\nGET /v1/experiments/<experiment>/timeline ?from=&to=&<filters>: exposures[] and conversions[] per day and variant, notes\nGET /v1/experiments/<experiment>/breakdown/<by> by country|region|city|device|os|platform|app_version|browser|language|host|page (= url)|referrer|source|channel|landing|utm_*:\n order[], segments[] { dim, cells, comparisons { lift, pValue, significant, better }, total, small }\nGET /v1/experiments/<experiment>/engagement { property, variants[] { visitors, sessions, pagesPerVisit, bounceRate, avgVisit } } (&property=)\nGET /v1/experiments/<experiment>/events-summary { property, variants[], visitors, rows[] { name, goalKey, isGoal, measured, perVariant, comparisons, small } } (&property=)\nGET /v1/experiments/<experiment>/export.breakdown.csv?by= the breakdown as CSV, lift per segment\nGET /v1/experiments/<experiment>/export.events-summary.csv the events table as CSV, lift per event\nGET /v1/experiments/<experiment>/events ?type=exposure|goal&before=&limit=&<filters>: raw events, nextBefore (needs events:read)\nGET /v1/config the config stored in the cloud (file + dashboard experiments)\nPUT /v1/config { config, prune? } push a normalized config (what defineConfig returns); answers cloudOnly experiments to adopt and kept ones (from an earlier push, missing from this one; prune: true removes them)\nGET /v1/overrides live overrides\nPUT /v1/overrides/<experiment> { status | traffic | weights | values } pause / resume / reweight without a deploy\nDELETE /v1/overrides/<experiment>\nGET /v1/properties analytics properties: live status, goals, domains, last 30 days\nPOST /v1/properties { key, name?, goals?, domains? } create one (dashboard-owned)\nPATCH /v1/properties/<key> { status: running | paused, name?, goals? }\nGET /v1/properties/<key>/summary ?from=&to= (YYYY-MM-DD) &<dimension>=a,b[&compare=previous|year|custom&cfrom=&cto=]: totals, days, goals, notes\nGET /v1/properties/<key>/breakdown ?by=source|channel|page|event|goal|country|…&goal=[&compare=…]: rows\nGET /v1/properties/<key>/funnel ?steps=page:/,event:Signup,goal:paid&within=visit|7d|30d[&by=]: steps with visitors, conversion, dropoff\n ?funnel=<id> runs a saved funnel (its steps and within)\nGET|POST /v1/properties/<key>/funnels { name, steps[], within? } PATCH|DELETE /v1/properties/<key>/funnels/<id>\nGET /v1/properties/<key>/paths ?page=/pricing&direction=next|prev: rows { value, visits }\nGET /v1/properties/<key>/retention ?start=visit|event:<n>|goal:<k>&return=visit|event:<n>&period=day|week&from=&to=: { period, cohorts[] { start, users, retained[] } }\nGET /v1/properties/<key>/realtime | /events?type=page|event | /props?name=&key= | /export.csv?by=|day (&raw=1)\nGET|POST /v1/segments { name, filters, propertyKey? } PATCH|DELETE /v1/segments/<id>\nGET /v1/domains every allowed domain and where it applies, observed origins\nPUT /v1/domains/<experiment|property>/<key> { hosts: [...] } replace one list ([] = any origin)\nGET /v1/notes ?experiment=&property=&kind=&from=&to=[&exact=1] newest first; experiment / property also return project-wide notes unless exact=1\nPOST /v1/notes { text (≤ 2000), day? (default today, project time zone), kind?: note|issue|win, experimentKey? | propertyKey? (none = whole project) }\nPATCH|DELETE /v1/notes/<id> { text?, day?, kind? }\nGET /v1/links short links: shortUrl, destinations [{ id, url, weight }], status, totalClicks\nPOST /v1/links { name, destinations: [{ url, weight? }], shortCode?, description?, clickLimit? }\nPATCH|DELETE /v1/links/<id> { name?, shortCode?, status: active|paused, destinations?, description? } GET /v1/links/<id>/stats: byDay (30 days), byDestination, byCountry, byDevice, byReferrer\nGET /v1/alerts rules, channels, digest, history, conditions, plan\nPOST /v1/alerts/rules { condition, params, actions?: { notify, pause, finish, dropLoser }, name?, experiment?, enabled?, cooldownHours? }\nPATCH|DELETE /v1/alerts/rules/<id> POST /v1/alerts/rules/<id>/test (dry run: what would fire now)\n\\`\\`\\`\n\nAlert conditions and params: experiments \\`srm\\`, \\`winner\\` { minVisitors? }, \\`loser\\` { lift, minVisitors? }, \\`exposures\\` { visitors },\n\\`conversions\\` { conversions }, \\`duration\\` { days }, \\`no_events\\` { hours }; account \\`quota\\` { percent }, \\`usage\\` { every } (each time this\nmonth's billed events cross another multiple); analytics \\`traffic_drop\\` / \\`traffic_spike\\` { property, percent }, \\`goal_silent\\`\n{ property, goal, hours }, \\`event_count\\` { property, event? (any event when absent), count, repeat? }. \\`params.progress\\` { total, fired,\nmonth? } is read-only. Enabled rules need Pro: \\`402 pro_required\\` otherwise (save it with \\`enabled: false\\`).\n\n\\`Authorization: Bearer sk_live_…\\` on each. Status values: draft | running | paused | finished.\n\n## Dashboard-scope endpoints (session, same shapes the dashboard uses)\n\nUnder \\`/v1/projects/<projectId>/…\\` with a user session: \\`experiments\\` (hosted experiments CRUD incl. \\`flow\\` targeting),\n\\`goals\\`, \\`timeline\\`, \\`breakdown\\`, \\`realtime\\`, \\`events\\`, \\`export\\`, \\`notes\\`, \\`domains\\`, \\`properties\\`, \\`links\\`, \\`alerts\\`, \\`billing\\`, \\`ai\\`.\nScripts should prefer the API-key endpoints above; the session ones exist for the UI.\n\n## Drop-in script (no SDK)\n\n\\`<script src=\"https://go.splithub.io/sh.js\" data-key=\"pk_live_…\"></script>\\` in \\`<head>\\`: redirect experiments, page-visit and\nclick goals from the cloud config, \\`window.splithub.track(name, props)\\` for every event (goals included), pageviews\nfor analytics properties (\\`data-property=\"site\"\\`). An app with the SDK does not need it: one install per property,\nor only the first of the two collects pageviews.\n\\`<meta name=\"splithub-experiment\" content=\"<id>\">\\` on a tested page for an instant decision.\n\n## Errors\n\n\\`400\\` validation (message in \\`error\\`), \\`401\\` bad key, \\`403\\` forbidden (\\`insufficient_scope\\` names the missing \\`scope\\`), \\`404\\` unknown experiment/project, \\`409\\` state\n(e.g. \\`config_not_pushed\\`, \\`file_owned\\`), \\`429\\` gate or rate limit. Bodies: \\`{ error, code?, hint? }\\`, auth errors included; \\`hint\\` is the next step.\n`;\n\nexport const SKILL_SPLITHUB_MCP = `---\nname: splithub-mcp\ndescription: Use or set up the SplitHub MCP server (@splithub/mcp) so an agent can create experiments, read verdicts, start/pause/finish experiments and push config through tools instead of shelling out, plus analytics, notes, alerts and short links. Use when the user asks to connect SplitHub to Claude Code, Cursor, Codex or another MCP client.\n---\n\n# SplitHub MCP server\n\n\\`@splithub/mcp\\` is a stdio MCP server that wraps the \\`splithub\\` CLI for the current project folder.\nSame credentials and config file as the CLI; nothing extra to configure.\n\n## Register it\n\nClaude Code (project scope, committed in \\`.mcp.json\\`):\n\n\\`\\`\\`json\n{ \"mcpServers\": { \"splithub\": { \"command\": \"npx\", \"args\": [\"-y\", \"@splithub/mcp\"] } } }\n\\`\\`\\`\n\nor \\`claude mcp add splithub -- npx -y @splithub/mcp\\`. Cursor: the same object in \\`.cursor/mcp.json\\`.\nCodex / other clients: command \\`npx\\`, args \\`-y @splithub/mcp\\`. \\`npx splithub skills --mcp\\` writes both files.\nEnv: \\`SPLITHUB_PROJECT_DIR\\` (defaults to the MCP client's working directory), \\`SPLITHUB_API\\` (staging or self-hosted cloud), \\`SPLITHUB_API_KEY\\` (CI).\n\n## Tools\n\n| tool | does | notes |\n|---|---|---|\n| \\`splithub_status\\` | all experiments with verdict headline | start here |\n| \\`splithub_results\\` | full verdict for one experiment; from / to / filters for a slice, by / timeline / engagement / events for one view (cloud) | report \\`verdict.message\\` verbatim; \\`daysToVerdict\\` = when to check again; a slice's verdict is not the experiment's |\n| \\`splithub_experiment_events\\` | the latest raw exposures and goals of an experiment (cloud) | check the wiring |\n| \\`splithub_review\\` | stored AI reviews (Pro): at start, on verdict changes, on finish, on demand | quote them as the analyst's opinion, the verdict stays the source of truth |\n| \\`splithub_plan\\` | visitors per variant for a baseline and a lift; days at an experiment's traffic | before creating |\n| \\`splithub_experiment_create\\` | adds an experiment to splithub.config.ts | kind value / component / redirect / mvt, id, variants (or factors for mvt), goal, values/to, weights, traffic, maxVisitors, start/end; running by default |\n| \\`splithub_refs\\` | files and lines that use an experiment and its goal | check the wiring, find leftovers |\n| \\`splithub_ship\\` | finish, remove from the config, rewrite the code to the kept variant | \\`dryRun: true\\` first; returns \\`diff\\` and \\`leftovers\\` |\n| \\`splithub_remove\\` | removes an experiment from the config (archived in the cloud) | when the code is already clean |\n| \\`splithub_projects\\` | every folder on this machine connected to a cloud project | |\n| \\`splithub_init\\` | sets up the config, framework files and skills | once per project |\n| \\`splithub_experiment_status\\` | start / pause / finish | applies live in cloud mode; after \\`finished\\`, ask which variant to keep and whether to clean the code (splithub-ship skill) |\n| \\`splithub_push\\` / \\`splithub_pull\\` | sync the config with the cloud | pull adopts dashboard-created experiments |\n| \\`splithub_doctor\\` | checks the installation | run after wiring code |\n| \\`splithub_login\\` | returns a sign-in link; the human approves it in the browser | show the link, then call \\`splithub_whoami\\` |\n| \\`splithub_whoami\\` | connected project and keys | |\n| \\`splithub_analytics\\` | analytics properties; one property's totals, goals, top pages and sources; \\`by\\` a dimension | counts, never verdicts |\n| \\`splithub_analytics_events\\` | the latest raw pageviews and events of a property | check tracking after wiring it |\n| \\`splithub_analytics_funnel\\` / \\`_funnels\\` / \\`_paths\\` / \\`_retention\\` / \\`_realtime\\` | funnels (run, save, list), next pages, cohorts, visitors now (cloud) | counts, never verdicts |\n| \\`splithub_analytics_connect\\` | picks or creates a property and names it on the app's provider | \\`wired.status\\` none / many: add the snippet yourself |\n| \\`splithub_segments\\` | saved report filters (cloud) | |\n| \\`splithub_notes\\` | what happened on a day, per experiment, property or project: list / add / edit / delete (cloud) | add one when you ship |\n| \\`splithub_alerts\\` | alert rules: list / add / enable / disable / delete / test (cloud, fire on Pro) | conditions in the splithub skill |\n| \\`splithub_links\\` | short links: list / stats / create / edit / pause / resume / delete (cloud) | several URLs split by weight |\n| \\`splithub_property_create\\` | adds an analytics property to splithub.config.ts and to the cloud | no push needed |\n| \\`splithub_property_status\\` | pause / resume, archive / restore (cloud) or remove a property | live in cloud mode |\n| \\`splithub_domains\\` | allowed domains per experiment and property; set or clear one list | empty = any origin |\n\nOld names still answer for one release: \\`splithub_create_experiment\\`, \\`splithub_set_status\\`, \\`splithub_create_property\\`,\n\\`splithub_set_property_status\\`. Use the names above.\n\n## Working rules\n\n- Create (running by default) → wire in code → \\`doctor\\` → \\`push\\` (cloud mode) → tell the user it goes live when they\n deploy this code and that \\`set_status paused\\` or Pause in the dashboard holds it.\n- Results: never call a winner from raw rates; quote the verdict. \\`srm_detected\\` = fix the setup first.\n- Running experiments are frozen: no weight / variant / seed edits; create a new one.\n- Errors carry a \\`code\\`. \\`NOT_LOGGED_IN\\`: call \\`splithub_login\\`, show the link to the user, wait for them, then retry.\n- The whole loop (plan → create → implement → doctor → push → results → finish → ship) is in the \\`splithub-loop\\` skill.\n- A \\`finished\\` experiment in \\`splithub_status\\` or \\`splithub_results\\` means the experiment is over but its code is still there: report\n the verdict, ask which variant to keep and whether to remove the experiment from the code, then follow the \\`splithub-ship\\` skill.\n`;\n\nexport { SKILL_SELF_HOSTED } from './skills-self-hosted';\nimport { SKILL_SELF_HOSTED } from './skills-self-hosted';\nexport { SKILL_LOOP, SKILL_SHIP } from './skills-ship';\nimport { SKILL_LOOP, SKILL_SHIP } from './skills-ship';\nexport { SKILL_ANALYTICS } from './skills-analytics';\nimport { SKILL_ANALYTICS } from './skills-analytics';\nexport { SKILL_APPS } from './skills-apps';\nimport { SKILL_APPS } from './skills-apps';\n\nexport const SKILLS: Skill[] = [\n { dir: 'splithub', body: SKILL_SPLITHUB },\n { dir: 'ab-testing', body: SKILL_AB_TESTING },\n { dir: 'splithub-api', body: SKILL_SPLITHUB_API },\n { dir: 'splithub-mcp', body: SKILL_SPLITHUB_MCP },\n { dir: 'splithub-self-hosted', body: SKILL_SELF_HOSTED },\n { dir: 'splithub-ship', body: SKILL_SHIP },\n { dir: 'splithub-loop', body: SKILL_LOOP },\n { dir: 'splithub-analytics', body: SKILL_ANALYTICS },\n { dir: 'splithub-apps', body: SKILL_APPS },\n];\n\nexport const MCP_SERVER_ENTRY = { command: 'npx', args: ['-y', '@splithub/mcp'] };\n","export function configTemplate(project: string, mode: 'self' | 'cloud', key?: string, options: { app?: boolean } = {}): string {\n // An app has no origin of its own: self-hosted events go to the server's full URL, and Expo inlines EXPO_PUBLIC_* variables.\n const endpoint = options.app ? \"process.env.EXPO_PUBLIC_SPLITHUB_ENDPOINT ?? 'https://example.com/api/splithub'\" : \"'/api/splithub'\";\n const envKey = options.app ? 'EXPO_PUBLIC_SPLITHUB_KEY' : 'NEXT_PUBLIC_SPLITHUB_KEY';\n const storage = mode === 'self' ? `{ mode: 'self', endpoint: ${endpoint} }` : `{ mode: 'cloud', key: ${key ? `'${key}'` : `process.env.${envKey} ?? ''`} }`;\n const appNote = options.app\n ? `\n// In an app this file is built into the binary: a new experiment here reaches users with the next\n// store release. Create experiments in the dashboard to start them without a release.`\n : '';\n return `import { defineConfig } from '@splithub/core';\n\n// SplitHub experiments. This file is the source of truth: the SDK, the CLI\n// and the dashboard all read it. Keys: lowercase a-z 0-9 - _. First variant = control.${appNote}\nexport default defineConfig({\n project: '${project}',\n storage: ${storage},\n // Drafts behave like running experiments while you develop (next dev, vite); production ignores them.\n runDraftsInDev: true,\n\n goals: {\n // events you mark as goals: call track('signup') where it happens.\n // An experiment's goal may also be any other event name you track().\n signup: { type: 'event' },\n },\n\n experiments: {\n // run \\`npx splithub create\\` or add entries here:\n //\n // 'hero-title': {\n // kind: 'value',\n // status: 'running',\n // variants: {\n // control: { weight: 50, value: 'Ship faster' },\n // direct: { weight: 50, value: 'Know which version wins' },\n // },\n // goal: 'signup',\n // },\n },\n});\n`;\n}\n\nexport function nextMiddlewareTemplate(configImport: string): string {\n return `import { splithubMiddleware } from '@splithub/next';\nimport splithub from '${configImport}';\n\n// Sets the visitor cookie, forwards it to Server Components and serves\n// redirect experiments with an invisible rewrite.\nexport default splithubMiddleware(splithub);\n\nexport const config = {\n matcher: ['/((?!_next|api|.*\\\\\\\\..*).*)'],\n};\n`;\n}\n\nexport function nextRouteTemplate(configImport: string, store: { imports: string; factory: string } = { imports: \"import { sqliteStore } from '@splithub/adapter-sqlite';\", factory: \"sqliteStore({ file: process.env.SPLITHUB_DB ?? './splithub.db' })\" }): string {\n return `import { createSplitHubHandler } from '@splithub/node';\n${store.imports}\nimport config from '${configImport}';\n\n// Self-hosted ingest + results: events stay in your database. The CLI reads\n// status / results from this route; set SPLITHUB_ADMIN_TOKEN to protect it.\nconst handler = createSplitHubHandler({\n config,\n store: ${store.factory},\n adminToken: process.env.SPLITHUB_ADMIN_TOKEN,\n});\n\nexport const POST = handler;\nexport const GET = handler;\nexport const runtime = 'nodejs';\n`;\n}\n\nexport function componentVariantTemplate(name: string, experiment: string, variant: string): string {\n return `// Variant \"${variant}\" of experiment \"${experiment}\". Edit freely.\nexport function ${name}() {\n return (\n <section>\n <h2>${experiment} · ${variant}</h2>\n </section>\n );\n}\n`;\n}\n\nexport const AGENTS_SECTION = `\n## A/B testing (SplitHub)\n\nThis project uses SplitHub (\\`@splithub/react\\`). Experiments are declared in\n\\`splithub.config.ts\\` and rendered with \\`<Experiment id>\\` / \\`useVariant(id)\\` /\n\\`useValue(id)\\`. Events: \\`useTrack()\\` then \\`track('<event name>')\\`; an experiment's goal is any event name.\n\n- Not connected yet? \\`npx splithub init --mode cloud\\` (or \\`npx splithub login\\`) prints a link: show it to the user, they sign in and approve, the CLI gets the keys. Never ask the user to paste keys.\n- New experiment: \\`npx splithub create --kind value|component|redirect|mvt --id <key> --variants control,<other> --goal <event name> --yes\\`\n then wire it in code (value → \\`useValue\\`, component → \\`<Experiment>\\` with one \\`<Variant>\\` per key, redirect → nothing,\n mvt → \\`--factor name=level:value,…\\` and \\`const { a, b } = useValue(id)\\`).\n- Results: \\`npx splithub results <id> --json\\`; report \\`verdict.message\\` verbatim, never call a winner from raw rates.\n- Lifecycle: \\`npx splithub start|pause|finish <id>\\`. Check setup: \\`npx splithub doctor\\`.\n- A \\`finished\\` experiment still has all its variants in the code: report the verdict, ask which variant to keep and whether to\n remove the experiment from the code, then follow .claude/skills/splithub-ship/SKILL.md. Never delete experiment code unasked.\n- \\`create\\` writes \\`status: 'running'\\`: the experiment goes live when the code is deployed. Always tell the user that, and that\n \\`npx splithub pause <id>\\` or Pause in the dashboard holds it. Never change \\`seed\\` of a running experiment.\n- Analytics: set it up with \\`npx splithub analytics connect --json\\` (names the property on the provider), read it with\n \\`npx splithub analytics <property> --json\\`; also \\`funnel\\`, \\`paths\\`, \\`retention\\`, \\`realtime\\`, \\`export\\` (SplitHub Cloud).\n Details: .claude/skills/splithub-analytics/SKILL.md\n- Notes, alerts, links, domains (SplitHub Cloud): \\`npx splithub notes add \"<what shipped>\"\\` when you ship, \\`npx splithub alerts\\` (rules, e.g.\n \\`alerts add usage --every 1000\\`), \\`npx splithub links\\` (short links), \\`npx splithub domains\\`. Humans: \\`npx splithub\\` opens the menu.\n- Apps (React Native / Expo / iOS / Android): new experiments start in the dashboard (the config is built into the binary);\n screens are page events. Details: .claude/skills/splithub-apps/SKILL.md\n- Config ships to the browser: no secrets in it. Full rules: .claude/skills/splithub/SKILL.md\n`;\n\nexport { SKILL_SPLITHUB as SKILL_MD } from './skills';\nimport { SKILL_SPLITHUB } from './skills';\n\nexport const CURSOR_RULE = `---\ndescription: SplitHub A/B testing conventions\nglobs: [\"splithub.config.ts\", \"splithub/**\", \"**/*.tsx\"]\nalwaysApply: false\n---\n${SKILL_SPLITHUB.replace(/^---[\\s\\S]*?---\\n/, '')}`;\n"],"mappings":";;;AAEO,IAAM,oBAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA8BvB,IAAM,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA,EAKzB,eAAe,QAAQ,qBAAqB,EAAE,CAAC;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/menu-analytics.ts"],"sourcesContent":["// The menu's analytics steps: set up (connect), properties (list, create, report, raw events, pause/resume), the\n// cloud reports (realtime, funnel, paths, retention) and allowed domains. Each step calls the same command function as `splithub analytics …` /\n// `splithub domains …`, so the output is the one scripts see without --json.\nimport * as p from '@clack/prompts';\nimport { newPropertyId } from '@splithub/core';\nimport { request, resolveTarget } from '../api';\nimport { loadConfig } from '../config-file';\nimport { detectProject } from '../project';\nimport { analytics } from './analytics';\nimport { domains } from './domains';\nimport type { Flags } from './init';\n\nexport type Mode = 'cloud' | 'self';\ntype AnalyticsAction = 'connect' | 'list' | 'report' | 'realtime' | 'funnel' | 'paths' | 'retention' | 'events' | 'create' | 'toggle' | 'back';\nexport interface PropertyChoice {\n value: string;\n label: string;\n hint: string;\n status: string;\n}\n\nexport const REPORT_SPANS = [7, 30, 90] as const;\nexport const REPORT_BREAKDOWNS = ['page', 'source', 'channel', 'country', 'device', 'event', 'goal'] as const;\nexport const FUNNEL_WITHIN = [\n { value: 'visit', label: 'In one visit' },\n { value: '7d', label: 'Within 7 days' },\n { value: '30d', label: 'Within 30 days' },\n] as const;\n\n/** Why a typed funnel is refused, or undefined: 2 to 8 steps, each page:, event: or goal:. */\nexport function funnelStepsError(input: string): string | undefined {\n const steps = input.split(',').map((s) => s.trim()).filter(Boolean);\n if (steps.length < 2) return 'Two steps at least, separated by commas';\n if (steps.length > 8) return 'Eight steps at most';\n const bad = steps.find((s) => !/^(page:\\/\\S*|event:.+|goal:.+)$/.test(s));\n return bad ? `\"${bad}\": start with page:/, event: or goal:` : undefined;\n}\nexport const CLOUD_ONLY = 'Allowed domains come with SplitHub Cloud: a self-hosted endpoint accepts events from wherever you mount it.';\n\n/** Options of the Analytics submenu. Realtime, funnels, paths and retention come with SplitHub Cloud; the rest reads raw counts when self-hosted. */\nexport function analyticsOptions(mode: Mode = 'cloud'): Array<{ value: AnalyticsAction; label: string; hint?: string }> {\n const cloud: Array<{ value: AnalyticsAction; label: string; hint?: string }> = [\n { value: 'realtime', label: \"Who's here now\", hint: 'last 5 minutes' },\n { value: 'funnel', label: 'Build a funnel', hint: 'pages, events, goals in order' },\n { value: 'paths', label: 'Where visitors go next' },\n { value: 'retention', label: 'Who comes back', hint: 'weekly cohorts' },\n ];\n return [\n { value: 'connect', label: 'Set up analytics in this app', hint: 'pick a property, name it in the code, send events' },\n { value: 'list', label: 'See all properties', hint: 'last 30 days' },\n { value: 'report', label: 'Open a report', hint: 'visitors, pages, sources, goals' },\n ...(mode === 'cloud' ? cloud : []),\n { value: 'events', label: 'Latest raw events' },\n { value: 'create', label: 'Create a property' },\n { value: 'toggle', label: 'Pause or resume a property' },\n { value: 'back', label: 'Back' },\n ];\n}\n\n/** Select options from `GET /properties`: the cloud answers `{ key, name, status, last30 }`, self-hosted `{ property, name, status, counts }`. */\nexport function propertyChoices(data: { properties: Array<Record<string, unknown>> }): PropertyChoice[] {\n return data.properties.flatMap((row) => {\n const key = typeof row.key === 'string' ? row.key : typeof row.property === 'string' ? row.property : null;\n if (!key) return [];\n const name = typeof row.name === 'string' && row.name ? row.name : null;\n const status = typeof row.status === 'string' ? row.status : 'running';\n const sums = (row.last30 ?? row.counts) as { visitors?: unknown } | null | undefined;\n const visitors = typeof sums?.visitors === 'number' ? sums.visitors : null;\n return [{ value: key, label: name ? `${name} (${key})` : key, hint: visitors === null ? status : `${status} · ${visitors.toLocaleString('en-US')} visitors`, status }];\n });\n}\n\n/** Where to name the property so its events arrive: the React provider prop and the sh.js tag. */\nexport function propertySnippets(key: string, publicKey?: string | null): { provider: string; script: string } {\n return {\n provider: `<SplitHubProvider config={config} property=\"${key}\">`,\n script: `<script src=\"https://go.splithub.io/sh.js\" data-key=\"${publicKey ?? 'pk_…'}\" data-property=\"${key}\" async></script>`,\n };\n}\n\n/** Hosts typed in one line: spaces or commas, schemes and paths dropped (`https://a.com/x` → `a.com`). */\nexport function parseHosts(input: string): string[] {\n const hosts = input\n .split(/[\\s,]+/)\n .map((h) => h.trim().toLowerCase().replace(/^[a-z]+:\\/\\//, '').replace(/[/?#].*$/, ''))\n .filter(Boolean);\n return [...new Set(hosts)];\n}\n\nasync function choices(flags: Flags): Promise<PropertyChoice[]> {\n const project = detectProject();\n try {\n return propertyChoices(await request<{ properties: Array<Record<string, unknown>> }>(resolveTarget(flags, project), '/properties'));\n } catch {\n // The dev server is down or the folder is not connected: the config file still knows the ids.\n if (!project.configFile) return [];\n const config = await loadConfig(project.configFile);\n return (config.properties ?? []).map((prop) => ({ value: prop.key, label: prop.name ? `${prop.name} (${prop.key})` : prop.key, hint: prop.status, status: prop.status }));\n }\n}\n\nexport async function pickProperty(flags: Flags, message: string): Promise<PropertyChoice | null> {\n const list = await choices(flags);\n if (list.length === 0) {\n p.log.warn('No analytics properties yet. Create one first.');\n return null;\n }\n const picked = await p.select({ message, options: list.map(({ value, label, hint }) => ({ value, label, hint })) });\n if (p.isCancel(picked)) return null;\n return list.find((x) => x.value === picked) ?? null;\n}\n\nasync function createStep(flags: Flags): Promise<void> {\n const name = await p.text({ message: 'Name of the property', placeholder: 'Marketing site' });\n if (p.isCancel(name)) return;\n const key = newPropertyId();\n await analytics(['create', key], { ...flags, name: name.trim() || undefined });\n const s = propertySnippets(key);\n p.note(`React / Next.js:\\n ${s.provider}\\n\\nAny site, with sh.js:\\n ${s.script}`, `Send events to ${key}`);\n}\n\nasync function reportStep(flags: Flags, mode: Mode): Promise<void> {\n const prop = await pickProperty(flags, 'Which property?');\n if (!prop) return;\n let days: number = 30;\n for (;;) {\n const span = await p.select({ message: 'Which period?', initialValue: days, options: REPORT_SPANS.map((d) => ({ value: d, label: `Last ${d} days` })) });\n if (p.isCancel(span)) return;\n days = span;\n await analytics([prop.value], { ...flags, days: String(days) });\n // Self-hosted answers raw counts only; breakdowns are computed in the cloud.\n if (mode !== 'cloud') return;\n for (;;) {\n console.log();\n const by = await p.select<string>({\n message: 'Break it down?',\n options: [...REPORT_BREAKDOWNS.map((b) => ({ value: b, label: `By ${b}` })), ...(mode === 'cloud' ? [{ value: 'compare', label: 'Compare with the period before' }] : []), { value: 'span', label: 'Another period' }, { value: 'done', label: 'Done' }],\n });\n if (p.isCancel(by) || by === 'done') return;\n if (by === 'span') break;\n if (by === 'compare') await analytics([prop.value], { ...flags, days: String(days), compare: 'previous' });\n else await analytics([prop.value], { ...flags, days: String(days), by });\n }\n }\n}\n\nasync function funnelStep(flags: Flags): Promise<void> {\n const prop = await pickProperty(flags, 'Funnel of which property?');\n if (!prop) return;\n const steps = await p.text({ message: 'Steps, in order', placeholder: 'page:/, page:/pricing, event:Signup, goal:paid', validate: funnelStepsError });\n if (p.isCancel(steps)) return;\n const within = await p.select<string>({ message: 'Counted when they happen', options: FUNNEL_WITHIN.map((w) => ({ value: w.value, label: w.label })) });\n if (p.isCancel(within)) return;\n await analytics(['funnel', prop.value], { ...flags, steps, within });\n}\n\nasync function pathsStep(flags: Flags): Promise<void> {\n const prop = await pickProperty(flags, 'Paths of which property?');\n if (!prop) return;\n const page = await p.text({ message: 'Which page?', placeholder: '/pricing', validate: (v) => (v.trim().startsWith('/') ? undefined : 'A path like /pricing') });\n if (p.isCancel(page)) return;\n const direction = await p.select<'next' | 'prev'>({ message: 'Show', options: [{ value: 'next', label: 'Where visitors go next' }, { value: 'prev', label: 'Where they came from' }] });\n if (p.isCancel(direction)) return;\n await analytics(['paths', prop.value], { ...flags, page: page.trim(), prev: direction === 'prev' });\n}\n\nasync function retentionStep(flags: Flags): Promise<void> {\n const prop = await pickProperty(flags, 'Retention of which property?');\n if (!prop) return;\n const period = await p.select<'week' | 'day'>({ message: 'Cohorts by', options: [{ value: 'week', label: 'Week', hint: 'last 12 weeks' }, { value: 'day', label: 'Day', hint: 'last 30 days' }] });\n if (p.isCancel(period)) return;\n await analytics(['retention', prop.value], { ...flags, period, days: period === 'week' ? '84' : '30' });\n}\n\nexport async function analyticsMenu(flags: Flags, mode: Mode): Promise<void> {\n for (;;) {\n const action = await p.select<AnalyticsAction>({ message: 'Analytics', options: analyticsOptions(mode) });\n if (p.isCancel(action) || action === 'back') return;\n switch (action) {\n case 'connect':\n await analytics(['connect'], flags);\n break;\n case 'list':\n await analytics([], flags);\n break;\n case 'report':\n await reportStep(flags, mode);\n break;\n case 'realtime': {\n const prop = await pickProperty(flags, 'Which property?');\n if (prop) await analytics(['realtime', prop.value], flags);\n break;\n }\n case 'funnel':\n await funnelStep(flags);\n break;\n case 'paths':\n await pathsStep(flags);\n break;\n case 'retention':\n await retentionStep(flags);\n break;\n case 'events': {\n const prop = await pickProperty(flags, 'Events of which property?');\n if (prop) await analytics(['events', prop.value], flags);\n break;\n }\n case 'create':\n await createStep(flags);\n break;\n case 'toggle': {\n const prop = await pickProperty(flags, 'Which property?');\n if (!prop) break;\n const verb = prop.status === 'paused' ? 'resume' : 'pause';\n const ok = await p.confirm({ message: `${verb === 'pause' ? 'Pause' : 'Resume'} ${prop.label}?` });\n if (ok === true) await analytics([verb, prop.value], flags);\n break;\n }\n }\n console.log();\n }\n}\n\n/** Allowed domains: the list, then set or clear one experiment's or property's origins. */\nexport async function domainsMenu(flags: Flags, mode: Mode, pickExperiment: (flags: Flags, message: string) => Promise<string | null>): Promise<void> {\n if (mode !== 'cloud') {\n p.log.info(CLOUD_ONLY);\n return;\n }\n await domains([], flags);\n console.log();\n const action = await p.select<'set' | 'clear' | 'back'>({\n message: 'Change one?',\n options: [\n { value: 'set', label: 'Limit to some domains', hint: 'subdomains are included' },\n { value: 'clear', label: 'Accept any origin again' },\n { value: 'back', label: 'Back' },\n ],\n });\n if (p.isCancel(action) || action === 'back') return;\n const kind = await p.select<'experiment' | 'property'>({ message: 'For what?', options: [{ value: 'experiment', label: 'An experiment' }, { value: 'property', label: 'An analytics property' }] });\n if (p.isCancel(kind)) return;\n const key = kind === 'experiment' ? await pickExperiment(flags, 'Which experiment?') : (await pickProperty(flags, 'Which property?'))?.value;\n if (!key) return;\n if (action === 'clear') return domains(['clear', kind, key], flags);\n const typed = await p.text({ message: 'Domains, separated by spaces or commas', placeholder: 'example.com app.example.com', validate: (v) => (parseHosts(v).length === 0 ? 'Type at least one domain' : undefined) });\n if (p.isCancel(typed)) return;\n await domains(['set', kind, key, ...parseHosts(typed)], flags);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAGA,YAAY,OAAO;AACnB,SAAS,qBAAqB;AAiBvB,IAAM,eAAe,CAAC,GAAG,IAAI,EAAE;AAC/B,IAAM,oBAAoB,CAAC,QAAQ,UAAU,WAAW,WAAW,UAAU,SAAS,MAAM;AAC5F,IAAM,gBAAgB;AAAA,EAC3B,EAAE,OAAO,SAAS,OAAO,eAAe;AAAA,EACxC,EAAE,OAAO,MAAM,OAAO,gBAAgB;AAAA,EACtC,EAAE,OAAO,OAAO,OAAO,iBAAiB;AAC1C;AAGO,SAAS,iBAAiB,OAAmC;AAClE,QAAM,QAAQ,MAAM,MAAM,GAAG,EAAE,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,OAAO;AAClE,MAAI,MAAM,SAAS,EAAG,QAAO;AAC7B,MAAI,MAAM,SAAS,EAAG,QAAO;AAC7B,QAAM,MAAM,MAAM,KAAK,CAAC,MAAM,CAAC,kCAAkC,KAAK,CAAC,CAAC;AACxE,SAAO,MAAM,IAAI,GAAG,0CAA0C;AAChE;AACO,IAAM,aAAa;AAGnB,SAAS,iBAAiB,OAAa,SAA0E;AACtH,QAAM,QAAyE;AAAA,IAC7E,EAAE,OAAO,YAAY,OAAO,kBAAkB,MAAM,iBAAiB;AAAA,IACrE,EAAE,OAAO,UAAU,OAA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AAO,QAAQ,CAAC,SAAS,MAAM,GAAG,GAAG,KAAK;AAClE,QAAM,QAAQ,MAAQ,OAAK,EAAE,SAAS,0CAA0C,aAAa,+BAA+B,UAAU,CAAC,MAAO,WAAW,CAAC,EAAE,WAAW,IAAI,6BAA6B,OAAW,CAAC;AACpN,MAAM,WAAS,KAAK,EAAG;AACvB,QAAM,QAAQ,CAAC,OAAO,MAAM,KAAK,GAAG,WAAW,KAAK,CAAC,GAAG,KAAK;AAC/D;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/dev.ts"],"sourcesContent":["// splithub dev — test experiments locally with full visibility.\n//\n// splithub dev opens the app (localhost:3000 for Next.js, 5173 for Vite) with ?sh_debug=1\n// splithub dev --url http://… a different page\n// splithub dev --hold redirect experiments log the target instead of navigating\n// splithub dev --no-open only print the link and watch\n//\n// With ?sh_debug the SDK and the drop-in script log every decision (which\n// variant and why), every exposure and goal with its payload, and the remote\n// overrides they applied, in the browser console and in a floating panel that\n// can force a variant, start a new visitor or hold redirects. Meanwhile this\n// command polls `status` and prints new visitors / conversions as they land.\n\nimport { spawn } from 'node:child_process';\nimport { fetchStatus, resolveTarget } from '../api';\nimport { detectProject } from '../project';\nimport { c } from '../ui';\n\nfunction openBrowser(url: string): void {\n const [cmd, args] = process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]];\n try {\n spawn(cmd, args, { stdio: 'ignore', detached: true }).unref();\n } catch {\n // no browser available: the link is printed anyway\n }\n}\n\nexport async function dev(flags: Record<string, unknown>): Promise<void> {\n const project = detectProject();\n const port = project?.framework === 'next' ? 3000 : 5173;\n const page = (typeof flags.url === 'string' && flags.url) || `http://localhost:${port}/`;\n const u = new URL(page);\n u.searchParams.set('sh_debug', flags.hold ? 'hold' : '1');\n const link = u.toString();\n\n console.log(`${c.bold('SplitHub dev mode')}\\n`);\n console.log(` ${c.cyan(link)}\\n`);\n console.log(c.dim(' In the browser: the console shows every assignment (variant + reason), exposure and goal; the panel'));\n console.log(c.dim(' in the corner forces variants, starts a new visitor and can hold redirects. Add ?sh_debug=0 to stop.\\n'));\n if (!flags['no-open']) openBrowser(link);\n\n const target = resolveTarget(flags, project);\n console.log(c.dim(` Watching ${target.url} every 5 s. Ctrl+C to stop.\\n`));\n const seen = new Map<string, { visitors: number; headline: string | null }>();\n let first = true;\n const poll = async () => {\n let data: Awaited<ReturnType<typeof fetchStatus>>;\n try {\n data = await fetchStatus(target);\n } catch (e) {\n if (first) console.log(c.yellow(` results endpoint not reachable yet (${e instanceof Error ? e.message : String(e)}); is the dev server running?`));\n first = false;\n return;\n }\n const now = new Date().toLocaleTimeString();\n for (const e of data.experiments) {\n const prev = seen.get(e.experiment);\n if (!prev) console.log(` ${c.dim(now)} ${c.bold(e.experiment)} ${c.dim(e.status)} · ${e.visitors} visitors${e.headline ? ` · ${e.headline}` : ''}`);\n else if (prev.visitors !== e.visitors || prev.headline !== (e.headline ?? null)) console.log(` ${c.dim(now)} ${c.bold(e.experiment)} ${c.green(`+${e.visitors - prev.visitors}`)} → ${e.visitors} visitors${e.headline ? ` · ${e.headline}` : ''}`);\n seen.set(e.experiment, { visitors: e.visitors, headline: e.headline ?? null });\n }\n first = false;\n };\n await poll();\n await new Promise<void>((resolve) => {\n const t = setInterval(() => void poll(), 5000);\n process.on('SIGINT', () => {\n clearInterval(t);\n resolve();\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,SAAS,aAAa;AAKtB,SAAS,YAAY,KAAmB;AACtC,QAAM,CAAC,KAAK,IAAI,IAAI,QAAQ,aAAa,UAAU,CAAC,OAAO,CAAC,MAAM,SAAS,IAAI,GAAG,CAAC,IAAI,QAAQ,aAAa,WAAW,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC;AAC3J,MAAI;AACF,UAAM,KAAK,MAAM,EAAE,OAAO,UAAU,UAAU,KA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