@jini-ai/integrations 0.4.2 → 0.6.10

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 (132) hide show
  1. package/CHANGELOG.md +99 -1
  2. package/README.md +1 -0
  3. package/dist/api-connections/access-token.d.ts +9 -0
  4. package/dist/api-connections/access-token.js +92 -0
  5. package/dist/api-connections/account-actions.d.ts +40 -0
  6. package/dist/api-connections/account-actions.js +110 -0
  7. package/dist/api-connections/attempt-state.d.ts +28 -0
  8. package/dist/api-connections/attempt-state.js +73 -0
  9. package/dist/api-connections/authorization.d.ts +45 -0
  10. package/dist/api-connections/authorization.js +120 -0
  11. package/dist/api-connections/deps.d.ts +41 -0
  12. package/dist/api-connections/deps.js +13 -0
  13. package/dist/api-connections/descriptor.d.ts +6 -0
  14. package/dist/api-connections/descriptor.js +111 -0
  15. package/dist/api-connections/errors.d.ts +23 -0
  16. package/dist/api-connections/errors.js +24 -0
  17. package/dist/api-connections/finish-authorization.d.ts +24 -0
  18. package/dist/api-connections/finish-authorization.js +117 -0
  19. package/dist/api-connections/index.d.ts +18 -0
  20. package/dist/api-connections/index.js +10 -0
  21. package/dist/api-connections/install-credential.d.ts +19 -0
  22. package/dist/api-connections/install-credential.js +12 -0
  23. package/dist/api-connections/keys.d.ts +27 -0
  24. package/dist/api-connections/keys.js +22 -0
  25. package/dist/api-connections/ports.d.ts +73 -0
  26. package/dist/api-connections/ports.js +2 -0
  27. package/dist/api-connections/records.d.ts +27 -0
  28. package/dist/api-connections/records.js +52 -0
  29. package/dist/api-connections/request-checks.d.ts +18 -0
  30. package/dist/api-connections/request-checks.js +67 -0
  31. package/dist/api-connections/service.d.ts +25 -0
  32. package/dist/api-connections/service.js +26 -0
  33. package/dist/api-connections/status.d.ts +28 -0
  34. package/dist/api-connections/status.js +36 -0
  35. package/dist/api-connections/token-store/errors.d.ts +20 -0
  36. package/dist/api-connections/token-store/errors.js +38 -0
  37. package/dist/api-connections/token-store/index.d.ts +6 -0
  38. package/dist/api-connections/token-store/index.js +6 -0
  39. package/dist/api-connections/token-store/record.d.ts +69 -0
  40. package/dist/api-connections/token-store/record.js +97 -0
  41. package/dist/api-connections/token-store/vault-token-store.d.ts +26 -0
  42. package/dist/api-connections/token-store/vault-token-store.js +215 -0
  43. package/dist/api-connections/types.d.ts +101 -0
  44. package/dist/api-connections/types.js +9 -0
  45. package/dist/credentialed-http/auth-schemes.js +8 -4
  46. package/dist/credentialed-http/credentialed-request.d.ts +4 -0
  47. package/dist/credentialed-http/credentialed-request.js +61 -77
  48. package/dist/credentialed-http/response-redaction.d.ts +15 -0
  49. package/dist/credentialed-http/response-redaction.js +82 -0
  50. package/dist/media-providers/catalog.d.ts +3 -1
  51. package/dist/media-providers/catalog.js +3 -1
  52. package/dist/media-providers/dispatch/async-operation-store.d.ts +31 -0
  53. package/dist/media-providers/dispatch/async-operation-store.js +75 -37
  54. package/dist/media-providers/dispatch/builtin-vendors.d.ts +1 -1
  55. package/dist/media-providers/dispatch/context.js +10 -2
  56. package/dist/media-providers/dispatch/engine.d.ts +6 -3
  57. package/dist/media-providers/dispatch/engine.js +99 -109
  58. package/dist/media-providers/dispatch/index.d.ts +4 -2
  59. package/dist/media-providers/dispatch/index.js +3 -1
  60. package/dist/media-providers/dispatch/media-provider-registry.d.ts +62 -0
  61. package/dist/media-providers/dispatch/media-provider-registry.js +141 -0
  62. package/dist/media-providers/dispatch/node.d.ts +13 -0
  63. package/dist/media-providers/dispatch/node.js +24 -0
  64. package/dist/media-providers/dispatch/openai-compatible.d.ts +1 -1
  65. package/dist/media-providers/dispatch/openai-compatible.js +90 -87
  66. package/dist/media-providers/dispatch/operation-runtime.js +116 -89
  67. package/dist/media-providers/dispatch/outbound.d.ts +8 -4
  68. package/dist/media-providers/dispatch/outbound.js +27 -26
  69. package/dist/media-providers/dispatch/providers/aihubmix.d.ts +1 -1
  70. package/dist/media-providers/dispatch/providers/aihubmix.js +61 -56
  71. package/dist/media-providers/dispatch/providers/custom-image.d.ts +1 -1
  72. package/dist/media-providers/dispatch/providers/elevenlabs.d.ts +1 -1
  73. package/dist/media-providers/dispatch/providers/fishaudio.d.ts +1 -1
  74. package/dist/media-providers/dispatch/providers/grok.d.ts +1 -1
  75. package/dist/media-providers/dispatch/providers/imagerouter-video-async.d.ts +1 -1
  76. package/dist/media-providers/dispatch/providers/imagerouter-video-async.js +53 -49
  77. package/dist/media-providers/dispatch/providers/imagerouter.d.ts +1 -1
  78. package/dist/media-providers/dispatch/providers/imagerouter.js +11 -24
  79. package/dist/media-providers/dispatch/providers/minimax.d.ts +1 -1
  80. package/dist/media-providers/dispatch/providers/nanobanana.d.ts +1 -1
  81. package/dist/media-providers/dispatch/providers/nanobanana.js +22 -30
  82. package/dist/media-providers/dispatch/providers/openai.d.ts +1 -1
  83. package/dist/media-providers/dispatch/providers/openai.js +51 -47
  84. package/dist/media-providers/dispatch/providers/openrouter.d.ts +1 -1
  85. package/dist/media-providers/dispatch/providers/openrouter.js +52 -37
  86. package/dist/media-providers/dispatch/providers/senseaudio.d.ts +1 -1
  87. package/dist/media-providers/dispatch/providers/senseaudio.js +47 -28
  88. package/dist/media-providers/dispatch/providers/volcengine.d.ts +1 -1
  89. package/dist/media-providers/dispatch/response-parsers.js +37 -21
  90. package/dist/media-providers/dispatch/sqlite-async-operation-store.js +9 -29
  91. package/dist/media-providers/dispatch/ssrf-guard.d.ts +3 -2
  92. package/dist/media-providers/dispatch/ssrf-guard.js +6 -5
  93. package/dist/media-providers/dispatch/types.d.ts +76 -2
  94. package/dist/media-providers/dispatch/vendor-adapter.d.ts +2 -43
  95. package/dist/media-providers/dispatch/vendor-adapter.js +2 -2
  96. package/dist/media-providers/dispatch/vendor-registry-core.d.ts +24 -0
  97. package/dist/media-providers/dispatch/vendor-registry-core.js +34 -0
  98. package/dist/media-providers/dispatch/vendor-registry.d.ts +10 -36
  99. package/dist/media-providers/dispatch/vendor-registry.js +14 -42
  100. package/dist/media-providers/policy.js +25 -17
  101. package/dist/media-providers/providers.d.ts +5 -0
  102. package/dist/media-providers/providers.js +2 -0
  103. package/dist/media-providers/sqlite-task-store.js +12 -80
  104. package/dist/media-providers/staging.js +77 -58
  105. package/dist/media-providers/task-lifecycle.d.ts +33 -0
  106. package/dist/media-providers/task-lifecycle.js +124 -0
  107. package/dist/media-providers/task-store.js +8 -86
  108. package/dist/media-providers/ui-defaults.d.ts +10 -0
  109. package/dist/media-providers/ui-defaults.js +167 -0
  110. package/dist/media-providers/video-request.js +112 -90
  111. package/dist/saved-requests/definition.d.ts +17 -0
  112. package/dist/saved-requests/definition.js +84 -0
  113. package/dist/saved-requests/execute.d.ts +17 -0
  114. package/dist/saved-requests/execute.js +95 -0
  115. package/dist/saved-requests/index.d.ts +6 -0
  116. package/dist/saved-requests/index.js +4 -0
  117. package/dist/saved-requests/projection.d.ts +9 -0
  118. package/dist/saved-requests/projection.js +48 -0
  119. package/dist/saved-requests/schema.d.ts +7 -0
  120. package/dist/saved-requests/schema.js +73 -0
  121. package/dist/saved-requests/types.d.ts +58 -0
  122. package/dist/saved-requests/types.js +2 -0
  123. package/dist/saved-requests/validation.d.ts +46 -0
  124. package/dist/saved-requests/validation.js +66 -0
  125. package/dist/webhooks/delivery.d.ts +14 -0
  126. package/dist/webhooks/delivery.js +41 -10
  127. package/dist/webhooks/index.d.ts +1 -0
  128. package/dist/webhooks/index.js +1 -0
  129. package/dist/webhooks/ports.d.ts +23 -0
  130. package/dist/webhooks/worker.d.ts +83 -0
  131. package/dist/webhooks/worker.js +105 -0
  132. package/package.json +46 -9
@@ -95,11 +95,13 @@ function mergeExtraBody(body, cap, passthrough) {
95
95
  body[def.name] = def.default;
96
96
  }
97
97
  if (passthrough && cap.allowedPassthroughParameters?.length) {
98
- const allow = new Set(cap.allowedPassthroughParameters);
99
- for (const [k, v] of Object.entries(passthrough)) {
100
- if (allow.has(k) && v !== undefined)
101
- body[k] = v;
102
- }
98
+ applyAllowedPassthrough(body, new Set(cap.allowedPassthroughParameters), passthrough);
99
+ }
100
+ }
101
+ function applyAllowedPassthrough(body, allow, passthrough) {
102
+ for (const [k, v] of Object.entries(passthrough)) {
103
+ if (allow.has(k) && v !== undefined)
104
+ body[k] = v;
103
105
  }
104
106
  }
105
107
  /** Builds the seedance multimodal content array (text + reference images). */
@@ -115,105 +117,125 @@ function buildSeedanceContent(input) {
115
117
  }
116
118
  return content;
117
119
  }
120
+ /** `generate_audio` (only a real boolean) then `seed` (only a real number), in that wire order. */
121
+ function audioAndSeed(input) {
122
+ return {
123
+ ...(typeof input.generateAudio === 'boolean' ? { generate_audio: input.generateAudio } : {}),
124
+ ...seedField(input),
125
+ };
126
+ }
127
+ function seedField(input) {
128
+ return typeof input.seed === 'number' ? { seed: input.seed } : {};
129
+ }
130
+ function buildSeedanceBody({ input, wireModel, seconds }) {
131
+ return {
132
+ model: wireModel,
133
+ prompt: input.prompt,
134
+ duration: seconds,
135
+ content: buildSeedanceContent(input),
136
+ resolution: snapResolutionToken({ resolution: input.resolution, size: input.size }),
137
+ ...(input.aspectRatio ? { ratio: input.aspectRatio } : {}),
138
+ ...audioAndSeed(input),
139
+ };
140
+ }
141
+ function buildWanBody({ input, wireModel, seconds, referenceUrl }) {
142
+ return {
143
+ model: wireModel,
144
+ input: {
145
+ prompt: input.prompt,
146
+ ...(referenceUrl ? { media: [{ type: 'first_frame', url: referenceUrl }] } : {}),
147
+ },
148
+ parameters: {
149
+ resolution: snapResolutionToken({ resolution: input.resolution, size: input.size }).toUpperCase(),
150
+ duration: seconds,
151
+ prompt_extend: true,
152
+ watermark: false,
153
+ ...(input.aspectRatio ? { aspect_ratio: input.aspectRatio } : {}),
154
+ ...seedField(input),
155
+ },
156
+ };
157
+ }
158
+ function buildVeoBody({ input, wireModel, seconds }) {
159
+ return {
160
+ model: wireModel,
161
+ prompt: input.prompt,
162
+ seconds,
163
+ size: snapVeoSize({ size: input.size }),
164
+ ...audioAndSeed(input),
165
+ };
166
+ }
167
+ function buildGenericBody({ cap, input, wireModel, seconds, referenceUrl }) {
168
+ const genericSize = snapSizeToSupported({ size: input.size, supported: cap.supportedSizes });
169
+ return {
170
+ model: wireModel,
171
+ prompt: input.prompt,
172
+ seconds: String(seconds),
173
+ ...(genericSize ? { size: genericSize } : {}),
174
+ ...(input.resolution ? { resolution: input.resolution } : {}),
175
+ ...(referenceUrl ? { input_reference: referenceUrl } : {}),
176
+ ...audioAndSeed(input),
177
+ };
178
+ }
179
+ const FAMILY_BODY_BUILDERS = {
180
+ seedance: buildSeedanceBody,
181
+ wan: buildWanBody,
182
+ veo: buildVeoBody,
183
+ generic: buildGenericBody,
184
+ };
185
+ /**
186
+ * An unrecognized `cap.family` (untyped host config) gets the generic body,
187
+ * as the original if/else chain's final `else` did. `Object.hasOwn` keeps a
188
+ * prototype key such as `"toString"` from resolving to a non-builder.
189
+ */
190
+ function bodyBuilderFor(family) {
191
+ return Object.hasOwn(FAMILY_BODY_BUILDERS, family) ? FAMILY_BODY_BUILDERS[family] : buildGenericBody;
192
+ }
118
193
  /**
119
194
  * Builds the upstream video request body for a model. Pure: no fetch, no
120
195
  * auth. Caller: `POST \`${baseUrl}${pathSuffix}\`` with auth headers +
121
196
  * `JSON.stringify(body)`.
122
197
  */
123
198
  export function buildVideoRequest({ cap, input }) {
124
- const hasReference = Boolean(input.imageRef?.dataUrl);
125
- const wireModel = resolveWireModel({ cap: cap, hasReference: hasReference });
126
- const family = deriveVideoFamily({ wireModel: wireModel }, { cap: cap });
127
- const seconds = snapDuration({ cap: cap, requested: input.durationSeconds });
128
- let body;
129
- if (family === 'seedance') {
130
- body = {
131
- model: wireModel,
132
- prompt: input.prompt,
133
- duration: seconds,
134
- content: buildSeedanceContent(input),
135
- resolution: snapResolutionToken({ resolution: input.resolution, size: input.size }),
136
- };
137
- if (input.aspectRatio)
138
- body.ratio = input.aspectRatio;
139
- if (typeof input.generateAudio === 'boolean')
140
- body.generate_audio = input.generateAudio;
141
- if (typeof input.seed === 'number')
142
- body.seed = input.seed;
143
- }
144
- else if (family === 'wan') {
145
- const wanInput = { prompt: input.prompt };
146
- if (hasReference) {
147
- wanInput.media = [{ type: 'first_frame', url: input.imageRef.dataUrl }];
148
- }
149
- const parameters = {
150
- resolution: snapResolutionToken({ resolution: input.resolution, size: input.size }).toUpperCase(),
151
- duration: seconds,
152
- prompt_extend: true,
153
- watermark: false,
154
- };
155
- if (input.aspectRatio)
156
- parameters.aspect_ratio = input.aspectRatio;
157
- if (typeof input.seed === 'number')
158
- parameters.seed = input.seed;
159
- body = { model: wireModel, input: wanInput, parameters };
160
- }
161
- else if (family === 'veo') {
162
- body = {
163
- model: wireModel,
164
- prompt: input.prompt,
165
- seconds,
166
- size: snapVeoSize({ size: input.size }),
167
- };
168
- if (typeof input.generateAudio === 'boolean')
169
- body.generate_audio = input.generateAudio;
170
- if (typeof input.seed === 'number')
171
- body.seed = input.seed;
172
- }
173
- else {
174
- body = {
175
- model: wireModel,
176
- prompt: input.prompt,
177
- seconds: String(seconds),
178
- };
179
- const genericSize = snapSizeToSupported({ size: input.size, supported: cap.supportedSizes });
180
- if (genericSize)
181
- body.size = genericSize;
182
- if (input.resolution)
183
- body.resolution = input.resolution;
184
- if (hasReference)
185
- body.input_reference = input.imageRef.dataUrl;
186
- if (typeof input.generateAudio === 'boolean')
187
- body.generate_audio = input.generateAudio;
188
- if (typeof input.seed === 'number')
189
- body.seed = input.seed;
190
- }
199
+ const referenceUrl = input.imageRef?.dataUrl;
200
+ const hasReference = Boolean(referenceUrl);
201
+ const wireModel = resolveWireModel({ cap, hasReference });
202
+ const family = deriveVideoFamily({ wireModel }, { cap });
203
+ const seconds = snapDuration({ cap, requested: input.durationSeconds });
204
+ const body = bodyBuilderFor(family)({ cap, input, wireModel, seconds, referenceUrl });
191
205
  mergeExtraBody(body, cap, input.passthrough);
192
206
  return { wireModel, family, pathSuffix: '/videos', contentType: 'application/json', body, hasReference };
193
207
  }
208
+ /** The first value that is neither `undefined` nor `null` — a `??` chain over a list. */
209
+ function firstPresent(...values) {
210
+ return values.find((v) => v !== undefined && v !== null);
211
+ }
212
+ /** `error.message` (object form), the string `error`, then `failure_reason`, then `message`. */
213
+ function responseError(d) {
214
+ const errorObj = d.error;
215
+ const fromObject = typeof errorObj === 'object' && errorObj ? errorObj.message : undefined;
216
+ const fromString = typeof errorObj === 'string' ? errorObj : undefined;
217
+ return firstPresent(fromObject, fromString, d.failure_reason, d.message);
218
+ }
219
+ function responseUrl(d, data) {
220
+ const dataArray = Array.isArray(d.data) ? d.data : undefined;
221
+ const unsignedUrls = Array.isArray(d.unsigned_urls) ? d.unsigned_urls : undefined;
222
+ return firstPresent(d.video_url, d.url, d.output_url, data?.video_url, data?.url, dataArray?.[0]?.url, unsignedUrls?.[0]);
223
+ }
194
224
  /** Best-effort normalization of an async-submit / poll response across vendor families. */
195
225
  export function normalizeVideoResponse({ raw }) {
196
226
  const d = (raw ?? {});
197
227
  const data = d.data;
198
- const dataArray = Array.isArray(d.data) ? d.data : undefined;
199
- const unsignedUrls = Array.isArray(d.unsigned_urls) ? d.unsigned_urls : undefined;
200
- const id = d.id ?? d.task_id ?? data?.id ?? data?.task_id;
201
- const status = d.status ?? data?.status;
202
- const url = d.video_url ?? d.url ?? d.output_url ?? data?.video_url ?? data?.url ?? dataArray?.[0]?.url ?? unsignedUrls?.[0];
203
- const errorObj = d.error;
204
- const error = (typeof errorObj === 'object' && errorObj ? errorObj.message : undefined) ??
205
- (typeof errorObj === 'string' ? errorObj : undefined) ??
206
- d.failure_reason ??
207
- d.message;
228
+ const fields = {
229
+ id: firstPresent(d.id, d.task_id, data?.id, data?.task_id),
230
+ status: firstPresent(d.status, data?.status),
231
+ url: responseUrl(d, data),
232
+ error: responseError(d),
233
+ };
208
234
  const result = {};
209
- if (id !== undefined && id !== null)
210
- result.id = String(id);
211
- if (status !== undefined && status !== null)
212
- result.status = String(status);
213
- if (url !== undefined && url !== null)
214
- result.url = String(url);
215
- if (error !== undefined && error !== null)
216
- result.error = String(error);
235
+ for (const key of Object.keys(fields)) {
236
+ if (fields[key] !== undefined)
237
+ result[key] = String(fields[key]);
238
+ }
217
239
  return result;
218
240
  }
219
241
  //# sourceMappingURL=video-request.js.map
@@ -0,0 +1,17 @@
1
+ import type { SavedRequestDefinition } from "./types.js";
2
+ import { compileInputSchema } from "./schema.js";
3
+ /** Validate persisted configuration at save AND invocation time. Unsupported keys refuse rather
4
+ * than becoming a more general HTTP/template tool. Returns a detached snapshot or a safe refusal.
5
+ * @complexity O(n) over a definition bounded to 16 KiB; no I/O. */
6
+ export declare function parseSavedRequestDefinition({ value }: {
7
+ value: unknown;
8
+ }, _options?: Record<string, never>): SavedRequestDefinition;
9
+ /** Internal execution preparation: retain the validator built while checking the detached schema.
10
+ * @complexity O(n) over the same 16 KiB definition bound; no I/O. */
11
+ export declare function prepareSavedRequestDefinition({ value }: {
12
+ value: unknown;
13
+ }, _options?: Record<string, never>): {
14
+ definition: SavedRequestDefinition;
15
+ validator: ReturnType<typeof compileInputSchema>;
16
+ };
17
+ //# sourceMappingURL=definition.d.ts.map
@@ -0,0 +1,84 @@
1
+ import { compileInputSchema } from "./schema.js";
2
+ import { closed, dataKey, fieldPath, httpsUrl, integer, name, record, requireCondition, snapshot } from "./validation.js";
3
+ /** Validate persisted configuration at save AND invocation time. Unsupported keys refuse rather
4
+ * than becoming a more general HTTP/template tool. Returns a detached snapshot or a safe refusal.
5
+ * @complexity O(n) over a definition bounded to 16 KiB; no I/O. */
6
+ export function parseSavedRequestDefinition({ value }, _options = {}) {
7
+ return prepareSavedRequestDefinition({ value }).definition;
8
+ }
9
+ /** Internal execution preparation: retain the validator built while checking the detached schema.
10
+ * @complexity O(n) over the same 16 KiB definition bound; no I/O. */
11
+ export function prepareSavedRequestDefinition({ value }, _options = {}) {
12
+ const definition = record({ value: snapshot({ value, maxBytes: 16_384, code: "invalid_definition" }) });
13
+ closed({ value: definition, keys: ["version", "method", "url", "credential", "inputSchema", "queryBindings", "bodyBindings", "staticBody", "output"] });
14
+ requireCondition({ valid: definition.version === 1 });
15
+ requireCondition({ valid: ["GET", "POST", "PUT", "PATCH", "DELETE"].includes(String(definition.method)) });
16
+ const url = httpsUrl({ value: definition.url });
17
+ checkCredential({ value: definition.credential, url });
18
+ for (const key of url.searchParams.keys())
19
+ dataKey({ value: key });
20
+ const schema = record({ value: definition.inputSchema });
21
+ const validator = compileInputSchema({ schema });
22
+ checkBindings({ definition, schema, url });
23
+ checkProjection({ value: definition.output });
24
+ return { definition: definition, validator };
25
+ }
26
+ function checkCredential({ value, url }, _options = {}) {
27
+ const credential = record({ value });
28
+ closed({ value: credential, keys: ["id", "revision", "origin"] });
29
+ for (const key of ["id", "revision"]) {
30
+ const text = credential[key];
31
+ requireCondition({ valid: typeof text === "string" && /^[\w:-]{1,128}$/.test(text) });
32
+ }
33
+ requireCondition({ valid: httpsUrl({ value: credential.origin }).origin === credential.origin });
34
+ requireCondition({ valid: url.origin === credential.origin });
35
+ }
36
+ function checkBindings({ definition, schema, url }, _options = {}) {
37
+ const properties = record({ value: schema.properties });
38
+ checkBindingMap({ value: definition.queryBindings, properties, occupied: [...url.searchParams.keys()], query: true });
39
+ const body = definition.staticBody === undefined ? {} : record({ value: definition.staticBody });
40
+ for (const key of Object.keys(body))
41
+ dataKey({ value: key });
42
+ checkBindingMap({ value: definition.bodyBindings, properties, occupied: Object.keys(body), query: false });
43
+ if (definition.method === "GET") {
44
+ requireCondition({ valid: Object.keys(record({ value: definition.bodyBindings })).length === 0 && Object.keys(body).length === 0 });
45
+ }
46
+ }
47
+ function checkBindingMap({ value, properties, occupied, query }, _options = {}) {
48
+ const bindings = record({ value });
49
+ integer({ value: Object.keys(bindings).length, max: 32 });
50
+ for (const [destination, source] of Object.entries(bindings)) {
51
+ dataKey({ value: destination });
52
+ const sourceKey = name({ value: source });
53
+ requireCondition({ valid: !occupied.includes(destination) && Object.hasOwn(properties, sourceKey) });
54
+ if (query)
55
+ requireCondition({ valid: !["object", "array"].includes(String(record({ value: properties[sourceKey] }).type)) });
56
+ }
57
+ }
58
+ function checkProjection({ value }, _options = {}) {
59
+ const projection = record({ value });
60
+ closed({ value: projection, keys: ["path", "maxItems", "fields"] });
61
+ fieldPath({ value: projection.path });
62
+ integer({ value: projection.maxItems, min: 1, max: 50 });
63
+ const fields = record({ value: projection.fields });
64
+ integer({ value: Object.keys(fields).length, min: 1, max: 32 });
65
+ for (const [key, field] of Object.entries(fields)) {
66
+ name({ value: key });
67
+ checkOutputField({ value: field });
68
+ }
69
+ }
70
+ function checkOutputField({ value }, _options = {}) {
71
+ const field = record({ value });
72
+ closed({ value: field, keys: ["path", "type", "maxLength", "allowedOrigin"] });
73
+ fieldPath({ value: field.path });
74
+ requireCondition({ valid: ["string", "number", "boolean", "url"].includes(String(field.type)) });
75
+ if (field.type === "string" || field.type === "url")
76
+ integer({ value: field.maxLength, min: 1, max: 4096 });
77
+ else
78
+ requireCondition({ valid: field.maxLength === undefined });
79
+ if (field.type === "url")
80
+ requireCondition({ valid: httpsUrl({ value: field.allowedOrigin }).origin === field.allowedOrigin });
81
+ else
82
+ requireCondition({ valid: field.allowedOrigin === undefined });
83
+ }
84
+ //# sourceMappingURL=definition.js.map
@@ -0,0 +1,17 @@
1
+ import type { SavedRequestDeps, SavedRequestResult } from "./types.js";
2
+ /** Execute an already-authorized host definition with visitor data. The model supplies only input;
3
+ * callers must recheck live policy/consent/quotas before calling. No retries of ambiguous effects.
4
+ * @param required Host ports, mounted workspace, saved definition and untrusted input.
5
+ * @param options Optional cancellation; the guard also imposes a whole-request 10s deadline.
6
+ * @returns Positively projected data explicitly marked untrusted.
7
+ * @throws SavedRequestError with value-free public refusal codes.
8
+ * @complexity O(n) bounded validation plus one credential resolution and one guarded HTTP send. */
9
+ export declare function executeSavedRequest({ deps, workspaceId, definition: raw, input: rawInput }: {
10
+ deps: SavedRequestDeps;
11
+ workspaceId: string;
12
+ definition: unknown;
13
+ input: unknown;
14
+ }, options?: {
15
+ signal?: AbortSignal;
16
+ }): Promise<SavedRequestResult>;
17
+ //# sourceMappingURL=execute.d.ts.map
@@ -0,0 +1,95 @@
1
+ import { createHttpClient } from "@jini-ai/platform/http/guarded";
2
+ import { CredentialedRequestValidationError, makeCredentialedRequest } from "../credentialed-http/credentialed-request.js";
3
+ import { prepareSavedRequestDefinition } from "./definition.js";
4
+ import { projectSavedRequestResponse } from "./projection.js";
5
+ import { requireCondition, SavedRequestError, snapshot } from "./validation.js";
6
+ /** Execute an already-authorized host definition with visitor data. The model supplies only input;
7
+ * callers must recheck live policy/consent/quotas before calling. No retries of ambiguous effects.
8
+ * @param required Host ports, mounted workspace, saved definition and untrusted input.
9
+ * @param options Optional cancellation; the guard also imposes a whole-request 10s deadline.
10
+ * @returns Positively projected data explicitly marked untrusted.
11
+ * @throws SavedRequestError with value-free public refusal codes.
12
+ * @complexity O(n) bounded validation plus one credential resolution and one guarded HTTP send. */
13
+ export async function executeSavedRequest({ deps, workspaceId, definition: raw, input: rawInput }, options = {}) {
14
+ const { definition, validator } = prepareSavedRequestDefinition({ value: raw });
15
+ const input = validatedInput({ validator, value: rawInput });
16
+ const bound = bindRequest({ definition, input });
17
+ let responseReceived = false;
18
+ try {
19
+ requireCondition({ valid: !deps.forbiddenOrigins.some(origin => new URL(origin).hostname === new URL(definition.url).hostname) });
20
+ options.signal?.throwIfAborted();
21
+ const credential = await resolveCredential({ deps, workspaceId, definition });
22
+ options.signal?.throwIfAborted();
23
+ const response = await makeCredentialedRequest({
24
+ deps: {
25
+ resolver: { describe: async () => credential, resolve: async () => credential },
26
+ schemeRegistry: deps.schemeRegistry, audit: deps.audit, clock: deps.clock,
27
+ httpClient: boundedHttpClient({ deps, signal: options.signal, onResponse: () => { responseReceived = true; } }),
28
+ },
29
+ input: { workspaceId, label: definition.credential.id, method: definition.method, url: bound.url },
30
+ }, { body: bound.body, headers: { Accept: "application/json", ...(bound.body === undefined ? {} : { "Content-Type": "application/json" }) }, responseFormat: "json" });
31
+ checkResponse({ response });
32
+ return projectSavedRequestResponse({ bodyText: response.bodyText, output: definition.output });
33
+ }
34
+ catch (error) {
35
+ if (error instanceof SavedRequestError)
36
+ throw error;
37
+ // The credential owner audits answered requests before JSON completeness/redaction checks.
38
+ // Preserve those refusals without misclassifying pre-send credential validation failures.
39
+ if (responseReceived && error instanceof CredentialedRequestValidationError)
40
+ throw new SavedRequestError({ code: "invalid_response" });
41
+ throw new SavedRequestError({ code: "execution_failed" });
42
+ }
43
+ }
44
+ function validatedInput({ validator, value }, _options = {}) {
45
+ const input = snapshot({ value, maxBytes: 16_384, code: "invalid_input" });
46
+ requireCondition({ valid: validator.validate(input).valid, code: "invalid_input" });
47
+ return input;
48
+ }
49
+ function bindRequest({ definition, input }, _options = {}) {
50
+ const url = new URL(definition.url);
51
+ for (const [key, source] of Object.entries(definition.queryBindings)) {
52
+ if (Object.hasOwn(input, source))
53
+ url.searchParams.set(key, String(input[source]));
54
+ }
55
+ const body = { ...definition.staticBody };
56
+ for (const [key, source] of Object.entries(definition.bodyBindings)) {
57
+ if (Object.hasOwn(input, source))
58
+ body[key] = input[source];
59
+ }
60
+ snapshot({ value: { url: url.href, body }, maxBytes: 16_384, code: "invalid_input" });
61
+ return { url: url.href, body: Object.keys(body).length === 0 ? undefined : JSON.stringify(body) };
62
+ }
63
+ async function resolveCredential({ deps, workspaceId, definition }, _options = {}) {
64
+ const credential = await deps.credentials.resolve({ workspaceId, credentialId: definition.credential.id });
65
+ if (!credential)
66
+ throw new SavedRequestError({ code: "credential_changed" });
67
+ requireCondition({ valid: credential.revision === definition.credential.revision, code: "credential_changed" });
68
+ requireCondition({ valid: new URL(credential.baseUrl).origin === definition.credential.origin, code: "credential_changed" });
69
+ // Legacy credentials allow additional hosts; visitor release approval covers only the base origin.
70
+ requireCondition({ valid: !/[\r\n\u0000]/u.test(credential.connection.token), code: "credential_changed" });
71
+ return { ...credential, additionalHosts: [] };
72
+ }
73
+ function boundedHttpClient({ deps, signal, onResponse }, _options = {}) {
74
+ // Equivalent to SINGLE_HOP_HTTPS_EGRESS_POLICY: the product policy stays in host composition.
75
+ // Construct the existing guard here so redirects/dev overrides cannot silently widen this grant.
76
+ const client = createHttpClient({ dns: deps.dns, transport: deps.transport, clock: deps.clock, userAgent: deps.userAgent, policy: {
77
+ allowedSchemes: ["https"], denyPrivateAddresses: true, devHostAllowlist: [], maxRedirects: 0,
78
+ connectTimeoutMs: 10_000, maxResponseBytes: 65_536, maxDecompressedBytes: 65_536,
79
+ } });
80
+ return { async send({ request }) {
81
+ const bounded = { ...request, totalDeadlineMs: 10_000, maxResponseBytes: 65_536, ...(signal === undefined ? {} : { signal }) };
82
+ const response = await client.send({ request: bounded }, { redirect: "error" });
83
+ onResponse();
84
+ return response;
85
+ } };
86
+ }
87
+ function checkResponse({ response }, _options = {}) {
88
+ requireCondition({ valid: response.status >= 200 && response.status < 300, code: "invalid_response" });
89
+ const headers = Object.fromEntries(Object.entries(response.headers).map(([key, value]) => [key.toLowerCase(), value]));
90
+ const contentType = headers["content-type"]?.split(";")[0]?.trim() ?? "";
91
+ requireCondition({ valid: /^application\/(?:[a-z0-9.-]+\+)?json$/i.test(contentType), code: "invalid_response" });
92
+ // The platform guard caps bytes and the credential owner's JSON mode refuses truncation.
93
+ // Check status/media type after that owner records the real status, before field projection.
94
+ }
95
+ //# sourceMappingURL=execute.js.map
@@ -0,0 +1,6 @@
1
+ export { parseSavedRequestDefinition } from "./definition.js";
2
+ export { executeSavedRequest } from "./execute.js";
3
+ export { SavedRequestError } from "./validation.js";
4
+ export type { SavedRequestErrorCode } from "./validation.js";
5
+ export type * from "./types.js";
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,4 @@
1
+ export { parseSavedRequestDefinition } from "./definition.js";
2
+ export { executeSavedRequest } from "./execute.js";
3
+ export { SavedRequestError } from "./validation.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,9 @@
1
+ import type { SavedRequestDefinition, SavedRequestResult } from "./types.js";
2
+ /** Project only declared, typed fields after credentialed-request redaction. No provider text
3
+ * becomes an instruction or browser directive. Bad types/URLs refuse; selected arrays are bounded.
4
+ * @complexity O(rows * fields * path depth), bounded by 50 * 32 * 8 and 16 KiB output. */
5
+ export declare function projectSavedRequestResponse({ bodyText, output }: {
6
+ bodyText: string;
7
+ output: SavedRequestDefinition["output"];
8
+ }, _options?: Record<string, never>): SavedRequestResult;
9
+ //# sourceMappingURL=projection.d.ts.map
@@ -0,0 +1,48 @@
1
+ import { requireCondition, SavedRequestError, snapshot } from "./validation.js";
2
+ /** Project only declared, typed fields after credentialed-request redaction. No provider text
3
+ * becomes an instruction or browser directive. Bad types/URLs refuse; selected arrays are bounded.
4
+ * @complexity O(rows * fields * path depth), bounded by 50 * 32 * 8 and 16 KiB output. */
5
+ export function projectSavedRequestResponse({ bodyText, output }, _options = {}) {
6
+ try {
7
+ const selected = readPath({ value: JSON.parse(bodyText), path: output.path });
8
+ const rows = Array.isArray(selected) ? selected.slice(0, output.maxItems) : [selected];
9
+ const items = rows.map(row => projectRow({ row, fields: output.fields }));
10
+ const result = { trust: "untrusted", items };
11
+ snapshot({ value: result, maxBytes: 16_384, code: "invalid_response" });
12
+ return result;
13
+ }
14
+ catch {
15
+ throw new SavedRequestError({ code: "invalid_response" });
16
+ }
17
+ }
18
+ function readPath({ value, path }, _options = {}) {
19
+ for (const key of path) {
20
+ requireCondition({ valid: typeof value === "object" && value !== null && !Array.isArray(value), code: "invalid_response" });
21
+ requireCondition({ valid: Object.hasOwn(value, key), code: "invalid_response" });
22
+ value = value[key];
23
+ }
24
+ return value;
25
+ }
26
+ function projectRow({ row, fields }, _options = {}) {
27
+ return Object.fromEntries(Object.entries(fields).map(([key, field]) => {
28
+ const value = readPath({ value: row, path: field.path });
29
+ checkValue({ value, field });
30
+ return [key, value];
31
+ }));
32
+ }
33
+ function checkValue({ value, field }, _options = {}) {
34
+ const type = field.type === "url" ? "string" : field.type;
35
+ requireCondition({ valid: typeof value === type, code: "invalid_response" });
36
+ if (typeof value === "number")
37
+ requireCondition({ valid: Number.isFinite(value), code: "invalid_response" });
38
+ if (typeof value === "string")
39
+ requireCondition({ valid: [...value].length <= field.maxLength, code: "invalid_response" });
40
+ if (field.type === "url")
41
+ checkPublicUrl({ value: value, origin: field.allowedOrigin });
42
+ }
43
+ function checkPublicUrl({ value, origin }, _options = {}) {
44
+ const url = new URL(value);
45
+ requireCondition({ valid: url.protocol === "https:" && url.origin === origin && !url.username && !url.password, code: "invalid_response" });
46
+ requireCondition({ valid: !/[\s\u0000-\u001f\u007f]/u.test(value), code: "invalid_response" });
47
+ }
48
+ //# sourceMappingURL=projection.js.map
@@ -0,0 +1,7 @@
1
+ import { Validator } from "@cfworker/json-schema";
2
+ /** Closed, bounded schemas only; no refs, combinators, formats, regex or executable expressions.
3
+ * @complexity O(s), with depth <= 4 and <= 32 properties per object; serialized schema is capped. */
4
+ export declare function compileInputSchema({ schema }: {
5
+ schema: Record<string, unknown>;
6
+ }, _options?: Record<string, never>): Validator;
7
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1,73 @@
1
+ import { Validator } from "@cfworker/json-schema";
2
+ import { closed, integer, name, record, requireCondition } from "./validation.js";
3
+ const KEYS = {
4
+ object: ["type", "properties", "required", "additionalProperties"],
5
+ array: ["type", "items", "minItems", "maxItems"],
6
+ string: ["type", "minLength", "maxLength", "enum"],
7
+ number: ["type", "minimum", "maximum", "enum"],
8
+ integer: ["type", "minimum", "maximum", "enum"],
9
+ boolean: ["type", "enum"],
10
+ };
11
+ /** Closed, bounded schemas only; no refs, combinators, formats, regex or executable expressions.
12
+ * @complexity O(s), with depth <= 4 and <= 32 properties per object; serialized schema is capped. */
13
+ export function compileInputSchema({ schema }, _options = {}) {
14
+ requireCondition({ valid: schema.type === "object" });
15
+ checkNode({ schema, depth: 0 });
16
+ return new Validator(schema, "2020-12", true);
17
+ }
18
+ function checkNode({ schema, depth }, _options = {}) {
19
+ requireCondition({ valid: depth <= 4 });
20
+ requireCondition({ valid: typeof schema.type === "string" && Object.hasOwn(KEYS, schema.type) });
21
+ const keys = KEYS[schema.type];
22
+ closed({ value: schema, keys });
23
+ if (schema.type === "object")
24
+ return checkObject({ schema, depth });
25
+ if (schema.type === "array")
26
+ return checkArray({ schema, depth });
27
+ checkPrimitive({ schema });
28
+ }
29
+ function checkObject({ schema, depth }, _options = {}) {
30
+ requireCondition({ valid: schema.additionalProperties === false });
31
+ const properties = record({ value: schema.properties });
32
+ integer({ value: Object.keys(properties).length, max: 32 });
33
+ for (const [key, child] of Object.entries(properties)) {
34
+ name({ value: key });
35
+ checkNode({ schema: record({ value: child }), depth: depth + 1 });
36
+ }
37
+ if (schema.required === undefined)
38
+ return;
39
+ requireCondition({ valid: Array.isArray(schema.required) });
40
+ const required = schema.required;
41
+ requireCondition({ valid: required.every(key => typeof key === "string" && Object.hasOwn(properties, key)) });
42
+ requireCondition({ valid: new Set(required).size === required.length });
43
+ }
44
+ function checkArray({ schema, depth }, _options = {}) {
45
+ integer({ value: schema.maxItems, max: 50 });
46
+ if (schema.minItems !== undefined)
47
+ integer({ value: schema.minItems, max: Number(schema.maxItems) });
48
+ checkNode({ schema: record({ value: schema.items }), depth: depth + 1 });
49
+ }
50
+ function checkPrimitive({ schema }, _options = {}) {
51
+ if (schema.type === "string") {
52
+ integer({ value: schema.maxLength, max: 4096 });
53
+ if (schema.minLength !== undefined)
54
+ integer({ value: schema.minLength, max: Number(schema.maxLength) });
55
+ }
56
+ if (schema.type === "number" || schema.type === "integer")
57
+ checkRange({ schema });
58
+ if (schema.enum !== undefined)
59
+ checkEnum({ schema });
60
+ }
61
+ function checkRange({ schema }, _options = {}) {
62
+ requireCondition({ valid: typeof schema.minimum === "number" && Number.isFinite(schema.minimum) });
63
+ requireCondition({ valid: typeof schema.maximum === "number" && Number.isFinite(schema.maximum) });
64
+ requireCondition({ valid: Number(schema.minimum) <= Number(schema.maximum) });
65
+ }
66
+ function checkEnum({ schema }, _options = {}) {
67
+ requireCondition({ valid: Array.isArray(schema.enum) });
68
+ const values = schema.enum;
69
+ integer({ value: values.length, min: 1, max: 32 });
70
+ const type = schema.type === "integer" ? "number" : schema.type;
71
+ requireCondition({ valid: values.every(value => typeof value === type) });
72
+ }
73
+ //# sourceMappingURL=schema.js.map