@basementstudio/sanity-ai-image-plugin 0.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/README.md ADDED
@@ -0,0 +1,257 @@
1
+ # `sanity-ai-image-plugin`
2
+
3
+ Portable Sanity Studio plugin and server helper for generating images with
4
+ Gemini, OpenAI, and other package-supported image models and dropping the
5
+ result straight into Sanity image fields.
6
+
7
+ This package is intentionally self-contained so it can be copied into a new repo
8
+ or published later without dragging along an app-specific schema layout.
9
+
10
+ This repo is source-first while it is being developed here:
11
+
12
+ - package exports point at `src/*`
13
+
14
+ ## What It Owns
15
+
16
+ - a Studio plugin via `aiImagePlugin(...)`
17
+ - a plugin-owned settings document and settings tool
18
+ - a generic image asset source
19
+ - optional generate-button targets for specific image fields
20
+ - a server helper export for the app-owned API route
21
+
22
+ ## Install Shape
23
+
24
+ The package exposes two entrypoints:
25
+
26
+ - `sanity-ai-image-plugin`
27
+ - `sanity-ai-image-plugin/server`
28
+
29
+ ## Consumer Setup
30
+
31
+ ### 1. Add the Studio plugin
32
+
33
+ ```ts
34
+ import { defineConfig } from "sanity";
35
+ import {
36
+ SUPPORTED_AI_IMAGE_MODELS,
37
+ createArticleFeaturedImageTarget,
38
+ aiImagePlugin,
39
+ } from "sanity-ai-image-plugin";
40
+
41
+ const allowedModels = [
42
+ SUPPORTED_AI_IMAGE_MODELS[0],
43
+ SUPPORTED_AI_IMAGE_MODELS[2],
44
+ ] as const;
45
+
46
+ export default defineConfig({
47
+ // ...your existing config
48
+ plugins: [
49
+ aiImagePlugin({
50
+ apiVersion: "2025-02-19",
51
+ allowedModels: [...allowedModels],
52
+ assetSource: true,
53
+ targets: [
54
+ createArticleFeaturedImageTarget(),
55
+ {
56
+ id: "home-page-featured-image",
57
+ type: "generateButton",
58
+ title: "Home Page Featured Image",
59
+ documentType: "homePage",
60
+ fieldPath: "featuredImage",
61
+ suggestedContextFieldPaths: ["title", "description"],
62
+ },
63
+ ],
64
+ }),
65
+ ],
66
+ });
67
+ ```
68
+
69
+ ### 2. Add the thin app-owned route.
70
+
71
+ ```ts
72
+ import {
73
+ handleAiImageRequest,
74
+ SUPPORTED_AI_IMAGE_MODELS,
75
+ } from "sanity-ai-image-plugin/server";
76
+
77
+ const allowedModels = [
78
+ SUPPORTED_AI_IMAGE_MODELS[0],
79
+ SUPPORTED_AI_IMAGE_MODELS[2],
80
+ ] as const;
81
+
82
+ export async function POST(request: Request) {
83
+ return handleAiImageRequest(request, {
84
+ allowedModels: [...allowedModels],
85
+ apiKey: process.env.GEMINI_API_KEY,
86
+ openAiApiKey: process.env.OPENAI_API_KEY,
87
+ // Same-origin protection is enabled by default.
88
+ // Optional overrides:
89
+ // model: process.env.AI_IMAGE_MODEL as (typeof allowedModels)[number],
90
+ // maxReferenceFileBytes: 8 * 1024 * 1024,
91
+ // maxTotalReferenceBytes: 5 * 8 * 1024 * 1024,
92
+ })
93
+ }
94
+ ```
95
+
96
+ ### 3. Set env vars
97
+
98
+ - `GEMINI_API_KEY` is required when you allow Google models
99
+ - `OPENAI_API_KEY` is required when you allow OpenAI models
100
+ - `AI_IMAGE_MODEL` is optional and can still override the server default
101
+
102
+ ## Supported Models
103
+
104
+ The package has an internal supported-model registry. In this first pass it
105
+ contains exactly:
106
+
107
+ - `gemini-2.5-flash-image`
108
+ - `gemini-3.1-flash-image-preview`
109
+ - `gpt-image-1`
110
+
111
+ Each installation can opt into any non-empty subset of those models with the
112
+ ordered `allowedModels` config. The first allowed model becomes the default
113
+ model for both the Studio UI and the server helper unless the settings document
114
+ or route overrides it.
115
+
116
+ ## Settings Model
117
+
118
+ The plugin owns one settings document:
119
+
120
+ - `_id`: `aiImagePlugin.settings`
121
+ - `_type`: `aiImagePluginSettings`
122
+
123
+ It stores:
124
+
125
+ - `globalModel`
126
+ - `globalPrompt`
127
+ - `globalReferenceImages`
128
+ - `targetConfigs[]`
129
+
130
+ Each target config can override:
131
+
132
+ - `targetId`
133
+ - `prompt`
134
+ - `referenceImages`
135
+
136
+ ## Behavior
137
+
138
+ ### Server helper
139
+
140
+ The server helper is same-origin only by default.
141
+
142
+ That means requests are accepted when the browser `Origin` matches the API
143
+ route origin exactly, for example:
144
+
145
+ - `http://localhost:3000/studio` -> `http://localhost:3000/api/ai-image-plugin`
146
+ - `https://myapp.vercel.app/studio` -> `https://myapp.vercel.app/api/ai-image-plugin`
147
+
148
+ The helper does not inspect the `/studio` path directly because browser
149
+ `Origin` headers only include the scheme, host, and port.
150
+
151
+ By default it also enforces:
152
+
153
+ - `8 MiB` maximum per reference image
154
+ - a combined reference-image cap of `maxReferences * 8 MiB`
155
+ - the requested `model` must be both package-supported and present in the
156
+ route's configured `allowedModels`
157
+
158
+ If your framework supports route-level body limits, keep those enabled too.
159
+
160
+ ### Asset source
161
+
162
+ The generic asset source composes:
163
+
164
+ 1. global prompt
165
+ 2. asset-source target prompt
166
+ 3. editor prompt
167
+
168
+ Reference images are combined from:
169
+
170
+ 1. global reference images
171
+ 2. asset-source target reference images
172
+ 3. local editor-uploaded reference images
173
+
174
+ The selected model is resolved like this:
175
+
176
+ 1. `settings.globalModel` when it is present and allowed
177
+ 2. otherwise the first configured `allowedModels` entry
178
+
179
+ ### Generate button targets
180
+
181
+ Generate-button targets match against:
182
+
183
+ - `documentType`
184
+ - `fieldPath`
185
+
186
+ When matched, the plugin renders a `Generate` button above the normal Sanity
187
+ image input.
188
+
189
+ Targets can also declare:
190
+
191
+ - `suggestedContextFieldPaths`
192
+
193
+ When the dialog opens, the plugin inspects the current document schema and shows
194
+ eligible top-level document fields as toggle tags. In this first pass, eligible
195
+ field types are:
196
+
197
+ - `string`
198
+ - `text`
199
+ - `number`
200
+ - `boolean`
201
+ - `date`
202
+ - `datetime`
203
+ - `slug`
204
+
205
+ Suggested context field paths are only default-on tags. They are filtered to
206
+ fields that exist on the current document type, and editors can toggle them on
207
+ or off for each generation.
208
+
209
+ Prompt composition order is:
210
+
211
+ 1. global prompt
212
+ 2. target prompt
213
+ 3. optional selected document context
214
+ 4. optional editor prompt
215
+
216
+ Selected document context is built as generic lines such as:
217
+
218
+ - `The field called "title" has content "...".`
219
+
220
+ ## Optional Preset
221
+
222
+ `createArticleFeaturedImageTarget(...)` is an optional preset for
223
+ `article.featuredImage`.
224
+
225
+ It feeds the model:
226
+
227
+ - shared global settings
228
+ - target-specific article settings
229
+ - editor-selectable document-derived title + excerpt context suggestions
230
+ - optional editor prompt
231
+
232
+ If you do not use that preset, the package still works as a generic asset source
233
+ and generic generate-button plugin.
234
+
235
+ ## Desk Structure
236
+
237
+ The plugin does not require custom desk structure wiring. If a consuming app
238
+ uses a custom structure and wants to hide `aiImagePluginSettings` from the normal
239
+ document list, that is optional and app-owned.
240
+
241
+ ## PNG Normalization
242
+
243
+ All reference images are converted to PNG before they are sent to the server
244
+ helper. That includes:
245
+
246
+ - locally uploaded reference files
247
+ - stored settings images downloaded from Sanity
248
+ - new images uploaded through the settings tool
249
+
250
+ ## Development
251
+
252
+ ```sh
253
+ bun run check
254
+ bun run build
255
+ bun test
256
+ ```
257
+
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@basementstudio/sanity-ai-image-plugin",
3
+ "private": false,
4
+ "version": "0.0.0",
5
+ "packageManager": "bun@1.3.7",
6
+ "description": "Portable Sanity Studio plugin and server helper for AI image generation.",
7
+ "type": "module",
8
+ "sideEffects": false,
9
+ "files": [
10
+ "src",
11
+ "README.md"
12
+ ],
13
+ "exports": {
14
+ ".": {
15
+ "types": "./src/index.ts",
16
+ "import": "./src/index.ts",
17
+ "default": "./src/index.ts"
18
+ },
19
+ "./server": {
20
+ "types": "./src/server.ts",
21
+ "import": "./src/server.ts",
22
+ "default": "./src/server.ts"
23
+ },
24
+ "./package.json": "./package.json"
25
+ },
26
+ "scripts": {
27
+ "build": "tsc -p tsconfig.build.json",
28
+ "check": "tsc -p tsconfig.json --noEmit",
29
+ "test": "bun test tests",
30
+ "changeset": "changeset",
31
+ "version-packages": "changeset version",
32
+ "release": "changeset publish",
33
+ "version-canary": "changeset version --snapshot canary",
34
+ "release-canary": "changeset publish --tag canary --no-git-tag"
35
+ },
36
+ "keywords": [
37
+ "sanity",
38
+ "sanity-plugin",
39
+ "gemini",
40
+ "image-generation",
41
+ "ai-image-plugin"
42
+ ],
43
+ "peerDependencies": {
44
+ "@sanity/ui": "^2.0.0 || ^3.0.0",
45
+ "react": "^18.0.0 || ^19.0.0",
46
+ "react-dom": "^18.0.0 || ^19.0.0",
47
+ "sanity": "^3.0.0 || ^4.0.0 || ^5.0.0"
48
+ },
49
+ "dependencies": {
50
+ "@ai-sdk/google": "^3",
51
+ "@ai-sdk/openai": "^3",
52
+ "ai": "^6"
53
+ },
54
+ "devDependencies": {
55
+ "@sanity/ui": "^3.1.14",
56
+ "@changesets/changelog-github": "^0.5.2",
57
+ "@changesets/cli": "^2.29.8",
58
+ "@types/bun": "^1.3.6",
59
+ "@types/node": "^20.19.30",
60
+ "@types/react": "^19.2.9",
61
+ "@types/react-dom": "^19.2.3",
62
+ "react": "^19.2.4",
63
+ "react-dom": "^19.2.4",
64
+ "sanity": "^5.6.0",
65
+ "typescript": "^5.9.3"
66
+ }
67
+ }
package/src/index.ts ADDED
@@ -0,0 +1,23 @@
1
+ export {
2
+ DEFAULT_API_ENDPOINT,
3
+ DEFAULT_ASSET_SOURCE_TARGET_ID,
4
+ MAX_REFERENCE_IMAGES,
5
+ SETTINGS_DOCUMENT_ID,
6
+ SETTINGS_SCHEMA_TYPE,
7
+ SETTINGS_TOOL_NAME,
8
+ SETTINGS_TOOL_TITLE,
9
+ SOURCE_NAME,
10
+ SOURCE_TITLE,
11
+ type AssetSourceTarget,
12
+ type GenerateButtonTarget,
13
+ type PluginOptions,
14
+ type SettingsTargetConfigValue,
15
+ type SettingsValue,
16
+ type StoredImage,
17
+ } from "./utils/shared";
18
+ export {
19
+ SUPPORTED_AI_IMAGE_MODELS,
20
+ type SupportedAiImageModelId,
21
+ } from "./utils/models";
22
+ export { createArticleFeaturedImageTarget } from "./presets/article-featured-image";
23
+ export { aiImagePlugin } from "./studio/plugin";
@@ -0,0 +1,23 @@
1
+ import type { GenerateButtonTarget } from "../utils/shared"
2
+
3
+ export function createArticleFeaturedImageTarget(
4
+ options: Partial<Omit<GenerateButtonTarget, "type">> = {}
5
+ ): GenerateButtonTarget {
6
+ return {
7
+ id: options.id || "article-featured-image",
8
+ type: "generateButton",
9
+ title: options.title || "Article Featured Image",
10
+ description:
11
+ options.description ||
12
+ "Adds a Generate button that combines shared art direction, article context, and an optional editor prompt.",
13
+ dialogTitle: options.dialogTitle || "Generate Featured Image",
14
+ documentType: options.documentType || "article",
15
+ fieldPath: options.fieldPath || "featuredImage",
16
+ promptLabel: options.promptLabel || "Custom prompt",
17
+ promptPlaceholder:
18
+ options.promptPlaceholder ||
19
+ "Optional custom instructions for this article image.",
20
+ suggestedContextFieldPaths:
21
+ options.suggestedContextFieldPaths || ["title", "excerpt"],
22
+ }
23
+ }
@@ -0,0 +1,20 @@
1
+ import { DEFAULT_SUPPORTED_AI_IMAGE_MODEL } from "../utils/models";
2
+
3
+ export const DEFAULT_MODEL = DEFAULT_SUPPORTED_AI_IMAGE_MODEL;
4
+ export const DEFAULT_PROVIDER_API_URL =
5
+ "https://generativelanguage.googleapis.com/v1beta";
6
+ export const DEFAULT_MAX_REFERENCE_FILE_BYTES = 8 * 1024 * 1024;
7
+
8
+ export const SUPPORTED_REFERENCE_IMAGE_TYPES = new Set([
9
+ "image/heic",
10
+ "image/heif",
11
+ "image/jpeg",
12
+ "image/png",
13
+ "image/webp",
14
+ ]);
15
+
16
+ export const OPENAI_SUPPORTED_REFERENCE_IMAGE_TYPES = new Set([
17
+ "image/jpeg",
18
+ "image/png",
19
+ "image/webp",
20
+ ]);
@@ -0,0 +1,207 @@
1
+ import {
2
+ isSupportedAiImageModelId,
3
+ resolveAllowedAiImageModel,
4
+ SUPPORTED_AI_IMAGE_MODELS,
5
+ } from "../utils/models";
6
+ import {
7
+ generateImageWithModel,
8
+ getErrorMessage,
9
+ getErrorStatusCode,
10
+ getFormRequestPayload,
11
+ getMissingApiKeyErrorMessage,
12
+ getProviderApiKey,
13
+ getProviderDisplayName,
14
+ getReferenceImageValidationError,
15
+ getSameOriginValidationError,
16
+ isMultipartFormData,
17
+ jsonResponse,
18
+ parseHeaderByteLength,
19
+ resolveRequestOptions,
20
+ } from "./utils";
21
+ import type { RequestOptions, SuccessResponse } from "./types";
22
+ export {
23
+ DEFAULT_MAX_REFERENCE_FILE_BYTES,
24
+ DEFAULT_MODEL,
25
+ DEFAULT_PROVIDER_API_URL,
26
+ SUPPORTED_REFERENCE_IMAGE_TYPES,
27
+ } from "./constants";
28
+ export type { RequestOptions, SuccessResponse } from "./types";
29
+
30
+ export async function handleAiImageRequest(
31
+ request: Request,
32
+ options: RequestOptions = {},
33
+ ): Promise<Response> {
34
+ let requestOptions: ReturnType<typeof resolveRequestOptions>;
35
+
36
+ // Normalize server config up front so the rest of the handler can assume a
37
+ // single, fully-resolved set of limits and model choices.
38
+ try {
39
+ requestOptions = resolveRequestOptions(options);
40
+ } catch (error) {
41
+ return jsonResponse(
42
+ {
43
+ error:
44
+ getErrorMessage(error) ||
45
+ "AI Image Plugin server configuration is invalid.",
46
+ },
47
+ 500,
48
+ );
49
+ }
50
+
51
+ // Reject browser requests that do not come from the same Sanity Studio
52
+ // origin when same-origin enforcement is enabled.
53
+ if (requestOptions.enforceSameOrigin) {
54
+ const sameOriginError = getSameOriginValidationError(request);
55
+
56
+ if (sameOriginError) {
57
+ return jsonResponse(
58
+ {
59
+ error: sameOriginError.error,
60
+ },
61
+ sameOriginError.status,
62
+ );
63
+ }
64
+ }
65
+
66
+ // The endpoint only accepts multipart form submissions because prompt/model
67
+ // metadata and uploaded reference images arrive together.
68
+ if (!isMultipartFormData(request.headers.get("content-type"))) {
69
+ return jsonResponse(
70
+ {
71
+ error: "AI Image Plugin requires a multipart/form-data request.",
72
+ },
73
+ 415,
74
+ );
75
+ }
76
+
77
+ // Fail early on obviously oversized requests before parsing the body.
78
+ const contentLength = parseHeaderByteLength(
79
+ request.headers.get("content-length"),
80
+ );
81
+
82
+ if (
83
+ contentLength !== null &&
84
+ contentLength > requestOptions.maxTotalReferenceBytes
85
+ ) {
86
+ return jsonResponse(
87
+ {
88
+ error: `AI Image Plugin requests cannot exceed ${requestOptions.maxTotalReferenceBytes} bytes.`,
89
+ },
90
+ 413,
91
+ );
92
+ }
93
+
94
+ let formData: FormData;
95
+
96
+ // Parse the multipart payload into the prompt, optional model override, and
97
+ // the capped list of uploaded reference images.
98
+ try {
99
+ formData = await request.formData();
100
+ } catch {
101
+ return jsonResponse(
102
+ {
103
+ error: "AI Image Plugin could not read the upload payload.",
104
+ },
105
+ 400,
106
+ );
107
+ }
108
+
109
+ const { prompt, referenceImages, requestedModel } = getFormRequestPayload(
110
+ formData,
111
+ requestOptions.maxReferences,
112
+ );
113
+
114
+ if (!prompt) {
115
+ return jsonResponse({ error: "Prompt is required." }, 400);
116
+ }
117
+
118
+ // Resolve the effective model, then make sure it is both supported by the
119
+ // plugin and allowed by this installation's server config.
120
+ const modelId = requestedModel || requestOptions.defaultModel;
121
+
122
+ if (!isSupportedAiImageModelId(modelId)) {
123
+ return jsonResponse(
124
+ {
125
+ error: `AI Image Plugin does not support the model "${modelId}". Supported models are: ${SUPPORTED_AI_IMAGE_MODELS.join(", ")}.`,
126
+ },
127
+ 400,
128
+ );
129
+ }
130
+
131
+ if (!requestOptions.allowedModels.includes(modelId)) {
132
+ return jsonResponse(
133
+ {
134
+ error: `AI Image Plugin does not allow the model "${modelId}" for this installation.`,
135
+ },
136
+ 400,
137
+ );
138
+ }
139
+
140
+ const selectedModel = resolveAllowedAiImageModel(
141
+ modelId,
142
+ requestOptions.allowedModels,
143
+ );
144
+ const referenceImageError = getReferenceImageValidationError({
145
+ maxReferenceFileBytes: requestOptions.maxReferenceFileBytes,
146
+ maxTotalReferenceBytes: requestOptions.maxTotalReferenceBytes,
147
+ model: selectedModel,
148
+ referenceImages,
149
+ });
150
+
151
+ if (referenceImageError) {
152
+ return jsonResponse(
153
+ {
154
+ error: referenceImageError.error,
155
+ },
156
+ referenceImageError.status,
157
+ );
158
+ }
159
+
160
+ // Pick the provider credentials that match the selected model family.
161
+ const apiKey = getProviderApiKey(selectedModel, options);
162
+
163
+ if (!apiKey) {
164
+ return jsonResponse(
165
+ {
166
+ error: getMissingApiKeyErrorMessage(selectedModel),
167
+ },
168
+ 500,
169
+ );
170
+ }
171
+
172
+ // Delegate the actual image generation call and translate provider failures
173
+ // into a stable API response shape for the Studio client.
174
+ try {
175
+ const generatedImage = await generateImageWithModel({
176
+ apiKey,
177
+ model: selectedModel,
178
+ prompt,
179
+ referenceImages,
180
+ ...(options.geminiApiUrl ? { geminiApiUrl: options.geminiApiUrl } : {}),
181
+ });
182
+
183
+ if (!generatedImage) {
184
+ return jsonResponse(
185
+ {
186
+ error:
187
+ "AI Image Plugin returned a response, but no generated image was found.",
188
+ },
189
+ 502,
190
+ );
191
+ }
192
+
193
+ return jsonResponse({
194
+ ...generatedImage,
195
+ model: selectedModel,
196
+ } satisfies SuccessResponse);
197
+ } catch (error) {
198
+ return jsonResponse(
199
+ {
200
+ error:
201
+ getErrorMessage(error) ||
202
+ `AI Image Plugin could not reach ${getProviderDisplayName(selectedModel)}.`,
203
+ },
204
+ getErrorStatusCode(error) || 502,
205
+ );
206
+ }
207
+ }
@@ -0,0 +1,30 @@
1
+ import type { SupportedAiImageModelId } from "../utils/models";
2
+
3
+ export type GenerateImageFunction = (options: Record<string, unknown>) => Promise<{
4
+ image?: unknown;
5
+ }>;
6
+
7
+ export type GeneratedImagePayload = {
8
+ base64?: string;
9
+ mediaType?: string;
10
+ uint8Array?: Uint8Array;
11
+ };
12
+
13
+ export type SuccessResponse = {
14
+ data: string;
15
+ mimeType: string;
16
+ model: string;
17
+ };
18
+
19
+ export type RequestOptions = {
20
+ allowedModels?: SupportedAiImageModelId[];
21
+ apiKey?: string;
22
+ enforceSameOrigin?: boolean;
23
+ geminiApiUrl?: string;
24
+ googleApiKey?: string;
25
+ maxReferenceFileBytes?: number;
26
+ maxReferences?: number;
27
+ maxTotalReferenceBytes?: number;
28
+ model?: SupportedAiImageModelId;
29
+ openAiApiKey?: string;
30
+ };