@splithub/core 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vite.js ADDED
@@ -0,0 +1,106 @@
1
+ import {
2
+ CLOUD_ENDPOINT,
3
+ applyRemoteOverrides,
4
+ fetchRemoteOverrides,
5
+ isSplitHubConfig,
6
+ resolveOverridesUrl
7
+ } from "./chunk-NWFRVOJZ.js";
8
+
9
+ // src/vite.ts
10
+ var VIRTUAL = "virtual:splithub-dev";
11
+ var RESOLVED = "\0" + VIRTUAL;
12
+ var CANDIDATES = ["splithub.config.ts", "splithub.config.js", "splithub.config.mjs"];
13
+ var tag = (s) => `\x1B[36m[splithub]\x1B[39m ${s}`;
14
+ var dim = (s) => `\x1B[2m${s}\x1B[22m`;
15
+ var CLIENT = `if (import.meta.hot) {
16
+ window.__splithubTerminal = true;
17
+ window.addEventListener('splithub:dev', (e) => import.meta.hot.send('splithub:note', e.detail));
18
+ }`;
19
+ function describeExperiment(config, e, live) {
20
+ const changed = live && live.status !== e.status ? live.status : null;
21
+ const status = changed ?? e.status;
22
+ const second = e.variants[1]?.key ?? "variant";
23
+ if (status === "running") return `${e.key}: running${changed ? " (started from the dashboard)" : ""}`;
24
+ if (status === "draft") {
25
+ return config.runDraftsInDev ? `${e.key}: draft, shown here as if running; visitors see it after ${dim(`npx splithub start ${e.key}`)}` : `${e.key}: draft, everyone sees the control, here too; add runDraftsInDev: true or open ${dim(`?sh_force=${e.key}:${second}`)}`;
26
+ }
27
+ return `${e.key}: ${status}${changed ? " from the dashboard" : ""}, everyone sees the control`;
28
+ }
29
+ async function liveConfig(config) {
30
+ if (config.storage.mode !== "cloud" || !config.storage.key) return null;
31
+ const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);
32
+ const timeout = new Promise((resolve) => setTimeout(() => resolve(null), 3e3));
33
+ const overrides = await Promise.race([fetchRemoteOverrides(url), timeout]);
34
+ return overrides ? applyRemoteOverrides(config, overrides) : null;
35
+ }
36
+ function splithub(options = {}) {
37
+ const seen = /* @__PURE__ */ new Set();
38
+ let configPath = null;
39
+ async function load(server) {
40
+ for (const file of options.config ? [options.config] : CANDIDATES) {
41
+ const path = file.replace(/^\.?\//, "");
42
+ try {
43
+ const mod = await server.ssrLoadModule(`/${path}`);
44
+ if (isSplitHubConfig(mod.default)) {
45
+ configPath = path;
46
+ return mod.default;
47
+ }
48
+ } catch {
49
+ }
50
+ }
51
+ return null;
52
+ }
53
+ async function summary(server) {
54
+ if (options.summary === false) return;
55
+ const log = server.config.logger;
56
+ const config = await load(server);
57
+ if (!config) {
58
+ log.info(tag("no splithub.config.ts found; run npx splithub init"), { timestamp: true });
59
+ return;
60
+ }
61
+ const live = await liveConfig(config).catch(() => null);
62
+ const mode = config.storage.mode === "cloud" ? config.storage.key ? "cloud" : "cloud, no public key yet" : "self-hosted";
63
+ const count = `${config.experiments.length} experiment${config.experiments.length === 1 ? "" : "s"}`;
64
+ log.info(tag(`${config.project} \xB7 ${mode} \xB7 ${count}${config.runDraftsInDev ? " \xB7 drafts run in development" : ""}`), { timestamp: true });
65
+ for (const e of config.experiments) log.info(tag(` ${describeExperiment(config, e, live?.experiments.find((x) => x.key === e.key))}`));
66
+ if (config.storage.mode === "cloud" && !(live ?? config).experiments.some((e) => e.status === "running")) {
67
+ log.info(tag(dim(" nothing is running yet, so no events are sent to the cloud")));
68
+ }
69
+ }
70
+ return {
71
+ name: "splithub",
72
+ apply: "serve",
73
+ configureServer(server) {
74
+ if (options.browserNotes !== false) {
75
+ server.ws.on("splithub:note", (data) => {
76
+ if (typeof data !== "string" || seen.has(data)) return;
77
+ seen.add(data);
78
+ server.config.logger.info(tag(data), { timestamp: true });
79
+ });
80
+ }
81
+ const start = () => void summary(server);
82
+ if (server.httpServer) server.httpServer.once("listening", start);
83
+ else start();
84
+ },
85
+ handleHotUpdate({ file, server }) {
86
+ if (!configPath || !file.replace(/\\/g, "/").endsWith(`/${configPath}`)) return;
87
+ seen.clear();
88
+ void summary(server);
89
+ },
90
+ resolveId(id) {
91
+ return id === VIRTUAL ? RESOLVED : void 0;
92
+ },
93
+ load(id) {
94
+ if (id !== RESOLVED) return void 0;
95
+ return options.browserNotes === false ? "" : CLIENT;
96
+ },
97
+ transformIndexHtml() {
98
+ return [{ tag: "script", attrs: { type: "module", src: `/@id/${VIRTUAL}` }, injectTo: "head-prepend" }];
99
+ }
100
+ };
101
+ }
102
+ export {
103
+ describeExperiment,
104
+ splithub
105
+ };
106
+ //# sourceMappingURL=vite.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/vite.ts"],"sourcesContent":["// Vite plugin: SplitHub notes in the terminal that runs `vite` / `npm run dev`.\n//\n// // vite.config.ts\n// import { splithub } from '@splithub/core/vite';\n// export default defineConfig({ plugins: [react(), splithub()] });\n//\n// On start and on every save of splithub.config.ts it prints what each\n// experiment does in development (draft hidden or shown, running, paused,\n// started from the dashboard). The SDK's development notes from the browser\n// (\"this visitor got control\", \"events held back\") are forwarded here too,\n// once per message until the config changes. Dev server only; builds are untouched.\n//\n// Vite's types are described structurally so @splithub/core keeps zero dependencies.\n\nimport { CLOUD_ENDPOINT } from './client';\nimport { isSplitHubConfig } from './config';\nimport { applyRemoteOverrides, fetchRemoteOverrides, resolveOverridesUrl } from './remote';\nimport type { Experiment, SplitHubConfig } from './types';\n\ninterface Logger {\n info(message: string, options?: { timestamp?: boolean }): void;\n}\ninterface DevServer {\n config: { root: string; logger: Logger };\n httpServer: { once(event: 'listening', listener: () => void): unknown } | null;\n ssrLoadModule(url: string): Promise<Record<string, unknown>>;\n ws: { on(event: string, listener: (data: unknown) => void): void };\n}\ninterface HotContext {\n file: string;\n server: DevServer;\n}\nexport interface SplitHubVitePlugin {\n name: string;\n apply: 'serve';\n configureServer(server: DevServer): void;\n handleHotUpdate(ctx: HotContext): void;\n resolveId(id: string): string | undefined;\n load(id: string): string | undefined;\n transformIndexHtml(): Array<{ tag: string; attrs: Record<string, string>; injectTo: 'head-prepend' }>;\n}\n\nexport interface SplitHubViteOptions {\n /** Path of the config, relative to the Vite root. Default: splithub.config.ts, .js or .mjs. */\n config?: string;\n /** Print the experiment summary on start and on config changes. Default true. */\n summary?: boolean;\n /** Forward the SDK's development notes from the browser. Default true. */\n browserNotes?: boolean;\n}\n\nconst VIRTUAL = 'virtual:splithub-dev';\nconst RESOLVED = '\\0' + VIRTUAL;\nconst CANDIDATES = ['splithub.config.ts', 'splithub.config.js', 'splithub.config.mjs'];\nconst tag = (s: string) => `\\x1b[36m[splithub]\\x1b[39m ${s}`;\nconst dim = (s: string) => `\\x1b[2m${s}\\x1b[22m`;\n\n// The browser side: the SDK announces notes as a window event; this sends them to the\n// dev server and tells the SDK that the terminal has them, so the browser console stays quiet.\nconst CLIENT = `if (import.meta.hot) {\n window.__splithubTerminal = true;\n window.addEventListener('splithub:dev', (e) => import.meta.hot.send('splithub:note', e.detail));\n}`;\n\n/** One line per experiment, in the words a developer needs. `live` is the experiment after dashboard changes. */\nexport function describeExperiment(config: SplitHubConfig, e: Experiment, live?: Experiment): string {\n const changed = live && live.status !== e.status ? live.status : null;\n const status = changed ?? e.status;\n const second = e.variants[1]?.key ?? 'variant';\n if (status === 'running') return `${e.key}: running${changed ? ' (started from the dashboard)' : ''}`;\n if (status === 'draft') {\n return config.runDraftsInDev\n ? `${e.key}: draft, shown here as if running; visitors see it after ${dim(`npx splithub start ${e.key}`)}`\n : `${e.key}: draft, everyone sees the control, here too; add runDraftsInDev: true or open ${dim(`?sh_force=${e.key}:${second}`)}`;\n }\n return `${e.key}: ${status}${changed ? ' from the dashboard' : ''}, everyone sees the control`;\n}\n\nasync function liveConfig(config: SplitHubConfig): Promise<SplitHubConfig | null> {\n if (config.storage.mode !== 'cloud' || !config.storage.key) return null;\n const url = resolveOverridesUrl(config.storage.endpoint ?? CLOUD_ENDPOINT, config.storage.key);\n const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), 3000));\n const overrides = await Promise.race([fetchRemoteOverrides(url), timeout]);\n return overrides ? applyRemoteOverrides(config, overrides) : null;\n}\n\nexport function splithub(options: SplitHubViteOptions = {}): SplitHubVitePlugin {\n const seen = new Set<string>();\n let configPath: string | null = null;\n\n async function load(server: DevServer): Promise<SplitHubConfig | null> {\n for (const file of options.config ? [options.config] : CANDIDATES) {\n const path = file.replace(/^\\.?\\//, '');\n try {\n const mod = await server.ssrLoadModule(`/${path}`);\n if (isSplitHubConfig(mod.default)) {\n configPath = path;\n return mod.default;\n }\n } catch {\n // not this file, or it does not compile right now: try the next one\n }\n }\n return null;\n }\n\n async function summary(server: DevServer): Promise<void> {\n if (options.summary === false) return;\n const log = server.config.logger;\n const config = await load(server);\n if (!config) {\n log.info(tag('no splithub.config.ts found; run npx splithub init'), { timestamp: true });\n return;\n }\n const live = await liveConfig(config).catch(() => null);\n const mode = config.storage.mode === 'cloud' ? (config.storage.key ? 'cloud' : 'cloud, no public key yet') : 'self-hosted';\n const count = `${config.experiments.length} experiment${config.experiments.length === 1 ? '' : 's'}`;\n log.info(tag(`${config.project} · ${mode} · ${count}${config.runDraftsInDev ? ' · drafts run in development' : ''}`), { timestamp: true });\n for (const e of config.experiments) log.info(tag(` ${describeExperiment(config, e, live?.experiments.find((x) => x.key === e.key))}`));\n if (config.storage.mode === 'cloud' && !(live ?? config).experiments.some((e) => e.status === 'running')) {\n log.info(tag(dim(' nothing is running yet, so no events are sent to the cloud')));\n }\n }\n\n return {\n name: 'splithub',\n apply: 'serve',\n configureServer(server) {\n if (options.browserNotes !== false) {\n server.ws.on('splithub:note', (data) => {\n if (typeof data !== 'string' || seen.has(data)) return;\n seen.add(data);\n server.config.logger.info(tag(data), { timestamp: true });\n });\n }\n const start = () => void summary(server);\n if (server.httpServer) server.httpServer.once('listening', start);\n else start();\n },\n handleHotUpdate({ file, server }) {\n if (!configPath || !file.replace(/\\\\/g, '/').endsWith(`/${configPath}`)) return;\n seen.clear();\n void summary(server);\n },\n resolveId(id) {\n return id === VIRTUAL ? RESOLVED : undefined;\n },\n load(id) {\n if (id !== RESOLVED) return undefined;\n return options.browserNotes === false ? '' : CLIENT;\n },\n transformIndexHtml() {\n return [{ tag: 'script', attrs: { type: 'module', src: `/@id/${VIRTUAL}` }, injectTo: 'head-prepend' }];\n },\n };\n}\n"],"mappings":";;;;;;;;;AAmDA,IAAM,UAAU;AAChB,IAAM,WAAW,OAAO;AACxB,IAAM,aAAa,CAAC,sBAAsB,sBAAsB,qBAAqB;AACrF,IAAM,MAAM,CAAC,MAAc,8BAA8B,CAAC;AAC1D,IAAM,MAAM,CAAC,MAAc,UAAU,CAAC;AAItC,IAAM,SAAS;AAAA;AAAA;AAAA;AAMR,SAAS,mBAAmB,QAAwB,GAAe,MAA2B;AACnG,QAAM,UAAU,QAAQ,KAAK,WAAW,EAAE,SAAS,KAAK,SAAS;AACjE,QAAM,SAAS,WAAW,EAAE;AAC5B,QAAM,SAAS,EAAE,SAAS,CAAC,GAAG,OAAO;AACrC,MAAI,WAAW,UAAW,QAAO,GAAG,EAAE,GAAG,YAAY,UAAU,kCAAkC,EAAE;AACnG,MAAI,WAAW,SAAS;AACtB,WAAO,OAAO,iBACV,GAAG,EAAE,GAAG,4DAA4D,IAAI,sBAAsB,EAAE,GAAG,EAAE,CAAC,KACtG,GAAG,EAAE,GAAG,kFAAkF,IAAI,aAAa,EAAE,GAAG,IAAI,MAAM,EAAE,CAAC;AAAA,EACnI;AACA,SAAO,GAAG,EAAE,GAAG,KAAK,MAAM,GAAG,UAAU,wBAAwB,EAAE;AACnE;AAEA,eAAe,WAAW,QAAwD;AAChF,MAAI,OAAO,QAAQ,SAAS,WAAW,CAAC,OAAO,QAAQ,IAAK,QAAO;AACnE,QAAM,MAAM,oBAAoB,OAAO,QAAQ,YAAY,gBAAgB,OAAO,QAAQ,GAAG;AAC7F,QAAM,UAAU,IAAI,QAAc,CAAC,YAAY,WAAW,MAAM,QAAQ,IAAI,GAAG,GAAI,CAAC;AACpF,QAAM,YAAY,M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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@splithub/core",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "The heart of SplitHub: the config, who sees which variant, and the event queue. No framework, no dependencies.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -12,6 +12,11 @@
12
12
  "types": "./dist/index.d.ts",
13
13
  "import": "./dist/index.js",
14
14
  "require": "./dist/index.cjs"
15
+ },
16
+ "./vite": {
17
+ "types": "./dist/vite.d.ts",
18
+ "import": "./dist/vite.js",
19
+ "require": "./dist/vite.cjs"
15
20
  }
16
21
  },
17
22
  "files": [