@digitraffic/common 2026.10.28-1 → 2026.10.30-2

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.
@@ -1,6 +1,6 @@
1
1
  import { HTTPError } from "ky";
2
2
  import { describe, expect, test, vi } from "vitest";
3
- import { createKyHooks, createLogginInterceptor, } from "../../aws/runtime/logging/http-interceptors.js";
3
+ import { createKyHooks, createLoggingInterceptor, } from "../../aws/runtime/logging/http-interceptors.js";
4
4
  function mockHttpLogger() {
5
5
  return {
6
6
  start: vi.fn(),
@@ -14,7 +14,7 @@ function asHttpLogger(mock) {
14
14
  /** Runs the interceptor and returns the handler it passed on to the next dispatch. */
15
15
  function intercept(httpLogger, innerHandler) {
16
16
  const dispatch = vi.fn(() => true);
17
- const interceptor = createLogginInterceptor(asHttpLogger(httpLogger));
17
+ const interceptor = createLoggingInterceptor(asHttpLogger(httpLogger));
18
18
  interceptor(dispatch)({}, innerHandler);
19
19
  expect(dispatch).toHaveBeenCalledTimes(1);
20
20
  return dispatch.mock.calls[0][1];
@@ -27,7 +27,7 @@ class InnerHandler {
27
27
  onResponseEnd = vi.fn();
28
28
  onResponseError = vi.fn();
29
29
  }
30
- describe("createLogginInterceptor", () => {
30
+ describe("createLoggingInterceptor", () => {
31
31
  const controller = {};
32
32
  test("exposes onRequestStart so undici accepts the handler", () => {
33
33
  const wrapped = intercept(mockHttpLogger(), new InnerHandler());
@@ -1,4 +1,3 @@
1
- import { EventEmitter } from "node:events";
2
1
  import { afterEach, describe, expect, test, vi } from "vitest";
3
2
  import { logger } from "../../aws/runtime/logging/dt-logger-default.js";
4
3
  import { HttpLogger, LoggerFactory, } from "../../aws/runtime/logging/http-logger.js";
@@ -29,16 +28,58 @@ describe("HttpLogger", () => {
29
28
  httpLogger.logResponse(200, 512);
30
29
  expect(infoSpy).toHaveBeenCalledWith({
31
30
  method: "HttpLogger.logStatus",
32
- [WIDE_CONTEXT.CONTEXT]: "Port-call",
31
+ [WIDE_CONTEXT.LOGGING.CONTEXT]: "port_call",
33
32
  [WIDE_CONTEXT.TRACE_ID]: "trace-123",
34
33
  [WIDE_CONTEXT.HTTP_KEYS.URL]: "https://example.test/visits/1",
35
- [WIDE_CONTEXT.HTTP_KEYS.URL_TEMPLATE]: "https://example.test/visits/{id}",
34
+ [WIDE_CONTEXT.HTTP_KEYS.URL_TEMPLATE]: "/visits/{id}",
36
35
  [WIDE_CONTEXT.HTTP_KEYS.ERROR_TYPE]: undefined,
37
36
  [WIDE_CONTEXT.HTTP_KEYS.STATUS_CODE]: 200,
38
37
  [WIDE_CONTEXT.HTTP_KEYS.DURATION]: 1.25,
39
38
  [WIDE_CONTEXT.HTTP_KEYS.CONTENT_LENGTH]: 512,
40
39
  });
41
40
  });
41
+ test.each([
42
+ ["https://example.test/visits/{id}", "/visits/{id}"],
43
+ ["http://example.test:8080/visits/{id}?a=1", "/visits/{id}?a=1"],
44
+ ["HTTPS://example.test/visits/{id}", "/visits/{id}"],
45
+ ["https://example.test", ""],
46
+ ["https://example.test?a=1", "?a=1"],
47
+ ["/visits/{id}", "/visits/{id}"],
48
+ ["/redirect/https://other.test/{id}", "/redirect/https://other.test/{id}"],
49
+ ])("strips scheme and host from url template %s", (template, expected) => {
50
+ const infoSpy = vi
51
+ .spyOn(logger, "info")
52
+ .mockImplementation(() => undefined);
53
+ new HttpLogger({
54
+ context: "Test",
55
+ url: "https://example.test/visits/1",
56
+ urlTemplate: template,
57
+ }).logResponse(200);
58
+ expect(infoSpy).toHaveBeenCalledWith(expect.objectContaining({
59
+ [WIDE_CONTEXT.HTTP_KEYS.URL]: "https://example.test/visits/1",
60
+ [WIDE_CONTEXT.HTTP_KEYS.URL_TEMPLATE]: expected,
61
+ }));
62
+ });
63
+ test("strips host from factory and per-request url templates", () => {
64
+ const infoSpy = vi
65
+ .spyOn(logger, "info")
66
+ .mockImplementation(() => undefined);
67
+ infoSpy.mockClear();
68
+ const factory = new LoggerFactory({
69
+ context: "Test",
70
+ urlTemplate: "https://example.test/default/{id}",
71
+ });
72
+ factory.logger("https://example.test/default/1").logResponse(200);
73
+ factory
74
+ .logger("https://example.test/other/1", "https://example.test/other/{id}")
75
+ .logResponse(200);
76
+ expect(infoSpy).toHaveBeenNthCalledWith(1, expect.objectContaining({
77
+ [WIDE_CONTEXT.HTTP_KEYS.URL_TEMPLATE]: "/default/{id}",
78
+ }));
79
+ expect(infoSpy).toHaveBeenNthCalledWith(2, expect.objectContaining({
80
+ [WIDE_CONTEXT.HTTP_KEYS.URL_TEMPLATE]: "/other/{id}",
81
+ }));
82
+ });
42
83
  test("logs error name and keeps status code unset when request fails", () => {
43
84
  const infoSpy = vi
44
85
  .spyOn(logger, "info")
@@ -50,7 +91,7 @@ describe("HttpLogger", () => {
50
91
  httpLogger.logError(new TypeError("request failed"));
51
92
  expect(infoSpy).toHaveBeenCalledWith(expect.objectContaining({
52
93
  method: "HttpLogger.logStatus",
53
- [WIDE_CONTEXT.CONTEXT]: "Test",
94
+ [WIDE_CONTEXT.LOGGING.CONTEXT]: "test",
54
95
  [WIDE_CONTEXT.HTTP_KEYS.ERROR_TYPE]: "TypeError",
55
96
  [WIDE_CONTEXT.HTTP_KEYS.STATUS_CODE]: undefined,
56
97
  [WIDE_CONTEXT.HTTP_KEYS.CONTENT_LENGTH]: undefined,
@@ -72,23 +113,5 @@ describe("HttpLogger", () => {
72
113
  [WIDE_CONTEXT.HTTP_KEYS.ERROR_TYPE]: typeof error === "string" ? error : "Unknown",
73
114
  }));
74
115
  });
75
- test("logs response status and content length from header", () => {
76
- const infoSpy = vi
77
- .spyOn(logger, "info")
78
- .mockImplementation(() => undefined);
79
- const body = new EventEmitter();
80
- const response = {
81
- statusCode: 204,
82
- headers: { "content-length": "5" },
83
- body,
84
- };
85
- const httpLogger = new LoggerFactory({ context: "Test" }).logger("https://example.test");
86
- httpLogger.log(response);
87
- body.emit("end");
88
- expect(infoSpy).toHaveBeenCalledWith(expect.objectContaining({
89
- [WIDE_CONTEXT.HTTP_KEYS.STATUS_CODE]: 204,
90
- [WIDE_CONTEXT.HTTP_KEYS.CONTENT_LENGTH]: 5,
91
- }));
92
- });
93
116
  });
94
117
  //# sourceMappingURL=http-logger.test.js.map
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,315 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import { z } from "zod";
3
+ import { convertJsonSchemaNullableToOneOfDeep, toApiGatewayJsonSchema, } from "../../utils/api-model.js";
4
+ describe("convertJsonSchemaNullableToOneOfDeep", () => {
5
+ test("does not change a schema without nullable", () => {
6
+ const input = {
7
+ type: "object",
8
+ properties: {
9
+ name: { type: "string", description: "Vessel name" },
10
+ ids: { type: "array", items: { type: "number" } },
11
+ union: { anyOf: [{ type: "string" }, { type: "number" }] },
12
+ },
13
+ required: ["name"],
14
+ additionalProperties: false,
15
+ };
16
+ expect(convertJsonSchemaNullableToOneOfDeep(input)).toEqual(input);
17
+ });
18
+ test("converts nullable fields to oneOf", () => {
19
+ const schema = convertJsonSchemaNullableToOneOfDeep({
20
+ type: "object",
21
+ properties: {
22
+ reason: {
23
+ type: "string",
24
+ nullable: true,
25
+ description: "Optional reason",
26
+ },
27
+ },
28
+ });
29
+ expect(schema).toEqual({
30
+ type: "object",
31
+ properties: {
32
+ reason: {
33
+ oneOf: [
34
+ { type: "string", description: "Optional reason" },
35
+ { type: "null" },
36
+ ],
37
+ },
38
+ },
39
+ });
40
+ });
41
+ test("converts nested nullable fields", () => {
42
+ const schema = convertJsonSchemaNullableToOneOfDeep({
43
+ type: "array",
44
+ items: {
45
+ type: "object",
46
+ properties: {
47
+ reason: { type: "string", nullable: true },
48
+ },
49
+ },
50
+ });
51
+ expect(schema).toEqual({
52
+ type: "array",
53
+ items: {
54
+ type: "object",
55
+ properties: {
56
+ reason: {
57
+ oneOf: [{ type: "string" }, { type: "null" }],
58
+ },
59
+ },
60
+ },
61
+ });
62
+ });
63
+ test("adds null to an existing union", () => {
64
+ const schema = convertJsonSchemaNullableToOneOfDeep({
65
+ anyOf: [{ type: "string" }, { type: "number" }],
66
+ nullable: true,
67
+ });
68
+ expect(schema).toEqual({
69
+ anyOf: [{ type: "string" }, { type: "number" }, { type: "null" }],
70
+ });
71
+ });
72
+ test("keeps null allowed when nullable schema uses allOf", () => {
73
+ // Zod can emit nullable intersections as { nullable: true, allOf: [...] }.
74
+ // anyOf is used instead of oneOf because an allOf alternative could also
75
+ // accept null, and oneOf would then reject it.
76
+ const schema = convertJsonSchemaNullableToOneOfDeep({
77
+ allOf: [{ type: "object" }, { type: "object" }],
78
+ nullable: true,
79
+ });
80
+ expect(schema).toEqual({
81
+ anyOf: [
82
+ { allOf: [{ type: "object" }, { type: "object" }] },
83
+ { type: "null" },
84
+ ],
85
+ });
86
+ });
87
+ test("keeps null allowed when nullable schema is only a reference", () => {
88
+ const schema = convertJsonSchemaNullableToOneOfDeep({
89
+ ref: "#/definitions/Vessel",
90
+ nullable: true,
91
+ });
92
+ expect(schema).toEqual({
93
+ anyOf: [{ ref: "#/definitions/Vessel" }, { type: "null" }],
94
+ });
95
+ });
96
+ test("keeps null allowed when nullable schema is empty", () => {
97
+ // An empty schema accepts everything, including null. oneOf would reject
98
+ // null because both alternatives match, so anyOf must be used.
99
+ const schema = convertJsonSchemaNullableToOneOfDeep({
100
+ nullable: true,
101
+ });
102
+ expect(schema).toEqual({
103
+ anyOf: [{}, { type: "null" }],
104
+ });
105
+ });
106
+ test("keeps a property named nullable", () => {
107
+ // "nullable" here is a field name, not the OpenAPI keyword
108
+ const schema = convertJsonSchemaNullableToOneOfDeep({
109
+ type: "object",
110
+ properties: {
111
+ nullable: { type: "boolean" },
112
+ },
113
+ required: ["nullable"],
114
+ });
115
+ expect(schema).toEqual({
116
+ type: "object",
117
+ properties: {
118
+ nullable: { type: "boolean" },
119
+ },
120
+ required: ["nullable"],
121
+ });
122
+ });
123
+ test("keeps literal values such as defaults untouched", () => {
124
+ // The default value is data, not schema. It must not be rewritten.
125
+ const schema = convertJsonSchemaNullableToOneOfDeep({
126
+ type: "object",
127
+ properties: {
128
+ settings: {
129
+ type: "object",
130
+ default: { nullable: true },
131
+ },
132
+ },
133
+ });
134
+ expect(schema).toEqual({
135
+ type: "object",
136
+ properties: {
137
+ settings: {
138
+ type: "object",
139
+ default: { nullable: true },
140
+ },
141
+ },
142
+ });
143
+ });
144
+ test("converts nullable inside dependencies schemas", () => {
145
+ const schema = convertJsonSchemaNullableToOneOfDeep({
146
+ type: "object",
147
+ dependencies: {
148
+ // schema dependency: applied when "credit" is present
149
+ credit: {
150
+ properties: {
151
+ billingAddress: { type: "string", nullable: true },
152
+ },
153
+ },
154
+ // property dependency: a plain name list, must stay unchanged
155
+ name: ["firstName"],
156
+ },
157
+ });
158
+ expect(schema).toEqual({
159
+ type: "object",
160
+ dependencies: {
161
+ credit: {
162
+ properties: {
163
+ billingAddress: {
164
+ oneOf: [{ type: "string" }, { type: "null" }],
165
+ },
166
+ },
167
+ },
168
+ name: ["firstName"],
169
+ },
170
+ });
171
+ });
172
+ test("keeps definitions resolvable when a nullable root is wrapped", () => {
173
+ // definitions must stay at the root, otherwise "#/definitions/Code"
174
+ // would point to nothing after wrapping
175
+ const schema = convertJsonSchemaNullableToOneOfDeep({
176
+ type: "object",
177
+ definitions: {
178
+ Code: { type: "string", nullable: true },
179
+ },
180
+ properties: {
181
+ code: { ref: "#/definitions/Code" },
182
+ },
183
+ nullable: true,
184
+ });
185
+ expect(schema).toEqual({
186
+ definitions: {
187
+ Code: { oneOf: [{ type: "string" }, { type: "null" }] },
188
+ },
189
+ oneOf: [
190
+ {
191
+ type: "object",
192
+ properties: {
193
+ code: { ref: "#/definitions/Code" },
194
+ },
195
+ },
196
+ { type: "null" },
197
+ ],
198
+ });
199
+ });
200
+ test("wraps a nullable anyOf that has sibling constraints", () => {
201
+ // enum applies to the whole schema, so null added inside anyOf alone
202
+ // would still be rejected by it
203
+ const schema = convertJsonSchemaNullableToOneOfDeep({
204
+ anyOf: [{ type: "string" }, { type: "number" }],
205
+ enum: ["a", 1],
206
+ nullable: true,
207
+ });
208
+ expect(schema).toEqual({
209
+ anyOf: [
210
+ {
211
+ anyOf: [{ type: "string" }, { type: "number" }],
212
+ enum: ["a", 1],
213
+ },
214
+ { type: "null" },
215
+ ],
216
+ });
217
+ });
218
+ test("removes nullable false from root and nested schemas", () => {
219
+ const schema = convertJsonSchemaNullableToOneOfDeep({
220
+ type: "object",
221
+ nullable: false,
222
+ properties: {
223
+ name: { type: "string", nullable: false },
224
+ },
225
+ });
226
+ expect(schema).toEqual({
227
+ type: "object",
228
+ properties: {
229
+ name: { type: "string" },
230
+ },
231
+ });
232
+ });
233
+ test("throws when wrapping would break a local reference", () => {
234
+ // "#/properties/..." would point to nothing after wrapping, so the
235
+ // conversion must fail at synth time instead of producing a broken model
236
+ expect(() => convertJsonSchemaNullableToOneOfDeep({
237
+ type: "object",
238
+ nullable: true,
239
+ properties: {
240
+ homeAddress: { type: "object" },
241
+ billingAddress: { ref: "#/properties/homeAddress" },
242
+ },
243
+ })).toThrow(/#\/properties\/homeAddress/);
244
+ });
245
+ test("allows definitions references when wrapping", () => {
246
+ expect(() => convertJsonSchemaNullableToOneOfDeep({
247
+ type: "object",
248
+ nullable: true,
249
+ definitions: { Code: { type: "string" } },
250
+ properties: {
251
+ code: { ref: "#/definitions/Code" },
252
+ },
253
+ })).not.toThrow();
254
+ });
255
+ test("does not treat references inside literal values as broken", () => {
256
+ // The default value is data. A "ref" inside it is not a schema reference
257
+ // and must not fail the conversion.
258
+ const schema = convertJsonSchemaNullableToOneOfDeep({
259
+ type: "object",
260
+ nullable: true,
261
+ properties: {
262
+ settings: {
263
+ type: "object",
264
+ default: { ref: "#/properties/code" },
265
+ },
266
+ },
267
+ });
268
+ expect(schema).toEqual({
269
+ oneOf: [
270
+ {
271
+ type: "object",
272
+ properties: {
273
+ settings: {
274
+ type: "object",
275
+ default: { ref: "#/properties/code" },
276
+ },
277
+ },
278
+ },
279
+ { type: "null" },
280
+ ],
281
+ });
282
+ });
283
+ test("creates an API Gateway schema from Zod", () => {
284
+ const schema = toApiGatewayJsonSchema(z.object({
285
+ reason: z.string().nullable(),
286
+ timestamp: z.iso.datetime(),
287
+ }));
288
+ expect(schema).toMatchObject({
289
+ type: "object",
290
+ properties: {
291
+ reason: {
292
+ oneOf: [{ type: "string" }, { type: "null" }],
293
+ },
294
+ timestamp: { type: "string", format: "date-time" },
295
+ },
296
+ });
297
+ expect(schema).not.toHaveProperty("properties.timestamp.pattern");
298
+ });
299
+ test("keeps a property named pattern but removes the pattern keyword", () => {
300
+ const schema = toApiGatewayJsonSchema(z.object({
301
+ // a field that happens to be named "pattern"
302
+ pattern: z.string().regex(/^[a-z]+$/),
303
+ }));
304
+ expect(schema).toMatchObject({
305
+ type: "object",
306
+ properties: {
307
+ pattern: { type: "string" },
308
+ },
309
+ required: ["pattern"],
310
+ });
311
+ // the regex keyword itself must not reach API Gateway
312
+ expect(schema).not.toHaveProperty("properties.pattern.pattern");
313
+ });
314
+ });
315
+ //# sourceMappingURL=api-model.test.js.map
@@ -4,6 +4,6 @@ import type { HttpLogger } from "./http-logger.js";
4
4
  /**
5
5
  * Create an Undici interceptor that logs HTTP requests and responses using the provided HttpLogger.
6
6
  */
7
- export declare function createLogginInterceptor(httpLogger: HttpLogger): Dispatcher.DispatcherComposeInterceptor;
7
+ export declare function createLoggingInterceptor(httpLogger: HttpLogger): Dispatcher.DispatcherComposeInterceptor;
8
8
  /** Create hooks for Ky HTTP client using the provided logger */
9
9
  export declare function createKyHooks(httpLogger: HttpLogger): Hooks;
@@ -10,7 +10,7 @@ function parseContentLengthFromHeader(headerValue) {
10
10
  /**
11
11
  * Create an Undici interceptor that logs HTTP requests and responses using the provided HttpLogger.
12
12
  */
13
- export function createLogginInterceptor(httpLogger) {
13
+ export function createLoggingInterceptor(httpLogger) {
14
14
  class LoggingHandler extends TypedDecoratorHandler {
15
15
  _statusCode;
16
16
  _receivedBytes = 0;
@@ -1,4 +1,3 @@
1
- import type { Dispatcher } from "undici";
2
1
  /**
3
2
  * Creates request loggers that share integration-level context.
4
3
  *
@@ -21,6 +20,9 @@ export declare class LoggerFactory {
21
20
  /**
22
21
  * Logs the outcome and duration of HTTP requests. Usually one, but in case of retries there may be multiple logs for the same logical request.
23
22
  *
23
+ * Given context will be reduced to snake_case.
24
+ * Given URL templates will have their scheme and host stripped.
25
+ *
24
26
  * Call {@link end} when a response status is available. Call {@link error}
25
27
  * when the request fails before a response is received. Each terminal method
26
28
  * writes one info-level log entry containing the request context, URL, status
@@ -39,8 +41,6 @@ export declare class HttpLogger {
39
41
  urlTemplate?: string;
40
42
  });
41
43
  start(): void;
42
- /** Hook logging into undici response events */
43
- log(response: Dispatcher.ResponseData<unknown>): void;
44
44
  /** Records a received HTTP response and writes the request log entry. */
45
45
  logResponse(statusCode: number, contentLength?: number): void;
46
46
  /**
@@ -1,3 +1,4 @@
1
+ import { snakeCase } from "es-toolkit";
1
2
  import { logger } from "./dt-logger-default.js";
2
3
  import { WIDE_CONTEXT } from "./wide-context.js";
3
4
  const METHOD = "HttpLogger.logStatus";
@@ -30,6 +31,9 @@ export class LoggerFactory {
30
31
  /**
31
32
  * Logs the outcome and duration of HTTP requests. Usually one, but in case of retries there may be multiple logs for the same logical request.
32
33
  *
34
+ * Given context will be reduced to snake_case.
35
+ * Given URL templates will have their scheme and host stripped.
36
+ *
33
37
  * Call {@link end} when a response status is available. Call {@link error}
34
38
  * when the request fails before a response is received. Each terminal method
35
39
  * writes one info-level log entry containing the request context, URL, status
@@ -42,28 +46,15 @@ export class HttpLogger {
42
46
  _traceId;
43
47
  _startTime;
44
48
  constructor(parameters) {
45
- this._context = parameters.context;
49
+ this._context = snakeCase(parameters.context);
46
50
  this._url = parameters.url;
47
51
  this._traceId = parameters.traceId;
48
- this._urlTemplate = parameters.urlTemplate;
52
+ this._urlTemplate = parameters.urlTemplate?.replace(/^https?:\/\/[^/?#]+/i, "");
49
53
  this._startTime = Date.now();
50
54
  }
51
55
  start() {
52
56
  this._startTime = Date.now();
53
57
  }
54
- /** Hook logging into undici response events */
55
- log(response) {
56
- const contentLengthHeader = response.headers["content-length"];
57
- const contentLength = contentLengthHeader
58
- ? parseInt(contentLengthHeader, 10)
59
- : undefined;
60
- response.body.on("error", (err) => {
61
- this.logError(err);
62
- });
63
- response.body.on("end", () => {
64
- this.logResponse(response.statusCode, contentLength);
65
- });
66
- }
67
58
  /** Records a received HTTP response and writes the request log entry. */
68
59
  logResponse(statusCode, contentLength) {
69
60
  const endTime = Date.now();
@@ -96,8 +87,8 @@ export class HttpLogger {
96
87
  logStatus(parameters) {
97
88
  logger.info({
98
89
  method: METHOD,
99
- [WIDE_CONTEXT.CONTEXT]: this._context,
100
90
  [WIDE_CONTEXT.TRACE_ID]: this._traceId,
91
+ [WIDE_CONTEXT.LOGGING.CONTEXT]: this._context,
101
92
  [WIDE_CONTEXT.HTTP_KEYS.URL]: this._url,
102
93
  [WIDE_CONTEXT.HTTP_KEYS.URL_TEMPLATE]: this._urlTemplate,
103
94
  [WIDE_CONTEXT.HTTP_KEYS.ERROR_TYPE]: parameters.errorType,
@@ -1,6 +1,8 @@
1
1
  export declare const WIDE_CONTEXT: {
2
2
  readonly TRACE_ID: "customTrace_id";
3
- readonly CONTEXT: "customContext";
3
+ readonly LOGGING: {
4
+ readonly CONTEXT: "customLogging.context";
5
+ };
4
6
  readonly HTTP_KEYS: {
5
7
  readonly DURATION: "customHttp.client.request.duration";
6
8
  readonly ERROR_TYPE: "customRequest.error.type";
@@ -1,6 +1,8 @@
1
1
  export const WIDE_CONTEXT = {
2
2
  TRACE_ID: "customTrace_id",
3
- CONTEXT: "customContext",
3
+ LOGGING: {
4
+ CONTEXT: "customLogging.context",
5
+ },
4
6
  HTTP_KEYS: {
5
7
  DURATION: "customHttp.client.request.duration",
6
8
  ERROR_TYPE: "customRequest.error.type",
@@ -1,6 +1,71 @@
1
1
  import type { JsonSchema, Model, RequestValidator, RestApi } from "aws-cdk-lib/aws-apigateway";
2
+ import type { ZodType } from "zod";
2
3
  import type { ModelWithReference } from "../aws/types/model-with-reference.js";
3
4
  type ModelReferenceUrl = `https://apigateway.amazonaws.com/restapis/${string}/models/${string}`;
5
+ type JsonSchemaWithNullable = JsonSchema & {
6
+ nullable?: boolean;
7
+ };
8
+ /**
9
+ * Converts nullable fields in an OpenAPI 3.0 JSON Schema to a form accepted by
10
+ * API Gateway model schemas.
11
+ *
12
+ * API Gateway rejects the OpenAPI 3.0 `nullable` keyword. Importing a model
13
+ * with it fails with errors such as "ArrayNode cannot be cast to TextNode".
14
+ * This input is not accepted:
15
+ *
16
+ * ```json
17
+ * { "type": "string", "nullable": true }
18
+ * ```
19
+ *
20
+ * This function removes `nullable` and expresses null as an alternative,
21
+ * which API Gateway accepts:
22
+ *
23
+ * ```json
24
+ * { "oneOf": [{ "type": "string" }, { "type": "null" }] }
25
+ * ```
26
+ *
27
+ * If the nullable schema is already an `anyOf` union, the null alternative is
28
+ * added to it. If it has no `type` at all (for example `allOf` or a plain
29
+ * reference), the whole schema is wrapped in an `anyOf` so that null stays
30
+ * allowed. The conversion is applied recursively to nested schemas. Field
31
+ * names and literal values such as defaults are left untouched.
32
+ *
33
+ * Limitation: when a nullable schema is wrapped, only references to
34
+ * `#/definitions/...` stay valid. If the schema contains local references to
35
+ * other locations, such as `#/properties/...`, an error is thrown instead of
36
+ * producing a model with broken references. Zod output never contains such
37
+ * references, so this only matters for hand-written schemas.
38
+ */
39
+ export declare function convertJsonSchemaNullableToOneOfDeep(schema: JsonSchemaWithNullable): JsonSchemaWithNullable;
40
+ /**
41
+ * Creates a JSON Schema that can be used as an API Gateway model from a Zod schema.
42
+ *
43
+ * API Gateway does not accept Zod's default nullable output or regex patterns in
44
+ * model schemas. This helper keeps nullable values as `oneOf` alternatives and
45
+ * removes the `pattern` keyword that API Gateway cannot import. Field names and
46
+ * literal values are not touched, so a field may safely be named for example
47
+ * "pattern" or "nullable".
48
+ *
49
+ * For example, this Zod schema:
50
+ *
51
+ * ```ts
52
+ * z.object({ reason: z.string().nullable() });
53
+ * ```
54
+ *
55
+ * becomes this API Gateway schema:
56
+ *
57
+ * ```json
58
+ * {
59
+ * "type": "object",
60
+ * "properties": {
61
+ * "reason": {
62
+ * "oneOf": [{ "type": "string" }, { "type": "null" }]
63
+ * }
64
+ * }
65
+ * }
66
+ * ```
67
+ */
68
+ export declare function toApiGatewayJsonSchema(schema: ZodType): JsonSchema;
4
69
  /**
5
70
  * Get a reference to an OpenAPI model object in a REST API.
6
71
  * Can be used to supply a reference to properties of a GeoJSON feature.
@@ -1,4 +1,233 @@
1
1
  import { JsonSchemaType, JsonSchemaVersion } from "aws-cdk-lib/aws-apigateway";
2
+ import { toJSONSchema } from "zod";
3
+ function isObject(value) {
4
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5
+ }
6
+ // Keywords whose value is a map from a name to a schema. The names are data
7
+ // (for example field names) and must not be changed, only the schema values.
8
+ // A dependencies value can also be a string array, which is left unchanged.
9
+ const SCHEMA_MAP_KEYWORDS = [
10
+ "properties",
11
+ "patternProperties",
12
+ "definitions",
13
+ "dependencies",
14
+ ];
15
+ // Keywords whose value is a list of schemas.
16
+ const SCHEMA_LIST_KEYWORDS = ["oneOf", "anyOf", "allOf"];
17
+ // Keywords whose value is a single schema.
18
+ const SCHEMA_KEYWORDS = [
19
+ "items",
20
+ "additionalProperties",
21
+ "additionalItems",
22
+ "contains",
23
+ "propertyNames",
24
+ "not",
25
+ ];
26
+ /**
27
+ * Walks a JSON Schema and applies the transform to every schema object,
28
+ * starting from the innermost ones. Only values of known schema keywords are
29
+ * treated as schemas. Everything else, such as field names in `properties`
30
+ * and literal values like `default`, is left untouched.
31
+ */
32
+ function transformSchemaDeep(schema, transform) {
33
+ if (!isObject(schema)) {
34
+ return schema;
35
+ }
36
+ const result = {};
37
+ for (const [key, value] of Object.entries(schema)) {
38
+ if (SCHEMA_MAP_KEYWORDS.includes(key) && isObject(value)) {
39
+ result[key] = Object.fromEntries(Object.entries(value).map(([name, subSchema]) => [
40
+ name,
41
+ transformSchemaDeep(subSchema, transform),
42
+ ]));
43
+ }
44
+ else if (SCHEMA_LIST_KEYWORDS.includes(key) && Array.isArray(value)) {
45
+ result[key] = value.map((item) => transformSchemaDeep(item, transform));
46
+ }
47
+ else if (key === "items" && Array.isArray(value)) {
48
+ result[key] = value.map((item) => transformSchemaDeep(item, transform));
49
+ }
50
+ else if (SCHEMA_KEYWORDS.includes(key) && isObject(value)) {
51
+ result[key] = transformSchemaDeep(value, transform);
52
+ }
53
+ else {
54
+ result[key] = value;
55
+ }
56
+ }
57
+ return transform(result);
58
+ }
59
+ /**
60
+ * Collects all local reference values ("#/...") from a schema. Walks only
61
+ * known schema keywords, so references inside literal values such as defaults
62
+ * or enums are not collected. Both the CDK property name "ref" and the raw
63
+ * JSON Schema keyword "$ref" are checked.
64
+ */
65
+ function findLocalReferences(schema) {
66
+ if (!isObject(schema)) {
67
+ return [];
68
+ }
69
+ const references = [];
70
+ for (const [key, value] of Object.entries(schema)) {
71
+ if ((key === "ref" || key === "$ref") &&
72
+ typeof value === "string" &&
73
+ value.startsWith("#/")) {
74
+ references.push(value);
75
+ }
76
+ else if (SCHEMA_MAP_KEYWORDS.includes(key) && isObject(value)) {
77
+ for (const subSchema of Object.values(value)) {
78
+ references.push(...findLocalReferences(subSchema));
79
+ }
80
+ }
81
+ else if ((SCHEMA_LIST_KEYWORDS.includes(key) || key === "items") &&
82
+ Array.isArray(value)) {
83
+ for (const item of value) {
84
+ references.push(...findLocalReferences(item));
85
+ }
86
+ }
87
+ else if (SCHEMA_KEYWORDS.includes(key) && isObject(value)) {
88
+ references.push(...findLocalReferences(value));
89
+ }
90
+ }
91
+ return references;
92
+ }
93
+ /**
94
+ * Wraps a schema and a null alternative into a union. Definitions are kept at
95
+ * the root, otherwise local references like "#/definitions/X" would point to
96
+ * nothing after wrapping.
97
+ *
98
+ * Throws if the schema contains local references to other locations, such as
99
+ * "#/properties/...". Wrapping would silently break them, so failing at synth
100
+ * time is safer than deploying a broken model.
101
+ */
102
+ function wrapSchemaWithNull(schema, unionKeyword) {
103
+ const { definitions, ...rest } = schema;
104
+ const brokenReferences = findLocalReferences(rest).filter((reference) => !reference.startsWith("#/definitions/"));
105
+ if (brokenReferences.length > 0) {
106
+ throw new Error(`Cannot convert nullable schema: wrapping would break local references: ${brokenReferences.join(", ")}. Only #/definitions/ references are supported.`);
107
+ }
108
+ const wrapped = {
109
+ [unionKeyword]: [rest, { type: "null" }],
110
+ };
111
+ if (definitions !== undefined) {
112
+ // biome-ignore lint/complexity/useLiteralKeys: index signature requires bracket notation
113
+ wrapped["definitions"] = definitions;
114
+ }
115
+ return wrapped;
116
+ }
117
+ /**
118
+ * Converts one schema object with `nullable: true` to a form that accepts null.
119
+ */
120
+ function convertNullableSchema(schema) {
121
+ if (!("nullable" in schema)) {
122
+ return schema;
123
+ }
124
+ // The nullable keyword is always removed because API Gateway rejects it.
125
+ // A null alternative is added only when the value was true.
126
+ const { nullable, ...rest } = schema;
127
+ if (nullable !== true) {
128
+ return rest;
129
+ }
130
+ // A simple typed schema cannot overlap with null, so oneOf is safe.
131
+ // biome-ignore lint/complexity/useLiteralKeys: index signature requires bracket notation
132
+ if (typeof rest["type"] === "string") {
133
+ return wrapSchemaWithNull(rest, "oneOf");
134
+ }
135
+ // A standalone anyOf can take null as one more alternative. This is only
136
+ // safe when anyOf is the sole keyword: sibling keywords such as enum apply
137
+ // to the whole schema and would still reject null.
138
+ // biome-ignore lint/complexity/useLiteralKeys: index signature requires bracket notation
139
+ const anyOf = rest["anyOf"];
140
+ if (Array.isArray(anyOf) && Object.keys(rest).length === 1) {
141
+ const hasNull = anyOf.some(
142
+ // biome-ignore lint/complexity/useLiteralKeys: index signature requires bracket notation
143
+ (item) => isObject(item) && item["type"] === "null");
144
+ return hasNull ? rest : { anyOf: [...anyOf, { type: "null" }] };
145
+ }
146
+ // Everything else: oneOf, allOf, references or an empty schema. Wrap in
147
+ // anyOf instead of oneOf, because the schema itself may also accept null
148
+ // and oneOf would then reject it (oneOf requires exactly one match).
149
+ return wrapSchemaWithNull(rest, "anyOf");
150
+ }
151
+ /**
152
+ * Removes the `pattern` keyword from one schema object. Field names that
153
+ * happen to be called "pattern" live inside `properties` and are not touched.
154
+ */
155
+ function removePatternKeyword(schema) {
156
+ if (!("pattern" in schema)) {
157
+ return schema;
158
+ }
159
+ const { pattern: _pattern, ...rest } = schema;
160
+ return rest;
161
+ }
162
+ /**
163
+ * Converts nullable fields in an OpenAPI 3.0 JSON Schema to a form accepted by
164
+ * API Gateway model schemas.
165
+ *
166
+ * API Gateway rejects the OpenAPI 3.0 `nullable` keyword. Importing a model
167
+ * with it fails with errors such as "ArrayNode cannot be cast to TextNode".
168
+ * This input is not accepted:
169
+ *
170
+ * ```json
171
+ * { "type": "string", "nullable": true }
172
+ * ```
173
+ *
174
+ * This function removes `nullable` and expresses null as an alternative,
175
+ * which API Gateway accepts:
176
+ *
177
+ * ```json
178
+ * { "oneOf": [{ "type": "string" }, { "type": "null" }] }
179
+ * ```
180
+ *
181
+ * If the nullable schema is already an `anyOf` union, the null alternative is
182
+ * added to it. If it has no `type` at all (for example `allOf` or a plain
183
+ * reference), the whole schema is wrapped in an `anyOf` so that null stays
184
+ * allowed. The conversion is applied recursively to nested schemas. Field
185
+ * names and literal values such as defaults are left untouched.
186
+ *
187
+ * Limitation: when a nullable schema is wrapped, only references to
188
+ * `#/definitions/...` stay valid. If the schema contains local references to
189
+ * other locations, such as `#/properties/...`, an error is thrown instead of
190
+ * producing a model with broken references. Zod output never contains such
191
+ * references, so this only matters for hand-written schemas.
192
+ */
193
+ export function convertJsonSchemaNullableToOneOfDeep(schema) {
194
+ return transformSchemaDeep(schema, convertNullableSchema);
195
+ }
196
+ /**
197
+ * Creates a JSON Schema that can be used as an API Gateway model from a Zod schema.
198
+ *
199
+ * API Gateway does not accept Zod's default nullable output or regex patterns in
200
+ * model schemas. This helper keeps nullable values as `oneOf` alternatives and
201
+ * removes the `pattern` keyword that API Gateway cannot import. Field names and
202
+ * literal values are not touched, so a field may safely be named for example
203
+ * "pattern" or "nullable".
204
+ *
205
+ * For example, this Zod schema:
206
+ *
207
+ * ```ts
208
+ * z.object({ reason: z.string().nullable() });
209
+ * ```
210
+ *
211
+ * becomes this API Gateway schema:
212
+ *
213
+ * ```json
214
+ * {
215
+ * "type": "object",
216
+ * "properties": {
217
+ * "reason": {
218
+ * "oneOf": [{ "type": "string" }, { "type": "null" }]
219
+ * }
220
+ * }
221
+ * }
222
+ * ```
223
+ */
224
+ export function toApiGatewayJsonSchema(schema) {
225
+ const jsonSchema = toJSONSchema(schema, {
226
+ target: "openapi-3.0",
227
+ unrepresentable: "any",
228
+ });
229
+ return transformSchemaDeep(jsonSchema, (schemaObject) => convertNullableSchema(removePatternKeyword(schemaObject)));
230
+ }
2
231
  /**
3
232
  * Get a reference to an OpenAPI model object in a REST API.
4
233
  * Can be used to supply a reference to properties of a GeoJSON feature.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@digitraffic/common",
3
- "version": "2026.10.28-1",
3
+ "version": "2026.10.30-2",
4
4
  "private": false,
5
5
  "description": "",
6
6
  "repository": {
@@ -149,7 +149,7 @@
149
149
  "undici": "8.12.2",
150
150
  "velocityjs": "2.1.7",
151
151
  "vitest": "4.1.12",
152
- "zod": "4.4.3"
152
+ "zod": "4.6.7"
153
153
  },
154
154
  "peerDependencies": {
155
155
  "@aws-sdk/client-api-gateway": "3.1098.0",
@@ -169,7 +169,7 @@
169
169
  "pg-native": "3.8.0",
170
170
  "pg-promise": "12.7.0",
171
171
  "undici": "8.12.2",
172
- "zod": "4.4.3"
172
+ "zod": "4.6.7"
173
173
  },
174
174
  "engines": {
175
175
  "node": ">=24 <25"