@gcmdev/faxios 0.1.0 → 0.2.1

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 (210) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +40 -1774
  3. package/dist/index.d.ts +9 -6
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js.map +1 -1
  6. package/dist/lib/adapters/fetch-helpers.d.ts +1 -0
  7. package/dist/lib/adapters/fetch-helpers.d.ts.map +1 -0
  8. package/dist/lib/adapters/fetch.d.ts +1 -0
  9. package/dist/lib/adapters/fetch.d.ts.map +1 -0
  10. package/dist/lib/adapters/fetch.js +23 -3
  11. package/dist/lib/adapters/fetch.js.map +1 -1
  12. package/dist/lib/cancel/CanceledError.d.ts +1 -0
  13. package/dist/lib/cancel/CanceledError.d.ts.map +1 -0
  14. package/dist/lib/cancel/isCancel.d.ts +3 -1
  15. package/dist/lib/cancel/isCancel.d.ts.map +1 -0
  16. package/dist/lib/cancel/isCancel.js +3 -0
  17. package/dist/lib/cancel/isCancel.js.map +1 -1
  18. package/dist/lib/core/Faxios.d.ts +6 -17
  19. package/dist/lib/core/Faxios.d.ts.map +1 -0
  20. package/dist/lib/core/Faxios.js +144 -76
  21. package/dist/lib/core/Faxios.js.map +1 -1
  22. package/dist/lib/core/FaxiosError.d.ts +19 -6
  23. package/dist/lib/core/FaxiosError.d.ts.map +1 -0
  24. package/dist/lib/core/FaxiosError.js +16 -1
  25. package/dist/lib/core/FaxiosError.js.map +1 -1
  26. package/dist/lib/core/FaxiosHeaders.d.ts +12 -8
  27. package/dist/lib/core/FaxiosHeaders.d.ts.map +1 -0
  28. package/dist/lib/core/FaxiosHeaders.js +1 -0
  29. package/dist/lib/core/FaxiosHeaders.js.map +1 -1
  30. package/dist/lib/core/buildFullPath.d.ts +1 -0
  31. package/dist/lib/core/buildFullPath.d.ts.map +1 -0
  32. package/dist/lib/core/define.d.ts +19 -2
  33. package/dist/lib/core/define.d.ts.map +1 -0
  34. package/dist/lib/core/define.js.map +1 -1
  35. package/dist/lib/core/dispatchRequest.d.ts +1 -0
  36. package/dist/lib/core/dispatchRequest.d.ts.map +1 -0
  37. package/dist/lib/core/dispatchRequest.js +4 -0
  38. package/dist/lib/core/dispatchRequest.js.map +1 -1
  39. package/dist/lib/core/mergeConfig.d.ts +1 -0
  40. package/dist/lib/core/mergeConfig.d.ts.map +1 -0
  41. package/dist/lib/core/prepareRequest.d.ts +1 -0
  42. package/dist/lib/core/prepareRequest.d.ts.map +1 -0
  43. package/dist/lib/core/prepareRequest.js +1 -20
  44. package/dist/lib/core/prepareRequest.js.map +1 -1
  45. package/dist/lib/core/route.d.ts +11 -2
  46. package/dist/lib/core/route.d.ts.map +1 -0
  47. package/dist/lib/core/route.js.map +1 -1
  48. package/dist/lib/core/settle.d.ts +1 -0
  49. package/dist/lib/core/settle.d.ts.map +1 -0
  50. package/dist/lib/core/transformData.d.ts +1 -0
  51. package/dist/lib/core/transformData.d.ts.map +1 -0
  52. package/dist/lib/core/validateSchema.d.ts +1 -0
  53. package/dist/lib/core/validateSchema.d.ts.map +1 -0
  54. package/dist/lib/defaults/index.d.ts +1 -0
  55. package/dist/lib/defaults/index.d.ts.map +1 -0
  56. package/dist/lib/defaults/index.js +3 -3
  57. package/dist/lib/defaults/index.js.map +1 -1
  58. package/dist/lib/defaults/transitional.d.ts +1 -1
  59. package/dist/lib/defaults/transitional.d.ts.map +1 -0
  60. package/dist/lib/defaults/transitional.js +0 -1
  61. package/dist/lib/defaults/transitional.js.map +1 -1
  62. package/dist/lib/env/data.d.ts +2 -1
  63. package/dist/lib/env/data.d.ts.map +1 -0
  64. package/dist/lib/env/data.js +1 -1
  65. package/dist/lib/env/data.js.map +1 -1
  66. package/dist/lib/faxios.d.ts +115 -48
  67. package/dist/lib/faxios.d.ts.map +1 -0
  68. package/dist/lib/faxios.js +14 -2
  69. package/dist/lib/faxios.js.map +1 -1
  70. package/dist/lib/helpers/FaxiosURLSearchParams.d.ts +3 -1
  71. package/dist/lib/helpers/FaxiosURLSearchParams.d.ts.map +1 -0
  72. package/dist/lib/helpers/FaxiosURLSearchParams.js.map +1 -1
  73. package/dist/lib/helpers/HttpStatusCode.d.ts +1 -0
  74. package/dist/lib/helpers/HttpStatusCode.d.ts.map +1 -0
  75. package/dist/lib/helpers/buildURL.d.ts +1 -0
  76. package/dist/lib/helpers/buildURL.d.ts.map +1 -0
  77. package/dist/lib/helpers/buildURL.js +7 -1
  78. package/dist/lib/helpers/buildURL.js.map +1 -1
  79. package/dist/lib/helpers/cloneConfig.d.ts +4 -0
  80. package/dist/lib/helpers/cloneConfig.d.ts.map +1 -0
  81. package/dist/lib/helpers/cloneConfig.js +21 -0
  82. package/dist/lib/helpers/cloneConfig.js.map +1 -0
  83. package/dist/lib/helpers/combineURLs.d.ts +1 -0
  84. package/dist/lib/helpers/combineURLs.d.ts.map +1 -0
  85. package/dist/lib/helpers/composeSignals.d.ts +1 -0
  86. package/dist/lib/helpers/composeSignals.d.ts.map +1 -0
  87. package/dist/lib/helpers/composeSignals.js +8 -1
  88. package/dist/lib/helpers/composeSignals.js.map +1 -1
  89. package/dist/lib/helpers/cookies.d.ts +1 -0
  90. package/dist/lib/helpers/cookies.d.ts.map +1 -0
  91. package/dist/lib/helpers/estimateDataURLDecodedBytes.d.ts +1 -0
  92. package/dist/lib/helpers/estimateDataURLDecodedBytes.d.ts.map +1 -0
  93. package/dist/lib/helpers/formDataToJSON.d.ts +1 -0
  94. package/dist/lib/helpers/formDataToJSON.d.ts.map +1 -0
  95. package/dist/lib/helpers/isAbsoluteURL.d.ts +1 -0
  96. package/dist/lib/helpers/isAbsoluteURL.d.ts.map +1 -0
  97. package/dist/lib/helpers/isFaxiosError.d.ts +8 -2
  98. package/dist/lib/helpers/isFaxiosError.d.ts.map +1 -0
  99. package/dist/lib/helpers/isFaxiosError.js +5 -1
  100. package/dist/lib/helpers/isFaxiosError.js.map +1 -1
  101. package/dist/lib/helpers/isURLSameOrigin.d.ts +1 -0
  102. package/dist/lib/helpers/isURLSameOrigin.d.ts.map +1 -0
  103. package/dist/lib/helpers/parseHeaders.d.ts +1 -0
  104. package/dist/lib/helpers/parseHeaders.d.ts.map +1 -0
  105. package/dist/lib/helpers/progressEventReducer.d.ts +1 -0
  106. package/dist/lib/helpers/progressEventReducer.d.ts.map +1 -0
  107. package/dist/lib/helpers/sanitizeHeaderValue.d.ts +1 -0
  108. package/dist/lib/helpers/sanitizeHeaderValue.d.ts.map +1 -0
  109. package/dist/lib/helpers/speedometer.d.ts +1 -0
  110. package/dist/lib/helpers/speedometer.d.ts.map +1 -0
  111. package/dist/lib/helpers/substitutePathParams.d.ts +1 -0
  112. package/dist/lib/helpers/substitutePathParams.d.ts.map +1 -0
  113. package/dist/lib/helpers/throttle.d.ts +1 -0
  114. package/dist/lib/helpers/throttle.d.ts.map +1 -0
  115. package/dist/lib/helpers/toFormData.d.ts +1 -0
  116. package/dist/lib/helpers/toFormData.d.ts.map +1 -0
  117. package/dist/lib/helpers/toURLEncodedForm.d.ts +1 -0
  118. package/dist/lib/helpers/toURLEncodedForm.d.ts.map +1 -0
  119. package/dist/lib/helpers/trackStream.d.ts +1 -0
  120. package/dist/lib/helpers/trackStream.d.ts.map +1 -0
  121. package/dist/lib/helpers/validator.d.ts +1 -0
  122. package/dist/lib/helpers/validator.d.ts.map +1 -0
  123. package/dist/lib/platform.d.ts +2 -1
  124. package/dist/lib/platform.d.ts.map +1 -0
  125. package/dist/lib/plugins/attempt.d.ts +2 -0
  126. package/dist/lib/plugins/attempt.d.ts.map +1 -0
  127. package/dist/lib/plugins/attempt.js +4 -0
  128. package/dist/lib/plugins/attempt.js.map +1 -0
  129. package/dist/lib/plugins/authBearer.d.ts +31 -0
  130. package/dist/lib/plugins/authBearer.d.ts.map +1 -0
  131. package/dist/lib/plugins/authBearer.js +99 -0
  132. package/dist/lib/plugins/authBearer.js.map +1 -0
  133. package/dist/lib/plugins/definePlugin.d.ts +22 -0
  134. package/dist/lib/plugins/definePlugin.d.ts.map +1 -0
  135. package/dist/lib/plugins/definePlugin.js +14 -0
  136. package/dist/lib/plugins/definePlugin.js.map +1 -0
  137. package/dist/lib/plugins/retry.d.ts +66 -0
  138. package/dist/lib/plugins/retry.d.ts.map +1 -0
  139. package/dist/lib/plugins/retry.js +168 -0
  140. package/dist/lib/plugins/retry.js.map +1 -0
  141. package/dist/lib/plugins/timing.d.ts +32 -0
  142. package/dist/lib/plugins/timing.d.ts.map +1 -0
  143. package/dist/lib/plugins/timing.js +53 -0
  144. package/dist/lib/plugins/timing.js.map +1 -0
  145. package/dist/lib/types/standard-schema.d.ts +1 -0
  146. package/dist/lib/types/standard-schema.d.ts.map +1 -0
  147. package/dist/lib/types.d.ts +125 -34
  148. package/dist/lib/types.d.ts.map +1 -0
  149. package/dist/lib/utils.d.ts +1 -0
  150. package/dist/lib/utils.d.ts.map +1 -0
  151. package/package.json +42 -19
  152. package/skills/configure-requests/SKILL.md +380 -0
  153. package/skills/configure-requests/references/axios-differences.md +67 -0
  154. package/skills/configure-requests/references/plugins.md +127 -0
  155. package/src/index.ts +57 -0
  156. package/src/lib/adapters/fetch-helpers.ts +167 -0
  157. package/src/lib/adapters/fetch.ts +810 -0
  158. package/src/lib/cancel/CanceledError.ts +23 -0
  159. package/src/lib/cancel/isCancel.ts +10 -0
  160. package/src/lib/core/Faxios.ts +513 -0
  161. package/src/lib/core/FaxiosError.ts +283 -0
  162. package/src/lib/core/FaxiosHeaders.ts +529 -0
  163. package/src/lib/core/buildFullPath.ts +51 -0
  164. package/src/lib/core/define.ts +127 -0
  165. package/src/lib/core/dispatchRequest.ts +171 -0
  166. package/src/lib/core/mergeConfig.ts +175 -0
  167. package/src/lib/core/prepareRequest.ts +155 -0
  168. package/src/lib/core/route.ts +68 -0
  169. package/src/lib/core/settle.ts +20 -0
  170. package/src/lib/core/transformData.ts +23 -0
  171. package/src/lib/core/validateSchema.ts +53 -0
  172. package/src/lib/defaults/index.ts +221 -0
  173. package/src/lib/defaults/transitional.ts +9 -0
  174. package/src/lib/env/data.ts +1 -0
  175. package/src/lib/faxios.ts +306 -0
  176. package/src/lib/helpers/FaxiosURLSearchParams.ts +52 -0
  177. package/src/lib/helpers/HttpStatusCode.ts +77 -0
  178. package/src/lib/helpers/buildURL.ts +77 -0
  179. package/src/lib/helpers/cloneConfig.ts +23 -0
  180. package/src/lib/helpers/combineURLs.ts +11 -0
  181. package/src/lib/helpers/composeSignals.ts +74 -0
  182. package/src/lib/helpers/cookies.ts +68 -0
  183. package/src/lib/helpers/deprecatedMethod.ts +32 -0
  184. package/src/lib/helpers/estimateDataURLDecodedBytes.ts +95 -0
  185. package/src/lib/helpers/formDataToJSON.ts +122 -0
  186. package/src/lib/helpers/isAbsoluteURL.ts +13 -0
  187. package/src/lib/helpers/isFaxiosError.ts +19 -0
  188. package/src/lib/helpers/isURLSameOrigin.ts +16 -0
  189. package/src/lib/helpers/parseHeaders.ts +76 -0
  190. package/src/lib/helpers/progressEventReducer.ts +57 -0
  191. package/src/lib/helpers/sanitizeHeaderValue.ts +61 -0
  192. package/src/lib/helpers/speedometer.ts +55 -0
  193. package/src/lib/helpers/substitutePathParams.ts +13 -0
  194. package/src/lib/helpers/throttle.ts +45 -0
  195. package/src/lib/helpers/toFormData.ts +296 -0
  196. package/src/lib/helpers/toURLEncodedForm.ts +14 -0
  197. package/src/lib/helpers/trackStream.ts +123 -0
  198. package/src/lib/helpers/validator.ts +114 -0
  199. package/src/lib/platform.ts +44 -0
  200. package/src/lib/plugins/attempt.ts +3 -0
  201. package/src/lib/plugins/authBearer.ts +124 -0
  202. package/src/lib/plugins/definePlugin.ts +34 -0
  203. package/src/lib/plugins/retry.ts +245 -0
  204. package/src/lib/plugins/timing.ts +76 -0
  205. package/src/lib/types/standard-schema.ts +58 -0
  206. package/src/lib/types.ts +496 -0
  207. package/src/lib/utils.ts +932 -0
  208. package/dist/lib/core/InterceptorManager.d.ts +0 -9
  209. package/dist/lib/core/InterceptorManager.js +0 -28
  210. package/dist/lib/core/InterceptorManager.js.map +0 -1
@@ -0,0 +1,221 @@
1
+ "use strict";
2
+
3
+ import FaxiosError from "../core/FaxiosError.js";
4
+ import formDataToJSON from "../helpers/formDataToJSON.js";
5
+ import toFormData from "../helpers/toFormData.js";
6
+ import toURLEncodedForm from "../helpers/toURLEncodedForm.js";
7
+ import platform from "../platform.js";
8
+ import type {
9
+ FaxiosDefaults,
10
+ FaxiosRequestHeaders,
11
+ FaxiosResponse,
12
+ GenericFormData,
13
+ InternalFaxiosRequestConfig
14
+ } from "../types.js";
15
+ import utils from "../utils.js";
16
+ import transitionalDefaults from "./transitional.js";
17
+
18
+ /**
19
+ * It takes a string, tries to parse it, and if it fails, it returns the stringified version
20
+ * of the input
21
+ *
22
+ * @param {any} rawValue - The value to be stringified.
23
+ * @param {Function} parser - A function that parses a string into a JavaScript object.
24
+ * @param {Function} encoder - A function that takes a value and returns a string.
25
+ *
26
+ * @returns {string} A stringified version of the rawValue.
27
+ */
28
+ function serializeObjectPayload(
29
+ data: unknown,
30
+ contentType: string,
31
+ formSerializer: Record<string, unknown> | undefined,
32
+ FormDataCtor: (new () => object) | null | undefined
33
+ ): unknown {
34
+ if (contentType.indexOf("application/x-www-form-urlencoded") > -1) {
35
+ return toURLEncodedForm(data, formSerializer).toString();
36
+ }
37
+ const isFileList = utils.isFileList(data);
38
+ if (isFileList || contentType.indexOf("multipart/form-data") > -1) {
39
+ const _FormData = FormDataCtor;
40
+ return toFormData(
41
+ isFileList ? { "files[]": data } : data,
42
+ (_FormData && new _FormData()) as GenericFormData | null | undefined,
43
+ formSerializer
44
+ );
45
+ }
46
+ return undefined;
47
+ }
48
+
49
+ function throwOnStrictJSONError(
50
+ e: unknown,
51
+ strictJSONParsing: boolean,
52
+ config: InternalFaxiosRequestConfig
53
+ ): void {
54
+ if (!strictJSONParsing) return;
55
+ if ((e as { name?: string; }).name === "SyntaxError") {
56
+ throw FaxiosError.from(
57
+ e as Error,
58
+ FaxiosError.ERR_BAD_RESPONSE,
59
+ config,
60
+ null,
61
+ (config as unknown as Record<string, unknown>)["response"] as
62
+ | FaxiosResponse
63
+ | undefined
64
+ );
65
+ }
66
+ throw e;
67
+ }
68
+
69
+ function stringifySafely(
70
+ rawValue: unknown,
71
+ parser?: ((s: string) => unknown) | null,
72
+ encoder?: ((v: unknown) => string) | null
73
+ ): unknown {
74
+ if (utils.isString(rawValue)) {
75
+ try {
76
+ (parser || JSON.parse)(rawValue as string);
77
+ return (rawValue as string).trim();
78
+ }
79
+ catch (e) {
80
+ if ((e as { name?: string; }).name !== "SyntaxError") {
81
+ throw e;
82
+ }
83
+ }
84
+ }
85
+
86
+ return (encoder || JSON.stringify)(rawValue);
87
+ }
88
+
89
+ const defaults: FaxiosDefaults = {
90
+ transitional: transitionalDefaults,
91
+
92
+ transformRequest: [
93
+ function transformRequest(
94
+ this: InternalFaxiosRequestConfig,
95
+ data: unknown,
96
+ headers: FaxiosRequestHeaders
97
+ ) {
98
+ const contentType =
99
+ (headers.getContentType() as string | null | undefined) || "";
100
+ const hasJSONContentType = contentType.indexOf("application/json") > -1;
101
+ const isObjectPayload = utils.isObject(data);
102
+
103
+ if (isObjectPayload && utils.isHTMLForm(data)) {
104
+ const GlobalFormData = (globalThis as Record<string, unknown>)[
105
+ "FormData"
106
+ ] as (new (el?: unknown) => unknown) | undefined;
107
+ if (GlobalFormData) {
108
+ data = new GlobalFormData(data);
109
+ }
110
+ }
111
+
112
+ const isFormData = utils.isFormData(data);
113
+
114
+ if (isFormData) {
115
+ return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
116
+ }
117
+
118
+ // fetch takes any ArrayBufferView as a body and sends only the view's bytes.
119
+ // Never unwrap it to `.buffer`: a subarray or DataView would send the whole backing buffer.
120
+ if (
121
+ utils.isArrayBuffer(data) ||
122
+ utils.isArrayBufferView(data) ||
123
+ utils.isBuffer(data) ||
124
+ utils.isStream(data) ||
125
+ utils.isFile(data) ||
126
+ utils.isBlob(data) ||
127
+ utils.isReadableStream?.(data)
128
+ ) {
129
+ return data;
130
+ }
131
+ if (utils.isURLSearchParams(data)) {
132
+ headers.setContentType(
133
+ "application/x-www-form-urlencoded;charset=utf-8",
134
+ false
135
+ );
136
+ return (data as { toString: () => string; }).toString();
137
+ }
138
+
139
+ if (isObjectPayload) {
140
+ const formSerializer = this.formSerializer as Record<string, unknown> | undefined;
141
+ const serialized = serializeObjectPayload(data, contentType, formSerializer, this.env?.FormData);
142
+ if (serialized !== undefined) return serialized;
143
+ }
144
+
145
+ if (isObjectPayload || hasJSONContentType) {
146
+ headers.setContentType("application/json", false);
147
+ return stringifySafely(data);
148
+ }
149
+
150
+ return data;
151
+ },
152
+ ],
153
+
154
+ transformResponse: [
155
+ function transformResponse(
156
+ this: InternalFaxiosRequestConfig,
157
+ data: unknown
158
+ ) {
159
+ const transitional = this.transitional || defaults.transitional;
160
+ const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
161
+ const responseType = this.responseType;
162
+ const JSONRequested = responseType === "json";
163
+ const shouldParseJSON = (forcedJSONParsing && !responseType) || JSONRequested;
164
+
165
+ if (utils.isResponse?.(data) || utils.isReadableStream?.(data)) {
166
+ return data;
167
+ }
168
+
169
+ if (data && utils.isString(data) && shouldParseJSON) {
170
+ const silentJSONParsing =
171
+ transitional && transitional.silentJSONParsing;
172
+ const strictJSONParsing = !silentJSONParsing && JSONRequested;
173
+
174
+ try {
175
+ return JSON.parse(data as string, utils.hasOwnProp(this, "parseReviver") ? this.parseReviver : undefined);
176
+ }
177
+ catch (e) {
178
+ throwOnStrictJSONError(e, strictJSONParsing, this);
179
+ }
180
+ }
181
+
182
+ return data;
183
+ },
184
+ ],
185
+
186
+ /**
187
+ * A timeout in milliseconds to abort a request. If set to 0 (default) a
188
+ * timeout is not created.
189
+ */
190
+ timeout: 0,
191
+
192
+ xsrfCookieName: "XSRF-TOKEN",
193
+ xsrfHeaderName: "X-XSRF-TOKEN",
194
+
195
+ maxContentLength: -1,
196
+ maxBodyLength: -1,
197
+
198
+ env: {
199
+ FormData: platform.classes.FormData,
200
+ },
201
+
202
+ validateStatus: function validateStatus(status: number) {
203
+ return status >= 200 && status < 300;
204
+ },
205
+
206
+ headers: {
207
+ common: {
208
+ Accept: "application/json, text/plain, */*",
209
+ "Content-Type": undefined,
210
+ },
211
+ delete: {},
212
+ get: {},
213
+ head: {},
214
+ post: {},
215
+ put: {},
216
+ patch: {},
217
+ query: {},
218
+ },
219
+ };
220
+
221
+ export default defaults;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+
3
+ export default {
4
+ silentJSONParsing: true,
5
+ forcedJSONParsing: true,
6
+ clarifyTimeoutError: false,
7
+ advertiseZstdAcceptEncoding: false,
8
+ validateStatusUndefinedResolves: true,
9
+ };
@@ -0,0 +1 @@
1
+ export const VERSION = "0.2.1";
@@ -0,0 +1,306 @@
1
+ // @ts-self-types="./faxios.d.ts"
2
+ "use strict";
3
+
4
+ import CanceledError from "./cancel/CanceledError.js";
5
+ import isCancel from "./cancel/isCancel.js";
6
+ import type { DefineConfig, DefinedEndpoint } from "./core/define.js";
7
+ import Faxios, { ejectMiddleware, useMiddleware } from "./core/Faxios.js";
8
+ import FaxiosError from "./core/FaxiosError.js";
9
+ import FaxiosHeaders from "./core/FaxiosHeaders.js";
10
+ import mergeConfig from "./core/mergeConfig.js";
11
+ import type { RouteBuilder, RouteConfig } from "./core/route.js";
12
+ import defaults from "./defaults/index.js";
13
+ import { VERSION } from "./env/data.js";
14
+ import formDataToJSON from "./helpers/formDataToJSON.js";
15
+ import HttpStatusCode from "./helpers/HttpStatusCode.js";
16
+ import isFaxiosError from "./helpers/isFaxiosError.js";
17
+ import toFormData from "./helpers/toFormData.js";
18
+ import type { StandardSchemaV1 } from "./types/standard-schema.js";
19
+ import type { Method, StringLiteralsOrString, CreateFaxiosDefaults, FaxiosDefaults, FaxiosHeaderValue, FaxiosMiddleware, FaxiosPluginArgument, FaxiosRequestConfig, HeadersDefaults, FaxiosResponse, SchemaConfig } from "./types.js";
20
+ import utils from "./utils.js";
21
+
22
+ /**
23
+ * Create an instance of Faxios
24
+ *
25
+ * @param {Object} defaultConfig The default config for the instance
26
+ *
27
+ * @returns {Faxios} A new instance of Faxios
28
+ */
29
+ function createInstance(defaultConfig: FaxiosRequestConfig): FaxiosInstance {
30
+ const context = new Faxios(defaultConfig);
31
+ const instance = (Faxios.prototype.request as (...args: Array<unknown>) => unknown).bind(context) as unknown as FaxiosInstance;
32
+
33
+ // Copy faxios.prototype to instance. The instance is a callable populated
34
+ // dynamically here; extend mutates it via own-key copy.
35
+ const target = instance as unknown as Record<string, unknown>;
36
+ utils.extend(target, Faxios.prototype, context, { allOwnKeys: true });
37
+
38
+ // Copy context to instance
39
+ utils.extend(target, context, null, { allOwnKeys: true });
40
+
41
+ // use() and eject() aren't Faxios members, so the instance gets them here. use() returns the
42
+ // callable instance for chaining. At runtime it only registers the middleware; the plugin rules
43
+ // live in FaxiosInstance["use"], so the cast is the single place the phantom TOpts/TCaps
44
+ // refinement meets the untyped registry.
45
+ const use = (middleware: Parameters<typeof useMiddleware>[1]): FaxiosInstance => {
46
+ useMiddleware(context, middleware);
47
+ return instance;
48
+ };
49
+ instance.use = use as FaxiosInstance["use"];
50
+ instance.eject = (middleware: unknown) => {
51
+ ejectMiddleware(context, middleware);
52
+ };
53
+
54
+ // Factory for creating new instances
55
+ instance.create = function create(instanceConfig?: CreateFaxiosDefaults): FaxiosInstance {
56
+ return createInstance(mergeConfig(defaultConfig, instanceConfig));
57
+ };
58
+
59
+ return instance;
60
+ }
61
+
62
+ // Keys of TNeed that THave lacks, or provides with an incompatible type.
63
+ type MissingCapabilities<THave, TNeed> = {
64
+ [K in keyof TNeed]: K extends keyof THave ? (THave[K] extends TNeed[K] ? never : K) : K;
65
+ }[keyof TNeed];
66
+
67
+ // `unknown` when THave satisfies TNeed; otherwise a required brand property whose name explains
68
+ // the fix and whose value names the missing capabilities, so the compiler error points at them.
69
+ type RequireCapabilities<THave, TNeed> = [MissingCapabilities<THave, TNeed>] extends [never]
70
+ ? unknown
71
+ : { "faxios: install a plugin that provides this capability first": MissingCapabilities<THave, TNeed>; };
72
+
73
+ // Capabilities TProv would provide that THave already has. use() throws ERR_BAD_OPTION for these at
74
+ // runtime, so they are a type error too.
75
+ type DuplicateCapabilities<THave, TProv> = Extract<keyof TProv, keyof THave>;
76
+
77
+ type RejectDuplicateCapabilities<THave, TProv> = [DuplicateCapabilities<THave, TProv>] extends [never]
78
+ ? unknown
79
+ : { "faxios: another installed plugin already provides this capability": DuplicateCapabilities<THave, TProv>; };
80
+
81
+ // A plugin that adds capabilities must carry them, however TProv was supplied (inferred, annotated
82
+ // or as an explicit type argument), so use() can't record a capability ctx.capabilities lacks.
83
+ // NoInfer: TypeScript infers into conditional branches, and this branch must stay a check only.
84
+ type RequireProvidesValue<TProv> = [keyof TProv] extends [never] ? unknown : { provides: NoInfer<TProv>; };
85
+
86
+ // use() skips a nullish provides, so it adds no capabilities. Without this, `provides: undefined`
87
+ // infers TProv as undefined and `TCaps & undefined` collapses to never, which satisfies every check.
88
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- no capabilities, as in FaxiosInstance
89
+ type ProvidedCapabilities<TProv> = [TProv] extends [null | undefined] ? {} : TProv;
90
+
91
+ // use() reads capability names with Object.keys() and skips the keys that could pollute a prototype,
92
+ // so the registry only holds string names. A symbol, number or dangerous key would be typed on
93
+ // ctx.capabilities without matching a registered name, and nothing could satisfy a requirement for one.
94
+ type UnsupportedCapabilityKeys<TCaps> = Extract<keyof TCaps, symbol | number | "__proto__" | "constructor" | "prototype">;
95
+
96
+ type RejectUnsupportedCapabilityKeys<TReq, TProv> = [UnsupportedCapabilityKeys<TReq> | UnsupportedCapabilityKeys<TProv>] extends [never]
97
+ ? unknown
98
+ : { "faxios: capability names must be strings other than __proto__, constructor and prototype": UnsupportedCapabilityKeys<TReq> | UnsupportedCapabilityKeys<TProv>; };
99
+
100
+ // Nothing sets a plugin option for the caller, so a required one would be typed as present in the
101
+ // plugin's middleware while every request that omits it leaves it undefined.
102
+ type RequiredOptions<TOpt> = { [K in keyof TOpt]-?: object extends Pick<TOpt, K> ? never : K; }[keyof TOpt];
103
+
104
+ type RequireOptionalOptions<TOpt> = [RequiredOptions<TOpt>] extends [never]
105
+ ? unknown
106
+ : { "faxios: plugin request options must be optional": RequiredOptions<TOpt>; };
107
+
108
+ type UnionToIntersection<T> = (T extends unknown ? (value: T) => void : never) extends (value: infer I) => void ? I : never;
109
+ type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;
110
+
111
+ // keyof a union holds only the keys every member shares, so a union of capability maps would check
112
+ // nothing. Which member applies can't be known, so a union is rejected.
113
+ type RejectUnionCapabilities<TReq, TProv> = IsUnion<TReq> extends true
114
+ ? { "faxios: a plugin's required capabilities can't be a union": TReq; }
115
+ : IsUnion<TProv> extends true ? { "faxios: a plugin's provided capabilities can't be a union": TProv; } : unknown;
116
+
117
+ type CheckPlugin<THave, TReq, TProv, TOpt> = RequireCapabilities<THave, TReq>
118
+ & RejectDuplicateCapabilities<THave, TProv>
119
+ & RequireProvidesValue<TProv>
120
+ & RejectUnsupportedCapabilityKeys<TReq, TProv>
121
+ & RequireOptionalOptions<TOpt>
122
+ & RejectUnionCapabilities<TReq, TProv>;
123
+
124
+ /**
125
+ * A faxios instance. `TOpts` holds the request options that installed plugins add to every
126
+ * config-taking member; `TCaps` holds the capabilities installed plugins provide.
127
+ */
128
+ // `{}` defaults: no plugin options or capabilities yet. Middleware written inline in use() is typed
129
+ // from these, so it can use `Object.keys(ctx.capabilities)` or `"name" in ctx.capabilities`
130
+ // without narrowing first.
131
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- see above
132
+ export type FaxiosInstance<TOpts = {}, TCaps = {}> = {
133
+ /**
134
+ * Register middleware or a plugin and return this instance, typed with the plugin's request
135
+ * options and capabilities added. A plugin whose required capabilities aren't installed yet, or
136
+ * that provides a capability another installed plugin already provides, is a type error.
137
+ */
138
+ use: <TReq = unknown, TProv = unknown, TOpt = unknown>(
139
+ middleware: FaxiosMiddleware<TOpts, TCaps> | (FaxiosPluginArgument<TReq, TProv, TOpt> & CheckPlugin<TCaps, TReq, TProv, TOpt>)
140
+ ) => FaxiosInstance<TOpts & TOpt, TCaps & ProvidedCapabilities<TProv>>;
141
+ /**
142
+ * Remove middleware or a plugin registered with use(), by reference. In-flight requests are
143
+ * unaffected. The instance type is not narrowed: request options and capabilities the ejected
144
+ * plugin added stay in its type.
145
+ */
146
+ // A method, so its parameter is checked bivariantly: middleware typed for this instance's
147
+ // options and capabilities is accepted.
148
+ // eslint-disable-next-line @typescript-eslint/method-signature-style -- see above
149
+ eject<TReq = unknown, TProv = unknown, TOpt = unknown>(middleware: FaxiosMiddleware<TOpt> | FaxiosPluginArgument<TReq, TProv, TOpt>): void;
150
+ /**
151
+ * Define a typed endpoint for `method` and `url` (with optional `{key}` placeholders). `config`
152
+ * holds request defaults and the `pathParamsSchema`, `paramsSchema`, `requestSchema` and
153
+ * `responseSchema` to apply; schemas are locked at define time. Per-call `url`, `method` and
154
+ * schemas are ignored, and `pathParams`, `params` and `data` are required when their schema is set.
155
+ * The endpoint is a plain function that sends through this instance, so add middleware with
156
+ * `.use()` on the instance, not on the endpoint.
157
+ */
158
+ define: <
159
+ PP extends StandardSchemaV1<unknown, Record<string, unknown>> | undefined = undefined,
160
+ P extends StandardSchemaV1 | undefined = undefined,
161
+ D extends StandardSchemaV1 | undefined = undefined,
162
+ R extends StandardSchemaV1 | undefined = undefined
163
+ >(
164
+ method: StringLiteralsOrString<Method>,
165
+ url: string,
166
+ config?: DefineConfig<PP, P, D, R> & TOpts
167
+ ) => DefinedEndpoint<PP, P, D, R, TOpts>;
168
+ /**
169
+ * Group endpoints that share `url` and `config`. Returns one endpoint factory per method (`get`,
170
+ * `post`, `put`, `patch`, `delete`, `head`, `options`; no `query`), each taking `paramsSchema`,
171
+ * `requestSchema`, `responseSchema` and request defaults like `define()`. The route-level
172
+ * `pathParamsSchema` applies to every method and wins over a method's. Endpoints are plain
173
+ * functions that send through this instance, so add middleware with `.use()` on the instance.
174
+ */
175
+ route: <PP extends StandardSchemaV1<unknown, Record<string, unknown>> | undefined = undefined>(
176
+ url: string,
177
+ config?: RouteConfig<PP> & TOpts
178
+ ) => RouteBuilder<PP, TOpts>;
179
+ <O, D = unknown>(config: SchemaConfig<O, D> & TOpts): Promise<FaxiosResponse<O, D>>;
180
+ <O, D = unknown>(url: string, config: SchemaConfig<O, D> & TOpts): Promise<FaxiosResponse<O, D>>;
181
+ <T = unknown, R = FaxiosResponse<T>, D = unknown>(config: FaxiosRequestConfig<D> & TOpts): Promise<R>;
182
+ <T = unknown, R = FaxiosResponse<T>, D = unknown>(url: string, config?: FaxiosRequestConfig<D> & TOpts): Promise<R>;
183
+ request: {
184
+ <O, D = unknown>(config: SchemaConfig<O, D> & TOpts): Promise<FaxiosResponse<O, D>>;
185
+ <T = unknown, R = FaxiosResponse<T>, D = unknown>(config: FaxiosRequestConfig<D> & TOpts): Promise<R>;
186
+ };
187
+ get: {
188
+ <O, D = unknown>(url: string, config: SchemaConfig<O, D> & TOpts): Promise<FaxiosResponse<O, D>>;
189
+ <T = unknown, R = FaxiosResponse<T>, D = unknown>(url: string, config?: FaxiosRequestConfig<D> & TOpts): Promise<R>;
190
+ };
191
+ delete: {
192
+ <O, D = unknown>(url: string, config: SchemaConfig<O, D> & TOpts): Promise<FaxiosResponse<O, D>>;
193
+ <T = unknown, R = FaxiosResponse<T>, D = unknown>(url: string, config?: FaxiosRequestConfig<D> & TOpts): Promise<R>;
194
+ };
195
+ head: {
196
+ <O, D = unknown>(url: string, config: SchemaConfig<O, D> & TOpts): Promise<FaxiosResponse<O, D>>;
197
+ <T = unknown, R = FaxiosResponse<T>, D = unknown>(url: string, config?: FaxiosRequestConfig<D> & TOpts): Promise<R>;
198
+ };
199
+ options: {
200
+ <O, D = unknown>(url: string, config: SchemaConfig<O, D> & TOpts): Promise<FaxiosResponse<O, D>>;
201
+ <T = unknown, R = FaxiosResponse<T>, D = unknown>(url: string, config?: FaxiosRequestConfig<D> & TOpts): Promise<R>;
202
+ };
203
+ post: {
204
+ <O, D = unknown>(url: string, data: D | undefined, config: SchemaConfig<O, D> & TOpts): Promise<FaxiosResponse<O, D>>;
205
+ <T = unknown, R = FaxiosResponse<T>, D = unknown>(url: string, data?: D, config?: FaxiosRequestConfig<D> & TOpts): Promise<R>;
206
+ };
207
+ put: {
208
+ <O, D = unknown>(url: string, data: D | undefined, config: SchemaConfig<O, D> & TOpts): Promise<FaxiosResponse<O, D>>;
209
+ <T = unknown, R = FaxiosResponse<T>, D = unknown>(url: string, data?: D, config?: FaxiosRequestConfig<D> & TOpts): Promise<R>;
210
+ };
211
+ patch: {
212
+ <O, D = unknown>(url: string, data: D | undefined, config: SchemaConfig<O, D> & TOpts): Promise<FaxiosResponse<O, D>>;
213
+ <T = unknown, R = FaxiosResponse<T>, D = unknown>(url: string, data?: D, config?: FaxiosRequestConfig<D> & TOpts): Promise<R>;
214
+ };
215
+ query: {
216
+ <O, D = unknown>(url: string, data: D | undefined, config: SchemaConfig<O, D> & TOpts): Promise<FaxiosResponse<O, D>>;
217
+ <T = unknown, R = FaxiosResponse<T>, D = unknown>(url: string, data?: D, config?: FaxiosRequestConfig<D> & TOpts): Promise<R>;
218
+ };
219
+ postForm: {
220
+ <O, D = unknown>(url: string, data: D | undefined, config: SchemaConfig<O, D> & TOpts): Promise<FaxiosResponse<O, D>>;
221
+ <T = unknown, R = FaxiosResponse<T>, D = unknown>(url: string, data?: D, config?: FaxiosRequestConfig<D> & TOpts): Promise<R>;
222
+ };
223
+ putForm: {
224
+ <O, D = unknown>(url: string, data: D | undefined, config: SchemaConfig<O, D> & TOpts): Promise<FaxiosResponse<O, D>>;
225
+ <T = unknown, R = FaxiosResponse<T>, D = unknown>(url: string, data?: D, config?: FaxiosRequestConfig<D> & TOpts): Promise<R>;
226
+ };
227
+ patchForm: {
228
+ <O, D = unknown>(url: string, data: D | undefined, config: SchemaConfig<O, D> & TOpts): Promise<FaxiosResponse<O, D>>;
229
+ <T = unknown, R = FaxiosResponse<T>, D = unknown>(url: string, data?: D, config?: FaxiosRequestConfig<D> & TOpts): Promise<R>;
230
+ };
231
+ // `common` plus one header group per method; a key set directly on
232
+ // `headers` applies to every method.
233
+ defaults: Omit<FaxiosDefaults, "headers"> & {
234
+ headers: HeadersDefaults & { [key: string]: FaxiosHeaderValue | undefined; };
235
+ } & Partial<TOpts>;
236
+ /**
237
+ * Build the URL for `config` without sending a request. Applies `baseURL`, `params` and
238
+ * `paramsSerializer`, but does not substitute `pathParams` or run schemas, so `{key}`
239
+ * placeholders come back as written.
240
+ */
241
+ getUri: (config?: FaxiosRequestConfig & TOpts) => string;
242
+ create: (instanceConfig?: CreateFaxiosDefaults) => FaxiosInstance;
243
+ };
244
+
245
+ /** The default export: an instance plus the static helpers only it carries. */
246
+ export type FaxiosStatic = FaxiosInstance & {
247
+ Faxios: typeof Faxios;
248
+ CanceledError: typeof CanceledError;
249
+ isCancel: typeof isCancel;
250
+ VERSION: typeof VERSION;
251
+ toFormData: typeof toFormData;
252
+ FaxiosError: typeof FaxiosError;
253
+ Cancel: typeof CanceledError;
254
+ all: (promises: Array<Promise<unknown>>) => Promise<Array<unknown>>;
255
+ spread: (fn: (...args: Array<unknown>) => unknown) => (arr: Array<unknown>) => unknown;
256
+ isFaxiosError: typeof isFaxiosError;
257
+ mergeConfig: typeof mergeConfig;
258
+ FaxiosHeaders: typeof FaxiosHeaders;
259
+ formToJSON: (thing: unknown) => unknown;
260
+ HttpStatusCode: typeof HttpStatusCode;
261
+ default: FaxiosStatic;
262
+ };
263
+
264
+ // Create the default instance to be exported; the statics are attached below.
265
+ const faxios = createInstance(defaults) as FaxiosStatic;
266
+
267
+ // Expose Faxios class to allow class inheritance
268
+ faxios.Faxios = Faxios;
269
+
270
+ faxios.CanceledError = CanceledError;
271
+ faxios.isCancel = isCancel;
272
+ faxios.VERSION = VERSION;
273
+ faxios.toFormData = toFormData;
274
+
275
+ // Expose FaxiosError class
276
+ faxios.FaxiosError = FaxiosError;
277
+
278
+ // alias for CanceledError for backward compatibility
279
+ faxios.Cancel = faxios.CanceledError;
280
+
281
+ // Expose all/spread
282
+ faxios.all = async function all(promises: Array<Promise<unknown>>): Promise<Array<unknown>> {
283
+ return Promise.all(promises);
284
+ };
285
+
286
+ faxios.spread = (fn: (...args: Array<unknown>) => unknown) => (arr: Array<unknown>) => fn(...arr);
287
+
288
+ // Expose isFaxiosError
289
+ faxios.isFaxiosError = isFaxiosError;
290
+
291
+ // Expose mergeConfig
292
+ faxios.mergeConfig = mergeConfig;
293
+
294
+ faxios.FaxiosHeaders = FaxiosHeaders;
295
+
296
+ faxios.formToJSON = (thing: unknown): unknown => formDataToJSON(utils.isHTMLForm(thing) ? ((): unknown => {
297
+ const GlobalFormData = (globalThis as Record<string, unknown>)["FormData"] as (new (el?: unknown) => unknown) | undefined;
298
+ return GlobalFormData ? new GlobalFormData(thing) : thing;
299
+ })() : thing);
300
+
301
+ faxios.HttpStatusCode = HttpStatusCode;
302
+
303
+ faxios.default = faxios;
304
+
305
+ // this module should only have a default export
306
+ export default faxios;
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+
3
+ import type { ParamEncoder } from "../types.js";
4
+ import toFormData from "./toFormData.js";
5
+
6
+ /**
7
+ * It encodes a string by replacing all characters that are not in the unreserved set with
8
+ * their percent-encoded equivalents
9
+ *
10
+ * @param {string} str - The string to encode.
11
+ *
12
+ * @returns {string} The encoded string.
13
+ */
14
+ function encode(str: string): string {
15
+ const charMap: Record<string, string> = {
16
+ "!": "%21",
17
+ "'": "%27",
18
+ "(": "%28",
19
+ ")": "%29",
20
+ "~": "%7E",
21
+ "%20": "+",
22
+ };
23
+ return encodeURIComponent(str).replace(/[!'()~]|%20/g, function replacer(match: string) {
24
+ return charMap[match] ?? match;
25
+ });
26
+ }
27
+
28
+ class FaxiosURLSearchParams {
29
+ #pairs: Array<[string, unknown]> = [];
30
+
31
+ constructor(params?: unknown, options?: unknown) {
32
+ params && toFormData(params, this, options as Record<string, unknown>);
33
+ }
34
+
35
+ append(name: string, value: unknown): void {
36
+ this.#pairs.push([ name, value ]);
37
+ }
38
+
39
+ toString(encoder?: ParamEncoder): string {
40
+ const _encode = encoder
41
+ ? (value: string) => encoder.call(undefined, value, encode)
42
+ : encode;
43
+
44
+ return this.#pairs
45
+ .map(function each(pair: [string, unknown]) {
46
+ return _encode(String(pair[0])) + "=" + _encode(String(pair[1]!));
47
+ }, "")
48
+ .join("&");
49
+ }
50
+ }
51
+
52
+ export default FaxiosURLSearchParams;
@@ -0,0 +1,77 @@
1
+ const HttpStatusCode = {
2
+ Continue: 100,
3
+ SwitchingProtocols: 101,
4
+ Processing: 102,
5
+ EarlyHints: 103,
6
+ Ok: 200,
7
+ Created: 201,
8
+ Accepted: 202,
9
+ NonAuthoritativeInformation: 203,
10
+ NoContent: 204,
11
+ ResetContent: 205,
12
+ PartialContent: 206,
13
+ MultiStatus: 207,
14
+ AlreadyReported: 208,
15
+ ImUsed: 226,
16
+ MultipleChoices: 300,
17
+ MovedPermanently: 301,
18
+ Found: 302,
19
+ SeeOther: 303,
20
+ NotModified: 304,
21
+ UseProxy: 305,
22
+ Unused: 306,
23
+ TemporaryRedirect: 307,
24
+ PermanentRedirect: 308,
25
+ BadRequest: 400,
26
+ Unauthorized: 401,
27
+ PaymentRequired: 402,
28
+ Forbidden: 403,
29
+ NotFound: 404,
30
+ MethodNotAllowed: 405,
31
+ NotAcceptable: 406,
32
+ ProxyAuthenticationRequired: 407,
33
+ RequestTimeout: 408,
34
+ Conflict: 409,
35
+ Gone: 410,
36
+ LengthRequired: 411,
37
+ PreconditionFailed: 412,
38
+ PayloadTooLarge: 413,
39
+ UriTooLong: 414,
40
+ UnsupportedMediaType: 415,
41
+ RangeNotSatisfiable: 416,
42
+ ExpectationFailed: 417,
43
+ ImATeapot: 418,
44
+ MisdirectedRequest: 421,
45
+ UnprocessableEntity: 422,
46
+ Locked: 423,
47
+ FailedDependency: 424,
48
+ TooEarly: 425,
49
+ UpgradeRequired: 426,
50
+ PreconditionRequired: 428,
51
+ TooManyRequests: 429,
52
+ RequestHeaderFieldsTooLarge: 431,
53
+ UnavailableForLegalReasons: 451,
54
+ InternalServerError: 500,
55
+ NotImplemented: 501,
56
+ BadGateway: 502,
57
+ ServiceUnavailable: 503,
58
+ GatewayTimeout: 504,
59
+ HttpVersionNotSupported: 505,
60
+ VariantAlsoNegotiates: 506,
61
+ InsufficientStorage: 507,
62
+ LoopDetected: 508,
63
+ NotExtended: 510,
64
+ NetworkAuthenticationRequired: 511,
65
+ WebServerIsDown: 521,
66
+ ConnectionTimedOut: 522,
67
+ OriginIsUnreachable: 523,
68
+ TimeoutOccurred: 524,
69
+ SslHandshakeFailed: 525,
70
+ InvalidSslCertificate: 526,
71
+ };
72
+
73
+ Object.entries(HttpStatusCode).forEach(([ key, value ]) => {
74
+ (HttpStatusCode as Record<string | number, string | number>)[value] = key;
75
+ });
76
+
77
+ export default HttpStatusCode;