@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
package/testing/mod.ts ADDED
@@ -0,0 +1,337 @@
1
+ /**
2
+ * Tests of an Encore app. Each test gets infrastructure of its own —
3
+ * databases, buckets, Redis databases and topics no other test sees — with
4
+ * nothing to set up but one line of runner config:
5
+ *
6
+ * | Runner | Config |
7
+ * |-----------|---------------------------------------------------------------------|
8
+ * | vitest | `test.setupFiles: ["@encore.dev/sdk/testing/vitest"]` |
9
+ * | jest | `setupFilesAfterEnv: ["@encore.dev/sdk/testing/jest"]` |
10
+ * | bun | `bunfig.toml`: `[test] preload = ["@encore.dev/sdk/testing/bun"]` |
11
+ * | node:test | `import "@encore.dev/sdk/testing/node"` at the top of each test file |
12
+ *
13
+ * The tests run with `encore test`, or with the runner itself (`vitest`,
14
+ * `bun test`, an editor's test button): Encore finds the app the tests are in,
15
+ * and starts its daemon if it is not running. `ENCORE_TEST=0` turns this off,
16
+ * and `ENCORE_TEST=1` turns it on for a runner Encore does not recognize.
17
+ *
18
+ * Nothing runs by itself in a test: what a test publishes is recorded, for it
19
+ * to read back with {@link published} and hand to a subscription with
20
+ * {@link deliver}.
21
+ *
22
+ * @example
23
+ * import {deliver, published} from "@encore.dev/sdk/testing";
24
+ *
25
+ * test("signup sends a welcome", async () => {
26
+ * await signup("ada");
27
+ * expect(published(signups)).toHaveLength(1);
28
+ * expect(await deliver(sendWelcome)).toBe(1);
29
+ * });
30
+ *
31
+ * @module
32
+ */
33
+ import type {AnySecret} from '../config/secrets';
34
+ import {setTestValue, type Config} from '../config/config';
35
+ import type {Message} from '../pubsub/subscription';
36
+ import {Subscription} from '../pubsub/subscription';
37
+ import type {OrderedTopic, Topic} from '../pubsub/topic';
38
+ import {fromMessageAttributes} from '../internal/reqfields';
39
+ import {
40
+ begin,
41
+ hookScope,
42
+ isContext,
43
+ requireScope,
44
+ requireScopes,
45
+ runIn,
46
+ Scope,
47
+ setupHooks,
48
+ testMode,
49
+ testName,
50
+ type Hooks,
51
+ } from '../internal/testing/scope';
52
+
53
+ export type {Hooks} from '../internal/testing/scope';
54
+
55
+ /** The options of {@link setup} and {@link scoped}. */
56
+ export interface ScopeOptions {
57
+ /**
58
+ * What each test starts from: a {@link Fixture}, or `null` for the
59
+ * resources' initial state, whatever {@link useFixture} says.
60
+ */
61
+ fixture?: Fixture | null;
62
+ }
63
+
64
+ /** The hooks {@link setup} was given, for {@link useFixture}. */
65
+ let registered: Hooks | undefined;
66
+
67
+ /**
68
+ * Registers per-test infrastructure with a runner's hooks: each test begins
69
+ * with resources of its own, released after it. The per-runner entry points
70
+ * (`@encore.dev/sdk/testing/vitest` and the others) call this for you.
71
+ *
72
+ * Once it has, a resource used outside any test — in a `beforeAll`, or at
73
+ * module level — throws: no test would see what it does. Set up what each
74
+ * test needs in `beforeEach`, or in a {@link fixture}.
75
+ *
76
+ * Outside test mode it registers nothing, so a test file still runs.
77
+ */
78
+ export function setup(hooks: Hooks, options?: ScopeOptions): void {
79
+ registered = hooks;
80
+ const fixture = options?.fixture;
81
+ setupHooks(
82
+ hooks,
83
+ fixture === undefined ? undefined : scope => choose(scope, fixture),
84
+ );
85
+ }
86
+
87
+ /**
88
+ * Wraps a test body to run in a scope of its own: for concurrent tests,
89
+ * which the runner's hooks cannot tell apart, or a runner without hooks.
90
+ *
91
+ * test.concurrent("x", scoped(async () => { ... }));
92
+ *
93
+ * The test starts from `options.fixture` if given, else from the fixture
94
+ * {@link useFixture} chose for it, where the runner hands the test its
95
+ * context (vitest, node:test). Outside test mode it runs `fn` as it is.
96
+ */
97
+ export function scoped<A extends unknown[], R>(
98
+ fn: (...args: A) => Promise<R> | R,
99
+ options?: ScopeOptions,
100
+ ): (...args: A) => Promise<R> {
101
+ // No parameters by name: jest and bun pass a test with parameters a
102
+ // `done` callback to call.
103
+ return async (...args: A): Promise<R> => {
104
+ const scope = begin(testName(args[0]));
105
+ if (scope === null) return fn(...args);
106
+ try {
107
+ return await runIn(scope, async () => {
108
+ const fixture =
109
+ options?.fixture !== undefined ? options.fixture : chosen(args[0]);
110
+ if (fixture !== undefined) await choose(scope, fixture);
111
+ return fn(...args);
112
+ });
113
+ } finally {
114
+ scope.end();
115
+ }
116
+ };
117
+ }
118
+
119
+ /**
120
+ * What the current test has published to `topic`, in the order it was
121
+ * published: by the test itself, and by the code it called. Nothing handles
122
+ * it otherwise: hand it to a subscription with {@link deliver}.
123
+ *
124
+ * Each message's `data` is what was published: decoded from JSON, or the
125
+ * bytes published as bytes.
126
+ */
127
+ export function published<T>(topic: Topic<T> | OrderedTopic<T>): Message<T>[] {
128
+ const scope = requireScope();
129
+ return scope.native.published(topic.name).map(msg => ({
130
+ data: (scope.raw.has(msg.id)
131
+ ? msg.data
132
+ : JSON.parse(msg.data.toString('utf8'))) as T,
133
+ rawData: msg.data,
134
+ id: msg.id,
135
+ attributes: fromMessageAttributes(msg.attributes).rest,
136
+ deliveryAttempt: 1,
137
+ publishTime: new Date(msg.publishTime),
138
+ orderingKey: msg.orderingKey ?? null,
139
+ }));
140
+ }
141
+
142
+ /**
143
+ * Runs `subscription`'s handler on each message the current test — or the
144
+ * code it called — published to its topic that the subscription has not
145
+ * handled yet, one at a time, in the order they were published, as part of
146
+ * the test. Resolves to how many it handled.
147
+ *
148
+ * As in a real delivery, the handler gets a message only if the
149
+ * subscription's filter matches it, decoded as the subscription says, with
150
+ * the Request Context fields it was published with, and `deliveryAttempt` 1
151
+ * the first time. What the handler publishes to the topic in turn is handed
152
+ * over in the same call.
153
+ *
154
+ * It stops at the first message the handler fails, and rejects with its
155
+ * error. That message stays unhandled: the next call hands it over again,
156
+ * its `deliveryAttempt` one more. Retry policies, ack deadlines and dead
157
+ * letters play no part.
158
+ */
159
+ export async function deliver<T>(
160
+ subscription: Subscription<T>,
161
+ ): Promise<number> {
162
+ const scope = requireScope();
163
+ return Subscription.deliverIn(
164
+ subscription as Subscription<unknown>,
165
+ scope,
166
+ requireScopes().maxDeliveries,
167
+ );
168
+ }
169
+
170
+ /**
171
+ * Gives `secret` a value for the current test, in place of the app's. No
172
+ * other test sees it, and it is gone when the test ends.
173
+ */
174
+ export function setSecret(secret: AnySecret, value: string | Uint8Array): void {
175
+ requireScope().native.setSecret(secret.name, Buffer.from(value));
176
+ }
177
+
178
+ /**
179
+ * Gives `config` a value for the current test, in place of the app's: what
180
+ * calling the config returns in the test from then on. No other test sees
181
+ * it, and it is gone when the test ends. Throws if the value does not
182
+ * satisfy the config's schema.
183
+ */
184
+ export function setConfig<T>(config: Config<T>, value: T): void {
185
+ setTestValue(requireScope(), config, value);
186
+ }
187
+
188
+ /**
189
+ * A saved state for tests to start from, in place of the app's freshly
190
+ * provisioned one: the rows a setup inserted, say. Declare one with
191
+ * {@link fixture}.
192
+ */
193
+ export interface Fixture {
194
+ /** The fixture's name, which identifies it across the app's test files. */
195
+ readonly name: string;
196
+ /** The fixture it extends: its setup starts from what that one saved. */
197
+ readonly parent?: Fixture;
198
+ /**
199
+ * Makes the current test start from the fixture, building it first if no
200
+ * test of the run has yet. Call it before the test first uses a resource:
201
+ * a test that has used one already cannot change what it started from.
202
+ */
203
+ load(): Promise<void>;
204
+ }
205
+
206
+ /** The options of {@link fixture}. */
207
+ export interface FixtureOptions {
208
+ /** A fixture to build on: the setup starts from what it saved. */
209
+ extends?: Fixture;
210
+ }
211
+
212
+ /**
213
+ * Declares a fixture: a state `setup` leaves the app's resources in,
214
+ * built once per test run and copied for each test that starts from it.
215
+ *
216
+ * const seeded = fixture("users.seeded", async () => {
217
+ * await db.exec`INSERT INTO users (name) VALUES ('ada'), ('grace')`;
218
+ * });
219
+ * useFixture(seeded);
220
+ *
221
+ * The setup is ordinary app code: its resources are the fixture's while it
222
+ * runs. It runs the first time a test loads the fixture, however many test
223
+ * files and workers load it. What it leaves in each database, bucket and
224
+ * Redis database it touched is saved; each test that loads the fixture gets
225
+ * a copy of its own. Other kinds of resource start each test from their
226
+ * initial state.
227
+ *
228
+ * The name identifies the fixture across the app's test files: two fixtures
229
+ * of one name are one fixture, built by whichever is loaded first.
230
+ */
231
+ export function fixture(
232
+ name: string,
233
+ setup: () => Promise<void> | void,
234
+ options?: FixtureOptions,
235
+ ): Fixture {
236
+ const f: Fixture = {
237
+ name,
238
+ parent: options?.extends,
239
+ load: () => load(f, requireScope()),
240
+ };
241
+ setups.set(f, setup);
242
+ return f;
243
+ }
244
+
245
+ /**
246
+ * Makes `f` what every test after this call in the file — or, called in a
247
+ * `describe` block, in the block — starts from; `null` for the resources'
248
+ * initial state. A {@link scoped} test starts from it too, unless told
249
+ * otherwise. Needs the runner adapter (or {@link setup}), whose hooks it
250
+ * adds to. Outside test mode it does nothing.
251
+ */
252
+ export function useFixture(f: Fixture | null): void {
253
+ if (!testMode) return;
254
+ if (registered === undefined) {
255
+ throw new Error(
256
+ 'useFixture needs the runner adapter for your test runner, such as ' +
257
+ "@encore.dev/sdk/testing/vitest in vitest's setupFiles",
258
+ );
259
+ }
260
+ registered.beforeEach((...args: unknown[]) => {
261
+ const ctx = args[0];
262
+ if (isContext(ctx)) chosenFor.set(ctx, f);
263
+ const scope = hookScope(ctx);
264
+ return scope === null ? undefined : choose(scope, f);
265
+ });
266
+ }
267
+
268
+ /** Each fixture's setup. */
269
+ const setups = new WeakMap<Fixture, () => Promise<void> | void>();
270
+
271
+ /** The fixture `useFixture` chose for the test of a runner's context. */
272
+ const chosenFor = new WeakMap<object, Fixture | null>();
273
+
274
+ function chosen(ctx: unknown): Fixture | null | undefined {
275
+ return isContext(ctx) ? chosenFor.get(ctx) : undefined;
276
+ }
277
+
278
+ /** Makes `scope`'s test start from `f`, or from nothing for `null`. */
279
+ async function choose(scope: Scope, f: Fixture | null): Promise<void> {
280
+ if (f === null) scope.native.useFixture(null);
281
+ else await load(f, scope);
282
+ }
283
+
284
+ /** Loads the fixture `f` into `scope`, building it first if need be. */
285
+ async function load(f: Fixture, scope: Scope): Promise<void> {
286
+ await ensureBuilt(f);
287
+ scope.native.useFixture(f.name);
288
+ }
289
+
290
+ /** Each fixture's build, as far as this process has asked. */
291
+ const builds = new WeakMap<Fixture, Promise<void>>();
292
+
293
+ function ensureBuilt(f: Fixture): Promise<void> {
294
+ let built = builds.get(f);
295
+ if (built === undefined) {
296
+ built = build(f);
297
+ builds.set(f, built);
298
+ }
299
+ return built;
300
+ }
301
+
302
+ /** Builds the fixture `f`, unless this process or another has already. */
303
+ async function build(f: Fixture): Promise<void> {
304
+ if (f.parent !== undefined) await ensureBuilt(f.parent);
305
+ const scopes = requireScopes();
306
+ const failed = (reason: string, cause?: unknown) =>
307
+ new Error(`cannot load the fixture ${JSON.stringify(f.name)}: ${reason}`, {
308
+ cause,
309
+ });
310
+ let native;
311
+ try {
312
+ native = await scopes.acquireFixture(f.name, f.parent?.name ?? null);
313
+ } catch (err) {
314
+ throw failed((err as Error).message, err);
315
+ }
316
+ if (native === null) return;
317
+
318
+ // The setup runs in a scope of its own, starting from the parent.
319
+ const scope = new Scope(native, `fixture ${JSON.stringify(f.name)}`);
320
+ try {
321
+ await runIn(scope, async () => setups.get(f)!());
322
+ } catch (err) {
323
+ const error = failed(
324
+ `its setup failed: ${err instanceof Error ? err.message : String(err)}`,
325
+ err,
326
+ );
327
+ scopes.failFixture(f.name, error.message);
328
+ scope.end();
329
+ throw error;
330
+ }
331
+ // The resources become the fixture's: saved, not released.
332
+ try {
333
+ await native.saveFixture(f.name);
334
+ } catch (err) {
335
+ throw failed((err as Error).message, err);
336
+ }
337
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Per-test infrastructure under `node --test`: `import
3
+ * "@encore.dev/sdk/testing/node"` at the top of each test file, before
4
+ * anything else.
5
+ *
6
+ * @module
7
+ */
8
+ import '../internal/testing/runner';
9
+ import {after, afterEach, beforeEach} from 'node:test';
10
+ import {setup} from './mod';
11
+
12
+ setup({beforeEach, afterEach, afterAll: after});
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Per-test infrastructure under vitest: `test.setupFiles:
3
+ * ["@encore.dev/sdk/testing/vitest"]` in the vitest config.
4
+ *
5
+ * @module
6
+ */
7
+ import '../internal/testing/runner';
8
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment -- an error in the build, which has no vitest
9
+ // @ts-ignore: vitest's own module, there when vitest runs this.
10
+ import {afterAll, afterEach, beforeEach} from 'vitest';
11
+ import {setup} from './mod';
12
+
13
+ setup({beforeEach, afterEach, afterAll});
package/tracing/mod.ts ADDED
@@ -0,0 +1,82 @@
1
+ import {SpanStatusCode, type Attributes, type Span} from '@opentelemetry/api';
2
+ import {tracerProvider} from '../otel';
3
+
4
+ export {tracerProvider};
5
+
6
+ /** Attributes recorded on the span. Use bounded names; put IDs in attributes. */
7
+ export interface SpanOptions {
8
+ attributes?: Attributes;
9
+ }
10
+
11
+ /**
12
+ * Runs a callback with an Encore-owned span active, ending it on return or
13
+ * promise settlement. Throws and rejections record an exception and ERROR
14
+ * status, unless the callback already set OTel's final OK status.
15
+ *
16
+ * The helper owns completion: do not call `end()` in the callback. Synchronous
17
+ * results and throws stay synchronous; PromiseLike results become Promises.
18
+ * No OpenTelemetry globals are registered.
19
+ */
20
+ export function span<T>(
21
+ name: string,
22
+ callback: (span: Span) => T,
23
+ ): T extends PromiseLike<unknown> ? Promise<Awaited<T>> : T;
24
+ export function span<T>(
25
+ name: string,
26
+ options: SpanOptions,
27
+ callback: (span: Span) => T,
28
+ ): T extends PromiseLike<unknown> ? Promise<Awaited<T>> : T;
29
+ export function span<T>(
30
+ name: string,
31
+ options: SpanOptions | ((span: Span) => T),
32
+ callback?: (span: Span) => T,
33
+ ): T | Promise<Awaited<T>> {
34
+ const fn = typeof options === 'function' ? options : callback!;
35
+ return tracerProvider()
36
+ .getTracer('encore')
37
+ .startActiveSpan(
38
+ name,
39
+ typeof options === 'function' ? {} : options,
40
+ current => {
41
+ const fail = (error: unknown) => {
42
+ current.setStatus({code: SpanStatusCode.ERROR});
43
+ try {
44
+ current.recordException(
45
+ error instanceof Error ? error : String(error),
46
+ );
47
+ } catch {
48
+ current.recordException('Unserializable thrown value');
49
+ }
50
+ current.end();
51
+ };
52
+ try {
53
+ const value = fn(current);
54
+ const then =
55
+ value !== null &&
56
+ (typeof value === 'object' || typeof value === 'function')
57
+ ? (value as unknown as {then?: unknown}).then
58
+ : undefined;
59
+ if (typeof then === 'function') {
60
+ // Capture `then` once: a getter can throw or change between reads.
61
+ return new Promise<unknown>((resolve, reject) => {
62
+ then.call(value, resolve, reject);
63
+ }).then(
64
+ result => {
65
+ current.end();
66
+ return result as Awaited<T>;
67
+ },
68
+ error => {
69
+ fail(error);
70
+ throw error;
71
+ },
72
+ );
73
+ }
74
+ current.end();
75
+ return value;
76
+ } catch (error) {
77
+ fail(error);
78
+ throw error;
79
+ }
80
+ },
81
+ );
82
+ }
@@ -0,0 +1,170 @@
1
+ import {expect, test} from 'bun:test';
2
+
3
+ // The native runtime exports completed public spans without global registration.
4
+ test('public spans reach the native OTLP destination with parents, errors, and log correlation', async () => {
5
+ const received: Buffer[] = [];
6
+ const server = Bun.serve({
7
+ port: 0,
8
+ async fetch(request) {
9
+ if (new URL(request.url).pathname === '/v1/traces') {
10
+ received.push(Buffer.from(await request.arrayBuffer()));
11
+ }
12
+ return new Response(new Uint8Array(), {
13
+ headers: {'content-type': 'application/x-protobuf'},
14
+ });
15
+ },
16
+ });
17
+ const proc = Bun.spawn({
18
+ cmd: [
19
+ process.execPath,
20
+ '-e',
21
+ `
22
+ import { span } from "${import.meta.dir}/mod";
23
+ import log from "${import.meta.dir}/../log/index";
24
+ await span("order_request", async () => {
25
+ await new Promise(resolve => setTimeout(resolve, 1));
26
+ span("validate_order", current => {
27
+ log.info("native correlation", {expected_span_id: current.spanContext().spanId});
28
+ return 3;
29
+ });
30
+ try {
31
+ await span("rejected_order", async () => { throw "invalid order"; });
32
+ } catch {}
33
+ });
34
+ setInterval(() => {}, 1000);
35
+ console.log("ready");
36
+ `,
37
+ ],
38
+ cwd: import.meta.dir,
39
+ env: {
40
+ ...process.env,
41
+ NODE_ENV: 'production',
42
+ ENCORE_RUNTIME_CONFIG: runtimeConfig(`http://127.0.0.1:${server.port}`),
43
+ OTEL_BSP_SCHEDULE_DELAY: '60000',
44
+ },
45
+ stdout: 'pipe',
46
+ stderr: 'pipe',
47
+ });
48
+ const timeout = setTimeout(() => proc.kill('SIGKILL'), 10_000);
49
+ try {
50
+ const reader = proc.stdout.getReader();
51
+ let stdout = '';
52
+ for (;;) {
53
+ const {done, value} = await reader.read();
54
+ if (done) break;
55
+ stdout += new TextDecoder().decode(value);
56
+ if (stdout.includes('ready')) break;
57
+ }
58
+ proc.kill('SIGTERM');
59
+ expect(await proc.exited).toBe(0);
60
+ expect(stdout).toContain('ready');
61
+ const exported = received.flatMap(body =>
62
+ fields(body, 1).flatMap(rs => fields(rs, 2).flatMap(ss => fields(ss, 2))),
63
+ );
64
+ const named = new Map(
65
+ exported.map(span => [fields(span, 5)[0]!.toString(), span]),
66
+ );
67
+ expect(exported).toHaveLength(3);
68
+ expect([...named.keys()].sort()).toEqual([
69
+ 'order_request',
70
+ 'rejected_order',
71
+ 'validate_order',
72
+ ]);
73
+ const outer = named.get('order_request')!;
74
+ for (const name of ['validate_order', 'rejected_order']) {
75
+ const child = named.get(name)!;
76
+ expect(fields(child, 1)[0]).toEqual(fields(outer, 1)[0]);
77
+ expect(fields(child, 4)[0]).toEqual(fields(outer, 2)[0]);
78
+ expect(fields(child, 8)[0]!.some(byte => byte !== 0)).toBe(true);
79
+ }
80
+ const failed = named.get('rejected_order')!;
81
+ expect(fields(fields(failed, 15)[0]!, 3)[0]).toEqual(Buffer.from([2]));
82
+ const event = fields(failed, 11)[0]!;
83
+ expect(fields(event, 2)[0]!.toString()).toBe('exception');
84
+ const stderr = await new Response(proc.stderr).text();
85
+ const record = stderr
86
+ .split('\n')
87
+ .filter(line => line.startsWith('{'))
88
+ .map(line => JSON.parse(line))
89
+ .find(record => record.message === 'native correlation');
90
+ expect(record.trace_id).toBe(fields(outer, 1)[0]!.toString('hex'));
91
+ expect(record.span_id).toBe(
92
+ fields(named.get('validate_order')!, 2)[0]!.toString('hex'),
93
+ );
94
+ expect(record.span_id).toBe(record.expected_span_id);
95
+ } finally {
96
+ clearTimeout(timeout);
97
+ proc.kill();
98
+ server.stop(true);
99
+ }
100
+ }, 15_000);
101
+
102
+ /** Raw values of protobuf field `want`. */
103
+ function fields(buf: Buffer, want: number): Buffer[] {
104
+ const out: Buffer[] = [];
105
+ let i = 0;
106
+ const varint = (): number => {
107
+ let n = 0;
108
+ let shift = 1;
109
+ for (;;) {
110
+ const b = buf[i++]!;
111
+ n += (b & 0x7f) * shift;
112
+ if (b < 0x80) return n;
113
+ shift *= 128;
114
+ }
115
+ };
116
+ while (i < buf.length) {
117
+ const key = varint();
118
+ const field = Math.floor(key / 8);
119
+ const start = i;
120
+ switch (key & 7) {
121
+ case 0:
122
+ varint();
123
+ break;
124
+ case 1:
125
+ i += 8;
126
+ break;
127
+ case 2: {
128
+ const len = varint();
129
+ if (field === want) out.push(buf.subarray(i, i + len));
130
+ i += len;
131
+ continue;
132
+ }
133
+ case 5:
134
+ i += 4;
135
+ break;
136
+ default:
137
+ throw new Error(`unsupported wire type ${key & 7}`);
138
+ }
139
+ if (field === want) out.push(buf.subarray(start, i));
140
+ }
141
+ return out;
142
+ }
143
+
144
+ /** RuntimeConfig hosting shop with an explicit TracingProvider OTLP/HTTP sink. */
145
+ function runtimeConfig(endpoint: string): string {
146
+ const varint = (n: number): number[] => {
147
+ const bytes: number[] = [];
148
+ do {
149
+ const byte = n & 0x7f;
150
+ n >>>= 7;
151
+ bytes.push(n ? byte | 0x80 : byte);
152
+ } while (n);
153
+ return bytes;
154
+ };
155
+ const msg = (field: number, body: number[]): number[] => [
156
+ ...varint((field << 3) | 2),
157
+ ...varint(body.length),
158
+ ...body,
159
+ ];
160
+ const str = (field: number, value: string) =>
161
+ msg(field, [...Buffer.from(value)]);
162
+ // RuntimeConfig{environment=1, deployment=3}; Deployment{hosted_services=5,
163
+ // observability=7}; Observability{tracing=1}; TracingProvider{rid=1, otlp_http=12}.
164
+ const tracing = [...str(1, 'traces'), ...msg(12, str(1, endpoint))];
165
+ const deployment = [...msg(5, str(1, 'shop')), ...msg(7, msg(1, tracing))];
166
+ return Buffer.from([
167
+ ...msg(1, str(1, 'app')),
168
+ ...msg(3, deployment),
169
+ ]).toString('base64');
170
+ }