@privy-io/api-base 0.2.0-beta-20230925232220

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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2022-2023 Horkos, Inc.
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ import{z as D}from"zod";var E=(t=>(t.APPLICATION_JSON="application/json",t))(E||{});var u=(e=>(e[e.OK=200]="OK",e[e.CREATED=201]="CREATED",e[e.NO_CONTENT=204]="NO_CONTENT",e[e.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",e[e.MOVED_TEMPORARILY=302]="MOVED_TEMPORARILY",e[e.NOT_MODIFIED=304]="NOT_MODIFIED",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.NOT_AUTHENTICATED=401]="NOT_AUTHENTICATED",e[e.FORBIDDEN=403]="FORBIDDEN",e[e.NOT_FOUND=404]="NOT_FOUND",e[e.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",e[e.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",e[e.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",e[e.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",e[e.BAD_GATEWAY=502]="BAD_GATEWAY",e[e.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",e[e.GATEWAY_TIME_OUT=504]="GATEWAY_TIME_OUT",e[e.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",e))(u||{});import{z as _}from"zod";var c=(n=>(n.MISSING_OR_INVALID_PRIVY_APP_ID="missing_or_invalid_privy_app_id",n.MISSING_OR_INVALID_PRIVY_ACCOUNT_ID="missing_or_invalid_privy_account_id",n.MISSING_OR_INVALID_TOKEN="missing_or_invalid_token",n.INVALID_DATA="invalid_data",n.INVALID_CREDENTIALS="invalid_credentials",n.LINKED_TO_ANOTHER_USER="linked_to_another_user",n.ALLOWLIST_REJECTED="allowlist_rejected",n.CANNOT_UNLINK_EMBEDDED_WALLET="cannot_unlink_embedded_wallet",n.CANNOT_UNLINK_SOLE_ACCOUNT="cannot_unlink_sole_account",n.CANNOT_LINK_MORE_OF_TYPE="cannot_link_more_of_type",n.LINKED_ACCOUNT_NOT_FOUND="linked_account_not_found",n.TOO_MANY_REQUESTS="too_many_requests",n.INVALID_ORIGIN="invalid_origin",n.MISSING_ORIGIN="missing_origin",n.TOKEN_ALREADY_USED="token_already_used",n.ALREADY_LOGGED_OUT="already_logged_out",n.NOT_SUPPORTED="not_supported",n.USER_UNSUBSCRIBED="user_unsubscribed",n.MAX_APPS_REACHED="max_apps_reached",n.DEVICE_REVOKED="device_revoked",n.WALLET_PASSWORD_EXISTS="wallet_password_exists",n))(c||{});var h=_.object({error:_.string(),cause:_.string().optional(),code:_.nativeEnum(c).optional()});var i=class{#n;#r;#e;#a;#p;#o;#t;#s;constructor({name:t,method:s,path:p,expectedStatusCode:T=200,pathParamsSchema:o,pathQuerySchema:I,bodySchema:l,responseSchema:f}){this.#n=t,this.#r=s,this.#e=p,this.#a=T,this.#p=o,this.#o=I,this.#t=l,this.#s=f}get name(){return this.#n}get method(){return this.#r}get path(){return this.#e}get expectedStatusCode(){return this.#a}parsePathParamsOrThrow(t){return this.#p?.parse(t)}parsePathQueryOrThrow(t){return this.#o?.parse(t)}parseBodyOrThrow(t){return this.#t.parse(t)}parseResponseOrThrow(t,s){let p=this.#s[s];if(!p)throw new Error(`No schema found for status code ${s}`);return p.content["application/json"].schema.parse(t)}static toJSONResponseSchema(t,s){return{content:{"application/json":{schema:t}},description:s}}toSpec(){return{[this.method]:{path:this.#e,request:{body:{content:{"application/json":{schema:this.#t}}}},responses:{[400]:i.toJSONResponseSchema(h,"Invalid Input"),[500]:i.toJSONResponseSchema(h,"Server Error"),...this.#s}}}}constructPath({params:t}){let s=this.path;return t!==void 0?(Object.keys(t).forEach(p=>{let T=t[p];s=s.replace(`:${p}`,`${T}`)}),`${s}`):s}};var r=class extends Error{status;code;constructor(t,s,p){super(s),this.code=p,this.status=t}toString(){return`${this.constructor.name}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}},y=class extends r{constructor(t,s){super(400,t,s)}},m=class extends r{constructor(t,s){super(401,t,s)}},O=class extends m{constructor(t){super(t||"User is not allowed to login to this app.","allowlist_rejected")}},N=class extends r{constructor(t,s){super(403,t,s)}},d=class extends r{constructor(t){super(404,t)}},P=class extends r{constructor(t){super(415,t)}},x=class extends r{constructor(t,s){super(422,t,s)}},R=class extends r{constructor(t){super(429,t||"Too many requests. Please wait to try again.","too_many_requests")}},A=class extends r{constructor(t){super(500,t||"Service unavailable.")}};var g=(o=>(o.GET="get",o.POST="post",o.PATCH="patch",o.DELETE="delete",o.PUT="put",o))(g||{});var S=(s=>(s.HTTP="http:",s.HTTPS="https:",s))(S||{});export{h as APIError,O as AllowlistRejectedError,N as ForbiddenError,r as HttpError,g as HttpMethod,A as InternalServerError,y as InvalidInputError,x as LegacyInvalidInputError,E as MimeType,d as NotFoundError,c as PrivyErrorCode,S as Protocols,i as Route,u as StatusCode,R as TooManyRequestsError,m as UnauthorizedError,P as UnsupportedMediaType,D as z};
@@ -0,0 +1,453 @@
1
+ import * as zod from 'zod';
2
+ import { ZodType, ZodCatch, z } from 'zod';
3
+ export { z } from 'zod';
4
+
5
+ declare enum HttpMethod {
6
+ GET = "get",
7
+ POST = "post",
8
+ PATCH = "patch",
9
+ DELETE = "delete",
10
+ PUT = "put"
11
+ }
12
+
13
+ declare enum MimeType {
14
+ APPLICATION_JSON = "application/json"
15
+ }
16
+
17
+ declare enum StatusCode {
18
+ OK = 200,
19
+ CREATED = 201,
20
+ NO_CONTENT = 204,
21
+ MOVED_PERMANENTLY = 301,
22
+ MOVED_TEMPORARILY = 302,
23
+ NOT_MODIFIED = 304,
24
+ BAD_REQUEST = 400,
25
+ NOT_AUTHENTICATED = 401,
26
+ FORBIDDEN = 403,
27
+ NOT_FOUND = 404,
28
+ METHOD_NOT_ALLOWED = 405,
29
+ UNSUPPORTED_MEDIA_TYPE = 415,
30
+ UNPROCESSABLE_CONTENT = 422,
31
+ TOO_MANY_REQUESTS = 429,
32
+ INTERNAL_SERVER_ERROR = 500,
33
+ NOT_IMPLEMENTED = 501,
34
+ BAD_GATEWAY = 502,
35
+ SERVICE_UNAVAILABLE = 503,
36
+ GATEWAY_TIME_OUT = 504,
37
+ HTTP_VERSION_NOT_SUPPORTED = 505
38
+ }
39
+
40
+ type PathParam = string | number;
41
+ /**
42
+ * PathParams is a recursive type that parses a path string and creates an object type
43
+ * where each property is a path parameter and its value is a PathParam type.
44
+ */
45
+ type PathParams<T extends string> = T extends `${infer _Start}:${infer Param}/${infer Rest}` ? {
46
+ [K in Param | keyof PathParams<Rest>]: PathParam;
47
+ } : T extends `${infer _Start}:${infer Param}` ? {
48
+ [K in Param]: PathParam;
49
+ } : Record<string, never>;
50
+ type TBaseQuery = {
51
+ [name: string]: string | number | boolean | undefined;
52
+ };
53
+ type TBaseBody = unknown;
54
+ type TBaseResponse = unknown | ArrayBuffer;
55
+ /**
56
+ * TBaseResponseStatusCodeMap is a type that maps each StatusCode to a TBaseResponse.
57
+ * It is used to define the expected response type for each possible HTTP status code.
58
+ * @template K - A key that extends StatusCode.
59
+ */
60
+ type TBaseResponseStatusCodeMap = {
61
+ [K in StatusCode]: TBaseResponse;
62
+ };
63
+ /**
64
+ * ZodTypeOrCatch is a type that can either be a ZodCatch of a ZodType or a ZodType itself.
65
+ * It is used to define the type of a value that can either be a valid ZodType or a ZodCatch, which represents an error.
66
+ * @template T - The type that the ZodType or ZodCatch is expected to validate.
67
+ */
68
+ type ZodTypeOrCatch<T> = ZodCatch<ZodType<T>> | ZodType<T>;
69
+ /**
70
+ * Sample Usage
71
+ *
72
+ * @example
73
+ * const route = new Route({
74
+ * name: 'Test',
75
+ * method: HttpMethod.GET,
76
+ * path: '/test/:id/:s',
77
+ * pathParamsSchema: z.object({
78
+ * id: z.string(),
79
+ * s: z.string()
80
+ * }),
81
+ * pathQuerySchema: z.object({
82
+ * name: z.string()
83
+ * }),
84
+ * bodySchema: z.object({
85
+ * name: z.string()
86
+ * }),
87
+ * responseSchema: {
88
+ * [StatusCode.OK]: Route.toJSONResponseSchema(z.object({
89
+ * name: z.string()
90
+ * }), 'OK')),
91
+ * }
92
+ * });
93
+ */
94
+ /**
95
+ * The Route class is a blueprint for defining HTTP routes in an application.
96
+ * It encapsulates all the necessary details about a route such as its name, HTTP method, path, and expected response.
97
+ * It also includes schemas for validating path parameters, query parameters, request body, and response.
98
+ *
99
+ * @template Name - A string that uniquely identifies the route.
100
+ * @template Method - The HTTP method (GET, POST, PUT, DELETE, etc.) that the route responds to.
101
+ * @template Path - The URL path of the route. It can include path parameters, denoted by a colon prefix (e.g., '/user/:id').
102
+ * @template PathParamsType - An object type derived from the path string, where each property is a path parameter and its value is a PathParam type.
103
+ * @template PathQueryType - An object type representing the expected structure of the query parameters in the route. It should be a subtype of TBaseQuery.
104
+ * @template BodyType - An object type representing the expected structure of the request body. It should be a subtype of TBaseBody.
105
+ * @template ResponseType - An object type representing the expected structure of the response. It should be a subtype of TBaseResponseStatusCodeMap and a record of ExpectedStatusCode to TBaseResponse.
106
+ * @template ExpectedStatusCode - The expected HTTP status code of the response. It should be a StatusCode. Default is StatusCode.OK.
107
+ */
108
+ declare class Route<Name extends string, Method extends HttpMethod, Path extends string, PathParamsType extends PathParams<Path>, PathQueryType extends TBaseQuery, BodyType extends TBaseBody, ResponseType extends Partial<TBaseResponseStatusCodeMap> & Record<ExpectedStatusCode, TBaseResponse>, ExpectedStatusCode extends StatusCode = StatusCode.OK> {
109
+ #private;
110
+ /**
111
+ * Constructs a new instance of the Route class.
112
+ *
113
+ * @param {Name} params.name - The name of the route.
114
+ * @param {Method} params.method - The HTTP method of the route.
115
+ * @param {Path} params.path - The path of the route.
116
+ * @param {ExpectedStatusCode} [params.expectedStatusCode=StatusCode.OK] - The expected status code of the route.
117
+ * @param {ZodType<PathParamsType>} params.pathParamsSchema - The schema for the path parameters.
118
+ * @param {ZodType<PathQueryType>} params.pathQuerySchema - The schema for the query parameters.
119
+ * @param {ZodTypeOrCatch<BodyType>} params.bodySchema - The schema for the request body.
120
+ * @param {Object} params.responseSchema - The schema for the response.
121
+ * @param {string} params.responseSchema[K].description - The description of the response.
122
+ * @param {Object} params.responseSchema[K].content - The content of the response.
123
+ * @param {ZodType<ResponseType[K]>} params.responseSchema[K].content[MimeType.APPLICATION_JSON].schema - The schema for the response content.
124
+ */
125
+ constructor({ name, method, path, expectedStatusCode, pathParamsSchema, pathQuerySchema, bodySchema, responseSchema, }: {
126
+ name: Name;
127
+ expectedStatusCode?: ExpectedStatusCode;
128
+ method: Method;
129
+ path: Path;
130
+ pathParamsSchema: ZodType<PathParamsType>;
131
+ pathQuerySchema: ZodType<PathQueryType>;
132
+ bodySchema: ZodTypeOrCatch<BodyType>;
133
+ responseSchema: {
134
+ [K in keyof ResponseType]: {
135
+ description: string;
136
+ content: {
137
+ [MimeType.APPLICATION_JSON]: {
138
+ schema: ZodType<ResponseType[K]>;
139
+ };
140
+ };
141
+ };
142
+ };
143
+ });
144
+ /**
145
+ * Getter for the name of the route.
146
+ * @returns {Name} The name of the route.
147
+ */
148
+ get name(): Name;
149
+ /**
150
+ * Getter for the HTTP method of the route.
151
+ * @returns {Method} The HTTP method of the route.
152
+ */
153
+ get method(): Method;
154
+ /**
155
+ * Getter for the path of the route.
156
+ * @returns {Path} The path of the route.
157
+ */
158
+ get path(): Path;
159
+ /**
160
+ * Getter for the expected status code of the route.
161
+ * @returns {ExpectedStatusCode} The expected status code of the route.
162
+ */
163
+ get expectedStatusCode(): ExpectedStatusCode;
164
+ /**
165
+ * Parses the path parameters or throws an error if they are invalid.
166
+ * @param {unknown} maybePathParams - The path parameters to parse.
167
+ * @returns {PathParamsType} The parsed path parameters.
168
+ */
169
+ parsePathParamsOrThrow(maybePathParams: unknown): PathParamsType;
170
+ /**
171
+ * Parses the path query or throws an error if it is invalid.
172
+ * @param {unknown} maybePathQuery - The path query to parse.
173
+ * @returns {PathQueryType} The parsed path query.
174
+ */
175
+ parsePathQueryOrThrow(maybePathQuery: unknown): PathQueryType;
176
+ /**
177
+ * Parses the body or throws an error if it is invalid.
178
+ * @param {unknown} maybeBody - The body to parse.
179
+ * @returns {BodyType} The parsed body.
180
+ */
181
+ parseBodyOrThrow(maybeBody: unknown): BodyType;
182
+ /**
183
+ * Parses the response or throws an error if it is invalid.
184
+ * @param {unknown} maybeResponse - The response to parse.
185
+ * @param {StatusCode} statusCode - The status code of the response.
186
+ * @returns {ResponseType} The parsed response.
187
+ */
188
+ parseResponseOrThrow(maybeResponse: unknown, statusCode: StatusCode): ResponseType[StatusCode.OK] | ResponseType[StatusCode.CREATED] | ResponseType[StatusCode.NO_CONTENT] | ResponseType[StatusCode.MOVED_PERMANENTLY] | ResponseType[StatusCode.MOVED_TEMPORARILY] | ResponseType[StatusCode.NOT_MODIFIED] | ResponseType[StatusCode.BAD_REQUEST] | ResponseType[StatusCode.NOT_AUTHENTICATED] | ResponseType[StatusCode.FORBIDDEN] | ResponseType[StatusCode.NOT_FOUND] | ResponseType[StatusCode.METHOD_NOT_ALLOWED] | ResponseType[StatusCode.UNSUPPORTED_MEDIA_TYPE] | ResponseType[StatusCode.UNPROCESSABLE_CONTENT] | ResponseType[StatusCode.TOO_MANY_REQUESTS] | ResponseType[StatusCode.INTERNAL_SERVER_ERROR] | ResponseType[StatusCode.NOT_IMPLEMENTED] | ResponseType[StatusCode.BAD_GATEWAY] | ResponseType[StatusCode.SERVICE_UNAVAILABLE] | ResponseType[StatusCode.GATEWAY_TIME_OUT] | ResponseType[StatusCode.HTTP_VERSION_NOT_SUPPORTED];
189
+ /**
190
+ * Converts a Zod schema to a JSON response schema.
191
+ * @template T - The type that the Zod schema validates.
192
+ * @param {T} schema - The Zod schema to convert.
193
+ * @param {string} description - The description of the response.
194
+ * @returns {Object} The JSON response schema.
195
+ */
196
+ static toJSONResponseSchema<T extends ZodType<unknown>>(schema: T, description: string): {
197
+ readonly content: {
198
+ readonly 'application/json': {
199
+ readonly schema: T;
200
+ };
201
+ };
202
+ readonly description: string;
203
+ };
204
+ /**
205
+ * Converts the route to a specification.
206
+ * @returns {Object} The specification of the route.
207
+ */
208
+ toSpec(): {
209
+ [x: string]: {
210
+ path: Path;
211
+ request: {
212
+ body: {
213
+ content: {
214
+ 'application/json': {
215
+ schema: ZodTypeOrCatch<BodyType>;
216
+ };
217
+ };
218
+ };
219
+ };
220
+ responses: {
221
+ 400: {
222
+ readonly content: {
223
+ readonly 'application/json': {
224
+ readonly schema: zod.ZodObject<{
225
+ error: zod.ZodString;
226
+ cause: zod.ZodOptional<zod.ZodString>;
227
+ code: zod.ZodOptional<zod.ZodNativeEnum<typeof undefined>>;
228
+ }, "strip", zod.ZodTypeAny, {
229
+ error: string;
230
+ cause?: string | undefined;
231
+ code?: undefined | undefined;
232
+ }, {
233
+ error: string;
234
+ cause?: string | undefined;
235
+ code?: undefined | undefined;
236
+ }>;
237
+ };
238
+ };
239
+ readonly description: string;
240
+ };
241
+ 500: {
242
+ readonly content: {
243
+ readonly 'application/json': {
244
+ readonly schema: zod.ZodObject<{
245
+ error: zod.ZodString;
246
+ cause: zod.ZodOptional<zod.ZodString>;
247
+ code: zod.ZodOptional<zod.ZodNativeEnum<typeof undefined>>;
248
+ }, "strip", zod.ZodTypeAny, {
249
+ error: string;
250
+ cause?: string | undefined;
251
+ code?: undefined | undefined;
252
+ }, {
253
+ error: string;
254
+ cause?: string | undefined;
255
+ code?: undefined | undefined;
256
+ }>;
257
+ };
258
+ };
259
+ readonly description: string;
260
+ };
261
+ } & { [K in keyof ResponseType]: {
262
+ description: string;
263
+ content: {
264
+ "application/json": {
265
+ schema: ZodType<ResponseType[K], zod.ZodTypeDef, ResponseType[K]>;
266
+ };
267
+ };
268
+ }; };
269
+ };
270
+ };
271
+ /**
272
+ * Constructs the full path of the route by replacing path parameters with their actual values.
273
+ * This method does not take into account any query parameters.
274
+ *
275
+ * @param {Object} params - An object containing the path parameters.
276
+ * @param {PathParamsType} params.params - The path parameters.
277
+ * @returns {string} The constructed path.
278
+ */
279
+ constructPath({ params }: {
280
+ params: PathParamsType;
281
+ }): string;
282
+ }
283
+ type AnyRoute = Route<any, any, any, any, any, any, any, any>;
284
+ type InferRouteTypes<T> = T extends Route<infer Name, infer Method, infer Path, infer PathParamsType, infer PathQueryType, infer BodyType, infer ResponseType, infer ExpectedStatusCode> ? {
285
+ name: Name;
286
+ method: Method;
287
+ path: Path;
288
+ pathParams: PathParamsType;
289
+ pathQuery: PathQueryType;
290
+ body: BodyType;
291
+ response: ResponseType;
292
+ expectedStatusCode: ExpectedStatusCode;
293
+ expectedResponse: ResponseType[ExpectedStatusCode];
294
+ } : never;
295
+
296
+ declare enum PrivyErrorCode {
297
+ /** The Privy app id is either not provided or not valid. Check the developer console to verify you are setting the correct value. */
298
+ MISSING_OR_INVALID_PRIVY_APP_ID = "missing_or_invalid_privy_app_id",
299
+ /** The Privy account id is either not provided or not valid. Check the developer console to verify you are setting the correct value. */
300
+ MISSING_OR_INVALID_PRIVY_ACCOUNT_ID = "missing_or_invalid_privy_account_id",
301
+ /** The refresh or access token is either not provided or not valid. */
302
+ MISSING_OR_INVALID_TOKEN = "missing_or_invalid_token",
303
+ /** The body of the request contains input that is invalid. Check the response body for detailed information. */
304
+ INVALID_DATA = "invalid_data",
305
+ /** A form of INVALID_DATA specifically when the user is trying to authenticate and did not match the provided challenge. */
306
+ INVALID_CREDENTIALS = "invalid_credentials",
307
+ /** You attempted to link an account that belongs to another user. */
308
+ LINKED_TO_ANOTHER_USER = "linked_to_another_user",
309
+ /** This app has an allowlist and the login account was not included. Either disable the allowlist or have the user try again with a different account. */
310
+ ALLOWLIST_REJECTED = "allowlist_rejected",
311
+ /** Embedded wallets cannot be unlinked */
312
+ CANNOT_UNLINK_EMBEDDED_WALLET = "cannot_unlink_embedded_wallet",
313
+ /** You are unable to unlink an account when there is only one account present. */
314
+ CANNOT_UNLINK_SOLE_ACCOUNT = "cannot_unlink_sole_account",
315
+ /** Cannot link another account of this type */
316
+ CANNOT_LINK_MORE_OF_TYPE = "cannot_link_more_of_type",
317
+ /** Linked account cannot be found. The account was either invalid or has already been unlinked. */
318
+ LINKED_ACCOUNT_NOT_FOUND = "linked_account_not_found",
319
+ /** Too many requests. Please wait to try again. */
320
+ TOO_MANY_REQUESTS = "too_many_requests",
321
+ /** Origin was expected and is invalid. */
322
+ INVALID_ORIGIN = "invalid_origin",
323
+ /** Origin was expected and is not set. */
324
+ MISSING_ORIGIN = "missing_origin",
325
+ /** Refresh token re-use detected. */
326
+ TOKEN_ALREADY_USED = "token_already_used",
327
+ /** Attempting to log out of a session that does not exist. */
328
+ ALREADY_LOGGED_OUT = "already_logged_out",
329
+ /** The value (phone number, email) that was submitted is not supported. */
330
+ NOT_SUPPORTED = "not_supported",
331
+ /** You have previously unsubscribed from the sending email/phone number. */
332
+ USER_UNSUBSCRIBED = "user_unsubscribed",
333
+ /** You have reached the maximum number of apps allowed per account. */
334
+ MAX_APPS_REACHED = "max_apps_reached",
335
+ /** You are trying to reconstruct an embedded wallet on a device that has been marked as revoked */
336
+ DEVICE_REVOKED = "device_revoked",
337
+ /** You attempted to set a password on a wallet with an existing password */
338
+ WALLET_PASSWORD_EXISTS = "wallet_password_exists"
339
+ }
340
+
341
+ type ApiError = {
342
+ error: string;
343
+ cause?: string;
344
+ code?: PrivyErrorCode;
345
+ };
346
+ declare class HttpError extends Error {
347
+ status: number;
348
+ /** Unique Privy error code. The SDK/customers should be able to use this code to programmatically */
349
+ code?: PrivyErrorCode;
350
+ constructor(status: number, message: string, code?: PrivyErrorCode);
351
+ toString(): string;
352
+ }
353
+ declare class InvalidInputError extends HttpError {
354
+ constructor(message: string, errorCode: PrivyErrorCode);
355
+ }
356
+ declare class UnauthorizedError extends HttpError {
357
+ constructor(message: string, errorCode?: PrivyErrorCode);
358
+ }
359
+ declare class AllowlistRejectedError extends UnauthorizedError {
360
+ /**
361
+ * TODO: Changing the default message will cause existing allowlist SDK checks to fail and
362
+ * should not be done until we're sure all users are off the version of the SDK that checks for
363
+ * that string.
364
+ */
365
+ constructor(message?: string);
366
+ }
367
+ declare class ForbiddenError extends HttpError {
368
+ constructor(message: string, errorCode?: PrivyErrorCode);
369
+ }
370
+ declare class NotFoundError extends HttpError {
371
+ constructor(message: string);
372
+ }
373
+ declare class UnsupportedMediaType extends HttpError {
374
+ constructor(message: string);
375
+ }
376
+ /**
377
+ * @deprecated
378
+ *
379
+ * Use InvalidInputError moving forward.
380
+ *
381
+ * In the past, we would occasionally return 422 for invalid input.
382
+ */
383
+ declare class LegacyInvalidInputError extends HttpError {
384
+ constructor(message: string, errorCode: PrivyErrorCode);
385
+ }
386
+ declare class TooManyRequestsError extends HttpError {
387
+ constructor(message?: string);
388
+ }
389
+ declare class InternalServerError extends HttpError {
390
+ constructor(message?: string);
391
+ }
392
+
393
+ declare enum Protocols {
394
+ HTTP = "http:",
395
+ HTTPS = "https:"
396
+ }
397
+
398
+ type ZodContent = {
399
+ content: {
400
+ 'application/json': {
401
+ schema: z.ZodTypeAny;
402
+ };
403
+ };
404
+ };
405
+ type OauthResponse = {
406
+ description: string;
407
+ } & ZodContent;
408
+ type Endpoint<K extends StatusCode> = {
409
+ path: string;
410
+ request: {
411
+ body: ZodContent;
412
+ };
413
+ responses: Record<K, OauthResponse>;
414
+ };
415
+ /**
416
+ * This is mostly a subset/copy of the `RouteConfig`
417
+ * from `@asteasolutions/zod-to-openapi`
418
+ * We need to create the type manually to do some TS magic
419
+ * so that `Responses<T>` below works properly
420
+ *
421
+ * Without Passing `K` explicitly from the top level down to the key
422
+ * of the `responses` property, typescript can't correctly infer
423
+ * the type of `EndpointSpec[string]['responses'][number]`
424
+ * and the whole type breaks
425
+ *
426
+ * To test this, try updating the definition of `EndpointSpec`
427
+ * remove the generics and see what happens to the `Responses` type
428
+ */
429
+ type EndpointSpec<K extends StatusCode> = Record<string, Endpoint<K>>;
430
+ type ValueOf<T> = T[keyof T];
431
+ /**
432
+ * @description Extracts all possible response types from an EndpointSpec object
433
+ * @example
434
+ * const spec = { ... } as const satisfies EndpointSpec
435
+ * type ApiResponse = Responses<typeof spec>
436
+ */
437
+ type Responses<T extends EndpointSpec<K>, K extends StatusCode = StatusCode.OK> = z.infer<ValueOf<ValueOf<T>['responses']>['content']['application/json']['schema']>;
438
+
439
+ declare const APIError: z.ZodObject<{
440
+ error: z.ZodString;
441
+ cause: z.ZodOptional<z.ZodString>;
442
+ code: z.ZodOptional<z.ZodNativeEnum<typeof PrivyErrorCode>>;
443
+ }, "strip", z.ZodTypeAny, {
444
+ error: string;
445
+ cause?: string | undefined;
446
+ code?: PrivyErrorCode | undefined;
447
+ }, {
448
+ error: string;
449
+ cause?: string | undefined;
450
+ code?: PrivyErrorCode | undefined;
451
+ }>;
452
+
453
+ export { APIError, AllowlistRejectedError, AnyRoute, ApiError, EndpointSpec, ForbiddenError, HttpError, HttpMethod, InferRouteTypes, InternalServerError, InvalidInputError, LegacyInvalidInputError, MimeType, NotFoundError, OauthResponse, PrivyErrorCode, Protocols, Responses, Route, StatusCode, TooManyRequestsError, UnauthorizedError, UnsupportedMediaType };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var E=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var B=Object.getOwnPropertyNames;var U=Object.prototype.hasOwnProperty;var M=(r,e)=>{for(var s in e)E(r,s,{get:e[s],enumerable:!0})},k=(r,e,s,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of B(e))!U.call(r,o)&&o!==s&&E(r,o,{get:()=>e[o],enumerable:!(a=b(e,o))||a.enumerable});return r};var w=r=>k(E({},"__esModule",{value:!0}),r);var K={};M(K,{APIError:()=>h,AllowlistRejectedError:()=>d,ForbiddenError:()=>P,HttpError:()=>p,HttpMethod:()=>f,InternalServerError:()=>l,InvalidInputError:()=>N,LegacyInvalidInputError:()=>A,MimeType:()=>y,NotFoundError:()=>x,PrivyErrorCode:()=>c,Protocols:()=>D,Route:()=>T,StatusCode:()=>O,TooManyRequestsError:()=>I,UnauthorizedError:()=>m,UnsupportedMediaType:()=>R,z:()=>u.z});module.exports=w(K);var u=require("zod");var y=(e=>(e.APPLICATION_JSON="application/json",e))(y||{});var O=(t=>(t[t.OK=200]="OK",t[t.CREATED=201]="CREATED",t[t.NO_CONTENT=204]="NO_CONTENT",t[t.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",t[t.MOVED_TEMPORARILY=302]="MOVED_TEMPORARILY",t[t.NOT_MODIFIED=304]="NOT_MODIFIED",t[t.BAD_REQUEST=400]="BAD_REQUEST",t[t.NOT_AUTHENTICATED=401]="NOT_AUTHENTICATED",t[t.FORBIDDEN=403]="FORBIDDEN",t[t.NOT_FOUND=404]="NOT_FOUND",t[t.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",t[t.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",t[t.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",t[t.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",t[t.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",t[t.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",t[t.BAD_GATEWAY=502]="BAD_GATEWAY",t[t.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",t[t.GATEWAY_TIME_OUT=504]="GATEWAY_TIME_OUT",t[t.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",t))(O||{});var _=require("zod");var c=(n=>(n.MISSING_OR_INVALID_PRIVY_APP_ID="missing_or_invalid_privy_app_id",n.MISSING_OR_INVALID_PRIVY_ACCOUNT_ID="missing_or_invalid_privy_account_id",n.MISSING_OR_INVALID_TOKEN="missing_or_invalid_token",n.INVALID_DATA="invalid_data",n.INVALID_CREDENTIALS="invalid_credentials",n.LINKED_TO_ANOTHER_USER="linked_to_another_user",n.ALLOWLIST_REJECTED="allowlist_rejected",n.CANNOT_UNLINK_EMBEDDED_WALLET="cannot_unlink_embedded_wallet",n.CANNOT_UNLINK_SOLE_ACCOUNT="cannot_unlink_sole_account",n.CANNOT_LINK_MORE_OF_TYPE="cannot_link_more_of_type",n.LINKED_ACCOUNT_NOT_FOUND="linked_account_not_found",n.TOO_MANY_REQUESTS="too_many_requests",n.INVALID_ORIGIN="invalid_origin",n.MISSING_ORIGIN="missing_origin",n.TOKEN_ALREADY_USED="token_already_used",n.ALREADY_LOGGED_OUT="already_logged_out",n.NOT_SUPPORTED="not_supported",n.USER_UNSUBSCRIBED="user_unsubscribed",n.MAX_APPS_REACHED="max_apps_reached",n.DEVICE_REVOKED="device_revoked",n.WALLET_PASSWORD_EXISTS="wallet_password_exists",n))(c||{});var h=_.z.object({error:_.z.string(),cause:_.z.string().optional(),code:_.z.nativeEnum(c).optional()});var T=class{#n;#r;#e;#a;#p;#o;#t;#s;constructor({name:e,method:s,path:a,expectedStatusCode:o=200,pathParamsSchema:i,pathQuerySchema:g,bodySchema:S,responseSchema:L}){this.#n=e,this.#r=s,this.#e=a,this.#a=o,this.#p=i,this.#o=g,this.#t=S,this.#s=L}get name(){return this.#n}get method(){return this.#r}get path(){return this.#e}get expectedStatusCode(){return this.#a}parsePathParamsOrThrow(e){return this.#p?.parse(e)}parsePathQueryOrThrow(e){return this.#o?.parse(e)}parseBodyOrThrow(e){return this.#t.parse(e)}parseResponseOrThrow(e,s){let a=this.#s[s];if(!a)throw new Error(`No schema found for status code ${s}`);return a.content["application/json"].schema.parse(e)}static toJSONResponseSchema(e,s){return{content:{"application/json":{schema:e}},description:s}}toSpec(){return{[this.method]:{path:this.#e,request:{body:{content:{"application/json":{schema:this.#t}}}},responses:{[400]:T.toJSONResponseSchema(h,"Invalid Input"),[500]:T.toJSONResponseSchema(h,"Server Error"),...this.#s}}}}constructPath({params:e}){let s=this.path;return e!==void 0?(Object.keys(e).forEach(a=>{let o=e[a];s=s.replace(`:${a}`,`${o}`)}),`${s}`):s}};var p=class extends Error{status;code;constructor(e,s,a){super(s),this.code=a,this.status=e}toString(){return`${this.constructor.name}: ${this.message}${this.cause?` [cause: ${this.cause}]`:""}`}},N=class extends p{constructor(e,s){super(400,e,s)}},m=class extends p{constructor(e,s){super(401,e,s)}},d=class extends m{constructor(e){super(e||"User is not allowed to login to this app.","allowlist_rejected")}},P=class extends p{constructor(e,s){super(403,e,s)}},x=class extends p{constructor(e){super(404,e)}},R=class extends p{constructor(e){super(415,e)}},A=class extends p{constructor(e,s){super(422,e,s)}},I=class extends p{constructor(e){super(429,e||"Too many requests. Please wait to try again.","too_many_requests")}},l=class extends p{constructor(e){super(500,e||"Service unavailable.")}};var f=(i=>(i.GET="get",i.POST="post",i.PATCH="patch",i.DELETE="delete",i.PUT="put",i))(f||{});var D=(s=>(s.HTTP="http:",s.HTTPS="https:",s))(D||{});0&&(module.exports={APIError,AllowlistRejectedError,ForbiddenError,HttpError,HttpMethod,InternalServerError,InvalidInputError,LegacyInvalidInputError,MimeType,NotFoundError,PrivyErrorCode,Protocols,Route,StatusCode,TooManyRequestsError,UnauthorizedError,UnsupportedMediaType,z});
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "@privy-io/api-base",
3
+ "version": "0.2.0-beta-20230925232220",
4
+ "engines": {
5
+ "npm": ">=8.0.0 <10.0.0",
6
+ "node": ">=18.0.0 <19"
7
+ },
8
+ "main": "./dist/index.js",
9
+ "module": "./dist/esm/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "typings": "./dist/index",
12
+ "exports": {
13
+ ".": {
14
+ "require": "./dist/index.js",
15
+ "import": "./dist/esm/index.js",
16
+ "types": "./dist/index.d.ts"
17
+ },
18
+ "./zod": {
19
+ "require": "./dist/index.js",
20
+ "import": "./dist/esm/index.js",
21
+ "types": "./dist/index.d.ts"
22
+ },
23
+ "./constants": {
24
+ "require": "./dist/index.js",
25
+ "import": "./dist/esm/index.js",
26
+ "types": "./dist/index.d.ts"
27
+ },
28
+ "./constants/*": {
29
+ "require": "./dist/index.js",
30
+ "import": "./dist/esm/index.js",
31
+ "types": "./dist/index.d.ts"
32
+ },
33
+ "./classes": {
34
+ "require": "./dist/index.js",
35
+ "import": "./dist/esm/index.js",
36
+ "types": "./dist/index.d.ts"
37
+ }
38
+ },
39
+ "scripts": {
40
+ "build": "npx tsup --clean --minify",
41
+ "prepublishOnly": "npm run clean && npm run build",
42
+ "clean": "rm -rf dist .turbo",
43
+ "dev": "npx tsup --watch",
44
+ "lint": "eslint ./**/*.ts && npx tsc --noEmit",
45
+ "format": "eslint ./**/*.ts --fix"
46
+ },
47
+ "dependencies": {
48
+ "zod": "^3.21.4"
49
+ },
50
+ "devDependencies": {
51
+ "@privy-io/tsconfig": "*",
52
+ "@privy-io/eslint-config-custom": "*",
53
+ "tsup": "^6.2.3",
54
+ "typescript": "~5.0.4"
55
+ },
56
+ "files": [
57
+ "dist/**/*",
58
+ "LICENSE",
59
+ "README.md"
60
+ ],
61
+ "publishConfig": {
62
+ "access": "public"
63
+ }
64
+ }