@encore.dev/sdk 2.0.0-beta.14 → 2.0.0-beta.16

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 (269) hide show
  1. package/README.md +144 -90
  2. package/app_meta.ts +56 -54
  3. package/config/config.test.ts +47 -13
  4. package/config/config.ts +60 -57
  5. package/config/secrets.ts +47 -50
  6. package/config/value.ts +23 -26
  7. package/cron/mod.test.ts +12 -0
  8. package/cron/mod.ts +37 -22
  9. package/dist/app_meta.d.ts +52 -50
  10. package/dist/app_meta.d.ts.map +1 -1
  11. package/dist/app_meta.js +2 -2
  12. package/dist/app_meta.js.map +1 -1
  13. package/dist/config/config.d.ts +58 -55
  14. package/dist/config/config.d.ts.map +1 -1
  15. package/dist/config/config.js +8 -9
  16. package/dist/config/config.js.map +1 -1
  17. package/dist/config/secrets.d.ts +45 -50
  18. package/dist/config/secrets.d.ts.map +1 -1
  19. package/dist/config/secrets.js +11 -9
  20. package/dist/config/secrets.js.map +1 -1
  21. package/dist/config/value.d.ts +20 -23
  22. package/dist/config/value.d.ts.map +1 -1
  23. package/dist/config/value.js +20 -23
  24. package/dist/config/value.js.map +1 -1
  25. package/dist/cron/mod.d.ts +34 -20
  26. package/dist/cron/mod.d.ts.map +1 -1
  27. package/dist/cron/mod.js +13 -13
  28. package/dist/cron/mod.js.map +1 -1
  29. package/dist/frontends/mod.d.ts +20 -19
  30. package/dist/frontends/mod.d.ts.map +1 -1
  31. package/dist/frontends/mod.js +20 -19
  32. package/dist/frontends/mod.js.map +1 -1
  33. package/dist/gateway/errors.d.ts +28 -30
  34. package/dist/gateway/errors.d.ts.map +1 -1
  35. package/dist/gateway/errors.js +29 -31
  36. package/dist/gateway/errors.js.map +1 -1
  37. package/dist/gateway/match.d.ts +54 -54
  38. package/dist/gateway/match.d.ts.map +1 -1
  39. package/dist/gateway/match.js +56 -56
  40. package/dist/gateway/match.js.map +1 -1
  41. package/dist/gateway/middleware.d.ts +62 -64
  42. package/dist/gateway/middleware.d.ts.map +1 -1
  43. package/dist/gateway/middleware.js +1 -1
  44. package/dist/gateway/middleware.js.map +1 -1
  45. package/dist/gateway/mod.d.ts +64 -67
  46. package/dist/gateway/mod.d.ts.map +1 -1
  47. package/dist/gateway/mod.js +72 -76
  48. package/dist/gateway/mod.js.map +1 -1
  49. package/dist/gateway/request.d.ts +138 -134
  50. package/dist/gateway/request.d.ts.map +1 -1
  51. package/dist/gateway/request.js +117 -108
  52. package/dist/gateway/request.js.map +1 -1
  53. package/dist/gateway/serve.d.ts +29 -34
  54. package/dist/gateway/serve.d.ts.map +1 -1
  55. package/dist/gateway/serve.js +51 -56
  56. package/dist/gateway/serve.js.map +1 -1
  57. package/dist/gateways/mod.d.ts +23 -21
  58. package/dist/gateways/mod.d.ts.map +1 -1
  59. package/dist/gateways/mod.js +25 -23
  60. package/dist/gateways/mod.js.map +1 -1
  61. package/dist/internal/otel/http.d.ts +4 -2
  62. package/dist/internal/otel/http.d.ts.map +1 -1
  63. package/dist/internal/otel/http.js +32 -5
  64. package/dist/internal/otel/http.js.map +1 -1
  65. package/dist/internal/runtime/napi/napi.cjs +6 -5
  66. package/dist/internal/runtime/napi/napi.d.cts +58 -16
  67. package/dist/internal/runtime/shutdown.d.ts +75 -57
  68. package/dist/internal/runtime/shutdown.d.ts.map +1 -1
  69. package/dist/internal/runtime/shutdown.js +88 -84
  70. package/dist/internal/runtime/shutdown.js.map +1 -1
  71. package/dist/log/logger.d.ts +43 -37
  72. package/dist/log/logger.d.ts.map +1 -1
  73. package/dist/log/logger.js +26 -25
  74. package/dist/log/logger.js.map +1 -1
  75. package/dist/metrics/mod.d.ts +133 -114
  76. package/dist/metrics/mod.d.ts.map +1 -1
  77. package/dist/metrics/mod.js +109 -101
  78. package/dist/metrics/mod.js.map +1 -1
  79. package/dist/otel.d.ts +6 -3
  80. package/dist/otel.d.ts.map +1 -1
  81. package/dist/otel.js +6 -3
  82. package/dist/otel.js.map +1 -1
  83. package/dist/pubsub/subscription.d.ts +88 -116
  84. package/dist/pubsub/subscription.d.ts.map +1 -1
  85. package/dist/pubsub/subscription.js +14 -17
  86. package/dist/pubsub/subscription.js.map +1 -1
  87. package/dist/pubsub/topic.d.ts +86 -113
  88. package/dist/pubsub/topic.d.ts.map +1 -1
  89. package/dist/pubsub/topic.js +68 -82
  90. package/dist/pubsub/topic.js.map +1 -1
  91. package/dist/redaction/mod.d.ts +62 -0
  92. package/dist/redaction/mod.d.ts.map +1 -0
  93. package/dist/redaction/mod.js +102 -0
  94. package/dist/redaction/mod.js.map +1 -0
  95. package/dist/reqctx/mod.d.ts +83 -86
  96. package/dist/reqctx/mod.d.ts.map +1 -1
  97. package/dist/reqctx/mod.js +39 -41
  98. package/dist/reqctx/mod.js.map +1 -1
  99. package/dist/services/index.d.ts +76 -75
  100. package/dist/services/index.d.ts.map +1 -1
  101. package/dist/services/index.js +73 -71
  102. package/dist/services/index.js.map +1 -1
  103. package/dist/shutdown/mod.d.ts +26 -25
  104. package/dist/shutdown/mod.d.ts.map +1 -1
  105. package/dist/shutdown/mod.js +26 -25
  106. package/dist/shutdown/mod.js.map +1 -1
  107. package/dist/storage/clickhouse/database.d.ts +113 -115
  108. package/dist/storage/clickhouse/database.d.ts.map +1 -1
  109. package/dist/storage/clickhouse/database.js +65 -79
  110. package/dist/storage/clickhouse/database.js.map +1 -1
  111. package/dist/storage/clickhouse/errors.d.ts +25 -26
  112. package/dist/storage/clickhouse/errors.d.ts.map +1 -1
  113. package/dist/storage/clickhouse/errors.js +15 -17
  114. package/dist/storage/clickhouse/errors.js.map +1 -1
  115. package/dist/storage/clickhouse/mod.d.ts +10 -10
  116. package/dist/storage/clickhouse/mod.js +10 -10
  117. package/dist/storage/objects/bucket.d.ts +230 -203
  118. package/dist/storage/objects/bucket.d.ts.map +1 -1
  119. package/dist/storage/objects/bucket.js +146 -106
  120. package/dist/storage/objects/bucket.js.map +1 -1
  121. package/dist/storage/objects/error.d.ts +4 -4
  122. package/dist/storage/objects/error.js +4 -4
  123. package/dist/storage/objects/mod.d.ts +1 -1
  124. package/dist/storage/objects/mod.d.ts.map +1 -1
  125. package/dist/storage/objects/mod.js.map +1 -1
  126. package/dist/storage/objects/refs.d.ts +2 -5
  127. package/dist/storage/objects/refs.d.ts.map +1 -1
  128. package/dist/storage/objects/refs.js.map +1 -1
  129. package/dist/storage/postgres/database.d.ts +124 -149
  130. package/dist/storage/postgres/database.d.ts.map +1 -1
  131. package/dist/storage/postgres/database.js +98 -135
  132. package/dist/storage/postgres/database.js.map +1 -1
  133. package/dist/storage/postgres/errors.d.ts +42 -48
  134. package/dist/storage/postgres/errors.d.ts.map +1 -1
  135. package/dist/storage/postgres/errors.js +44 -51
  136. package/dist/storage/postgres/errors.js.map +1 -1
  137. package/dist/storage/postgres/interval.d.ts +19 -19
  138. package/dist/storage/postgres/interval.d.ts.map +1 -1
  139. package/dist/storage/postgres/interval.js +21 -21
  140. package/dist/storage/postgres/interval.js.map +1 -1
  141. package/dist/storage/redis/bitfield.d.ts +48 -23
  142. package/dist/storage/redis/bitfield.d.ts.map +1 -1
  143. package/dist/storage/redis/bitfield.js +38 -19
  144. package/dist/storage/redis/bitfield.js.map +1 -1
  145. package/dist/storage/redis/command.d.ts +16 -12
  146. package/dist/storage/redis/command.d.ts.map +1 -1
  147. package/dist/storage/redis/command.js +16 -12
  148. package/dist/storage/redis/command.js.map +1 -1
  149. package/dist/storage/redis/commands.d.ts +99 -100
  150. package/dist/storage/redis/commands.d.ts.map +1 -1
  151. package/dist/storage/redis/commands.js +84 -85
  152. package/dist/storage/redis/commands.js.map +1 -1
  153. package/dist/storage/redis/database.d.ts +138 -122
  154. package/dist/storage/redis/database.d.ts.map +1 -1
  155. package/dist/storage/redis/database.js +120 -101
  156. package/dist/storage/redis/database.js.map +1 -1
  157. package/dist/storage/redis/mod.d.ts +52 -48
  158. package/dist/storage/redis/mod.d.ts.map +1 -1
  159. package/dist/storage/redis/mod.js +52 -48
  160. package/dist/storage/redis/mod.js.map +1 -1
  161. package/dist/storage/redis/options.d.ts +26 -24
  162. package/dist/storage/redis/options.d.ts.map +1 -1
  163. package/dist/storage/redis/options.js.map +1 -1
  164. package/dist/storage/redis/pubsub.d.ts +16 -16
  165. package/dist/storage/redis/pubsub.d.ts.map +1 -1
  166. package/dist/storage/redis/pubsub.js +14 -14
  167. package/dist/storage/redis/pubsub.js.map +1 -1
  168. package/dist/storage/redis/reply.d.ts +80 -72
  169. package/dist/storage/redis/reply.d.ts.map +1 -1
  170. package/dist/storage/redis/reply.js +53 -46
  171. package/dist/storage/redis/reply.js.map +1 -1
  172. package/dist/storage/redis/scan.d.ts +4 -4
  173. package/dist/storage/redis/scan.d.ts.map +1 -1
  174. package/dist/storage/redis/scan.js +6 -6
  175. package/dist/storage/redis/scan.js.map +1 -1
  176. package/dist/storage/redis/script.d.ts +28 -21
  177. package/dist/storage/redis/script.d.ts.map +1 -1
  178. package/dist/storage/redis/script.js +29 -22
  179. package/dist/storage/redis/script.js.map +1 -1
  180. package/dist/storage/redis/target.d.ts +17 -1
  181. package/dist/storage/redis/target.d.ts.map +1 -1
  182. package/dist/storage/redis/target.js +30 -1
  183. package/dist/storage/redis/target.js.map +1 -1
  184. package/dist/storage/redis/wire.d.ts +6 -6
  185. package/dist/storage/redis/wire.d.ts.map +1 -1
  186. package/dist/storage/redis/wire.js +6 -6
  187. package/dist/storage/redis/wire.js.map +1 -1
  188. package/dist/testing/mod.d.ts +83 -88
  189. package/dist/testing/mod.d.ts.map +1 -1
  190. package/dist/testing/mod.js +75 -81
  191. package/dist/testing/mod.js.map +1 -1
  192. package/dist/testing/playwright.d.ts +28 -32
  193. package/dist/testing/playwright.d.ts.map +1 -1
  194. package/dist/testing/playwright.js +22 -27
  195. package/dist/testing/playwright.js.map +1 -1
  196. package/dist/testing/puppeteer.d.ts +11 -12
  197. package/dist/testing/puppeteer.d.ts.map +1 -1
  198. package/dist/testing/puppeteer.js +17 -18
  199. package/dist/testing/puppeteer.js.map +1 -1
  200. package/dist/testing/system.d.ts +72 -90
  201. package/dist/testing/system.d.ts.map +1 -1
  202. package/dist/testing/system.js +90 -107
  203. package/dist/testing/system.js.map +1 -1
  204. package/dist/tracing/http.d.ts +2 -1
  205. package/dist/tracing/http.d.ts.map +1 -1
  206. package/dist/tracing/http.js +2 -1
  207. package/dist/tracing/http.js.map +1 -1
  208. package/dist/tracing/node.d.ts.map +1 -1
  209. package/dist/tracing/node.js +1 -1
  210. package/dist/tracing/node.js.map +1 -1
  211. package/dist/tsconfig.build.tsbuildinfo +1 -1
  212. package/frontends/mod.test.ts +6 -2
  213. package/frontends/mod.ts +20 -19
  214. package/gateway/errors.ts +30 -32
  215. package/gateway/match.ts +61 -57
  216. package/gateway/middleware.ts +62 -64
  217. package/gateway/mod.ts +73 -76
  218. package/gateway/request.ts +143 -140
  219. package/gateway/serve.ts +58 -63
  220. package/gateways/mod.ts +25 -23
  221. package/internal/otel/http.test.ts +50 -0
  222. package/internal/otel/http.ts +40 -5
  223. package/internal/runtime/napi/napi.cjs +6 -5
  224. package/internal/runtime/napi/napi.d.cts +58 -16
  225. package/internal/runtime/shutdown.ts +113 -101
  226. package/log/logger.test.ts +8 -0
  227. package/log/logger.ts +48 -45
  228. package/metrics/mod.ts +138 -122
  229. package/otel.ts +6 -3
  230. package/package.json +6 -1
  231. package/pubsub/subscription.ts +93 -123
  232. package/pubsub/topic.ts +96 -130
  233. package/redaction/bridge.test.ts +99 -0
  234. package/redaction/mod.test.ts +188 -0
  235. package/redaction/mod.ts +226 -0
  236. package/reqctx/mod.ts +83 -86
  237. package/services/index.ts +78 -78
  238. package/shutdown/mod.ts +26 -25
  239. package/storage/clickhouse/database.ts +115 -129
  240. package/storage/clickhouse/errors.ts +27 -29
  241. package/storage/clickhouse/mod.ts +10 -10
  242. package/storage/objects/bucket.test.ts +168 -16
  243. package/storage/objects/bucket.ts +336 -247
  244. package/storage/objects/error.ts +4 -4
  245. package/storage/objects/mod.ts +1 -0
  246. package/storage/objects/refs.ts +2 -5
  247. package/storage/postgres/database.ts +131 -164
  248. package/storage/postgres/errors.ts +45 -52
  249. package/storage/postgres/interval.ts +21 -21
  250. package/storage/redis/bitfield.ts +51 -26
  251. package/storage/redis/command.ts +16 -12
  252. package/storage/redis/commands.ts +99 -100
  253. package/storage/redis/database.ts +145 -123
  254. package/storage/redis/mod.ts +52 -48
  255. package/storage/redis/options.ts +26 -24
  256. package/storage/redis/pubsub.ts +14 -14
  257. package/storage/redis/redis.test.ts +17 -2
  258. package/storage/redis/reply.ts +85 -77
  259. package/storage/redis/scan.ts +6 -6
  260. package/storage/redis/script.ts +29 -22
  261. package/storage/redis/target.ts +34 -1
  262. package/storage/redis/wire.ts +8 -8
  263. package/testing/mod.ts +99 -105
  264. package/testing/playwright.ts +32 -37
  265. package/testing/puppeteer.ts +22 -23
  266. package/testing/system.ts +117 -133
  267. package/tracing/http.ts +2 -1
  268. package/tracing/native.test.ts +158 -8
  269. package/tracing/node.ts +1 -0
package/README.md CHANGED
@@ -1,7 +1,44 @@
1
- # Encore JavaScript/TypeScript Infra SDK (@encore.dev/sdk)
1
+ # Encore JavaScript/TypeScript Infra SDK (`@encore.dev/sdk`)
2
2
 
3
- This package contains the Encore JavaScript/TypeScript SDK, it is intended for you to use in your applications to develop
4
- against the Encore API.
3
+ This package provides the Encore JavaScript/TypeScript SDK for building applications with Encore's infrastructure primitives.
4
+
5
+ ## Telemetry redaction
6
+
7
+ `redactor()` applies the deployed redaction policy to copies of payloads and metadata without emitting telemetry.
8
+
9
+ ```typescript
10
+ import {redactor} from '@encore.dev/sdk/redaction';
11
+
12
+ const redact = redactor();
13
+ const http = redact.http('POST', '/orders/private?token=secret');
14
+ const {route, path, query} = http.requestUrl();
15
+ const request = http.request({headers: wireHeaders, body: requestBytes});
16
+ const response = http.response({headers: responseHeaders, body: responseBytes});
17
+
18
+ // method is a real @bufbuild/protobuf DescMethod.
19
+ const grpc = redact.grpc(method);
20
+ const safeRequest = grpc.request({metadata, message: protobufBytes});
21
+ const safeResponse = grpc.response({
22
+ metadata,
23
+ message: protobufBytes,
24
+ trailers,
25
+ });
26
+ const published = redact.topic('submitted').publish(jsonBytes);
27
+ const delivered = redact.topic('submitted').delivery('worker', jsonBytes);
28
+ ```
29
+
30
+ Headers, metadata, and trailers are iterables of `[string, string]` pairs.
31
+ gRPC binary metadata uses base64 wire values. HTTP exchanges return
32
+ `{headers, body?}`; gRPC exchanges return `{metadata, message?}` and preserve
33
+ supplied response trailers as `trailers`. Omitting `body` or `message` skips
34
+ payload capture, while passing empty bytes still requests capture. Payloads use
35
+ the `omit`, `withheld`, or `recorded` status tags; only `recorded` contains
36
+ safe `body` bytes and a `truncated` flag.
37
+
38
+ `requestUrl()` returns nullable `route`, `path`, and `query` strings. `query`
39
+ has no leading `?`. Never replace `null` fields or omitted/withheld payloads
40
+ with original values. Server spans use these safe URL fields without raw
41
+ fallbacks.
5
42
 
6
43
  ## Postgres handles
7
44
 
@@ -17,18 +54,20 @@ async function findOrder(queries: Queryable, id: number) {
17
54
  const order = await findOrder(db.read(), 1);
18
55
  ```
19
56
 
20
- Use `read({ primary: true })`, `write()`, or `admin()` to select access before
21
- passing a database to another function. `DatabaseRef`, `Connection`, and
22
- `Transaction` implement `Queryable`; the `Database` declaration does not.
23
- Direct operations on the declaration infer writer access. Handles share the
24
- declaration's pool. A `read()` handle runs on read-only connections, so its
25
- writes fail with SQLSTATE 25006 and its transactions are read-only; it reads
26
- from the database's read-only pool on a replica if the runtime config has one,
27
- unless `primary: true` is set.
57
+ Use `read({ primary: true })`, `write()`, or `admin()` to select an access mode
58
+ before passing a database handle to another function. `DatabaseRef`,
59
+ `Connection`, and `Transaction` implement `Queryable`; the `Database`
60
+ declaration itself does not. Direct operations on the `Database` declaration
61
+ infer writer access. Handles share the declaration's connection pool.
62
+
63
+ A `read()` handle runs on read-only connections, so writes fail with SQLSTATE
64
+ `25006` and its transactions are read-only. It reads from a read replica pool
65
+ if the runtime config provides one, unless `primary: true` is set.
28
66
 
29
- `queryRow` and `rawQueryRow` return a row or `null` and reject multiple rows.
30
- `exec` and `rawExec` return `{ rowsAffected: bigint }`, draining any `RETURNING`
31
- rows before resolving. The bigint preserves PostgreSQL's full affected-row count.
67
+ `queryRow` and `rawQueryRow` return a single row or `null`, and reject if more
68
+ than one row is returned. `exec` and `rawExec` return `{ rowsAffected: bigint }`,
69
+ draining any `RETURNING` rows before resolving. The `bigint` preserves
70
+ PostgreSQL's full affected-row count.
32
71
 
33
72
  ```typescript
34
73
  await using conn = await db.write().acquire();
@@ -37,15 +76,17 @@ const result = await tx.exec`UPDATE orders SET paid = true WHERE id = ${1}`;
37
76
  await tx.commit();
38
77
  ```
39
78
 
40
- Transactions roll back on async disposal unless explicitly completed; a clean
41
- scope exit does not commit. Connections return to the pool on async disposal.
42
- An acquired connection cannot be used or closed while its transaction is active.
43
- A connection's session settings and role (`SET`, `set_config`, `SET ROLE`) are
44
- reset before the pool lends it again. Only the statements a query sends are
45
- seen: a setting a function or procedure changes for the session, such as
46
- `SELECT set_tenant($1)` calling `set_config(..., false)`, is not, and stays for
47
- the connection's next borrower. Scope a setting to a transaction with
48
- `set_config(name, value, true)`:
79
+ Transactions roll back on async disposal unless explicitly committed or rolled
80
+ back; exiting a scope cleanly does not commit. Connections return to the pool
81
+ on async disposal. An acquired connection cannot be used or closed while its
82
+ transaction is active.
83
+
84
+ Session settings and roles (`SET`, `set_config`, `SET ROLE`) are reset before
85
+ the pool lends a connection again. However, Encore only tracks statements sent
86
+ directly in queries: a setting changed indirectly by a stored function or
87
+ procedure (such as `SELECT set_tenant($1)` calling `set_config(..., false)`) is
88
+ not detected and remains in effect for the next borrower. Scope per-request
89
+ settings to a transaction using `set_config(name, value, true)`:
49
90
 
50
91
  ```typescript
51
92
  await using tx = await db.write().begin();
@@ -55,8 +96,9 @@ await tx.commit();
55
96
  ```
56
97
 
57
98
  Streaming queries exclusively borrow their connection or transaction until
58
- exhausted or closed. `for await` closes a stream when the loop exits early;
59
- when manually advancing an iterator, call `return()` before reusing its owner.
99
+ exhausted or closed. `for await` closes the stream automatically if the loop
100
+ exits early; when manually advancing an iterator, call `return()` before
101
+ reusing its connection or transaction.
60
102
 
61
103
  Run the SQL wrapper tests with `bun test storage/postgres/database.test.ts`.
62
104
  The native integration test is enabled with `ENCORE_TS_POSTGRES_TEST_HOST=host:port`
@@ -67,9 +109,9 @@ if it is not staged beside the SDK.
67
109
  ## Pub/Sub payloads and ordering
68
110
 
69
111
  Subscriptions start automatically when declared. JSON messages are decoded into
70
- `Message<T>.data`; `rawData` always contains the original bytes. The wrapper also
71
- exposes `id`, `attributes`, `deliveryAttempt`, `publishTime`, and `orderingKey`
72
- (`null` for messages without a key).
112
+ `Message<T>.data`, while `rawData` always contains the original bytes. The
113
+ message wrapper also exposes `id`, `attributes`, `deliveryAttempt`,
114
+ `publishTime`, and `orderingKey` (`null` for messages without a key).
73
115
 
74
116
  ```typescript
75
117
  import {OrderedTopic, Subscription, Topic} from '@encore.dev/sdk/pubsub';
@@ -100,21 +142,21 @@ await files.publish(Buffer.from([0, 255]));
100
142
  `Buffer`/`Uint8Array` bytes. Both topic constructors default to at-least-once
101
143
  delivery; pass `{ deliveryGuarantee: "exactly-once" }` to request exactly-once.
102
144
  `OrderedTopic.publish(payload, orderingKey, attributes?)` requires an explicit,
103
- non-empty key, which is published as the provider's own ordering key, not as an
104
- attribute. Use `OrderedTopic.named<T>("name")` for a topic declared elsewhere,
105
- including Python or Rust. A `Topic` is unordered; declare an `OrderedTopic` for
106
- ordered delivery.
107
-
108
- TypeScript types do not validate incoming JSON. Supply `decode: (data) => ...`
109
- to validate or transform the parsed JSON into your message type. Use
110
- `encoding: "raw"` for byte subscriptions, or combine it with a `decode` callback
111
- for a custom format. Invalid JSON, decoder errors, and handler failures reject
112
- the delivery so the runtime can apply its retry policy.
113
-
114
- This changes `message.data` from raw bytes to decoded JSON by default. Existing
115
- handlers that parse JSON manually should use the decoded value, or explicitly
116
- select `encoding: "raw"`. Consumer termination no longer starts another consumer
117
- after a timer: failures are logged, and normal completion leaves it stopped.
145
+ non-empty ordering key, which is sent as the provider's native ordering key
146
+ rather than an attribute. Use `OrderedTopic.named<T>("name")` to reference a
147
+ topic declared elsewhere (including in Python or Rust). A `Topic` is unordered;
148
+ declare an `OrderedTopic` when you need ordered delivery.
149
+
150
+ TypeScript types do not validate incoming JSON at runtime. Supply
151
+ `decode: (data) => ...` to validate or transform parsed JSON into your message
152
+ type. Use `encoding: "raw"` for byte subscriptions, or combine it with a
153
+ `decode` callback for a custom format. Invalid JSON, decoder errors, and
154
+ handler failures reject the delivery so the runtime can apply its retry policy.
155
+
156
+ `message.data` is decoded JSON by default rather than raw bytes. Handlers that
157
+ parse JSON manually should use the decoded value directly or explicitly select
158
+ `encoding: "raw"`. When a consumer stops, it is no longer restarted on a timer:
159
+ failures are logged, and normal completion leaves the consumer stopped.
118
160
 
119
161
  ## Tracing
120
162
 
@@ -134,23 +176,26 @@ const items = await span(
134
176
  );
135
177
  ```
136
178
 
137
- `span(name, callback)` omits attributes. The callback gets
138
- an OpenTelemetry `Span`; the helper owns completion, so do not call `end()`.
139
- Synchronous callbacks return or throw synchronously. PromiseLike results become
140
- Promises, and the span ends after settlement. Throws and rejections record an
141
- exception and ERROR status, preserving the original value. OTel's OK status is
142
- final: setting it prevents a later ERROR status. Successful callbacks leave
143
- status UNSET unless the callback sets it.
144
-
145
- Use bounded span names; put order IDs and other variable data in attributes.
146
- Nested spans, logs, metric exemplars, and service calls share the active context
147
- across awaits and timers. Detached work must manage its own lifetime.
148
-
149
- Encore always uses its cached, owned provider, independent of OTel globals.
150
- Importing or using tracing registers no global provider, context manager,
151
- propagator, meter, or logger. Native `span` works without OTel setup. For OTel
152
- interop, the app owns its context manager and configures it through normal OTel
153
- setup before instrumented work. Pass Encore's tracer provider explicitly:
179
+ `span(name, callback)` creates a span without attributes. The callback receives
180
+ an OpenTelemetry `Span`; the helper manages the span's lifecycle, so do not
181
+ call `end()`. Synchronous callbacks return or throw synchronously.
182
+ `PromiseLike` results return a `Promise`, and the span ends once it settles.
183
+ Thrown errors and rejections record an exception and set the span status to
184
+ `ERROR`, rethrowing the original error. OpenTelemetry's `OK` status is final:
185
+ setting it prevents a later `ERROR` status. Successful callbacks leave the
186
+ status `UNSET` unless the callback sets it explicitly.
187
+
188
+ Use bounded span names and place order IDs or other high-cardinality values in
189
+ attributes. Nested spans, logs, metric exemplars, and service calls inherit the
190
+ active context across `await` boundaries and timers. Detached background work
191
+ must manage its own lifecycle.
192
+
193
+ Encore always uses its own cached tracer provider, independent of OpenTelemetry
194
+ globals. Importing or using tracing does not register a global provider,
195
+ context manager, propagator, meter, or logger. Native `span` works without any
196
+ OpenTelemetry setup. For OpenTelemetry interop, configure your application's
197
+ context manager through standard OpenTelemetry setup before instrumented work,
198
+ and pass Encore's tracer provider explicitly:
154
199
 
155
200
  ```typescript
156
201
  import {span, tracerProvider} from '@encore.dev/sdk/tracing';
@@ -166,9 +211,9 @@ await tracer.startActiveSpan('order_request', async current => {
166
211
  });
167
212
  ```
168
213
 
169
- The app may choose `trace.setGlobalTracerProvider(tracerProvider())` for libraries
170
- that use the global API; Encore never does this automatically. `tracerProvider`
171
- remains available from `@encore.dev/sdk`. See the paired
214
+ Your application may call `trace.setGlobalTracerProvider(tracerProvider())` for
215
+ libraries that rely on the global API; Encore never sets globals automatically.
216
+ `tracerProvider` is also exported from `@encore.dev/sdk`. See the paired
172
217
  [tracing fixtures](../../../tests/ts/telemetry) for runnable examples.
173
218
 
174
219
  ### HTTP handlers
@@ -182,19 +227,20 @@ Bun.serve({fetch: instrumentHTTP(handleRequest)});
182
227
  ```
183
228
 
184
229
  `instrumentHTTP` extracts W3C trace context and Encore Request Context, then
185
- runs the handler with an Encore-owned SERVER span active. Nested spans, logs,
186
- metrics and service calls inherit it. Extra handler arguments and `this` are
187
- preserved; no OTel globals are registered or replaced.
188
-
189
- Span names use the HTTP method. Raw URL paths and queries are not recorded:
190
- paths may contain credentials or personal identifiers. Framework adapters can
191
- add a safe `http.route` template. Response status is recorded;
192
- 5xx responses and thrown errors mark the span ERROR. Exceptions are rethrown.
193
- The original response and its body are untouched: the span ends when the
194
- handler returns a response, not when a streaming body finishes. Handlers must
195
- return a `Response`; WebSocket upgrades need a runtime-specific adapter.
196
- Only accept Encore Request Context headers from trusted Encore ingress; the
197
- wrapper decodes them, not authenticates them.
230
+ runs the handler inside an Encore-owned `SERVER` span. Nested spans, logs,
231
+ metrics, and service calls inherit this context. Extra handler arguments and
232
+ `this` are preserved, and no OpenTelemetry globals are registered or replaced.
233
+
234
+ Span names are `METHOD /template` when a deployed policy supplies a route, or
235
+ `METHOD` with no `http.route` otherwise; unknown methods use `HTTP`. Recorded
236
+ URL paths, queries, and user agents come only from the deployed policy. Response
237
+ status codes are recorded, and 5xx responses or thrown errors mark the span as
238
+ `ERROR` (errors are rethrown). The original `Response` and its body are
239
+ untouched, so the span ends when the handler returns a `Response` rather than
240
+ when a streaming body finishes. Handlers must return a `Response`; WebSocket
241
+ upgrades require a runtime-specific adapter. Only accept Encore Request Context
242
+ headers from trusted Encore ingress — the wrapper decodes them without
243
+ authenticating them.
198
244
 
199
245
  ### Node HTTP handlers
200
246
 
@@ -210,20 +256,28 @@ createServer(
210
256
  ).listen(3000);
211
257
  ```
212
258
 
213
- The Node adapter accepts native `IncomingMessage`/`ServerResponse` listeners;
214
- request and response bodies are not converted or buffered. It shares trace
215
- and Request Context extraction with the Fetch wrapper and preserves `this`.
216
- During response processing, request/response event callbacks run in the
217
- request's context.
218
-
219
- Its span lasts until response `finish`, premature `close`, response error,
220
- or a thrown/rejected handler failure. A handler returning before a streamed
221
- response finishes does not end the span. Premature closes mark it ERROR.
222
- The adapter records and rethrows handler failures; the application remains
223
- responsible for error responses and handling rejected async listeners.
224
- Failures before headers are sent have no recorded HTTP response status.
225
- Synchronous return values are preserved; PromiseLike results become Promises.
226
- HTTP upgrade and CONNECT events require separate instrumentation.
259
+ The Node adapter wraps native `IncomingMessage`/`ServerResponse` listeners
260
+ without converting or buffering request or response bodies. It shares trace and
261
+ Request Context extraction with the Fetch wrapper and preserves `this`. During
262
+ response processing, request and response event callbacks run in the request's
263
+ context.
264
+
265
+ The span ends on response `finish`, premature `close`, response error, or a
266
+ thrown/rejected handler error. Returning from a handler before a streamed
267
+ response finishes does not end the span. Premature closes mark the span as
268
+ `ERROR`. The adapter records and rethrows handler failures; your application
269
+ remains responsible for writing error responses and handling rejected async
270
+ listeners. Failures occurring before headers are sent do not record an HTTP
271
+ response status. Synchronous return values are preserved; `PromiseLike` results
272
+ return a `Promise`. HTTP `upgrade` and `CONNECT` events require separate
273
+ instrumentation.
274
+
275
+ ### Framework instrumentation
276
+
277
+ The Node and Fetch wrappers use the deployed route template, or just the
278
+ method if no route matches. For framework-specific routes, use the framework's
279
+ OpenTelemetry instrumentation with Encore's providers instead. Do not install
280
+ two server tracers for the same requests.
227
281
 
228
282
  ## Formatting and linting
229
283
 
package/app_meta.ts CHANGED
@@ -3,42 +3,43 @@ import * as runtime from './internal/runtime/mod';
3
3
  /** Describes the running Encore application. */
4
4
  export interface AppMeta {
5
5
  /**
6
- * The Encore application ID. If the application is not linked to the Encore platform this will be an empty string.
7
- * To link to the Encore platform run `encore cloud link` from your terminal in the root directory of the Encore app.
6
+ * The Encore application ID. If the application is not linked to the Encore
7
+ * platform, this is an empty string. To link the application, run
8
+ * `encore cloud link` in the root directory of your Encore app.
8
9
  */
9
10
  appId: string;
10
11
 
11
12
  /**
12
- * The Encore application slug — the human-readable identifier shown in the Encore
13
- * Cloud dashboard and used by the CLI. If the application is not linked to the
14
- * Encore platform this will be an empty string.
13
+ * The Encore application slug — the human-readable identifier shown in the
14
+ * Encore Cloud dashboard and used by the CLI. If the application is not
15
+ * linked to the Encore platform, this is an empty string.
15
16
  *
16
- * Distinct from `appId`: the id is opaque and stable, the slug is readable and may
17
- * be renamed. Locally the two are the same.
17
+ * Distinct from `appId`: the ID is opaque and stable, whereas the slug is
18
+ * human-readable and may be renamed. Locally, both have the same value.
18
19
  */
19
20
  appSlug: string;
20
21
 
21
22
  /**
22
- * The API gateways of this application this service is given, keyed by
23
- * gateway name: those its code looks up the URL of, and the one it hosts.
23
+ * The API gateways visible to this service, keyed by gateway name.
24
24
  *
25
- * An application can declare several gateways, so there is no single base URL for
26
- * the API — look up the gateway you mean by name. A service's processes, its
27
- * Workers' included, list the gateways its code names (`url("api")` from
28
- * `@encore.dev/sdk/gateways`) and the one it hosts, and no other; one told of
29
- * none, as under `encore test`, reports an empty object.
25
+ * Because an application can declare multiple gateways, there is no single
26
+ * base URL for the API — look up the gateway you want by name. A service's
27
+ * processes (including its workers) receive only the gateways referenced by
28
+ * its code (`url("api")` from `@encore.dev/sdk/gateways`) and any gateway
29
+ * hosted by the service itself. When no gateways are configured (such as
30
+ * under `encore test`), this is an empty object.
30
31
  */
31
32
  gateways: Record<string, GatewayMeta>;
32
33
 
33
34
  /**
34
- * The frontends of this application this service is given — those its code
35
- * looks up the URL of (`url("web")` from `@encore.dev/sdk/frontends`), and
36
- * the one it hosts — keyed by name, with where each is reached. One the
37
- * environment gives no origins is left out.
35
+ * The frontends visible to this service, keyed by frontend name. Includes
36
+ * frontends referenced by this service's code (`url("web")` from
37
+ * `@encore.dev/sdk/frontends`) and any frontend hosted by the service itself.
38
+ * Frontends with no configured origins in this environment are omitted.
38
39
  */
39
40
  frontends: Record<string, FrontendMeta>;
40
41
 
41
- /** Information about the environment the app is running in. */
42
+ /** Information about the environment the application is running in. */
42
43
  environment: EnvironmentMeta;
43
44
 
44
45
  /** Information about the build. */
@@ -50,37 +51,37 @@ export interface AppMeta {
50
51
 
51
52
  /** Describes an API gateway serving the application. */
52
53
  export interface GatewayMeta {
53
- /** The name of the gateway, as declared by the application. */
54
+ /** The gateway name as declared by the application. */
54
55
  name: string;
55
56
 
56
57
  /**
57
- * The URL the API of this running application is called at through this
58
- * gateway: the first of its origins. Empty when the environment gives the
59
- * gateway no origins.
58
+ * The primary URL at which this gateway is reached (the first entry in
59
+ * `origins`). Empty when no origins are configured for the gateway in this
60
+ * environment.
60
61
  */
61
62
  url: string;
62
63
 
63
64
  /**
64
- * Every origin the gateway is reached at in this environment
65
- * (`scheme://host[:port]`), the first its URL. After the first, an entry may
66
- * be a pattern of one, `https://*.example.com`, or `*`, which makes the
67
- * gateway the one serving requests no other origin matches.
65
+ * All origins at which the gateway is reached in this environment
66
+ * (`scheme://host[:port]`). The first entry is the primary `url`. Subsequent
67
+ * entries may be wildcard patterns (such as `https://*.example.com`) or `*`,
68
+ * which makes this gateway handle requests that no other origin matches.
68
69
  */
69
70
  origins: string[];
70
71
  }
71
72
 
72
- /** Describes a frontend of the application, and where it is reached. */
73
+ /** Describes a frontend of the application and where it is reached. */
73
74
  export interface FrontendMeta {
74
- /** The name of the frontend: for one a service hosts, the service's. */
75
+ /** The frontend name (or the hosting service's name for a service-hosted frontend). */
75
76
  name: string;
76
77
 
77
- /** The URL the frontend is reached at: the first of its origins. */
78
+ /** The primary URL at which the frontend is reached (the first entry in `origins`). */
78
79
  url: string;
79
80
 
80
81
  /**
81
- * Every origin the frontend is reached at in this environment, the first its
82
- * URL; after the first, an entry may be a pattern of one,
83
- * `https://*.example.com`.
82
+ * All origins at which the frontend is reached in this environment. The first
83
+ * entry is the primary `url`; subsequent entries may be wildcard patterns
84
+ * such as `https://*.example.com`.
84
85
  */
85
86
  origins: string[];
86
87
  }
@@ -88,20 +89,20 @@ export interface FrontendMeta {
88
89
  /** Describes the environment the Encore application is running in. */
89
90
  export interface EnvironmentMeta {
90
91
  /**
91
- * The name of environment that this application.
92
- * For local development it is "local".
92
+ * The name of the environment this application is running in.
93
+ * For local development, this is `"local"`.
93
94
  */
94
95
  name: string;
95
96
 
96
97
  /**
97
- * The type of environment is this application running in.
98
- * For local development it is "development".
98
+ * The type of environment this application is running in.
99
+ * For local development, this is `"development"`.
99
100
  */
100
101
  type: EnvironmentType;
101
102
 
102
103
  /**
103
- * The cloud this is running in.
104
- * For local development it is "local".
104
+ * The cloud provider this application is running on.
105
+ * For local development, this is `"local"`.
105
106
  */
106
107
  cloud: CloudProvider;
107
108
  }
@@ -110,22 +111,22 @@ export interface EnvironmentMeta {
110
111
  export type EnvironmentType =
111
112
  // A production environment.
112
113
  | 'production'
113
- // A long-lived cloud-hosted, non-production environment, such as test environments, or local development.
114
+ // A long-lived cloud-hosted non-production environment, or local development.
114
115
  | 'development'
115
- // A short-lived cloud-hosted, non-production environments, such as preview environments
116
+ // A short-lived cloud-hosted non-production environment, such as a preview environment.
116
117
  | 'ephemeral'
117
- // When running automated tests.
118
+ // An automated test environment.
118
119
  | 'test';
119
120
 
120
- /** Describes what cloud provider the application is running in. */
121
+ /** Describes which cloud provider the application is running on. */
121
122
  export type CloudProvider =
122
123
  | 'aws' // Amazon Web Services
123
124
  | 'gcp' // Google Cloud Platform
124
125
  | 'azure' // Microsoft Azure
125
- | 'encore' // Encore Cloud.
126
+ | 'encore' // Encore Cloud
126
127
  | 'local'; // Local development
127
128
 
128
- /** Information about the build that formed the running application. */
129
+ /** Information about the build that produced the running application. */
129
130
  export interface BuildMeta {
130
131
  /** The VCS revision the deployed application was built from. */
131
132
  revision: string;
@@ -133,33 +134,34 @@ export interface BuildMeta {
133
134
 
134
135
  /** Information about the deployment of the running application. */
135
136
  export interface DeployMeta {
136
- /** The unique id of the deployment. Generated by the Encore Platform. */
137
+ /** The unique deployment ID generated by the Encore platform. */
137
138
  id: string;
138
139
 
139
- /** The time the Encore Platform deployed this build to the environment. */
140
+ /** The time the Encore platform deployed this build to the environment. */
140
141
  time: Date;
141
142
 
142
- /** The services hosted by this deployment, keyed by the service name. */
143
+ /** The services hosted by this deployment, keyed by service name. */
143
144
  hostedServices: Record<string, HostedService>;
144
145
 
145
146
  /**
146
- * The Worker of its service this process runs: a long-running process of
147
- * the service that serves no requests, declared in the `workers` section of
148
- * its `encore.service.json`. Undefined for the service's main process.
147
+ * The name of the worker this process is running, if any. A worker is a
148
+ * long-running process belonging to a service that does not serve HTTP
149
+ * requests, declared under `workers` in `encore.service.json`. Undefined for
150
+ * the service's main process.
149
151
  */
150
152
  worker?: string;
151
153
  }
152
154
 
153
155
  export interface HostedService {
154
- /** The name of the service */
156
+ /** The name of the service. */
155
157
  name: string;
156
158
  }
157
159
 
158
160
  /**
159
161
  * Returns metadata about the running Encore application.
160
162
  *
161
- * The metadata is cached and is the same object each call,
162
- * and therefore must not be modified by the caller.
163
+ * The metadata is cached and returns the same object on every call, so callers
164
+ * must not mutate it.
163
165
  */
164
166
  export function appMeta(): AppMeta {
165
167
  // Compute the metadata on first use.
@@ -158,12 +158,16 @@ describe('config', () => {
158
158
  const dir = mkdtempSync(join(tmpdir(), 'encore-config-test-'));
159
159
  const live = join(dir, 'configs.json');
160
160
 
161
- // Each probe is given its own config source, `live` unless told otherwise.
162
- const run = (probe: string, source = live) => {
161
+ // Each probe is given its own config source, `live` unless told otherwise,
162
+ // in a runtime on `cloud`, local unless told otherwise.
163
+ const run = (probe: string, source = live, cloud = CLOUD_LOCAL) => {
163
164
  const proc = Bun.spawnSync({
164
165
  cmd: [process.execPath, '-e', probe],
165
166
  cwd: import.meta.dir,
166
- env: {...process.env, ENCORE_RUNTIME_CONFIG: runtimeConfig(source)},
167
+ env: {
168
+ ...process.env,
169
+ ENCORE_RUNTIME_CONFIG: runtimeConfig(source, cloud),
170
+ },
167
171
  });
168
172
  const stdout = proc.stdout.toString();
169
173
  if (proc.exitCode !== 0) {
@@ -187,8 +191,7 @@ describe('config', () => {
187
191
  const flags = config("flags", { scope: "shared" });
188
192
  const missing = config("nothing");
189
193
  const a = checkout(), b = checkout();
190
- let unset;
191
- try { secret("Unset")(); } catch (e) { unset = e.message; }
194
+ const unset = secret("Unset")();
192
195
  console.log(JSON.stringify({
193
196
  maxItems: a.max_items,
194
197
  timeout: a.timeout instanceof Duration ? a.timeout.seconds : null,
@@ -222,12 +225,34 @@ describe('config', () => {
222
225
  flagKey: 'shared-flag-key',
223
226
  missing: {},
224
227
  name: 'checkout',
225
- // Not set is an error wherever the app runs, locally too.
226
- unset: 'secret Unset is not set',
228
+ // Locally a secret lacks a value until it is set: it reads as empty.
229
+ unset: '',
227
230
  });
228
231
  expect(out[1]).toEqual({changed: 7, timeout: 60, now: 7});
229
232
  });
230
233
 
234
+ test.skipIf(!lib)(
235
+ 'fails a read of an unset secret where the app is not local',
236
+ () => {
237
+ const mod = JSON.stringify(`${import.meta.dir}/mod`);
238
+ const out = run(
239
+ `
240
+ import { secret } from ${mod};
241
+ let unset;
242
+ try { secret("Unset")(); } catch (e) { unset = e.message; }
243
+ console.log(JSON.stringify({ key: secret("FlagKey")(), unset }));
244
+ `,
245
+ live,
246
+ CLOUD_AWS,
247
+ );
248
+ // A deploy gives each service every secret it uses.
249
+ expect(out[0]).toEqual({
250
+ key: 'shared-flag-key',
251
+ unset: 'secret Unset is not set',
252
+ });
253
+ },
254
+ );
255
+
231
256
  test.skipIf(!lib)(
232
257
  'calls a listener once with the latest of rapid changes',
233
258
  () => {
@@ -292,12 +317,16 @@ describe('config', () => {
292
317
  );
293
318
  });
294
319
 
320
+ /** `encore.runtime.v1.Environment.Cloud`'s values the tests run on. */
321
+ const CLOUD_LOCAL = 1;
322
+ const CLOUD_AWS = 3;
323
+
295
324
  /**
296
- * A serialized `encore.runtime.v1.RuntimeConfig` hosting service `orders`,
297
- * with two configs, the secrets their fields read, and `live` as the config
298
- * source. Hand-encoded, as in app_meta.test.ts.
325
+ * A serialized `encore.runtime.v1.RuntimeConfig` hosting service `orders` on
326
+ * `cloud`, with two configs, the secrets their fields read, and `live` as the
327
+ * config source. Hand-encoded, as in app_meta.test.ts.
299
328
  */
300
- function runtimeConfig(live: string): string {
329
+ function runtimeConfig(live: string, cloud: number): string {
301
330
  const varint = (n: number): number[] => {
302
331
  const out: number[] = [];
303
332
  for (;;) {
@@ -377,8 +406,13 @@ function runtimeConfig(live: string): string {
377
406
  const infra = msg(1, resources);
378
407
  // Deployment{deploy_id=1, hosted_services=5}
379
408
  const deployment = [...str(1, 'deploy-1'), ...msg(5, str(1, 'orders'))];
380
- // Environment{app_id=1, env_name=4}
381
- const environment = [...str(1, 'app'), ...str(4, 'local')];
409
+ // Environment{app_id=1, env_name=4, cloud=6}
410
+ const environment = [
411
+ ...str(1, 'app'),
412
+ ...str(4, 'local'),
413
+ ...tag(6, 0),
414
+ ...varint(cloud),
415
+ ];
382
416
  const cfg = [...msg(1, environment), ...msg(2, infra), ...msg(3, deployment)];
383
417
  return Buffer.from(Uint8Array.from(cfg)).toString('base64');
384
418
  }