@virtbase/proxmox-api 3.0.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +21 -53
  2. package/LICENSE +22 -0
  3. package/README.md +81 -82
  4. package/dist/client.d.ts +13 -7
  5. package/dist/client.js +23 -23
  6. package/dist/errors.d.ts +364 -0
  7. package/dist/errors.js +372 -0
  8. package/dist/index.d.ts +5 -3
  9. package/dist/index.js +3 -18
  10. package/dist/model.d.ts +28875 -28491
  11. package/dist/model.js +4 -16
  12. package/dist/proxmox-engine.d.ts +273 -54
  13. package/dist/proxmox-engine.js +772 -248
  14. package/dist/proxy.d.ts +61 -19
  15. package/dist/proxy.js +118 -33
  16. package/dist/qm-monitor.d.ts +225 -25
  17. package/dist/qm-monitor.js +152 -52
  18. package/dist/schema-info.d.ts +12 -0
  19. package/dist/schema-info.js +13 -0
  20. package/dist/tasks.d.ts +129 -0
  21. package/dist/tasks.js +132 -0
  22. package/package.json +33 -34
  23. package/dist/client.d.ts.map +0 -1
  24. package/dist/client.js.map +0 -1
  25. package/dist/index.d.ts.map +0 -1
  26. package/dist/index.js.map +0 -1
  27. package/dist/model.d.ts.map +0 -1
  28. package/dist/model.js.map +0 -1
  29. package/dist/proxmox-engine.d.ts.map +0 -1
  30. package/dist/proxmox-engine.js.map +0 -1
  31. package/dist/proxy.d.ts.map +0 -1
  32. package/dist/proxy.js.map +0 -1
  33. package/dist/qm-monitor.d.ts.map +0 -1
  34. package/dist/qm-monitor.js.map +0 -1
  35. package/src/__tests__/helpers.ts +0 -39
  36. package/src/__tests__/proxmox-engine.test.ts +0 -393
  37. package/src/__tests__/proxy.test.ts +0 -190
  38. package/src/__tests__/qm-monitor.test.ts +0 -215
  39. package/src/client.ts +0 -58
  40. package/src/index.ts +0 -34
  41. package/src/model.ts +0 -32101
  42. package/src/proxmox-engine.ts +0 -452
  43. package/src/proxy.ts +0 -195
  44. package/src/qm-monitor.ts +0 -303
@@ -1,452 +0,0 @@
1
- // Proxmox-API Interactive proxmox API for developpers how do not like reading docs
2
- // Copyright (C) 2020-2022 Chemouni Uriel <uchemouni@gmail.com>
3
- //
4
- // This program is free software: you can redistribute it and/or modify
5
- // it under the terms of the GNU General Public License as published by
6
- // the Free Software Foundation, either version 3 of the License, or
7
- // (at your option) any later version.
8
- //
9
- // This program is distributed in the hope that it will be useful,
10
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- // GNU General Public License for more details.
13
- //
14
- // You should have received a copy of the GNU General Public License
15
- // along with this program. If not, see <http://www.gnu.org/licenses/>.
16
-
17
- import type { ApiParamType, ApiRequestable } from "./proxy.js";
18
-
19
- const USER_AGENT = "proxmox-api (https://github.com/UrielCh/proxmox-api)";
20
-
21
- const BASE_HEADERS: Readonly<Record<string, string>> = {
22
- Accept: "*/*",
23
- "User-Agent": USER_AGENT,
24
- };
25
-
26
- /**
27
- * Common Proxmox authentification properties
28
- */
29
- export interface ProxmoxEngineOptionsCommon {
30
- /**
31
- * Proxmox address
32
- * currently used as hostname, so it can not contains a port number.
33
- */
34
- host: string;
35
- /**
36
- * Proxmox connexion port, default is 8006
37
- */
38
- port?: number;
39
- /**
40
- * http protocol, can be http or https, default is https
41
- */
42
- schema?: "https" | "http";
43
- /**
44
- * separated timeout for authentification call, default is 5 second
45
- */
46
- authTimeout?: number;
47
- /**
48
- * timeout for proxmox request, default is 60 seconds
49
- */
50
- queryTimeout?: number;
51
- /**
52
- * print the request in curl or fetch format
53
- */
54
- debug?: "curl" | "fetch";
55
- }
56
-
57
- /**
58
- * Proxmox authentification as user / password
59
- */
60
- export interface ProxmoxEngineOptionsPass extends ProxmoxEngineOptionsCommon {
61
- /**
62
- * Your username, if not specified will use root@pam
63
- */
64
- username?: string;
65
- /**
66
- * The password
67
- */
68
- password: string;
69
- }
70
-
71
- /**
72
- * Proxmox authentification as tokenID / tokenSecret
73
- */
74
- export interface ProxmoxEngineOptionsToken extends ProxmoxEngineOptionsCommon {
75
- tokenID: string;
76
- tokenSecret: string;
77
- }
78
-
79
- /**
80
- * Shape of a `fetch` implementation accepted by {@link ProxmoxEngine}.
81
- *
82
- * Structurally satisfied by the platform `fetch`, so any WHATWG-compatible
83
- * replacement - a mock, an instrumented wrapper, an agent-bound fetch - can be
84
- * passed straight through.
85
- */
86
- export type FetchInterface = (
87
- url: string | URL,
88
- options?: RequestInit,
89
- ) => Promise<Response>;
90
-
91
- /**
92
- * Type Union for proxmox Authentification options
93
- */
94
- export type ProxmoxEngineOptions = (
95
- | ProxmoxEngineOptionsToken
96
- | ProxmoxEngineOptionsPass
97
- ) & { fetch?: FetchInterface };
98
-
99
- /**
100
- * The `{ data, errors }` envelope every PVE endpoint replies with.
101
- *
102
- * Untyped here on purpose: the shape of `data` is decided by the endpoint, and
103
- * `model.ts` types it at the call site. `errors` is a free-form map of
104
- * per-parameter messages.
105
- */
106
- interface ProxmoxResponse {
107
- data: unknown;
108
- errors?: unknown;
109
- }
110
-
111
- /**
112
- * Own enumerable entries of `params`, minus the null and undefined ones.
113
- *
114
- * PVE rejects empty values, and callers routinely pass optional fields
115
- * through as undefined, so they are dropped rather than serialised.
116
- */
117
- function definedEntries(params?: ApiParamType): Array<[string, unknown]> {
118
- if (!params) return [];
119
- return Object.entries(params).filter(
120
- ([, value]) => value !== null && value !== undefined,
121
- );
122
- }
123
-
124
- /**
125
- * Encode one parameter the way the PVE API expects: booleans as 1/0, arrays as
126
- * the key repeated once per element.
127
- */
128
- function appendParam(
129
- target: URLSearchParams,
130
- key: string,
131
- value: unknown,
132
- ): void {
133
- if (value === true) {
134
- target.set(key, "1");
135
- } else if (value === false) {
136
- target.set(key, "0");
137
- } else if (Array.isArray(value)) {
138
- for (const element of value) target.append(key, `${element}`);
139
- } else {
140
- target.set(key, `${value}`);
141
- }
142
- }
143
-
144
- /**
145
- * Default Proxmox doRequest provider, this Class will be used if you provide Proxmox authentification options to the Proxy generator
146
- */
147
- export class ProxmoxEngine implements ApiRequestable {
148
- public CSRFPreventionToken?: string;
149
- public ticket?: string;
150
- private readonly username: string;
151
- private readonly password: string;
152
- private hostname: string; // was named host
153
- private port?: number;
154
- private readonly schema: "http" | "https";
155
- private authTimeout: number;
156
- private queryTimeout: number;
157
- private debug?: "curl" | "fetch";
158
- private fetch: FetchInterface;
159
-
160
- constructor(options: ProxmoxEngineOptions) {
161
- // Bound to globalThis: some runtimes reject the platform `fetch` when it
162
- // is invoked as a method of another object.
163
- this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
164
- if ("tokenID" in options && options.tokenSecret) {
165
- this.username = "";
166
- this.password = "";
167
- if (!options.tokenID.match(/.*@.+!.+/)) {
168
- const msg =
169
- "invalid tokenID, format should look be like USER@REALM!TOKENID";
170
- console.error(msg);
171
- throw Error(msg);
172
- }
173
- if (
174
- !options.tokenSecret.match(
175
- /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
176
- )
177
- ) {
178
- const msg =
179
- "invalid tokenSecret, format should be an lowercased UUID like 12345678-1234-1234-1234-1234567890ab";
180
- console.error(msg);
181
- throw Error(msg);
182
- }
183
- // USER@REALM!TOKENID
184
- this.ticket = `PVEAPIToken=${options.tokenID}=${options.tokenSecret}`;
185
- } else {
186
- const optPass = options as ProxmoxEngineOptionsPass;
187
- this.username = optPass.username || "root@pam";
188
- this.password = optPass.password;
189
- if (!this.password) {
190
- const msg = `password is missing for Proxmox connection`;
191
- console.error(msg);
192
- throw Error(msg);
193
- }
194
- }
195
- this.hostname = options.host;
196
- this.port = options.port;
197
- this.schema = options.schema || "https";
198
- this.authTimeout = options.authTimeout || 5000;
199
- this.queryTimeout = options.queryTimeout || 60000;
200
- this.debug = options.debug;
201
- }
202
-
203
- get host(): string {
204
- if (!this.port) return this.hostname;
205
- return `${this.hostname}:${this.port}`;
206
- }
207
-
208
- /**
209
- *
210
- * @param method http method GET POST PUT of DELETE
211
- * @param path http path
212
- * @param pathTemplate http path without var replacements *
213
- * @param params query params
214
- * @param retries retries id
215
- * @returns data from remote response
216
- */
217
- public async doRequest(
218
- method: string,
219
- path: string,
220
- pathTemplate: string,
221
- params?: ApiParamType,
222
- retries = 0,
223
- ): Promise<unknown> {
224
- const { CSRFPreventionToken, ticket } = await this.getTicket();
225
- // ensure that method is uppercased
226
- const httpMethod = method.toUpperCase();
227
-
228
- const headers: Record<string, string> = { ...BASE_HEADERS };
229
- // auth
230
- if (!this.username) {
231
- headers.Authorization = ticket; // PVEAPIToken=USER@REALM!TOKENID=UUID
232
- } else {
233
- headers.cookie = `PVEAuthCookie=${ticket}`;
234
- headers.CSRFPreventionToken = CSRFPreventionToken;
235
- }
236
-
237
- // proxmox base url
238
- const requestUrl = new URL(`${this.schema}://${this.host}${path}`);
239
- let body: string | undefined;
240
-
241
- const entries = definedEntries(params);
242
- if (entries.length > 0) {
243
- const sendsBody = httpMethod === "PUT" || httpMethod === "POST";
244
- const searchParams = sendsBody
245
- ? new URLSearchParams()
246
- : requestUrl.searchParams;
247
- for (const [key, value] of entries) appendParam(searchParams, key, value);
248
- if (sendsBody) {
249
- body = searchParams.toString();
250
- headers["Content-Type"] = "application/x-www-form-urlencoded";
251
- // `Content-Length` is deliberately left to fetch, which derives it
252
- // from the body. Upstream set it by hand from `body.length`; that
253
- // happens to agree here - `URLSearchParams.toString()` percent-encodes
254
- // to ASCII - but it is a second source of truth for the same fact, and
255
- // one that silently disagrees the moment the body is transformed.
256
- }
257
- }
258
-
259
- const fetchInit: RequestInit = {
260
- method: httpMethod,
261
- body,
262
- headers,
263
- // Self-clearing, unlike a setTimeout/clearTimeout pair - which leaked a
264
- // pending timer on every request that threw.
265
- signal: AbortSignal.timeout(this.queryTimeout),
266
- };
267
-
268
- let res: Response;
269
- try {
270
- res = await this.fetch(requestUrl, fetchInit);
271
- } catch (e) {
272
- this.logRequest(httpMethod, requestUrl, fetchInit, headers, {
273
- ticket,
274
- CSRFPreventionToken,
275
- });
276
- const attempt = retries + 1;
277
- if (attempt < 2) {
278
- return this.doRequest(httpMethod, path, pathTemplate, params, attempt);
279
- }
280
- // throw Error
281
- let errMsg = `FaILED to call ${httpMethod} ${requestUrl}`;
282
- const err = e as { cause?: { message?: string } };
283
- if (err.cause?.message) errMsg += ` cause by:${err.cause.message}`;
284
- throw new Error(errMsg, { cause: e });
285
- }
286
-
287
- const data = await this.readBody(res, httpMethod, requestUrl);
288
-
289
- switch (res.status) {
290
- case 400:
291
- throw Error(
292
- `${httpMethod} ${requestUrl} return Error ${res.status} ${res.statusText}: ${JSON.stringify(data)}`,
293
- );
294
- case 500:
295
- throw Error(
296
- `${httpMethod} ${requestUrl} return Error ${res.status} ${res.statusText}: ${JSON.stringify(data)}`,
297
- );
298
- case 401:
299
- if (
300
- res.statusText === "invalid PVE ticket" ||
301
- res.statusText === "permission denied - invalid PVE ticket"
302
- ) {
303
- this.ticket = undefined;
304
- // A token is not renewable, so do not spend the retry on it.
305
- let attempt = this.username ? retries : 10;
306
- attempt++;
307
- if (attempt < 2)
308
- return this.doRequest(
309
- httpMethod,
310
- path,
311
- pathTemplate,
312
- params,
313
- attempt,
314
- );
315
- }
316
- throw Error(
317
- `${httpMethod} ${requestUrl} return Error ${res.status} ${res.statusText}: ${JSON.stringify(data)}`,
318
- );
319
- case 200:
320
- return data.data;
321
- default:
322
- throw Error(
323
- `${httpMethod} ${requestUrl} connection failed with ${res.status} ${res.statusText} return: ${JSON.stringify(data)}`,
324
- );
325
- }
326
- }
327
-
328
- /**
329
- * Decode a response into the PVE `{ data, errors }` envelope.
330
- */
331
- private async readBody(
332
- res: Response,
333
- method: string,
334
- requestUrl: URL,
335
- ): Promise<ProxmoxResponse> {
336
- const contentType = res.headers.get("content-type");
337
- const data: ProxmoxResponse = { data: null };
338
-
339
- // PVE answers `application/json;charset=UTF-8`, but match on the media
340
- // type alone so a proxy that respaces the parameter is still understood.
341
- if (contentType?.startsWith("application/json")) {
342
- try {
343
- return (await res.json()) as ProxmoxResponse;
344
- } catch {
345
- data.errors = "Failed to parse response json";
346
- }
347
- } else if (contentType === "application/octet-stream") {
348
- data.data = res.body;
349
- } else if (!contentType) {
350
- data.errors = "";
351
- try {
352
- data.errors = await res.text();
353
- } catch {
354
- // ignore reading error;
355
- }
356
- } else {
357
- // should never append
358
- throw Error(
359
- `${method} ${requestUrl} unexpected contentType "${contentType}" status Line:${res.status} ${res.statusText}`,
360
- );
361
- }
362
- return data;
363
- }
364
-
365
- /**
366
- * Echo the request that just failed, as a runnable `curl` line or as the
367
- * `fetch` call that produced it. Only fires when `debug` is set.
368
- */
369
- private logRequest(
370
- method: string,
371
- requestUrl: URL,
372
- fetchInit: RequestInit,
373
- headers: Record<string, string>,
374
- auth: { ticket: string; CSRFPreventionToken: string },
375
- ): void {
376
- if (!this.debug) return;
377
- if (this.debug === "fetch") {
378
- console.log(`fetch("${requestUrl}", ${JSON.stringify(fetchInit)})`);
379
- return;
380
- }
381
- const credentials = headers.cookie
382
- ? `-H "CSRFPreventionToken: ${auth.CSRFPreventionToken}" --cookie ${JSON.stringify(headers.cookie)}`
383
- : `-H "Authorization: ${auth.ticket}"`;
384
- const data = fetchInit.body
385
- ? `--data ${JSON.stringify(fetchInit.body)}`
386
- : "";
387
- if (method === "POST") {
388
- console.log(`curl -v --insecure ${credentials} ${data} ${requestUrl}`);
389
- } else if (method === "GET") {
390
- console.log(`curl -v --insecure ${credentials} ${requestUrl}`);
391
- } else {
392
- console.log(`curl -v -X ${method} ${credentials} ${data} ${requestUrl}`);
393
- }
394
- }
395
-
396
- /**
397
- * return the current ticket/token, or create new ones, is previous one had been discared, or missing.
398
- * @returns Proxmox API ticket and CSRFPreventionToken
399
- */
400
- public async getTicket(): Promise<{
401
- ticket: string;
402
- CSRFPreventionToken: string;
403
- }> {
404
- if (this.ticket) {
405
- if (!this.username)
406
- return { ticket: this.ticket, CSRFPreventionToken: "" };
407
- if (this.CSRFPreventionToken)
408
- return {
409
- ticket: this.ticket,
410
- CSRFPreventionToken: this.CSRFPreventionToken,
411
- };
412
- }
413
-
414
- // update ticket endpoint
415
- const requestUrl = `${this.schema}://${this.host}/api2/json/access/ticket`;
416
-
417
- try {
418
- const { password, username } = this;
419
- const body = new URLSearchParams({ username, password }).toString();
420
- const headers = {
421
- ...BASE_HEADERS,
422
- "Content-Type": "application/x-www-form-urlencoded",
423
- };
424
- const r = await this.fetch(requestUrl, {
425
- method: "POST",
426
- headers,
427
- signal: AbortSignal.timeout(this.authTimeout),
428
- body,
429
- });
430
- const text = await r.text();
431
- if (r.status !== 200) {
432
- throw Error(`login failed with ${r.status}: ${r.statusText} ${text}`);
433
- }
434
- const respObj = JSON.parse(text) as {
435
- data: {
436
- cap: unknown;
437
- ticket: string;
438
- CSRFPreventionToken: string;
439
- username: string;
440
- };
441
- };
442
- const { CSRFPreventionToken, ticket } = respObj.data;
443
- this.CSRFPreventionToken = CSRFPreventionToken;
444
- this.ticket = ticket;
445
- return { ticket, CSRFPreventionToken };
446
- } catch (e) {
447
- throw new Error(`Auth ${requestUrl} Failed!`, { cause: e });
448
- }
449
- }
450
- }
451
-
452
- export default ProxmoxEngine;
package/src/proxy.ts DELETED
@@ -1,195 +0,0 @@
1
- // Proxmox-API Interactive proxmox API for developpers how do not like reading docs
2
- // Copyright (C) 2020-2022 Chemouni Uriel <uchemouni@gmail.com>
3
- //
4
- // This program is free software: you can redistribute it and/or modify
5
- // it under the terms of the GNU General Public License as published by
6
- // the Free Software Foundation, either version 3 of the License, or
7
- // (at your option) any later version.
8
- //
9
- // This program is distributed in the hope that it will be useful,
10
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- // GNU General Public License for more details.
13
- //
14
- // You should have received a copy of the GNU General Public License
15
- // along with this program. If not, see <http://www.gnu.org/licenses/>.
16
-
17
- /**
18
- * Parameters for one API call.
19
- *
20
- * Values are whatever the endpoint declares in `model.ts`; the engine encodes
21
- * them on the way out.
22
- */
23
- export type ApiParamType = Record<string, unknown>;
24
-
25
- /**
26
- * The transport the proxy calls into.
27
- *
28
- * Implement it to send requests somewhere other than a live cluster - a
29
- * recorded fixture, a queue, a per-tenant router - and hand the result to
30
- * {@link buildApiProxy} or `proxmoxApi()`.
31
- */
32
- export interface ApiRequestable {
33
- /**
34
- * Execute one request.
35
- *
36
- * @param httpMethod GET, POST, PUT or DELETE.
37
- * @param path The concrete path, placeholders already substituted.
38
- * @param pathTemplate The same path with `*` in place of each substituted
39
- * value, which makes calls to one endpoint groupable for logging or
40
- * metrics regardless of the ids involved.
41
- * @param params Query or body parameters.
42
- */
43
- doRequest(
44
- httpMethod: string,
45
- path: string,
46
- pathTemplate: string,
47
- params?: ApiParamType,
48
- ): Promise<unknown>;
49
- }
50
-
51
- /**
52
- * Keys that resolve on the node instead of extending the path.
53
- *
54
- * Without these, `String(proxmox)` or a debugger inspecting the object would
55
- * silently build `/toString` and hand back another proxy.
56
- */
57
- const OBJECT_KEYS: ReadonlySet<string> = new Set([
58
- "toString",
59
- "valueOf",
60
- "toLocaleString",
61
- ]);
62
-
63
- /**
64
- * Reserved at the root only.
65
- *
66
- * A root proxy is the value most likely to be handed to code that sniffs for
67
- * an EventEmitter - a logger, a test harness - and every one of those probes
68
- * would otherwise mint a path segment. Deeper nodes are not exposed that way,
69
- * so they keep these names usable as real segments.
70
- */
71
- const EVENT_EMITTER_KEYS: ReadonlySet<string> = new Set([
72
- "addListener",
73
- "emit",
74
- "eventNames",
75
- "getMaxListeners",
76
- "listenerCount",
77
- "listeners",
78
- "off",
79
- "on",
80
- "once",
81
- "prependListener",
82
- "prependOnceListener",
83
- "rawListeners",
84
- "removeAllListeners",
85
- "removeListener",
86
- "setMaxListeners",
87
- ]);
88
-
89
- const ROOT_KEYS: ReadonlySet<string> = new Set([
90
- ...OBJECT_KEYS,
91
- ...EVENT_EMITTER_KEYS,
92
- ]);
93
-
94
- /**
95
- * Characters that would change the shape of the URL rather than sit inside a
96
- * path segment. A `/` would invent a path level; `?` and `#` would start a
97
- * query or fragment and drop the rest of the path.
98
- */
99
- const UNSAFE_IN_SEGMENT = /[/?#]/g;
100
-
101
- function escapeSegment(value: string | number): string {
102
- return String(value).replace(UNSAFE_IN_SEGMENT, (char) =>
103
- encodeURIComponent(char),
104
- );
105
- }
106
-
107
- /**
108
- * One node of the path being built.
109
- *
110
- * Nodes are immutable: navigating produces a new node, so a partially walked
111
- * path can be held onto and reused.
112
- */
113
- class ApiNode {
114
- constructor(
115
- readonly engine: ApiRequestable,
116
- readonly path: string,
117
- readonly model: string,
118
- ) {}
119
-
120
- toString(): string {
121
- return `ProxyApi{path:${this.path}}`;
122
- }
123
- }
124
-
125
- /**
126
- * Resolve one property access into either a request function or the next node.
127
- */
128
- function navigate(node: ApiNode, key: string): unknown {
129
- if (key === "$") {
130
- return (id: string | number) =>
131
- descend(node, escapeSegment(id), "*", childHandler);
132
- }
133
-
134
- if (key.startsWith("$")) {
135
- const httpMethod = key.slice(1);
136
- return (params?: ApiParamType) =>
137
- node.engine.doRequest(httpMethod, node.path, node.model, params);
138
- }
139
-
140
- // A leading underscore is the escape hatch for segments that collide with a
141
- // reserved name: `_on` requests `/on`.
142
- const segment = key.startsWith("_") ? key.slice(1) : key;
143
- return descend(node, segment, segment, childHandler);
144
- }
145
-
146
- function descend(
147
- node: ApiNode,
148
- pathSegment: string,
149
- modelSegment: string,
150
- handler: ProxyHandler<ApiNode>,
151
- ): unknown {
152
- return new Proxy(
153
- new ApiNode(
154
- node.engine,
155
- `${node.path}/${pathSegment}`,
156
- `${node.model}/${modelSegment}`,
157
- ),
158
- handler,
159
- );
160
- }
161
-
162
- function createHandler(reserved: ReadonlySet<string>): ProxyHandler<ApiNode> {
163
- return {
164
- // `new proxmox.nodes()` yields the node rather than throwing, which keeps
165
- // the proxy inert in code that probes values by constructing them.
166
- construct: (target) => target,
167
- get(target, property) {
168
- if (typeof property === "symbol" || reserved.has(property)) {
169
- const value = Reflect.get(target, property);
170
- // Bound to the node, not the proxy. Called on the proxy, `toString`
171
- // would read `this.path` back through this trap, get another proxy,
172
- // stringify that, and recurse until the stack ran out.
173
- return typeof value === "function" ? value.bind(target) : value;
174
- }
175
- return navigate(target, property);
176
- },
177
- };
178
- }
179
-
180
- const childHandler = createHandler(OBJECT_KEYS);
181
- const rootHandler = createHandler(ROOT_KEYS);
182
-
183
- /**
184
- * Build the proxy that turns property access into API paths.
185
- *
186
- * Nothing is requested while the path is walked - each step returns a new
187
- * proxy. The call happens when a `$`-prefixed method is invoked.
188
- *
189
- * @param engine Transport to send requests through.
190
- * @param path Prefix every path is built on, normally `/api2/json`.
191
- * @typeParam T The generated API shape to present, e.g. `Proxmox.Api`.
192
- */
193
- export function buildApiProxy<T>(engine: ApiRequestable, path: string): T {
194
- return new Proxy(new ApiNode(engine, path, path), rootHandler) as T;
195
- }