@distilled.cloud/core 1.0.0-rc.17 → 1.0.0-rc.18

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 (259) hide show
  1. package/lib/_bundle/base.js +2 -2
  2. package/lib/_bundle/base.js.map +1 -1
  3. package/lib/_bundle/graphql.js +2 -2
  4. package/lib/_bundle/graphql.js.map +1 -1
  5. package/lib/_bundle/rest.js +1 -1
  6. package/lib/_bundle/rest.js.map +1 -1
  7. package/lib/annotations.d.ts +15 -0
  8. package/lib/annotations.d.ts.map +1 -0
  9. package/lib/annotations.js +2 -0
  10. package/lib/annotations.js.map +1 -0
  11. package/lib/api.d.ts +15 -0
  12. package/lib/api.d.ts.map +1 -1
  13. package/lib/api.js +1 -1
  14. package/lib/category.d.ts.map +1 -1
  15. package/lib/config.d.ts +54 -13
  16. package/lib/config.d.ts.map +1 -1
  17. package/lib/config.js +1 -1
  18. package/lib/debug.d.ts.map +1 -1
  19. package/lib/error-category.d.ts.map +1 -1
  20. package/lib/errors.d.ts +2 -13
  21. package/lib/errors.d.ts.map +1 -1
  22. package/lib/errors.js +1 -1
  23. package/lib/graphql.d.ts +14 -0
  24. package/lib/graphql.d.ts.map +1 -1
  25. package/lib/index.d.ts +3 -2
  26. package/lib/index.d.ts.map +1 -1
  27. package/lib/index.js +1 -0
  28. package/lib/pagination.d.ts +34 -2
  29. package/lib/pagination.d.ts.map +1 -1
  30. package/lib/pagination.js +1 -1
  31. package/lib/protocol-http.d.ts +30 -6
  32. package/lib/protocol-http.d.ts.map +1 -1
  33. package/lib/protocol-http.js +1 -1
  34. package/lib/protocol-rest.d.ts +53 -39
  35. package/lib/protocol-rest.d.ts.map +1 -1
  36. package/lib/protocol-rest.js +1 -1
  37. package/lib/response-validation.d.ts +4 -3
  38. package/lib/response-validation.d.ts.map +1 -1
  39. package/lib/schema-lite-typed.js +1 -2
  40. package/lib/telemetry-debug.d.ts +14 -0
  41. package/lib/telemetry-debug.d.ts.map +1 -0
  42. package/lib/telemetry-debug.js +2 -0
  43. package/lib/telemetry-debug.js.map +1 -0
  44. package/lib/telemetry-hooks.d.ts +32 -0
  45. package/lib/telemetry-hooks.d.ts.map +1 -0
  46. package/lib/telemetry-hooks.js +2 -0
  47. package/lib/telemetry-hooks.js.map +1 -0
  48. package/lib/telemetry-host-rules.d.ts +23 -0
  49. package/lib/telemetry-host-rules.d.ts.map +1 -0
  50. package/lib/telemetry-host-rules.js +2 -0
  51. package/lib/telemetry-host-rules.js.map +1 -0
  52. package/lib/telemetry-lambda-context.d.ts +17 -0
  53. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  54. package/lib/telemetry-lambda-context.js +2 -0
  55. package/lib/telemetry-lambda-context.js.map +1 -0
  56. package/lib/telemetry-message-context.d.ts +52 -0
  57. package/lib/telemetry-message-context.d.ts.map +1 -0
  58. package/lib/telemetry-message-context.js +2 -0
  59. package/lib/telemetry-message-context.js.map +1 -0
  60. package/lib/telemetry-metrics.d.ts +6 -0
  61. package/lib/telemetry-metrics.d.ts.map +1 -0
  62. package/lib/telemetry-metrics.js +2 -0
  63. package/lib/telemetry-metrics.js.map +1 -0
  64. package/lib/telemetry-name-template.d.ts +13 -0
  65. package/lib/telemetry-name-template.d.ts.map +1 -0
  66. package/lib/telemetry-name-template.js +2 -0
  67. package/lib/telemetry-name-template.js.map +1 -0
  68. package/lib/telemetry-stream.d.ts +9 -0
  69. package/lib/telemetry-stream.d.ts.map +1 -0
  70. package/lib/telemetry-stream.js +2 -0
  71. package/lib/telemetry-stream.js.map +1 -0
  72. package/lib/telemetry-xray.d.ts +28 -0
  73. package/lib/telemetry-xray.d.ts.map +1 -0
  74. package/lib/telemetry-xray.js +2 -0
  75. package/lib/telemetry-xray.js.map +1 -0
  76. package/lib/telemetry.d.ts +269 -0
  77. package/lib/telemetry.d.ts.map +1 -0
  78. package/lib/telemetry.js +3 -0
  79. package/lib/telemetry.js.map +1 -0
  80. package/package.json +1 -3
  81. package/src/annotations.ts +37 -0
  82. package/src/api.ts +123 -24
  83. package/src/category.ts +21 -22
  84. package/src/config.ts +58 -29
  85. package/src/debug.ts +9 -6
  86. package/src/error-category.ts +12 -14
  87. package/src/errors.ts +7 -7
  88. package/src/graphql.ts +123 -18
  89. package/src/index.ts +3 -2
  90. package/src/pagination.ts +119 -6
  91. package/src/protocol-http.ts +63 -43
  92. package/src/protocol-rest.ts +201 -140
  93. package/src/response-validation.ts +4 -3
  94. package/src/telemetry-debug.ts +135 -0
  95. package/src/telemetry-hooks.ts +33 -0
  96. package/src/telemetry-host-rules.ts +39 -0
  97. package/src/telemetry-lambda-context.ts +46 -0
  98. package/src/telemetry-message-context.ts +170 -0
  99. package/src/telemetry-metrics.ts +69 -0
  100. package/src/telemetry-name-template.ts +26 -0
  101. package/src/telemetry-stream.ts +91 -0
  102. package/src/telemetry-xray.ts +66 -0
  103. package/src/telemetry.ts +768 -0
  104. package/lib/codegen/boolean-string-enums.d.ts +0 -36
  105. package/lib/codegen/boolean-string-enums.d.ts.map +0 -1
  106. package/lib/codegen/boolean-string-enums.js +0 -147
  107. package/lib/codegen/boolean-string-enums.js.map +0 -1
  108. package/lib/codegen/chunk.d.ts +0 -7
  109. package/lib/codegen/chunk.d.ts.map +0 -1
  110. package/lib/codegen/chunk.js +0 -139
  111. package/lib/codegen/chunk.js.map +0 -1
  112. package/lib/codegen/cli.d.ts +0 -80
  113. package/lib/codegen/cli.d.ts.map +0 -1
  114. package/lib/codegen/cli.js +0 -166
  115. package/lib/codegen/cli.js.map +0 -1
  116. package/lib/codegen/datafy.d.ts +0 -14
  117. package/lib/codegen/datafy.d.ts.map +0 -1
  118. package/lib/codegen/datafy.js +0 -853
  119. package/lib/codegen/datafy.js.map +0 -1
  120. package/lib/codegen/dedupe.d.ts +0 -5
  121. package/lib/codegen/dedupe.d.ts.map +0 -1
  122. package/lib/codegen/dedupe.js +0 -153
  123. package/lib/codegen/dedupe.js.map +0 -1
  124. package/lib/codegen/emit.d.ts +0 -125
  125. package/lib/codegen/emit.d.ts.map +0 -1
  126. package/lib/codegen/emit.js +0 -99
  127. package/lib/codegen/emit.js.map +0 -1
  128. package/lib/codegen/format.d.ts +0 -11
  129. package/lib/codegen/format.d.ts.map +0 -1
  130. package/lib/codegen/format.js +0 -32
  131. package/lib/codegen/format.js.map +0 -1
  132. package/lib/codegen/generated-at.d.ts +0 -29
  133. package/lib/codegen/generated-at.d.ts.map +0 -1
  134. package/lib/codegen/generated-at.js +0 -78
  135. package/lib/codegen/generated-at.js.map +0 -1
  136. package/lib/codegen/generator.d.ts +0 -353
  137. package/lib/codegen/generator.d.ts.map +0 -1
  138. package/lib/codegen/generator.js +0 -810
  139. package/lib/codegen/generator.js.map +0 -1
  140. package/lib/codegen/graph.d.ts +0 -36
  141. package/lib/codegen/graph.d.ts.map +0 -1
  142. package/lib/codegen/graph.js +0 -136
  143. package/lib/codegen/graph.js.map +0 -1
  144. package/lib/codegen/graphql-client.d.ts +0 -70
  145. package/lib/codegen/graphql-client.d.ts.map +0 -1
  146. package/lib/codegen/graphql-client.js +0 -439
  147. package/lib/codegen/graphql-client.js.map +0 -1
  148. package/lib/codegen/graphql.d.ts +0 -207
  149. package/lib/codegen/graphql.d.ts.map +0 -1
  150. package/lib/codegen/graphql.js +0 -786
  151. package/lib/codegen/graphql.js.map +0 -1
  152. package/lib/codegen/latin1.d.ts +0 -3
  153. package/lib/codegen/latin1.d.ts.map +0 -1
  154. package/lib/codegen/latin1.js +0 -126
  155. package/lib/codegen/latin1.js.map +0 -1
  156. package/lib/codegen/members.d.ts +0 -32
  157. package/lib/codegen/members.d.ts.map +0 -1
  158. package/lib/codegen/members.js +0 -62
  159. package/lib/codegen/members.js.map +0 -1
  160. package/lib/codegen/model-diff.d.ts +0 -10
  161. package/lib/codegen/model-diff.d.ts.map +0 -1
  162. package/lib/codegen/model-diff.js +0 -67
  163. package/lib/codegen/model-diff.js.map +0 -1
  164. package/lib/codegen/naming.d.ts +0 -29
  165. package/lib/codegen/naming.d.ts.map +0 -1
  166. package/lib/codegen/naming.js +0 -74
  167. package/lib/codegen/naming.js.map +0 -1
  168. package/lib/codegen/openapi-cli.d.ts +0 -52
  169. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  170. package/lib/codegen/openapi-cli.js +0 -84
  171. package/lib/codegen/openapi-cli.js.map +0 -1
  172. package/lib/codegen/openapi.d.ts +0 -209
  173. package/lib/codegen/openapi.d.ts.map +0 -1
  174. package/lib/codegen/openapi.js +0 -1548
  175. package/lib/codegen/openapi.js.map +0 -1
  176. package/lib/codegen/operations.d.ts +0 -24
  177. package/lib/codegen/operations.d.ts.map +0 -1
  178. package/lib/codegen/operations.js +0 -56
  179. package/lib/codegen/operations.js.map +0 -1
  180. package/lib/codegen/pagination.d.ts +0 -39
  181. package/lib/codegen/pagination.d.ts.map +0 -1
  182. package/lib/codegen/pagination.js +0 -31
  183. package/lib/codegen/pagination.js.map +0 -1
  184. package/lib/codegen/patch-audit.d.ts +0 -84
  185. package/lib/codegen/patch-audit.d.ts.map +0 -1
  186. package/lib/codegen/patch-audit.js +0 -366
  187. package/lib/codegen/patch-audit.js.map +0 -1
  188. package/lib/codegen/patches.d.ts +0 -129
  189. package/lib/codegen/patches.d.ts.map +0 -1
  190. package/lib/codegen/patches.js +0 -472
  191. package/lib/codegen/patches.js.map +0 -1
  192. package/lib/codegen/prelude.d.ts +0 -15
  193. package/lib/codegen/prelude.d.ts.map +0 -1
  194. package/lib/codegen/prelude.js +0 -60
  195. package/lib/codegen/prelude.js.map +0 -1
  196. package/lib/codegen/privatize.d.ts +0 -21
  197. package/lib/codegen/privatize.d.ts.map +0 -1
  198. package/lib/codegen/privatize.js +0 -176
  199. package/lib/codegen/privatize.js.map +0 -1
  200. package/lib/codegen/proto.d.ts +0 -121
  201. package/lib/codegen/proto.d.ts.map +0 -1
  202. package/lib/codegen/proto.js +0 -960
  203. package/lib/codegen/proto.js.map +0 -1
  204. package/lib/codegen/pure.d.ts +0 -6
  205. package/lib/codegen/pure.d.ts.map +0 -1
  206. package/lib/codegen/pure.js +0 -91
  207. package/lib/codegen/pure.js.map +0 -1
  208. package/lib/codegen/rewrite-operation-ids.d.ts +0 -154
  209. package/lib/codegen/rewrite-operation-ids.d.ts.map +0 -1
  210. package/lib/codegen/rewrite-operation-ids.js +0 -1117
  211. package/lib/codegen/rewrite-operation-ids.js.map +0 -1
  212. package/lib/codegen/spec-path.d.ts +0 -16
  213. package/lib/codegen/spec-path.d.ts.map +0 -1
  214. package/lib/codegen/spec-path.js +0 -101
  215. package/lib/codegen/spec-path.js.map +0 -1
  216. package/lib/codegen/table.d.ts +0 -5
  217. package/lib/codegen/table.d.ts.map +0 -1
  218. package/lib/codegen/table.js +0 -249
  219. package/lib/codegen/table.js.map +0 -1
  220. package/lib/json-patch.d.ts +0 -58
  221. package/lib/json-patch.d.ts.map +0 -1
  222. package/lib/json-patch.js +0 -2
  223. package/lib/json-patch.js.map +0 -1
  224. package/lib/schema-lite-typed.js.map +0 -1
  225. package/lib/testing.d.ts +0 -40
  226. package/lib/testing.d.ts.map +0 -1
  227. package/lib/testing.js +0 -2
  228. package/lib/testing.js.map +0 -1
  229. package/src/codegen/boolean-string-enums.ts +0 -155
  230. package/src/codegen/chunk.ts +0 -147
  231. package/src/codegen/cli.ts +0 -293
  232. package/src/codegen/datafy.ts +0 -874
  233. package/src/codegen/dedupe.ts +0 -173
  234. package/src/codegen/emit.ts +0 -200
  235. package/src/codegen/format.ts +0 -49
  236. package/src/codegen/generated-at.ts +0 -88
  237. package/src/codegen/generator.ts +0 -1229
  238. package/src/codegen/graph.ts +0 -151
  239. package/src/codegen/graphql-client.ts +0 -545
  240. package/src/codegen/graphql.ts +0 -1145
  241. package/src/codegen/latin1.ts +0 -131
  242. package/src/codegen/members.ts +0 -79
  243. package/src/codegen/model-diff.ts +0 -67
  244. package/src/codegen/naming.ts +0 -85
  245. package/src/codegen/openapi-cli.ts +0 -141
  246. package/src/codegen/openapi.ts +0 -1845
  247. package/src/codegen/operations.ts +0 -73
  248. package/src/codegen/pagination.ts +0 -64
  249. package/src/codegen/patch-audit.ts +0 -480
  250. package/src/codegen/patches.ts +0 -581
  251. package/src/codegen/prelude.ts +0 -70
  252. package/src/codegen/privatize.ts +0 -200
  253. package/src/codegen/proto.ts +0 -1092
  254. package/src/codegen/pure.ts +0 -94
  255. package/src/codegen/rewrite-operation-ids.ts +0 -1219
  256. package/src/codegen/spec-path.ts +0 -112
  257. package/src/codegen/table.ts +0 -254
  258. package/src/json-patch.ts +0 -273
  259. package/src/testing.ts +0 -74
@@ -1,3 +1,31 @@
1
+ import * as Context from "effect/Context";
2
+ import * as Effect from "effect/Effect";
3
+ import * as HttpClient from "effect/http/HttpClient";
4
+ import type * as HttpClientRequest from "effect/http/HttpClientRequest";
5
+ import type * as HttpClientResponse from "effect/http/HttpClientResponse";
6
+ import * as Layer from "effect/Layer";
7
+ import * as Redacted from "effect/Redacted";
8
+ import type * as AST from "effect/SchemaAST";
9
+ import { rawResponseRootSymbol } from "./annotations.ts";
10
+ import * as API from "./api.ts";
11
+ import { debugHttp } from "./debug.ts";
12
+ import { HTTP_STATUS_MAP, InternalServerError } from "./errors.ts";
13
+ import { recordPageHeaders } from "./pagination.ts";
14
+ import { isOpaqueValue, unwrapRedactedDeep } from "./plain-values.ts";
15
+ import {
16
+ buildRequest,
17
+ getAnn,
18
+ getProps,
19
+ mapKeys,
20
+ mapsVerbatim,
21
+ matchTypedError,
22
+ resolveNode,
23
+ responseHeaderMembers,
24
+ withResponseHeaders,
25
+ type ResponseHeaderMember,
26
+ } from "./protocol-http.ts";
27
+ import { checkResponse, withholdActual } from "./response-validation.ts";
28
+ import { parseRetryAfterForStatus } from "./retry-after.ts";
1
29
  /**
2
30
  * Generic REST protocol factory for simple bearer/header-auth JSON APIs
3
31
  * (Neon, Fly.io, PlanetScale, Supabase, Turso, ...).
@@ -25,33 +53,7 @@
25
53
  * Anything provider-specific (envelope quirks, bespoke error codes) belongs
26
54
  * in the provider package -- via these options or a hand-written protocol.
27
55
  */
28
- import * as Context from "effect/Context";
29
- import * as Effect from "effect/Effect";
30
- import * as HttpClient from "effect/http/HttpClient";
31
- import type * as HttpClientRequest from "effect/http/HttpClientRequest";
32
- import type * as HttpClientResponse from "effect/http/HttpClientResponse";
33
- import * as Layer from "effect/Layer";
34
- import * as Redacted from "effect/Redacted";
35
- import type * as AST from "effect/SchemaAST";
36
- import * as API from "./api.ts";
37
- import { debugHttp } from "./debug.ts";
38
- import { HTTP_STATUS_MAP, InternalServerError } from "./errors.ts";
39
- import { isOpaqueValue, unwrapRedactedDeep } from "./plain-values.ts";
40
- import {
41
- buildRequest,
42
- getAnn,
43
- getPropAnn,
44
- getProps,
45
- mapKeys,
46
- mapsVerbatim,
47
- matchTypedError,
48
- resolveNode,
49
- responseHeaderMembers,
50
- withResponseHeaders,
51
- type ResponseHeaderMember,
52
- } from "./protocol-http.ts";
53
- import { checkResponse, withholdActual } from "./response-validation.ts";
54
- import { parseRetryAfterForStatus } from "./retry-after.ts";
56
+ import * as Telemetry from "./telemetry.ts";
55
57
  import { httpSymbol, makeAnnotation, type HttpTrait } from "./trait.ts";
56
58
 
57
59
  // =============================================================================
@@ -62,8 +64,9 @@ export const sensitiveValueSymbol = /*@__PURE__*/ Symbol.for(
62
64
  "@distilled.cloud/core/sensitive-value",
63
65
  );
64
66
  /**
65
- * Marks a string member as sensitive (mirrors `smithy.api#sensitive`).
66
- * The REST protocol wraps decoded values in `Redacted` on the way out and
67
+ * Marks a string member, map value or list element as sensitive (mirrors
68
+ * `smithy.api#sensitive`). The REST protocol wraps decoded values in
69
+ * `Redacted` on the way out (an untyped `S.Unknown` value whole) and
67
70
  * accepts `string | Redacted<string>` on the way in (unwrapped before
68
71
  * serialization). Takes an ignored argument so generators can inline the
69
72
  * smithy trait value (`T.SensitiveValue({})`).
@@ -77,15 +80,13 @@ export const rawResponseSymbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/core
77
80
  */
78
81
  export const RawResponse = (_value?: unknown) => makeAnnotation(rawResponseSymbol, true);
79
82
 
80
- export const rawResponseRootSymbol = /*@__PURE__*/ Symbol.for(
81
- "@distilled.cloud/core/raw-response-root",
82
- );
83
83
  /**
84
84
  * Marks a response schema whose ENTIRE value is the response body (the
85
85
  * generator's `rootPipe` for synthesized bare-payload wrappers): the emitted
86
86
  * response type IS the payload type and the protocol returns the mapped body
87
87
  * directly.
88
88
  */
89
+ export { rawResponseRootSymbol };
89
90
  export const RawResponseRoot = () => makeAnnotation(rawResponseRootSymbol, true);
90
91
 
91
92
  export const binaryResponseSymbol = /*@__PURE__*/ Symbol.for(
@@ -102,41 +103,77 @@ export const BinaryResponse = () => makeAnnotation(binaryResponseSymbol, true);
102
103
  export { unwrapRedactedDeep };
103
104
 
104
105
  /**
105
- * Walk a decoded (TS-named) value alongside its schema AST, wrapping members
106
- * marked {@link SensitiveValue} in `Redacted`. Keys the schema doesn't model
107
- * pass through verbatim.
106
+ * A sensitive value that {@link wrapSensitive} wraps: a string, or any
107
+ * non-null value of an untyped (`S.Unknown`) schema, such as a JSON scalar or
108
+ * object. A typed struct is walked so its own sensitive members are wrapped
109
+ * and its type stays accurate.
108
110
  */
109
- export const wrapSensitive = (ast: AST.AST, value: unknown): unknown => {
110
- if (value === null || typeof value !== "object" || isOpaqueValue(value)) {
111
+ const isSecretValue = (type: AST.AST, v: unknown): boolean =>
112
+ typeof v === "string" || (v !== null && resolveNode(type)._tag === "Unknown");
113
+
114
+ /**
115
+ * Walk a decoded (TS-named) value alongside its schema AST, wrapping values
116
+ * marked {@link SensitiveValue} (members, map values, list elements) in
117
+ * `Redacted`. Keys the schema doesn't model pass through. A union applies
118
+ * every arm in turn; a map arm skips keys a sibling arm names.
119
+ */
120
+ export const wrapSensitive = (
121
+ ast: AST.AST,
122
+ value: unknown,
123
+ siblingNames?: ReadonlySet<string>,
124
+ ): unknown => {
125
+ if (
126
+ value === null ||
127
+ typeof value !== "object" ||
128
+ isOpaqueValue(value) ||
129
+ Redacted.isRedacted(value)
130
+ ) {
111
131
  return value;
112
132
  }
113
133
  const node = resolveNode(ast);
114
134
  if (node._tag === "Union") {
115
135
  // Redact every possible sensitive member, including in partial responses.
116
- return node.types.reduce<unknown>((redacted, arm) => wrapSensitive(arm, redacted), value);
136
+ const named = new Set(
137
+ node.types.flatMap((arm) => {
138
+ const armNode = resolveNode(arm);
139
+ return armNode._tag === "Objects" ? getProps(armNode).map((p) => String(p.name)) : [];
140
+ }),
141
+ );
142
+ return node.types.reduce<unknown>(
143
+ (redacted, arm) => wrapSensitive(arm, redacted, named),
144
+ value,
145
+ );
117
146
  }
118
147
  if (node._tag === "Arrays") {
119
148
  if (!Array.isArray(value)) return value;
120
149
  const elem = (node as any).rest?.[0] as AST.AST | undefined;
121
- return elem ? value.map((v) => wrapSensitive(elem, v)) : value;
150
+ if (!elem) return value;
151
+ const sensitive = getAnn(elem, sensitiveValueSymbol) !== undefined;
152
+ return value.map((v) =>
153
+ sensitive && isSecretValue(elem, v) && !Redacted.isRedacted(v)
154
+ ? Redacted.make(v)
155
+ : wrapSensitive(elem, v),
156
+ );
122
157
  }
123
158
  if (node._tag === "Objects" && !Array.isArray(value)) {
124
159
  const props = getProps(node);
125
- if (props.length === 0) return value;
160
+ const mapValue = node.indexSignatures[0]?.type;
161
+ if (props.length === 0 && mapValue === undefined) return value;
126
162
  const byName = new Map(props.map((p) => [String(p.name), p]));
127
- const out: Record<string, unknown> = {};
128
- for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
129
- if (v === undefined) continue;
130
- const prop = byName.get(k);
131
- if (!prop) {
132
- out[k] = v;
133
- } else if (getPropAnn(prop, sensitiveValueSymbol) !== undefined && typeof v === "string") {
134
- out[k] = Redacted.make(v);
135
- } else {
136
- out[k] = wrapSensitive(prop.type, v);
137
- }
138
- }
139
- return out;
163
+ // fromEntries keeps a `__proto__` key an entry instead of the prototype.
164
+ return Object.fromEntries(
165
+ Object.entries(value as Record<string, unknown>).flatMap<[string, unknown]>(([k, v]) => {
166
+ if (v === undefined) return [];
167
+ const prop = byName.get(k);
168
+ const type = prop?.type ?? (siblingNames?.has(k) ? undefined : mapValue);
169
+ if (type === undefined) return [[k, v]];
170
+ // Union arms run over each other's output: keep a value one already wrapped.
171
+ if (getAnn(type, sensitiveValueSymbol) !== undefined && isSecretValue(type, v)) {
172
+ return [[k, Redacted.isRedacted(v) ? v : Redacted.make(v)]];
173
+ }
174
+ return [[k, wrapSensitive(type, v)]];
175
+ }),
176
+ );
140
177
  }
141
178
  return value;
142
179
  };
@@ -144,9 +181,10 @@ export const wrapSensitive = (ast: AST.AST, value: unknown): unknown => {
144
181
  const sensitiveOutputs = /*@__PURE__*/ new WeakMap<AST.AST, boolean>();
145
182
 
146
183
  /**
147
- * Whether any member reachable from `ast` is marked {@link SensitiveValue}.
148
- * Parse errors for such an output withhold the response body (see
149
- * {@link RestParseErrorInfo}); hand-written protocols use this to do the same.
184
+ * Whether any member, map value or list element reachable from `ast` is
185
+ * marked {@link SensitiveValue}. Such an output is decoded through
186
+ * {@link wrapSensitive}, and its parse errors withhold the response body (see
187
+ * {@link checkSuccess}, which every REST-style protocol's success path uses).
150
188
  */
151
189
  export const hasSensitiveMember = (ast: AST.AST): boolean => {
152
190
  const cached = sensitiveOutputs.get(ast);
@@ -278,45 +316,80 @@ const defaultErrorEnvelope = (body: unknown): RestErrorEnvelope | undefined => {
278
316
  // here; the generated operation annotations reintroduce it for callers.
279
317
  const fail = (e: unknown): Effect.Effect<never> => Effect.fail(e) as Effect.Effect<never>;
280
318
 
281
- /** Whether {@link wrapSensitive} can change any value of `root`. Cached per schema. */
282
- export const hasSensitive = (root: AST.AST): boolean => {
283
- let result = sensitiveCache.get(root);
284
- if (result !== undefined) return result;
285
- result = false;
286
- const seen = new Set<AST.AST>();
287
- const stack: AST.AST[] = [root];
288
- walk: while (stack.length > 0) {
289
- const ast = stack.pop()!;
290
- if (seen.has(ast)) continue;
291
- seen.add(ast);
292
- const node = resolveNode(ast);
293
- if (node._tag === "Union") {
294
- for (const t of (node as AST.Union).types) stack.push(t);
295
- } else if (node._tag === "Arrays") {
296
- const elem = (node as any).rest?.[0] as AST.AST | undefined;
297
- if (elem) stack.push(elem);
298
- } else if (node._tag === "Objects") {
299
- for (const p of getProps(node)) {
300
- if (getPropAnn(p, sensitiveValueSymbol) !== undefined) {
301
- result = true;
302
- break walk;
303
- }
304
- stack.push(p.type);
305
- }
306
- }
319
+ // =============================================================================
320
+ // 2xx bodies
321
+ // =============================================================================
322
+
323
+ /** A 2xx body a protocol read, for {@link checkSuccess}. */
324
+ export interface SuccessBody {
325
+ /** The value to check and return: the body mapped onto the output's TS names. */
326
+ readonly value: unknown;
327
+ /** What a parse error reports as `body` for an output without sensitive members. */
328
+ readonly body: unknown;
329
+ /** Whether the body was not JSON. */
330
+ readonly nonJson: boolean;
331
+ }
332
+
333
+ /** The outcome of {@link checkSuccess}: the value, or the parse error's fields. */
334
+ export type SuccessCheck =
335
+ | { readonly ok: true; readonly value: unknown }
336
+ | { readonly ok: false; readonly error: RestParseErrorInfo };
337
+
338
+ /**
339
+ * Check a 2xx body against the operation's output schema and deliver its
340
+ * sensitive values as `Redacted`. Every REST-style protocol ends its success
341
+ * path here, so all of them treat a body that can hold a secret alike:
342
+ *
343
+ * - The checked value comes back through {@link wrapSensitive}.
344
+ * - A mismatch (validating modes, see `core/response-validation`) reports
345
+ * `read.body` and the schema error.
346
+ * - For an output with sensitive members ({@link hasSensitiveMember}), a
347
+ * non-JSON body fails in every mode with `"Invalid JSON response"`, and a
348
+ * mismatch reports `body: "[REDACTED]"` and the schema error without the
349
+ * value it found (`withholdActual`).
350
+ *
351
+ * Synchronous, for protocols that already hold the calling fiber's context;
352
+ * {@link validateSuccess} is the `Effect` form.
353
+ */
354
+ export const checkSuccess = (
355
+ context: Context.Context<any>,
356
+ outputAst: AST.AST,
357
+ read: SuccessBody,
358
+ ): SuccessCheck => {
359
+ const sensitive = hasSensitiveMember(outputAst);
360
+ if (read.nonJson && sensitive) {
361
+ return { ok: false, error: { body: "[REDACTED]", cause: "Invalid JSON response" } };
307
362
  }
308
- sensitiveCache.set(root, result);
309
- return result;
363
+ const invalid = checkResponse(context, outputAst, read.value);
364
+ if (invalid !== undefined) {
365
+ return {
366
+ ok: false,
367
+ error: sensitive
368
+ ? { body: "[REDACTED]", cause: withholdActual(invalid) }
369
+ : { body: read.body, cause: invalid },
370
+ };
371
+ }
372
+ return { ok: true, value: sensitive ? wrapSensitive(outputAst, read.value) : read.value };
310
373
  };
311
- const sensitiveCache = /*@__PURE__*/ new WeakMap<AST.AST, boolean>();
374
+
375
+ /**
376
+ * {@link checkSuccess} on the calling fiber, failing with `parseError` (the
377
+ * SDK's `<Sdk>ParseError`) built from the withheld-or-not fields.
378
+ */
379
+ export const validateSuccess = <E>(
380
+ outputAst: AST.AST,
381
+ read: SuccessBody,
382
+ parseError: (info: RestParseErrorInfo) => E,
383
+ ): Effect.Effect<unknown, E> =>
384
+ Effect.withFiber((fiber) => {
385
+ const checked = checkSuccess(fiber.context as Context.Context<any>, outputAst, read);
386
+ return checked.ok ? Effect.succeed(checked.value) : Effect.fail(parseError(checked.error));
387
+ });
312
388
 
313
389
  /** Per-operation decode facts, read from the output schema once. */
314
390
  interface DecodePlan {
315
391
  readonly binary: boolean;
316
392
  readonly verbatim: boolean;
317
- readonly sensitive: boolean;
318
- /** Parse errors withhold the body (see {@link hasSensitiveMember}). */
319
- readonly withholdBody: boolean;
320
393
  /** Members read from response headers (`T.Header`). */
321
394
  readonly headers: ReadonlyArray<ResponseHeaderMember>;
322
395
  }
@@ -328,8 +401,6 @@ const decodePlanFor = (outputAst: AST.AST): DecodePlan => {
328
401
  plan = {
329
402
  binary: getAnn(outputAst, binaryResponseSymbol) !== undefined,
330
403
  verbatim: mapsVerbatim(outputAst, "decode"),
331
- sensitive: hasSensitive(outputAst),
332
- withholdBody: hasSensitiveMember(outputAst),
333
404
  headers: responseHeaderMembers(outputAst),
334
405
  };
335
406
  decodePlans.set(outputAst, plan);
@@ -369,12 +440,15 @@ export const makeRestProtocol = <C>(options: RestProtocolOptions<C>): Layer.Laye
369
440
  f,
370
441
  );
371
442
 
372
- /** The request, or the error a refusing `baseUrl` threw. */
443
+ /**
444
+ * The request; fails with the error a refusing `baseUrl` threw, or with
445
+ * `InvalidInput` for a label that would address another resource.
446
+ */
373
447
  const requestFor = (
374
448
  creds: C,
375
449
  input: unknown,
376
450
  inputAst: AST.AST,
377
- ): HttpClientRequest.HttpClientRequest | { readonly refused: unknown } => {
451
+ ): Effect.Effect<HttpClientRequest.HttpClientRequest> => {
378
452
  const http = getAnn(inputAst, httpSymbol) as HttpTrait | undefined;
379
453
  let baseUrl: string;
380
454
  try {
@@ -386,7 +460,7 @@ export const makeRestProtocol = <C>(options: RestProtocolOptions<C>): Layer.Laye
386
460
  // A baseUrl that refuses the route (missing scope in the
387
461
  // credentials) fails the call with that error, typed for callers by
388
462
  // the operation's declared error channel.
389
- return { refused: e };
463
+ return fail(e);
390
464
  }
391
465
  return buildRequest({
392
466
  input: unwrapRedactedDeep(input),
@@ -395,7 +469,7 @@ export const makeRestProtocol = <C>(options: RestProtocolOptions<C>): Layer.Laye
395
469
  headers: options.headers(creds),
396
470
  mapMemberHeader: options.mapMemberHeader,
397
471
  unknownKeyToWire: options.unknownKeyToWire,
398
- });
472
+ }) as Effect.Effect<HttpClientRequest.HttpClientRequest>;
399
473
  };
400
474
 
401
475
  /** Map a read response body to the call's outcome. */
@@ -486,30 +560,18 @@ export const makeRestProtocol = <C>(options: RestProtocolOptions<C>): Layer.Laye
486
560
  // with sensitive members, a non-JSON body fails in every mode and parse
487
561
  // errors withhold the body.
488
562
  const plan = decodePlanFor(outputAst);
489
- if (nonJson && plan.withholdBody) {
490
- return {
491
- ok: false,
492
- error: options.parseError({ body: "[REDACTED]", cause: "Invalid JSON response" }),
493
- };
494
- }
495
563
  let body: unknown = nonJson ? text : (json ?? {});
496
564
  if (options.transformResponse) body = options.transformResponse(body);
497
- const mapped = withResponseHeaders(
498
- plan.headers,
499
- plan.verbatim ? body : mapKeys(outputAst, body, "decode"),
500
- headers,
501
- );
502
- const invalid = checkResponse(context, outputAst, mapped);
503
- if (invalid !== undefined) {
504
- return {
505
- ok: false,
506
- error: options.parseError({
507
- body: plan.withholdBody ? "[REDACTED]" : nonJson ? text : json,
508
- cause: plan.withholdBody ? withholdActual(invalid) : invalid,
509
- }),
510
- };
511
- }
512
- return { ok: true, value: plan.sensitive ? wrapSensitive(outputAst, mapped) : mapped };
565
+ const checked = checkSuccess(context, outputAst, {
566
+ value: withResponseHeaders(
567
+ plan.headers,
568
+ plan.verbatim ? body : mapKeys(outputAst, body, "decode"),
569
+ headers,
570
+ ),
571
+ body: nonJson ? text : json,
572
+ nonJson,
573
+ });
574
+ return checked.ok ? checked : { ok: false, error: options.parseError(checked.error) };
513
575
  };
514
576
 
515
577
  const decodeResponse = (
@@ -518,32 +580,32 @@ export const makeRestProtocol = <C>(options: RestProtocolOptions<C>): Layer.Laye
518
580
  outputAst: AST.AST,
519
581
  errorClasses: ReadonlyArray<unknown>,
520
582
  ): Effect.Effect<unknown> =>
521
- response.status >= 200 && response.status < 300 && decodePlanFor(outputAst).binary
522
- ? Effect.map(Effect.orDie(response.arrayBuffer), (bytes) => new Uint8Array(bytes))
523
- : Effect.matchEffect(response.text, {
524
- onFailure: Effect.die,
525
- onSuccess: (text) => {
526
- const decoded = decodeText(
527
- context,
528
- response.status,
529
- response.headers as Record<string, string | undefined>,
530
- text ?? "",
531
- outputAst,
532
- errorClasses,
533
- );
534
- return decoded.ok ? Effect.succeed(decoded.value) : fail(decoded.error);
535
- },
536
- });
583
+ // A body read that fails (reset or abort mid-body) fails the call with
584
+ // its `HttpClientError`, which every operation's error channel declares.
585
+ (response.status >= 200 && response.status < 300 && decodePlanFor(outputAst).binary
586
+ ? Effect.map(response.arrayBuffer, (bytes) => new Uint8Array(bytes))
587
+ : Effect.flatMap(response.text, (text) => {
588
+ recordPageHeaders(context, response.headers);
589
+ const decoded = decodeText(
590
+ context,
591
+ response.status,
592
+ response.headers as Record<string, string | undefined>,
593
+ text ?? "",
594
+ outputAst,
595
+ errorClasses,
596
+ );
597
+ return decoded.ok ? Effect.succeed(decoded.value) : fail(decoded.error);
598
+ })) as Effect.Effect<unknown>;
537
599
 
538
600
  const call = (op: API.PreparedOperation, input: unknown): Effect.Effect<unknown> =>
539
601
  Effect.withFiber((fiber) => {
540
602
  const context = fiber.context as Context.Context<any>;
541
603
  return withCredentials(context, (creds) => {
542
- const request = requestFor(creds, input, op.inputAst);
543
- if ("refused" in request) return fail(request.refused);
544
604
  const client = Context.get(context, HttpClient.HttpClient);
545
- return Effect.flatMap(client.execute(request), (response) =>
546
- decodeResponse(context, response, op.outputAst, op.errors),
605
+ return Effect.flatMap(requestFor(creds, input, op.inputAst), (request) =>
606
+ Effect.flatMap(Telemetry.execute(context, client, request), (response) =>
607
+ decodeResponse(context, response, op.outputAst, op.errors),
608
+ ),
547
609
  );
548
610
  });
549
611
  }) as Effect.Effect<unknown>;
@@ -555,10 +617,9 @@ export const makeRestProtocol = <C>(options: RestProtocolOptions<C>): Layer.Laye
555
617
  // fiber; see RestProtocolOptions.credentials).
556
618
  encode: ({ input, inputAst }) =>
557
619
  Effect.withFiber((fiber) =>
558
- withCredentials(fiber.context as Context.Context<any>, (creds) => {
559
- const request = requestFor(creds, input, inputAst);
560
- return "refused" in request ? fail(request.refused) : Effect.succeed(request);
561
- }),
620
+ withCredentials(fiber.context as Context.Context<any>, (creds) =>
621
+ requestFor(creds, input, inputAst),
622
+ ),
562
623
  ) as Effect.Effect<HttpClientRequest.HttpClientRequest>,
563
624
  decode: ({ response, outputAst, errors }) =>
564
625
  Effect.withFiber((fiber) =>
@@ -7,9 +7,10 @@
7
7
  * lenient (default): the response is returned as the protocol read it.
8
8
  * A body that does not match the declared output type
9
9
  * (a missing member, a wrong primitive, a non-JSON
10
- * body) still succeeds, except that core's REST
11
- * protocol, Stripe and Fly.io fail a non-JSON body for
12
- * an output with sensitive members in every mode.
10
+ * body) still succeeds, except that a non-JSON body for
11
+ * an output with sensitive members fails in every mode
12
+ * (REST-style protocols through core's `checkSuccess`
13
+ * in `protocol-rest`, plus ZeroSSL and AWS).
13
14
  * additionalProperties: the response is checked against the output
14
15
  * schema, and a mismatch fails the call with the SDK's
15
16
  * `<Sdk>ParseError` (AWS: `ParseError`). Keys the
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Debug telemetry: spans for distilled's internals, on top of the operation
3
+ * span every call records. Opt in by providing the layer; a program that
4
+ * never imports this module never bundles it.
5
+ *
6
+ * ```ts
7
+ * import { TelemetryDebug } from "@distilled.cloud/core/telemetry-debug";
8
+ * program.pipe(Effect.provide(TelemetryDebug.layer));
9
+ * ```
10
+ *
11
+ * With it, the operation span is the parent of:
12
+ *
13
+ * - one `Attempt` span per try, with Effect's HTTP span under it;
14
+ * - INTERNAL spans at trace level `Debug` for first-call setup,
15
+ * serialize, sign, deserialize, backoff sleeps and the caller's read
16
+ * of a streamed output (`Tracer.MinimumTraceLevel` can drop them);
17
+ *
18
+ * and carries the caller's `code.*` attributes.
19
+ *
20
+ * `layerWith({ logRequests: true })` also prints one stderr line per request
21
+ * and per response, whether or not an exporter is installed:
22
+ *
23
+ * ```
24
+ * [distilled] -> GET /zones/{zone_id}
25
+ * [distilled] <- 404 {"success":false,"errors":[...]}
26
+ * ```
27
+ *
28
+ * Response lines carry up to 400 characters of the body, which can hold
29
+ * secrets the API returns.
30
+ */
31
+ import * as Cause from "effect/Cause";
32
+ import * as Effect from "effect/Effect";
33
+ import * as Exit from "effect/Exit";
34
+ import * as Layer from "effect/Layer";
35
+ import * as Stream from "effect/Stream";
36
+ import * as Tracer from "effect/Tracer";
37
+ import { Debug, type DebugHooks, OperationSpan, tagOf } from "./telemetry.ts";
38
+
39
+ const phase: DebugHooks["phase"] = (name, effect, attributes) =>
40
+ Effect.withSpan(effect, name, { level: "Debug", attributes, captureStackTrace: false });
41
+
42
+ const attempt: DebugHooks["attempt"] = (base, n) =>
43
+ Effect.withFiber((fiber) => {
44
+ const call = fiber.getRef(OperationSpan);
45
+ if (call === undefined) return base;
46
+ return Effect.useSpan(
47
+ "Attempt",
48
+ {
49
+ parent: call.span,
50
+ attributes: { "distilled.attempt": n, "http.request.resend_count": n - 1 },
51
+ },
52
+ (span) => {
53
+ call.attempt = span;
54
+ const run = Effect.tapError(base, (error) =>
55
+ Effect.sync(() => span.attribute("error.type", tagOf(error))),
56
+ );
57
+ return Effect.provideService(run, Tracer.ParentSpan, span);
58
+ },
59
+ );
60
+ });
61
+
62
+ /**
63
+ * `distilled.read_stream`: from the caller's first pull on a streamed
64
+ * output member (an S3 object body, a Bedrock event stream) to its end,
65
+ * with the member's name and how many items (and bytes) it carried. It
66
+ * fills the operation span's time after the response headers arrive.
67
+ */
68
+ const readStream: DebugHooks["readStream"] = (stream, parent, member) =>
69
+ Stream.unwrap(
70
+ Effect.map(
71
+ Effect.makeSpan("distilled.read_stream", {
72
+ parent,
73
+ level: "Debug",
74
+ attributes: { "distilled.stream.member": member },
75
+ }),
76
+ (span) => {
77
+ let items = 0;
78
+ let bytes = 0;
79
+ const counted = Stream.map(stream, (item) => {
80
+ items++;
81
+ if (item instanceof Uint8Array) bytes += item.byteLength;
82
+ return item;
83
+ });
84
+ return Stream.onExit(counted, (exit) =>
85
+ Effect.clockWith((clock) =>
86
+ Effect.sync(() => {
87
+ span.attribute("distilled.stream.items", items);
88
+ if (bytes > 0) span.attribute("distilled.stream.bytes", bytes);
89
+ if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) {
90
+ span.attribute("error.type", tagOf(Cause.squash(exit.cause)));
91
+ }
92
+ span.end(clock.currentTimeNanosUnsafe(), exit);
93
+ }),
94
+ ),
95
+ );
96
+ },
97
+ ),
98
+ );
99
+
100
+ const LOCATION = /\(?((?:file:\/\/)?[^\s()]+):(\d+):(\d+)\)?$/;
101
+
102
+ /** OTel `code.*` attributes for the caller's line. */
103
+ const callSite: DebugHooks["callSite"] = (site) => {
104
+ const line = site?.();
105
+ const match = line ? LOCATION.exec(line) : null;
106
+ if (!match) return undefined;
107
+ const fn = /^at (\S+) \(/.exec(line!)?.[1];
108
+ return {
109
+ "code.file.path": match[1],
110
+ "code.line.number": Number(match[2]),
111
+ "code.column.number": Number(match[3]),
112
+ ...(fn ? { "code.function.name": fn } : {}),
113
+ };
114
+ };
115
+
116
+ export interface Options {
117
+ /** Print each request and response to stderr. Default `false`. */
118
+ readonly logRequests?: boolean;
119
+ }
120
+
121
+ const layerWith = (options: Options = {}): Layer.Layer<never> =>
122
+ Layer.succeed(Debug, {
123
+ phase,
124
+ attempt,
125
+ readStream,
126
+ callSite,
127
+ logRequests: options.logRequests === true,
128
+ }) as Layer.Layer<never>;
129
+
130
+ export const TelemetryDebug = {
131
+ /** Turns on debug spans for every distilled call it is provided to. */
132
+ layer: /*@__PURE__*/ layerWith(),
133
+ /** Debug spans, with options (`logRequests`). */
134
+ layerWith,
135
+ } as const;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * App callbacks on each recorded operation span, for attributes distilled
3
+ * does not record (an app's own ids, a custom request field):
4
+ *
5
+ * ```ts
6
+ * import { TelemetryHooks } from "@distilled.cloud/core/telemetry-hooks";
7
+ *
8
+ * program.pipe(
9
+ * Effect.provide(
10
+ * TelemetryHooks.layer({
11
+ * onStart: (span, { method, input }) => {
12
+ * if (method === "S3/PutObject") span.attribute("app.tenant", tenantOf(input));
13
+ * },
14
+ * onEnd: (span, exit) => {},
15
+ * }),
16
+ * ),
17
+ * );
18
+ * ```
19
+ *
20
+ * `onStart` runs when the span starts, before the request is built, with
21
+ * the operation's span name, its `rpc.method` and the caller's input.
22
+ * `onEnd` runs when the call ends, after every retry. Both run only when a
23
+ * span is recorded (an exporter is installed). A program that never
24
+ * imports this module never bundles it.
25
+ */
26
+ import * as Layer from "effect/Layer";
27
+ import { Hooks, type SpanHooks } from "./telemetry.ts";
28
+
29
+ export type { SpanHooks };
30
+
31
+ export const TelemetryHooks = {
32
+ layer: (hooks: SpanHooks): Layer.Layer<never> => Layer.succeed(Hooks, hooks),
33
+ } as const;