@dual-os/sdk 0.0.0-stage → 0.8.0-next.1

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 (214) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +7 -2
  3. package/dist/Action.d.ts +200 -0
  4. package/dist/Action.d.ts.map +1 -0
  5. package/dist/Action.js +171 -0
  6. package/dist/Action.js.map +1 -0
  7. package/dist/AgentChannel.d.ts +1725 -0
  8. package/dist/AgentChannel.d.ts.map +1 -0
  9. package/dist/AgentChannel.js +734 -0
  10. package/dist/AgentChannel.js.map +1 -0
  11. package/dist/AgentChannelConformance.d.ts +1542 -0
  12. package/dist/AgentChannelConformance.d.ts.map +1 -0
  13. package/dist/AgentChannelConformance.js +162 -0
  14. package/dist/AgentChannelConformance.js.map +1 -0
  15. package/dist/AgentChannelRuntime.d.ts +77 -0
  16. package/dist/AgentChannelRuntime.d.ts.map +1 -0
  17. package/dist/AgentChannelRuntime.js +269 -0
  18. package/dist/AgentChannelRuntime.js.map +1 -0
  19. package/dist/AiProvider.d.ts +131 -0
  20. package/dist/AiProvider.d.ts.map +1 -0
  21. package/dist/AiProvider.js +99 -0
  22. package/dist/AiProvider.js.map +1 -0
  23. package/dist/AuthMethod.d.ts +380 -0
  24. package/dist/AuthMethod.d.ts.map +1 -0
  25. package/dist/AuthMethod.js +224 -0
  26. package/dist/AuthMethod.js.map +1 -0
  27. package/dist/AuthMethodBinding.d.ts +76 -0
  28. package/dist/AuthMethodBinding.d.ts.map +1 -0
  29. package/dist/AuthMethodBinding.js +30 -0
  30. package/dist/AuthMethodBinding.js.map +1 -0
  31. package/dist/AuthMethodExecution.d.ts +222 -0
  32. package/dist/AuthMethodExecution.d.ts.map +1 -0
  33. package/dist/AuthMethodExecution.js +276 -0
  34. package/dist/AuthMethodExecution.js.map +1 -0
  35. package/dist/ConnectionResolver.d.ts +218 -0
  36. package/dist/ConnectionResolver.d.ts.map +1 -0
  37. package/dist/ConnectionResolver.js +152 -0
  38. package/dist/ConnectionResolver.js.map +1 -0
  39. package/dist/DefinitionError.d.ts +66 -0
  40. package/dist/DefinitionError.d.ts.map +1 -0
  41. package/dist/DefinitionError.js +81 -0
  42. package/dist/DefinitionError.js.map +1 -0
  43. package/dist/DualRegistry.d.ts +70 -0
  44. package/dist/DualRegistry.d.ts.map +1 -0
  45. package/dist/DualRegistry.js +95 -0
  46. package/dist/DualRegistry.js.map +1 -0
  47. package/dist/DualRuntime.d.ts +278 -0
  48. package/dist/DualRuntime.d.ts.map +1 -0
  49. package/dist/DualRuntime.js +310 -0
  50. package/dist/DualRuntime.js.map +1 -0
  51. package/dist/Files.d.ts +79 -0
  52. package/dist/Files.d.ts.map +1 -0
  53. package/dist/Files.js +65 -0
  54. package/dist/Files.js.map +1 -0
  55. package/dist/Group.d.ts +105 -0
  56. package/dist/Group.d.ts.map +1 -0
  57. package/dist/Group.js +85 -0
  58. package/dist/Group.js.map +1 -0
  59. package/dist/Http.d.ts +341 -0
  60. package/dist/Http.d.ts.map +1 -0
  61. package/dist/Http.js +676 -0
  62. package/dist/Http.js.map +1 -0
  63. package/dist/Mcp.d.ts +108 -0
  64. package/dist/Mcp.d.ts.map +1 -0
  65. package/dist/Mcp.js +175 -0
  66. package/dist/Mcp.js.map +1 -0
  67. package/dist/OAuth2TokenRefresher.d.ts +17 -0
  68. package/dist/OAuth2TokenRefresher.d.ts.map +1 -0
  69. package/dist/OAuth2TokenRefresher.js +18 -0
  70. package/dist/OAuth2TokenRefresher.js.map +1 -0
  71. package/dist/OAuthFlow.d.ts +70 -0
  72. package/dist/OAuthFlow.d.ts.map +1 -0
  73. package/dist/OAuthFlow.js +487 -0
  74. package/dist/OAuthFlow.js.map +1 -0
  75. package/dist/Plugin.d.ts +382 -0
  76. package/dist/Plugin.d.ts.map +1 -0
  77. package/dist/Plugin.js +248 -0
  78. package/dist/Plugin.js.map +1 -0
  79. package/dist/PluginRuntime.d.ts +3185 -0
  80. package/dist/PluginRuntime.d.ts.map +1 -0
  81. package/dist/PluginRuntime.js +330 -0
  82. package/dist/PluginRuntime.js.map +1 -0
  83. package/dist/Runner.d.ts +1 -0
  84. package/dist/Runner.js +123 -0
  85. package/dist/Runner.js.map +1 -0
  86. package/dist/ToolFile.d.ts +22 -0
  87. package/dist/ToolFile.d.ts.map +1 -0
  88. package/dist/ToolFile.js +32 -0
  89. package/dist/ToolFile.js.map +1 -0
  90. package/dist/Trigger.d.ts +357 -0
  91. package/dist/Trigger.d.ts.map +1 -0
  92. package/dist/Trigger.js +286 -0
  93. package/dist/Trigger.js.map +1 -0
  94. package/dist/_virtual/_rolldown/runtime.js +12 -0
  95. package/dist/index.d.ts +24 -0
  96. package/dist/index.js +24 -0
  97. package/dist/internal/auth-context.d.ts +21 -0
  98. package/dist/internal/auth-context.d.ts.map +1 -0
  99. package/dist/internal/auth-context.js +1 -0
  100. package/dist/internal/auth-execution.d.ts +25 -0
  101. package/dist/internal/auth-execution.d.ts.map +1 -0
  102. package/dist/internal/auth-execution.js +65 -0
  103. package/dist/internal/auth-execution.js.map +1 -0
  104. package/dist/internal/auth-runtime.d.ts +3 -0
  105. package/dist/internal/auth-runtime.d.ts.map +1 -0
  106. package/dist/internal/auth-runtime.js +15 -0
  107. package/dist/internal/auth-runtime.js.map +1 -0
  108. package/dist/internal/capabilities.d.ts +22 -0
  109. package/dist/internal/capabilities.d.ts.map +1 -0
  110. package/dist/internal/capabilities.js +21 -0
  111. package/dist/internal/capabilities.js.map +1 -0
  112. package/dist/internal/children.d.ts +32 -0
  113. package/dist/internal/children.d.ts.map +1 -0
  114. package/dist/internal/children.js +52 -0
  115. package/dist/internal/children.js.map +1 -0
  116. package/dist/internal/collection-utils.d.ts +2 -0
  117. package/dist/internal/collection-utils.d.ts.map +1 -0
  118. package/dist/internal/collection-utils.js +5 -0
  119. package/dist/internal/collection-utils.js.map +1 -0
  120. package/dist/internal/dual/actions.d.ts +31 -0
  121. package/dist/internal/dual/actions.d.ts.map +1 -0
  122. package/dist/internal/dual/actions.js +25 -0
  123. package/dist/internal/dual/actions.js.map +1 -0
  124. package/dist/internal/dual/invoke.d.ts +61 -0
  125. package/dist/internal/dual/invoke.d.ts.map +1 -0
  126. package/dist/internal/dual/invoke.js +74 -0
  127. package/dist/internal/dual/invoke.js.map +1 -0
  128. package/dist/internal/dual/registry.d.ts +123 -0
  129. package/dist/internal/dual/registry.d.ts.map +1 -0
  130. package/dist/internal/dual/registry.js +171 -0
  131. package/dist/internal/dual/registry.js.map +1 -0
  132. package/dist/internal/dual/triggers.d.ts +27 -0
  133. package/dist/internal/dual/triggers.d.ts.map +1 -0
  134. package/dist/internal/dual/triggers.js +25 -0
  135. package/dist/internal/dual/triggers.js.map +1 -0
  136. package/dist/internal/handler-context.d.ts +7 -0
  137. package/dist/internal/handler-context.d.ts.map +1 -0
  138. package/dist/internal/handler-context.js +30 -0
  139. package/dist/internal/handler-context.js.map +1 -0
  140. package/dist/internal/identifier.d.ts +4 -0
  141. package/dist/internal/identifier.d.ts.map +1 -0
  142. package/dist/internal/identifier.js +27 -0
  143. package/dist/internal/identifier.js.map +1 -0
  144. package/dist/internal/plugin-handlers.d.ts +36 -0
  145. package/dist/internal/plugin-handlers.d.ts.map +1 -0
  146. package/dist/internal/plugin-handlers.js +51 -0
  147. package/dist/internal/plugin-handlers.js.map +1 -0
  148. package/dist/internal/proto.d.ts +5 -0
  149. package/dist/internal/proto.d.ts.map +1 -0
  150. package/dist/internal/proto.js +9 -0
  151. package/dist/internal/proto.js.map +1 -0
  152. package/dist/internal/schema-runtime.d.ts +4 -0
  153. package/dist/internal/schema-runtime.d.ts.map +1 -0
  154. package/dist/internal/schema-runtime.js +9 -0
  155. package/dist/internal/schema-runtime.js.map +1 -0
  156. package/dist/internal/trigger-runtime-shared.d.ts +39 -0
  157. package/dist/internal/trigger-runtime-shared.d.ts.map +1 -0
  158. package/dist/internal/trigger-runtime-shared.js +131 -0
  159. package/dist/internal/trigger-runtime-shared.js.map +1 -0
  160. package/dist/internal/trigger-runtime.d.ts +10 -0
  161. package/dist/internal/trigger-runtime.d.ts.map +1 -0
  162. package/dist/internal/trigger-runtime.js +94 -0
  163. package/dist/internal/trigger-runtime.js.map +1 -0
  164. package/dist/internal/types.d.ts +5 -0
  165. package/dist/internal/types.d.ts.map +1 -0
  166. package/dist/internal/types.js +1 -0
  167. package/dist/remote-runtime.d.ts +584 -0
  168. package/dist/remote-runtime.d.ts.map +1 -0
  169. package/dist/remote-runtime.js +366 -0
  170. package/dist/remote-runtime.js.map +1 -0
  171. package/package.json +54 -4
  172. package/src/Action.ts +370 -0
  173. package/src/AgentChannel.ts +888 -0
  174. package/src/AgentChannelConformance.ts +124 -0
  175. package/src/AgentChannelRuntime.ts +617 -0
  176. package/src/AiProvider.ts +255 -0
  177. package/src/AuthMethod.ts +954 -0
  178. package/src/AuthMethodBinding.ts +112 -0
  179. package/src/AuthMethodExecution.ts +542 -0
  180. package/src/ConnectionResolver.ts +265 -0
  181. package/src/DefinitionError.ts +115 -0
  182. package/src/DualRegistry.ts +152 -0
  183. package/src/DualRuntime.ts +1081 -0
  184. package/src/Files.ts +89 -0
  185. package/src/Group.ts +292 -0
  186. package/src/Http.ts +1222 -0
  187. package/src/Mcp.ts +299 -0
  188. package/src/OAuth2TokenRefresher.ts +22 -0
  189. package/src/OAuthFlow.ts +874 -0
  190. package/src/Plugin.ts +912 -0
  191. package/src/PluginRuntime.ts +414 -0
  192. package/src/Runner.ts +249 -0
  193. package/src/ToolFile.ts +28 -0
  194. package/src/Trigger.ts +722 -0
  195. package/src/index.ts +158 -0
  196. package/src/internal/auth-context.ts +27 -0
  197. package/src/internal/auth-execution.ts +241 -0
  198. package/src/internal/auth-runtime.ts +20 -0
  199. package/src/internal/capabilities.ts +55 -0
  200. package/src/internal/children.ts +126 -0
  201. package/src/internal/collection-utils.ts +8 -0
  202. package/src/internal/dual/actions.ts +116 -0
  203. package/src/internal/dual/invoke.ts +307 -0
  204. package/src/internal/dual/registry.ts +340 -0
  205. package/src/internal/dual/triggers.ts +128 -0
  206. package/src/internal/handler-context.ts +57 -0
  207. package/src/internal/identifier.ts +27 -0
  208. package/src/internal/plugin-handlers.ts +146 -0
  209. package/src/internal/proto.ts +8 -0
  210. package/src/internal/schema-runtime.ts +15 -0
  211. package/src/internal/trigger-runtime-shared.ts +449 -0
  212. package/src/internal/trigger-runtime.ts +223 -0
  213. package/src/internal/types.ts +12 -0
  214. package/src/remote-runtime.ts +469 -0
package/src/Http.ts ADDED
@@ -0,0 +1,1222 @@
1
+ /**
2
+ * The HTTP runtime of generated API plugins: each operation's contract and call, request encoding,
3
+ * response decoding, continuation links, redirects and uploads.
4
+ *
5
+ * @since 0.0.0
6
+ */
7
+ import {
8
+ Array,
9
+ Boolean,
10
+ DateTime,
11
+ Effect,
12
+ Equal,
13
+ Option,
14
+ Order,
15
+ Predicate,
16
+ Random,
17
+ Record,
18
+ Result,
19
+ Schema,
20
+ SchemaGetter,
21
+ SchemaIssue,
22
+ String,
23
+ flow,
24
+ pipe,
25
+ } from "effect";
26
+ import type { SchemaAST } from "effect";
27
+
28
+ import { Base64, Base64Url } from "effect/encoding";
29
+ import {
30
+ FetchHttpClient,
31
+ HttpBody,
32
+ HttpClient,
33
+ HttpClientError,
34
+ HttpClientRequest,
35
+ Headers,
36
+ UrlParams,
37
+ } from "effect/http";
38
+ import type { HttpClientResponse } from "effect/http";
39
+
40
+ import * as Action from "./Action.ts";
41
+ import type * as AuthMethod from "./AuthMethod.ts";
42
+ import { Files } from "./Files.ts";
43
+ import { Mcp } from "./Mcp.ts";
44
+ import * as ToolFile from "./ToolFile.ts";
45
+
46
+ function preserveJsonProperties<A, Input>(value: A, input: Input): A {
47
+ if (Equal.equals(value, input)) return value;
48
+ if (Array.isArray(value) && Array.isArray(input)) {
49
+ for (const entry of Array.zip(value, input)) preserveJsonProperties(entry[0], entry[1]);
50
+ } else if (Predicate.isObject(value) && Predicate.isObject(input)) {
51
+ for (const entry of Record.toEntries(input)) {
52
+ if (Record.has(value, entry[0])) {
53
+ preserveJsonProperties(value[entry[0]], entry[1]);
54
+ } else {
55
+ Object.defineProperty(value, entry[0], {
56
+ configurable: true,
57
+ enumerable: true,
58
+ value: entry[1],
59
+ writable: true,
60
+ });
61
+ }
62
+ }
63
+ }
64
+ return value;
65
+ }
66
+
67
+ function decodeResponse<Output extends Schema.Top>(output: Output) {
68
+ return flow(
69
+ Effect.succeed,
70
+ Effect.flatMap(input =>
71
+ pipe(
72
+ Schema.decodeUnknownEffect(output)(input),
73
+ Effect.map(value => preserveJsonProperties(value, input)),
74
+ ),
75
+ ),
76
+ );
77
+ }
78
+
79
+ /**
80
+ * An action's input and output schemas.
81
+ *
82
+ * @since 0.0.0
83
+ * @category models
84
+ */
85
+ export interface Contract {
86
+ readonly input: Schema.Top;
87
+ readonly output: Schema.Top;
88
+ }
89
+
90
+ /**
91
+ * Runs an action: its input in, its output or a failure out.
92
+ *
93
+ * @since 0.0.0
94
+ * @category models
95
+ */
96
+ export type Handler<Methods extends readonly AuthMethod.Any[], Input, Output> = (
97
+ input: Input,
98
+ context: Action.HandlerContext<Methods>,
99
+ ) => Effect.Effect<Output, Action.ActionHandlerFailure, HttpClient.HttpClient>;
100
+
101
+ /**
102
+ * A file input: a ToolFile as a download returns it, or just its bytes with a type and name.
103
+ *
104
+ * @since 0.0.0
105
+ * @category schemas
106
+ */
107
+ export type File = typeof File.Type;
108
+ export const File = Schema.Struct({
109
+ _tag: Schema.optionalKey(Schema.Literal("ToolFile")),
110
+ contentBase64: Schema.Uint8ArrayFromBase64,
111
+ contentType: Schema.optionalKey(Schema.NullOr(Schema.String)),
112
+ filename: Schema.optionalKey(Schema.NullOr(Schema.String)),
113
+ sizeBytes: Schema.optionalKey(Schema.Natural),
114
+ }).annotate({
115
+ description:
116
+ "A ToolFile, such as the result of a download, passed unchanged; or its contentBase64 with an optional contentType and filename.",
117
+ });
118
+
119
+ const signatures: [string, [number, number[]][]][] = [
120
+ ["image/jpeg", [[0, [0xff, 0xd8, 0xff]]]],
121
+ ["image/png", [[0, [0x89, 0x50, 0x4e, 0x47]]]],
122
+ ["image/gif", [[0, [0x47, 0x49, 0x46, 0x38]]]],
123
+ [
124
+ "image/webp",
125
+ [
126
+ [0, [0x52, 0x49, 0x46, 0x46]],
127
+ [8, [0x57, 0x45, 0x42, 0x50]],
128
+ ],
129
+ ],
130
+ ["application/pdf", [[0, [0x25, 0x50, 0x44, 0x46]]]],
131
+ ["application/zip", [[0, [0x50, 0x4b, 0x03, 0x04]]]],
132
+ ];
133
+
134
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
135
+
136
+ function sniff(bytes: Uint8Array) {
137
+ return pipe(
138
+ Array.findFirst(signatures, signature =>
139
+ Array.every(signature[1], part =>
140
+ Array.every(part[1], (byte, index) => bytes[part[0] + index] === byte),
141
+ ),
142
+ ),
143
+ Option.map(signature => signature[0]),
144
+ Option.orElse(() =>
145
+ Option.liftPredicate("text/plain", () =>
146
+ Result.isSuccess(Result.try(() => utf8.decode(bytes))),
147
+ ),
148
+ ),
149
+ Option.getOrNull,
150
+ );
151
+ }
152
+
153
+ function toolFile(bytes: Uint8Array, declared: string | null, filename: string | null) {
154
+ return {
155
+ _tag: "ToolFile",
156
+ contentBase64: Base64.encode(bytes),
157
+ contentType:
158
+ declared === null || pipe(declared, String.startsWith("application/octet-stream"))
159
+ ? (sniff(bytes) ?? declared)
160
+ : declared,
161
+ filename,
162
+ sizeBytes: bytes.byteLength,
163
+ } satisfies ToolFile.File;
164
+ }
165
+
166
+ function invalid(expected: string, value: unknown, options: SchemaAST.ParseOptions) {
167
+ return Effect.fail(new SchemaIssue.InvalidValue({ expected }, value, options));
168
+ }
169
+
170
+ function decodeBytes(text: string, options: SchemaAST.ParseOptions) {
171
+ return Result.match(
172
+ Base64Url.decode(pipe(text, String.replaceAll("+", "-"), String.replaceAll("/", "_"))),
173
+ {
174
+ onFailure: () => invalid("a Base64 or Base64Url string", text, options),
175
+ onSuccess: bytes => Effect.succeed(bytes),
176
+ },
177
+ );
178
+ }
179
+
180
+ type Carrier = "base64" | "base64url" | "data-uri";
181
+
182
+ interface Content {
183
+ bytes: Uint8Array;
184
+ contentType: string | null;
185
+ }
186
+
187
+ function contentOf(carrier: Carrier) {
188
+ return SchemaGetter.transformEffect<Content, string>((text, options) => {
189
+ if (carrier !== "data-uri") {
190
+ return Effect.map(decodeBytes(text, options), bytes => ({ bytes, contentType: null }));
191
+ }
192
+ return Option.match(pipe(text, String.match(/^data:([^;,]*)(?:;[^;,]*)*;base64,(.*)$/su)), {
193
+ onNone: () => invalid("a Base64 data URI", text, options),
194
+ onSome: parts =>
195
+ Effect.map(decodeBytes(Array.getUnsafe(parts, 2), options), bytes => ({
196
+ bytes,
197
+ contentType: pipe(
198
+ Array.getUnsafe(parts, 1),
199
+ Option.liftPredicate(String.isNonEmpty),
200
+ Option.getOrNull,
201
+ ),
202
+ })),
203
+ });
204
+ });
205
+ }
206
+
207
+ function textOf(carrier: Carrier, content: Content) {
208
+ if (carrier === "base64") return Base64.encode(content.bytes);
209
+ if (carrier === "base64url") return Base64Url.encode(content.bytes);
210
+ const contentType = content.contentType ?? sniff(content.bytes) ?? "application/octet-stream";
211
+ return `data:${contentType};base64,${Base64.encode(content.bytes)}`;
212
+ }
213
+
214
+ function fileFrom(carrier: Carrier) {
215
+ return Schema.String.pipe(
216
+ Schema.decodeTo(ToolFile.Schema, {
217
+ decode: SchemaGetter.compose(
218
+ contentOf(carrier),
219
+ SchemaGetter.transform(content => toolFile(content.bytes, content.contentType, null)),
220
+ ),
221
+ encode: SchemaGetter.transformEffect((file: ToolFile.File, options) =>
222
+ Effect.map(decodeBytes(file.contentBase64, options), bytes =>
223
+ textOf(carrier, { bytes, contentType: file.contentType }),
224
+ ),
225
+ ),
226
+ }),
227
+ );
228
+ }
229
+
230
+ function encodedFrom(carrier: Carrier) {
231
+ return File.pipe(
232
+ Schema.decodeTo(Schema.String, {
233
+ decode: SchemaGetter.transform(file =>
234
+ textOf(carrier, { bytes: file.contentBase64, contentType: file.contentType ?? null }),
235
+ ),
236
+ encode: SchemaGetter.compose(
237
+ contentOf(carrier),
238
+ SchemaGetter.transform(content => ({
239
+ contentBase64: content.bytes,
240
+ contentType: content.contentType,
241
+ })),
242
+ ),
243
+ }),
244
+ );
245
+ }
246
+
247
+ /**
248
+ * A file the API returns as a Base64 string inside JSON, decoded into a ToolFile with its content
249
+ * type recognized from the bytes.
250
+ *
251
+ * @since 0.0.0
252
+ * @category schemas
253
+ */
254
+ export const FileFromBase64 = fileFrom("base64");
255
+
256
+ /**
257
+ * {@link FileFromBase64} for an API that writes the file in Base64Url.
258
+ *
259
+ * @since 0.0.0
260
+ * @category schemas
261
+ */
262
+ export const FileFromBase64Url = fileFrom("base64url");
263
+
264
+ /**
265
+ * A {@link File} input the API reads as a Base64 string inside JSON.
266
+ *
267
+ * @since 0.0.0
268
+ * @category schemas
269
+ */
270
+ export const Base64FromFile = encodedFrom("base64");
271
+
272
+ /**
273
+ * {@link Base64FromFile} for an API that reads the file in Base64Url.
274
+ *
275
+ * @since 0.0.0
276
+ * @category schemas
277
+ */
278
+ export const Base64UrlFromFile = encodedFrom("base64url");
279
+
280
+ /**
281
+ * {@link FileFromBase64} for an API that writes the file as a data URI, which also carries its
282
+ * content type.
283
+ *
284
+ * @since 0.0.0
285
+ * @category schemas
286
+ */
287
+ export const FileFromDataUri = fileFrom("data-uri");
288
+
289
+ /**
290
+ * {@link Base64FromFile} for an API that reads the file as a data URI, built from the file's
291
+ * content type.
292
+ *
293
+ * @since 0.0.0
294
+ * @category schemas
295
+ */
296
+ export const DataUriFromFile = encodedFrom("data-uri");
297
+
298
+ type DateTimeText = typeof DateTimeText.Type;
299
+ const DateTimeText = Schema.String.annotate({ format: "date-time" });
300
+
301
+ const rfc3339 = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.\d+)?(?:Z|([+-]\d{2}:\d{2}))$/u;
302
+
303
+ /** The instant of an RFC 3339 date-time with its offset; an impossible date such as February 30 has none. */
304
+ function rfc3339Instant(text: string) {
305
+ return pipe(
306
+ Option.fromNullishOr(rfc3339.exec(text)),
307
+ Option.flatMap(match =>
308
+ Option.filter(DateTime.makeZoned(text, { timeZone: match[2] ?? "+00:00" }), zoned =>
309
+ String.startsWith(match[1] ?? "")(DateTime.formatIsoOffset(zoned)),
310
+ ),
311
+ ),
312
+ Option.map(DateTime.toUtc),
313
+ );
314
+ }
315
+
316
+ function instants<Wire>(
317
+ wire: Schema.Codec<Wire>,
318
+ expected: string,
319
+ read: (value: Wire) => Option.Option<DateTime.Utc>,
320
+ write: (instant: DateTime.Utc) => Wire,
321
+ ) {
322
+ const fromWire = SchemaGetter.transformEffect<string, Wire>((value, options) =>
323
+ Option.match(read(value), {
324
+ onNone: () => invalid(expected, value, options),
325
+ onSome: instant => Effect.succeed(DateTime.formatIso(instant)),
326
+ }),
327
+ );
328
+ const toWire = SchemaGetter.transformEffect<Wire, string>((text, options) =>
329
+ Option.match(rfc3339Instant(text), {
330
+ onNone: () => invalid("an ISO 8601 date-time", text, options),
331
+ onSome: instant => Effect.succeed(write(instant)),
332
+ }),
333
+ );
334
+ return {
335
+ input: pipe(DateTimeText, Schema.decodeTo(wire, { decode: toWire, encode: fromWire })),
336
+ output: pipe(wire, Schema.decodeTo(DateTimeText, { decode: fromWire, encode: toWire })),
337
+ };
338
+ }
339
+
340
+ const unixSeconds = instants(
341
+ Schema.Int,
342
+ "Unix seconds",
343
+ seconds => Option.map(DateTime.make(seconds * 1000), DateTime.toUtc),
344
+ instant => Math.floor(DateTime.toEpochMillis(instant) / 1000),
345
+ );
346
+
347
+ const rfc2822 = instants(
348
+ Schema.String,
349
+ "an RFC 2822 date-time",
350
+ text => Option.map(DateTime.make(text), DateTime.toUtc),
351
+ instant => DateTime.toDateUtc(instant).toUTCString(),
352
+ );
353
+
354
+ /**
355
+ * A date-time the API writes as Unix seconds, decoded into an ISO 8601 UTC string.
356
+ *
357
+ * @since 0.0.0
358
+ * @category schemas
359
+ */
360
+ export const DateTimeFromUnixSeconds = unixSeconds.output;
361
+
362
+ /**
363
+ * An ISO 8601 date-time input the API reads as Unix seconds.
364
+ *
365
+ * @since 0.0.0
366
+ * @category schemas
367
+ */
368
+ export const UnixSecondsFromDateTime = unixSeconds.input;
369
+
370
+ /**
371
+ * A date-time the API writes in RFC 2822 form, decoded into an ISO 8601 UTC string.
372
+ *
373
+ * @since 0.0.0
374
+ * @category schemas
375
+ */
376
+ export const DateTimeFromRfc2822 = rfc2822.output;
377
+
378
+ /**
379
+ * An ISO 8601 date-time input the API reads in RFC 2822 form.
380
+ *
381
+ * @since 0.0.0
382
+ * @category schemas
383
+ */
384
+ export const Rfc2822FromDateTime = rfc2822.input;
385
+
386
+ /**
387
+ * An action output whose response decodes into a different shape, such as a file the API sends as
388
+ * Base64: the action declares the decoded shape and the call decodes the response with `wire`.
389
+ *
390
+ * @since 0.0.0
391
+ * @category models
392
+ */
393
+ export interface Decoded<Wire extends Schema.Top> {
394
+ readonly _tag: "Decoded";
395
+ readonly wire: Wire;
396
+ }
397
+
398
+ /**
399
+ * Declares an output by the response schema it decodes from; see {@link Decoded}.
400
+ *
401
+ * @since 0.0.0
402
+ * @category constructors
403
+ */
404
+ export function decoded<const Wire extends Schema.Top>(wire: Wire): Decoded<Wire> {
405
+ return { _tag: "Decoded", wire };
406
+ }
407
+
408
+ type Request =
409
+ | HttpClientRequest.HttpClientRequest
410
+ | Effect.Effect<HttpClientRequest.HttpClientRequest, Action.ActionHandlerError>;
411
+
412
+ /** `binary` returns a released version's base64 `ToolFile`; `file` stores the body as a file. */
413
+ type Body = "json" | "text" | "binary" | "file" | "void" | "unknown";
414
+
415
+ type GraphqlResponse = typeof GraphqlResponse.Type;
416
+ const GraphqlResponse = Schema.Struct({
417
+ data: Schema.optionalKey(Schema.NullOr(Schema.Record(Schema.String, Schema.Unknown))),
418
+ errors: Schema.optionalKey(
419
+ Schema.Array(
420
+ Schema.StructWithRest(Schema.Struct({ message: Schema.String }), [
421
+ Schema.Record(Schema.String, Schema.Unknown),
422
+ ]),
423
+ ),
424
+ ),
425
+ });
426
+
427
+ /**
428
+ * A response status, media type and decoding mode advertised by an HTTP action.
429
+ *
430
+ * @since 0.4.1
431
+ * @category models
432
+ */
433
+ export interface Variant {
434
+ readonly status?: number;
435
+ readonly contentType: string;
436
+ readonly body: Body;
437
+ readonly headers?: readonly string[];
438
+ }
439
+
440
+ type Media =
441
+ | { readonly contentBase64: Uint8Array; readonly contentType?: string | null }
442
+ | Files.File;
443
+
444
+ type Upload =
445
+ | { readonly mode: "media"; readonly media: Media }
446
+ | { readonly mode: "multipart"; readonly media: Media; readonly metadata: unknown }
447
+ | {
448
+ readonly mode: "start";
449
+ readonly contentType: string;
450
+ readonly metadata?: unknown;
451
+ readonly totalBytes: number;
452
+ }
453
+ | {
454
+ readonly mode: "chunk";
455
+ readonly sessionUrl: string;
456
+ readonly totalBytes: number;
457
+ readonly offset: number;
458
+ readonly media: Media;
459
+ }
460
+ | { readonly mode: "status"; readonly sessionUrl: string; readonly totalBytes: number };
461
+
462
+ function coerce(value: unknown) {
463
+ return Predicate.isObject(value) ? JSON.stringify(value) : `${value}`;
464
+ }
465
+
466
+ /**
467
+ * Encodes a path parameter as one segment.
468
+ *
469
+ * @since 0.0.0
470
+ * @category encoding
471
+ */
472
+ export function path(value: unknown) {
473
+ return encodeURIComponent(coerce(value));
474
+ }
475
+
476
+ /**
477
+ * Encodes a path parameter written inside single quotes, an OData string literal, doubling its
478
+ * quotes: `O'Brien` in `People('{name}')` is sent as `People('O''Brien')`.
479
+ *
480
+ * @since 0.0.0
481
+ * @category encoding
482
+ */
483
+ export function literal(value: unknown) {
484
+ return path(pipe(coerce(value), String.replaceAll("'", "''")));
485
+ }
486
+
487
+ /**
488
+ * Encodes a path parameter whose slashes stay path separators.
489
+ *
490
+ * @since 0.0.0
491
+ * @category encoding
492
+ */
493
+ export function segments(value: unknown) {
494
+ return Array.join(Array.map(String.split(coerce(value), "/"), encodeURIComponent), "/");
495
+ }
496
+
497
+ function deepObject(name: string, value: unknown): [string, string][] {
498
+ if (Array.isArray(value)) {
499
+ return Array.flatMap(value, (item, index) => deepObject(`${name}[${index}]`, item));
500
+ }
501
+ if (Predicate.isObject(value)) {
502
+ return Array.flatMap(Record.toEntries(value), entry =>
503
+ deepObject(`${name}[${entry[0]}]`, entry[1]),
504
+ );
505
+ }
506
+ return value === undefined ? [] : [[name, coerce(value)]];
507
+ }
508
+
509
+ /**
510
+ * Query, header or form entries, repeating array values unless their name is joined, and encoding
511
+ * `deep` names as bracketed keys such as `metadata[plan]` and `expand[0]`. A joined name is
512
+ * comma-separated, or separated by the delimiter it is paired with, such as `["ids", "|"]`.
513
+ * `exploded` object parameters use their property names as query keys (`role=vet&active=true`).
514
+ *
515
+ * @since 0.0.0
516
+ * @category encoding
517
+ */
518
+ export function params(
519
+ fields: Record.ReadonlyRecord<string, unknown>,
520
+ joined: readonly (string | readonly [string, string])[] = [],
521
+ deep: readonly string[] = [],
522
+ exploded: readonly string[] = [],
523
+ ) {
524
+ return Array.flatMap(Record.toEntries(fields), field => {
525
+ if (field[1] === undefined) return [];
526
+ if (Array.contains(deep, field[0])) return deepObject(field[0], field[1]);
527
+ const values = field[1];
528
+ if (
529
+ Array.contains(exploded, field[0]) &&
530
+ Predicate.isObject(values) &&
531
+ !Array.isArray(values)
532
+ ) {
533
+ return Array.filterMap(Record.toEntries(values), entry =>
534
+ entry[1] === undefined
535
+ ? Result.failVoid
536
+ : Result.succeed([entry[0], coerce(entry[1])] as const),
537
+ );
538
+ }
539
+ if (!Array.isArray(values)) return [[field[0], coerce(values)] as const];
540
+ const separator = Array.findFirst(joined, entry => {
541
+ const pair = Predicate.isString(entry) ? ([entry, ","] as const) : entry;
542
+ return pair[0] === field[0] ? Option.some(pair[1]) : Option.none();
543
+ });
544
+ return Option.match(separator, {
545
+ onNone: () => Array.map(values, item => [field[0], coerce(item)] as const),
546
+ onSome: value => [[field[0], Array.join(Array.map(values, coerce), value)] as const],
547
+ });
548
+ });
549
+ }
550
+
551
+ function filePart(bytes: Uint8Array, name: string, contentType: string) {
552
+ return new globalThis.File([new Uint8Array(bytes)], name, { type: contentType });
553
+ }
554
+
555
+ /**
556
+ * Multipart form fields, sending each {@link File} as a file part.
557
+ *
558
+ * @since 0.0.0
559
+ * @category encoding
560
+ */
561
+ export function form(payload: Record.ReadonlyRecord<string, unknown>) {
562
+ return Record.map(payload, (value, name) =>
563
+ Array.map(Array.ensure(value), item => {
564
+ if (item === undefined) return undefined;
565
+ if (!Schema.is(File)(item)) return coerce(item);
566
+ return filePart(
567
+ item.contentBase64,
568
+ item.filename ?? name,
569
+ item.contentType ?? "application/octet-stream",
570
+ );
571
+ }),
572
+ );
573
+ }
574
+
575
+ function fileFailed(error: Files.FileError) {
576
+ return Action.ActionHandlerError.make({ cause: error, message: error.message });
577
+ }
578
+
579
+ function readFile(file: Files.File) {
580
+ return pipe(Files.read(file), Effect.mapError(fileFailed));
581
+ }
582
+
583
+ /**
584
+ * Sends a file as the raw request body.
585
+ *
586
+ * @since 0.1.0
587
+ * @category encoding
588
+ */
589
+ export const withFile = Effect.fnUntraced(function* (
590
+ request: HttpClientRequest.HttpClientRequest,
591
+ file: Files.File,
592
+ ) {
593
+ return HttpClientRequest.bodyUint8Array(request, yield* readFile(file), file.contentType);
594
+ });
595
+
596
+ /**
597
+ * Sends multipart form fields, each {@link Files.File} as a file part.
598
+ *
599
+ * @since 0.1.0
600
+ * @category encoding
601
+ */
602
+ export const withForm = Effect.fnUntraced(function* (
603
+ request: HttpClientRequest.HttpClientRequest,
604
+ payload: Record.ReadonlyRecord<string, unknown>,
605
+ ) {
606
+ return HttpClientRequest.bodyFormDataRecord(
607
+ request,
608
+ Record.fromEntries(
609
+ yield* Effect.forEach(Record.toEntries(payload), field =>
610
+ Effect.map(
611
+ Effect.forEach(
612
+ Array.filter(Array.ensure(field[1]), item => item !== undefined),
613
+ item =>
614
+ Effect.gen(function* () {
615
+ if (!Schema.is(Files.File)(item)) return coerce(item);
616
+ return filePart(yield* readFile(item), item.name, item.contentType);
617
+ }),
618
+ ),
619
+ parts => [field[0], parts] satisfies [string, (string | globalThis.File)[]],
620
+ ),
621
+ ),
622
+ ),
623
+ );
624
+ });
625
+
626
+ function mediaBytes(media: Media) {
627
+ if (Schema.is(Files.File)(media)) {
628
+ return Effect.map(readFile(media), bytes => ({ bytes, contentType: media.contentType }));
629
+ }
630
+ return Effect.succeed({
631
+ bytes: media.contentBase64,
632
+ contentType: Option.getOrNull(Option.fromNullishOr(media.contentType)),
633
+ });
634
+ }
635
+
636
+ function isSafeUrl(value: string, origin?: string) {
637
+ if (!URL.canParse(value)) return false;
638
+ const url = new URL(value);
639
+ return (
640
+ url.protocol === "https:" &&
641
+ url.username === "" &&
642
+ url.password === "" &&
643
+ (origin === undefined || url.origin === origin)
644
+ );
645
+ }
646
+
647
+ function refused(message: string) {
648
+ return Effect.fail(Action.ActionHandlerError.make({ message }));
649
+ }
650
+
651
+ /**
652
+ * Follows a returned next-page link on the operation's own origin: only its path and query are
653
+ * taken, so the connection's host routing applies and credentials never reach another host.
654
+ *
655
+ * @since 0.0.0
656
+ * @category requests
657
+ */
658
+ export function continuation(request: HttpClientRequest.HttpClientRequest, nextLink?: string) {
659
+ if (nextLink === undefined) return Effect.succeed(request);
660
+ const declared = new URL(request.url);
661
+ const next = URL.canParse(nextLink) ? new URL(nextLink) : undefined;
662
+ if (next === undefined || !isSafeUrl(nextLink) || next.pathname !== declared.pathname) {
663
+ return refused("A continuation URL must be an HTTPS link to the same operation path");
664
+ }
665
+ return Effect.succeed(
666
+ HttpClientRequest.makeWith(
667
+ request.method,
668
+ `${declared.origin}${next.pathname}${next.search}`,
669
+ UrlParams.empty,
670
+ Option.none(),
671
+ request.headers,
672
+ HttpBody.empty,
673
+ ),
674
+ );
675
+ }
676
+
677
+ /**
678
+ * A request to a preauthenticated upload URL, which is sent without the connection's credentials.
679
+ *
680
+ * @since 0.0.0
681
+ * @category requests
682
+ */
683
+ export function preauthenticated(
684
+ method: (url: string) => HttpClientRequest.HttpClientRequest,
685
+ url: string,
686
+ ...steps: readonly ((
687
+ request: HttpClientRequest.HttpClientRequest,
688
+ ) => HttpClientRequest.HttpClientRequest)[]
689
+ ) {
690
+ if (!isSafeUrl(url)) return refused("An upload session requires a preauthenticated HTTPS URL");
691
+ return Effect.succeed(Array.reduce(steps, method(url), (request, step) => step(request)));
692
+ }
693
+
694
+ function failure(
695
+ error:
696
+ | Action.ActionHandlerError
697
+ | Action.HttpClientFailure
698
+ | { readonly cause: unknown; readonly response: HttpClientResponse.HttpClientResponse },
699
+ ) {
700
+ return Schema.is(Action.ActionHandlerError)(error) ? error : Action.fromHttpClientFailure(error);
701
+ }
702
+
703
+ // Like HttpClient.followRedirects, except that a redirect to another origin sends no
704
+ // request header at all: auth methods may set any header, such as GitLab's PRIVATE-TOKEN.
705
+ function redirect(response: HttpClientResponse.HttpClientResponse) {
706
+ const location = response.headers["location"];
707
+ if (response.status < 300 || response.status >= 400 || location === undefined) return undefined;
708
+ const sent = response.request;
709
+ const url = new URL(location, sent.url);
710
+ const request =
711
+ (response.status === 303 && sent.method !== "GET" && sent.method !== "HEAD") ||
712
+ ((response.status === 301 || response.status === 302) && sent.method === "POST")
713
+ ? HttpClientRequest.setBody(HttpClientRequest.setMethod(sent, "GET"), HttpBody.empty)
714
+ : sent;
715
+ return url.origin === new URL(sent.url).origin
716
+ ? HttpClientRequest.setUrl(request, url)
717
+ : HttpClientRequest.setUrl(
718
+ HttpClientRequest.makeWith(
719
+ request.method,
720
+ "",
721
+ UrlParams.empty,
722
+ Option.none(),
723
+ Headers.empty,
724
+ request.body,
725
+ ),
726
+ url,
727
+ );
728
+ }
729
+
730
+ function follow(
731
+ client: HttpClient.HttpClient,
732
+ response: HttpClientResponse.HttpClientResponse,
733
+ redirects: number,
734
+ ): Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError> {
735
+ const next = redirect(response);
736
+ return next === undefined || redirects === 10
737
+ ? Effect.succeed(response)
738
+ : Effect.flatMap(client.execute(next), result => follow(client, result, redirects + 1));
739
+ }
740
+
741
+ /** The file name a `Content-Disposition` header suggests, preferring its encoded form. */
742
+ function dispositionName(header?: string) {
743
+ if (header === undefined) return undefined;
744
+ const encoded = pipe(
745
+ String.match(/(?:^|;)\s*filename\*\s*=\s*UTF-8'[^']*'([^;]+)/iu)(header),
746
+ Option.flatMap(match => Option.fromUndefinedOr(match[1])),
747
+ );
748
+ const decoded = pipe(
749
+ encoded,
750
+ Option.flatMap(value => Option.liftThrowable(() => decodeURIComponent(String.trim(value)))()),
751
+ );
752
+ return Option.getOrElse(decoded, () =>
753
+ pipe(
754
+ String.match(/(?:^|;)\s*filename\s*=\s*(?:"((?:\\.|[^"\\])*)"|([^;]*))/iu)(header),
755
+ Option.flatMap(match =>
756
+ Option.orElse(
757
+ Option.map(Option.fromUndefinedOr(match[1]), name =>
758
+ String.replace(/\\(.)/gu, "$1")(name),
759
+ ),
760
+ () => Option.map(Option.fromUndefinedOr(match[2]), String.trim),
761
+ ),
762
+ ),
763
+ Option.getOrUndefined,
764
+ ),
765
+ );
766
+ }
767
+
768
+ const read = Effect.fnUntraced(function* (
769
+ response: HttpClientResponse.HttpClientResponse,
770
+ body: Body,
771
+ ) {
772
+ if (body === "json") return yield* response.json;
773
+ if (body === "text") return yield* response.text;
774
+ if (body === "void") return {};
775
+ if (body === "unknown") {
776
+ const text = yield* response.text;
777
+ if (String.isEmpty(String.trim(text))) return null;
778
+ return Option.getOrElse(
779
+ Schema.decodeOption(Schema.fromJsonString(Schema.Json))(text),
780
+ () => text,
781
+ );
782
+ }
783
+ const bytes = new Uint8Array(yield* response.arrayBuffer);
784
+ const name = dispositionName(response.headers["content-disposition"]);
785
+ if (body === "file") {
786
+ return yield* pipe(
787
+ Files.write({
788
+ bytes,
789
+ contentType: Option.getOrNull(Option.fromUndefinedOr(response.headers["content-type"])),
790
+ name: name ?? "file",
791
+ }),
792
+ Effect.mapError(fileFailed),
793
+ );
794
+ }
795
+ return toolFile(bytes, response.headers["content-type"] ?? null, name ?? null);
796
+ });
797
+
798
+ /**
799
+ * One API operation as {@link make} returns it: its contract and the call that performs it. The
800
+ * `Context` parameter lets a package name its handler context once, so declaration files print
801
+ * `Endpoint<Context, …>` instead of repeating its auth methods in every action.
802
+ *
803
+ * @since 0.0.0
804
+ * @category models
805
+ */
806
+ export interface Endpoint<Context, Input extends Schema.Top, Output extends Schema.Top> {
807
+ readonly input: Input;
808
+ readonly output: Output;
809
+ readonly run: (
810
+ input: Input["Type"],
811
+ context: Context,
812
+ ) => Effect.Effect<Output["Type"], Action.ActionHandlerFailure, HttpClient.HttpClient>;
813
+ }
814
+
815
+ /**
816
+ * An {@link Endpoint} whose output is the decoded type of the response schema it keeps as `wire`.
817
+ *
818
+ * @since 0.0.0
819
+ * @category models
820
+ */
821
+ export interface DecodedEndpoint<Context, Input extends Schema.Top, Wire extends Schema.Top> {
822
+ readonly input: Input;
823
+ readonly output: Schema.toType<Wire>;
824
+ readonly wire: Wire;
825
+ readonly run: (
826
+ input: Input["Type"],
827
+ context: Context,
828
+ ) => Effect.Effect<Wire["Type"], Action.ActionHandlerFailure, HttpClient.HttpClient>;
829
+ }
830
+
831
+ /**
832
+ * Binds the runtime to a package's auth module: the calls a generated version file makes. Its
833
+ * `authorize` applies a connection's credentials to the client. Its optional `checkResponse` fails
834
+ * a successful response that reports a failed call, such as Slack's `{ ok: false, error }`.
835
+ * `preauthenticatedUploadUrl` restricts credential-free upload requests and every redirect to
836
+ * provider-approved HTTPS URLs, without changing authenticated calls or other providers.
837
+ *
838
+ * @since 0.0.0
839
+ * @category constructors
840
+ */
841
+ export function make<
842
+ const Methods extends readonly AuthMethod.Any[],
843
+ Context extends Action.HandlerContext<Methods> = Action.HandlerContext<Methods>,
844
+ >(auth: {
845
+ readonly authorize: (
846
+ client: HttpClient.HttpClient,
847
+ context: Action.HandlerContext<Methods>,
848
+ ) => HttpClient.HttpClient;
849
+ readonly checkResponse?: (
850
+ response: HttpClientResponse.HttpClientResponse,
851
+ ) => Effect.Effect<void, Action.ActionHandlerError | HttpClientError.HttpClientError>;
852
+ readonly preauthenticatedUploadUrl?: Schema.Schema<string>;
853
+ }) {
854
+ const { authorize, checkResponse = () => Effect.void } = auth;
855
+ const send = Effect.fnUntraced(function* (context: Context | undefined, request: Request) {
856
+ const base = yield* HttpClient.HttpClient;
857
+ const uploadPolicy = context === undefined ? auth.preauthenticatedUploadUrl : undefined;
858
+ const client =
859
+ uploadPolicy === undefined
860
+ ? base
861
+ : HttpClient.mapRequestEffect(base, outgoing =>
862
+ isSafeUrl(outgoing.url) && Schema.is(uploadPolicy)(outgoing.url)
863
+ ? Effect.succeed(outgoing)
864
+ : Effect.fail(
865
+ new HttpClientError.HttpClientError({
866
+ reason: new HttpClientError.InvalidUrlError({
867
+ description: "The upload URL is not an approved provider HTTPS destination",
868
+ request: outgoing,
869
+ }),
870
+ }),
871
+ ),
872
+ );
873
+ const transport = HttpClient.transformResponse(
874
+ client,
875
+ Effect.flatMap(response => follow(client, response, 0)),
876
+ );
877
+ const authorized = context === undefined ? transport : authorize(transport, context);
878
+ const execution = authorized.execute(Effect.isEffect(request) ? yield* request : request);
879
+ const options = yield* Effect.serviceOption(FetchHttpClient.RequestInit);
880
+ const response = yield* Boolean.match(uploadPolicy !== undefined, {
881
+ onFalse: () => execution,
882
+ onTrue: () =>
883
+ Effect.provideService(execution, FetchHttpClient.RequestInit, {
884
+ ...Option.getOrElse(options, () => ({})),
885
+ redirect: "manual",
886
+ }),
887
+ });
888
+ if (response.status < 200 || response.status >= 300) {
889
+ return yield* Effect.fail({ cause: yield* response.text, response });
890
+ }
891
+ yield* checkResponse(response);
892
+ return response;
893
+ });
894
+
895
+ /**
896
+ * One API operation: its action contract and the call that performs it. A {@link Decoded} output
897
+ * declares the decoded shape and hands the call its response schema.
898
+ */
899
+ function endpoint<const Input extends Schema.Top, const Output extends Schema.Top>(
900
+ contract: { readonly input: Input; readonly output: Output },
901
+ run: (
902
+ input: Input["Type"],
903
+ context: Context,
904
+ output: Output,
905
+ ) => Effect.Effect<Output["Type"], Action.ActionHandlerFailure, HttpClient.HttpClient>,
906
+ ): Endpoint<Context, Input, Output>;
907
+ function endpoint<const Input extends Schema.Top, const Wire extends Schema.Top>(
908
+ contract: { readonly input: Input; readonly output: Decoded<Wire> },
909
+ run: (
910
+ input: Input["Type"],
911
+ context: Context,
912
+ output: Wire,
913
+ ) => Effect.Effect<Wire["Type"], Action.ActionHandlerFailure, HttpClient.HttpClient>,
914
+ ): DecodedEndpoint<Context, Input, Wire>;
915
+ function endpoint<const Input extends Schema.Top, const Output extends Schema.Top>(
916
+ contract: { readonly input: Input; readonly output: Output | Decoded<Output> },
917
+ run: (
918
+ input: Input["Type"],
919
+ context: Context,
920
+ output: Output,
921
+ ) => Effect.Effect<Output["Type"], Action.ActionHandlerFailure, HttpClient.HttpClient>,
922
+ ) {
923
+ if (!Schema.isSchema(contract.output)) {
924
+ const wire = contract.output.wire;
925
+ return {
926
+ input: contract.input,
927
+ output: Schema.toType(wire),
928
+ run: (input: Input["Type"], context: Context) => run(input, context, wire),
929
+ wire,
930
+ };
931
+ }
932
+ const output = contract.output;
933
+ return {
934
+ input: contract.input,
935
+ output,
936
+ run: (input: Input["Type"], context: Context) => run(input, context, output),
937
+ };
938
+ }
939
+
940
+ /** Sends a request and decodes its body as the operation's single response. */
941
+ function execute<Output extends Schema.Top>(
942
+ context: Context | undefined,
943
+ output: Output,
944
+ request: Request,
945
+ body: Body,
946
+ ) {
947
+ return pipe(
948
+ send(context, request),
949
+ Effect.flatMap(response => read(response, body)),
950
+ Effect.flatMap(decodeResponse(output)),
951
+ Effect.mapError(failure),
952
+ );
953
+ }
954
+
955
+ /** Sends a request and decodes the declared response variant its status and media type select. */
956
+ const variants = Effect.fnUntraced(function* <Output extends Schema.Top>(
957
+ context: Context | undefined,
958
+ output: Output,
959
+ request: Request,
960
+ declared: readonly Variant[],
961
+ media?: boolean,
962
+ ) {
963
+ const response = yield* send(context, request);
964
+ const exact = Array.flatMap(declared, variant =>
965
+ variant.status === undefined ? [] : [variant.status],
966
+ );
967
+ const contentType = pipe(
968
+ response.headers["content-type"] ?? "",
969
+ String.split(";"),
970
+ Array.headNonEmpty,
971
+ String.trim,
972
+ String.toLowerCase,
973
+ );
974
+ const ordered = Array.sort(
975
+ declared,
976
+ Order.mapInput(Order.Number, (variant: Variant) => {
977
+ if (variant.body === "void" || variant.body === "unknown") return 3;
978
+ if (variant.contentType === "*/*") return 2;
979
+ return pipe(variant.contentType, String.endsWith("/*")) ? 1 : 0;
980
+ }),
981
+ );
982
+ const variant = Array.findFirst(ordered, candidate => {
983
+ const status =
984
+ candidate.status === undefined
985
+ ? !Array.contains(exact, response.status)
986
+ : candidate.status === response.status;
987
+ if (!status) return false;
988
+ if (media !== undefined) {
989
+ return (candidate.body === "binary" || candidate.body === "file") === media;
990
+ }
991
+ if (
992
+ candidate.body === "void" ||
993
+ candidate.body === "unknown" ||
994
+ candidate.contentType === "*/*"
995
+ ) {
996
+ return true;
997
+ }
998
+ if (pipe(candidate.contentType, String.endsWith("/*"))) {
999
+ return pipe(
1000
+ contentType,
1001
+ String.startsWith(pipe(candidate.contentType, String.slice(0, -1))),
1002
+ );
1003
+ }
1004
+ return contentType === candidate.contentType;
1005
+ });
1006
+ if (Option.isNone(variant)) {
1007
+ return yield* Effect.fail({
1008
+ cause: "The API returned an undeclared successful response",
1009
+ response,
1010
+ });
1011
+ }
1012
+ const headers = Array.flatMap(variant.value.headers ?? [], name => {
1013
+ const value = response.headers[String.toLowerCase(name)];
1014
+ return value === undefined ? [] : [[name, value] as const];
1015
+ });
1016
+ return yield* decodeResponse(output)({
1017
+ body: yield* read(response, variant.value.body),
1018
+ contentType: variant.value.contentType,
1019
+ status: response.status,
1020
+ ...(variant.value.headers === undefined ? {} : { headers: Record.fromEntries(headers) }),
1021
+ });
1022
+ }, Effect.mapError(failure));
1023
+
1024
+ /** Google's media, multipart and resumable upload protocols. */
1025
+ const googleUpload = Effect.fnUntraced(function* <Output extends Schema.Top>(
1026
+ context: Context,
1027
+ output: Output,
1028
+ request: HttpClientRequest.HttpClientRequest,
1029
+ payload: Upload,
1030
+ options: { readonly maxSize?: number; readonly resumable?: string },
1031
+ ) {
1032
+ const client = authorize(yield* HttpClient.HttpClient, context);
1033
+ const media = "media" in payload ? yield* mediaBytes(payload.media) : undefined;
1034
+ const size = "totalBytes" in payload ? payload.totalBytes : (media?.bytes.byteLength ?? 0);
1035
+ if (size < 0 || (options.maxSize !== undefined && size > options.maxSize)) {
1036
+ return yield* refused("The upload size is outside the API's declared limit");
1037
+ }
1038
+ const origin = new URL(request.url).origin;
1039
+ if (payload.mode === "start") {
1040
+ if (options.resumable === undefined) {
1041
+ return yield* refused("This API has no resumable upload protocol");
1042
+ }
1043
+ const response = yield* client.execute(
1044
+ pipe(
1045
+ HttpClientRequest.setUrl(request, options.resumable),
1046
+ HttpClientRequest.setUrlParam("uploadType", "resumable"),
1047
+ HttpClientRequest.setHeaders({
1048
+ "x-upload-content-length": `${size}`,
1049
+ "x-upload-content-type": payload.contentType,
1050
+ }),
1051
+ HttpClientRequest.bodyJsonUnsafe(payload.metadata ?? {}),
1052
+ ),
1053
+ );
1054
+ if (response.status < 200 || response.status >= 300) {
1055
+ return yield* Effect.fail({ cause: yield* response.text, response });
1056
+ }
1057
+ const sessionUrl = response.headers["location"];
1058
+ if (sessionUrl === undefined || !isSafeUrl(sessionUrl, origin)) {
1059
+ return yield* Effect.fail({
1060
+ cause: "The API returned an invalid upload session URL",
1061
+ response,
1062
+ });
1063
+ }
1064
+ return yield* decodeResponse(output)({ nextOffset: 0, sessionUrl, state: "pending" });
1065
+ }
1066
+ if (payload.mode === "chunk" || payload.mode === "status") {
1067
+ if (!isSafeUrl(payload.sessionUrl, origin)) {
1068
+ return yield* refused("The upload session URL must use the API's HTTPS origin");
1069
+ }
1070
+ const bytes = media?.bytes ?? new Uint8Array();
1071
+ const end = payload.mode === "chunk" ? payload.offset + bytes.byteLength : 0;
1072
+ if (
1073
+ payload.mode === "chunk" &&
1074
+ (payload.offset < 0 ||
1075
+ bytes.byteLength === 0 ||
1076
+ end > size ||
1077
+ (end < size && bytes.byteLength % 262_144 !== 0))
1078
+ ) {
1079
+ return yield* refused(
1080
+ "Upload chunks must fit the total size and use 256 KiB multiples except for the final chunk",
1081
+ );
1082
+ }
1083
+ const response = yield* client.execute(
1084
+ pipe(
1085
+ HttpClientRequest.put(payload.sessionUrl),
1086
+ HttpClientRequest.bodyUint8Array(bytes, media?.contentType ?? "application/octet-stream"),
1087
+ HttpClientRequest.setHeader(
1088
+ "content-range",
1089
+ payload.mode === "status"
1090
+ ? `bytes */${size}`
1091
+ : `bytes ${payload.offset}-${end - 1}/${size}`,
1092
+ ),
1093
+ ),
1094
+ );
1095
+ if (response.status === 308) {
1096
+ const range = response.headers["range"];
1097
+ if (range !== undefined && !/^bytes=0-\d+$/u.test(range)) {
1098
+ return yield* Effect.fail({
1099
+ cause: "The API returned an invalid upload range",
1100
+ response,
1101
+ });
1102
+ }
1103
+ const nextOffset = range === undefined ? 0 : Number(pipe(range, String.slice(8))) + 1;
1104
+ if (nextOffset > size) {
1105
+ return yield* Effect.fail({
1106
+ cause: "The API returned an upload offset beyond the total size",
1107
+ response,
1108
+ });
1109
+ }
1110
+ return yield* decodeResponse(output)({
1111
+ nextOffset,
1112
+ sessionUrl: payload.sessionUrl,
1113
+ state: "pending",
1114
+ });
1115
+ }
1116
+ if (response.status < 200 || response.status >= 300) {
1117
+ return yield* Effect.fail({ cause: yield* response.text, response });
1118
+ }
1119
+ return yield* decodeResponse(output)({ resource: yield* response.json, state: "complete" });
1120
+ }
1121
+ const selected = HttpClientRequest.setUrlParam(request, "uploadType", payload.mode);
1122
+ const bytes = media?.bytes ?? new Uint8Array();
1123
+ const contentType = media?.contentType ?? "application/octet-stream";
1124
+ const boundary = `dual-${yield* Random.nextInt}-${yield* Random.nextInt}`;
1125
+ const metadata =
1126
+ payload.mode === "multipart"
1127
+ ? yield* Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown))(payload.metadata)
1128
+ : "";
1129
+ const body =
1130
+ payload.mode === "media"
1131
+ ? HttpClientRequest.bodyUint8Array(selected, bytes, contentType)
1132
+ : HttpClientRequest.bodyUint8Array(
1133
+ selected,
1134
+ new Uint8Array(
1135
+ yield* Effect.promise(() =>
1136
+ new Blob([
1137
+ `--${boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n${metadata}\r\n--${boundary}\r\nContent-Type: ${contentType}\r\n\r\n`,
1138
+ new Uint8Array(bytes),
1139
+ `\r\n--${boundary}--\r\n`,
1140
+ ]).arrayBuffer(),
1141
+ ),
1142
+ ),
1143
+ `multipart/related; boundary=${boundary}`,
1144
+ );
1145
+ const response = yield* client.execute(body);
1146
+ if (response.status < 200 || response.status >= 300) {
1147
+ return yield* Effect.fail({ cause: yield* response.text, response });
1148
+ }
1149
+ return yield* decodeResponse(output)({ resource: yield* response.json, state: "complete" });
1150
+ }, Effect.mapError(failure));
1151
+
1152
+ /** Sends a GraphQL operation and decodes its root field, failing with the errors it returns. */
1153
+ const graphql = Effect.fnUntraced(function* <Output extends Schema.Top>(
1154
+ context: Context,
1155
+ output: Output,
1156
+ request: Request,
1157
+ field: string,
1158
+ ) {
1159
+ const response = yield* send(context, request);
1160
+ const body = yield* Schema.decodeUnknownEffect(GraphqlResponse)(yield* response.json);
1161
+ if (body.errors !== undefined && Array.isReadonlyArrayNonEmpty(body.errors)) {
1162
+ return yield* Action.ActionHandlerError.make({
1163
+ details: body.errors,
1164
+ message: Array.join(
1165
+ Array.map(body.errors, error => error.message),
1166
+ "; ",
1167
+ ),
1168
+ });
1169
+ }
1170
+ return yield* decodeResponse(output)(body.data?.[field]);
1171
+ }, Effect.mapError(failure));
1172
+
1173
+ /**
1174
+ * Calls a Model Context Protocol tool in a session with the server. A tool that reports an error
1175
+ * fails the action with its text; otherwise the output is its structured content, or its content
1176
+ * blocks when it declares no output schema.
1177
+ */
1178
+ const mcp = Effect.fnUntraced(
1179
+ function* <Output extends Schema.Top>(
1180
+ context: Context,
1181
+ output: Output,
1182
+ server: string,
1183
+ tool: string,
1184
+ args: unknown,
1185
+ structured: boolean,
1186
+ ) {
1187
+ const connection = yield* Mcp.connect(
1188
+ authorize(yield* HttpClient.HttpClient, context),
1189
+ server,
1190
+ {},
1191
+ );
1192
+ const result = yield* Schema.decodeUnknownEffect(Mcp.CallToolResult)(
1193
+ yield* connection.request("tools/call", { arguments: args, name: tool }),
1194
+ );
1195
+ if (result.isError === true) {
1196
+ return yield* Action.ActionHandlerError.make({
1197
+ details: result.content,
1198
+ message: Array.join(
1199
+ Array.flatMap(result.content, block => Array.fromNullishOr(block.text)),
1200
+ "\n",
1201
+ ),
1202
+ });
1203
+ }
1204
+ return yield* decodeResponse(output)(
1205
+ Boolean.match(structured, {
1206
+ onFalse: () => ({ content: result.content }),
1207
+ onTrue: () => result.structuredContent,
1208
+ }),
1209
+ );
1210
+ },
1211
+ Effect.scoped,
1212
+ Effect.mapError(error =>
1213
+ Schema.is(Mcp.McpError)(error)
1214
+ ? Action.ActionHandlerError.make({ message: error.message })
1215
+ : failure(error),
1216
+ ),
1217
+ );
1218
+
1219
+ return { endpoint, execute, googleUpload, graphql, mcp, variants };
1220
+ }
1221
+
1222
+ export * as Http from "./Http.ts";