gencow 0.1.294 → 0.1.296

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.
@@ -1949,11 +1949,14 @@ import { createHmac as createHmac2, randomBytes as randomBytes2, timingSafeEqual
1949
1949
 
1950
1950
  // ../core/src/v.ts
1951
1951
  var GencowValidationError = class extends Error {
1952
- statusCode = 400;
1953
- constructor(message) {
1952
+ constructor(message, validationPhase = "unknown") {
1954
1953
  super(message);
1954
+ this.validationPhase = validationPhase;
1955
1955
  this.name = "GencowValidationError";
1956
1956
  }
1957
+ validationPhase;
1958
+ statusCode = 400;
1959
+ status = 400;
1957
1960
  };
1958
1961
  var GENCOW_OPTIONAL_INNER = /* @__PURE__ */ Symbol.for("gencow.v.optionalInner");
1959
1962
  function assertStandardResult(value) {
@@ -4352,6 +4355,59 @@ function collectProcedureRouteMaps(appModule) {
4352
4355
  }
4353
4356
  return { queryProcedureMap, mutationProcedureMap, internalProcedureMap };
4354
4357
  }
4358
+ function collectStrictProcedureRouteMaps(appModule) {
4359
+ const maps = {
4360
+ queryProcedureMap: /* @__PURE__ */ new Map(),
4361
+ mutationProcedureMap: /* @__PURE__ */ new Map(),
4362
+ internalProcedureMap: /* @__PURE__ */ new Map()
4363
+ };
4364
+ const invalid = (duplicate) => {
4365
+ throw Object.assign(new Error("The application declaration is invalid."), {
4366
+ code: "RUNTIME_APP_DECLARATION_INVALID",
4367
+ ...duplicate ? { declarationKind: duplicate.kind, declarationName: duplicate.name } : {}
4368
+ });
4369
+ };
4370
+ const add = (value, crud2) => {
4371
+ const proc = asProcedureDef(value);
4372
+ if (!proc || !proc.name || !Number.isFinite(proc.inputValidationIndex) || !Number.isFinite(proc.outputValidationIndex) || crud2 && proc.kind === "internal") return invalid();
4373
+ const map2 = proc.kind === "query" ? maps.queryProcedureMap : proc.kind === "mutation" ? maps.mutationProcedureMap : maps.internalProcedureMap;
4374
+ if (map2.has(proc.name)) return invalid(proc);
4375
+ const snapshot = Object.freeze({ ...proc, middlewares: Object.freeze([...proc.middlewares]) });
4376
+ map2.set(proc.name, snapshot);
4377
+ };
4378
+ const entries = (value) => {
4379
+ if (!value || typeof value !== "object" || Array.isArray(value)) return invalid();
4380
+ try {
4381
+ return Object.values(value);
4382
+ } catch {
4383
+ return invalid();
4384
+ }
4385
+ };
4386
+ const read = (value, key) => {
4387
+ try {
4388
+ return value[key];
4389
+ } catch {
4390
+ return invalid();
4391
+ }
4392
+ };
4393
+ const candidate = resolveDefineApiCandidate(appModule);
4394
+ if (!candidate || typeof candidate !== "object") return maps;
4395
+ const procedures = read(candidate, "procedures"), crud = read(candidate, "crud");
4396
+ if (procedures !== void 0) {
4397
+ for (const value of entries(procedures)) if (value !== void 0) add(value, false);
4398
+ }
4399
+ if (crud !== void 0) {
4400
+ for (const value of entries(crud)) {
4401
+ if (value === void 0) continue;
4402
+ if (!value || typeof value !== "object" || Array.isArray(value)) invalid();
4403
+ for (const key of ["list", "get", "create", "update", "remove"]) {
4404
+ const operation = read(value, key);
4405
+ if (operation !== void 0) add(operation, true);
4406
+ }
4407
+ }
4408
+ }
4409
+ return maps;
4410
+ }
4355
4411
 
4356
4412
  // ../shared/src/introspection/workflow-runtime-catalog.ts
4357
4413
  var WORKFLOW_DEFINITION_METADATA = /* @__PURE__ */ Symbol.for("@gencow/core/workflow-definition");
@@ -7296,6 +7352,44 @@ function collectCrudCodegenMeta(appModule) {
7296
7352
 
7297
7353
  // scripts/tooling-codegen-runtime.ts
7298
7354
  import { builtinModules } from "node:module";
7355
+ import { randomUUID as randomUUID2 } from "node:crypto";
7356
+
7357
+ // ../shared/src/analyzer/consumers/auditor/application-declaration-audit.ts
7358
+ function assertAppDeclarations(appModule) {
7359
+ try {
7360
+ return collectStrictProcedureRouteMaps(appModule);
7361
+ } catch (error62) {
7362
+ let summary = "Application declarations are invalid.";
7363
+ try {
7364
+ const issue2 = error62;
7365
+ const kind = issue2?.declarationKind, name2 = issue2?.declarationName;
7366
+ if (typeof kind === "string" && ["query", "mutation", "internal"].includes(kind) && typeof name2 === "string" && /^[\p{L}\p{N}_.:-]{1,128}$/u.test(name2))
7367
+ summary = `Duplicate ${kind} declaration "${name2}".`;
7368
+ } catch {
7369
+ }
7370
+ throw Object.assign(new Error("Application declarations are invalid."), {
7371
+ code: "RUNTIME_APP_DECLARATION_INVALID",
7372
+ declarationDetail: summary
7373
+ });
7374
+ }
7375
+ }
7376
+ function auditAppDeclarations(appModule) {
7377
+ try {
7378
+ assertAppDeclarations(appModule);
7379
+ return [];
7380
+ } catch (error62) {
7381
+ return [
7382
+ {
7383
+ code: "RUNTIME_APP_DECLARATION_INVALID",
7384
+ severity: "error",
7385
+ summary: error62.declarationDetail,
7386
+ hint: "Correct malformed procedures or duplicate same-kind procedure/CRUD names, then run gencow codegen before deploying."
7387
+ }
7388
+ ];
7389
+ }
7390
+ }
7391
+
7392
+ // scripts/tooling-codegen-runtime.ts
7299
7393
  import { readFileSync as readFileSync4, statSync as statSync4 } from "node:fs";
7300
7394
  import { mkdir, mkdtemp, rm } from "node:fs/promises";
7301
7395
  import { isAbsolute as isAbsolute3, join as join7, relative as relative5, resolve as resolve11 } from "node:path";
@@ -7589,7 +7683,10 @@ function createCliRegistryExtractorDeps(options = {}) {
7589
7683
  }
7590
7684
  collectors = {
7591
7685
  collectCrudCodegenMeta: options.collectors?.collectCrudCodegenMeta ?? collectCrudCodegenMeta,
7592
- collectProcedureRouteMaps: options.collectors?.collectProcedureRouteMaps ?? collectProcedureRouteMaps,
7686
+ collectProcedureRouteMaps: (appModule2) => {
7687
+ const admitted = options.validateDeclarations ? assertAppDeclarations(appModule2) : void 0;
7688
+ return options.collectors?.collectProcedureRouteMaps ? options.collectors.collectProcedureRouteMaps(appModule2) : admitted ?? collectProcedureRouteMaps(appModule2);
7689
+ },
7593
7690
  getQueryDef: coreModule.getQueryDef,
7594
7691
  getRegisteredMutations: coreModule.getRegisteredMutations,
7595
7692
  getRegisteredQueries: coreModule.getRegisteredQueries,
@@ -7609,13 +7706,19 @@ function createCliRegistryExtractorDeps(options = {}) {
7609
7706
  };
7610
7707
  }
7611
7708
  async function extractRegistry2(input2, options = {}) {
7612
- return extractRegistry(input2, createCliRegistryExtractorDeps(options));
7709
+ try {
7710
+ return await extractRegistry(input2, createCliRegistryExtractorDeps(options));
7711
+ } catch (error62) {
7712
+ if (error62 && typeof error62 === "object" && "code" in error62 && error62.code === "RUNTIME_APP_DECLARATION_INVALID")
7713
+ Object.assign(error62, { correlationId: `declaration_${randomUUID2()}` });
7714
+ throw error62;
7715
+ }
7613
7716
  }
7614
7717
  async function runCodegen2(input2) {
7615
7718
  const fs2 = createNodeFileSystemAdapter();
7616
7719
  const processRunner = createNodeProcessRunner();
7617
7720
  const deps = {
7618
- extractRegistry: ({ projectRoot, functionsDirAbs }) => extractRegistry2({ projectRoot, functionsDirAbs }),
7721
+ extractRegistry: ({ projectRoot, functionsDirAbs }) => extractRegistry2({ projectRoot, functionsDirAbs }, { validateDeclarations: true }),
7619
7722
  extractTables: ({ projectRoot, schemaPath, schemaPaths, functionsDirAbs }) => extractTables({ projectRoot, schemaPath, schemaPaths, functionsDirAbs }, { fs: fs2, processRunner })
7620
7723
  };
7621
7724
  return runCodegen({
@@ -9622,7 +9725,7 @@ function createModuleAuditPlugin() {
9622
9725
  }
9623
9726
 
9624
9727
  // ../shared/src/analyzer/consumers/auditor/security-auditor-plugin.ts
9625
- function createSecurityAuditPlugin() {
9728
+ function createSecurityAuditPlugin(input2) {
9626
9729
  return {
9627
9730
  name: "security-auditor",
9628
9731
  version: 1,
@@ -9652,7 +9755,7 @@ function createSecurityAuditPlugin() {
9652
9755
  },
9653
9756
  value: report
9654
9757
  });
9655
- const diagnostics = [];
9758
+ const diagnostics = input2 && "appModule" in input2 ? auditAppDeclarations(input2.appModule) : [];
9656
9759
  if (report.publicQueries.length > 0) {
9657
9760
  diagnostics.push({
9658
9761
  code: "AUD_PUBLIC_QUERY",
@@ -9854,7 +9957,7 @@ async function runAppLoadedAnalysis(input2) {
9854
9957
  fixMode: "none"
9855
9958
  },
9856
9959
  utilities,
9857
- plugins: [activateAnalyzerPlugin(createSecurityAuditPlugin())],
9960
+ plugins: [activateAnalyzerPlugin(createSecurityAuditPlugin(input2))],
9858
9961
  policy: {
9859
9962
  minimumSeverityToBlockByPhase: {
9860
9963
  "loaded-analysis": "error"
@@ -30166,6 +30269,7 @@ export {
30166
30269
  GENCOW_CONFIG_DEFAULTS,
30167
30270
  USER_AUTH_SCHEMA_FILENAME,
30168
30271
  analyzeModuleImportEntries,
30272
+ assertAppDeclarations,
30169
30273
  assertProcessSuccess,
30170
30274
  assertSourceEntrypoints,
30171
30275
  assignAggregateKeys,
@@ -30178,6 +30282,7 @@ export {
30178
30282
  auditAnalyzerSelfFetch,
30179
30283
  auditAnalyzerUnsafeDbUsage,
30180
30284
  auditAnalyzerWorkflowShadowing,
30285
+ auditAppDeclarations,
30181
30286
  buildAuthSchemaGenTsFromTables,
30182
30287
  buildAuthSchemaTsFromTables,
30183
30288
  buildBetterAuthOptions,
@@ -22,6 +22,8 @@ import {
22
22
  setRealtimeChannelLegacySnapshot,
23
23
  } from "../../shared/src/introspection/index.ts";
24
24
  import { builtinModules, createRequire } from "node:module";
25
+ import { randomUUID } from "node:crypto";
26
+ import { assertAppDeclarations } from "../../shared/src/analyzer/consumers/auditor/application-declaration-audit.js";
25
27
  import { readFileSync, statSync } from "node:fs";
26
28
  import { mkdir, mkdtemp, rm } from "node:fs/promises";
27
29
  import { isAbsolute, join, relative, resolve } from "node:path";
@@ -40,6 +42,7 @@ type CoreModuleShape = {
40
42
  };
41
43
 
42
44
  type CliRegistryRuntimeOptions = {
45
+ validateDeclarations?: boolean;
43
46
  importModule?: (modulePath: string) => Promise<unknown>;
44
47
  runtime?: "bun" | "node";
45
48
  resolveAppEntry?: (functionsDirAbs: string) => string;
@@ -428,7 +431,12 @@ function createCliRegistryExtractorDeps(options: CliRegistryRuntimeOptions = {})
428
431
  }
429
432
  collectors = {
430
433
  collectCrudCodegenMeta: options.collectors?.collectCrudCodegenMeta ?? collectCrudCodegenMeta,
431
- collectProcedureRouteMaps: options.collectors?.collectProcedureRouteMaps ?? collectProcedureRouteMaps,
434
+ collectProcedureRouteMaps: (appModule) => {
435
+ const admitted = options.validateDeclarations ? assertAppDeclarations(appModule) : undefined;
436
+ return options.collectors?.collectProcedureRouteMaps
437
+ ? options.collectors.collectProcedureRouteMaps(appModule)
438
+ : admitted ?? collectProcedureRouteMaps(appModule);
439
+ },
432
440
  getQueryDef: coreModule.getQueryDef,
433
441
  getRegisteredMutations: coreModule.getRegisteredMutations,
434
442
  getRegisteredQueries: coreModule.getRegisteredQueries,
@@ -453,14 +461,20 @@ export async function extractRegistry(
453
461
  input: RegistryExtractorInput,
454
462
  options: CliRegistryRuntimeOptions = {},
455
463
  ) {
456
- return extractRegistryInternal(input, createCliRegistryExtractorDeps(options));
464
+ try {
465
+ return await extractRegistryInternal(input, createCliRegistryExtractorDeps(options));
466
+ } catch (error) {
467
+ if (error && typeof error === "object" && "code" in error && error.code === "RUNTIME_APP_DECLARATION_INVALID")
468
+ Object.assign(error, { correlationId: `declaration_${randomUUID()}` });
469
+ throw error;
470
+ }
457
471
  }
458
472
 
459
473
  export async function runCodegen(input: RunCodegenInput) {
460
474
  const fs = createNodeFileSystemAdapter();
461
475
  const processRunner = createNodeProcessRunner();
462
476
  const deps: Partial<RunCodegenDeps> = {
463
- extractRegistry: ({ projectRoot, functionsDirAbs }) => extractRegistry({ projectRoot, functionsDirAbs }),
477
+ extractRegistry: ({ projectRoot, functionsDirAbs }) => extractRegistry({ projectRoot, functionsDirAbs }, { validateDeclarations: true }),
464
478
  extractTables: ({ projectRoot, schemaPath, schemaPaths, functionsDirAbs }) =>
465
479
  extractTables({ projectRoot, schemaPath, schemaPaths, functionsDirAbs }, { fs, processRunner }),
466
480
  };
@@ -3,6 +3,7 @@
3
3
  import { getProviderState, type GencowAIProvider } from "./ai-provider";
4
4
  import {
5
5
  assertValidImageOptions,
6
+ buildImageRequestBody,
6
7
  sanitizeImageErrorMessage,
7
8
  type AiImageFormat,
8
9
  type AiImageGenerateOptions,
@@ -233,21 +234,6 @@ function mapResult(body: Json, jobId: string): AiImageJobResult {
233
234
  };
234
235
  }
235
236
 
236
- function buildBody(options: AiImageGenerateOptions): Json {
237
- const format = options.format ?? "png";
238
- return {
239
- model: options.model ?? "gpt-image-2",
240
- prompt: options.prompt.normalize("NFC").trim(),
241
- n: 1,
242
- quality: options.quality ?? "auto",
243
- output_format: format,
244
- ...(options.size && options.size !== "auto" ? { size: options.size } : {}),
245
- ...(options.outputCompression !== undefined ? { output_compression: options.outputCompression } : {}),
246
- ...(options.background ? { background: options.background } : {}),
247
- ...(options.moderation ? { moderation: options.moderation } : {}),
248
- };
249
- }
250
-
251
237
  export function createImageJobsClient(provider?: GencowAIProvider, deps: ImageJobsDeps = {}) {
252
238
  const sleep = deps.sleep ?? abortableSleep;
253
239
  const random = deps.random ?? Math.random;
@@ -362,7 +348,7 @@ export function createImageJobsClient(provider?: GencowAIProvider, deps: ImageJo
362
348
  throw invalid("AI_IMAGE_REQUEST_INVALID", cause instanceof Error ? cause.message : String(cause), "Fix the image options and call start() again; nothing was sent.");
363
349
  }
364
350
  transport();
365
- const body = buildBody(options);
351
+ const body = buildImageRequestBody(options) as Json;
366
352
  const maxRetries = Math.max(0, options.maxRetries ?? 2);
367
353
  let waited = 0;
368
354
  const withKey = (error: GencowAIImageJobError, retriedHint: boolean) => {
@@ -2,7 +2,8 @@
2
2
 
3
3
  import { generateImage as aiGenerateImage, type GenerateImageResult } from "ai";
4
4
  import type { ImageModelV3 } from "@ai-sdk/provider";
5
- import { consumeGencowImageCredits, ensureGencowAI } from "./ai-provider";
5
+ import type { FetchFunction } from "@ai-sdk/provider-utils";
6
+ import { consumeGencowImageCredits, ensureGencowAI, getProviderState, type GencowAIProvider } from "./ai-provider";
6
7
  import { wrapGencowAIError } from "./ai-errors";
7
8
 
8
9
  type ImageModelTransport = {
@@ -15,6 +16,8 @@ type ImageModelGenerateResult = Awaited<ReturnType<ImageModelV3["doGenerate"]>>;
15
16
  type GencowImageDeps = {
16
17
  ensureReady: () => Promise<ImageModelTransport>;
17
18
  consumeCredits: () => Promise<number>;
19
+ /** Provider state for requests that carry reference images (they bypass the AI SDK transport). */
20
+ referenceTransport: () => ImageReferenceTransport;
18
21
  };
19
22
 
20
23
  export type AiImageSize = "auto" | `${number}x${number}`;
@@ -32,6 +35,11 @@ export interface AiImageGenerateOptions {
32
35
  outputCompression?: number;
33
36
  background?: AiImageBackground;
34
37
  moderation?: AiImageModeration;
38
+ /**
39
+ * Up to 5 images (20 MB in total) that the new image should stay consistent with: base64 data URLs, a previous
40
+ * result ({ base64, mimeType }), or { bytes, mimeType }. Web URLs are rejected. Needs the deployed AI proxy.
41
+ */
42
+ referenceImages?: AiReferenceImage[];
35
43
  }
36
44
 
37
45
  export interface AiGeneratedImage {
@@ -76,6 +84,7 @@ export function assertValidImageOptions(options: AiImageGenerateOptions): void {
76
84
  if (options.moderation !== undefined && options.moderation !== "auto") {
77
85
  throw new Error("moderation must be auto");
78
86
  }
87
+ if (options.referenceImages !== undefined) assertValidReferenceImages(options.referenceImages);
79
88
  }
80
89
 
81
90
  export function sanitizeImageErrorMessage(value: string): string {
@@ -143,12 +152,27 @@ function mapGenerateImageResult(
143
152
  };
144
153
  }
145
154
 
155
+ function mapCallFilesToReferenceImages(callOptions: ImageModelCallOptions): AiReferenceImage[] {
156
+ if (callOptions.mask) {
157
+ throw new Error(
158
+ "Gencow image generation does not support a mask (inpainting). Pass the reference images without a mask.",
159
+ );
160
+ }
161
+ return (callOptions.files ?? []).map((file) => {
162
+ if (file.type === "url") return file.url;
163
+ if (typeof file.data === "string") return { base64: file.data, mimeType: file.mediaType };
164
+ return { bytes: file.data, mimeType: file.mediaType };
165
+ });
166
+ }
167
+
146
168
  function mapCallOptionsToFacadeOptions(
147
169
  modelId: string,
148
170
  callOptions: ImageModelCallOptions,
149
171
  ): AiImageGenerateOptions {
150
172
  const openai = callOptions.providerOptions?.openai as Record<string, unknown> | undefined;
173
+ const referenceImages = mapCallFilesToReferenceImages(callOptions);
151
174
  return {
175
+ ...(referenceImages.length > 0 ? { referenceImages } : {}),
152
176
  prompt: callOptions.prompt ?? "",
153
177
  model: modelId,
154
178
  ...(callOptions.size ? { size: callOptions.size as AiImageSize } : {}),
@@ -186,11 +210,17 @@ async function runImageGeneration(
186
210
  ctx: {
187
211
  getModel: () => Promise<ImageModelV3>;
188
212
  consumeCredits: () => Promise<number>;
213
+ referenceTransport: () => ImageReferenceTransport;
189
214
  },
190
215
  ): Promise<AiImageGenerateResult> {
191
216
  const format = options.format ?? "png";
192
217
 
193
218
  try {
219
+ if (options.referenceImages && options.referenceImages.length > 0) {
220
+ // The AI SDK transport would turn references into a multipart /images/edits call, which the Gateway does not
221
+ // expose; the Gateway takes JSON `images` on /images/generations instead.
222
+ return await generateImageWithReferences(ctx.referenceTransport(), { ...options, model: modelId });
223
+ }
194
224
  const result = await aiGenerateImage({
195
225
  model: await ctx.getModel(),
196
226
  ...mapToGenerateImageOptions({ ...options, model: modelId }),
@@ -221,23 +251,301 @@ export function createGencowImageModel(
221
251
  return transport.imageModel(modelId);
222
252
  },
223
253
  consumeCredits: deps.consumeCredits,
254
+ referenceTransport: deps.referenceTransport,
224
255
  });
225
256
  return mapFacadeResultToDoGenerate(result);
226
257
  },
227
258
  };
228
259
  }
229
260
 
230
- async function generate(options: AiImageGenerateOptions): Promise<AiImageGenerateResult> {
231
- assertValidImageOptions(options);
232
- const model = options.model ?? "gpt-image-2";
233
- const gencow = await ensureGencowAI();
261
+ // Reference images for image generation (spec-gateway-image-generation-image-input-20261118.md).
262
+ // The Gateway accepts base64 data URLs only; it never fetches a web URL. The limits below mirror the Gateway's, so a
263
+ // request that cannot succeed is rejected here before anything is sent or charged. The Gateway still validates the
264
+ // real image bytes.
265
+
266
+ /** A base64 data URL, a previous result ({ base64, mimeType }), or raw bytes with their media type. */
267
+ export type AiReferenceImage =
268
+ | string
269
+ | { base64: string; mimeType: string }
270
+ | { bytes: Uint8Array | ArrayBuffer; mimeType: string };
271
+
272
+ export const MAX_REFERENCE_IMAGES = 5;
273
+ export const MAX_REFERENCE_IMAGE_TOTAL_BYTES = 20 * 1024 * 1024;
274
+ const SUPPORTED_MEDIA_TYPES = ["image/png", "image/jpeg", "image/webp"];
275
+ const SUPPORTED_LIST = "png, jpeg, or webp";
276
+ const DATA_URL_RE = /^data:([^;,]+);base64,(.*)$/is;
277
+ const BASE64_BODY_RE = /^[A-Za-z0-9+/]+={0,2}$/;
278
+ const IMAGE_DATA_RE = /(?:data:image\/[a-z0-9.+-]+;base64,)?[A-Za-z0-9+/]{80,}={0,2}/g;
279
+
280
+ type PreparedReference = { bytes: number; toDataUrl: () => string };
281
+
282
+ function fail(message: string): never {
283
+ throw new Error(message);
284
+ }
285
+
286
+ function base64ByteLength(base64: string): number {
287
+ const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
288
+ return Math.floor((base64.length * 3) / 4) - padding;
289
+ }
290
+
291
+ function encodeBytes(bytes: Uint8Array): string {
292
+ let binary = "";
293
+ const chunk = 0x8000;
294
+ for (let i = 0; i < bytes.length; i += chunk) {
295
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
296
+ }
297
+ return btoa(binary);
298
+ }
299
+
300
+ function checkMediaType(value: string): string {
301
+ const mediaType = value.trim().toLowerCase();
302
+ if (!SUPPORTED_MEDIA_TYPES.includes(mediaType)) {
303
+ fail(`Reference image type ${mediaType || "(missing)"} is not supported; use ${SUPPORTED_LIST}.`);
304
+ }
305
+ return mediaType;
306
+ }
307
+
308
+ function prepareDataUrl(value: string): PreparedReference {
309
+ const trimmed = value.trim();
310
+ if (/^[a-z][a-z0-9+.-]*:/i.test(trimmed) && !/^data:/i.test(trimmed)) {
311
+ fail(
312
+ "Reference images cannot be web URLs; the server does not download images. Pass a base64 data URL (data:image/png;base64,...).",
313
+ );
314
+ }
315
+ const match = DATA_URL_RE.exec(trimmed);
316
+ if (!match) fail("A reference image must be a base64 data URL (data:image/png;base64,...).");
317
+ const mediaType = checkMediaType(match![1]!);
318
+ const base64 = match![2]!.replace(/\s+/g, "");
319
+ if (!base64 || base64.length % 4 === 1 || !BASE64_BODY_RE.test(base64)) {
320
+ fail("A reference image is not valid base64.");
321
+ }
322
+ return { bytes: base64ByteLength(base64), toDataUrl: () => `data:${mediaType};base64,${base64}` };
323
+ }
234
324
 
235
- return runImageGeneration(model, options, {
236
- getModel: async () => gencow.imageModel(model),
237
- consumeCredits: () => consumeGencowImageCredits(gencow),
325
+ function prepareOne(item: AiReferenceImage): PreparedReference {
326
+ if (typeof item === "string") return prepareDataUrl(item);
327
+ if (item === null || typeof item !== "object") {
328
+ fail("A reference image must be a base64 data URL, { base64, mimeType }, or { bytes, mimeType }.");
329
+ }
330
+ const candidate = item as { base64?: unknown; bytes?: unknown; mimeType?: unknown };
331
+ const mediaType = checkMediaType(typeof candidate.mimeType === "string" ? candidate.mimeType : "");
332
+ if (typeof candidate.base64 === "string") {
333
+ return prepareDataUrl(
334
+ candidate.base64.trim().startsWith("data:") ? candidate.base64 : `data:${mediaType};base64,${candidate.base64}`,
335
+ );
336
+ }
337
+ if (candidate.bytes instanceof Uint8Array || candidate.bytes instanceof ArrayBuffer) {
338
+ const bytes = candidate.bytes instanceof Uint8Array ? candidate.bytes : new Uint8Array(candidate.bytes);
339
+ if (bytes.byteLength === 0) fail("A reference image must not be empty.");
340
+ return { bytes: bytes.byteLength, toDataUrl: () => `data:${mediaType};base64,${encodeBytes(bytes)}` };
341
+ }
342
+ return fail("A reference image must be a base64 data URL, { base64, mimeType }, or { bytes, mimeType }.");
343
+ }
344
+
345
+ function prepareReferenceImages(references: unknown): PreparedReference[] {
346
+ if (!Array.isArray(references)) fail("referenceImages must be an array.");
347
+ const list = references as AiReferenceImage[];
348
+ if (list.length > MAX_REFERENCE_IMAGES) {
349
+ fail(`referenceImages accepts at most ${MAX_REFERENCE_IMAGES} images per request.`);
350
+ }
351
+ let total = 0;
352
+ return list.map((item) => {
353
+ const prepared = prepareOne(item);
354
+ total += prepared.bytes;
355
+ if (total > MAX_REFERENCE_IMAGE_TOTAL_BYTES) {
356
+ fail("referenceImages exceed 20 MB in total; resize or compress the images.");
357
+ }
358
+ return prepared;
238
359
  });
239
360
  }
240
361
 
241
- export const image = {
242
- generate,
362
+ /** Throws a plain Error naming the problem; nothing is encoded or sent. */
363
+ export function assertValidReferenceImages(references: unknown): void {
364
+ prepareReferenceImages(references);
365
+ }
366
+
367
+ /** The Gateway's `images` field: one `{ image_url: <data URL> }` per reference. */
368
+ export function referenceImagesToRequest(references: readonly AiReferenceImage[]): Array<{ image_url: string }> {
369
+ return prepareReferenceImages(references).map((item) => ({ image_url: item.toDataUrl() }));
370
+ }
371
+
372
+ /** One request body for /images/generations and /images/jobs, so the two paths cannot drift. */
373
+ export function buildImageRequestBody(options: AiImageGenerateOptions): Record<string, unknown> {
374
+ const references = options.referenceImages ?? [];
375
+ return {
376
+ model: options.model ?? "gpt-image-2",
377
+ prompt: options.prompt.normalize("NFC").trim(),
378
+ n: 1,
379
+ quality: options.quality ?? "auto",
380
+ output_format: options.format ?? "png",
381
+ ...(options.size && options.size !== "auto" ? { size: options.size } : {}),
382
+ ...(options.outputCompression !== undefined ? { output_compression: options.outputCompression } : {}),
383
+ ...(options.background ? { background: options.background } : {}),
384
+ ...(options.moderation ? { moderation: options.moderation } : {}),
385
+ ...(references.length > 0 ? { images: referenceImagesToRequest(references) } : {}),
386
+ };
387
+ }
388
+
389
+ export type GencowAIImageErrorInit = {
390
+ code: string;
391
+ message: string;
392
+ status?: number;
393
+ param?: string;
394
+ stage: string;
395
+ stateChanged: boolean;
396
+ retryable: boolean;
397
+ nextAction: string;
398
+ requestId?: string;
399
+ };
400
+
401
+ /** Failure of a synchronous image request that carried reference images. */
402
+ export class GencowAIImageError extends Error {
403
+ readonly code: string;
404
+ readonly status?: number;
405
+ readonly param?: string;
406
+ readonly stage: string;
407
+ readonly stateChanged: boolean;
408
+ readonly retryable: boolean;
409
+ readonly nextAction: string;
410
+ readonly requestId?: string;
411
+
412
+ constructor(init: GencowAIImageErrorInit) {
413
+ super(redact(init.message));
414
+ this.name = "GencowAIImageError";
415
+ this.code = init.code;
416
+ this.status = init.status;
417
+ this.param = init.param;
418
+ this.stage = init.stage;
419
+ this.stateChanged = init.stateChanged;
420
+ this.retryable = init.retryable;
421
+ this.nextAction = init.nextAction;
422
+ this.requestId = init.requestId;
423
+ }
424
+ }
425
+
426
+ function redact(value: string): string {
427
+ const cleaned = value.replace(IMAGE_DATA_RE, "[redacted_image_data]").trim();
428
+ return cleaned ? (cleaned.length > 300 ? `${cleaned.slice(0, 300)}...` : cleaned) : "AI image request failed";
429
+ }
430
+
431
+ /** What a synchronous request needs from the provider state. */
432
+ export type ImageReferenceTransport = {
433
+ proxyUrl: string | undefined;
434
+ apiKey: string | undefined;
435
+ headers: Record<string, string> | undefined;
436
+ fetch: FetchFunction;
243
437
  };
438
+
439
+ type Json = Record<string, any>;
440
+
441
+ async function errorFromResponse(response: Response): Promise<GencowAIImageError> {
442
+ const body = ((await response.json().catch(() => ({}))) ?? {}) as Json;
443
+ const err = (body.error ?? {}) as Json;
444
+ const diagnostic = (body.diagnostic ?? {}) as Json;
445
+ const transient = response.status === 429 || response.status === 503;
446
+ return new GencowAIImageError({
447
+ code: typeof err.code === "string" ? err.code : `HTTP_${response.status}`,
448
+ message: typeof err.message === "string" ? err.message : `Image request failed with HTTP ${response.status}`,
449
+ status: response.status,
450
+ ...(typeof err.param === "string" ? { param: err.param } : {}),
451
+ stage: typeof diagnostic.stage === "string" ? diagnostic.stage : "request",
452
+ stateChanged: diagnostic.state_changed === true,
453
+ retryable: typeof diagnostic.retryable === "boolean" ? diagnostic.retryable : transient,
454
+ nextAction:
455
+ typeof diagnostic.next_action === "string" && diagnostic.next_action
456
+ ? diagnostic.next_action
457
+ : "Review the error code and message, then retry only if retryable is true.",
458
+ requestId:
459
+ typeof diagnostic.request_id === "string" ? diagnostic.request_id : (response.headers.get("x-request-id") ?? undefined),
460
+ });
461
+ }
462
+
463
+ /**
464
+ * Synchronous generation with reference images. The Gateway answers in the OpenAI image shape; the charge comes from
465
+ * `_gencow.creditsCharged`. Not retried here: a retry could be charged twice, so use ai.image.start() with an
466
+ * idempotencyKey when retry safety matters.
467
+ */
468
+ export async function generateImageWithReferences(
469
+ transport: ImageReferenceTransport,
470
+ options: AiImageGenerateOptions,
471
+ ): Promise<AiImageGenerateResult> {
472
+ if (!transport.proxyUrl) {
473
+ throw new GencowAIImageError({
474
+ code: "AI_IMAGE_REFERENCE_PROXY_REQUIRED",
475
+ message: "Reference images need the Gencow AI proxy; local direct provider mode does not support them.",
476
+ stage: "configuration",
477
+ stateChanged: false,
478
+ retryable: false,
479
+ nextAction:
480
+ "Use reference images in a deployed app (or with GENCOW_AI_PROXY_URL set), or generate without referenceImages locally.",
481
+ });
482
+ }
483
+ const body = buildImageRequestBody(options);
484
+ let response: Response;
485
+ try {
486
+ response = await transport.fetch(`${transport.proxyUrl.replace(/\/+$/, "")}/images/generations`, {
487
+ method: "POST",
488
+ headers: {
489
+ "content-type": "application/json",
490
+ ...(transport.headers ?? {}),
491
+ ...(transport.apiKey ? { authorization: `Bearer ${transport.apiKey}` } : {}),
492
+ },
493
+ body: JSON.stringify(body),
494
+ });
495
+ } catch (cause) {
496
+ throw new GencowAIImageError({
497
+ code: "AI_IMAGE_NETWORK_ERROR",
498
+ message: `Image request failed before a response arrived: ${cause instanceof Error ? cause.message : String(cause)}`,
499
+ stage: "transport",
500
+ stateChanged: true,
501
+ retryable: false,
502
+ nextAction:
503
+ "The image may still have been generated and charged. Check your credit balance before retrying, or use ai.image.start() with an idempotencyKey for retry-safe generation.",
504
+ });
505
+ }
506
+ if (!response.ok) throw await errorFromResponse(response);
507
+
508
+ const result = ((await response.json()) ?? {}) as Json;
509
+ const data = Array.isArray(result.data) ? (result.data as Json[]) : [];
510
+ const format = options.format ?? "png";
511
+ const fallbackType = format === "jpeg" ? "image/jpeg" : format === "webp" ? "image/webp" : "image/png";
512
+ const usage = result.usage as Json | undefined;
513
+ return {
514
+ images: data.map((item) => ({
515
+ base64: String(item.b64_json ?? ""),
516
+ mimeType: typeof item.mime_type === "string" ? item.mime_type : fallbackType,
517
+ ...(typeof item.revised_prompt === "string" && item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {}),
518
+ })),
519
+ ...(usage
520
+ ? {
521
+ usage: {
522
+ inputTokens: usage.prompt_tokens,
523
+ outputTokens: usage.completion_tokens,
524
+ totalTokens: usage.total_tokens,
525
+ },
526
+ }
527
+ : {}),
528
+ creditsCharged: typeof result._gencow?.creditsCharged === "number" ? result._gencow.creditsCharged : 0,
529
+ model: typeof result.model === "string" ? result.model : (options.model ?? "gpt-image-2"),
530
+ };
531
+ }
532
+
533
+ export function createImageClient(provider?: GencowAIProvider) {
534
+ async function generate(options: AiImageGenerateOptions): Promise<AiImageGenerateResult> {
535
+ assertValidImageOptions(options);
536
+ const model = options.model ?? "gpt-image-2";
537
+ // The proxy health check belongs to the AI SDK transport only; a reference-image request goes straight to the
538
+ // Gateway and must not wait for it.
539
+ return runImageGeneration(model, options, {
540
+ getModel: async () => {
541
+ const gencow = await ensureGencowAI(provider);
542
+ return gencow.imageModel(model);
543
+ },
544
+ consumeCredits: () => consumeGencowImageCredits(provider),
545
+ referenceTransport: () => getProviderState(provider),
546
+ });
547
+ }
548
+ return { generate };
549
+ }
550
+
551
+ export const image = createImageClient();