@encore.dev/sdk 2.0.0-beta.6 → 2.0.0-beta.8

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 (356) hide show
  1. package/README.md +55 -0
  2. package/app_meta.ts +8 -0
  3. package/config/config.test.ts +10 -3
  4. package/config/config.ts +75 -21
  5. package/config/mod.ts +4 -3
  6. package/config/secrets.ts +72 -55
  7. package/cron/mod.ts +32 -0
  8. package/dist/app_meta.d.ts +7 -0
  9. package/dist/app_meta.d.ts.map +1 -0
  10. package/dist/app_meta.js +1 -0
  11. package/dist/app_meta.js.map +1 -1
  12. package/dist/config/config.d.ts +44 -18
  13. package/dist/config/config.d.ts.map +1 -0
  14. package/dist/config/config.js +43 -18
  15. package/dist/config/config.js.map +1 -1
  16. package/dist/config/mod.d.ts +5 -4
  17. package/dist/config/mod.d.ts.map +1 -0
  18. package/dist/config/mod.js +2 -2
  19. package/dist/config/mod.js.map +1 -1
  20. package/dist/config/secrets.d.ts +62 -39
  21. package/dist/config/secrets.d.ts.map +1 -0
  22. package/dist/config/secrets.js +21 -37
  23. package/dist/config/secrets.js.map +1 -1
  24. package/dist/config/value.d.ts +1 -0
  25. package/dist/config/value.d.ts.map +1 -0
  26. package/dist/cron/mod.d.ts +31 -0
  27. package/dist/cron/mod.d.ts.map +1 -0
  28. package/dist/cron/mod.js +23 -0
  29. package/dist/cron/mod.js.map +1 -1
  30. package/dist/gateway/errors.d.ts +101 -0
  31. package/dist/gateway/errors.d.ts.map +1 -0
  32. package/dist/gateway/errors.js +146 -0
  33. package/dist/gateway/errors.js.map +1 -0
  34. package/dist/gateway/match.d.ts +127 -0
  35. package/dist/gateway/match.d.ts.map +1 -0
  36. package/dist/gateway/match.js +206 -0
  37. package/dist/gateway/match.js.map +1 -0
  38. package/dist/gateway/middleware.d.ts +108 -0
  39. package/dist/gateway/middleware.d.ts.map +1 -0
  40. package/dist/gateway/middleware.js +9 -0
  41. package/dist/gateway/middleware.js.map +1 -0
  42. package/dist/gateway/mod.d.ts +129 -0
  43. package/dist/gateway/mod.d.ts.map +1 -0
  44. package/dist/gateway/mod.js +187 -0
  45. package/dist/gateway/mod.js.map +1 -0
  46. package/dist/gateway/request.d.ts +304 -0
  47. package/dist/gateway/request.d.ts.map +1 -0
  48. package/dist/gateway/request.js +403 -0
  49. package/dist/gateway/request.js.map +1 -0
  50. package/dist/gateway/serve.d.ts +114 -0
  51. package/dist/gateway/serve.d.ts.map +1 -0
  52. package/dist/gateway/serve.js +510 -0
  53. package/dist/gateway/serve.js.map +1 -0
  54. package/dist/internal/clients/call.d.ts +147 -0
  55. package/dist/internal/clients/call.d.ts.map +1 -0
  56. package/dist/internal/clients/call.js +274 -0
  57. package/dist/internal/clients/call.js.map +1 -0
  58. package/dist/internal/clients/grpc.d.ts +90 -0
  59. package/dist/internal/clients/grpc.d.ts.map +1 -0
  60. package/dist/internal/clients/grpc.js +355 -0
  61. package/dist/internal/clients/grpc.js.map +1 -0
  62. package/dist/internal/clients/mod.d.ts +81 -0
  63. package/dist/internal/clients/mod.d.ts.map +1 -0
  64. package/dist/internal/clients/mod.js +237 -0
  65. package/dist/internal/clients/mod.js.map +1 -0
  66. package/dist/internal/fetch.d.ts +54 -0
  67. package/dist/internal/fetch.d.ts.map +1 -0
  68. package/dist/internal/fetch.js +240 -0
  69. package/dist/internal/fetch.js.map +1 -0
  70. package/dist/internal/otel/backend.d.ts +2 -0
  71. package/dist/internal/otel/backend.d.ts.map +1 -0
  72. package/dist/internal/otel/context.d.ts +1 -0
  73. package/dist/internal/otel/context.d.ts.map +1 -0
  74. package/dist/internal/otel/context_manager.d.ts +1 -0
  75. package/dist/internal/otel/context_manager.d.ts.map +1 -0
  76. package/dist/internal/otel/encode.d.ts +2 -0
  77. package/dist/internal/otel/encode.d.ts.map +1 -0
  78. package/dist/internal/otel/index.d.ts +2 -2
  79. package/dist/internal/otel/index.d.ts.map +1 -0
  80. package/dist/internal/otel/index.js +1 -2
  81. package/dist/internal/otel/index.js.map +1 -1
  82. package/dist/internal/otel/meter.d.ts +1 -0
  83. package/dist/internal/otel/meter.d.ts.map +1 -0
  84. package/dist/internal/otel/propagator.d.ts +1 -0
  85. package/dist/internal/otel/propagator.d.ts.map +1 -0
  86. package/dist/internal/otel/provider.d.ts +1 -0
  87. package/dist/internal/otel/provider.d.ts.map +1 -0
  88. package/dist/internal/otel/span.d.ts +4 -0
  89. package/dist/internal/otel/span.d.ts.map +1 -0
  90. package/dist/internal/otel/span.js +5 -0
  91. package/dist/internal/otel/span.js.map +1 -1
  92. package/dist/internal/otel/tracer.d.ts +1 -0
  93. package/dist/internal/otel/tracer.d.ts.map +1 -0
  94. package/dist/internal/otel/tracer.js +11 -5
  95. package/dist/internal/otel/tracer.js.map +1 -1
  96. package/dist/internal/reqfields.d.ts +150 -0
  97. package/dist/internal/reqfields.d.ts.map +1 -0
  98. package/dist/internal/reqfields.js +312 -0
  99. package/dist/internal/reqfields.js.map +1 -0
  100. package/dist/internal/runtime/meter.d.ts +1 -0
  101. package/dist/internal/runtime/meter.d.ts.map +1 -0
  102. package/dist/internal/runtime/mod.d.ts +6 -0
  103. package/dist/internal/runtime/mod.d.ts.map +1 -0
  104. package/dist/internal/runtime/mod.js +32 -2
  105. package/dist/internal/runtime/mod.js.map +1 -1
  106. package/dist/internal/runtime/napi/napi.cjs +160 -16
  107. package/dist/internal/runtime/napi/napi.d.cts +474 -29
  108. package/dist/internal/runtime/shutdown.d.ts +5 -0
  109. package/dist/internal/runtime/shutdown.d.ts.map +1 -0
  110. package/dist/internal/runtime/shutdown.js +9 -1
  111. package/dist/internal/runtime/shutdown.js.map +1 -1
  112. package/dist/internal/testing/runner.d.ts +2 -0
  113. package/dist/internal/testing/runner.d.ts.map +1 -0
  114. package/dist/internal/testing/runner.js +10 -0
  115. package/dist/internal/testing/runner.js.map +1 -0
  116. package/dist/internal/testing/scope.d.ts +81 -0
  117. package/dist/internal/testing/scope.d.ts.map +1 -0
  118. package/dist/internal/testing/scope.js +237 -0
  119. package/dist/internal/testing/scope.js.map +1 -0
  120. package/dist/internal/utils/constraints.d.ts +1 -0
  121. package/dist/internal/utils/constraints.d.ts.map +1 -0
  122. package/dist/log/index.d.ts +1 -0
  123. package/dist/log/index.d.ts.map +1 -0
  124. package/dist/log/logger.d.ts +2 -0
  125. package/dist/log/logger.d.ts.map +1 -0
  126. package/dist/log/runtime.d.ts +2 -0
  127. package/dist/log/runtime.d.ts.map +1 -0
  128. package/dist/log/stderr.d.ts +1 -0
  129. package/dist/log/stderr.d.ts.map +1 -0
  130. package/dist/metrics/mod.d.ts +45 -118
  131. package/dist/metrics/mod.d.ts.map +1 -0
  132. package/dist/metrics/mod.js +44 -179
  133. package/dist/metrics/mod.js.map +1 -1
  134. package/dist/mod.d.ts +1 -2
  135. package/dist/mod.d.ts.map +1 -0
  136. package/dist/mod.js +0 -1
  137. package/dist/mod.js.map +1 -1
  138. package/dist/otel.d.ts +1 -0
  139. package/dist/otel.d.ts.map +1 -0
  140. package/dist/pubsub/encoding.d.ts +5 -0
  141. package/dist/pubsub/encoding.d.ts.map +1 -0
  142. package/dist/pubsub/encoding.js +10 -2
  143. package/dist/pubsub/encoding.js.map +1 -1
  144. package/dist/pubsub/mod.d.ts +4 -3
  145. package/dist/pubsub/mod.d.ts.map +1 -0
  146. package/dist/pubsub/mod.js +2 -2
  147. package/dist/pubsub/mod.js.map +1 -1
  148. package/dist/pubsub/refs.d.ts +8 -0
  149. package/dist/pubsub/refs.d.ts.map +1 -0
  150. package/dist/pubsub/refs.js.map +1 -1
  151. package/dist/pubsub/subscription.d.ts +104 -10
  152. package/dist/pubsub/subscription.d.ts.map +1 -0
  153. package/dist/pubsub/subscription.js +98 -16
  154. package/dist/pubsub/subscription.js.map +1 -1
  155. package/dist/pubsub/topic.d.ts +87 -23
  156. package/dist/pubsub/topic.d.ts.map +1 -0
  157. package/dist/pubsub/topic.js +143 -40
  158. package/dist/pubsub/topic.js.map +1 -1
  159. package/dist/reqctx/mod.d.ts +191 -0
  160. package/dist/reqctx/mod.d.ts.map +1 -0
  161. package/dist/reqctx/mod.js +160 -0
  162. package/dist/reqctx/mod.js.map +1 -0
  163. package/dist/services/index.d.ts +145 -4
  164. package/dist/services/index.d.ts.map +1 -0
  165. package/dist/services/index.js +155 -8
  166. package/dist/services/index.js.map +1 -1
  167. package/dist/shutdown/mod.d.ts +1 -0
  168. package/dist/shutdown/mod.d.ts.map +1 -0
  169. package/dist/storage/objects/bucket.d.ts +312 -7
  170. package/dist/storage/objects/bucket.d.ts.map +1 -0
  171. package/dist/storage/objects/bucket.js +305 -15
  172. package/dist/storage/objects/bucket.js.map +1 -1
  173. package/dist/storage/objects/error.d.ts +10 -0
  174. package/dist/storage/objects/error.d.ts.map +1 -0
  175. package/dist/storage/objects/error.js +25 -1
  176. package/dist/storage/objects/error.js.map +1 -1
  177. package/dist/storage/objects/mod.d.ts +4 -3
  178. package/dist/storage/objects/mod.d.ts.map +1 -0
  179. package/dist/storage/objects/mod.js +1 -1
  180. package/dist/storage/objects/mod.js.map +1 -1
  181. package/dist/storage/objects/refs.d.ts +20 -4
  182. package/dist/storage/objects/refs.d.ts.map +1 -0
  183. package/dist/storage/objects/refs.js +6 -0
  184. package/dist/storage/objects/refs.js.map +1 -1
  185. package/dist/storage/postgres/database.d.ts +81 -25
  186. package/dist/storage/postgres/database.d.ts.map +1 -0
  187. package/dist/storage/postgres/database.js +125 -37
  188. package/dist/storage/postgres/database.js.map +1 -1
  189. package/dist/storage/postgres/errors.d.ts +120 -0
  190. package/dist/storage/postgres/errors.d.ts.map +1 -0
  191. package/dist/storage/postgres/errors.js +162 -0
  192. package/dist/storage/postgres/errors.js.map +1 -0
  193. package/dist/storage/postgres/interval.d.ts +44 -0
  194. package/dist/storage/postgres/interval.d.ts.map +1 -0
  195. package/dist/storage/postgres/interval.js +153 -0
  196. package/dist/storage/postgres/interval.js.map +1 -0
  197. package/dist/storage/postgres/mod.d.ts +4 -1
  198. package/dist/storage/postgres/mod.d.ts.map +1 -0
  199. package/dist/storage/postgres/mod.js +2 -0
  200. package/dist/storage/postgres/mod.js.map +1 -1
  201. package/dist/storage/redis/bitfield.d.ts +67 -0
  202. package/dist/storage/redis/bitfield.d.ts.map +1 -0
  203. package/dist/storage/redis/bitfield.js +114 -0
  204. package/dist/storage/redis/bitfield.js.map +1 -0
  205. package/dist/storage/redis/command.d.ts +45 -0
  206. package/dist/storage/redis/command.d.ts.map +1 -0
  207. package/dist/storage/redis/command.js +78 -0
  208. package/dist/storage/redis/command.js.map +1 -0
  209. package/dist/storage/redis/commands.d.ts +223 -139
  210. package/dist/storage/redis/commands.d.ts.map +1 -0
  211. package/dist/storage/redis/commands.js +128 -6
  212. package/dist/storage/redis/commands.js.map +1 -1
  213. package/dist/storage/redis/database.d.ts +56 -22
  214. package/dist/storage/redis/database.d.ts.map +1 -0
  215. package/dist/storage/redis/database.js +62 -0
  216. package/dist/storage/redis/database.js.map +1 -1
  217. package/dist/storage/redis/mod.d.ts +31 -4
  218. package/dist/storage/redis/mod.d.ts.map +1 -0
  219. package/dist/storage/redis/mod.js +26 -1
  220. package/dist/storage/redis/mod.js.map +1 -1
  221. package/dist/storage/redis/native.d.ts +8 -0
  222. package/dist/storage/redis/native.d.ts.map +1 -0
  223. package/dist/storage/redis/native.js +10 -0
  224. package/dist/storage/redis/native.js.map +1 -1
  225. package/dist/storage/redis/options.d.ts +1 -0
  226. package/dist/storage/redis/options.d.ts.map +1 -0
  227. package/dist/storage/redis/pubsub.d.ts +2 -0
  228. package/dist/storage/redis/pubsub.d.ts.map +1 -0
  229. package/dist/storage/redis/reply.d.ts +34 -0
  230. package/dist/storage/redis/reply.d.ts.map +1 -0
  231. package/dist/storage/redis/reply.js +40 -1
  232. package/dist/storage/redis/reply.js.map +1 -1
  233. package/dist/storage/redis/scan.d.ts +1 -0
  234. package/dist/storage/redis/scan.d.ts.map +1 -0
  235. package/dist/storage/redis/script.d.ts +1 -0
  236. package/dist/storage/redis/script.d.ts.map +1 -0
  237. package/dist/storage/redis/target.d.ts +5 -3
  238. package/dist/storage/redis/target.d.ts.map +1 -0
  239. package/dist/storage/redis/target.js +39 -28
  240. package/dist/storage/redis/target.js.map +1 -1
  241. package/dist/storage/redis/wire.d.ts +7 -10
  242. package/dist/storage/redis/wire.d.ts.map +1 -0
  243. package/dist/storage/redis/wire.js +8 -32
  244. package/dist/storage/redis/wire.js.map +1 -1
  245. package/dist/testing/bun.d.ts +8 -0
  246. package/dist/testing/bun.d.ts.map +1 -0
  247. package/dist/testing/bun.js +13 -0
  248. package/dist/testing/bun.js.map +1 -0
  249. package/dist/testing/jest.d.ts +8 -0
  250. package/dist/testing/jest.d.ts.map +1 -0
  251. package/dist/testing/jest.js +11 -0
  252. package/dist/testing/jest.js.map +1 -0
  253. package/dist/testing/mod.d.ts +160 -0
  254. package/dist/testing/mod.d.ts.map +1 -0
  255. package/dist/testing/mod.js +227 -0
  256. package/dist/testing/mod.js.map +1 -0
  257. package/dist/testing/node.d.ts +9 -0
  258. package/dist/testing/node.d.ts.map +1 -0
  259. package/dist/testing/node.js +12 -0
  260. package/dist/testing/node.js.map +1 -0
  261. package/dist/testing/vitest.d.ts +8 -0
  262. package/dist/testing/vitest.d.ts.map +1 -0
  263. package/dist/testing/vitest.js +13 -0
  264. package/dist/testing/vitest.js.map +1 -0
  265. package/dist/tracing/mod.d.ts +19 -0
  266. package/dist/tracing/mod.d.ts.map +1 -0
  267. package/dist/tracing/mod.js +46 -0
  268. package/dist/tracing/mod.js.map +1 -0
  269. package/dist/tsconfig.build.tsbuildinfo +1 -1
  270. package/dist/types/mod.d.ts +1 -0
  271. package/dist/types/mod.d.ts.map +1 -0
  272. package/gateway/errors.ts +172 -0
  273. package/gateway/gateway.e2e.test.ts +297 -0
  274. package/gateway/gateway.test.ts +891 -0
  275. package/gateway/match.ts +239 -0
  276. package/gateway/middleware.ts +134 -0
  277. package/gateway/mod.ts +210 -0
  278. package/gateway/request.ts +578 -0
  279. package/gateway/serve.ts +738 -0
  280. package/internal/clients/call.ts +389 -0
  281. package/internal/clients/grpc.test.ts +368 -0
  282. package/internal/clients/grpc.ts +485 -0
  283. package/internal/clients/mod.test.ts +464 -0
  284. package/internal/clients/mod.ts +337 -0
  285. package/internal/fetch.ts +276 -0
  286. package/internal/otel/index.ts +1 -7
  287. package/internal/otel/span.ts +6 -0
  288. package/internal/otel/tracer.test.ts +43 -15
  289. package/internal/otel/tracer.ts +12 -5
  290. package/internal/reqfields.ts +390 -0
  291. package/internal/runtime/mod.ts +41 -2
  292. package/internal/runtime/napi/napi.cjs +160 -16
  293. package/internal/runtime/napi/napi.d.cts +474 -29
  294. package/internal/runtime/shutdown.ts +11 -1
  295. package/internal/testing/runner.ts +10 -0
  296. package/internal/testing/scope.ts +273 -0
  297. package/metrics/mod.test.ts +13 -16
  298. package/metrics/mod.ts +57 -226
  299. package/mod.ts +0 -8
  300. package/otel.test.ts +13 -6
  301. package/package.json +67 -15
  302. package/pubsub/encoding.ts +11 -1
  303. package/pubsub/mod.ts +10 -3
  304. package/pubsub/pubsub.test.ts +232 -14
  305. package/pubsub/refs.ts +16 -0
  306. package/pubsub/subscription.ts +194 -16
  307. package/pubsub/topic.test.ts +26 -0
  308. package/pubsub/topic.ts +220 -25
  309. package/reqctx/mod.ts +284 -0
  310. package/reqctx/reqctx.test.ts +193 -0
  311. package/scripts/postprocess-docs.test.ts +48 -0
  312. package/services/index.test.ts +341 -1
  313. package/services/index.ts +183 -8
  314. package/storage/objects/bucket.test.ts +573 -0
  315. package/storage/objects/bucket.ts +649 -20
  316. package/storage/objects/error.ts +28 -1
  317. package/storage/objects/mod.ts +15 -0
  318. package/storage/objects/refs.ts +51 -3
  319. package/storage/postgres/database.integration.test.ts +275 -0
  320. package/storage/postgres/database.test.ts +193 -6
  321. package/storage/postgres/database.ts +202 -55
  322. package/storage/postgres/errors.ts +186 -0
  323. package/storage/postgres/interval.test.ts +72 -0
  324. package/storage/postgres/interval.ts +170 -0
  325. package/storage/postgres/mod.ts +4 -0
  326. package/storage/redis/bitfield.ts +162 -0
  327. package/storage/redis/command.ts +84 -0
  328. package/storage/redis/commands.ts +271 -21
  329. package/storage/redis/database.ts +77 -23
  330. package/storage/redis/mod.ts +38 -2
  331. package/storage/redis/native.ts +11 -0
  332. package/storage/redis/redis.test.ts +170 -10
  333. package/storage/redis/reply.ts +76 -1
  334. package/storage/redis/runtime.test.ts +15 -0
  335. package/storage/redis/target.ts +47 -44
  336. package/storage/redis/wire.ts +8 -32
  337. package/testing/bun.ts +13 -0
  338. package/testing/jest.ts +11 -0
  339. package/testing/mod.ts +337 -0
  340. package/testing/node.ts +12 -0
  341. package/testing/vitest.ts +13 -0
  342. package/tracing/mod.ts +82 -0
  343. package/tracing/native.test.ts +170 -0
  344. package/tracing/tracing.test.ts +317 -0
  345. package/dist/internal/otel/request_context.d.ts +0 -11
  346. package/dist/internal/otel/request_context.js +0 -20
  347. package/dist/internal/otel/request_context.js.map +0 -1
  348. package/dist/internal/reqtrack/mod.d.ts +0 -6
  349. package/dist/internal/reqtrack/mod.js +0 -28
  350. package/dist/internal/reqtrack/mod.js.map +0 -1
  351. package/dist/req_meta.d.ts +0 -47
  352. package/dist/req_meta.js +0 -26
  353. package/dist/req_meta.js.map +0 -1
  354. package/internal/otel/request_context.ts +0 -32
  355. package/internal/reqtrack/mod.ts +0 -39
  356. package/req_meta.ts +0 -75
@@ -0,0 +1,337 @@
1
+ /**
2
+ * What the service clients Encore generates call through: a service, looked
3
+ * up on the first call that needs it, and its HTTP calls. For the generated
4
+ * code: it may change with the generator. Code calling the clients takes
5
+ * their errors and options from `@encore.dev/sdk/services`.
6
+ *
7
+ * Nothing here loads the runtime until a call needs a service's base URL, so
8
+ * a generated client given a `baseUrl` runs without Encore, as against a
9
+ * mock server in a plain test.
10
+ *
11
+ * @hidden
12
+ * @module
13
+ */
14
+
15
+ import {
16
+ CallError,
17
+ callHeaders,
18
+ deadline,
19
+ errorBody,
20
+ errorText,
21
+ failure,
22
+ fetchFor,
23
+ httpStatus,
24
+ isErrCode,
25
+ type CallOptions,
26
+ type ClientOptions,
27
+ type ErrCode,
28
+ type GraphQLError,
29
+ } from './call';
30
+
31
+ export {
32
+ CallError,
33
+ type CallOptions,
34
+ type ClientOptions,
35
+ type ErrCode,
36
+ } from './call';
37
+
38
+ /**
39
+ * One HTTP call of a generated client. For the generated code: it may change
40
+ * with the generator.
41
+ *
42
+ * @hidden
43
+ */
44
+ export interface HttpCall {
45
+ method: string;
46
+ /** The path, already encoded, starting with `/`. */
47
+ path: string;
48
+ /** Query parameters; one `undefined` or `null` is left out, an array is
49
+ * sent once per element. */
50
+ query?: [string, unknown][];
51
+ /** Header parameters; one `undefined` or `null` is left out. */
52
+ headers?: [string, unknown][];
53
+ /** A body sent as JSON. */
54
+ json?: unknown;
55
+ /** A body sent as it is, of `contentType`. */
56
+ body?: Uint8Array | string;
57
+ contentType?: string;
58
+ }
59
+
60
+ /**
61
+ * A service the generated clients call, looked up on the first call that
62
+ * needs its base URL. For the generated code: it may change with the
63
+ * generator.
64
+ *
65
+ * @hidden
66
+ */
67
+ export class Service {
68
+ /** The base URL, once looked up. */
69
+ private base: Promise<string> | undefined;
70
+
71
+ constructor(readonly name: string) {}
72
+
73
+ /**
74
+ * The base URL calls made with `client` go to, without a trailing slash:
75
+ * its `baseUrl`, else the one Encore gives the service.
76
+ */
77
+ async baseUrl(client: ClientOptions): Promise<string> {
78
+ if (client.baseUrl !== undefined) return client.baseUrl.replace(/\/+$/, '');
79
+ // A failed lookup is tried again by the next call.
80
+ this.base ??= lookup(this.name).catch((err: unknown) => {
81
+ this.base = undefined;
82
+ throw err;
83
+ });
84
+ return this.base;
85
+ }
86
+
87
+ /** Sends `call`, and decodes its answer from JSON. */
88
+ async json<T>(
89
+ client: ClientOptions,
90
+ options: CallOptions | undefined,
91
+ call: HttpCall,
92
+ ): Promise<T> {
93
+ return this.send(client, options, call, async res => {
94
+ const text = await res.text();
95
+ // An empty answer is JSON's `null`.
96
+ if (text === '') return null as T;
97
+ try {
98
+ return JSON.parse(text) as T;
99
+ } catch (err) {
100
+ throw failure(
101
+ 'internal',
102
+ `decoding the answer: ${errorText(err)}`,
103
+ err,
104
+ );
105
+ }
106
+ });
107
+ }
108
+
109
+ /** Sends `call`, and reads its answer's body. */
110
+ async bytes(
111
+ client: ClientOptions,
112
+ options: CallOptions | undefined,
113
+ call: HttpCall,
114
+ ): Promise<Uint8Array> {
115
+ return this.send(
116
+ client,
117
+ options,
118
+ call,
119
+ async res => new Uint8Array(await res.arrayBuffer()),
120
+ );
121
+ }
122
+
123
+ /** Sends `call`, and drops its answer. */
124
+ async empty(
125
+ client: ClientOptions,
126
+ options: CallOptions | undefined,
127
+ call: HttpCall,
128
+ ): Promise<void> {
129
+ await this.send(client, options, call, async res => {
130
+ await res.body?.cancel();
131
+ });
132
+ }
133
+
134
+ /**
135
+ * Sends GraphQL `document` with `variables` to the service's `path`, and
136
+ * returns the answer's `field` of its data. A variable left `undefined` is
137
+ * left out, which a `null` is not. A `required` field missing or null fails
138
+ * the call with `internal`.
139
+ */
140
+ async graphql<T>(
141
+ client: ClientOptions,
142
+ options: CallOptions | undefined,
143
+ path: string,
144
+ document: string,
145
+ variables: Record<string, unknown>,
146
+ field: string,
147
+ required = false,
148
+ ): Promise<T> {
149
+ const call: HttpCall = {
150
+ method: 'POST',
151
+ path,
152
+ json: {query: document, variables},
153
+ };
154
+ return this.exchange(client, options, call, async res => {
155
+ const text = await res.text();
156
+ let envelope: {data?: unknown; errors?: unknown} | undefined;
157
+ try {
158
+ const parsed: unknown = JSON.parse(text);
159
+ if (typeof parsed === 'object' && parsed !== null) {
160
+ envelope = parsed as {data?: unknown; errors?: unknown};
161
+ }
162
+ } catch {
163
+ envelope = undefined;
164
+ }
165
+ const errors = envelope?.errors;
166
+ if (
167
+ errors !== undefined &&
168
+ errors !== null &&
169
+ !(Array.isArray(errors) && errors.length === 0)
170
+ ) {
171
+ throw graphqlError(errors, res.status);
172
+ }
173
+ if (!res.ok) throw errorBody(res, text);
174
+ const data = envelope?.data;
175
+ if (data === undefined || data === null) {
176
+ throw failure(
177
+ 'unknown',
178
+ 'graphql: the answer has neither data nor errors',
179
+ );
180
+ }
181
+ const value = (data as Record<string, unknown>)[field] ?? null;
182
+ if (value === null && required) {
183
+ throw failure(
184
+ 'internal',
185
+ `graphql: the answer's ${field} is missing or null`,
186
+ );
187
+ }
188
+ return value as T;
189
+ });
190
+ }
191
+
192
+ /** Sends `call`, failing on an error answer, and reads the answer with
193
+ * `read`. */
194
+ private async send<T>(
195
+ client: ClientOptions,
196
+ options: CallOptions | undefined,
197
+ call: HttpCall,
198
+ read: (res: Response) => Promise<T>,
199
+ ): Promise<T> {
200
+ return this.exchange(client, options, call, async res => {
201
+ if (!res.ok) throw errorBody(res, await res.text());
202
+ return read(res);
203
+ });
204
+ }
205
+
206
+ /** Sends `call` and reads its answer with `read`, under the call's
207
+ * timeout and signal, which cover the answer's body too. */
208
+ private async exchange<T>(
209
+ client: ClientOptions,
210
+ options: CallOptions | undefined,
211
+ call: HttpCall,
212
+ read: (res: Response) => Promise<T>,
213
+ ): Promise<T> {
214
+ const limit = deadline(client, options);
215
+ try {
216
+ let url = (await this.baseUrl(client)) + call.path;
217
+ const query = new URLSearchParams();
218
+ for (const [name, value] of call.query ?? []) {
219
+ for (const v of Array.isArray(value) ? value : [value]) {
220
+ if (v !== undefined && v !== null) query.append(name, paramText(v));
221
+ }
222
+ }
223
+ const qs = query.toString();
224
+ if (qs !== '') url += `?${qs}`;
225
+ const params: [string, string][] = [];
226
+ for (const [name, value] of call.headers ?? []) {
227
+ if (value !== undefined && value !== null) {
228
+ params.push([name, paramText(value)]);
229
+ }
230
+ }
231
+ const headers = callHeaders(client, options, params);
232
+ let body: RequestInit['body'];
233
+ if (call.json !== undefined) {
234
+ headers.set('Content-Type', 'application/json');
235
+ try {
236
+ body = JSON.stringify(call.json);
237
+ } catch (err) {
238
+ // A cycle, or a BigInt, which JSON has no form for.
239
+ throw failure(
240
+ 'invalid_argument',
241
+ `encoding the body: ${errorText(err)}`,
242
+ err,
243
+ );
244
+ }
245
+ } else if (call.body !== undefined) {
246
+ if (call.contentType !== undefined) {
247
+ headers.set('Content-Type', call.contentType);
248
+ }
249
+ // TS ≥5.7's Uint8Array<ArrayBufferLike> is no BodyInit, though fetch
250
+ // takes one.
251
+ body = call.body as RequestInit['body'];
252
+ }
253
+ let res: Response;
254
+ try {
255
+ res = await fetchFor(client)(url, {
256
+ method: call.method,
257
+ headers,
258
+ body,
259
+ signal: limit.signal,
260
+ });
261
+ } catch (err) {
262
+ throw limit.error(
263
+ err,
264
+ `${call.method} ${shownUrl(url)}`,
265
+ 'unavailable',
266
+ );
267
+ }
268
+ try {
269
+ return await read(res);
270
+ } catch (err) {
271
+ if (err instanceof CallError) throw err;
272
+ throw limit.error(err, 'reading the answer', 'unavailable');
273
+ }
274
+ } finally {
275
+ limit.done();
276
+ }
277
+ }
278
+ }
279
+
280
+ /**
281
+ * The service named `name`, looked up on the first call that needs it. For
282
+ * the generated code: it may change with the generator.
283
+ *
284
+ * @hidden
285
+ */
286
+ export function service(name: string): Service {
287
+ return new Service(name);
288
+ }
289
+
290
+ /** The base URL Encore gives `name`: the services module, and with it the
291
+ * runtime, is loaded only now, so a client given a `baseUrl` runs without
292
+ * Encore. */
293
+ async function lookup(name: string): Promise<string> {
294
+ try {
295
+ const services = await import('../../services/index');
296
+ return services.baseUrl(name);
297
+ } catch (err) {
298
+ throw failure(
299
+ 'unavailable',
300
+ `encore: no base URL is known for service ${JSON.stringify(name)}: ${errorText(err)}`,
301
+ err,
302
+ );
303
+ }
304
+ }
305
+
306
+ /** `url` as an error shows it: without its query, fragment or credentials,
307
+ * which may hold secrets, as an error that escapes a handler is logged. */
308
+ function shownUrl(url: string): string {
309
+ return url
310
+ .replace(/[?#].*$/s, '')
311
+ .replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@]*@/i, '$1');
312
+ }
313
+
314
+ /** A parameter's text: a structured one as JSON. */
315
+ function paramText(value: unknown): string {
316
+ return typeof value === 'object' ? JSON.stringify(value) : String(value);
317
+ }
318
+
319
+ /** The error a GraphQL answer with `errors` in it is. */
320
+ function graphqlError(errors: unknown, status: number): CallError {
321
+ const list: GraphQLError[] = (Array.isArray(errors) ? errors : [errors]).map(
322
+ e =>
323
+ typeof e === 'object' && e !== null && !Array.isArray(e)
324
+ ? (e as GraphQLError)
325
+ : {message: JSON.stringify(e)},
326
+ );
327
+ const first = list[0]?.extensions?.['code'];
328
+ const lower = typeof first === 'string' ? first.toLowerCase() : undefined;
329
+ const code: ErrCode = isErrCode(lower) ? lower : 'unknown';
330
+ const message = list
331
+ .map(e => (typeof e.message === 'string' ? e.message : ''))
332
+ .join('; ');
333
+ return new CallError(code, message, {
334
+ status: status >= 400 ? status : httpStatus(code),
335
+ graphqlErrors: list,
336
+ });
337
+ }
@@ -0,0 +1,276 @@
1
+ /**
2
+ * The `fetch` of `@encore.dev/sdk/services`, which sends the app's services
3
+ * the trace and Request Context: apart from the module looking services up,
4
+ * so what sends calls loads without the runtime, as a generated client
5
+ * pointed at a mock server does.
6
+ *
7
+ * @module
8
+ */
9
+
10
+ import {isSpanContextValid, trace, type Context} from '@opentelemetry/api';
11
+ import {activeContext} from './otel/context';
12
+ import {W3CPropagator} from './otel/propagator';
13
+ import * as reqfields from './reqfields';
14
+
15
+ /**
16
+ * The global `fetch`, carrying the trace and Request Context of the active
17
+ * context to the app's services.
18
+ *
19
+ * A request for one of the app's services gets the active context's Request
20
+ * Context fields, in place of any its headers carried, and the active span's
21
+ * W3C `traceparent` and `tracestate`, unless it carries a `traceparent`
22
+ * already, as an instrumented client's does: Encore records the call's span
23
+ * where it reaches the service. A request to anything else goes without any
24
+ * Request Context headers, even those copied from a request the service
25
+ * received.
26
+ *
27
+ * A request is for the app's services when its URL is at the origin of a
28
+ * base URL `baseUrl`, `serviceUrl` or `client` of `@encore.dev/sdk/services`
29
+ * returned in this process, as every service URL is made from one.
30
+ *
31
+ * A request made in a context with a trace or Request Context follows its
32
+ * redirects here, rather than in the global `fetch`, so that each is sent
33
+ * what its own URL is due: a redirect away from the app's services carries
34
+ * no Request Context, and one to them carries the context's. It follows them
35
+ * by fetch's own rules for each status, and its response's `url` and
36
+ * `redirected` say where it ended. A `Request`'s body is streamed, not read
37
+ * first, so a 307 or 308 that would send it again fails, as fetch's does for
38
+ * a streamed body.
39
+ *
40
+ * @example
41
+ * import {fetch} from "@encore.dev/sdk/services";
42
+ * const res = await fetch(`${baseUrl("orders")}/orders/1`);
43
+ */
44
+ export const fetch: typeof globalThis.fetch = wrapFetch();
45
+
46
+ /**
47
+ * `base`, sending the trace and Request Context of the active context to the
48
+ * app's services as {@link fetch} does: for a `fetch` of the app's own, as an
49
+ * instrumented or retrying one. Without `base`, the global `fetch`, looked up
50
+ * at each call.
51
+ *
52
+ * @example
53
+ * import {wrapFetch} from "@encore.dev/sdk/services";
54
+ * const tracedFetch = wrapFetch(instrumentedFetch);
55
+ */
56
+ export function wrapFetch(
57
+ base?: typeof globalThis.fetch,
58
+ ): typeof globalThis.fetch {
59
+ const send: Send = base ?? ((input, init) => globalThis.fetch(input, init));
60
+ return withMembersOfGlobalFetch(
61
+ async (input: string | URL | Request, init?: RequestInit) => {
62
+ const request = input instanceof Request ? input : undefined;
63
+ const url = request?.url ?? String(input);
64
+ const headers = new Headers(init?.headers ?? request?.headers);
65
+ const ctx = activeContext();
66
+ prepare(url, headers, ctx);
67
+ const redirect = init?.redirect ?? request?.redirect ?? 'follow';
68
+ if (!hasContext(ctx) || redirect !== 'follow') {
69
+ return send(input, {...init, headers});
70
+ }
71
+ return followRedirects(send, url, initOf(request, init), headers, ctx);
72
+ },
73
+ base ?? globalThis.fetch,
74
+ );
75
+ }
76
+
77
+ /** How a wrapped fetch sends each request. */
78
+ type Send = (
79
+ input: string | URL | Request,
80
+ init?: RequestInit,
81
+ ) => Promise<Response>;
82
+
83
+ /** `fn` with the members `base` has besides its call, as Bun's global
84
+ * `preconnect`, so it is a `typeof fetch` wherever the global is. */
85
+ function withMembersOfGlobalFetch(
86
+ fn: (input: string | URL | Request, init?: RequestInit) => Promise<Response>,
87
+ base: typeof globalThis.fetch,
88
+ ): typeof globalThis.fetch {
89
+ const global = base as unknown as Record<string, unknown>;
90
+ const out = fn as unknown as Record<string, unknown>;
91
+ for (const key of Object.getOwnPropertyNames(global)) {
92
+ if (!(key in out)) out[key] = global[key];
93
+ }
94
+ return fn as unknown as typeof globalThis.fetch;
95
+ }
96
+
97
+ /** The origins of the base URLs looked up in this process: where the app's
98
+ * services are reached. Every service URL is the egress endpoint's, or
99
+ * locally the run proxy's, plus the service's path; nothing else is served
100
+ * at either. */
101
+ const origins = new Set<string>();
102
+
103
+ /** Records `base`, a service's base URL looked up in this process, as one
104
+ * of the app's services': a request for its origin is sent the trace and
105
+ * Request Context. */
106
+ export function recordOrigin(base: string): void {
107
+ const origin = originOf(base);
108
+ if (origin !== undefined) origins.add(origin);
109
+ }
110
+
111
+ const DEFAULT_PORTS: Record<string, string> = {'http:': '80', 'https:': '443'};
112
+
113
+ /** `url`'s scheme, host and port, with the scheme's default port when it
114
+ * has none; `undefined` when it is not a URL. */
115
+ function originOf(url: string): string | undefined {
116
+ let u: URL;
117
+ try {
118
+ u = new URL(url);
119
+ } catch {
120
+ return undefined;
121
+ }
122
+ if (u.hostname === '') return undefined;
123
+ const port = u.port || DEFAULT_PORTS[u.protocol] || '';
124
+ return `${u.protocol}//${u.hostname}:${port}`;
125
+ }
126
+
127
+ const w3c = new W3CPropagator();
128
+ const setter = {set: (h: Headers, k: string, v: string) => h.set(k, v)};
129
+
130
+ /**
131
+ * Sets the trace and Request Context of `ctx` on a request to `url`: drops
132
+ * the Request Context headers it carried, then, when it is for one of the
133
+ * app's services, sets the context's fields and, unless it carries one, its
134
+ * `traceparent`.
135
+ */
136
+ function prepare(url: string, headers: Headers, ctx: Context): void {
137
+ if (!origins.has(originOf(url) ?? '')) {
138
+ const stale: string[] = [];
139
+ headers.forEach((_, name) => {
140
+ if (name.toLowerCase().startsWith(reqfields.HEADER_PREFIX))
141
+ stale.push(name);
142
+ });
143
+ for (const name of stale) headers.delete(name);
144
+ return;
145
+ }
146
+ reqfields.toHeaders(headers, ctx);
147
+ const span = trace.getSpanContext(ctx);
148
+ if (!headers.has('traceparent') && span && isSpanContextValid(span)) {
149
+ // A tracestate the request carried belongs to another trace's
150
+ // traceparent: the span's own, with Encore's mark, replaces it.
151
+ headers.delete('tracestate');
152
+ w3c.inject(ctx, headers, setter);
153
+ }
154
+ }
155
+
156
+ /** Whether `ctx` holds a trace or Request Context to send. */
157
+ function hasContext(ctx: Context): boolean {
158
+ const span = trace.getSpanContext(ctx);
159
+ return (
160
+ (span !== undefined && isSpanContextValid(span)) ||
161
+ Object.keys(reqfields.current(ctx)).length > 0
162
+ );
163
+ }
164
+
165
+ /** The statuses a redirect is answered with. */
166
+ const REDIRECTS = new Set([301, 302, 303, 307, 308]);
167
+
168
+ /** As many redirects as fetch follows. */
169
+ const MAX_REDIRECTS = 20;
170
+
171
+ /** The headers that describe a body, dropped with it. */
172
+ const BODY_HEADERS = [
173
+ 'content-encoding',
174
+ 'content-language',
175
+ 'content-location',
176
+ 'content-type',
177
+ 'content-length',
178
+ ];
179
+
180
+ /** The headers a redirect to another origin drops, as fetch does. */
181
+ const CREDENTIAL_HEADERS = ['authorization', 'cookie', 'proxy-authorization'];
182
+
183
+ /** `init` with what `request`, if any, says and `init` does not. Its body
184
+ * is streamed, not read first: a redirect that would send it again fails, as
185
+ * fetch's does for a streamed body. */
186
+ function initOf(
187
+ request: Request | undefined,
188
+ init: RequestInit | undefined,
189
+ ): RequestInit {
190
+ if (request === undefined) return {...init};
191
+ const out: Record<string, unknown> = {
192
+ method: request.method,
193
+ signal: request.signal,
194
+ credentials: request.credentials,
195
+ keepalive: request.keepalive,
196
+ body: init?.body === undefined ? request.body : undefined,
197
+ };
198
+ // The fetch policies a Request has where the runtime has them: Node's and
199
+ // Bun's types disagree on which.
200
+ const policies = request as unknown as Record<string, unknown>;
201
+ for (const key of POLICIES) {
202
+ if (policies[key] !== undefined) out[key] = policies[key];
203
+ }
204
+ // An option set to `undefined` is not given, as fetch takes it.
205
+ for (const [key, value] of Object.entries(init ?? {})) {
206
+ if (value !== undefined) out[key] = value;
207
+ }
208
+ return out as RequestInit;
209
+ }
210
+
211
+ /** The fetch policies of a Request a redirect followed here keeps. */
212
+ const POLICIES = ['cache', 'integrity', 'mode', 'referrer', 'referrerPolicy'];
213
+
214
+ /** `res`, the answer to the last of a request's redirects, at `url`, saying
215
+ * so as fetch's own would. */
216
+ function redirected(res: Response, url: string): Response {
217
+ return Object.defineProperties(res, {
218
+ url: {value: url, enumerable: true},
219
+ redirected: {value: true, enumerable: true},
220
+ });
221
+ }
222
+
223
+ /**
224
+ * Sends a request and follows the redirects it is answered with, as fetch's
225
+ * `redirect: "follow"` does, preparing the headers of each for its own URL
226
+ * in `ctx`, the context the call was made in.
227
+ */
228
+ async function followRedirects(
229
+ send: Send,
230
+ url: string,
231
+ init: RequestInit,
232
+ headers: Headers,
233
+ ctx: Context,
234
+ ): Promise<Response> {
235
+ let method = (init.method ?? 'GET').toUpperCase();
236
+ let body = init.body ?? null;
237
+ for (let redirects = 0; ; redirects++) {
238
+ const res = await send(url, {
239
+ ...init,
240
+ method,
241
+ body,
242
+ headers,
243
+ redirect: 'manual',
244
+ // Node sends a streamed body only half-duplex, and says so.
245
+ ...(body instanceof ReadableStream ? {duplex: 'half'} : {}),
246
+ } as RequestInit);
247
+ const location = res.headers.get('location');
248
+ if (!REDIRECTS.has(res.status) || location === null) {
249
+ return redirects === 0 ? res : redirected(res, url);
250
+ }
251
+ if (redirects === MAX_REDIRECTS) {
252
+ await res.body?.cancel();
253
+ throw new TypeError(`fetch failed: more than ${MAX_REDIRECTS} redirects`);
254
+ }
255
+ const next = new URL(location, url).href;
256
+ if (
257
+ ((res.status === 301 || res.status === 302) && method === 'POST') ||
258
+ (res.status === 303 && method !== 'GET' && method !== 'HEAD')
259
+ ) {
260
+ method = 'GET';
261
+ body = null;
262
+ for (const name of BODY_HEADERS) headers.delete(name);
263
+ } else if (body instanceof ReadableStream) {
264
+ await res.body?.cancel();
265
+ throw new TypeError(
266
+ 'fetch failed: a redirect cannot send a streamed body again',
267
+ );
268
+ }
269
+ if (originOf(next) !== originOf(url)) {
270
+ for (const name of CREDENTIAL_HEADERS) headers.delete(name);
271
+ }
272
+ await res.body?.cancel();
273
+ url = next;
274
+ prepare(url, headers, ctx);
275
+ }
276
+ }
@@ -10,11 +10,5 @@ export {ContextManager} from './context_manager';
10
10
  export {W3CPropagator, formatTraceparent, parseTraceparent} from './propagator';
11
11
  export {Meter, MeterProvider} from './meter';
12
12
  export {TracerProvider} from './provider';
13
- export {
14
- activeCtxBytes,
15
- ENCORE_REQUEST_KEY,
16
- getRequestFromContext,
17
- withRequestContext,
18
- } from './request_context';
19
- export {Span} from './span';
13
+ export {activeCtxBytes, Span} from './span';
20
14
  export {Tracer} from './tracer';
@@ -17,6 +17,7 @@ import {
17
17
  type TimeInput,
18
18
  } from '@opentelemetry/api';
19
19
  import type {Backend} from './backend';
20
+ import {activeContext} from './context';
20
21
  import {
21
22
  ctxBytes,
22
23
  encodeEnd,
@@ -237,6 +238,11 @@ export function contextCtxBytes(ctx: Context): Buffer | undefined {
237
238
  return span ? spanCtxBytes(span) : undefined;
238
239
  }
239
240
 
241
+ /** The active span's 25-byte context, if any. */
242
+ export function activeCtxBytes(): Buffer | undefined {
243
+ return contextCtxBytes(activeContext());
244
+ }
245
+
240
246
  /** The 25-byte context of the span in `ctx` when it is sampled: what a
241
247
  * measurement's exemplar names. */
242
248
  export function sampledCtxBytes(ctx: Context): Buffer | undefined {