diff --git a/packages/vue/README.md b/packages/vue/README.md new file mode 100644 index 00000000..f1438869 --- /dev/null +++ b/packages/vue/README.md @@ -0,0 +1,35 @@ +# Abby for Vue 3 + +Install `@tryabby/vue` in a Vue 3.5 application. Create the plugin from your project configuration and install it before mounting the app. + +```ts +import { createApp } from "vue"; +import { createAbby } from "@tryabby/vue"; +import App from "./App.vue"; + +export const abby = createAbby({ + projectId: "YOUR_PROJECT_ID", currentEnvironment: "production", + environments: ["production"], flags: ["newCheckout"], + remoteConfig: { checkoutLabel: "String" }, + tests: { checkout: { variants: ["control", "short"] } }, +}); +createApp(App).use(abby).mount("#app"); +``` + +Inside a component's setup, the three composables return computed values that update when the core loads project data. + +```vue + + +``` + +Each installation gets its own core instance. For SSR or a preloaded application, pass the same project response into `app.use(abby, initialData)` on the server and client. The A/B test renders its first configured variant for hydration, then selects the visitor's assigned variant on mount. Call `onAct()` on conversion to record the raw variant name even when the display value uses a lookup. diff --git a/packages/vue/package.json b/packages/vue/package.json new file mode 100644 index 00000000..1136791d --- /dev/null +++ b/packages/vue/package.json @@ -0,0 +1,31 @@ +{ + "name": "@tryabby/vue", + "version": "0.1.0", + "description": "Typed Vue 3 composables for Abby", + "license": "ISC", + "main": "./dist/index.js", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + } + }, + "files": ["dist"], + "scripts": { + "build": "tsup src/index.ts --format esm,cjs --dts --clean", + "test": "tsc --noEmit && vitest run" + }, + "dependencies": { "@tryabby/core": "workspace:*", "js-cookie": "^3.0.1" }, + "peerDependencies": { "vue": "^3.5.0" }, + "devDependencies": { + "@types/js-cookie": "^3.0.3", + "jsdom": "^20.0.3", + "tsup": "^6.5.0", + "typescript": "5.5.4", + "vitest": "2.0.5", + "vue": "^3.5.0" + } +} diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts new file mode 100644 index 00000000..b27e221a --- /dev/null +++ b/packages/vue/src/index.ts @@ -0,0 +1,96 @@ +import { + Abby, AbbyEventType, HttpService, getABStorageKey, getFFStorageKey, + getRCStorageKey, type ABConfig, type AbbyConfig, type AbbyDataResponse, + type RemoteConfigValueString, type StorageServiceOptions, +} from "@tryabby/core"; +import Cookies from "js-cookie"; +import { + computed, inject, onMounted, ref, shallowRef, watch, + type App, type InjectionKey, +} from "vue"; + +export { defineConfig, type ABConfig, type AbbyConfig } from "@tryabby/core"; + +export function createAbby< + const Flag extends string, + const Tests extends Record, + const Remote extends Record, +>(config: AbbyConfig, Remote>) { + type Test = Extract; + type RemoteKey = Extract; + type Variant = Tests[K]["variants"][number]; + + function storage(keyFor: (project: string, name: string) => string) { + return { + get: (name: string) => Cookies.get(keyFor(config.projectId, name)) ?? null, + set: (name: string, value: string, options?: StorageServiceOptions) => + Cookies.set(keyFor(config.projectId, name), value, { expires: options?.expiresInDays }), + }; + } + + function state(initialData?: AbbyDataResponse) { + // Core updates the tests object as it selects variants. Give each app + // its own copy, including separate SSR requests that reuse this plugin. + const tests = Object.fromEntries(Object.entries(config.tests ?? {}).map( + ([name, test]) => [name, { ...test }], + )) as Tests; + const client = new Abby( + { ...config, tests }, storage(getABStorageKey), storage(getFFStorageKey), storage(getRCStorageKey), + ); + if (initialData) client.init(initialData); + const revision = shallowRef(0); + const unsubscribe = client.subscribe(() => { revision.value++; }); + return { client, revision, unsubscribe }; + } + + const key: InjectionKey> = Symbol("Abby"); + function useState() { + const current = inject(key); + if (!current) throw new Error("Install the Abby plugin with app.use(abby) before using its composables."); + return current; + } + + function install(app: App, initialData?: AbbyDataResponse) { + const current = state(initialData); + app.provide(key, current); + app.onUnmount(current.unsubscribe); + if (!initialData && typeof window !== "undefined") void current.client.loadProjectData(); + } + + function useFeatureFlag(name: Flag) { + const { client, revision } = useState(); + return computed(() => { void revision.value; return client.getFeatureFlag(name); }); + } + + function useRemoteConfig(name: K) { + const { client, revision } = useState(); + return computed(() => { void revision.value; return client.getRemoteConfig(name); }); + } + + function useAbby, unknown> | undefined = undefined>( + name: K, lookup?: Lookup, + ) { + const { client, revision } = useState(); + const mounted = ref(false); + const selected = computed>(() => { + void revision.value; + // The initial render uses the same fallback on the server and client. + return mounted.value ? client.getTestVariant(name) : config.tests![name].variants[0]; + }); + function track(type: AbbyEventType) { + if (mounted.value && selected.value) HttpService.sendData({ + url: config.apiUrl, type, + data: { projectId: config.projectId, testName: name, selectedVariant: selected.value }, + }); + } + onMounted(() => { + mounted.value = true; + watch(selected, () => track(AbbyEventType.PING), { immediate: true }); + }); + type Value = Lookup extends Record, unknown> ? Lookup[Variant] : Variant; + const variant = computed(() => (lookup ? lookup[selected.value] : selected.value) as Value); + return { variant, onAct: () => track(AbbyEventType.ACT) }; + } + + return { install, useAbby, useFeatureFlag, useRemoteConfig }; +} diff --git a/packages/vue/tests/ssr.test.ts b/packages/vue/tests/ssr.test.ts new file mode 100644 index 00000000..6c050af9 --- /dev/null +++ b/packages/vue/tests/ssr.test.ts @@ -0,0 +1,27 @@ +// @vitest-environment node +import { HttpService } from "@tryabby/core"; +import { createSSRApp, h } from "vue"; +import { renderToString } from "vue/server-renderer"; +import { expect, it, vi } from "vitest"; +import { createAbby } from "../src"; + +it("renders preloaded flags independently across SSR requests without fetching or tracking", async () => { + const fetch = vi.spyOn(HttpService, "getProjectData"); + const track = vi.spyOn(HttpService, "sendData"); + try { + const abby = createAbby({ projectId: "ssr", environments: ["test"], currentEnvironment: "test", + flags: ["enabled"], tests: { layout: { variants: ["first", "second"] } } }); + function render(enabled: boolean) { + const app = createSSRApp({ setup() { + const flag = abby.useFeatureFlag("enabled"); + const { variant } = abby.useAbby("layout"); + return () => h("p", String(flag.value) + "/" + variant.value); + }}); + app.use(abby, { tests: [], flags: [{ name: "enabled", value: enabled }], remoteConfig: [] }); + return renderToString(app); + } + expect(await Promise.all([render(true), render(false)])).toEqual(["

true/first

", "

false/first

"]); + expect(fetch).not.toHaveBeenCalled(); + expect(track).not.toHaveBeenCalled(); + } finally { fetch.mockRestore(); track.mockRestore(); } +}); diff --git a/packages/vue/tests/types.ts b/packages/vue/tests/types.ts new file mode 100644 index 00000000..a0ec9ee0 --- /dev/null +++ b/packages/vue/tests/types.ts @@ -0,0 +1,21 @@ +import { expectTypeOf } from "vitest"; +import type { ComputedRef } from "vue"; +import { createAbby } from "../src"; + +// Compiled by tsc. Composables run inside component setup at runtime. +export function checkInference() { + const abby = createAbby({ + projectId: "types", environments: ["prod"], currentEnvironment: "prod", + flags: ["beta"], remoteConfig: { price: "Number", label: "String" }, + tests: { treatment: { variants: ["control", "test"] } }, + }); + expectTypeOf(abby.useAbby("treatment").variant).toEqualTypeOf>(); + expectTypeOf(abby.useAbby("treatment", { control: 1, test: 2 }).variant).toEqualTypeOf>(); + expectTypeOf(abby.useFeatureFlag("beta")).toEqualTypeOf>(); + expectTypeOf(abby.useRemoteConfig("price")).toEqualTypeOf>(); + expectTypeOf(abby.useRemoteConfig("label")).toEqualTypeOf>(); + // @ts-expect-error Unknown flag. + abby.useFeatureFlag("other"); + // @ts-expect-error Missing a variant. + abby.useAbby("treatment", { control: 1 }); +} diff --git a/packages/vue/tests/vue.test.ts b/packages/vue/tests/vue.test.ts new file mode 100644 index 00000000..5128bc46 --- /dev/null +++ b/packages/vue/tests/vue.test.ts @@ -0,0 +1,68 @@ +// @vitest-environment jsdom +import { AbbyEventType, HttpService, type AbbyDataResponse } from "@tryabby/core"; +import { createApp, defineComponent, h, nextTick } from "vue"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { createAbby } from "../src"; + +const config = { + projectId: "vue-test", currentEnvironment: "test", environments: ["test"], + flags: ["showBanner"] as ("showBanner")[], + remoteConfig: { caption: "String" } as const, + tests: { color: { variants: ["blue", "green"] as const } }, + cookies: { disableByDefault: true }, +}; +const data = (caption: string, enabled: boolean): AbbyDataResponse => ({ + tests: [{ name: "color", weights: [0, 1] }], + flags: [{ name: "showBanner", value: enabled }], + remoteConfig: [{ name: "caption", value: caption }], +}); + +afterEach(() => { vi.restoreAllMocks(); }); + +describe("Vue plugin", () => { + it("isolates installations and tracks the chosen variant for an action", async () => { + const events = vi.spyOn(HttpService, "sendData").mockImplementation(() => undefined); + const abby = createAbby(config); + function mount(caption: string, flag: boolean) { + const host = document.createElement("div"); + const app = createApp(defineComponent({ setup() { + const { variant, onAct } = abby.useAbby("color", { blue: "B", green: "G" }); + const enabled = abby.useFeatureFlag("showBanner"); + const text = abby.useRemoteConfig("caption"); + return () => h("button", { onClick: onAct }, [text.value, String(enabled.value), variant.value].join("/")); + }})); + app.use(abby, data(caption, flag)); + app.mount(host); + return { host, app }; + } + const a = mount("First", true); + const b = mount("Second", false); + await nextTick(); + expect(a.host.textContent).toBe("First/true/G"); + expect(b.host.textContent).toBe("Second/false/G"); + a.host.querySelector("button")!.click(); + expect(events.mock.lastCall?.[0]).toMatchObject({ + type: AbbyEventType.ACT, data: { projectId: "vue-test", selectedVariant: "green", testName: "color" }, + }); + a.app.unmount(); + b.app.unmount(); + }); + + it("updates a mounted component after the project data arrives", async () => { + let release!: (value: AbbyDataResponse) => void; + const response = new Promise(resolve => { release = resolve; }); + vi.spyOn(HttpService, "getProjectData").mockReturnValue(response); + const abby = createAbby(config); + const app = createApp(defineComponent({ setup() { + const flag = abby.useFeatureFlag("showBanner"); + return () => h("p", String(flag.value)); + }})); + const host = document.createElement("div"); + app.use(abby); + app.mount(host); + expect(host.textContent).toBe("false"); + release(data("Ready", true)); + await vi.waitFor(() => expect(host.textContent).toBe("true")); + app.unmount(); + }); +}); diff --git a/packages/vue/tsconfig.json b/packages/vue/tsconfig.json new file mode 100644 index 00000000..8203fb98 --- /dev/null +++ b/packages/vue/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "strict": true, + "module": "ESNext", + "moduleResolution": "Bundler", + "target": "ES2022", + "skipLibCheck": true, + "allowSyntheticDefaultImports": true + }, + "include": ["src", "tests"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 69fa896e..f50b8016 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6,6 +6,34 @@ settings: importers: + packages/vue: + dependencies: + '@tryabby/core': + specifier: workspace:* + version: link:../core + js-cookie: + specifier: ^3.0.1 + version: 3.0.5 + devDependencies: + '@types/js-cookie': + specifier: ^3.0.3 + version: 3.0.3 + jsdom: + specifier: ^20.0.3 + version: 20.0.3 + tsup: + specifier: ^6.5.0 + version: 6.7.0(postcss@8.4.41)(ts-node@10.9.1(@types/node@22.1.0)(typescript@5.5.4))(typescript@5.5.4) + typescript: + specifier: 5.5.4 + version: 5.5.4 + vitest: + specifier: 2.0.5 + version: 2.0.5(@types/node@22.1.0)(jsdom@20.0.3)(less@4.2.0)(sass@1.77.8)(terser@5.31.1) + vue: + specifier: ^3.5.0 + version: 3.5.46(typescript@5.5.4) + .: devDependencies: '@biomejs/biome': @@ -1110,6 +1138,87 @@ importers: packages: + vue@3.5.46: + resolution: {integrity: sha512-0kW5CgfjMPBqmH158049SaE1muufp+K/ZyrwvSEwrwYky6QB7zL2y8kXfruneKb9O12eh0xAJL6CVSpzb9o0Kg==} + peerDependencies: + typescript: '*' + peerDependenciesMeta: + typescript: + optional: true + + '@vue/compiler-dom@3.5.46': + resolution: {integrity: sha512-Bj3lCSw3DQnDRDxw115XqdLDd0+18Nftlgd8OXSGG+ud74hxJIE17eYrM+VWgQrTMsvJbLh9Hzf2MkwAzru36Q==} + + '@vue/compiler-core@3.5.46': + resolution: {integrity: sha512-yb+N8/mgBcoeqCJPVyJI/D3OphLrSMXnB3ZQUNmRLU/1fsMW4bFfdJWNi9oIj7+EA3ULKKkP7b/VCpcYQYeiuQ==} + + '@babel/parser@7.29.15': + resolution: {integrity: sha512-RpKWyisHoP81twtSCgmE02iU0RnPcq1DN5bBEbpUePrjA9Q3wXhufnCJrrayPpoZieqFh3zyZQqwtSK0gGccRA==} + engines: {node: '>=6.0.0'} + hasBin: true + + '@babel/types@7.29.15': + resolution: {integrity: sha512-/XKpKDakL//LZ66bq1XsZOswuqeI5MZqPLDu18o3XdkU1fNJ7bdPtzgnc4ZNS+bBGHV0FJG8jjb8SwcC3nNVQQ==} + engines: {node: '>=6.9.0'} + + '@babel/helper-string-parser@7.29.15': + resolution: {integrity: sha512-C2FuapQ2Kh1OnVHAoLi5rD3GBJ8COb9Q609T6HEpLqaBAo560PDP5OxBE5dCI/h951MBO/+bCUYU5SZ+8ZlV+w==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-identifier@7.29.7': + resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} + engines: {node: '>=6.9.0'} + + '@vue/shared@3.5.46': + resolution: {integrity: sha512-P1WePbdzHrcIciWtmY2Im9EFhdakd3rZxYqvalOa3SfoxtF35Q8Uhmj1tKn6bWP4utcOpN8ao6BoJUItq0Uf+g==} + + entities@7.0.1: + resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==} + engines: {node: '>=0.12'} + + source-map-js@1.3.0: + resolution: {integrity: sha512-pdUVfIWcK0kCgK831ibqkZDcL7I9zljjOu0TQFnA+fiQ6y1CYqYB7RkTOHHO45FGMg5P/Mvk/+4ToQ7gAYAL5Q==} + engines: {node: '>=6.0.0'} + + '@vue/compiler-sfc@3.5.46': + resolution: {integrity: sha512-hjUvMxGh+QIgegwksfp6BRBYleE/a8veZHvTR6sa+o+bM4HU+WnrUZlhN0X+pDcsl8Lhwmbu72xPvLMk3XUwog==} + + '@vue/compiler-ssr@3.5.46': + resolution: {integrity: sha512-qebChL3aP0m1k+TlSf+fZWvOwAf3flBCi5o+n01ykR3DX4mTIWheFltmoiQ12+z66/4cGeXqbB2P7sPWkGhQNQ==} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + postcss@8.5.34: + resolution: {integrity: sha512-P1Qzj0XXZjMda74C7qiVnBG90UKNbyNUAOeQRBW8X63RsIMV57gevRqjnkELdwtZ/S2/uQFksJhmwuN8xShLPw==} + engines: {node: ^10 || ^12 || >=14} + + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + '@vue/runtime-dom@3.5.46': + resolution: {integrity: sha512-6L7lbBvXTYBFFjIt25a0pgdpmn3Ns8RqUnNVibRzF4bgyiWJvqOhKEV5MXYWKlCttZE3aGeJN8mveo+6IrIKXA==} + + '@vue/reactivity@3.5.46': + resolution: {integrity: sha512-+FHtYTvGxgFoX3oRs7soz6JHizGv50Q26WJN6PWtXuTLXRfkfUpDUTRuoTA/kiZVVt8NMeMpsPQLh9h++ReUjQ==} + + '@vue/runtime-core@3.5.46': + resolution: {integrity: sha512-eJUzKAUaHAmtnys/l9qduPzUnBrYMkmsCU7TN+vbSOSpm8kcETT7nacKxIO4MBej/XiOraVzq+lSeZv7o1//jQ==} + + csstype@3.2.4: + resolution: {integrity: sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==} + + '@vue/server-renderer@3.5.46': + resolution: {integrity: sha512-4mc0YWREc6OZ5pDCigvKPDzIUV+aciiH92yvyTS6xaHHxW/80rMceQQn11pYe7OEEBt2YQgYWR9zF8QF30GJUQ==} + '@adobe/css-tools@4.2.0': resolution: {integrity: sha512-E09FiIft46CmH5Qnjb0wsW54/YQd69LsxeKUOWawmws1XWvyFGURnAChH0mlr7YPFR1ofwvUQfcL0J3lMxXqPA==} @@ -14391,6 +14500,105 @@ packages: snapshots: + vue@3.5.46(typescript@5.5.4): + dependencies: + '@vue/compiler-dom': 3.5.46 + '@vue/compiler-sfc': 3.5.46 + '@vue/runtime-dom': 3.5.46 + '@vue/server-renderer': 3.5.46 + '@vue/shared': 3.5.46 + optionalDependencies: + typescript: 5.5.4 + + '@vue/compiler-dom@3.5.46': + dependencies: + '@vue/compiler-core': 3.5.46 + '@vue/shared': 3.5.46 + + '@vue/compiler-core@3.5.46': + dependencies: + '@babel/parser': 7.29.15 + '@vue/shared': 3.5.46 + entities: 7.0.1 + estree-walker: 2.0.2 + source-map-js: 1.3.0 + + '@babel/parser@7.29.15': + dependencies: + '@babel/types': 7.29.15 + + '@babel/types@7.29.15': + dependencies: + '@babel/helper-string-parser': 7.29.15 + '@babel/helper-validator-identifier': 7.29.7 + + '@babel/helper-string-parser@7.29.15': {} + + '@babel/helper-validator-identifier@7.29.7': {} + + '@vue/shared@3.5.46': {} + + entities@7.0.1: {} + + source-map-js@1.3.0: {} + + '@vue/compiler-sfc@3.5.46': + dependencies: + '@babel/parser': 7.29.15 + '@vue/compiler-core': 3.5.46 + '@vue/compiler-dom': 3.5.46 + '@vue/compiler-ssr': 3.5.46 + '@vue/shared': 3.5.46 + estree-walker: 2.0.2 + magic-string: 0.30.21 + postcss: 8.5.34 + source-map-js: 1.3.0 + + '@vue/compiler-ssr@3.5.46': + dependencies: + '@vue/compiler-dom': 3.5.46 + '@vue/shared': 3.5.46 + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + '@jridgewell/sourcemap-codec@1.6.0': {} + + postcss@8.5.34: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.3.0 + + nanoid@3.3.20: {} + + picocolors@1.1.1: {} + + '@vue/runtime-dom@3.5.46': + dependencies: + '@vue/reactivity': 3.5.46 + '@vue/runtime-core': 3.5.46 + '@vue/shared': 3.5.46 + csstype: 3.2.4 + + '@vue/reactivity@3.5.46': + dependencies: + '@vue/shared': 3.5.46 + + '@vue/runtime-core@3.5.46': + dependencies: + '@vue/reactivity': 3.5.46 + '@vue/shared': 3.5.46 + + csstype@3.2.4: {} + + '@vue/server-renderer@3.5.46': + dependencies: + '@vue/compiler-ssr': 3.5.46 + '@vue/runtime-dom': 3.5.46 + '@vue/shared': 3.5.46 + '@adobe/css-tools@4.2.0': {} '@alloc/quick-lru@5.2.0': {}