@sanity/personalization-plugin 2.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Jon Burbridge
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,287 @@
1
+ # @sanity/personalization-plugin
2
+
3
+ ## Previously know as @sanity/personalisation-plugin
4
+
5
+ > This is a **Sanity Studio v3** plugin.
6
+
7
+ This plugin allows users to add a/b/n testing experiments to individual fields.
8
+
9
+ ![image](./overview.gif)
10
+
11
+ For this plugin you need to defined the experiments you are running and the variations those experiments have. Each experiment needs to have an id, a label, and an array of variants that have an id and a label. You can either pass an array of experiments in the plugin config, or you can use and async function to retrieve the experiments and variants from an external service like growthbook, Amplitude, LaunchDarkly... You could even store the experiments in your sanity dataset.
12
+
13
+ Once configured you can query the values using the ids of the experiment and variant
14
+
15
+ - [@sanity/personalization-plugin](#@sanity/personalization-plugin)
16
+ - [Installation](#installation)
17
+ - [Usage](#usage)
18
+ - [Loading Experiments](#loading-experiments)
19
+ - [Using complex field configurations](#using-complex-field-configurations)
20
+ - [Validation of individual array items](#validation-of-individual-array-items)
21
+ - [Shape of stored data](#shape-of-stored-data)
22
+ - [Querying data](#querying-data)
23
+ - [License](#license)
24
+ - [Develop \& test](#develop--test)
25
+ - [Release new version](#release-new-version)
26
+ - [License](#license-1)
27
+
28
+ ## Installation
29
+
30
+ ```sh
31
+ npm install @sanity/personalization-plugin
32
+ ```
33
+
34
+ ## Usage
35
+
36
+ Add it as a plugin in `sanity.config.ts` (or .js):
37
+
38
+ ```ts
39
+ import {defineConfig} from 'sanity'
40
+ import {fieldLevelExperiments} from '@sanity/personalization-plugin'
41
+
42
+ const experiment1 = {
43
+ id: '123',
44
+ label: 'experiment 1',
45
+ variants: [
46
+ {
47
+ id: '123-a',
48
+ label: 'first var',
49
+ },
50
+ {
51
+ id: '123-b',
52
+ label: 'second var',
53
+ },
54
+ ],
55
+ }
56
+ const experiment2 = {
57
+ id: '456',
58
+ label: 'experiment 2',
59
+ variants: [
60
+ {
61
+ id: '456-a',
62
+ label: 'b first var',
63
+ },
64
+ {
65
+ id: '456-b',
66
+ label: 'b second var',
67
+ },
68
+ ],
69
+ }
70
+
71
+ export default defineConfig({
72
+ //...
73
+ plugins: [
74
+ //...
75
+ fieldLevelExperiments({
76
+ fields: ['string'],
77
+
78
+ experiments: [experiment1, experiment2],
79
+ }),
80
+ ],
81
+ })
82
+ ```
83
+
84
+ This will register two new fields to the schema., based on the setting passed intto `fields:`
85
+
86
+ - `experimentString` an Object field with `string` field called `default`, a `string` field called `experimentId` and an array field of type:
87
+ - `varirantsString` an object field with a `string` field called `value`, a string field called `variantId`, a `string` field called `experimentId`.
88
+
89
+ Use the experiment field in your schema like this:
90
+
91
+ ```ts
92
+ //for Example in post.ts
93
+
94
+ fields: [
95
+ defineField({
96
+ name: 'title',
97
+ type: 'experimentString',
98
+ }),
99
+ ]
100
+ ```
101
+
102
+ ## Loading Experiments
103
+
104
+ Experiments must be an array of objects with an id and label and an array of variants objects with an id and label.
105
+
106
+ ```ts
107
+ experiments: [
108
+ {
109
+ id: '123',
110
+ label: 'experiment 1',
111
+ variants: [
112
+ {
113
+ id: '123-a',
114
+ label: 'first var',
115
+ },
116
+ {
117
+ id: '123-b',
118
+ label: 'second var',
119
+ },
120
+ ],
121
+ },
122
+ {
123
+ id: '456',
124
+ label: 'experiment 2',
125
+ variants: [
126
+ {
127
+ id: '456-a',
128
+ label: 'b first var',
129
+ },
130
+ {
131
+ id: '456-b',
132
+ label: 'b second var',
133
+ },
134
+ ],
135
+ },
136
+ ]
137
+ ```
138
+
139
+ Or an asynchronous function that returns an array of objects with an id and label and an array of variants objects with an id and label.
140
+
141
+ ```ts
142
+ experiments: async () => {
143
+ const response = await fetch('https://example.com/experiments')
144
+ const {externalExperiments} = await response.json()
145
+
146
+ const experiments: ExperimentType[] = externalExperiments?.map(
147
+ (experiment) => {
148
+ const experimentId = experiment.id
149
+ const experimentLabel = experiment.name
150
+ const variants = experiment.variations?.map((variant) => {
151
+ return {
152
+ id: variant.variationId,
153
+ label: variant.name,
154
+ }
155
+ })
156
+ return {
157
+ id: experimentId,
158
+ label: experimentLabel,
159
+ variants,
160
+ }
161
+ },
162
+ )
163
+ return experiments
164
+ }
165
+ ```
166
+
167
+ The async function contains a configured Sanity Client in the first parameter, allowing you to store Language options as documents. Your query should return an array of objects with an id and title.
168
+
169
+ ```ts
170
+ experiments: async (client) => {
171
+ const experiments = await client.fetch(`*[_type == 'experiment']`)
172
+ return experiments
173
+ },
174
+ ```
175
+
176
+ ## Using complex field configurations
177
+
178
+ For more control over the value field, you can pass a schema definition into the fields array.
179
+
180
+ ```ts
181
+ import {defineConfig} from 'sanity'
182
+ import {fieldLevelExperiments} from '@sanity/personalization-plugin'
183
+
184
+ export default defineConfig({
185
+ //...
186
+ plugins: [
187
+ //...
188
+ fieldLevelExperiments({
189
+ fields: [
190
+ defineField({
191
+ name: 'featuredProduct',
192
+ type: 'reference',
193
+ to: [{type: 'product'}],
194
+ hidden: ({document}) => !document?.title,
195
+ }),
196
+ ],
197
+ experiments: [experiment1, experiment2],
198
+ }),
199
+ ],
200
+ })
201
+ ```
202
+
203
+ This would also create two new fields in your schema.
204
+
205
+ - `experimentFeaturedProduct` an Object field with `reference` field called `default`, a `string` field called `experimentId` and an array field of type:
206
+ - `variantFeaturedProduct` an object field with a `reference` field called `value`, a string field called `variandId`, a `string` field called `experimentId`.
207
+
208
+ Note that the name key in the field gets rewritten to value and is instead used to name the object field.
209
+
210
+ ## Validation of individual array items
211
+
212
+ You may wish to validate individual fields for various reasons. From the variant array field, add a validation rule that can look through all the array items, and return item-specific validation messages at the path of that array item.
213
+
214
+ ```ts
215
+ defineField({
216
+ name: 'title',
217
+ title: 'Title',
218
+ type: 'experimentString',
219
+ validation: (rule) =>
220
+ rule.custom((experiment: ExperimentGeneric<string>) => {
221
+ if (!experiment.default) {
222
+ return 'Default value is required'
223
+ }
224
+
225
+ const invalidVariants = experiment.variants?.filter((variant) => !variant.value)
226
+
227
+ if (invalidVariants?.length) {
228
+ return invalidVariants.map((item) => ({
229
+ message: `Variant is missing a value`,
230
+ path: ['variants', {_key: item._key}, 'value'],
231
+ }))
232
+ }
233
+ return true
234
+ }),
235
+ }),
236
+ ```
237
+
238
+ ## Shape of stored data
239
+
240
+ The custom input contains buttons which will add new array items with the experiment and variant already populated. Data returned from this array will look like this:
241
+
242
+ ```json
243
+ "title": {
244
+ "default": "asdf",
245
+ "experimentValue": "test-1",
246
+ "variants": [
247
+ {
248
+ "experimentId": "test-1",
249
+ "value": "asdf",
250
+ "variantId": "test-1-a"
251
+ },
252
+ {
253
+ "experimentId": "test-1",
254
+ "variantId": "test-1-b",
255
+ "value": "asdf"
256
+ }
257
+ ]
258
+ }
259
+ ```
260
+
261
+ Querying data
262
+ Using GROQ filters you can query for a specific experitment, with a fallback to default value like so:
263
+
264
+ ```ts
265
+ *[_type == "post"] {
266
+ "title":coalesce(title.variants[experimentId == $experiment && variantId == $variant][0].value, title.default),
267
+ }
268
+ ```
269
+
270
+ ## License
271
+
272
+ [MIT](LICENSE) © Jon Burbridge
273
+
274
+ ## Develop & test
275
+
276
+ This plugin uses [@sanity/plugin-kit](https://github.com/sanity-io/plugin-kit)
277
+ with default configuration for build & watch scripts.
278
+
279
+ See [Testing a plugin in Sanity Studio](https://github.com/sanity-io/plugin-kit#testing-a-plugin-in-sanity-studio)
280
+ on how to run this plugin with hotreload in the studio.
281
+
282
+ ### Release new version
283
+
284
+ Run ["CI & Release" workflow](https://github.com/sanity-io/sanity-plugin-personalization/actions/workflows/main.yml).
285
+ Make sure to select the main branch and check "Release new version".
286
+
287
+ Semantic release will only release on configured branches, so it is safe to run release on any branch.
@@ -0,0 +1,70 @@
1
+ import {ArrayOfObjectsInputProps} from 'sanity'
2
+ import {FieldDefinition} from 'sanity'
3
+ import {ObjectField} from 'sanity'
4
+ import {Path} from 'sanity'
5
+ import {Plugin as Plugin_2} from 'sanity'
6
+ import {PreviewProps} from 'sanity'
7
+ import {SanityClient} from 'sanity'
8
+ import {SchemaType} from 'sanity'
9
+
10
+ export declare type ArrayInputProps = ArrayOfObjectsInputProps & {
11
+ objectName: string
12
+ }
13
+
14
+ export declare type ExperimentContextProps = Required<FieldPluginConfig> & {
15
+ experiments: ExperimentType[]
16
+ }
17
+
18
+ export declare type ExperimentGeneric<T> = {
19
+ _type: string
20
+ default?: T
21
+ experimentValue?: string
22
+ variants?: Array<
23
+ {
24
+ _key: string
25
+ } & VariantGeneric<T>
26
+ >
27
+ }
28
+
29
+ export declare type ExperimentType = {
30
+ id: string
31
+ label: string
32
+ variants: VariantType[]
33
+ }
34
+
35
+ export declare const fieldLevelExperiments: Plugin_2<FieldPluginConfig>
36
+
37
+ export declare type FieldPluginConfig = {
38
+ fields: (string | FieldDefinition)[]
39
+ experiments: ExperimentType[] | ((client: SanityClient) => Promise<ExperimentType[]>)
40
+ apiVersion?: string
41
+ }
42
+
43
+ /**
44
+ * Flattens a document's schema type into a flat array of fields and includes their path
45
+ */
46
+ export declare function flattenSchemaType(schemaType: SchemaType): ObjectFieldWithPath[]
47
+
48
+ export declare type ObjectFieldWithPath = ObjectField<SchemaType> & {
49
+ path: Path
50
+ }
51
+
52
+ export declare type VariantGeneric<T> = {
53
+ _type: string
54
+ variantId?: string
55
+ experimentId?: string
56
+ value?: T
57
+ }
58
+
59
+ export declare type VariantPreviewProps = Omit<PreviewProps, 'SchemaType'> & {
60
+ experiment: string
61
+ variant: string
62
+ value: any
63
+ }
64
+
65
+ export declare type VariantType = {
66
+ id: string
67
+ label: string
68
+ }
69
+
70
+ export {}
@@ -0,0 +1,70 @@
1
+ import {ArrayOfObjectsInputProps} from 'sanity'
2
+ import {FieldDefinition} from 'sanity'
3
+ import {ObjectField} from 'sanity'
4
+ import {Path} from 'sanity'
5
+ import {Plugin as Plugin_2} from 'sanity'
6
+ import {PreviewProps} from 'sanity'
7
+ import {SanityClient} from 'sanity'
8
+ import {SchemaType} from 'sanity'
9
+
10
+ export declare type ArrayInputProps = ArrayOfObjectsInputProps & {
11
+ objectName: string
12
+ }
13
+
14
+ export declare type ExperimentContextProps = Required<FieldPluginConfig> & {
15
+ experiments: ExperimentType[]
16
+ }
17
+
18
+ export declare type ExperimentGeneric<T> = {
19
+ _type: string
20
+ default?: T
21
+ experimentValue?: string
22
+ variants?: Array<
23
+ {
24
+ _key: string
25
+ } & VariantGeneric<T>
26
+ >
27
+ }
28
+
29
+ export declare type ExperimentType = {
30
+ id: string
31
+ label: string
32
+ variants: VariantType[]
33
+ }
34
+
35
+ export declare const fieldLevelExperiments: Plugin_2<FieldPluginConfig>
36
+
37
+ export declare type FieldPluginConfig = {
38
+ fields: (string | FieldDefinition)[]
39
+ experiments: ExperimentType[] | ((client: SanityClient) => Promise<ExperimentType[]>)
40
+ apiVersion?: string
41
+ }
42
+
43
+ /**
44
+ * Flattens a document's schema type into a flat array of fields and includes their path
45
+ */
46
+ export declare function flattenSchemaType(schemaType: SchemaType): ObjectFieldWithPath[]
47
+
48
+ export declare type ObjectFieldWithPath = ObjectField<SchemaType> & {
49
+ path: Path
50
+ }
51
+
52
+ export declare type VariantGeneric<T> = {
53
+ _type: string
54
+ variantId?: string
55
+ experimentId?: string
56
+ value?: T
57
+ }
58
+
59
+ export declare type VariantPreviewProps = Omit<PreviewProps, 'SchemaType'> & {
60
+ experiment: string
61
+ variant: string
62
+ value: any
63
+ }
64
+
65
+ export declare type VariantType = {
66
+ id: string
67
+ label: string
68
+ }
69
+
70
+ export {}