@openstax/ts-utils 1.2.8 → 1.3.0

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 (134) hide show
  1. package/dist/cjs/assertions.d.ts +75 -0
  2. package/dist/cjs/assertions.js +74 -29
  3. package/dist/cjs/aws/ssmService.d.ts +3 -0
  4. package/dist/cjs/aws/ssmService.js +3 -0
  5. package/dist/cjs/config/awsParameterConfig.d.ts +8 -0
  6. package/dist/cjs/config/awsParameterConfig.js +8 -0
  7. package/dist/cjs/config/envConfig.d.ts +21 -0
  8. package/dist/cjs/config/envConfig.js +20 -14
  9. package/dist/cjs/config/index.d.ts +28 -0
  10. package/dist/cjs/config/index.js +3 -6
  11. package/dist/cjs/config/lambdaParameterConfig.d.ts +10 -0
  12. package/dist/cjs/config/lambdaParameterConfig.js +10 -2
  13. package/dist/cjs/config/replaceConfig.d.ts +10 -0
  14. package/dist/cjs/config/replaceConfig.js +10 -0
  15. package/dist/cjs/config/resolveConfigValue.d.ts +3 -0
  16. package/dist/cjs/config/resolveConfigValue.js +2 -2
  17. package/dist/cjs/errors.d.ts +27 -0
  18. package/dist/cjs/errors.js +29 -2
  19. package/dist/cjs/guards.d.ts +24 -0
  20. package/dist/cjs/guards.js +18 -19
  21. package/dist/cjs/middleware/apiErrorHandler.d.ts +8 -0
  22. package/dist/cjs/middleware/apiErrorHandler.js +8 -0
  23. package/dist/cjs/middleware/apiSlowResponseMiddleware.d.ts +12 -0
  24. package/dist/cjs/middleware/apiSlowResponseMiddleware.js +12 -0
  25. package/dist/cjs/middleware/lambdaCorsResponseMiddleware.d.ts +11 -1
  26. package/dist/cjs/middleware/lambdaCorsResponseMiddleware.js +11 -1
  27. package/dist/cjs/middleware/throwNotFoundMiddleware.d.ts +3 -0
  28. package/dist/cjs/middleware/throwNotFoundMiddleware.js +3 -0
  29. package/dist/cjs/middleware.d.ts +38 -0
  30. package/dist/cjs/middleware.js +26 -16
  31. package/dist/cjs/misc/hashValue.d.ts +5 -0
  32. package/dist/cjs/misc/hashValue.js +3 -4
  33. package/dist/cjs/misc/helpers.d.ts +94 -0
  34. package/dist/cjs/misc/helpers.js +52 -14
  35. package/dist/cjs/misc/merge.d.ts +18 -0
  36. package/dist/cjs/misc/merge.js +10 -3
  37. package/dist/cjs/misc/partitionSequence.d.ts +31 -0
  38. package/dist/cjs/misc/partitionSequence.js +1 -1
  39. package/dist/cjs/pagination.d.ts +28 -0
  40. package/dist/cjs/pagination.js +1 -1
  41. package/dist/cjs/routing/helpers.d.ts +45 -0
  42. package/dist/cjs/routing/helpers.js +40 -22
  43. package/dist/cjs/routing/index.d.ts +169 -0
  44. package/dist/cjs/routing/index.js +127 -45
  45. package/dist/cjs/services/apiGateway/index.d.ts +1 -0
  46. package/dist/cjs/services/apiGateway/index.js +2 -0
  47. package/dist/cjs/services/authProvider/index.d.ts +2 -1
  48. package/dist/cjs/services/authProvider/utils/decryptAndVerify.d.ts +9 -0
  49. package/dist/cjs/services/authProvider/utils/decryptAndVerify.js +9 -0
  50. package/dist/cjs/services/logger/console.d.ts +3 -0
  51. package/dist/cjs/services/logger/console.js +3 -0
  52. package/dist/cjs/services/logger/index.d.ts +25 -0
  53. package/dist/cjs/services/logger/index.js +11 -0
  54. package/dist/cjs/services/lrsGateway/attempt-utils.d.ts +7 -10
  55. package/dist/cjs/services/lrsGateway/attempt-utils.js +19 -40
  56. package/dist/cjs/tsconfig.without-specs.cjs.tsbuildinfo +1 -1
  57. package/dist/cjs/types.d.ts +21 -0
  58. package/dist/esm/assertions.d.ts +75 -0
  59. package/dist/esm/assertions.js +74 -29
  60. package/dist/esm/aws/ssmService.d.ts +3 -0
  61. package/dist/esm/aws/ssmService.js +3 -0
  62. package/dist/esm/config/awsParameterConfig.d.ts +8 -0
  63. package/dist/esm/config/awsParameterConfig.js +8 -0
  64. package/dist/esm/config/envConfig.d.ts +21 -0
  65. package/dist/esm/config/envConfig.js +20 -14
  66. package/dist/esm/config/index.d.ts +28 -0
  67. package/dist/esm/config/index.js +3 -6
  68. package/dist/esm/config/lambdaParameterConfig.d.ts +10 -0
  69. package/dist/esm/config/lambdaParameterConfig.js +10 -2
  70. package/dist/esm/config/replaceConfig.d.ts +10 -0
  71. package/dist/esm/config/replaceConfig.js +10 -0
  72. package/dist/esm/config/resolveConfigValue.d.ts +3 -0
  73. package/dist/esm/config/resolveConfigValue.js +2 -2
  74. package/dist/esm/errors.d.ts +27 -0
  75. package/dist/esm/errors.js +27 -0
  76. package/dist/esm/guards.d.ts +24 -0
  77. package/dist/esm/guards.js +18 -19
  78. package/dist/esm/middleware/apiErrorHandler.d.ts +8 -0
  79. package/dist/esm/middleware/apiErrorHandler.js +8 -0
  80. package/dist/esm/middleware/apiSlowResponseMiddleware.d.ts +12 -0
  81. package/dist/esm/middleware/apiSlowResponseMiddleware.js +12 -0
  82. package/dist/esm/middleware/lambdaCorsResponseMiddleware.d.ts +11 -1
  83. package/dist/esm/middleware/lambdaCorsResponseMiddleware.js +11 -1
  84. package/dist/esm/middleware/throwNotFoundMiddleware.d.ts +3 -0
  85. package/dist/esm/middleware/throwNotFoundMiddleware.js +3 -0
  86. package/dist/esm/middleware.d.ts +38 -0
  87. package/dist/esm/middleware.js +26 -16
  88. package/dist/esm/misc/hashValue.d.ts +5 -0
  89. package/dist/esm/misc/hashValue.js +3 -4
  90. package/dist/esm/misc/helpers.d.ts +94 -0
  91. package/dist/esm/misc/helpers.js +48 -10
  92. package/dist/esm/misc/merge.d.ts +18 -0
  93. package/dist/esm/misc/merge.js +10 -3
  94. package/dist/esm/misc/partitionSequence.d.ts +31 -0
  95. package/dist/esm/misc/partitionSequence.js +1 -1
  96. package/dist/esm/pagination.d.ts +28 -0
  97. package/dist/esm/pagination.js +1 -1
  98. package/dist/esm/routing/helpers.d.ts +45 -0
  99. package/dist/esm/routing/helpers.js +40 -22
  100. package/dist/esm/routing/index.d.ts +169 -0
  101. package/dist/esm/routing/index.js +127 -45
  102. package/dist/esm/services/apiGateway/index.d.ts +1 -0
  103. package/dist/esm/services/apiGateway/index.js +2 -0
  104. package/dist/esm/services/authProvider/index.d.ts +2 -1
  105. package/dist/esm/services/authProvider/utils/decryptAndVerify.d.ts +9 -0
  106. package/dist/esm/services/authProvider/utils/decryptAndVerify.js +9 -0
  107. package/dist/esm/services/logger/console.d.ts +3 -0
  108. package/dist/esm/services/logger/console.js +3 -0
  109. package/dist/esm/services/logger/index.d.ts +25 -0
  110. package/dist/esm/services/logger/index.js +11 -0
  111. package/dist/esm/services/lrsGateway/attempt-utils.d.ts +7 -10
  112. package/dist/esm/services/lrsGateway/attempt-utils.js +16 -35
  113. package/dist/esm/tsconfig.without-specs.esm.tsbuildinfo +1 -1
  114. package/dist/esm/types.d.ts +21 -0
  115. package/package.json +3 -2
  116. package/script/bin/copy-from-template.bash +32 -0
  117. package/script/bin/delete-stack.bash +22 -0
  118. package/script/bin/deploy.bash +41 -0
  119. package/script/bin/destroy-deployment.bash +60 -0
  120. package/script/bin/empty-bucket.bash +28 -0
  121. package/script/bin/get-arg.bash +10 -0
  122. package/script/bin/get-deployed-environments.bash +9 -0
  123. package/script/bin/get-env-param.bash +23 -0
  124. package/script/bin/get-kwarg.bash +10 -0
  125. package/script/bin/get-stack-param.bash +6 -0
  126. package/script/bin/has-flag.bash +10 -0
  127. package/script/bin/init-constants-script.bash +20 -0
  128. package/script/bin/init-params-script.bash +118 -0
  129. package/script/bin/stack-exists.bash +5 -0
  130. package/script/bin/upload-pager-duty-endpoints.bash +44 -0
  131. package/script/bin/upload-params.bash +59 -0
  132. package/script/bin/which.bash +14 -0
  133. package/script/bin-entry.bash +33 -0
  134. package/script/build.bash +21 -0
@@ -1,3 +1,34 @@
1
+ /**
2
+ * partitions a sequence based on a partition function returning {value: any; matches?: boolean}
3
+ * - if the function returns `matches` explicitly then adjacent matching elements will
4
+ * be grouped and the predicate value in the result will be from the last item in the group
5
+ * - if the function returns only a value then matching will be evaluated based on the deep
6
+ * equality of the value with its neighbors
7
+ *
8
+ * this is different from lodash/partition and lodash/groupBy because:
9
+ * - it preserves the order of the items, items will only be grouped if they are already adjacent
10
+ * - there can be any number of groups
11
+ * - it tells you the partition value
12
+ * - the partition value can be reduced, if you care (so you can like, partition on sequential values)
13
+ *
14
+ * simple predicate:
15
+ * returns: [[0, [1,2]], [1, [3,4,5]]]
16
+ * partitionSequence((n: number) => ({value: Math.floor(n / 3)}), [1,2,3,4,5])
17
+ *
18
+ * mutating partition:
19
+ * returns: [
20
+ * [{min: 1,max: 3}, [1,2,3]],
21
+ * [{min: 5,max: 6}, [5,6]],
22
+ * [{min: 8,max: 8}, [8]],
23
+ * ]
24
+ * partitionSequence(
25
+ * (n: number, p?: {min: number; max: number}) =>
26
+ * p && p.max + 1 === n
27
+ * ? {value: {...p, max: n}, matches: true}
28
+ * : {value: {min: n, max: n}, matches: false}
29
+ * , [1,2,3,5,6,8]
30
+ * )
31
+ */
1
32
  export declare const partitionSequence: <T, P>(getPartition: (thing: T, previous?: P | undefined) => {
2
33
  matches?: boolean | undefined;
3
34
  value: P;
@@ -1,5 +1,5 @@
1
1
  import deepEqual from 'deep-equal';
2
- /*
2
+ /**
3
3
  * partitions a sequence based on a partition function returning {value: any; matches?: boolean}
4
4
  * - if the function returns `matches` explicitly then adjacent matching elements will
5
5
  * be grouped and the predicate value in the result will be from the last item in the group
@@ -2,6 +2,26 @@ import { QueryParams, RouteMatchRecord } from './routing';
2
2
  export declare type PaginationHandler<Pa, Q extends QueryParams> = <R>(queryParams: Q, match: RouteMatchRecord<R>) => Pa & {
3
3
  getUnusedQueryParams: () => Q;
4
4
  };
5
+ /**
6
+ * helper to create middleware with the given paginator. aside from taking care of annoying to write pagination logic, these helpers also make
7
+ * sure that all item list responses have the same formatting.
8
+ *
9
+ * eg:
10
+ * const getQueryParams = getKeyValueOr('queryStringParameters', {} as QueryParams);
11
+ * const setUnusedQueryParams = putKeyValue('queryStringParameters');
12
+ *
13
+ * export const loadMorePaginationMiddleware = createPaginationMiddleware<ApiRouteRequest>()({getQueryParams, setUnusedQueryParams, paginator: loadMorePagination});
14
+ * export const pageNumberPaginationMiddleware = createPaginationMiddleware<ApiRouteRequest>()({getQueryParams, setUnusedQueryParams, paginator: pageNumberPagination});
15
+ *
16
+ * eg the pagination middleware then provides your necessary inputs (getPageToken... in this case) and formats the response:
17
+ * const result = await services.myDocumentStore.getVersions(key, services.pagination.getPageTokenNumber());
18
+ *
19
+ * if (!result) {
20
+ * throw new NotFoundError('requested item not found');
21
+ * }
22
+ *
23
+ * return apiJsonResponse(200, services.pagination.getPaginationResponse(result));
24
+ */
5
25
  export declare const createPaginationMiddleware: <Ri, Q extends QueryParams = {
6
26
  [key: string]: string | undefined;
7
27
  }, R = any>() => <Pa>({ getQueryParams, setUnusedQueryParams, paginator }: {
@@ -29,6 +49,10 @@ export declare const loadMorePagination: <R, Q extends QueryParams>(queryParams:
29
49
  };
30
50
  };
31
51
  };
52
+ /**
53
+ * if you're writing a data loader, this is what you need to return to be compatible with the loadMore style paginator.
54
+ * this is how the response formatter knows the token for the next page to put in the response metadata.
55
+ * */
32
56
  export interface LoadMorePaginationResultInput<T> {
33
57
  items: T[];
34
58
  nextPageToken: string | number | undefined;
@@ -54,6 +78,10 @@ export declare const pageNumberPagination: <R, Q extends QueryParams>(queryParam
54
78
  };
55
79
  };
56
80
  };
81
+ /**
82
+ * if you're writing a data loader, this is what you need to return to be compatible with the pageNumber style paginator.
83
+ * this is how the response formatter knows the information to put in the response metadata.
84
+ * */
57
85
  export interface PageNumberPaginationResultInput<T> {
58
86
  items: T[];
59
87
  pageSize: number;
@@ -1,7 +1,7 @@
1
1
  import { notNaN } from './assertions';
2
2
  import { InvalidRequestError } from './errors';
3
3
  import { renderAnyRouteUrl } from './routing';
4
- /*
4
+ /**
5
5
  * helper to create middleware with the given paginator. aside from taking care of annoying to write pagination logic, these helpers also make
6
6
  * sure that all item list responses have the same formatting.
7
7
  *
@@ -1,10 +1,55 @@
1
1
  import type { HttpHeaders } from '.';
2
+ /**
3
+ * Get the value of a header, case insensitive; note if there are multiple headers of the same
4
+ * value, this only returns the first value
5
+ *
6
+ * @param headers
7
+ * @param name the name of the header, case ignored
8
+ */
2
9
  export declare const getHeader: (headers: HttpHeaders, name: string) => string | undefined;
10
+ /**
11
+ * Gets the body of a request
12
+ * @param request
13
+ * @throws InvalidRequestError if the content type is not application/json or not parsable
14
+ */
3
15
  export declare const getRequestBody: (request: {
4
16
  headers: HttpHeaders;
5
17
  body?: string | undefined;
6
18
  }) => any;
19
+ /**
20
+ * stub validator because writing validators is annoying
21
+ */
7
22
  export declare const unsafePayloadValidator: <T>() => (input: any) => input is T;
23
+ /**
24
+ * Middleware that validates the request payload and adds it to the middleware (with key `payload`)
25
+ * so it can be accessed downstream.
26
+ *
27
+ * This middleware accomplishes a few things:
28
+ * - establishes type of payload for route body logic
29
+ * - validates the payload for route logic
30
+ * - establishes type of payload for client logic calling this route
31
+ *
32
+ * @param validator a guard function that takes the request payload and returns true if it is valid,
33
+ * narrowing the type of the payload to the correct type
34
+ * @throws InvalidRequestError if the payload is not valid
35
+ *
36
+ * @example
37
+ * export const exampleRoute = createRoute({
38
+ * name: 'exampleRoute', method: METHOD.POST, path: '/example/:id',
39
+ * requestServiceProvider: composeServiceMiddleware(
40
+ * // here we are adding to previously composed middleware
41
+ * requestServiceProvider,
42
+ * requestPayloadProvider(validatePayload)
43
+ * )},
44
+ * async(params: {id: string}, services) => {
45
+ * const result = await services.myDocumentStore.putItem({
46
+ * ...services.payload,
47
+ * id: params.id,
48
+ * });
49
+ * return apiJsonResponse(201, result);
50
+ * }
51
+ * );
52
+ */
8
53
  export declare const requestPayloadProvider: <T>(validator: (input: any) => input is T) => () => <M extends {
9
54
  request: Parameters<typeof getRequestBody>[0];
10
55
  }>(requestServices: M) => M & {
@@ -1,8 +1,13 @@
1
1
  import { assertErrorInstanceOf } from '../assertions';
2
2
  import { InvalidRequestError } from '../errors';
3
3
  import { isPlainObject } from '../guards';
4
- // use this to support case insensitive header keys
5
- // note if there are multiple headers of the same value, this only returns the first value
4
+ /**
5
+ * Get the value of a header, case insensitive; note if there are multiple headers of the same
6
+ * value, this only returns the first value
7
+ *
8
+ * @param headers
9
+ * @param name the name of the header, case ignored
10
+ */
6
11
  export const getHeader = (headers, name) => {
7
12
  const key = Object.keys(headers).find(header => header.toLowerCase() === name.toLowerCase());
8
13
  const value = key ? headers[key] : undefined;
@@ -10,6 +15,11 @@ export const getHeader = (headers, name) => {
10
15
  ? value[0]
11
16
  : value;
12
17
  };
18
+ /**
19
+ * Gets the body of a request
20
+ * @param request
21
+ * @throws InvalidRequestError if the content type is not application/json or not parsable
22
+ */
13
23
  export const getRequestBody = (request) => {
14
24
  if (getHeader(request.headers, 'content-type') !== 'application/json') {
15
25
  throw new InvalidRequestError('unknown content type: ' + getHeader(request.headers, 'content-type'));
@@ -27,34 +37,42 @@ export const getRequestBody = (request) => {
27
37
  }
28
38
  };
29
39
  /* utils and middleware for loading request payload (must follow this pattern for `PayloadForRoute` to work) */
30
- // stub validator because writing validators is annoying
40
+ /**
41
+ * stub validator because writing validators is annoying
42
+ */
31
43
  export const unsafePayloadValidator = () => (input) => {
32
44
  return isPlainObject(input) && Object.keys(input).length > 0;
33
45
  };
34
- /*
35
- * the given validator is a guard, which provides the correct type this helper loads the body, runs the validator, throws if it isn't valid, or returns it as
36
- * the correct type if it is valid.
46
+ /**
47
+ * Middleware that validates the request payload and adds it to the middleware (with key `payload`)
48
+ * so it can be accessed downstream.
37
49
  *
38
- * this accomplishes a few things:
50
+ * This middleware accomplishes a few things:
39
51
  * - establishes type of payload for route body logic
40
52
  * - validates the payload for route logic
41
53
  * - establishes type of payload for client logic calling this route
42
54
  *
43
- * eg:
44
- * export const exampleRoute = createRoute({name: 'exampleRoute', method: METHOD.POST, path: '/example/:id',
45
- * requestServiceProvider: composeServiceMiddleware(
46
- * requestServiceProvider, // previously compiled middleware can be re-composed if you have something to add
47
- * requestPayloadProvider(validatePayload)
48
- * )},
49
- * async(params: {id: string}, services) => {
50
- * const result = await services.myDocumentStore.putItem({
51
- * ...services.payload,
52
- * id: params.id,
53
- * });
54
- * return apiJsonResponse(201, result);
55
- * }
56
- * );
57
- * */
55
+ * @param validator a guard function that takes the request payload and returns true if it is valid,
56
+ * narrowing the type of the payload to the correct type
57
+ * @throws InvalidRequestError if the payload is not valid
58
+ *
59
+ * @example
60
+ * export const exampleRoute = createRoute({
61
+ * name: 'exampleRoute', method: METHOD.POST, path: '/example/:id',
62
+ * requestServiceProvider: composeServiceMiddleware(
63
+ * // here we are adding to previously composed middleware
64
+ * requestServiceProvider,
65
+ * requestPayloadProvider(validatePayload)
66
+ * )},
67
+ * async(params: {id: string}, services) => {
68
+ * const result = await services.myDocumentStore.putItem({
69
+ * ...services.payload,
70
+ * id: params.id,
71
+ * });
72
+ * return apiJsonResponse(201, result);
73
+ * }
74
+ * );
75
+ */
58
76
  export const requestPayloadProvider = (validator) => () => (requestServices) => {
59
77
  const payload = getRequestBody(requestServices.request);
60
78
  // for more precise error messages, throw your own InvalidRequestError from your validator function
@@ -1,19 +1,35 @@
1
1
  import { Track } from '../profile';
2
2
  import { Logger } from '../services/logger';
3
+ /** HTTP query parameters */
3
4
  export declare type QueryParams = Record<string, string | undefined | string[] | null>;
5
+ /**
6
+ * The type for a map of string substitutions to use when building route paths, e.g. a route may
7
+ * be defined as `'/api/:id'` and then rendered as `'/api/123'` when the `id` route param is set
8
+ * to `'123'`
9
+ */
4
10
  export declare type RouteParams = {
5
11
  [key: string]: string;
6
12
  };
13
+ /** A type that is compatible with any `Route` type */
7
14
  export declare type AnyRoute<R> = R extends Route<infer N, infer P, infer Sa, infer Sr, infer Ri, infer Ro> ? Route<N, P, Sa, Sr, Ri, Ro> : never;
8
15
  export declare type AnySpecificRoute<R, Sa, Ri, Ro> = R extends Route<infer N, infer P, Sa, infer Sr, Ri, Ro> & infer E ? Route<N, P, Sa, Sr, Ri, Ro> & E : never;
16
+ /** The inferred "route output" (`Ro`) type for a given route */
9
17
  export declare type OutputForRoute<R> = R extends Route<any, any, any, any, any, infer Ro> ? Ro : never;
18
+ /** The inferred type for the params of the provided route type, `R`; may be undefined */
10
19
  export declare type ParamsForRoute<R> = R extends Route<any, infer P, any, any, any, any> ? P : never;
20
+ /** The inferred type for the request services of the provided route type, `R`. */
11
21
  export declare type RequestServicesForRoute<R> = R extends Route<any, any, any, infer Sr, any, any> ? Sr : never;
22
+ /** The type for the params of the provided route type, `R`; will be `{}` if undefined */
12
23
  export declare type ParamsForRouteOrEmpty<R> = ParamsForRoute<R> extends undefined ? {} : Exclude<ParamsForRoute<R>, undefined>;
24
+ /** derives the route match type for this route, which includes the route itself and the matching params. */
13
25
  export declare type RouteMatchRecord<R> = R extends AnyRoute<R> ? {
14
26
  route: R;
15
27
  params: ParamsForRoute<R>;
16
28
  } : never;
29
+ /**
30
+ * The conditional type for the payload for a given route, `R`. This isn't a route structure, its
31
+ * a convention based on the request middleware
32
+ */
17
33
  export declare type PayloadForRoute<R> = RequestServicesForRoute<R> extends {
18
34
  payload: any;
19
35
  } ? RequestServicesForRoute<R>['payload'] : undefined;
@@ -40,16 +56,105 @@ declare type CreateRouteConfig<Sa, Sr, Ri, N extends string, Ex> = (Sr extends u
40
56
  name: N;
41
57
  path: string;
42
58
  } & Ex;
59
+ /**
60
+ * Interface for a function that creates a route. There are two overloaded signatures, because
61
+ * sometimes typescript can't figure out the value of `Sr` between the handler and the service
62
+ * provider. Forcing it through the provider types first by putting the handler in a subsequent
63
+ * argument seems to help.
64
+ */
43
65
  export interface CreateRoute<Sa, Ri, Ex> {
44
66
  <N extends string, Ro, Sr extends unknown | undefined = undefined, P extends RouteParams | undefined = undefined>(config: CreateRouteConfig<Sa, Sr, Ri, N, Ex> & {
45
67
  handler: RouteHandler<P, Sr, Ro>;
46
68
  }): Route<N, P, Sa, Sr, Ri, Ro> & Ex;
47
69
  <N extends string, Ro, Sr extends unknown | undefined, P extends RouteParams | undefined = undefined>(config: CreateRouteConfig<Sa, Sr, Ri, N, Ex>, handler: RouteHandler<P, Sr, Ro>): Route<N, P, Sa, Sr, Ri, Ro> & Ex;
48
70
  }
71
+ /**
72
+ * Makes a createRoute function that can be used to create routes (this is a factory factory). The
73
+ * `makeCreateRoute` function is typically called once in the backend and once in the frontend to
74
+ * set the types for the resulting `createRoute` function -- that latter function is called once
75
+ * per route. E.g. for the backend, the call could look like:
76
+ *
77
+ * ```
78
+ * export const createRoute = makeCreateRoute<AppServices, ApiRouteRequest, {
79
+ * method: METHOD;
80
+ * }>();
81
+ * ```
82
+ *
83
+ * Notes:
84
+ * * The `{method: METHOD}` defines the `Ex` extension type; here, the `method` property is only
85
+ * relevant to backend routes.
86
+ * * when defining the `createRoute` method, only the request input format is defined, the output
87
+ * format is derived from the routes.
88
+ *
89
+ * When calling the resulting `createRoute` function, the only required params of the route are the
90
+ * name, path, and handler. Other params can be added to the type and then later used in the
91
+ * routeMatcher.
92
+ *
93
+ * eg when defining requestServiceProvider in line, the types have a hard time, it helps to put in another argument:
94
+ * ```
95
+ * export const exampleRoute = createRoute({
96
+ * name: 'exampleRoute', method: METHOD.GET, path: '/api/example/:key',
97
+ * requestServiceProvider: composeServiceMiddleware({
98
+ * cookieAuthMiddleware,
99
+ * documentStoreMiddleware,
100
+ * }},
101
+ * async(params: {key: string}, services) => {
102
+ * const result = await services.myDocumentStore.getItem(params.key);
103
+ *
104
+ * if (!result) {
105
+ * throw new NotFoundError('requested item not found');
106
+ * }
107
+ *
108
+ * return apiJsonResponse(200, result);
109
+ * }
110
+ * );
111
+ * ```
112
+ * eg when using a pre-existing provider variable the types work better:
113
+ * ```
114
+ * export const exampleRoute = createRoute({
115
+ * name: 'exampleRoute', method: METHOD.GET, path: '/api/example/:key',
116
+ * requestServiceProvider,
117
+ * handler: async(params: {key: string}, services) => {
118
+ * const result = await services.myDocumentStore.getItem(params.key);
119
+ *
120
+ * if (!result) {
121
+ * throw new NotFoundError('requested item not found');
122
+ * }
123
+ *
124
+ * return apiJsonResponse(200, result);
125
+ * }
126
+ * });
127
+ * ```
128
+ */
49
129
  export declare const makeCreateRoute: <Sa, Ri, Ex = {}>() => CreateRoute<Sa, Ri, Ex>;
130
+ /**
131
+ * Makes a renderRouteUrl function that can be used to render route paths (this is a factory
132
+ * factory). The returned function takes a `route`, `params`, and `query` and returns a string
133
+ * with the params and query substituted into the route path.
134
+ *
135
+ * this function is initialized using the Ru type which indicates the specific routes wired into
136
+ * the application, which means that if you try to build a url with a route which is not wired
137
+ * into the router you will get a type error. this is a feature to prevent referencing routes that
138
+ * don't exist or aren't handling requests properly.
139
+ *
140
+ * if you are making a helper function or need to render a route outside your application, you
141
+ * can use the `renderAnyRouteUrl` function
142
+ */
50
143
  export declare const makeRenderRouteUrl: <Ru extends {
51
144
  path: string;
52
145
  }>() => <R extends Ru>(route: R, params: ParamsForRoute<R>, query?: QueryParams) => string;
146
+ /**
147
+ * A pre-made result from `makeRenderRouteUrl`, this function interpolates parameter and query
148
+ * arguments into a route path.
149
+ *
150
+ * prefer using `renderRouteUrl` initialized with your applications route union
151
+ * when possible to help catch improperly initialized routes.
152
+ *
153
+ * @param route the route that has a `path` to be interpolated
154
+ * @param params the parameters to interpolate into the route path
155
+ * @param query the query parameters to add to the route path
156
+ * @returns the interpolated route path
157
+ */
53
158
  export declare const renderAnyRouteUrl: <R extends any>(route: R, params: ParamsForRoute<R>, query?: QueryParams) => string;
54
159
  declare type RequestPathExtractor<Ri> = (request: Ri) => string;
55
160
  declare type RequestLogExtractor<Ri> = (request: Ri) => JsonCompatibleStruct;
@@ -67,6 +172,36 @@ declare type RequestResponder<Sa, Ri, Ro> = {
67
172
  logger: Logger;
68
173
  }) => RoF): (request: Ri) => RoF;
69
174
  };
175
+ /**
176
+ * A factory factory for creating request responders (functions that take a request and return a
177
+ * response -- these functions let us implement Lambda `handler` functions).
178
+ *
179
+ * Use it in two steps. First, call it with the general business logic that defines routes, logs,
180
+ * errors, etc:
181
+ * ```
182
+ * const getRequestResponder = makeGetRequestResponder<
183
+ * AppServices, TRoutes, ApiRouteRequest, Promise<ApiRouteResponse>
184
+ * >() // this empty invocation helps typescript mix defined and inferred types
185
+ * ({
186
+ * routes: apiRoutes, // the route definitions
187
+ * pathExtractor, // how to get the path out of the request format
188
+ * routeMatcher, // logic for matching route (beyond path matching, optional)
189
+ * errorHandler, // any special error handling
190
+ * });
191
+ * ```
192
+ * Note here that among other things we're specifying a generic response format that the response
193
+ * and error handling middleware can use, if any routes have responses that don't adhere to this
194
+ * it'll complain about it.
195
+ *
196
+ * Next, we use the `getRequestResponder` to create a responder for a specific lambda entrypoint:
197
+ * ```
198
+ * export const handler: (request: APIGatewayProxyEventV2): Promise<ApiRouteResponse> =>
199
+ * getRequestResponder(
200
+ * lambdaServices, // the AppServices for this entrypoint
201
+ * lambdaMiddleware // environment specific response middleware (like cors)
202
+ * );
203
+ * ```
204
+ */
70
205
  export declare const makeGetRequestResponder: <Sa, Ru, Ri, Ro>() => ({ routes, pathExtractor, routeMatcher, errorHandler, logExtractor }: {
71
206
  routes: () => AnySpecificRoute<Ru, Sa, Ri, Ro>[];
72
207
  pathExtractor: RequestPathExtractor<Ri>;
@@ -74,14 +209,19 @@ export declare const makeGetRequestResponder: <Sa, Ru, Ri, Ro>() => ({ routes, p
74
209
  routeMatcher?: RequestRouteMatcher<Ri, AnySpecificRoute<Ru, Sa, Ri, Ro>> | undefined;
75
210
  errorHandler?: ((e: Error, logger: Logger) => Ro) | undefined;
76
211
  }) => RequestResponder<Sa, Ri, Ro>;
212
+ /** HTTP Headers */
77
213
  export declare type HttpHeaders = {
78
214
  [key: string]: string | undefined | string[];
79
215
  };
216
+ /** A type that works in JSON */
80
217
  export declare type JsonCompatibleValue = string | number | null | undefined | boolean;
218
+ /** A JSON array type */
81
219
  export declare type JsonCompatibleArray = Array<JsonCompatibleValue | JsonCompatibleStruct | JsonCompatibleStruct>;
220
+ /** A JSON object type */
82
221
  export declare type JsonCompatibleStruct = {
83
222
  [key: string]: JsonCompatibleStruct | JsonCompatibleValue | JsonCompatibleArray;
84
223
  };
224
+ /** The type for an API response */
85
225
  export declare type ApiResponse<S extends number, T> = {
86
226
  isBase64Encoded?: boolean;
87
227
  statusCode: S;
@@ -91,9 +231,38 @@ export declare type ApiResponse<S extends number, T> = {
91
231
  [key: string]: string;
92
232
  };
93
233
  };
234
+ /**
235
+ * Returns a JSON response. Handles serializing the data to JSON and setting the content-type header.
236
+ * @param statusCode e.g. 201
237
+ * @param data the object to be serialized to JSON
238
+ * @param headers HTTP headers
239
+ * @example
240
+ * return apiJsonResponse(
241
+ * 200, {
242
+ * message: "hello, world!",
243
+ * foo: "bar",
244
+ * },
245
+ * { 'X-Frame-Options': 'DENY' }
246
+ * );
247
+ */
94
248
  export declare const apiJsonResponse: <S extends number, T extends JsonCompatibleStruct>(statusCode: S, data: T, headers?: HttpHeaders | undefined) => ApiResponse<S, T>;
249
+ /**
250
+ * Returns a plain text response. Handles setting the content-type header.
251
+ * @param statusCode e.g. 201
252
+ * @param data some string
253
+ * @param headers HTTP headers
254
+ * @example return apiTextResponse(200, 'some text')
255
+ */
95
256
  export declare const apiTextResponse: <S extends number>(statusCode: S, data: string, headers?: HttpHeaders | undefined) => ApiResponse<S, string>;
257
+ /**
258
+ * Returns an HTML response. Handles setting the content-type header.
259
+ * @param statusCode e.g. 201
260
+ * @param data some string
261
+ * @param headers HTTP headers
262
+ * @example return apiHtmlResponse(200, '<b>some text</b>')
263
+ */
96
264
  export declare const apiHtmlResponse: <S extends number>(statusCode: S, data: string, headers?: HttpHeaders | undefined) => ApiResponse<S, string>;
265
+ /** HTTP method enum */
97
266
  export declare enum METHOD {
98
267
  GET = "GET",
99
268
  HEAD = "HEAD",