@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
package/src/graphql.ts CHANGED
@@ -59,6 +59,7 @@ import * as Schedule from "effect/Schedule";
59
59
  import * as S from "effect/Schema";
60
60
  import * as Stream from "effect/Stream";
61
61
  import { unwrapRedactedDeep } from "./plain-values.ts";
62
+ import * as Telemetry from "./telemetry.ts";
62
63
 
63
64
  export const QuerySymbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/graphql/Query");
64
65
  const inspect = /*@__PURE__*/ Symbol.for("nodejs.util.inspect.custom");
@@ -304,6 +305,20 @@ export interface CompiledOperation {
304
305
  readonly tree: SelNode;
305
306
  }
306
307
 
308
+ /**
309
+ * What a GraphQL SDK's document spans carry, generated from its GraphQL
310
+ * model's `telemetry` entry (see `packages/dev/src/codegen/telemetry-traits.md`).
311
+ * One span per document: `<prefix>.<rootField>`, or `<prefix>.<kind>` when
312
+ * the document selects several root fields.
313
+ */
314
+ export interface GraphQLTelemetry extends Telemetry.ServiceTelemetry {
315
+ readonly prefix: string;
316
+ /** `<kind>.<rootField>`, then argument name, then the attributes read from its value. */
317
+ readonly fields?: Readonly<
318
+ Record<string, Readonly<Record<string, ReadonlyArray<Telemetry.AttributeRule>>>>
319
+ >;
320
+ }
321
+
307
322
  export class GqlTransport
308
323
  extends /*@__PURE__*/ Context.Service<
309
324
  GqlTransport,
@@ -311,6 +326,8 @@ export class GqlTransport
311
326
  readonly execute: (
312
327
  req: CompiledOperation,
313
328
  ) => Effect.Effect<GraphQLResponse, GraphQLTransportError, any>;
329
+ /** The SDK's span facts; no spans without it. */
330
+ readonly telemetry?: GraphQLTelemetry;
314
331
  }
315
332
  >()("@distilled.cloud/graphql/Transport") {}
316
333
 
@@ -1246,7 +1263,18 @@ const execute = (compiled: Compiled): Effect.Effect<unknown, ExecuteError, GqlTr
1246
1263
  const response = yield* transport.execute(compiled);
1247
1264
  const data = redactSelected(compiled.tree, response.data);
1248
1265
  const raw = response.errors ?? [];
1249
- if (raw.length === 0) return data;
1266
+ if (raw.length === 0) {
1267
+ // Without errors, a GraphQL response must carry a `data` object.
1268
+ if (!isRecord(response.data)) {
1269
+ return yield* Effect.fail(
1270
+ new GraphQLTransportError({
1271
+ message: "GraphQL response has no data object and no errors",
1272
+ status: response.status,
1273
+ }),
1274
+ );
1275
+ }
1276
+ return data;
1277
+ }
1250
1278
  const issues = raw.map((error) => classify(compiled, error, response));
1251
1279
  const [first, ...rest] = issues as [GraphQLIssue, ...GraphQLIssue[]];
1252
1280
  return yield* Effect.fail(
@@ -1259,15 +1287,71 @@ const execute = (compiled: Compiled): Effect.Effect<unknown, ExecuteError, GqlTr
1259
1287
  }),
1260
1288
  );
1261
1289
  });
1262
- return compiled.kind === "query"
1263
- ? once.pipe(
1264
- Effect.retry({
1265
- while: (error) => isRetryable(compiled, error),
1266
- times: 5,
1267
- schedule: Schedule.exponential("200 millis"),
1268
- }),
1269
- )
1270
- : once;
1290
+ const attempts = Effect.withFiber((fiber) => {
1291
+ if (compiled.kind !== "query") return once;
1292
+ const context = fiber.context as Context.Context<any>;
1293
+ let retries = 0;
1294
+ return once.pipe(
1295
+ Effect.retry({
1296
+ while: (error) => {
1297
+ const retry = isRetryable(compiled, error) && retries < 5;
1298
+ // Schedule.exponential("200 millis"): 200 ms, then doubling.
1299
+ if (retry) Telemetry.retried(context, ++retries, error, 200 * 2 ** (retries - 1));
1300
+ return retry;
1301
+ },
1302
+ times: 5,
1303
+ schedule: Schedule.exponential("200 millis"),
1304
+ }),
1305
+ );
1306
+ });
1307
+ return Effect.withFiber((fiber) => {
1308
+ const debug = fiber.getRef(Telemetry.Debug);
1309
+ const telemetry = Context.getOrUndefined(fiber.context, GqlTransport)?.telemetry;
1310
+ if (telemetry === undefined) return attempts;
1311
+ const [info, input] = documentInfo(telemetry, compiled);
1312
+ return Telemetry.operationSpan(fiber, debug, info, undefined, input, () => attempts);
1313
+ }) as Effect.Effect<unknown, ExecuteError, GqlTransport>;
1314
+ };
1315
+
1316
+ /**
1317
+ * One document's span facts: its root fields name it, and their arguments
1318
+ * fill the attributes the SDK's `fields` rules name (an input object keyed
1319
+ * `<kind>.<field>.<argument>`).
1320
+ */
1321
+ const documentInfo = (
1322
+ telemetry: GraphQLTelemetry,
1323
+ compiled: Compiled,
1324
+ ): readonly [Telemetry.OperationInfo, Record<string, unknown>] => {
1325
+ const roots = [...new Set([...compiled.tree.children.values()].map((node) => node.field))];
1326
+ const single = roots.length === 1 ? roots[0] : undefined;
1327
+ const target = single ?? compiled.kind;
1328
+ const input: Record<string, unknown> = {};
1329
+ const rules: Record<string, ReadonlyArray<Telemetry.AttributeRule>> = {};
1330
+ for (const node of compiled.tree.children.values()) {
1331
+ const fieldRules = telemetry.fields?.[`${compiled.kind}.${node.field}`];
1332
+ if (fieldRules === undefined || node.args === undefined) continue;
1333
+ for (const arg in node.args) {
1334
+ const argRules = fieldRules[arg];
1335
+ if (argRules === undefined) continue;
1336
+ const key = `${compiled.kind}.${node.field}.${arg}`;
1337
+ input[key] = compiled.variables[node.args[arg]!];
1338
+ rules[key] = argRules;
1339
+ }
1340
+ }
1341
+ const info = Telemetry.operationInfo(
1342
+ telemetry,
1343
+ {
1344
+ name: `${telemetry.prefix}.${target}`,
1345
+ method: `${telemetry.prefix}/${target}`,
1346
+ attributes: {
1347
+ "graphql.operation.type": compiled.kind,
1348
+ ...(single !== undefined ? { "graphql.operation.name": single } : {}),
1349
+ },
1350
+ input: rules,
1351
+ },
1352
+ undefined,
1353
+ );
1354
+ return [info, input];
1271
1355
  };
1272
1356
 
1273
1357
  type ExecuteError = GraphQLIssue | GraphQLFailure | GraphQLTransportError;
@@ -1294,13 +1378,34 @@ const isRecord = (value: unknown): value is Record<string, unknown> =>
1294
1378
  * declares (or the global errors for a path-less error). A tie between
1295
1379
  * different tags is ambiguous and stays {@link UnknownGraphQLError}.
1296
1380
  */
1297
- const classify = (
1298
- compiled: Compiled,
1299
- raw: RawGraphQLError,
1300
- response: GraphQLResponse,
1301
- ): GraphQLIssue => {
1302
- const path = Array.isArray(raw.path) ? raw.path : undefined;
1303
- const root = typeof path?.[0] === "string" ? compiled.rootErrors.get(path[0]) : undefined;
1381
+ const classify = (compiled: Compiled, entry: unknown, response: GraphQLResponse): GraphQLIssue => {
1382
+ // The entry comes from the wire: anything that is not an object (`null`,
1383
+ // a bare string) is read as an error with only a message.
1384
+ const raw: Partial<RawGraphQLError> = isRecord(entry)
1385
+ ? (entry as Partial<RawGraphQLError>)
1386
+ : {
1387
+ message:
1388
+ typeof entry === "string"
1389
+ ? entry
1390
+ : `malformed GraphQL error entry (${entry === null ? "null" : typeof entry})`,
1391
+ };
1392
+ const rawPath = Array.isArray(raw.path) ? (raw.path as ReadonlyArray<unknown>) : undefined;
1393
+ const root = typeof rawPath?.[0] === "string" ? compiled.rootErrors.get(rawPath[0]) : undefined;
1394
+ // The error classes validate `path` and `locations`, so a malformed value
1395
+ // is left out instead of making the constructor throw.
1396
+ const path = rawPath?.every((key) => typeof key === "string" || typeof key === "number")
1397
+ ? (rawPath as ReadonlyArray<string | number>)
1398
+ : undefined;
1399
+ const locations =
1400
+ Array.isArray(raw.locations) &&
1401
+ raw.locations.every(
1402
+ (location: unknown) =>
1403
+ isRecord(location) &&
1404
+ typeof location.line === "number" &&
1405
+ typeof location.column === "number",
1406
+ )
1407
+ ? raw.locations
1408
+ : undefined;
1304
1409
  const candidates = root
1305
1410
  ? root.errors
1306
1411
  : uniqueByTag(
@@ -1321,7 +1426,7 @@ const classify = (
1321
1426
  message,
1322
1427
  code,
1323
1428
  path,
1324
- locations: raw.locations,
1429
+ locations,
1325
1430
  extensions: raw.extensions,
1326
1431
  traceId:
1327
1432
  typeof extensions.traceId === "string"
package/src/index.ts CHANGED
@@ -9,8 +9,8 @@
9
9
  *
10
10
  * Each namespace is also importable on its own subpath
11
11
  * (`@distilled.cloud/core/response-validation`, ...); generated SDKs use the
12
- * subpaths. Code generation (`codegen/*`) and test helpers (`testing`) stay
13
- * subpath-only.
12
+ * subpaths. The code generator and test helpers live in the unpublished
13
+ * `@distilled.cloud/dev` package.
14
14
  */
15
15
  export * as API from "./api.ts";
16
16
  export * as Category from "./category.ts";
@@ -24,4 +24,5 @@ export * as Crypto from "./crypto.ts";
24
24
  export * as ResponseValidation from "./response-validation.ts";
25
25
  export * as Retry from "./retry.ts";
26
26
  export * as RetryAfter from "./retry-after.ts";
27
+ export * as Telemetry from "./telemetry.ts";
27
28
  export * as Trait from "./trait.ts";
package/src/pagination.ts CHANGED
@@ -7,6 +7,8 @@
7
7
  * - Token-based (AWS style): NextToken/MaxResults continuation tokens
8
8
  * - Relay (GraphQL connections): after/first with a `pageInfo` block whose
9
9
  * `hasNextPage` -- not the cursor -- marks the end
10
+ * - Link: the next page's token is a query parameter of the `rel="next"` URL
11
+ * in the `Link` response header (RFC 8288; GitHub, Okta, Sentry)
10
12
  * - Single: one-shot list endpoints that still expose the paginated surface
11
13
  *
12
14
  * Each SDK stores a {@link PaginatedTrait} on its operations (sourced from the
@@ -15,6 +17,7 @@
15
17
  * Ported from the distilled repo's `core/pagination`.
16
18
  */
17
19
  import type * as Arr from "effect/Array";
20
+ import * as Context from "effect/Context";
18
21
  import * as Effect from "effect/Effect";
19
22
  import * as Stream from "effect/Stream";
20
23
 
@@ -69,8 +72,11 @@ export const getItems = (obj: unknown, path: string): readonly unknown[] => {
69
72
  /** Pagination trait describing how to navigate between pages. */
70
73
  export interface PaginatedTrait {
71
74
  /** Pagination strategy */
72
- readonly mode?: "token" | "page" | "cursor" | "relay" | "single";
73
- /** The name of the input member containing the page/cursor token */
75
+ readonly mode?: "token" | "page" | "cursor" | "relay" | "link" | "single";
76
+ /**
77
+ * The name of the input member containing the page/cursor token. In link
78
+ * mode it is also the query parameter read from the `rel="next"` URL.
79
+ */
74
80
  readonly inputToken?: string;
75
81
  /** The path to the output member containing the next page/cursor token */
76
82
  readonly outputToken?: string;
@@ -155,9 +161,10 @@ export const paginatePageNumber = <Input extends Record<string, unknown>, Output
155
161
  // next one (e.g. Cloudflare's `result_info.page`). Taking that value as
156
162
  // the next page re-requests the same page forever. Only accept an
157
163
  // *advancing* page number; otherwise advance by one and terminate when
158
- // a page comes back with no items (or the token is absent).
164
+ // a page comes back with no items (or the token is absent). A `null`
165
+ // items member (e.g. `result: null`) is an empty page, as in `getItems`.
159
166
  const items = pagination.items
160
- ? (getPath(response, pagination.items) as readonly unknown[] | undefined)
167
+ ? (getPath(response, pagination.items) as readonly unknown[] | null | undefined)
161
168
  : undefined;
162
169
 
163
170
  const nextState: State = {
@@ -165,6 +172,7 @@ export const paginatePageNumber = <Input extends Record<string, unknown>, Output
165
172
  done:
166
173
  nextPage === null ||
167
174
  nextPage === undefined ||
175
+ items === null ||
168
176
  (items !== undefined && items.length === 0),
169
177
  };
170
178
 
@@ -338,6 +346,97 @@ export const paginateRelay = <Input extends Record<string, unknown>, Output, E,
338
346
  );
339
347
  };
340
348
 
349
+ // ============================================================================
350
+ // Link-header Pagination (RFC 8288)
351
+ // ============================================================================
352
+
353
+ /** Where the protocol puts a call's response headers during a link traversal. */
354
+ interface PageHeadersSlot {
355
+ headers: Readonly<Record<string, string | undefined>> | undefined;
356
+ }
357
+
358
+ const PageHeaders = /*@__PURE__*/ Context.Reference<PageHeadersSlot | undefined>(
359
+ "@distilled.cloud/core/Pagination/PageHeaders",
360
+ { defaultValue: () => undefined },
361
+ );
362
+
363
+ /**
364
+ * Hand a response's headers to the link traversal running on this fiber, if
365
+ * any. Protocols call it for every response they decode; outside
366
+ * {@link paginateLink} it does nothing.
367
+ */
368
+ export const recordPageHeaders = (
369
+ context: Context.Context<never>,
370
+ headers: Readonly<Record<string, string | undefined>>,
371
+ ): void => {
372
+ const slot = Context.get(context, PageHeaders);
373
+ if (slot !== undefined) slot.headers = headers;
374
+ };
375
+
376
+ /**
377
+ * The URL of the `rel="next"` link in a `Link` header value, e.g.
378
+ * `<https://api.github.com/repositories/1/issues?page=2>; rel="next", <...>; rel="last"`.
379
+ */
380
+ export const nextLink = (header: string | undefined): string | undefined => {
381
+ if (header === undefined) return undefined;
382
+ for (const link of header.split(/,\s*(?=<)/)) {
383
+ const match = /^\s*<([^>]*)>(.*)$/.exec(link);
384
+ const rel = match && /;\s*rel\s*=\s*"?([^";]*)"?/i.exec(match[2]!);
385
+ if (rel && rel[1]!.toLowerCase().split(/\s+/).includes("next")) return match![1];
386
+ }
387
+ return undefined;
388
+ };
389
+
390
+ /**
391
+ * Stream of pages that follows the `Link` response header: each request
392
+ * takes `inputToken` from the query of the previous response's `rel="next"`
393
+ * URL, and traversal ends when a response has no next link (or its token
394
+ * repeats the current one). The response body carries no token, so this
395
+ * works for APIs whose list responses are bare arrays.
396
+ *
397
+ * The protocol must report response headers through
398
+ * {@link recordPageHeaders} (the REST protocol does); otherwise traversal
399
+ * stops after the first page.
400
+ */
401
+ export const paginateLink = <Input extends Record<string, unknown>, Output, E, R>(
402
+ operation: (input: Input) => Effect.Effect<Output, E, R>,
403
+ input: Input,
404
+ pagination: PaginatedTrait,
405
+ ): Stream.Stream<Output, E, R> => {
406
+ const inputToken = pagination.inputToken;
407
+ if (!inputToken) {
408
+ return missingPaginationConfig("Link pagination requires inputToken");
409
+ }
410
+ type State = { token: unknown; done: boolean };
411
+
412
+ return Stream.unfold({ token: input[inputToken], done: false } as State, (state) =>
413
+ Effect.gen(function* () {
414
+ if (state.done) return undefined;
415
+
416
+ const requestPayload =
417
+ state.token !== undefined ? ({ ...input, [inputToken]: state.token } as Input) : input;
418
+ const slot: PageHeadersSlot = { headers: undefined };
419
+ const response = yield* Effect.provideService(operation(requestPayload), PageHeaders, slot);
420
+
421
+ const next = nextLink(slot.headers?.["link"]);
422
+ // The token goes back as the query text it came as (`page=2` -> "2");
423
+ // query members are sent as text either way.
424
+ const token =
425
+ next === undefined
426
+ ? undefined
427
+ : (new URL(next, "http://_").searchParams.get(inputToken) ?? undefined);
428
+
429
+ const nextState: State = {
430
+ token,
431
+ done:
432
+ isTerminalToken(token) || (state.token !== undefined && token === String(state.token)),
433
+ };
434
+
435
+ return [response, nextState] as const;
436
+ }),
437
+ );
438
+ };
439
+
341
440
  /**
342
441
  * Shared default pagination dispatcher for SDKs that use generic
343
442
  * token/cursor/page traversal.
@@ -352,6 +451,8 @@ export const paginateWithDefaults: PaginationStrategy = (operation, input, pagin
352
451
  return paginateCursor(operation, input, pagination);
353
452
  case "relay":
354
453
  return paginateRelay(operation, input, pagination);
454
+ case "link":
455
+ return paginateLink(operation, input, pagination);
355
456
  case "single":
356
457
  return paginateSingle(operation, input, pagination);
357
458
  case "token":
@@ -375,6 +476,19 @@ export const paginateWithDefaults: PaginationStrategy = (operation, input, pagin
375
476
  export const extractItems = <Output, Item, E, R>(
376
477
  pages: Stream.Stream<Output, E, R>,
377
478
  itemsPath: string,
479
+ ): Stream.Stream<Item, E, R> => flattenPages(pages, (page) => getItems(page, itemsPath));
480
+
481
+ /**
482
+ * The items of a stream of pages that are themselves the lists (bare-array
483
+ * responses).
484
+ */
485
+ export const extractArrayItems = <Output, Item, E, R>(
486
+ pages: Stream.Stream<Output, E, R>,
487
+ ): Stream.Stream<Item, E, R> => flattenPages(pages, (page) => (Array.isArray(page) ? page : []));
488
+
489
+ const flattenPages = <Output, Item, E, R>(
490
+ pages: Stream.Stream<Output, E, R>,
491
+ itemsOf: (page: Output) => readonly unknown[],
378
492
  ): Stream.Stream<Item, E, R> =>
379
493
  // Flattens each pulled chunk of pages directly, skipping pages with no
380
494
  // items. `Stream.flatMap` / `flattenIterable` would do the same but pull in
@@ -386,8 +500,7 @@ export const extractItems = <Output, Item, E, R>(
386
500
  pull,
387
501
  (chunk) => {
388
502
  const items: Item[] = [];
389
- for (const page of chunk)
390
- for (const item of getItems(page, itemsPath)) items.push(item as Item);
503
+ for (const page of chunk) for (const item of itemsOf(page)) items.push(item as Item);
391
504
  return items.length > 0
392
505
  ? Effect.succeed(items as unknown as Arr.NonEmptyReadonlyArray<Item>)
393
506
  : next;
@@ -1,3 +1,4 @@
1
+ import * as Effect from "effect/Effect";
1
2
  import * as Headers from "effect/http/Headers";
2
3
  import * as HttpBody from "effect/http/HttpBody";
3
4
  import * as HttpClientRequest from "effect/http/HttpClientRequest";
@@ -12,8 +13,12 @@ import * as HttpClientRequest from "effect/http/HttpClientRequest";
12
13
  * {@link matchTypedError}).
13
14
  */
14
15
  import type * as AST from "effect/SchemaAST";
16
+ import { getAnn, getProps } from "./annotations.ts";
17
+ import * as Category from "./category.ts";
15
18
  import { debugHttp } from "./debug.ts";
16
19
  import { isOpaqueValue } from "./plain-values.ts";
20
+ import * as Schema from "./schema-lite-typed.ts";
21
+ import { restoreStack, suppressStack } from "./telemetry.ts";
17
22
  import {
18
23
  bodySymbol,
19
24
  deepQuerySymbol,
@@ -37,27 +42,7 @@ import {
37
42
 
38
43
  //#region AST helpers (survive S.optional / Suspend / transforms)
39
44
 
40
- export const getProps = (ast: AST.AST): readonly AST.PropertySignature[] => {
41
- if (ast._tag === "Objects") return ast.propertySignatures;
42
- if (ast._tag === "Suspend") return getProps(ast.thunk());
43
- if (ast.encoding && ast.encoding.length > 0) return getProps(ast.encoding[0]!.to);
44
- return [];
45
- };
46
-
47
- export const getAnn = (ast: AST.AST, symbol: symbol): unknown => {
48
- const direct = (ast.annotations as Record<symbol, unknown> | undefined)?.[symbol];
49
- if (direct !== undefined) return direct;
50
- if (ast._tag === "Suspend") return getAnn(ast.thunk(), symbol);
51
- if (ast.encoding && ast.encoding.length > 0) return getAnn(ast.encoding[0]!.to, symbol);
52
- // S.optional -> Union[self, Undefined]; descend into the single real member.
53
- if (ast._tag === "Union") {
54
- const real = (ast as AST.Union).types.filter(
55
- (t) => t._tag !== "Undefined" && !(t._tag === "Literal" && (t as any).literal === null),
56
- );
57
- if (real.length === 1) return getAnn(real[0]!, symbol);
58
- }
59
- return undefined;
60
- };
45
+ export { getAnn, getProps } from "./annotations.ts";
61
46
 
62
47
  export const getPropAnn = (prop: AST.PropertySignature, symbol: symbol): unknown =>
63
48
  getAnn(prop.type, symbol);
@@ -607,6 +592,38 @@ export const makeRequest = (
607
592
  HttpBody.empty,
608
593
  );
609
594
 
595
+ /**
596
+ * The input cannot be sent: a path label whose value would address another
597
+ * resource (`.` or `..`, which the URL parser resolves to the parent path).
598
+ * Raised before anything is sent.
599
+ */
600
+ export class InvalidInput
601
+ extends /*@__PURE__*/ Schema.TaggedError<InvalidInput>()("InvalidInput", {
602
+ member: Schema.String,
603
+ message: Schema.String,
604
+ }).pipe(Category.withBadRequestError) {}
605
+
606
+ /**
607
+ * The refusal for a path label value that would address another resource,
608
+ * or `undefined`. The URL parser resolves a `.` or `..` segment,
609
+ * percent-encoded or not, so no encoding can carry one
610
+ * (`/projects/p1/branches/..` -> `/projects/p1/`). A greedy label keeps its
611
+ * `/`, so each of its segments counts.
612
+ */
613
+ export const invalidLabel = (
614
+ member: string,
615
+ value: unknown,
616
+ greedy?: boolean,
617
+ ): InvalidInput | undefined => {
618
+ const text = String(value);
619
+ return (greedy ? text.split("/") : [text]).some((s) => s === "." || s === "..")
620
+ ? new InvalidInput({
621
+ member,
622
+ message: `Input member ${member} cannot be ${JSON.stringify(text)}: as a path label it would address another resource`,
623
+ })
624
+ : undefined;
625
+ };
626
+
610
627
  /**
611
628
  * Build an HTTP request from an operation input and its schema, driven by
612
629
  * the trait annotations: `Http()` supplies method + URI template, `Label()`
@@ -619,19 +636,26 @@ export const makeRequest = (
619
636
  * The schema is read once per input schema (see `planFor`); later calls only
620
637
  * walk the input value.
621
638
  *
639
+ * Fails with {@link InvalidInput}, before anything is sent, when a label is
640
+ * `.` or `..` (for a greedy `{name+}` label, when any of its segments is).
622
641
  * Throws when the input schema is missing the `Http()` trait -- a codegen
623
- * bug -- and, before anything is sent, when a label is `.` or `..` (for a
624
- * greedy `{name+}` label, when any of its segments is). Each surfaces as a
625
- * defect by the calling protocol's Effect context.
642
+ * bug, which the calling protocol's Effect surfaces as a defect.
626
643
  */
627
- export const buildRequest = ({
644
+ export const buildRequest = (
645
+ options: BuildRequestOptions,
646
+ ): Effect.Effect<HttpClientRequest.HttpClientRequest, InvalidInput> => {
647
+ const request = requestOrInvalid(options);
648
+ return request instanceof InvalidInput ? Effect.fail(request) : Effect.succeed(request);
649
+ };
650
+
651
+ const requestOrInvalid = ({
628
652
  input,
629
653
  inputAst,
630
654
  baseUrl,
631
655
  headers: baseHeaders,
632
656
  mapMemberHeader,
633
657
  unknownKeyToWire,
634
- }: BuildRequestOptions): HttpClientRequest.HttpClientRequest => {
658
+ }: BuildRequestOptions): HttpClientRequest.HttpClientRequest | InvalidInput => {
635
659
  const inputObj = (input ?? {}) as Record<string, unknown>;
636
660
  const plan = planFor(inputAst);
637
661
  const { http, rootDict, members, known } = plan;
@@ -654,17 +678,8 @@ export const buildRequest = ({
654
678
  if (value === undefined) continue;
655
679
  switch (m.bind) {
656
680
  case "label": {
657
- // The URL parser resolves a `.` or `..` segment, percent-encoded or
658
- // not, so no encoding can carry one: it would address another path
659
- // (`/projects/p1/branches/..` -> `/projects/p1/`). A greedy label keeps
660
- // its `/`, so each of its segments counts.
661
- if (
662
- (m.greedy ? String(value).split("/") : [String(value)]).some(
663
- (s) => s === "." || s === "..",
664
- )
665
- ) {
666
- throw new Error(`invalid value for input HTTP label: ${m.key}`);
667
- }
681
+ const invalid = invalidLabel(m.key, value, m.greedy);
682
+ if (invalid) return invalid;
668
683
  const encoded = encodeURIComponent(String(value));
669
684
  const preserve = m.preserve;
670
685
  const label =
@@ -969,11 +984,16 @@ export const matchTypedError = (
969
984
  }
970
985
  }
971
986
  if (!best) return undefined;
972
- return new (best.cls as new (args: any) => unknown)({
973
- code: best.code ?? 0,
974
- message: best.message,
975
- body: response.body,
976
- headers: response.headers,
977
- });
987
+ const saved = suppressStack();
988
+ try {
989
+ return new (best.cls as new (args: any) => unknown)({
990
+ code: best.code ?? 0,
991
+ message: best.message,
992
+ body: response.body,
993
+ headers: response.headers,
994
+ });
995
+ } finally {
996
+ restoreStack(saved);
997
+ }
978
998
  };
979
999
  //#endregion