@jini-ai/integrations 0.4.2 → 0.4.3

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.
Files changed (116) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/api-connections/access-token.d.ts +9 -0
  3. package/dist/api-connections/access-token.js +92 -0
  4. package/dist/api-connections/account-actions.d.ts +40 -0
  5. package/dist/api-connections/account-actions.js +110 -0
  6. package/dist/api-connections/attempt-state.d.ts +28 -0
  7. package/dist/api-connections/attempt-state.js +73 -0
  8. package/dist/api-connections/authorization.d.ts +45 -0
  9. package/dist/api-connections/authorization.js +120 -0
  10. package/dist/api-connections/deps.d.ts +41 -0
  11. package/dist/api-connections/deps.js +13 -0
  12. package/dist/api-connections/descriptor.d.ts +6 -0
  13. package/dist/api-connections/descriptor.js +111 -0
  14. package/dist/api-connections/errors.d.ts +23 -0
  15. package/dist/api-connections/errors.js +24 -0
  16. package/dist/api-connections/finish-authorization.d.ts +24 -0
  17. package/dist/api-connections/finish-authorization.js +117 -0
  18. package/dist/api-connections/index.d.ts +18 -0
  19. package/dist/api-connections/index.js +10 -0
  20. package/dist/api-connections/install-credential.d.ts +19 -0
  21. package/dist/api-connections/install-credential.js +12 -0
  22. package/dist/api-connections/keys.d.ts +27 -0
  23. package/dist/api-connections/keys.js +22 -0
  24. package/dist/api-connections/ports.d.ts +73 -0
  25. package/dist/api-connections/ports.js +2 -0
  26. package/dist/api-connections/records.d.ts +27 -0
  27. package/dist/api-connections/records.js +52 -0
  28. package/dist/api-connections/request-checks.d.ts +18 -0
  29. package/dist/api-connections/request-checks.js +67 -0
  30. package/dist/api-connections/service.d.ts +25 -0
  31. package/dist/api-connections/service.js +26 -0
  32. package/dist/api-connections/status.d.ts +28 -0
  33. package/dist/api-connections/status.js +36 -0
  34. package/dist/api-connections/token-store/errors.d.ts +20 -0
  35. package/dist/api-connections/token-store/errors.js +38 -0
  36. package/dist/api-connections/token-store/index.d.ts +6 -0
  37. package/dist/api-connections/token-store/index.js +6 -0
  38. package/dist/api-connections/token-store/record.d.ts +69 -0
  39. package/dist/api-connections/token-store/record.js +97 -0
  40. package/dist/api-connections/token-store/vault-token-store.d.ts +26 -0
  41. package/dist/api-connections/token-store/vault-token-store.js +215 -0
  42. package/dist/api-connections/types.d.ts +101 -0
  43. package/dist/api-connections/types.js +9 -0
  44. package/dist/credentialed-http/auth-schemes.js +8 -4
  45. package/dist/credentialed-http/credentialed-request.js +47 -77
  46. package/dist/credentialed-http/response-redaction.d.ts +5 -0
  47. package/dist/credentialed-http/response-redaction.js +62 -0
  48. package/dist/media-providers/catalog.d.ts +3 -1
  49. package/dist/media-providers/catalog.js +3 -1
  50. package/dist/media-providers/dispatch/async-operation-store.d.ts +31 -0
  51. package/dist/media-providers/dispatch/async-operation-store.js +75 -37
  52. package/dist/media-providers/dispatch/builtin-vendors.d.ts +1 -1
  53. package/dist/media-providers/dispatch/context.js +10 -2
  54. package/dist/media-providers/dispatch/engine.d.ts +6 -3
  55. package/dist/media-providers/dispatch/engine.js +99 -109
  56. package/dist/media-providers/dispatch/index.d.ts +4 -2
  57. package/dist/media-providers/dispatch/index.js +3 -1
  58. package/dist/media-providers/dispatch/media-provider-registry.d.ts +62 -0
  59. package/dist/media-providers/dispatch/media-provider-registry.js +141 -0
  60. package/dist/media-providers/dispatch/node.d.ts +13 -0
  61. package/dist/media-providers/dispatch/node.js +24 -0
  62. package/dist/media-providers/dispatch/openai-compatible.d.ts +1 -1
  63. package/dist/media-providers/dispatch/openai-compatible.js +90 -87
  64. package/dist/media-providers/dispatch/operation-runtime.js +116 -89
  65. package/dist/media-providers/dispatch/outbound.d.ts +8 -4
  66. package/dist/media-providers/dispatch/outbound.js +27 -26
  67. package/dist/media-providers/dispatch/providers/aihubmix.d.ts +1 -1
  68. package/dist/media-providers/dispatch/providers/aihubmix.js +61 -56
  69. package/dist/media-providers/dispatch/providers/custom-image.d.ts +1 -1
  70. package/dist/media-providers/dispatch/providers/elevenlabs.d.ts +1 -1
  71. package/dist/media-providers/dispatch/providers/fishaudio.d.ts +1 -1
  72. package/dist/media-providers/dispatch/providers/grok.d.ts +1 -1
  73. package/dist/media-providers/dispatch/providers/imagerouter-video-async.d.ts +1 -1
  74. package/dist/media-providers/dispatch/providers/imagerouter-video-async.js +53 -49
  75. package/dist/media-providers/dispatch/providers/imagerouter.d.ts +1 -1
  76. package/dist/media-providers/dispatch/providers/imagerouter.js +11 -24
  77. package/dist/media-providers/dispatch/providers/minimax.d.ts +1 -1
  78. package/dist/media-providers/dispatch/providers/nanobanana.d.ts +1 -1
  79. package/dist/media-providers/dispatch/providers/nanobanana.js +22 -30
  80. package/dist/media-providers/dispatch/providers/openai.d.ts +1 -1
  81. package/dist/media-providers/dispatch/providers/openai.js +51 -47
  82. package/dist/media-providers/dispatch/providers/openrouter.d.ts +1 -1
  83. package/dist/media-providers/dispatch/providers/openrouter.js +52 -37
  84. package/dist/media-providers/dispatch/providers/senseaudio.d.ts +1 -1
  85. package/dist/media-providers/dispatch/providers/senseaudio.js +47 -28
  86. package/dist/media-providers/dispatch/providers/volcengine.d.ts +1 -1
  87. package/dist/media-providers/dispatch/response-parsers.js +37 -21
  88. package/dist/media-providers/dispatch/sqlite-async-operation-store.js +9 -29
  89. package/dist/media-providers/dispatch/ssrf-guard.d.ts +3 -2
  90. package/dist/media-providers/dispatch/ssrf-guard.js +6 -5
  91. package/dist/media-providers/dispatch/types.d.ts +76 -2
  92. package/dist/media-providers/dispatch/vendor-adapter.d.ts +2 -43
  93. package/dist/media-providers/dispatch/vendor-adapter.js +2 -2
  94. package/dist/media-providers/dispatch/vendor-registry-core.d.ts +24 -0
  95. package/dist/media-providers/dispatch/vendor-registry-core.js +34 -0
  96. package/dist/media-providers/dispatch/vendor-registry.d.ts +10 -36
  97. package/dist/media-providers/dispatch/vendor-registry.js +14 -42
  98. package/dist/media-providers/policy.js +25 -17
  99. package/dist/media-providers/providers.d.ts +5 -0
  100. package/dist/media-providers/providers.js +2 -0
  101. package/dist/media-providers/sqlite-task-store.js +12 -80
  102. package/dist/media-providers/staging.js +77 -58
  103. package/dist/media-providers/task-lifecycle.d.ts +33 -0
  104. package/dist/media-providers/task-lifecycle.js +124 -0
  105. package/dist/media-providers/task-store.js +8 -86
  106. package/dist/media-providers/ui-defaults.d.ts +10 -0
  107. package/dist/media-providers/ui-defaults.js +167 -0
  108. package/dist/media-providers/video-request.js +112 -90
  109. package/dist/webhooks/delivery.d.ts +14 -0
  110. package/dist/webhooks/delivery.js +41 -10
  111. package/dist/webhooks/index.d.ts +1 -0
  112. package/dist/webhooks/index.js +1 -0
  113. package/dist/webhooks/ports.d.ts +23 -0
  114. package/dist/webhooks/worker.d.ts +83 -0
  115. package/dist/webhooks/worker.js +105 -0
  116. package/package.json +31 -8
@@ -45,6 +45,40 @@ function retryAfterMsFrom(resp) {
45
45
  const seconds = Number(raw);
46
46
  return Number.isFinite(seconds) && seconds > 0 ? seconds * 1_000 : undefined;
47
47
  }
48
+ /** The wire model, size and length one request is for — derived from the context, so submit and poll agree. */
49
+ function videoMetaFor({ ctx, config }) {
50
+ return {
51
+ wireModel: (config.wireModel || ctx.wireModel).trim(),
52
+ size: imageRouterSizeFor({ aspect: ctx.aspect, surface: 'video' }),
53
+ seconds: typeof ctx.length === 'number' ? ctx.length : 'auto',
54
+ };
55
+ }
56
+ /** Decodes an OpenAI-shaped `{ data: [...] }` body into the completed render result. */
57
+ async function completedVideo({ data, ctx, meta }) {
58
+ const bytes = await bytesFromOpenAICompatibleData({ data, providerTag: 'imagerouter video' }, ctx);
59
+ const { wireModel, size, seconds } = meta;
60
+ return {
61
+ kind: 'complete',
62
+ result: {
63
+ bytes,
64
+ providerNote: `imagerouter/${wireModel} · ${size} · ${seconds === 'auto' ? 'auto' : `${seconds}s`} · ${bytes.length} bytes`,
65
+ suggestedExt: '.mp4',
66
+ },
67
+ };
68
+ }
69
+ /** A vendor-reported terminal failure, or `undefined` while the job is not in a failed state. */
70
+ function failedOutcome(data) {
71
+ const status = typeof data.status === 'string' ? data.status.toLowerCase() : '';
72
+ if (!TERMINAL_FAILED_STATUSES.has(status))
73
+ return undefined;
74
+ const error = data.error;
75
+ const detail = typeof error?.message === 'string' && error.message ? error.message : status;
76
+ return { kind: 'failed', message: `imagerouter video job failed: ${detail}` };
77
+ }
78
+ function retryAfterField(resp) {
79
+ const retryAfterMs = retryAfterMsFrom(resp);
80
+ return retryAfterMs !== undefined ? { retryAfterMs } : {};
81
+ }
48
82
  /**
49
83
  * Builds the ImageRouter video polling adapter for a given endpoint configuration.
50
84
  *
@@ -52,8 +86,7 @@ function retryAfterMsFrom(resp) {
52
86
  * context's own `wireModel`.
53
87
  * @complexity O(1) per built request; one vendor round trip per parse.
54
88
  */
55
- export function createImageRouterVideoPollingAdapter(_required, optional = {}) {
56
- const config = optional;
89
+ export function createImageRouterVideoPollingAdapter(_required, config = {}) {
57
90
  const baseUrl = trimTrailingSlash((config.baseUrl || DEFAULT_BASE_URL).trim());
58
91
  return {
59
92
  expectedLatencyClass: 'slow',
@@ -61,43 +94,30 @@ export function createImageRouterVideoPollingAdapter(_required, optional = {}) {
61
94
  // not have landed cannot be safely re-issued — a duplicate submit is a duplicate charge.
62
95
  submitIsIdempotent: false,
63
96
  buildSubmitRequest({ ctx }) {
64
- const wireModel = (config.wireModel || ctx.wireModel).trim();
65
- const seconds = typeof ctx.length === 'number' ? ctx.length : 'auto';
66
- const size = imageRouterSizeFor({ aspect: ctx.aspect, surface: 'video' });
97
+ const meta = videoMetaFor({ ctx, config });
67
98
  return {
68
99
  url: `${baseUrl}/videos/generations`,
69
- init: withUnsignedRequestInit({ ctx: ctx, init: {
100
+ init: withUnsignedRequestInit({ ctx, init: {
70
101
  method: 'POST',
71
102
  headers: { 'content-type': 'application/json' },
72
103
  body: JSON.stringify({
73
104
  prompt: ctx.prompt || 'A short cinematic clip.',
74
- model: wireModel,
75
- size,
76
- seconds,
105
+ model: meta.wireModel,
106
+ size: meta.size,
107
+ seconds: meta.seconds,
77
108
  response_format: 'b64_json',
78
109
  }),
79
110
  } }),
80
- meta: { wireModel, size, seconds },
111
+ meta,
81
112
  };
82
113
  },
83
114
  async parseSubmitResponse({ resp, ctx, request }) {
84
115
  const data = (await parseOpenAICompatibleJson(resp, 'imagerouter video'));
85
- if (Array.isArray(data.data)) {
86
- const bytes = await bytesFromOpenAICompatibleData({ data, providerTag: 'imagerouter video' }, ctx);
87
- const { wireModel, size, seconds } = request.meta;
88
- return {
89
- kind: 'complete',
90
- result: {
91
- bytes,
92
- providerNote: `imagerouter/${wireModel} · ${size} · ${seconds === 'auto' ? 'auto' : `${seconds}s`} · ${bytes.length} bytes`,
93
- suggestedExt: '.mp4',
94
- },
95
- };
96
- }
116
+ if (Array.isArray(data.data))
117
+ return completedVideo({ data, ctx, meta: request.meta });
97
118
  if (typeof data.id === 'string' && data.id) {
98
119
  // Only the job handle is persisted — no credential, no request body.
99
- const retryAfterMs = retryAfterMsFrom(resp);
100
- return { kind: 'pending', state: { jobId: data.id }, ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) };
120
+ return { kind: 'pending', state: { jobId: data.id }, ...retryAfterField(resp) };
101
121
  }
102
122
  throw new Error('imagerouter video submit returned neither generated data nor a job id');
103
123
  },
@@ -108,34 +128,18 @@ export function createImageRouterVideoPollingAdapter(_required, optional = {}) {
108
128
  }
109
129
  return {
110
130
  url: `${baseUrl}/videos/${encodeURIComponent(jobId)}`,
111
- init: withUnsignedRequestInit({ ctx: ctx, init: { method: 'GET', headers: { accept: 'application/json' } } }),
112
- meta: { wireModel: (config.wireModel || ctx.wireModel).trim(), size: imageRouterSizeFor({ aspect: ctx.aspect, surface: 'video' }), seconds: typeof ctx.length === 'number' ? ctx.length : 'auto' },
131
+ init: withUnsignedRequestInit({ ctx, init: { method: 'GET', headers: { accept: 'application/json' } } }),
132
+ meta: videoMetaFor({ ctx, config }),
113
133
  };
114
134
  },
115
- async parsePollResponse({ resp, ctx, state: _state }) {
135
+ async parsePollResponse({ resp, ctx }) {
116
136
  const data = (await parseOpenAICompatibleJson(resp, 'imagerouter video'));
117
- const status = typeof data.status === 'string' ? data.status.toLowerCase() : '';
118
- if (TERMINAL_FAILED_STATUSES.has(status)) {
119
- const error = data.error;
120
- const detail = typeof error?.message === 'string' && error.message ? error.message : status;
121
- return { kind: 'failed', message: `imagerouter video job failed: ${detail}` };
122
- }
123
- if (Array.isArray(data.data)) {
124
- const bytes = await bytesFromOpenAICompatibleData({ data, providerTag: 'imagerouter video' }, ctx);
125
- const wireModel = (config.wireModel || ctx.wireModel).trim();
126
- const size = imageRouterSizeFor({ aspect: ctx.aspect, surface: 'video' });
127
- const seconds = typeof ctx.length === 'number' ? ctx.length : 'auto';
128
- return {
129
- kind: 'complete',
130
- result: {
131
- bytes,
132
- providerNote: `imagerouter/${wireModel} · ${size} · ${seconds === 'auto' ? 'auto' : `${seconds}s`} · ${bytes.length} bytes`,
133
- suggestedExt: '.mp4',
134
- },
135
- };
136
- }
137
- const retryAfterMs = retryAfterMsFrom(resp);
138
- return { kind: 'pending', ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) };
137
+ const failed = failedOutcome(data);
138
+ if (failed)
139
+ return failed;
140
+ if (Array.isArray(data.data))
141
+ return completedVideo({ data, ctx, meta: videoMetaFor({ ctx, config }) });
142
+ return { kind: 'pending', ...retryAfterField(resp) };
139
143
  },
140
144
  };
141
145
  }
@@ -1,5 +1,5 @@
1
1
  import type { ProviderCredentials, RenderContext, RenderResult } from '../types.js';
2
- import type { VendorAdapterRegistry } from '../vendor-registry.js';
2
+ import type { VendorAdapterRegistry } from '../vendor-registry-core.js';
3
3
  /** ImageRouter's image/video generation `size` string for a given aspect ratio. */
4
4
  export declare function imageRouterSizeFor({ aspect, surface }: {
5
5
  aspect: string | undefined;
@@ -18,35 +18,22 @@
18
18
  */
19
19
  import { buildOpenAIImageUrl, buildOpenAIVideoUrl, bytesFromOpenAICompatibleData, parseOpenAICompatibleJson, sniffImageExt, withRequestInit, } from '../openai-compatible.js';
20
20
  import { dispatchVendorRequest, requireApiKey } from '../vendor-adapter.js';
21
+ // Maps (not object literals) so an inherited key such as `constructor` can never resolve as an aspect.
22
+ const PORTRAIT_AND_4_3_SIZES = [['9:16', '576x1024'], ['4:3', '1024x768'], ['3:4', '768x1024']];
23
+ const IMAGE_SIZES = new Map([['16:9', '1024x576'], ...PORTRAIT_AND_4_3_SIZES]);
24
+ const VIDEO_SIZES = new Map([['1:1', '1024x1024'], ...PORTRAIT_AND_4_3_SIZES]);
21
25
  /** ImageRouter's image/video generation `size` string for a given aspect ratio. */
22
26
  export function imageRouterSizeFor({ aspect, surface }) {
23
- if (surface === 'video') {
24
- if (aspect === '1:1')
25
- return '1024x1024';
26
- if (aspect === '9:16')
27
- return '576x1024';
28
- if (aspect === '4:3')
29
- return '1024x768';
30
- if (aspect === '3:4')
31
- return '768x1024';
32
- return '1024x576';
33
- }
34
- if (aspect === '16:9')
35
- return '1024x576';
36
- if (aspect === '9:16')
37
- return '576x1024';
38
- if (aspect === '4:3')
39
- return '1024x768';
40
- if (aspect === '3:4')
41
- return '768x1024';
42
- return '1024x1024';
27
+ const [sizes, fallback] = surface === 'video' ? [VIDEO_SIZES, '1024x576'] : [IMAGE_SIZES, '1024x1024'];
28
+ return sizes.get(aspect ?? '') ?? fallback;
43
29
  }
30
+ const DEFAULT_BASE_URL = 'https://api.imagerouter.io/v1/openai';
44
31
  const NO_CREDENTIAL_MESSAGE = 'no ImageRouter API key — configure it or set IMAGEROUTER_API_KEY';
45
32
  const imageRouterImageAdapter = {
46
33
  requireCredential: requireApiKey({ message: NO_CREDENTIAL_MESSAGE }),
47
34
  buildRequest({ ctx, credentials }) {
48
35
  const apiKey = credentials.apiKey; // requireCredential already validated this.
49
- const baseUrl = (credentials.baseUrl || 'https://api.imagerouter.io/v1/openai').trim();
36
+ const baseUrl = (credentials.baseUrl || DEFAULT_BASE_URL).trim();
50
37
  const wireModel = (credentials.model || ctx.wireModel).trim();
51
38
  const size = imageRouterSizeFor({ aspect: ctx.aspect, surface: 'image' });
52
39
  const body = {
@@ -81,13 +68,13 @@ const imageRouterImageAdapter = {
81
68
  },
82
69
  };
83
70
  export async function renderImageRouterImage({ ctx, credentials }) {
84
- return dispatchVendorRequest({ adapter: imageRouterImageAdapter, ctx: ctx, credentials: credentials });
71
+ return dispatchVendorRequest({ adapter: imageRouterImageAdapter, ctx, credentials });
85
72
  }
86
73
  const imageRouterVideoAdapter = {
87
74
  requireCredential: requireApiKey({ message: NO_CREDENTIAL_MESSAGE }),
88
75
  buildRequest({ ctx, credentials }) {
89
76
  const apiKey = credentials.apiKey; // requireCredential already validated this.
90
- const baseUrl = (credentials.baseUrl || 'https://api.imagerouter.io/v1/openai').trim();
77
+ const baseUrl = (credentials.baseUrl || DEFAULT_BASE_URL).trim();
91
78
  const wireModel = (credentials.model || ctx.wireModel).trim();
92
79
  const seconds = typeof ctx.length === 'number' ? ctx.length : 'auto';
93
80
  const size = imageRouterSizeFor({ aspect: ctx.aspect, surface: 'video' });
@@ -123,7 +110,7 @@ const imageRouterVideoAdapter = {
123
110
  },
124
111
  };
125
112
  export async function renderImageRouterVideo({ ctx, credentials }) {
126
- return dispatchVendorRequest({ adapter: imageRouterVideoAdapter, ctx: ctx, credentials: credentials });
113
+ return dispatchVendorRequest({ adapter: imageRouterVideoAdapter, ctx, credentials });
127
114
  }
128
115
  /** Explicit composition: importing a renderer never changes another module's registry. */
129
116
  export function registerVendorAdapters({ registry }, _optional = {}) {
@@ -1,5 +1,5 @@
1
1
  import type { ProviderCredentials, RenderContext, RenderResult } from '../types.js';
2
- import type { VendorAdapterRegistry } from '../vendor-registry.js';
2
+ import type { VendorAdapterRegistry } from '../vendor-registry-core.js';
3
3
  export declare function renderMinimaxTTS({ ctx, credentials }: {
4
4
  ctx: RenderContext;
5
5
  credentials: ProviderCredentials;
@@ -1,5 +1,5 @@
1
1
  import type { ProviderCredentials, RenderContext, RenderResult } from '../types.js';
2
- import type { VendorAdapterRegistry } from '../vendor-registry.js';
2
+ import type { VendorAdapterRegistry } from '../vendor-registry-core.js';
3
3
  export declare function renderNanoBananaImage({ ctx, credentials }: {
4
4
  ctx: RenderContext;
5
5
  credentials: ProviderCredentials;
@@ -51,40 +51,32 @@ function nanoBananaHeaders(baseUrl, apiKey) {
51
51
  /**
52
52
  * `providers.ts`'s `MEDIA_ASPECTS` are all natively supported by Nano
53
53
  * Banana's `imageConfig.aspectRatio`; anything else defaults to `'1:1'`.
54
- * Written as independent `if` returns (rather than the origin's one
55
- * `||`-chained condition) to match this package's established
54
+ * Written as a `Set` membership test (rather than the origin's one
55
+ * `||`-chained condition) to match this package's table-driven
56
56
  * aspect-mapping style (see `imagerouter.ts`'s `imageRouterSizeFor`) — same
57
- * input -> output mapping for every case, not a behavior change.
57
+ * input -> output mapping for every case, not a behavior change. A `Set`,
58
+ * not an object literal, so an inherited key like `constructor` can never match.
58
59
  */
60
+ const NANOBANANA_ASPECTS = new Set(['1:1', '16:9', '9:16', '4:3', '3:4']);
59
61
  function nanoBananaAspectFor(aspect) {
60
- if (aspect === '1:1')
61
- return '1:1';
62
- if (aspect === '16:9')
63
- return '16:9';
64
- if (aspect === '9:16')
65
- return '9:16';
66
- if (aspect === '4:3')
67
- return '4:3';
68
- if (aspect === '3:4')
69
- return '3:4';
70
- return '1:1';
62
+ return aspect !== undefined && NANOBANANA_ASPECTS.has(aspect) ? aspect : '1:1';
71
63
  }
64
+ function asArray(value) {
65
+ return Array.isArray(value) ? value : [];
66
+ }
67
+ /** A part's non-empty `inlineData.data` string, else `undefined` (camelCase only — Gemini's documented field). */
68
+ function inlineDataOf(part) {
69
+ const data = part?.inlineData?.data;
70
+ return typeof data === 'string' && data ? data : undefined;
71
+ }
72
+ /** The first inline image across every candidate's parts, in order. */
72
73
  function inlineImageBytesFromGenerateContent(data) {
73
- const candidates = data?.candidates;
74
- if (Array.isArray(candidates)) {
75
- for (const candidate of candidates) {
76
- const parts = candidate?.content?.parts;
77
- if (Array.isArray(parts)) {
78
- for (const part of parts) {
79
- const inline = part?.inlineData;
80
- if (typeof inline?.data === 'string' && inline.data) {
81
- return Buffer.from(inline.data, 'base64');
82
- }
83
- }
84
- }
85
- }
86
- }
87
- throw new Error('nano-banana image response missing candidates[].content.parts[].inlineData.data');
74
+ const candidates = asArray(data?.candidates);
75
+ const parts = candidates.flatMap((candidate) => asArray(candidate?.content?.parts));
76
+ const b64 = parts.map(inlineDataOf).find((d) => d !== undefined);
77
+ if (!b64)
78
+ throw new Error('nano-banana image response missing candidates[].content.parts[].inlineData.data');
79
+ return Buffer.from(b64, 'base64');
88
80
  }
89
81
  const NO_CREDENTIAL_MESSAGE = 'no Nano Banana credential — configure an API key or set GOOGLE_API_KEY / GEMINI_API_KEY.';
90
82
  const nanoBananaImageAdapter = {
@@ -135,7 +127,7 @@ const nanoBananaImageAdapter = {
135
127
  },
136
128
  };
137
129
  export async function renderNanoBananaImage({ ctx, credentials }) {
138
- return dispatchVendorRequest({ adapter: nanoBananaImageAdapter, ctx: ctx, credentials: credentials });
130
+ return dispatchVendorRequest({ adapter: nanoBananaImageAdapter, ctx, credentials });
139
131
  }
140
132
  /** Explicit composition: importing a renderer never changes another module's registry. */
141
133
  export function registerVendorAdapters({ registry }, _optional = {}) {
@@ -1,5 +1,5 @@
1
1
  import type { ProviderCredentials, RenderContext, RenderResult } from '../types.js';
2
- import type { VendorAdapterRegistry } from '../vendor-registry.js';
2
+ import type { VendorAdapterRegistry } from '../vendor-registry-core.js';
3
3
  export declare function renderOpenAIImage({ ctx, credentials }: {
4
4
  ctx: RenderContext;
5
5
  credentials: ProviderCredentials;
@@ -51,16 +51,53 @@ import { dispatchVendorRequest, requireApiKey } from '../vendor-adapter.js';
51
51
  // especially). The guarded client owns the socket and deadline budgets,
52
52
  // so a caller-configured global fetch default cannot cut a legitimately
53
53
  // slow-but-succeeding generation short. Pooling belongs to the injected guarded client.
54
- const OPENAI_IMAGE_HEADERS_TIMEOUT_MS = 10 * 60 * 1000;
55
- const OPENAI_IMAGE_BODY_TIMEOUT_MS = 10 * 60 * 1000;
54
+ // (Formerly two equal headers/body constants combined with `Math.max`; one
55
+ // ceiling covers both since the request carries a single abort signal.)
56
+ const OPENAI_IMAGE_TIMEOUT_MS = 10 * 60 * 1000;
57
+ const OPENAI_DEFAULT_BASE_URL = 'https://api.openai.com/v1';
58
+ const OPENAI_DEFAULT_SPEECH_VOICE = 'alloy';
56
59
  const OPENAI_IMAGE_NO_CREDENTIAL_MESSAGE = 'no OpenAI credential — configure an API key or set OPENAI_API_KEY.';
57
60
  const OPENAI_SPEECH_NO_CREDENTIAL_MESSAGE = 'no OpenAI credential — configure an API key or set OPENAI_API_KEY';
61
+ /**
62
+ * Resolves the base URL (default OpenAI endpoint), Azure detection, error tag
63
+ * and auth headers from already-validated credentials.
64
+ * @throws never — `requireCredential` has already rejected a missing API key.
65
+ */
66
+ function resolveOpenAITarget({ credentials }) {
67
+ const apiKey = credentials.apiKey; // requireCredential already validated this.
68
+ const rawBase = credentials.baseUrl || OPENAI_DEFAULT_BASE_URL;
69
+ const azure = detectAzureEndpoint(rawBase);
70
+ const headers = {
71
+ authorization: `Bearer ${apiKey}`,
72
+ 'content-type': 'application/json',
73
+ };
74
+ if (azure) {
75
+ // Azure's canonical auth header. Some deployments accept Bearer too,
76
+ // but api-key is what their docs document, so both are sent. OpenAI
77
+ // ignores unknown headers, so this is harmless on the standard
78
+ // endpoint too.
79
+ headers['api-key'] = apiKey;
80
+ }
81
+ return { rawBase, azure, tag: azure ? 'azure-openai' : 'openai', headers };
82
+ }
83
+ /**
84
+ * Splits the caller's `voice` into a concrete OpenAI voice id or free-form
85
+ * speaking-style instructions. A blank voice falls through to the default
86
+ * voice with empty instructions (no voice id is the empty string).
87
+ */
88
+ function resolveSpeechVoice({ voice }) {
89
+ const requestedVoice = voice?.trim() || '';
90
+ if (OPENAI_TTS_VOICES.has(requestedVoice))
91
+ return { voiceId: requestedVoice, instructions: '' };
92
+ // gpt-4o-mini-tts accepts free-form speaking-style instructions. If
93
+ // the caller passed prose rather than a concrete voice id, preserve
94
+ // it here instead of surfacing a provider error.
95
+ return { voiceId: OPENAI_DEFAULT_SPEECH_VOICE, instructions: requestedVoice };
96
+ }
58
97
  const openAIImageAdapter = {
59
98
  requireCredential: requireApiKey({ message: OPENAI_IMAGE_NO_CREDENTIAL_MESSAGE }),
60
99
  buildRequest({ ctx, credentials }) {
61
- const apiKey = credentials.apiKey; // requireCredential already validated this.
62
- const rawBase = credentials.baseUrl || 'https://api.openai.com/v1';
63
- const azure = detectAzureEndpoint(rawBase);
100
+ const { rawBase, azure, tag, headers } = resolveOpenAITarget({ credentials });
64
101
  const url = buildOpenAIImageUrl(rawBase, azure);
65
102
  const body = {
66
103
  prompt: ctx.prompt || 'A high-quality reference image.',
@@ -85,26 +122,15 @@ const openAIImageAdapter = {
85
122
  // gpt-image-* accepts quality 'high' | 'medium' | 'low'.
86
123
  body.quality = 'high';
87
124
  }
88
- const headers = {
89
- authorization: `Bearer ${apiKey}`,
90
- 'content-type': 'application/json',
91
- };
92
- if (azure) {
93
- // Azure's canonical auth header. Some deployments accept Bearer too,
94
- // but api-key is what their docs document, so both are sent. OpenAI
95
- // ignores unknown headers, so this is harmless on the standard
96
- // endpoint too.
97
- headers['api-key'] = apiKey;
98
- }
99
125
  return {
100
126
  url,
101
127
  init: withRequestInit(ctx, {
102
128
  method: 'POST',
103
129
  headers,
104
130
  body: JSON.stringify(body),
105
- signal: AbortSignal.timeout(Math.max(OPENAI_IMAGE_HEADERS_TIMEOUT_MS, OPENAI_IMAGE_BODY_TIMEOUT_MS)),
131
+ signal: AbortSignal.timeout(OPENAI_IMAGE_TIMEOUT_MS),
106
132
  }),
107
- meta: { tag: azure ? 'azure-openai' : 'openai', wireModel: ctx.wireModel },
133
+ meta: { tag, wireModel: ctx.wireModel },
108
134
  };
109
135
  },
110
136
  async parseResponse({ resp, ctx, request }) {
@@ -148,31 +174,16 @@ const openAIImageAdapter = {
148
174
  },
149
175
  };
150
176
  export async function renderOpenAIImage({ ctx, credentials }) {
151
- return dispatchVendorRequest({ adapter: openAIImageAdapter, ctx: ctx, credentials: credentials });
177
+ return dispatchVendorRequest({ adapter: openAIImageAdapter, ctx, credentials });
152
178
  }
153
179
  const openAISpeechAdapter = {
154
180
  requireCredential: requireApiKey({ message: OPENAI_SPEECH_NO_CREDENTIAL_MESSAGE }),
155
181
  buildRequest({ ctx, credentials }) {
156
- const apiKey = credentials.apiKey; // requireCredential already validated this.
157
- const rawBase = credentials.baseUrl || 'https://api.openai.com/v1';
158
- const azure = detectAzureEndpoint(rawBase);
182
+ const { rawBase, azure, tag, headers } = resolveOpenAITarget({ credentials });
159
183
  const url = buildOpenAISpeechUrl(rawBase, azure);
160
184
  const format = ctx.speechFormat;
161
- const text = (ctx.prompt && ctx.prompt.trim()) || 'This is a test.';
162
- let voiceId = 'alloy';
163
- let instructions = '';
164
- const requestedVoice = (ctx.voice && ctx.voice.trim()) || '';
165
- if (requestedVoice) {
166
- if (OPENAI_TTS_VOICES.has(requestedVoice)) {
167
- voiceId = requestedVoice;
168
- }
169
- else {
170
- // gpt-4o-mini-tts accepts free-form speaking-style instructions. If
171
- // the caller passed prose rather than a concrete voice id, preserve
172
- // it here instead of surfacing a provider error.
173
- instructions = requestedVoice;
174
- }
175
- }
185
+ const text = ctx.prompt?.trim() || 'This is a test.';
186
+ const { voiceId, instructions } = resolveSpeechVoice({ voice: ctx.voice });
176
187
  const body = {
177
188
  input: text,
178
189
  voice: voiceId,
@@ -184,13 +195,6 @@ const openAISpeechAdapter = {
184
195
  if (instructions && ctx.model === 'gpt-4o-mini-tts') {
185
196
  body.instructions = instructions;
186
197
  }
187
- const headers = {
188
- authorization: `Bearer ${apiKey}`,
189
- 'content-type': 'application/json',
190
- };
191
- if (azure) {
192
- headers['api-key'] = apiKey;
193
- }
194
198
  return {
195
199
  url,
196
200
  init: withRequestInit(ctx, {
@@ -198,7 +202,7 @@ const openAISpeechAdapter = {
198
202
  headers,
199
203
  body: JSON.stringify(body),
200
204
  }),
201
- meta: { tag: azure ? 'azure-openai' : 'openai', wireModel: ctx.wireModel, voiceId, format, instructions },
205
+ meta: { tag, wireModel: ctx.wireModel, voiceId, format, instructions },
202
206
  };
203
207
  },
204
208
  parseResponse: createRawBytesParser({
@@ -212,11 +216,11 @@ const openAISpeechAdapter = {
212
216
  noteBits.splice(2, 0, 'styled');
213
217
  return noteBits.join(' · ');
214
218
  },
215
- suggestedExt: ({ bytes: _bytes, meta }) => (meta.format === 'opus' ? '.ogg' : `.${meta.format}`),
219
+ suggestedExt: ({ meta }) => (meta.format === 'opus' ? '.ogg' : `.${meta.format}`),
216
220
  }),
217
221
  };
218
222
  export async function renderOpenAISpeech({ ctx, credentials }) {
219
- return dispatchVendorRequest({ adapter: openAISpeechAdapter, ctx: ctx, credentials: credentials });
223
+ return dispatchVendorRequest({ adapter: openAISpeechAdapter, ctx, credentials });
220
224
  }
221
225
  /** Explicit composition: importing a renderer never changes another module's registry. */
222
226
  export function registerVendorAdapters({ registry }, _optional = {}) {
@@ -1,5 +1,5 @@
1
1
  import type { ProviderCredentials, RenderContext, RenderResult } from '../types.js';
2
- import type { VendorAdapterRegistry } from '../vendor-registry.js';
2
+ import type { VendorAdapterRegistry } from '../vendor-registry-core.js';
3
3
  /**
4
4
  * OpenRouter normalizes aspect ratios across the providers it fronts;
5
5
  * `providers.ts`'s `MEDIA_ASPECTS` are all natively supported, default to
@@ -35,9 +35,8 @@ import { sniffImageExt, truncate, withRequestInit } from '../openai-compatible.j
35
35
  import { dispatchVendorRequest, requireApiKey } from '../vendor-adapter.js';
36
36
  // Chat-completions image generation can take a while for some routed
37
37
  // models; matches the same 10-minute ceiling `openai.ts`'s image dispatcher
38
- // uses for the same reason (see `OPENAI_IMAGE_HEADERS_TIMEOUT_MS`/
39
- // `OPENAI_IMAGE_BODY_TIMEOUT_MS` there — this vendor has no separate
40
- // headers/body distinction, so a single `AbortSignal.timeout` suffices).
38
+ // uses for the same reason (see `OPENAI_IMAGE_TIMEOUT_MS` there — a single
39
+ // `AbortSignal.timeout` covers the whole request for both vendors).
41
40
  const OPENROUTER_IMAGE_TIMEOUT_MS = 10 * 60 * 1000;
42
41
  /**
43
42
  * OpenRouter normalizes aspect ratios across the providers it fronts;
@@ -104,39 +103,8 @@ const openRouterImageAdapter = {
104
103
  if (!resp.ok) {
105
104
  throw new Error(`openrouter image ${resp.status}: ${truncate(text, 240)}`);
106
105
  }
107
- let data;
108
- try {
109
- data = JSON.parse(text);
110
- }
111
- catch {
112
- throw new Error(`openrouter image non-JSON response: ${truncate(text, 200)}`);
113
- }
114
- const images = data?.choices?.[0]?.message?.images;
115
- if (!Array.isArray(images) || images.length === 0) {
116
- throw new Error(`openrouter image response contained no images for model ${wireModel}: ${truncate(text, 200)}`);
117
- }
118
- const dataUrl = images[0]?.image_url?.url;
119
- if (typeof dataUrl !== 'string' || !dataUrl) {
120
- throw new Error(`openrouter image response missing image_url.url: ${truncate(text, 200)}`);
121
- }
122
- // Strip a "data:image/...;base64," prefix and decode; fall back to
123
- // downloading a plain URL, or treating the string as raw base64.
124
- const b64Match = dataUrl.match(/^data:image\/[^;]+;base64,(.+)$/s);
125
- let bytes;
126
- if (b64Match) {
127
- bytes = Buffer.from(b64Match[1], 'base64');
128
- }
129
- else if (dataUrl.startsWith('http')) {
130
- // Downloading already-generated bytes, not waiting on generation — UPLOAD-class (2min), not
131
- // the 10-minute GENERATE-class timeout the chat-completions call itself uses above.
132
- const imgResp = await assertAndFetchExternalAsset({ url: dataUrl }, { ...ctx, init: withRequestInit(ctx) });
133
- if (!imgResp.ok)
134
- throw new Error(`openrouter image download ${imgResp.status}`);
135
- bytes = Buffer.from(await imgResp.arrayBuffer());
136
- }
137
- else {
138
- bytes = Buffer.from(dataUrl, 'base64');
139
- }
106
+ const imageUrl = extractOpenRouterImageUrl({ text, wireModel });
107
+ const bytes = await decodeOpenRouterImage({ imageUrl, ctx });
140
108
  return {
141
109
  bytes,
142
110
  providerNote: `openrouter/${wireModel} · ${aspectRatio} · ${bytes.length} bytes`,
@@ -144,8 +112,55 @@ const openRouterImageAdapter = {
144
112
  };
145
113
  },
146
114
  };
115
+ /**
116
+ * Parses an OK chat-completions body and returns
117
+ * `choices[0].message.images[0].image_url.url`.
118
+ * @throws Error — non-JSON body, no images, or a missing/empty/non-string url;
119
+ * each message quotes the truncated body (never request headers/credentials).
120
+ */
121
+ function extractOpenRouterImageUrl({ text, wireModel }) {
122
+ let data;
123
+ try {
124
+ data = JSON.parse(text);
125
+ }
126
+ catch {
127
+ throw new Error(`openrouter image non-JSON response: ${truncate(text, 200)}`);
128
+ }
129
+ const images = firstChoiceImages({ data });
130
+ if (!Array.isArray(images) || images.length === 0) {
131
+ throw new Error(`openrouter image response contained no images for model ${wireModel}: ${truncate(text, 200)}`);
132
+ }
133
+ const imageUrl = images[0]?.image_url?.url;
134
+ if (typeof imageUrl !== 'string' || !imageUrl) {
135
+ throw new Error(`openrouter image response missing image_url.url: ${truncate(text, 200)}`);
136
+ }
137
+ return imageUrl;
138
+ }
139
+ /** `choices[0].message.images` of a parsed body, or `undefined` when any level is absent (a JSON `null` body included). */
140
+ function firstChoiceImages({ data }) {
141
+ return data?.choices?.[0]?.message?.images;
142
+ }
143
+ /**
144
+ * Turns the returned image reference into bytes.
145
+ * @throws Error — the SSRF guard refuses the download URL, or the download is not OK.
146
+ */
147
+ async function decodeOpenRouterImage({ imageUrl, ctx }) {
148
+ // Strip a "data:image/...;base64," prefix and decode; fall back to
149
+ // downloading a plain URL, or treating the string as raw base64.
150
+ const b64Match = imageUrl.match(/^data:image\/[^;]+;base64,(.+)$/s);
151
+ if (b64Match)
152
+ return Buffer.from(b64Match[1], 'base64');
153
+ if (!imageUrl.startsWith('http'))
154
+ return Buffer.from(imageUrl, 'base64');
155
+ // Downloading already-generated bytes, not waiting on generation — UPLOAD-class (2min), not
156
+ // the 10-minute GENERATE-class timeout the chat-completions call itself uses above.
157
+ const imgResp = await assertAndFetchExternalAsset({ url: imageUrl }, { ...ctx, init: withRequestInit(ctx) });
158
+ if (!imgResp.ok)
159
+ throw new Error(`openrouter image download ${imgResp.status}`);
160
+ return Buffer.from(await imgResp.arrayBuffer());
161
+ }
147
162
  export async function renderOpenRouterImage({ ctx, credentials }) {
148
- return dispatchVendorRequest({ adapter: openRouterImageAdapter, ctx: ctx, credentials: credentials });
163
+ return dispatchVendorRequest({ adapter: openRouterImageAdapter, ctx, credentials });
149
164
  }
150
165
  /** Explicit composition: importing a renderer never changes another module's registry. */
151
166
  export function registerVendorAdapters({ registry }, _optional = {}) {
@@ -1,5 +1,5 @@
1
1
  import type { ProviderCredentials, RenderContext, RenderResult } from '../types.js';
2
- import type { VendorAdapterRegistry } from '../vendor-registry.js';
2
+ import type { VendorAdapterRegistry } from '../vendor-registry-core.js';
3
3
  export declare function renderSenseAudioTTS({ ctx, credentials }: {
4
4
  ctx: RenderContext;
5
5
  credentials: ProviderCredentials;