@wats/graph 0.3.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.
- package/LICENSE +21 -0
- package/README.md +3 -0
- package/dist/client.d.ts +41 -0
- package/dist/client.js +392 -0
- package/dist/createFetchTransport.d.ts +6 -0
- package/dist/createFetchTransport.js +46 -0
- package/dist/createMockTransport.d.ts +20 -0
- package/dist/createMockTransport.js +120 -0
- package/dist/endpoint.d.ts +26 -0
- package/dist/endpoint.js +223 -0
- package/dist/endpoints/businessManagement.d.ts +157 -0
- package/dist/endpoints/businessManagement.js +277 -0
- package/dist/endpoints/calling.d.ts +65 -0
- package/dist/endpoints/calling.js +284 -0
- package/dist/endpoints/flows/callables.d.ts +90 -0
- package/dist/endpoints/flows/callables.js +97 -0
- package/dist/endpoints/flows/dataExchange.d.ts +4 -0
- package/dist/endpoints/flows/dataExchange.js +40 -0
- package/dist/endpoints/flows/flowJson.d.ts +18 -0
- package/dist/endpoints/flows/flowJson.js +214 -0
- package/dist/endpoints/flows/index.d.ts +6 -0
- package/dist/endpoints/flows/index.js +26 -0
- package/dist/endpoints/flows/shared.d.ts +17 -0
- package/dist/endpoints/flows/shared.js +113 -0
- package/dist/endpoints/flows/types.d.ts +105 -0
- package/dist/endpoints/flows/types.js +0 -0
- package/dist/endpoints/flows.d.ts +2 -0
- package/dist/endpoints/flows.js +23 -0
- package/dist/endpoints/media.d.ts +123 -0
- package/dist/endpoints/media.js +976 -0
- package/dist/endpoints/messages.d.ts +375 -0
- package/dist/endpoints/messages.js +675 -0
- package/dist/endpoints/templates/builders.d.ts +9 -0
- package/dist/endpoints/templates/builders.js +101 -0
- package/dist/endpoints/templates/callables.d.ts +54 -0
- package/dist/endpoints/templates/callables.js +98 -0
- package/dist/endpoints/templates/index.d.ts +5 -0
- package/dist/endpoints/templates/index.js +16 -0
- package/dist/endpoints/templates/shared.d.ts +21 -0
- package/dist/endpoints/templates/shared.js +203 -0
- package/dist/endpoints/templates/types.d.ts +135 -0
- package/dist/endpoints/templates/types.js +0 -0
- package/dist/endpoints/templates/validation.d.ts +2 -0
- package/dist/endpoints/templates/validation.js +113 -0
- package/dist/endpoints/templates.d.ts +2 -0
- package/dist/endpoints/templates.js +14 -0
- package/dist/endpoints/waba/index.d.ts +4 -0
- package/dist/endpoints/waba/index.js +1 -0
- package/dist/endpoints/waba/phoneNumbers.d.ts +25 -0
- package/dist/endpoints/waba/phoneNumbers.js +23 -0
- package/dist/endpoints/waba/types.d.ts +8 -0
- package/dist/endpoints/waba/types.js +0 -0
- package/dist/endpoints/wabaEndpoints.d.ts +6 -0
- package/dist/endpoints/wabaEndpoints.js +38 -0
- package/dist/errorRegistry.d.ts +45 -0
- package/dist/errorRegistry.js +68 -0
- package/dist/errorSubclasses.d.ts +277 -0
- package/dist/errorSubclasses.js +613 -0
- package/dist/errors.d.ts +92 -0
- package/dist/errors.js +250 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +48 -0
- package/dist/internal/validation/arrays.d.ts +19 -0
- package/dist/internal/validation/arrays.js +102 -0
- package/dist/internal/validation/errors.d.ts +3 -0
- package/dist/internal/validation/errors.js +13 -0
- package/dist/internal/validation/headers.d.ts +15 -0
- package/dist/internal/validation/headers.js +77 -0
- package/dist/internal/validation/index.d.ts +8 -0
- package/dist/internal/validation/index.js +8 -0
- package/dist/internal/validation/json.d.ts +10 -0
- package/dist/internal/validation/json.js +79 -0
- package/dist/internal/validation/options.d.ts +5 -0
- package/dist/internal/validation/options.js +36 -0
- package/dist/internal/validation/paths.d.ts +8 -0
- package/dist/internal/validation/paths.js +37 -0
- package/dist/internal/validation/records.d.ts +20 -0
- package/dist/internal/validation/records.js +69 -0
- package/dist/internal/validation/strings.d.ts +12 -0
- package/dist/internal/validation/strings.js +46 -0
- package/dist/pagination.d.ts +35 -0
- package/dist/pagination.js +160 -0
- package/dist/subclients/phoneNumberClient.d.ts +60 -0
- package/dist/subclients/phoneNumberClient.js +194 -0
- package/dist/subclients/wabaClient.d.ts +66 -0
- package/dist/subclients/wabaClient.js +180 -0
- package/dist/transport.d.ts +32 -0
- package/dist/transport.js +5 -0
- package/package.json +70 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 WATS contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { GraphMessagesEndpoint } from "./endpoints/messages";
|
|
2
|
+
import type { Transport, TransportResponse } from "./transport";
|
|
3
|
+
export declare const DEFAULT_GRAPH_BASE_URL = "https://graph.facebook.com/";
|
|
4
|
+
export interface GraphClientConfig {
|
|
5
|
+
accessToken: string;
|
|
6
|
+
apiVersion: string;
|
|
7
|
+
baseUrl?: string;
|
|
8
|
+
transport?: Transport;
|
|
9
|
+
}
|
|
10
|
+
export type GraphQueryValue = string | number | boolean | null | undefined;
|
|
11
|
+
export type GraphQueryParams = Record<string, GraphQueryValue>;
|
|
12
|
+
export interface GraphRequestOptions {
|
|
13
|
+
method: string;
|
|
14
|
+
path: string;
|
|
15
|
+
query?: GraphQueryParams;
|
|
16
|
+
body?: unknown;
|
|
17
|
+
headers?: HeadersInit;
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
}
|
|
20
|
+
export interface GraphRawRequestOptions {
|
|
21
|
+
method: string;
|
|
22
|
+
url: string;
|
|
23
|
+
body?: unknown;
|
|
24
|
+
headers?: HeadersInit;
|
|
25
|
+
signal?: AbortSignal;
|
|
26
|
+
}
|
|
27
|
+
export declare class GraphClient {
|
|
28
|
+
private readonly baseUrl;
|
|
29
|
+
private readonly apiVersion;
|
|
30
|
+
private readonly accessToken;
|
|
31
|
+
private readonly transport;
|
|
32
|
+
readonly messages: GraphMessagesEndpoint;
|
|
33
|
+
constructor(config: GraphClientConfig);
|
|
34
|
+
requestRaw(options: GraphRawRequestOptions): Promise<TransportResponse>;
|
|
35
|
+
request<TResponse>(options: GraphRequestOptions): Promise<TResponse>;
|
|
36
|
+
private validateAbsoluteRequestUrl;
|
|
37
|
+
private assertNoAuthorizationOverride;
|
|
38
|
+
private buildUrl;
|
|
39
|
+
private extractFallbackGraphPayload;
|
|
40
|
+
private parseResponseBody;
|
|
41
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
export class GraphClient {
|
|
2
|
+
baseUrl;
|
|
3
|
+
apiVersion;
|
|
4
|
+
accessToken;
|
|
5
|
+
transport;
|
|
6
|
+
messages;
|
|
7
|
+
constructor(config) {
|
|
8
|
+
if (typeof config !== "object" || config === null) {
|
|
9
|
+
throw new GraphRequestValidationError("Invalid GraphClient config: expected an options object.");
|
|
10
|
+
}
|
|
11
|
+
this.accessToken = validateAccessToken(config.accessToken);
|
|
12
|
+
this.apiVersion = validateApiVersion(config.apiVersion);
|
|
13
|
+
this.baseUrl = validateBaseUrl(config.baseUrl);
|
|
14
|
+
this.transport = config.transport ?? createFetchTransport();
|
|
15
|
+
this.messages = new GraphMessagesEndpoint(this);
|
|
16
|
+
}
|
|
17
|
+
async requestRaw(options) {
|
|
18
|
+
if (typeof options !== "object" || options === null || Array.isArray(options)) {
|
|
19
|
+
throw new GraphRequestValidationError("Invalid Graph raw request options: expected an options object.");
|
|
20
|
+
}
|
|
21
|
+
const method = asTransportMethod(options.method);
|
|
22
|
+
const url = this.validateAbsoluteRequestUrl(options.url);
|
|
23
|
+
const signal = validateAbortSignal(options.signal);
|
|
24
|
+
this.assertNoAuthorizationOverride(options.headers);
|
|
25
|
+
let headers;
|
|
26
|
+
try {
|
|
27
|
+
headers = new Headers(options.headers);
|
|
28
|
+
} catch (error) {
|
|
29
|
+
throw new GraphRequestValidationError("Invalid request headers: CR, LF, NUL, or other forbidden control characters in header name or value are not allowed.", error);
|
|
30
|
+
}
|
|
31
|
+
headers.set("authorization", `Bearer ${this.accessToken}`);
|
|
32
|
+
const transportReq = {
|
|
33
|
+
method,
|
|
34
|
+
url,
|
|
35
|
+
headers,
|
|
36
|
+
body: toBodyInit(options.body)
|
|
37
|
+
};
|
|
38
|
+
try {
|
|
39
|
+
return await this.transport.request(transportReq, signal !== undefined ? { signal } : undefined);
|
|
40
|
+
} catch (error) {
|
|
41
|
+
if (error instanceof GraphNetworkError) {
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
throw new GraphNetworkError("Graph request failed due to a network error", error);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
async request(options) {
|
|
48
|
+
validateRequestOptionsObject(options);
|
|
49
|
+
const path = validateRequestPath(options.path);
|
|
50
|
+
const signal = validateAbortSignal(options.signal);
|
|
51
|
+
const url = this.buildUrl(path, options.query);
|
|
52
|
+
const method = asTransportMethod(options.method);
|
|
53
|
+
this.assertNoAuthorizationOverride(options.headers);
|
|
54
|
+
let headers;
|
|
55
|
+
try {
|
|
56
|
+
headers = new Headers(options.headers);
|
|
57
|
+
} catch (error) {
|
|
58
|
+
throw new GraphRequestValidationError("Invalid request headers: CR, LF, NUL, or other forbidden control characters in header name or value are not allowed.", error);
|
|
59
|
+
}
|
|
60
|
+
headers.set("authorization", `Bearer ${this.accessToken}`);
|
|
61
|
+
const bodyIsStream = isReadableStreamLike(options.body);
|
|
62
|
+
if (isJsonLikeBody(options.body) && !headers.has("content-type")) {
|
|
63
|
+
headers.set("content-type", "application/json");
|
|
64
|
+
}
|
|
65
|
+
if (bodyIsStream && !headers.has("content-type")) {
|
|
66
|
+
headers.set("content-type", "application/octet-stream");
|
|
67
|
+
}
|
|
68
|
+
const body = toBodyInit(options.body);
|
|
69
|
+
const transportReq = {
|
|
70
|
+
method,
|
|
71
|
+
url,
|
|
72
|
+
headers,
|
|
73
|
+
body
|
|
74
|
+
};
|
|
75
|
+
let response;
|
|
76
|
+
try {
|
|
77
|
+
response = await this.transport.request(transportReq, signal !== undefined ? { signal } : undefined);
|
|
78
|
+
} catch (error) {
|
|
79
|
+
if (error instanceof GraphNetworkError) {
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
throw new GraphNetworkError("Graph request failed due to a network error", error);
|
|
83
|
+
}
|
|
84
|
+
const parsedBody = await this.parseResponseBody(response);
|
|
85
|
+
if (response.status < 200 || response.status >= 300) {
|
|
86
|
+
if (isGraphErrorEnvelope(parsedBody)) {
|
|
87
|
+
throw createGraphApiError({
|
|
88
|
+
status: response.status,
|
|
89
|
+
payload: parsedBody.error,
|
|
90
|
+
fallbackMessage: getFallbackErrorMessage(response.status)
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
const fallbackPayload = this.extractFallbackGraphPayload(parsedBody);
|
|
94
|
+
const params = {
|
|
95
|
+
status: response.status,
|
|
96
|
+
fallbackMessage: getFallbackErrorMessage(response.status),
|
|
97
|
+
classify: false
|
|
98
|
+
};
|
|
99
|
+
if (fallbackPayload !== undefined) {
|
|
100
|
+
params.payload = fallbackPayload;
|
|
101
|
+
}
|
|
102
|
+
throw createGraphApiError(params);
|
|
103
|
+
}
|
|
104
|
+
return parsedBody;
|
|
105
|
+
}
|
|
106
|
+
validateAbsoluteRequestUrl(value) {
|
|
107
|
+
if (typeof value !== "string" || value.trim().length === 0 || hasForbiddenControlChar(value)) {
|
|
108
|
+
throw new GraphRequestValidationError("Invalid Graph raw request URL: expected a non-empty http(s) URL without control characters.");
|
|
109
|
+
}
|
|
110
|
+
let url;
|
|
111
|
+
try {
|
|
112
|
+
url = new URL(value);
|
|
113
|
+
} catch (error) {
|
|
114
|
+
throw new GraphRequestValidationError("Invalid Graph raw request URL: expected a valid absolute URL.", error);
|
|
115
|
+
}
|
|
116
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
117
|
+
throw new GraphRequestValidationError(`Invalid Graph raw request URL: protocol must be http: or https: (got ${JSON.stringify(url.protocol)}).`);
|
|
118
|
+
}
|
|
119
|
+
return url.toString();
|
|
120
|
+
}
|
|
121
|
+
assertNoAuthorizationOverride(init) {
|
|
122
|
+
if (init === undefined) {
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
const fail = () => {
|
|
126
|
+
throw new GraphRequestValidationError("Invalid request headers: authorization header is managed by the client; do not override.");
|
|
127
|
+
};
|
|
128
|
+
const isAuth = (name) => name.toLowerCase() === "authorization";
|
|
129
|
+
if (init instanceof Headers) {
|
|
130
|
+
if (init.has("authorization")) {
|
|
131
|
+
fail();
|
|
132
|
+
}
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (Array.isArray(init)) {
|
|
136
|
+
for (const entry of init) {
|
|
137
|
+
if (Array.isArray(entry) && entry.length > 0 && typeof entry[0] === "string") {
|
|
138
|
+
if (isAuth(entry[0])) {
|
|
139
|
+
fail();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (typeof init === "object" && init !== null) {
|
|
146
|
+
for (const key of Object.keys(init)) {
|
|
147
|
+
if (isAuth(key)) {
|
|
148
|
+
fail();
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
buildUrl(path, query) {
|
|
154
|
+
const segments = splitAndValidatePath(path);
|
|
155
|
+
const basePathname = this.baseUrl.pathname.endsWith("/") ? this.baseUrl.pathname : `${this.baseUrl.pathname}/`;
|
|
156
|
+
const joined = [this.apiVersion, ...segments].join("/");
|
|
157
|
+
const url = new URL(this.baseUrl.toString());
|
|
158
|
+
url.pathname = `${basePathname}${joined}`;
|
|
159
|
+
if (query) {
|
|
160
|
+
for (const [key, value] of Object.entries(query)) {
|
|
161
|
+
if (value === null || value === undefined) {
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
url.searchParams.set(key, String(value));
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return url.toString();
|
|
168
|
+
}
|
|
169
|
+
extractFallbackGraphPayload(value) {
|
|
170
|
+
if (!isGraphApiErrorPayload(value)) {
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
return value;
|
|
174
|
+
}
|
|
175
|
+
async parseResponseBody(response) {
|
|
176
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
177
|
+
if (contentType.includes("application/json")) {
|
|
178
|
+
try {
|
|
179
|
+
return await response.json();
|
|
180
|
+
} catch (error) {
|
|
181
|
+
if (response.status >= 200 && response.status < 300) {
|
|
182
|
+
throw new GraphSerializationError("Failed to parse successful Graph response JSON.", error);
|
|
183
|
+
}
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
const text = await response.text();
|
|
188
|
+
if (text.length === 0) {
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
try {
|
|
192
|
+
return JSON.parse(text);
|
|
193
|
+
} catch {
|
|
194
|
+
return text;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
import {
|
|
199
|
+
createGraphApiError,
|
|
200
|
+
GraphNetworkError,
|
|
201
|
+
GraphRequestValidationError,
|
|
202
|
+
GraphSerializationError,
|
|
203
|
+
isGraphApiErrorPayload,
|
|
204
|
+
isGraphErrorEnvelope
|
|
205
|
+
} from "./errors";
|
|
206
|
+
import { GraphMessagesEndpoint } from "./endpoints/messages";
|
|
207
|
+
import { createFetchTransport } from "./createFetchTransport";
|
|
208
|
+
export const DEFAULT_GRAPH_BASE_URL = "https://graph.facebook.com/";
|
|
209
|
+
const ACCESS_TOKEN_MAX_LEN = 4096;
|
|
210
|
+
const API_VERSION_REGEXP = /^v\d+(?:\.\d+)?$/;
|
|
211
|
+
function hasForbiddenControlChar(value) {
|
|
212
|
+
for (let i = 0;i < value.length; i += 1) {
|
|
213
|
+
const code = value.charCodeAt(i);
|
|
214
|
+
if (code < 32 || code === 127) {
|
|
215
|
+
return true;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return false;
|
|
219
|
+
}
|
|
220
|
+
function validateAccessToken(value) {
|
|
221
|
+
if (typeof value !== "string") {
|
|
222
|
+
throw new GraphRequestValidationError("Invalid GraphClient config: accessToken must be a non-empty string.");
|
|
223
|
+
}
|
|
224
|
+
if (value.length === 0) {
|
|
225
|
+
throw new GraphRequestValidationError("Invalid GraphClient config: accessToken must be a non-empty string.");
|
|
226
|
+
}
|
|
227
|
+
if (value.trim().length === 0) {
|
|
228
|
+
throw new GraphRequestValidationError("Invalid GraphClient config: accessToken must not be whitespace-only.");
|
|
229
|
+
}
|
|
230
|
+
if (value.length > ACCESS_TOKEN_MAX_LEN) {
|
|
231
|
+
throw new GraphRequestValidationError(`Invalid GraphClient config: accessToken exceeds ${ACCESS_TOKEN_MAX_LEN}-character bound.`);
|
|
232
|
+
}
|
|
233
|
+
if (hasForbiddenControlChar(value)) {
|
|
234
|
+
throw new GraphRequestValidationError("Invalid GraphClient config: accessToken must not contain control characters (CR/LF/NUL/etc.).");
|
|
235
|
+
}
|
|
236
|
+
return value;
|
|
237
|
+
}
|
|
238
|
+
function validateApiVersion(value) {
|
|
239
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
240
|
+
throw new GraphRequestValidationError("Invalid GraphClient config: apiVersion must be a non-empty string matching /^v\\d+(\\.\\d+)?$/.");
|
|
241
|
+
}
|
|
242
|
+
if (!API_VERSION_REGEXP.test(value)) {
|
|
243
|
+
throw new GraphRequestValidationError(`Invalid GraphClient config: apiVersion ${JSON.stringify(value)} does not match /^v\\d+(\\.\\d+)?$/.`);
|
|
244
|
+
}
|
|
245
|
+
return value;
|
|
246
|
+
}
|
|
247
|
+
function validateBaseUrl(value) {
|
|
248
|
+
if (value === undefined) {
|
|
249
|
+
return new URL(DEFAULT_GRAPH_BASE_URL);
|
|
250
|
+
}
|
|
251
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
252
|
+
throw new GraphRequestValidationError("Invalid GraphClient config: baseUrl must be a non-empty string URL.");
|
|
253
|
+
}
|
|
254
|
+
let url;
|
|
255
|
+
try {
|
|
256
|
+
url = new URL(value);
|
|
257
|
+
} catch (error) {
|
|
258
|
+
throw new GraphRequestValidationError(`Invalid GraphClient config: baseUrl ${JSON.stringify(value)} is not a valid URL.`, error);
|
|
259
|
+
}
|
|
260
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
261
|
+
throw new GraphRequestValidationError(`Invalid GraphClient config: baseUrl protocol must be http: or https: (got ${JSON.stringify(url.protocol)}).`);
|
|
262
|
+
}
|
|
263
|
+
return url;
|
|
264
|
+
}
|
|
265
|
+
const MAX_GRAPH_PATH_DECODE_ROUNDS = 5;
|
|
266
|
+
function assertSafeGraphPathSegment(segment) {
|
|
267
|
+
if (segment === "." || segment === "..") {
|
|
268
|
+
throw new GraphRequestValidationError("Invalid Graph request path. Dot-segments are not allowed.");
|
|
269
|
+
}
|
|
270
|
+
if (segment.includes("/") || segment.includes("\\")) {
|
|
271
|
+
throw new GraphRequestValidationError("Invalid Graph request path. Path traversal patterns are not allowed.");
|
|
272
|
+
}
|
|
273
|
+
if (segment.includes("?") || segment.includes("#")) {
|
|
274
|
+
throw new GraphRequestValidationError("Invalid Graph request path. Query strings and fragments are not allowed in path.");
|
|
275
|
+
}
|
|
276
|
+
for (let i = 0;i < segment.length; i += 1) {
|
|
277
|
+
const code = segment.charCodeAt(i);
|
|
278
|
+
if (code < 32 || code === 127) {
|
|
279
|
+
throw new GraphRequestValidationError("Invalid Graph request path. Control characters are not allowed in path segments.");
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
function normalizeGraphPathSegment(segment) {
|
|
284
|
+
let currentSegment = segment;
|
|
285
|
+
assertSafeGraphPathSegment(currentSegment);
|
|
286
|
+
for (let round = 0;round < MAX_GRAPH_PATH_DECODE_ROUNDS; round += 1) {
|
|
287
|
+
let decodedSegment;
|
|
288
|
+
try {
|
|
289
|
+
decodedSegment = decodeURIComponent(currentSegment);
|
|
290
|
+
} catch (error) {
|
|
291
|
+
throw new GraphRequestValidationError("Invalid Graph request path. Malformed percent-encoding.", error);
|
|
292
|
+
}
|
|
293
|
+
assertSafeGraphPathSegment(decodedSegment);
|
|
294
|
+
if (decodedSegment === currentSegment) {
|
|
295
|
+
return encodeURIComponent(decodedSegment);
|
|
296
|
+
}
|
|
297
|
+
currentSegment = decodedSegment;
|
|
298
|
+
}
|
|
299
|
+
throw new GraphRequestValidationError("Invalid Graph request path. Excessive nested percent-encoding in path segment.");
|
|
300
|
+
}
|
|
301
|
+
function splitAndValidatePath(path) {
|
|
302
|
+
if (path.length > 0) {
|
|
303
|
+
for (let i = 0;i < path.length; i += 1) {
|
|
304
|
+
const code = path.charCodeAt(i);
|
|
305
|
+
if (code < 32 || code === 127) {
|
|
306
|
+
throw new GraphRequestValidationError("Invalid Graph request path. Control characters are not allowed.");
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
|
311
|
+
if (normalizedPath.includes("?") || normalizedPath.includes("#")) {
|
|
312
|
+
throw new GraphRequestValidationError("Invalid Graph request path. Query strings and fragments are not allowed in path.");
|
|
313
|
+
}
|
|
314
|
+
return normalizedPath.split("/").filter((segment) => segment.length > 0).map((segment) => normalizeGraphPathSegment(segment));
|
|
315
|
+
}
|
|
316
|
+
function isReadableStreamLike(value) {
|
|
317
|
+
if (value === null || typeof value !== "object") {
|
|
318
|
+
return false;
|
|
319
|
+
}
|
|
320
|
+
const globalReadableStream = globalThis.ReadableStream;
|
|
321
|
+
if (typeof globalReadableStream === "function" && value instanceof globalReadableStream) {
|
|
322
|
+
return true;
|
|
323
|
+
}
|
|
324
|
+
return typeof value.getReader === "function";
|
|
325
|
+
}
|
|
326
|
+
function isJsonLikeBody(value) {
|
|
327
|
+
if (value === null || value === undefined) {
|
|
328
|
+
return false;
|
|
329
|
+
}
|
|
330
|
+
if (typeof value === "string") {
|
|
331
|
+
return false;
|
|
332
|
+
}
|
|
333
|
+
if (value instanceof FormData || value instanceof Blob || value instanceof ArrayBuffer || ArrayBuffer.isView(value) || value instanceof URLSearchParams || isReadableStreamLike(value)) {
|
|
334
|
+
return false;
|
|
335
|
+
}
|
|
336
|
+
return true;
|
|
337
|
+
}
|
|
338
|
+
function toBodyInit(body) {
|
|
339
|
+
if (body === null || body === undefined) {
|
|
340
|
+
return null;
|
|
341
|
+
}
|
|
342
|
+
if (typeof body === "string") {
|
|
343
|
+
return body;
|
|
344
|
+
}
|
|
345
|
+
if (body instanceof FormData || body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || body instanceof URLSearchParams || isReadableStreamLike(body)) {
|
|
346
|
+
return body;
|
|
347
|
+
}
|
|
348
|
+
try {
|
|
349
|
+
return JSON.stringify(body);
|
|
350
|
+
} catch (error) {
|
|
351
|
+
throw new GraphSerializationError("Failed to serialize request body to JSON.", error);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
function getFallbackErrorMessage(status) {
|
|
355
|
+
return `Graph API request failed with status ${status}`;
|
|
356
|
+
}
|
|
357
|
+
function asTransportMethod(method) {
|
|
358
|
+
if (typeof method !== "string") {
|
|
359
|
+
throw new GraphRequestValidationError("Invalid Graph request method: expected a non-empty string.");
|
|
360
|
+
}
|
|
361
|
+
if (method.length === 0 || method.trim().length === 0) {
|
|
362
|
+
throw new GraphRequestValidationError("Invalid Graph request method: expected a non-empty string.");
|
|
363
|
+
}
|
|
364
|
+
if (hasForbiddenControlChar(method)) {
|
|
365
|
+
throw new GraphRequestValidationError("Invalid Graph request method: control characters are not allowed.");
|
|
366
|
+
}
|
|
367
|
+
const upper = method.toUpperCase();
|
|
368
|
+
if (upper === "GET" || upper === "POST" || upper === "PUT" || upper === "PATCH" || upper === "DELETE") {
|
|
369
|
+
return upper;
|
|
370
|
+
}
|
|
371
|
+
throw new GraphRequestValidationError(`Invalid Graph request method: ${JSON.stringify(method)}.`);
|
|
372
|
+
}
|
|
373
|
+
function validateAbortSignal(value) {
|
|
374
|
+
if (value === undefined) {
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
if (typeof value !== "object" || value === null || typeof value.aborted !== "boolean" || typeof value.addEventListener !== "function" || typeof value.removeEventListener !== "function") {
|
|
378
|
+
throw new GraphRequestValidationError("Invalid Graph request signal: expected an AbortSignal-like object.");
|
|
379
|
+
}
|
|
380
|
+
return value;
|
|
381
|
+
}
|
|
382
|
+
function validateRequestOptionsObject(options) {
|
|
383
|
+
if (typeof options !== "object" || options === null || Array.isArray(options)) {
|
|
384
|
+
throw new GraphRequestValidationError("Invalid Graph request options: expected an options object.");
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
function validateRequestPath(value) {
|
|
388
|
+
if (typeof value !== "string" || value.length === 0 || value.trim().length === 0) {
|
|
389
|
+
throw new GraphRequestValidationError("Invalid Graph request path: expected a non-empty string.");
|
|
390
|
+
}
|
|
391
|
+
return value;
|
|
392
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Transport, TransportInterceptor } from "./transport";
|
|
2
|
+
export interface CreateFetchTransportOptions {
|
|
3
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
4
|
+
readonly interceptors?: readonly TransportInterceptor[];
|
|
5
|
+
}
|
|
6
|
+
export declare function createFetchTransport(options?: CreateFetchTransportOptions): Transport;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { GraphNetworkError } from "./errors";
|
|
2
|
+
function wrapResponse(res) {
|
|
3
|
+
return {
|
|
4
|
+
status: res.status,
|
|
5
|
+
headers: res.headers,
|
|
6
|
+
body: res.body,
|
|
7
|
+
arrayBuffer: () => res.arrayBuffer(),
|
|
8
|
+
json: () => res.json(),
|
|
9
|
+
text: () => res.text()
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
export function createFetchTransport(options) {
|
|
13
|
+
const interceptors = options?.interceptors ?? [];
|
|
14
|
+
return {
|
|
15
|
+
async request(req, opts) {
|
|
16
|
+
const resolvedFetch = options?.fetch ?? globalThis.fetch;
|
|
17
|
+
if (typeof resolvedFetch !== "function") {
|
|
18
|
+
throw new GraphNetworkError("No fetch implementation available: provide options.fetch or a runtime that exposes globalThis.fetch.");
|
|
19
|
+
}
|
|
20
|
+
let currentReq = req;
|
|
21
|
+
for (const interceptor of interceptors) {
|
|
22
|
+
if (interceptor.onRequest !== undefined) {
|
|
23
|
+
currentReq = await interceptor.onRequest(currentReq);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
let rawResponse;
|
|
27
|
+
try {
|
|
28
|
+
rawResponse = await resolvedFetch(currentReq.url, {
|
|
29
|
+
method: currentReq.method,
|
|
30
|
+
headers: currentReq.headers,
|
|
31
|
+
body: currentReq.body,
|
|
32
|
+
...opts?.signal !== undefined ? { signal: opts.signal } : {}
|
|
33
|
+
});
|
|
34
|
+
} catch (error) {
|
|
35
|
+
throw new GraphNetworkError("Graph request failed due to a network error", error);
|
|
36
|
+
}
|
|
37
|
+
let wrapped = wrapResponse(rawResponse);
|
|
38
|
+
for (const interceptor of interceptors) {
|
|
39
|
+
if (interceptor.onResponse !== undefined) {
|
|
40
|
+
wrapped = await interceptor.onResponse(currentReq, wrapped);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return wrapped;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Transport, TransportRequest } from "./transport";
|
|
2
|
+
export type MockTransportResponseSpec = {
|
|
3
|
+
readonly status: number;
|
|
4
|
+
readonly headers?: Record<string, string> | Headers;
|
|
5
|
+
readonly body?: string | Uint8Array | object | null;
|
|
6
|
+
} | ((req: TransportRequest) => MockTransportResponseSpec | Promise<MockTransportResponseSpec>);
|
|
7
|
+
export interface MockTransportConfig {
|
|
8
|
+
readonly responses?: readonly MockTransportResponseSpec[];
|
|
9
|
+
readonly defaultResponse?: MockTransportResponseSpec;
|
|
10
|
+
readonly onRequest?: (req: TransportRequest) => void;
|
|
11
|
+
readonly fail?: Error | ((req: TransportRequest) => Error);
|
|
12
|
+
readonly failAfter?: number;
|
|
13
|
+
}
|
|
14
|
+
export interface MockTransportHandle {
|
|
15
|
+
readonly transport: Transport;
|
|
16
|
+
readonly requests: ReadonlyArray<TransportRequest>;
|
|
17
|
+
respond(response: MockTransportResponseSpec): void;
|
|
18
|
+
reset(): void;
|
|
19
|
+
}
|
|
20
|
+
export declare function createMockTransport(config?: MockTransportConfig): MockTransportHandle;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
function toHeaders(init) {
|
|
2
|
+
if (init instanceof Headers) {
|
|
3
|
+
return init;
|
|
4
|
+
}
|
|
5
|
+
if (init === undefined) {
|
|
6
|
+
return new Headers;
|
|
7
|
+
}
|
|
8
|
+
return new Headers(init);
|
|
9
|
+
}
|
|
10
|
+
function encodeBody(body) {
|
|
11
|
+
if (body === null || body === undefined) {
|
|
12
|
+
return { bytes: new Uint8Array(0), contentType: null };
|
|
13
|
+
}
|
|
14
|
+
if (typeof body === "string") {
|
|
15
|
+
return { bytes: new TextEncoder().encode(body), contentType: null };
|
|
16
|
+
}
|
|
17
|
+
if (body instanceof Uint8Array) {
|
|
18
|
+
return { bytes: body, contentType: null };
|
|
19
|
+
}
|
|
20
|
+
const jsonString = JSON.stringify(body);
|
|
21
|
+
return {
|
|
22
|
+
bytes: new TextEncoder().encode(jsonString),
|
|
23
|
+
contentType: "application/json"
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function buildTransportResponse(spec) {
|
|
27
|
+
const objSpec = spec;
|
|
28
|
+
const headers = toHeaders(objSpec.headers);
|
|
29
|
+
const { bytes, contentType } = encodeBody(objSpec.body);
|
|
30
|
+
if (contentType !== null && !headers.has("content-type")) {
|
|
31
|
+
headers.set("content-type", contentType);
|
|
32
|
+
}
|
|
33
|
+
let consumed = false;
|
|
34
|
+
const consume = () => {
|
|
35
|
+
if (consumed) {
|
|
36
|
+
throw new Error("MockTransport response body already consumed");
|
|
37
|
+
}
|
|
38
|
+
consumed = true;
|
|
39
|
+
return bytes;
|
|
40
|
+
};
|
|
41
|
+
const makeStream = () => {
|
|
42
|
+
return new ReadableStream({
|
|
43
|
+
start(controller) {
|
|
44
|
+
if (bytes.length > 0) {
|
|
45
|
+
controller.enqueue(bytes);
|
|
46
|
+
}
|
|
47
|
+
controller.close();
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
};
|
|
51
|
+
const response = {
|
|
52
|
+
status: objSpec.status,
|
|
53
|
+
headers,
|
|
54
|
+
body: bytes.length === 0 ? null : makeStream(),
|
|
55
|
+
async arrayBuffer() {
|
|
56
|
+
const b = consume();
|
|
57
|
+
const buf = new ArrayBuffer(b.byteLength);
|
|
58
|
+
new Uint8Array(buf).set(b);
|
|
59
|
+
return buf;
|
|
60
|
+
},
|
|
61
|
+
async text() {
|
|
62
|
+
const b = consume();
|
|
63
|
+
return new TextDecoder().decode(b);
|
|
64
|
+
},
|
|
65
|
+
async json() {
|
|
66
|
+
const b = consume();
|
|
67
|
+
return JSON.parse(new TextDecoder().decode(b));
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
return response;
|
|
71
|
+
}
|
|
72
|
+
async function resolveSpec(spec, req) {
|
|
73
|
+
if (typeof spec === "function") {
|
|
74
|
+
return resolveSpec(await spec(req), req);
|
|
75
|
+
}
|
|
76
|
+
return spec;
|
|
77
|
+
}
|
|
78
|
+
export function createMockTransport(config) {
|
|
79
|
+
const cfg = config ?? {};
|
|
80
|
+
const queue = cfg.responses ? [...cfg.responses] : [];
|
|
81
|
+
const requests = [];
|
|
82
|
+
const handle = {
|
|
83
|
+
transport: {
|
|
84
|
+
async request(req) {
|
|
85
|
+
if (cfg.onRequest !== undefined) {
|
|
86
|
+
cfg.onRequest(req);
|
|
87
|
+
}
|
|
88
|
+
requests.push(req);
|
|
89
|
+
if (cfg.fail !== undefined) {
|
|
90
|
+
const threshold = cfg.failAfter;
|
|
91
|
+
const shouldFail = threshold === undefined || requests.length > threshold;
|
|
92
|
+
if (shouldFail) {
|
|
93
|
+
const err = typeof cfg.fail === "function" ? cfg.fail(req) : cfg.fail;
|
|
94
|
+
throw err;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
let spec = queue.shift();
|
|
98
|
+
if (spec === undefined) {
|
|
99
|
+
spec = cfg.defaultResponse;
|
|
100
|
+
}
|
|
101
|
+
if (spec === undefined) {
|
|
102
|
+
throw new Error(`MockTransport received an unexpected request (${req.method} ${req.url}): no queued response and no defaultResponse configured.`);
|
|
103
|
+
}
|
|
104
|
+
const resolved = await resolveSpec(spec, req);
|
|
105
|
+
return buildTransportResponse(resolved);
|
|
106
|
+
}
|
|
107
|
+
},
|
|
108
|
+
get requests() {
|
|
109
|
+
return Object.freeze(requests.slice());
|
|
110
|
+
},
|
|
111
|
+
respond(response) {
|
|
112
|
+
queue.push(response);
|
|
113
|
+
},
|
|
114
|
+
reset() {
|
|
115
|
+
queue.length = 0;
|
|
116
|
+
requests.length = 0;
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
return handle;
|
|
120
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { GraphClient } from "./client";
|
|
2
|
+
export type EndpointHttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
3
|
+
export interface EndpointParamSpec {
|
|
4
|
+
readonly in: "path" | "query";
|
|
5
|
+
readonly required?: boolean;
|
|
6
|
+
}
|
|
7
|
+
export interface EndpointDefinition<TParams extends Record<string, string> = Record<string, string>, TBody = unknown, TResponse = unknown> {
|
|
8
|
+
readonly method: EndpointHttpMethod;
|
|
9
|
+
readonly pathTemplate: string;
|
|
10
|
+
readonly params: {
|
|
11
|
+
readonly [K in keyof TParams]: EndpointParamSpec;
|
|
12
|
+
};
|
|
13
|
+
readonly buildBody?: (body: TBody) => unknown;
|
|
14
|
+
readonly bodyContentType?: string;
|
|
15
|
+
readonly __response?: TResponse;
|
|
16
|
+
}
|
|
17
|
+
export interface EndpointInvokeOptions {
|
|
18
|
+
readonly signal?: AbortSignal;
|
|
19
|
+
readonly headers?: Record<string, string> | Headers;
|
|
20
|
+
}
|
|
21
|
+
export interface EndpointCallable<TParams extends Record<string, string>, TBody, TResponse> {
|
|
22
|
+
(client: GraphClient, params: TParams, body?: TBody, opts?: EndpointInvokeOptions): Promise<TResponse>;
|
|
23
|
+
readonly definition: EndpointDefinition<TParams, TBody, TResponse>;
|
|
24
|
+
}
|
|
25
|
+
export declare function assertSafePathParamValue(name: string, value: string): void;
|
|
26
|
+
export declare function defineEndpoint<TParams extends Record<string, string>, TBody = unknown, TResponse = unknown>(def: EndpointDefinition<TParams, TBody, TResponse>): EndpointCallable<TParams, TBody, TResponse>;
|