@planescrm/sdk 0.55.0 → 0.72.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.
package/dist/client.js ADDED
@@ -0,0 +1,3255 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/client-entry.ts
21
+ var client_entry_exports = {};
22
+ __export(client_entry_exports, {
23
+ AuthenticationError: () => AuthenticationError,
24
+ AuthorizationError: () => AuthorizationError,
25
+ DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
26
+ DEFAULT_MAX_RETRIES: () => DEFAULT_MAX_RETRIES,
27
+ DEFAULT_TIMEOUT: () => DEFAULT_TIMEOUT,
28
+ NotFoundError: () => NotFoundError,
29
+ PlanesClient: () => PlanesClient2,
30
+ PlanesError: () => PlanesError,
31
+ RateLimitError: () => RateLimitError,
32
+ ServerError: () => ServerError,
33
+ ValidationError: () => ValidationError
34
+ });
35
+ module.exports = __toCommonJS(client_entry_exports);
36
+
37
+ // src/config.ts
38
+ var MemoryTokenStorage = class {
39
+ constructor(seed) {
40
+ this.tokens = seed ?? null;
41
+ }
42
+ async getTokens() {
43
+ return this.tokens;
44
+ }
45
+ async setTokens(tokens) {
46
+ this.tokens = tokens;
47
+ }
48
+ };
49
+ var DEFAULT_BASE_URL = "https://api.planescrm.com/api/v1";
50
+ var DEFAULT_TIMEOUT = 3e4;
51
+ var DEFAULT_MAX_RETRIES = 3;
52
+ var DEFAULT_TOKEN_REFRESH_SKEW_MS = 6e4;
53
+
54
+ // src/errors.ts
55
+ var PlanesError = class extends Error {
56
+ constructor(message, status, code) {
57
+ super(message);
58
+ this.name = "PlanesError";
59
+ this.status = status;
60
+ this.code = code;
61
+ }
62
+ };
63
+ var AuthenticationError = class extends PlanesError {
64
+ constructor(message = "Authentication failed") {
65
+ super(message, 401, "authentication_error");
66
+ this.name = "AuthenticationError";
67
+ }
68
+ };
69
+ var AuthorizationError = class extends PlanesError {
70
+ constructor(message = "Insufficient permissions") {
71
+ super(message, 403, "authorization_error");
72
+ this.name = "AuthorizationError";
73
+ }
74
+ };
75
+ var NotFoundError = class extends PlanesError {
76
+ constructor(message = "Resource not found") {
77
+ super(message, 404, "not_found");
78
+ this.name = "NotFoundError";
79
+ }
80
+ };
81
+ var ValidationError = class extends PlanesError {
82
+ constructor(message = "Validation failed", fieldErrors = []) {
83
+ super(message, 400, "validation_error");
84
+ this.name = "ValidationError";
85
+ this.fieldErrors = fieldErrors;
86
+ }
87
+ };
88
+ var RateLimitError = class extends PlanesError {
89
+ constructor(retryAfter = 1, message = "Rate limit exceeded") {
90
+ super(message, 429, "rate_limit_error");
91
+ this.name = "RateLimitError";
92
+ this.retryAfter = retryAfter;
93
+ }
94
+ };
95
+ var ServerError = class extends PlanesError {
96
+ constructor(message = "Internal server error") {
97
+ super(message, 500, "server_error");
98
+ this.name = "ServerError";
99
+ }
100
+ };
101
+ var WebhookVerificationError = class extends PlanesError {
102
+ constructor(message = "Webhook signature verification failed") {
103
+ super(message, 400, "webhook_verification_error");
104
+ this.name = "WebhookVerificationError";
105
+ }
106
+ };
107
+ var OAuthError = class extends PlanesError {
108
+ constructor(errorCode, message = "OAuth error") {
109
+ super(message, 400, "oauth_error");
110
+ this.name = "OAuthError";
111
+ this.errorCode = errorCode;
112
+ }
113
+ };
114
+
115
+ // src/client-shims/node-crypto.ts
116
+ function unavailable(name) {
117
+ throw new Error(
118
+ `${name} is not available in @planescrm/sdk/client. Use the main @planescrm/sdk entry on a server.`
119
+ );
120
+ }
121
+ function createHmac(_algorithm, _key) {
122
+ return unavailable("createHmac (webhook verification)");
123
+ }
124
+ function timingSafeEqual(_a, _b) {
125
+ return unavailable("timingSafeEqual (webhook verification)");
126
+ }
127
+
128
+ // src/oauth.ts
129
+ async function refreshAccessToken(options) {
130
+ const baseUrl = options.baseUrl.replace(/\/+$/, "");
131
+ const url = `${baseUrl}/oauth/token`;
132
+ const body = new URLSearchParams({
133
+ grant_type: "refresh_token",
134
+ client_id: options.clientId,
135
+ client_secret: options.clientSecret,
136
+ refresh_token: options.refreshToken
137
+ });
138
+ const response = await fetch(url, {
139
+ method: "POST",
140
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
141
+ body: body.toString()
142
+ });
143
+ if (!response.ok) {
144
+ const errorBody = await response.json().catch(() => ({}));
145
+ const errorCode = errorBody["error"] ?? "unknown_error";
146
+ const errorDescription = errorBody["error_description"] ?? "Token refresh failed";
147
+ throw new OAuthError(errorCode, errorDescription);
148
+ }
149
+ return await response.json();
150
+ }
151
+ async function clientCredentialsGrant(options) {
152
+ const baseUrl = options.baseUrl.replace(/\/+$/, "");
153
+ const url = `${baseUrl}/oauth/token`;
154
+ const body = new URLSearchParams({
155
+ grant_type: "client_credentials",
156
+ client_id: options.clientId,
157
+ client_secret: options.clientSecret,
158
+ scope: options.scopes.join(" ")
159
+ });
160
+ const response = await fetch(url, {
161
+ method: "POST",
162
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
163
+ body: body.toString()
164
+ });
165
+ if (!response.ok) {
166
+ const errorBody = await response.json().catch(() => ({}));
167
+ const errorCode = errorBody["error"] ?? "unknown_error";
168
+ const errorDescription = errorBody["error_description"] ?? "Client credentials grant failed";
169
+ throw new OAuthError(errorCode, errorDescription);
170
+ }
171
+ return await response.json();
172
+ }
173
+
174
+ // src/http.ts
175
+ var HttpClient = class {
176
+ constructor(config) {
177
+ this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
178
+ this.accessToken = config.accessToken;
179
+ this.apiKey = config.apiKey;
180
+ this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
181
+ this.retryOnRateLimit = config.retryOnRateLimit !== false;
182
+ this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
183
+ this.getAccessToken = config.getAccessToken;
184
+ this.onUnauthorized = config.onUnauthorized;
185
+ this.fetchImpl = config.fetch;
186
+ if (config.clientId && config.clientSecret) {
187
+ this.oauth = {
188
+ clientId: config.clientId,
189
+ clientSecret: config.clientSecret,
190
+ tokenStorage: config.tokenStorage ?? new MemoryTokenStorage(),
191
+ skewMs: config.tokenRefreshSkewMs ?? DEFAULT_TOKEN_REFRESH_SKEW_MS,
192
+ scopes: config.scopes
193
+ };
194
+ }
195
+ }
196
+ async request(options) {
197
+ const url = this.buildUrl(options.path, options.params);
198
+ const bodyStr = options.body !== void 0 ? JSON.stringify(options.body) : void 0;
199
+ let lastError;
200
+ let didRefreshOn401 = false;
201
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
202
+ const authHeaders = await this.resolveAuthHeaders();
203
+ const headers = {
204
+ "Content-Type": "application/json",
205
+ ...authHeaders,
206
+ ...options.headers
207
+ };
208
+ if (options.idempotencyKey) headers["Idempotency-Key"] = options.idempotencyKey;
209
+ const timer = timeoutSignal(this.timeout);
210
+ const fetchOptions = {
211
+ method: options.method,
212
+ headers,
213
+ signal: timer.signal
214
+ };
215
+ if (bodyStr !== void 0) {
216
+ fetchOptions.body = bodyStr;
217
+ }
218
+ try {
219
+ const response = await (this.fetchImpl ?? fetch)(url, fetchOptions);
220
+ if (response.ok) {
221
+ if (response.status === 204) {
222
+ return void 0;
223
+ }
224
+ if (options.responseType === "arrayBuffer") {
225
+ return await response.arrayBuffer();
226
+ }
227
+ return await response.json();
228
+ }
229
+ if (response.status === 429 && this.retryOnRateLimit && attempt < this.maxRetries) {
230
+ const retryAfter = this.parseRetryAfter(response);
231
+ await this.sleep(retryAfter * 1e3);
232
+ continue;
233
+ }
234
+ if (response.status === 401 && this.oauth && !didRefreshOn401) {
235
+ didRefreshOn401 = true;
236
+ await this.refreshTokens();
237
+ attempt--;
238
+ continue;
239
+ }
240
+ if (response.status === 401 && this.onUnauthorized && !didRefreshOn401) {
241
+ didRefreshOn401 = true;
242
+ if (await this.recoverSession(authHeaders["Authorization"])) {
243
+ attempt--;
244
+ continue;
245
+ }
246
+ }
247
+ lastError = await this.mapError(response);
248
+ if (response.status !== 429 || !this.retryOnRateLimit) {
249
+ throw lastError;
250
+ }
251
+ } finally {
252
+ timer.clear();
253
+ }
254
+ }
255
+ throw lastError ?? new RateLimitError();
256
+ }
257
+ getAuthHeaders() {
258
+ if (this.getAccessToken) return {};
259
+ if (this.accessToken) {
260
+ return { Authorization: `Bearer ${this.accessToken}` };
261
+ }
262
+ if (this.apiKey) {
263
+ return { Authorization: `Bearer ${this.apiKey}` };
264
+ }
265
+ return {};
266
+ }
267
+ /**
268
+ * Resolve the Authorization header for the current request. For the static
269
+ * accessToken/apiKey modes this is {@link getAuthHeaders}. For the
270
+ * OAuth-managed path it reads the stored token, proactively refreshing when
271
+ * the token is within the skew window of expiry.
272
+ */
273
+ async resolveAuthHeaders() {
274
+ if (this.getAccessToken) {
275
+ const token = await withTimeout(this.getAccessToken(), this.timeout, "getAccessToken");
276
+ return token ? { Authorization: `Bearer ${token}` } : {};
277
+ }
278
+ if (!this.oauth) {
279
+ return this.getAuthHeaders();
280
+ }
281
+ const tokens = await this.oauth.tokenStorage.getTokens();
282
+ if (!tokens) {
283
+ return {};
284
+ }
285
+ if (tokens.expiresAt - Date.now() <= this.oauth.skewMs) {
286
+ const refreshed = await this.refreshTokens();
287
+ return { Authorization: `Bearer ${refreshed.accessToken}` };
288
+ }
289
+ return { Authorization: `Bearer ${tokens.accessToken}` };
290
+ }
291
+ /**
292
+ * Refresh the OAuth access token via `refreshAccessToken` and persist the new
293
+ * tokens through the configured {@link TokenStorage}. Concurrent callers share
294
+ * a single in-flight refresh.
295
+ */
296
+ async refreshTokens() {
297
+ if (!this.oauth) {
298
+ throw new AuthenticationError("Token refresh requires the OAuth clientId/clientSecret path");
299
+ }
300
+ if (this.refreshInFlight) {
301
+ return this.refreshInFlight;
302
+ }
303
+ const oauth = this.oauth;
304
+ this.refreshInFlight = (async () => {
305
+ const current = await oauth.tokenStorage.getTokens();
306
+ if (!current?.refreshToken) {
307
+ const response2 = await clientCredentialsGrant({
308
+ baseUrl: this.baseUrl,
309
+ clientId: oauth.clientId,
310
+ clientSecret: oauth.clientSecret,
311
+ scopes: oauth.scopes ?? []
312
+ });
313
+ const next2 = {
314
+ accessToken: response2.access_token,
315
+ refreshToken: response2.refresh_token ?? null,
316
+ expiresAt: Date.now() + response2.expires_in * 1e3
317
+ };
318
+ await oauth.tokenStorage.setTokens(next2);
319
+ return next2;
320
+ }
321
+ const response = await refreshAccessToken({
322
+ baseUrl: this.baseUrl,
323
+ clientId: oauth.clientId,
324
+ clientSecret: oauth.clientSecret,
325
+ refreshToken: current.refreshToken
326
+ });
327
+ const next = {
328
+ accessToken: response.access_token,
329
+ refreshToken: response.refresh_token || current.refreshToken,
330
+ expiresAt: Date.now() + response.expires_in * 1e3
331
+ };
332
+ await oauth.tokenStorage.setTokens(next);
333
+ return next;
334
+ })();
335
+ try {
336
+ return await this.refreshInFlight;
337
+ } finally {
338
+ this.refreshInFlight = void 0;
339
+ }
340
+ }
341
+ /**
342
+ * Ask the app to refresh its session after a 401. Resolves `true` when the
343
+ * request should be retried.
344
+ * - Requests that got a 401 while a refresh is running share that one call.
345
+ * - A request whose 401 arrives after a refresh already finished (it was
346
+ * sent with the old token) doesn't start a second refresh: if the current
347
+ * token differs from the one it sent, it just retries with the new one.
348
+ * - A refresh that throws, or doesn't settle within the request timeout,
349
+ * counts as "still signed out": the original 401 surfaces.
350
+ */
351
+ async recoverSession(sentAuthorization) {
352
+ if (!this.onUnauthorized || !this.getAccessToken) return false;
353
+ if (!this.unauthorizedInFlight) {
354
+ try {
355
+ const current = await withTimeout(this.getAccessToken(), this.timeout, "getAccessToken");
356
+ if (current && `Bearer ${current}` !== sentAuthorization) return true;
357
+ } catch {
358
+ return false;
359
+ }
360
+ }
361
+ if (!this.unauthorizedInFlight) {
362
+ const call = this.onUnauthorized;
363
+ const inFlight = (async () => {
364
+ try {
365
+ return await withTimeout(call(), this.timeout, "onUnauthorized");
366
+ } catch {
367
+ return false;
368
+ }
369
+ })().finally(() => {
370
+ if (this.unauthorizedInFlight === inFlight) this.unauthorizedInFlight = void 0;
371
+ });
372
+ this.unauthorizedInFlight = inFlight;
373
+ }
374
+ return this.unauthorizedInFlight;
375
+ }
376
+ buildUrl(path, params) {
377
+ const url = new URL(`${this.baseUrl}${path}`);
378
+ if (params) {
379
+ for (const [key, value] of Object.entries(params)) {
380
+ if (value !== void 0 && value !== null) {
381
+ url.searchParams.set(key, String(value));
382
+ }
383
+ }
384
+ }
385
+ return url.toString();
386
+ }
387
+ parseRetryAfter(response) {
388
+ const header = response.headers.get("Retry-After");
389
+ if (header) {
390
+ const seconds = Number(header);
391
+ if (!Number.isNaN(seconds) && seconds > 0) {
392
+ return seconds;
393
+ }
394
+ }
395
+ return 1;
396
+ }
397
+ async mapError(response) {
398
+ let body = {};
399
+ try {
400
+ body = await response.json();
401
+ } catch {
402
+ }
403
+ const envelope = body["error"];
404
+ const message = (typeof body["message"] === "string" ? body["message"] : void 0) ?? (typeof envelope?.message === "string" ? envelope.message : void 0) ?? response.statusText ?? "Request failed";
405
+ switch (response.status) {
406
+ case 400: {
407
+ const fieldErrors = body["errors"] ?? [];
408
+ return new ValidationError(message, fieldErrors);
409
+ }
410
+ case 401:
411
+ return new AuthenticationError(message);
412
+ case 403:
413
+ return new AuthorizationError(message);
414
+ case 404:
415
+ return new NotFoundError(message);
416
+ case 429: {
417
+ const retryAfter = this.parseRetryAfter(response);
418
+ return new RateLimitError(retryAfter, message);
419
+ }
420
+ default:
421
+ if (response.status >= 500) {
422
+ return new ServerError(message);
423
+ }
424
+ return new PlanesError(message, response.status, "unknown_error");
425
+ }
426
+ }
427
+ sleep(ms) {
428
+ return new Promise((resolve) => setTimeout(resolve, ms));
429
+ }
430
+ };
431
+ function timeoutSignal(ms) {
432
+ if (typeof AbortSignal.timeout === "function") {
433
+ return { signal: AbortSignal.timeout(ms), clear: () => void 0 };
434
+ }
435
+ const controller = new AbortController();
436
+ const timer = setTimeout(() => controller.abort(), ms);
437
+ return { signal: controller.signal, clear: () => clearTimeout(timer) };
438
+ }
439
+ function withTimeout(promise, ms, what) {
440
+ return new Promise((resolve, reject) => {
441
+ const timer = setTimeout(() => reject(new Error(`${what} did not settle within ${ms}ms`)), ms);
442
+ Promise.resolve(promise).then(
443
+ (value) => {
444
+ clearTimeout(timer);
445
+ resolve(value);
446
+ },
447
+ (err) => {
448
+ clearTimeout(timer);
449
+ reject(err);
450
+ }
451
+ );
452
+ });
453
+ }
454
+
455
+ // src/resources/base-resource.ts
456
+ var ApiResource = class {
457
+ constructor(http, basePath) {
458
+ this.http = http;
459
+ this.basePath = basePath;
460
+ }
461
+ };
462
+ var BaseResource = class extends ApiResource {
463
+ /**
464
+ * List entities with optional filters and pagination.
465
+ */
466
+ async list(params) {
467
+ return this.http.request({
468
+ method: "GET",
469
+ path: this.basePath,
470
+ params
471
+ });
472
+ }
473
+ /**
474
+ * Get a single entity by ID.
475
+ */
476
+ async get(id) {
477
+ return this.http.request({
478
+ method: "GET",
479
+ path: `${this.basePath}/${id}`
480
+ });
481
+ }
482
+ /**
483
+ * Create a new entity. Pass `idempotencyKey` (a UUID you keep for retries) to
484
+ * make a retry safe on routes that honor it (customers, opportunities, contacts,
485
+ * tasks): a repeat returns the first response and creates nothing.
486
+ */
487
+ async create(data, options) {
488
+ return this.http.request({
489
+ method: "POST",
490
+ path: this.basePath,
491
+ body: data,
492
+ ...options?.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}
493
+ });
494
+ }
495
+ /**
496
+ * Update an existing entity.
497
+ */
498
+ async update(id, data) {
499
+ return this.http.request({
500
+ method: "PATCH",
501
+ path: `${this.basePath}/${id}`,
502
+ body: data
503
+ });
504
+ }
505
+ /**
506
+ * Delete an entity by ID.
507
+ */
508
+ async delete(id) {
509
+ await this.http.request({
510
+ method: "DELETE",
511
+ path: `${this.basePath}/${id}`
512
+ });
513
+ }
514
+ };
515
+
516
+ // src/resources/query-params.ts
517
+ function toQueryParams(params) {
518
+ const out = {};
519
+ if (!params) return out;
520
+ for (const [key, value] of Object.entries(params)) {
521
+ if (value === void 0 || value === null) continue;
522
+ if (key === "customFields" && typeof value === "object" && !Array.isArray(value)) {
523
+ for (const [field, v] of Object.entries(value)) {
524
+ if (v !== void 0 && v !== null) out[`cf.${field}`] = String(v);
525
+ }
526
+ continue;
527
+ }
528
+ if (Array.isArray(value)) {
529
+ if (value.length === 0) continue;
530
+ out[key] = value.map(String).join(",");
531
+ } else {
532
+ out[key] = value;
533
+ }
534
+ }
535
+ return out;
536
+ }
537
+
538
+ // src/resources/opportunities.ts
539
+ var OpportunityResource = class extends BaseResource {
540
+ constructor(http) {
541
+ super(http, "/opportunities");
542
+ }
543
+ /**
544
+ * List opportunities. `tag_ids` is ANY-of and travels as one comma-separated
545
+ * query value (`?tag_ids=a,b`), which is what the API's filter schema parses.
546
+ */
547
+ async list(params) {
548
+ return this.http.request({
549
+ method: "GET",
550
+ path: this.basePath,
551
+ params: toQueryParams(params)
552
+ });
553
+ }
554
+ /**
555
+ * GET /opportunities/trade-options — the active trades a client can request
556
+ * (`requestedTradeIds` on create/update), sorted by name.
557
+ */
558
+ async tradeOptions() {
559
+ return this.http.request({
560
+ method: "GET",
561
+ path: `${this.basePath}/trade-options`
562
+ });
563
+ }
564
+ /** PUT /opportunities/{id} — partial update; stage moves go through workflow transitions. */
565
+ async update(id, data) {
566
+ return this.http.request({
567
+ method: "PUT",
568
+ path: `${this.basePath}/${id}`,
569
+ body: data
570
+ });
571
+ }
572
+ /** GET /opportunities/:id/transitions — the pipeline moves available from the current stage, for the caller's role. */
573
+ async listTransitions(id) {
574
+ return this.http.request({ method: "GET", path: `${this.basePath}/${id}/transitions` });
575
+ }
576
+ /**
577
+ * POST /opportunities/:id/transition — take one pipeline move, as the stage button does: required
578
+ * fields are checked, the move is logged, and the stage's automations run (they can send email).
579
+ */
580
+ async transition(id, data) {
581
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/transition`, body: data });
582
+ }
583
+ /** GET /opportunities/:id/workflow — the pipeline instance with its transition history (404 if none). */
584
+ async getWorkflow(id) {
585
+ return this.http.request({ method: "GET", path: `${this.basePath}/${id}/workflow` });
586
+ }
587
+ };
588
+
589
+ // src/resources/customers.ts
590
+ var CustomerResource = class extends BaseResource {
591
+ constructor(http) {
592
+ super(http, "/customers");
593
+ }
594
+ /**
595
+ * Update a customer. The API route is `PUT /customers/{id}` (not PATCH like
596
+ * the other resources), so this overrides the base verb; the body is still a
597
+ * partial — send only the fields to change. See `UpdateCustomerDto.address`
598
+ * for how a service address resolves to a property.
599
+ */
600
+ async update(id, data) {
601
+ return this.http.request({
602
+ method: "PUT",
603
+ path: `/customers/${id}`,
604
+ body: data
605
+ });
606
+ }
607
+ /**
608
+ * List customers. `tag_ids` is ANY-of and travels as one comma-separated
609
+ * query value (`?tag_ids=a,b`), which is what the API's filter schema parses.
610
+ */
611
+ async list(params) {
612
+ return this.http.request({
613
+ method: "GET",
614
+ path: this.basePath,
615
+ params: toQueryParams(params)
616
+ });
617
+ }
618
+ /**
619
+ * Fold a duplicate company (`loserId`) into a survivor (`winnerId`).
620
+ *
621
+ * Everything hanging off the loser moves to the winner, the winner's empty
622
+ * fields are filled from the loser, and the loser is soft-deleted with a
623
+ * resolvable pointer — `GET /customers/{loserId}` afterwards returns the
624
+ * winner's detail with a `mergedFrom` pointer, so a stored loser id keeps
625
+ * working. Irreversible; requires admin scope.
626
+ */
627
+ async merge(winnerId, loserId) {
628
+ return this.http.request({
629
+ method: "POST",
630
+ path: `/customers/${winnerId}/merge/${loserId}`
631
+ });
632
+ }
633
+ /**
634
+ * POST /customers/{id}/convert-to-company — turn a person customer into a
635
+ * company. The person becomes the company's primary contact (their email and
636
+ * phone, with do-not-contact and marketing opt-outs carried over). A customer
637
+ * that's already a company is a 409 `ALREADY_COMPANY`.
638
+ */
639
+ async convertToCompany(id, data = {}) {
640
+ return this.http.request({
641
+ method: "POST",
642
+ path: `${this.basePath}/${id}/convert-to-company`,
643
+ body: data
644
+ });
645
+ }
646
+ };
647
+
648
+ // src/resources/properties.ts
649
+ var PropertyResource = class extends ApiResource {
650
+ constructor(http) {
651
+ super(http, "/properties");
652
+ }
653
+ /** GET /customers/{customerId}/properties — paginated (`page`, `limit` ≤ 100). */
654
+ async list(customerId, params) {
655
+ return this.http.request({
656
+ method: "GET",
657
+ path: `/customers/${customerId}/properties`,
658
+ params: toQueryParams(params)
659
+ });
660
+ }
661
+ /** GET /properties/{id} — one property, without naming its customer. */
662
+ async get(id) {
663
+ return this.http.request({
664
+ method: "GET",
665
+ path: `${this.basePath}/${id}`
666
+ });
667
+ }
668
+ /** POST /customers/{customerId}/properties — the property inherits the customer's org path. */
669
+ async create(customerId, data) {
670
+ return this.http.request({
671
+ method: "POST",
672
+ path: `/customers/${customerId}/properties`,
673
+ body: data
674
+ });
675
+ }
676
+ /** PUT /customers/{customerId}/properties/{id} — partial update. */
677
+ async update(customerId, id, data) {
678
+ return this.http.request({
679
+ method: "PUT",
680
+ path: `/customers/${customerId}/properties/${id}`,
681
+ body: data
682
+ });
683
+ }
684
+ /** GET /customers/:customerId/properties/:id — one property, checked against its customer (404 if it isn't theirs). */
685
+ async getForCustomer(customerId, id) {
686
+ return this.http.request({
687
+ method: "GET",
688
+ path: `/customers/${customerId}/properties/${id}`
689
+ });
690
+ }
691
+ /** POST /properties/:id/geocode — queue a fresh geocode of the property's address. */
692
+ async geocode(id) {
693
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/geocode` });
694
+ }
695
+ /** DELETE /customers/{customerId}/properties/{id} — soft delete (204). */
696
+ async delete(customerId, id) {
697
+ await this.http.request({
698
+ method: "DELETE",
699
+ path: `/customers/${customerId}/properties/${id}`
700
+ });
701
+ }
702
+ };
703
+
704
+ // src/resources/calendar-events.ts
705
+ var CalendarEventResource = class extends BaseResource {
706
+ constructor(http) {
707
+ super(http, "/events");
708
+ }
709
+ async list(params) {
710
+ return this.http.request({
711
+ method: "GET",
712
+ path: this.basePath,
713
+ params: params ?? {}
714
+ });
715
+ }
716
+ /**
717
+ * PATCH /events/:id. For an occurrence of a recurring event, `editMode`
718
+ * picks which occurrences change (`this` when omitted — the server's
719
+ * default); it is ignored for one-time events.
720
+ */
721
+ async update(id, data, options = {}) {
722
+ return this.http.request({
723
+ method: "PATCH",
724
+ path: `${this.basePath}/${id}`,
725
+ params: { recurrence_edit_mode: options.editMode },
726
+ body: data
727
+ });
728
+ }
729
+ /**
730
+ * POST /events/:id/complete — marks the event completed and runs its "on
731
+ * complete" transition, best-effort. The event is completed even when the
732
+ * transition can't run; `workflow_trigger` says whether it fired, was
733
+ * skipped (none set, or `handled_by_pipeline_rule`: the pipeline's rule
734
+ * moves the record instead) or failed (with a reason).
735
+ */
736
+ async complete(id, body = {}) {
737
+ return this.http.request({
738
+ method: "POST",
739
+ path: `${this.basePath}/${id}/complete`,
740
+ body
741
+ });
742
+ }
743
+ /**
744
+ * POST /events/:id/cancel. For an occurrence of a recurring event, `editMode`
745
+ * picks which occurrences are cancelled (`this` when omitted). 409 if already
746
+ * cancelled; 422 for a completed event.
747
+ */
748
+ async cancel(id, options = {}) {
749
+ return this.http.request({
750
+ method: "POST",
751
+ path: `${this.basePath}/${id}/cancel`,
752
+ params: { recurrence_edit_mode: options.editMode }
753
+ });
754
+ }
755
+ /** POST /events/:id/participants — add a user, contact, crew or agent to the event. No invite is sent. */
756
+ async addParticipant(id, data) {
757
+ return this.http.request({
758
+ method: "POST",
759
+ path: `${this.basePath}/${id}/participants`,
760
+ body: data
761
+ });
762
+ }
763
+ /** PATCH /events/:id/participants/:participantId — set a participant's response. */
764
+ async updateParticipantStatus(id, participantId, status) {
765
+ return this.http.request({
766
+ method: "PATCH",
767
+ path: `${this.basePath}/${id}/participants/${participantId}`,
768
+ body: { status }
769
+ });
770
+ }
771
+ };
772
+
773
+ // src/resources/contracts.ts
774
+ var ContractResource = class extends BaseResource {
775
+ constructor(http) {
776
+ super(http, "/contracts");
777
+ }
778
+ /** POST /contracts/for-subject — a bare agreement for a customer or a service schedule (no opportunity, no line groups). */
779
+ async createForSubject(data) {
780
+ return this.http.request({ method: "POST", path: `${this.basePath}/for-subject`, body: data });
781
+ }
782
+ /** POST /contracts/flat — a contract on an opportunity with a manually entered total and a contract template, no estimates. */
783
+ async createFlat(data) {
784
+ return this.http.request({ method: "POST", path: `${this.basePath}/flat`, body: data });
785
+ }
786
+ /** POST /contracts/{id}/change-orders — a change order on a signed or fulfilled contract (409 otherwise). */
787
+ async createChangeOrder(id, data) {
788
+ return this.http.request({
789
+ method: "POST",
790
+ path: `${this.basePath}/${id}/change-orders`,
791
+ body: data
792
+ });
793
+ }
794
+ /**
795
+ * GET /contracts/{id}/change-orders — the change orders written against a
796
+ * contract, oldest first, each with its line groups. A change order has none
797
+ * of its own, so asking for one returns an empty list.
798
+ */
799
+ async listChangeOrders(id) {
800
+ return this.http.request({
801
+ method: "GET",
802
+ path: `${this.basePath}/${id}/change-orders`
803
+ });
804
+ }
805
+ /** POST /contracts/{id}/submit — submit for approval; auto-approved when under the tenant's threshold. */
806
+ async submit(id) {
807
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/submit` });
808
+ }
809
+ /** POST /contracts/{id}/approve — approve a contract pending approval (needs the approve grant). */
810
+ async approve(id) {
811
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/approve` });
812
+ }
813
+ /** POST /contracts/{id}/cancel — cancel a contract in any state before it's signed. */
814
+ async cancel(id) {
815
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/cancel` });
816
+ }
817
+ /** POST /contracts/{id}/reopen — return a kicked-back contract to draft for review and re-send. */
818
+ async reopen(id) {
819
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/reopen` });
820
+ }
821
+ /**
822
+ * POST /contracts/{id}/send — **emails the signer a "Review & Sign" link.**
823
+ * Snapshots the clauses and creates the signing token. An empty body
824
+ * addresses the customer; `signerContactId` sends it to that contact instead.
825
+ * The first send of a contract uses one unit of the tenant's e-signature
826
+ * allowance; a re-send doesn't. Not safe to retry blindly after a timeout: a
827
+ * repeat emails again.
828
+ */
829
+ async send(id, data = {}) {
830
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/send`, body: data });
831
+ }
832
+ /**
833
+ * GET /contracts/{id}/pdf — the contract PDF bytes. `type: 'signed'` returns
834
+ * the stored signed copy (404 until it's signed); otherwise a preview renders.
835
+ */
836
+ async downloadPdf(id, options = {}) {
837
+ return this.http.request({
838
+ method: "GET",
839
+ path: `${this.basePath}/${id}/pdf`,
840
+ params: options.type ? { type: options.type } : {},
841
+ headers: { Accept: "application/pdf" },
842
+ responseType: "arrayBuffer"
843
+ });
844
+ }
845
+ };
846
+
847
+ // src/resources/jobs.ts
848
+ var JobResource = class extends ApiResource {
849
+ constructor(http) {
850
+ super(http, "/jobs");
851
+ }
852
+ /** The jobs under one opportunity — the same route as `listForOpportunity()`. */
853
+ async list(opportunityId, params) {
854
+ return this.listForOpportunity(opportunityId, params);
855
+ }
856
+ /**
857
+ * List the jobs under one opportunity — `GET /opportunities/{opportunityId}/jobs`,
858
+ * the API's job list route. Default order is `created_at` desc;
859
+ * `sort_by: 'recent'` puts the calling user's most recently opened jobs first.
860
+ */
861
+ async listForOpportunity(opportunityId, params) {
862
+ return this.http.request({
863
+ method: "GET",
864
+ path: `/opportunities/${opportunityId}/jobs`,
865
+ params: toQueryParams(params)
866
+ });
867
+ }
868
+ /** GET /opportunities/{opportunityId}/jobs/{id} */
869
+ async get(opportunityId, id) {
870
+ return this.http.request({
871
+ method: "GET",
872
+ path: `/opportunities/${opportunityId}/jobs/${id}`
873
+ });
874
+ }
875
+ /**
876
+ * POST /opportunities/{opportunityId}/jobs — 422 WORKFLOW_NOT_CONFIGURED when
877
+ * the trade has no published job workflow (check `getTradeCoverage()` first).
878
+ */
879
+ async create(opportunityId, data) {
880
+ return this.http.request({
881
+ method: "POST",
882
+ path: `/opportunities/${opportunityId}/jobs`,
883
+ body: data
884
+ });
885
+ }
886
+ /** PUT /opportunities/{opportunityId}/jobs/{id} — partial update (status, notes). */
887
+ async update(opportunityId, id, data) {
888
+ return this.http.request({
889
+ method: "PUT",
890
+ path: `/opportunities/${opportunityId}/jobs/${id}`,
891
+ body: data
892
+ });
893
+ }
894
+ /** DELETE /opportunities/{opportunityId}/jobs/{id} — soft delete (204). */
895
+ async delete(opportunityId, id) {
896
+ await this.http.request({
897
+ method: "DELETE",
898
+ path: `/opportunities/${opportunityId}/jobs/${id}`
899
+ });
900
+ }
901
+ /**
902
+ * GET /jobs/trade-coverage — every active trade with whether a job can be
903
+ * created under it (a published job workflow resolves: the trade's own or the
904
+ * generic one). Check before creating a job to avoid a 422
905
+ * WORKFLOW_NOT_CONFIGURED. Readable by any role that can create jobs (403
906
+ * otherwise); carries no workflow details.
907
+ */
908
+ async getTradeCoverage() {
909
+ return this.http.request({
910
+ method: "GET",
911
+ path: "/jobs/trade-coverage"
912
+ });
913
+ }
914
+ /** GET /jobs/{id}/workflow — the job's pipeline instance with its transition history (404 if none). */
915
+ async getWorkflow(id) {
916
+ return this.http.request({ method: "GET", path: `${this.basePath}/${id}/workflow` });
917
+ }
918
+ /**
919
+ * POST /jobs/{id}/transition — take one pipeline move, as the stage button
920
+ * does: required fields are checked, the move is logged, and **the
921
+ * transition's actions run**. A tenant can attach actions that create or send
922
+ * an invoice, charge a saved card, send a contract, or send email, SMS or a
923
+ * webhook. Not safe to retry blindly after a timeout: check `getWorkflow()`
924
+ * first, because a repeat runs the actions again.
925
+ */
926
+ async transition(id, data) {
927
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/transition`, body: data });
928
+ }
929
+ /** GET /jobs/{id}/transitions — the pipeline moves available from the job's current stage, for the caller's role. */
930
+ async listTransitions(id) {
931
+ return this.http.request({
932
+ method: "GET",
933
+ path: `${this.basePath}/${id}/transitions`
934
+ });
935
+ }
936
+ };
937
+
938
+ // src/resources/estimates.ts
939
+ var EstimateResource = class extends ApiResource {
940
+ constructor(http) {
941
+ super(http, "/estimates");
942
+ }
943
+ /** GET /jobs/{jobId}/estimates — newest first, paginated (`page`, `limit` ≤ 100). */
944
+ async list(jobId, params) {
945
+ return this.http.request({
946
+ method: "GET",
947
+ path: `/jobs/${jobId}/estimates`,
948
+ params: toQueryParams(params)
949
+ });
950
+ }
951
+ /**
952
+ * Every estimate across all of one opportunity's jobs, in one request —
953
+ * `GET /opportunities/{opportunityId}/estimates`. Newest first; each row
954
+ * carries its `jobId`. Paginated with `page` / `limit` (max 100).
955
+ */
956
+ async listForOpportunity(opportunityId, params) {
957
+ return this.http.request({
958
+ method: "GET",
959
+ path: `/opportunities/${opportunityId}/estimates`,
960
+ params: toQueryParams(params)
961
+ });
962
+ }
963
+ /** GET /jobs/{jobId}/estimates/{id} — the estimate with its line items. */
964
+ async get(jobId, id) {
965
+ return this.http.request({
966
+ method: "GET",
967
+ path: `/jobs/${jobId}/estimates/${id}`
968
+ });
969
+ }
970
+ /** POST /jobs/{jobId}/estimates — optionally cloned from an estimate template. */
971
+ async create(jobId, data) {
972
+ return this.http.request({
973
+ method: "POST",
974
+ path: `/jobs/${jobId}/estimates`,
975
+ body: data
976
+ });
977
+ }
978
+ /** PUT /jobs/{jobId}/estimates/{id} — partial update (measurements, notes, discount, tax). */
979
+ async update(jobId, id, data) {
980
+ return this.http.request({
981
+ method: "PUT",
982
+ path: `/jobs/${jobId}/estimates/${id}`,
983
+ body: data
984
+ });
985
+ }
986
+ /** DELETE /jobs/{jobId}/estimates/{id} — soft delete (204). */
987
+ async delete(jobId, id) {
988
+ await this.http.request({
989
+ method: "DELETE",
990
+ path: `/jobs/${jobId}/estimates/${id}`
991
+ });
992
+ }
993
+ /** GET /estimates/{id}/workflow — the estimate's pipeline instance with its transition history (404 if none). */
994
+ async getWorkflow(id) {
995
+ return this.http.request({ method: "GET", path: `${this.basePath}/${id}/workflow` });
996
+ }
997
+ /**
998
+ * POST /estimates/{id}/transition — take one pipeline move. **The
999
+ * transition's actions run**, as for `jobs.transition()`: a tenant can attach
1000
+ * actions that bill, charge, send a contract, or send email, SMS or a webhook.
1001
+ * Not safe to retry blindly after a timeout: check `getWorkflow()` first.
1002
+ */
1003
+ async transition(id, data) {
1004
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/transition`, body: data });
1005
+ }
1006
+ /**
1007
+ * PUT /jobs/{jobId}/estimates/{id}/status — move the estimate's status (see
1008
+ * `UpdateEstimateStatusDto` for the allowed moves). The route itself sends
1009
+ * nothing and creates no contract or invoice; a tenant's webhooks or
1010
+ * automations on the status change can.
1011
+ */
1012
+ async updateStatus(jobId, id, data) {
1013
+ return this.http.request({
1014
+ method: "PUT",
1015
+ path: `/jobs/${jobId}/estimates/${id}/status`,
1016
+ body: data
1017
+ });
1018
+ }
1019
+ /** GET /estimates/{id}/transitions — the pipeline moves available from the estimate's current stage, for the caller's role. */
1020
+ async listTransitions(id) {
1021
+ return this.http.request({
1022
+ method: "GET",
1023
+ path: `${this.basePath}/${id}/transitions`
1024
+ });
1025
+ }
1026
+ /**
1027
+ * POST /jobs/{jobId}/estimates/{estimateId}/line-items — add a line item. With
1028
+ * `materialCatalogId` or `tradeLaborItemId`, the catalog fills in description,
1029
+ * unit and price. The estimate's subtotal and total are recalculated.
1030
+ */
1031
+ async createLineItem(jobId, estimateId, data) {
1032
+ return this.http.request({
1033
+ method: "POST",
1034
+ path: `/jobs/${jobId}/estimates/${estimateId}/line-items`,
1035
+ body: data
1036
+ });
1037
+ }
1038
+ /** PUT /jobs/{jobId}/estimates/{estimateId}/line-items/{id} — partial update; totals are recalculated. */
1039
+ async updateLineItem(jobId, estimateId, id, data) {
1040
+ return this.http.request({
1041
+ method: "PUT",
1042
+ path: `/jobs/${jobId}/estimates/${estimateId}/line-items/${id}`,
1043
+ body: data
1044
+ });
1045
+ }
1046
+ /** DELETE /jobs/{jobId}/estimates/{estimateId}/line-items/{id} — totals are recalculated. */
1047
+ async deleteLineItem(jobId, estimateId, id) {
1048
+ await this.http.request({
1049
+ method: "DELETE",
1050
+ path: `/jobs/${jobId}/estimates/${estimateId}/line-items/${id}`
1051
+ });
1052
+ }
1053
+ /** PUT /jobs/{jobId}/estimates/{estimateId}/line-items/reorder — set each item's `sortOrder` (and optionally `section`) in one call. */
1054
+ async reorderLineItems(jobId, estimateId, data) {
1055
+ return this.http.request({
1056
+ method: "PUT",
1057
+ path: `/jobs/${jobId}/estimates/${estimateId}/line-items/reorder`,
1058
+ body: data
1059
+ });
1060
+ }
1061
+ };
1062
+
1063
+ // src/resources/invoices.ts
1064
+ var InvoiceResource = class extends BaseResource {
1065
+ constructor(http) {
1066
+ super(http, "/admin/invoices");
1067
+ }
1068
+ /** List invoices, newest first. Each row carries the customer's `customerName`. */
1069
+ async list(params) {
1070
+ return this.http.request({
1071
+ method: "GET",
1072
+ path: this.basePath,
1073
+ params
1074
+ });
1075
+ }
1076
+ /**
1077
+ * GET /admin/invoices/:id — the invoice with its line items, payments
1078
+ * (including any `needs_review` payment) and `payLink` state.
1079
+ */
1080
+ async get(id) {
1081
+ return this.http.request({
1082
+ method: "GET",
1083
+ path: `${this.basePath}/${id}`
1084
+ });
1085
+ }
1086
+ /**
1087
+ * POST /admin/invoices/:id/pay-link — issue a fresh durable pay link for a
1088
+ * `sent` or `partially_paid` invoice (Send Invoice grant) and return its URL,
1089
+ * e.g. to share by text. Rotates: the previously emailed link stops working.
1090
+ * Any other status → 409 `INVOICE_NOT_PAYABLE`.
1091
+ */
1092
+ async createPayLink(id) {
1093
+ return this.http.request({
1094
+ method: "POST",
1095
+ path: `${this.basePath}/${id}/pay-link`
1096
+ });
1097
+ }
1098
+ /**
1099
+ * GET /admin/invoices/:id/pdf — the invoice PDF bytes (Read Invoice grant).
1100
+ * A sent invoice returns the copy stored when it was sent; a draft renders on
1101
+ * demand with a DRAFT watermark.
1102
+ */
1103
+ async downloadPdf(id) {
1104
+ return this.http.request({
1105
+ method: "GET",
1106
+ path: `${this.basePath}/${id}/pdf`,
1107
+ headers: { Accept: "application/pdf" },
1108
+ responseType: "arrayBuffer"
1109
+ });
1110
+ }
1111
+ /**
1112
+ * GET /admin/invoices/overdue — sent / partially paid invoices with a balance
1113
+ * past their due date, most overdue first, each with `daysOverdue` and the
1114
+ * last overdue offset reached (E56-F8-S2). Read Invoice.
1115
+ */
1116
+ async listOverdue(params) {
1117
+ return this.http.request({
1118
+ method: "GET",
1119
+ path: `${this.basePath}/overdue`,
1120
+ params
1121
+ });
1122
+ }
1123
+ /** GET /admin/invoices/{invoiceId}/payments — every payment recorded against the invoice (Read Payment). */
1124
+ async listPayments(invoiceId) {
1125
+ return this.http.request({
1126
+ method: "GET",
1127
+ path: `${this.basePath}/${invoiceId}/payments`
1128
+ });
1129
+ }
1130
+ /**
1131
+ * GET /admin/payments/recording-settings — the tenant's resolved
1132
+ * payment-recording settings (whether manual recording is on, and which
1133
+ * methods). Read Invoice.
1134
+ */
1135
+ async getPaymentRecordingSettings() {
1136
+ return this.http.request({
1137
+ method: "GET",
1138
+ path: "/admin/payments/recording-settings"
1139
+ });
1140
+ }
1141
+ /** GET /admin/invoices/overdue/summary — `{ count, total }` of every overdue invoice. Read Invoice. */
1142
+ async overdueSummary() {
1143
+ return this.http.request({
1144
+ method: "GET",
1145
+ path: `${this.basePath}/overdue/summary`
1146
+ });
1147
+ }
1148
+ };
1149
+
1150
+ // src/resources/inventory.ts
1151
+ var InventoryResource = class extends BaseResource {
1152
+ constructor(http) {
1153
+ super(http, "/admin/inventory/items");
1154
+ }
1155
+ async list(params) {
1156
+ return this.http.request({
1157
+ method: "GET",
1158
+ path: this.basePath,
1159
+ params: toQueryParams(params)
1160
+ });
1161
+ }
1162
+ /** PUT /admin/inventory/items/{id} — partial update. */
1163
+ async update(id, data) {
1164
+ return this.http.request({
1165
+ method: "PUT",
1166
+ path: `${this.basePath}/${id}`,
1167
+ body: data
1168
+ });
1169
+ }
1170
+ // ---- Material used on a job (E64-S9). The routes live under /jobs/{jobId}. ----
1171
+ /**
1172
+ * POST /jobs/{jobId}/consumption — record stock drawn from a location for a
1173
+ * job. Each line lowers that location's on-hand quantity.
1174
+ */
1175
+ async recordJobConsumption(jobId, data) {
1176
+ return this.http.request({
1177
+ method: "POST",
1178
+ path: `/jobs/${jobId}/consumption`,
1179
+ body: data
1180
+ });
1181
+ }
1182
+ /**
1183
+ * GET /jobs/{jobId}/consumption — one page of the job's consume and return
1184
+ * movements (newest first by default), the job's totals across every page,
1185
+ * and page metadata. The rows are under `items`, not `data`.
1186
+ */
1187
+ async listJobConsumption(jobId, params) {
1188
+ return this.http.request({
1189
+ method: "GET",
1190
+ path: `/jobs/${jobId}/consumption`,
1191
+ params: toQueryParams(params)
1192
+ });
1193
+ }
1194
+ /** POST /jobs/{jobId}/return — put unused stock from a job back into a location. */
1195
+ async returnFromJob(jobId, data) {
1196
+ return this.http.request({
1197
+ method: "POST",
1198
+ path: `/jobs/${jobId}/return`,
1199
+ body: data
1200
+ });
1201
+ }
1202
+ /** GET /jobs/{jobId}/material-variance — estimated vs actual material for the job. */
1203
+ async getJobMaterialVariance(jobId) {
1204
+ return this.http.request({
1205
+ method: "GET",
1206
+ path: `/jobs/${jobId}/material-variance`
1207
+ });
1208
+ }
1209
+ };
1210
+
1211
+ // src/resources/contacts.ts
1212
+ var ContactChannelResource = class {
1213
+ constructor(http, contactId) {
1214
+ this.http = http;
1215
+ this.contactId = contactId;
1216
+ }
1217
+ /** Returns `{ channel, duplicateOf }` — `duplicateOf` is the dedup signal. */
1218
+ async create(data) {
1219
+ return this.http.request({
1220
+ method: "POST",
1221
+ path: `/contacts/${this.contactId}/channels`,
1222
+ body: data
1223
+ });
1224
+ }
1225
+ async update(channelId, data) {
1226
+ return this.http.request({
1227
+ method: "PATCH",
1228
+ path: `/contacts/${this.contactId}/channels/${channelId}`,
1229
+ body: data
1230
+ });
1231
+ }
1232
+ async delete(channelId) {
1233
+ await this.http.request({
1234
+ method: "DELETE",
1235
+ path: `/contacts/${this.contactId}/channels/${channelId}`
1236
+ });
1237
+ }
1238
+ };
1239
+ var ContactResource = class extends BaseResource {
1240
+ constructor(http) {
1241
+ super(http, "/contacts");
1242
+ }
1243
+ /**
1244
+ * List contacts. Typed against the real filter schema (customer_id /
1245
+ * property_id / q / sort_by / sort_order / page / limit / include) — the base
1246
+ * `list` would accept any key and let a typo reach the server as a 400.
1247
+ * `include: ['channels', 'links']` attaches each row's channels and active
1248
+ * links in the same response.
1249
+ */
1250
+ async list(params) {
1251
+ return this.http.request({
1252
+ method: "GET",
1253
+ path: this.basePath,
1254
+ params: toQueryParams(params)
1255
+ });
1256
+ }
1257
+ async merge(winnerId, loserId) {
1258
+ return this.http.request({
1259
+ method: "POST",
1260
+ path: `/contacts/${winnerId}/merge/${loserId}`
1261
+ });
1262
+ }
1263
+ /** GET /contacts/roles — the distinct roles in use on active links, for a role picker. */
1264
+ async listRoles() {
1265
+ return this.http.request({ method: "GET", path: "/contacts/roles" });
1266
+ }
1267
+ /** GET /contacts/:id/links — every link, active and ended (history). `get()` returns active links only. */
1268
+ async listLinks(contactId) {
1269
+ return this.http.request({ method: "GET", path: `/contacts/${contactId}/links` });
1270
+ }
1271
+ /** POST /contacts/:id/links — link the contact to a customer or property. */
1272
+ async addLink(contactId, data) {
1273
+ return this.http.request({ method: "POST", path: `/contacts/${contactId}/links`, body: data });
1274
+ }
1275
+ /** PATCH /contacts/:id/links/:linkId — change role/primary, or end the link (`endedAt`). */
1276
+ async updateLink(contactId, linkId, data) {
1277
+ return this.http.request({
1278
+ method: "PATCH",
1279
+ path: `/contacts/${contactId}/links/${linkId}`,
1280
+ body: data
1281
+ });
1282
+ }
1283
+ /** POST /contacts/:id/workflow/start — opt the contact into the relationship pipeline (409 if started). */
1284
+ async startWorkflow(contactId) {
1285
+ return this.http.request({ method: "POST", path: `/contacts/${contactId}/workflow/start` });
1286
+ }
1287
+ /** GET /contacts/:id/workflow — current stage and the transitions available from it. */
1288
+ async getWorkflow(contactId) {
1289
+ return this.http.request({ method: "GET", path: `/contacts/${contactId}/workflow` });
1290
+ }
1291
+ /** POST /contacts/:id/workflow/transitions/:transitionId — 422 for an invalid move or unmet required fields. */
1292
+ async transition(contactId, transitionId) {
1293
+ return this.http.request({
1294
+ method: "POST",
1295
+ path: `/contacts/${contactId}/workflow/transitions/${transitionId}`,
1296
+ body: {}
1297
+ });
1298
+ }
1299
+ /** GET /contacts/:id/workflow/history */
1300
+ async getWorkflowHistory(contactId) {
1301
+ return this.http.request({ method: "GET", path: `/contacts/${contactId}/workflow/history` });
1302
+ }
1303
+ channels(contactId) {
1304
+ return new ContactChannelResource(this.http, contactId);
1305
+ }
1306
+ };
1307
+
1308
+ // src/resources/activities.ts
1309
+ var ActivityResource = class {
1310
+ constructor(http) {
1311
+ this.http = http;
1312
+ }
1313
+ async create(data) {
1314
+ return this.http.request({
1315
+ method: "POST",
1316
+ path: "/activities",
1317
+ body: data
1318
+ });
1319
+ }
1320
+ async list(params) {
1321
+ return this.http.request({
1322
+ method: "GET",
1323
+ path: "/activities",
1324
+ params
1325
+ });
1326
+ }
1327
+ async listForEntity(entityType, entityId, params) {
1328
+ return this.http.request({
1329
+ method: "GET",
1330
+ path: `/${entityType}/${entityId}/activities`,
1331
+ params
1332
+ });
1333
+ }
1334
+ };
1335
+
1336
+ // src/resources/communications.ts
1337
+ var CommunicationsResource = class {
1338
+ constructor(http) {
1339
+ this.http = http;
1340
+ }
1341
+ async log(data) {
1342
+ return this.http.request({
1343
+ method: "POST",
1344
+ path: "/communications",
1345
+ body: data
1346
+ });
1347
+ }
1348
+ async list(params) {
1349
+ return this.http.request({
1350
+ method: "GET",
1351
+ path: "/communications",
1352
+ params
1353
+ });
1354
+ }
1355
+ async get(id) {
1356
+ return this.http.request({
1357
+ method: "GET",
1358
+ path: `/communications/${id}`
1359
+ });
1360
+ }
1361
+ async link(id, data) {
1362
+ return this.http.request({
1363
+ method: "POST",
1364
+ path: `/communications/${id}/link`,
1365
+ body: data
1366
+ });
1367
+ }
1368
+ };
1369
+
1370
+ // src/resources/conversations.ts
1371
+ var ConversationsResource = class {
1372
+ constructor(http) {
1373
+ this.http = http;
1374
+ }
1375
+ async log(data) {
1376
+ return this.http.request({ method: "POST", path: "/conversations", body: data });
1377
+ }
1378
+ async list(params) {
1379
+ return this.http.request({ method: "GET", path: "/conversations", params });
1380
+ }
1381
+ /** The review queue: `list()` pinned to `match_status: 'needs_review'`. */
1382
+ async reviewQueue(params) {
1383
+ return this.list({ ...params, match_status: "needs_review" });
1384
+ }
1385
+ async get(id) {
1386
+ return this.http.request({ method: "GET", path: `/conversations/${encodeURIComponent(id)}` });
1387
+ }
1388
+ async update(id, data) {
1389
+ return this.http.request({ method: "PATCH", path: `/conversations/${encodeURIComponent(id)}`, body: data });
1390
+ }
1391
+ async delete(id) {
1392
+ await this.http.request({ method: "DELETE", path: `/conversations/${encodeURIComponent(id)}` });
1393
+ }
1394
+ async link(id, data) {
1395
+ return this.http.request({ method: "POST", path: `/conversations/${encodeURIComponent(id)}/links`, body: data });
1396
+ }
1397
+ async unlink(id, linkId) {
1398
+ return this.http.request({
1399
+ method: "DELETE",
1400
+ path: `/conversations/${encodeURIComponent(id)}/links/${encodeURIComponent(linkId)}`
1401
+ });
1402
+ }
1403
+ async resolve(id, data) {
1404
+ return this.http.request({ method: "POST", path: `/conversations/${encodeURIComponent(id)}/resolve`, body: data });
1405
+ }
1406
+ async getInternalDomains() {
1407
+ return this.http.request({ method: "GET", path: "/conversations/settings/internal-domains" });
1408
+ }
1409
+ /** Requires an admin: the server checks `Update` on `Subject.Tenant` (tenant-wide matching config), not `Subject.Conversation`. */
1410
+ async setInternalDomains(data) {
1411
+ return this.http.request({ method: "PUT", path: "/conversations/settings/internal-domains", body: data });
1412
+ }
1413
+ /**
1414
+ * E57-F2-S4 — disconnect the CALLER's own Circleback connection (Update
1415
+ * Conversation). Another user's connection id is a 404. Connecting is the
1416
+ * interactive browser OAuth flow (Settings → Conversations), not an SDK call.
1417
+ */
1418
+ async disconnectCircleback(data) {
1419
+ return this.http.request({
1420
+ method: "POST",
1421
+ path: "/conversations/sources/circleback/disconnect",
1422
+ body: data
1423
+ });
1424
+ }
1425
+ /**
1426
+ * E57-F2-S8 — pull one company's meetings from every active teammate's
1427
+ * connected source (Update Conversation). 202, runs in the background.
1428
+ * 404 for a company you can't see; 409 `NO_SOURCES` when nobody has one.
1429
+ */
1430
+ async pull(data) {
1431
+ return this.http.request({ method: "POST", path: "/conversations/pull", body: data });
1432
+ }
1433
+ /**
1434
+ * E57-F2-S9 — whether a Pull has finished: pass the `job_ids` `pull()`
1435
+ * returned (1–50). Update Conversation, like `pull()`. 404
1436
+ * `PULL_NOT_FOUND` when none of them is readable (expired after ~2h,
1437
+ * unknown) — treat that as settled.
1438
+ */
1439
+ async getPullStatus(jobIds) {
1440
+ return this.http.request({
1441
+ method: "GET",
1442
+ path: "/conversations/pull/status",
1443
+ params: { job_ids: jobIds.join(",") }
1444
+ });
1445
+ }
1446
+ /** E57-F2-S8 — sync the caller's OWN Circleback connection now (deduplicated). 409 `NO_CONNECTION` when they have none. */
1447
+ async syncNow() {
1448
+ return this.http.request({ method: "POST", path: "/conversations/sources/circleback/sync-now" });
1449
+ }
1450
+ /** E57-F2-S8 — the caller's own connection, `has_sources`, and (admins only) the roster. */
1451
+ async syncStatus() {
1452
+ return this.http.request({ method: "GET", path: "/conversations/sync-status" });
1453
+ }
1454
+ /**
1455
+ * E57-F4-S1 — a synced meeting's transcript, fetched live from the meeting
1456
+ * recorder (never stored by Planes; the response is `Cache-Control:
1457
+ * no-store`). Read Conversation, plus the tenant's transcript-access rule:
1458
+ * 403 `TRANSCRIPT_OWNER_ONLY` under `owner` for a non-owner; 409
1459
+ * `TRANSCRIPT_SOURCE_UNAVAILABLE` (`owner_name` says who must reconnect) or
1460
+ * `TRANSCRIPT_NOT_AVAILABLE` (not a synced meeting); 404 when you can't see
1461
+ * the conversation. `segments: []` = no transcript yet.
1462
+ */
1463
+ async getTranscript(id) {
1464
+ return this.http.request({
1465
+ method: "GET",
1466
+ path: `/conversations/${encodeURIComponent(id)}/transcript`
1467
+ });
1468
+ }
1469
+ /** E57-F4-S1 — who can view transcripts: `owner` (default) or `viewers`. Read Conversation. */
1470
+ async getTranscriptAccess() {
1471
+ return this.http.request({ method: "GET", path: "/conversations/settings/transcript-access" });
1472
+ }
1473
+ /** E57-F4-S1 — requires an admin: the server checks `Update` on `Subject.Tenant`. */
1474
+ async setTranscriptAccess(value) {
1475
+ return this.http.request({
1476
+ method: "PUT",
1477
+ path: "/conversations/settings/transcript-access",
1478
+ body: { transcript_access: value }
1479
+ });
1480
+ }
1481
+ };
1482
+
1483
+ // src/resources/gmail.ts
1484
+ var GmailResource = class {
1485
+ constructor(http) {
1486
+ this.http = http;
1487
+ }
1488
+ /**
1489
+ * Send an email RIGHT NOW from the connected user's real Gmail address.
1490
+ * Hits `POST /admin/integrations/google/gmail/send` — final per Task 4
1491
+ * (`apps/api/src/modules/integrations/google/google-connection.controller.ts`).
1492
+ */
1493
+ async send(data) {
1494
+ return this.http.request({
1495
+ method: "POST",
1496
+ path: "/admin/integrations/google/gmail/send",
1497
+ body: data
1498
+ });
1499
+ }
1500
+ };
1501
+
1502
+ // src/resources/documents.ts
1503
+ var DocumentsResource = class {
1504
+ constructor(http) {
1505
+ this.http = http;
1506
+ }
1507
+ /** Attach an external (link-only) document — e.g. a Google Drive link — to a record. */
1508
+ async attachExternal(data) {
1509
+ return this.http.request({
1510
+ method: "POST",
1511
+ path: "/documents/external",
1512
+ body: data
1513
+ });
1514
+ }
1515
+ /** Documents filed directly on one record (uploaded + external), newest first. */
1516
+ async listForEntity(entityType, entityId) {
1517
+ return this.http.request({
1518
+ method: "GET",
1519
+ path: `/${entityType}/${entityId}/documents`
1520
+ });
1521
+ }
1522
+ };
1523
+
1524
+ // src/resources/tags.ts
1525
+ var TagResource = class extends ApiResource {
1526
+ constructor(http) {
1527
+ super(http, "/tags");
1528
+ }
1529
+ /** GET /tags */
1530
+ async list(params) {
1531
+ return this.http.request({
1532
+ method: "GET",
1533
+ path: this.basePath,
1534
+ params
1535
+ });
1536
+ }
1537
+ /** POST /tags — 409 on a case-insensitive duplicate name. */
1538
+ async create(data) {
1539
+ return this.http.request({ method: "POST", path: this.basePath, body: data });
1540
+ }
1541
+ /** PATCH /tags/:id — rename / recolor; 409 on a case-insensitive duplicate name. */
1542
+ async update(id, data) {
1543
+ return this.http.request({ method: "PATCH", path: `${this.basePath}/${id}`, body: data });
1544
+ }
1545
+ /** DELETE /tags/:id — cascades the tag off every record. */
1546
+ async delete(id) {
1547
+ await this.http.request({ method: "DELETE", path: `${this.basePath}/${id}` });
1548
+ }
1549
+ /**
1550
+ * POST /tags/:winnerId/merge/:loserId — fold a duplicate tag into another: records
1551
+ * move to the winner (`retagged`), duplicates are dropped (`dropped`), and the
1552
+ * loser is deleted. Irreversible.
1553
+ */
1554
+ async merge(winnerId, loserId) {
1555
+ return this.http.request({ method: "POST", path: `${this.basePath}/${winnerId}/merge/${loserId}` });
1556
+ }
1557
+ /** `TagsService.setEntityTags()` returns the final tag set wrapped in `{ tags }`. */
1558
+ async setEntityTags(entityType, entityId, data) {
1559
+ return this.http.request({
1560
+ method: "PUT",
1561
+ path: `/entities/${entityType}/${entityId}/tags`,
1562
+ body: data
1563
+ });
1564
+ }
1565
+ /**
1566
+ * POST /entities/:type/:id/tags — add ONE tag, keeping the record's other tags.
1567
+ * Safe to call concurrently with other tag changes on the same record (unlike
1568
+ * read-modify-write through `setEntityTags()`). Adding a tag the record already
1569
+ * carries is a no-op. Returns the record's full tag set.
1570
+ */
1571
+ async addEntityTag(entityType, entityId, ref) {
1572
+ const body = ref.tagId !== void 0 ? { tag_id: ref.tagId } : { tag_name: ref.tagName };
1573
+ return this.http.request({
1574
+ method: "POST",
1575
+ path: `/entities/${entityType}/${entityId}/tags`,
1576
+ body
1577
+ });
1578
+ }
1579
+ /**
1580
+ * DELETE /entities/:type/:id/tags/:tagId — remove ONE tag, keeping the rest.
1581
+ * Removing a tag the record doesn't carry is a no-op. Returns the record's
1582
+ * full tag set.
1583
+ */
1584
+ async removeEntityTag(entityType, entityId, tagId) {
1585
+ return this.http.request({
1586
+ method: "DELETE",
1587
+ path: `/entities/${entityType}/${entityId}/tags/${tagId}`
1588
+ });
1589
+ }
1590
+ async getEntityTags(entityType, entityId) {
1591
+ return this.http.request({
1592
+ method: "GET",
1593
+ path: `/entities/${entityType}/${entityId}/tags`
1594
+ });
1595
+ }
1596
+ async getEntities(tagId, params) {
1597
+ return this.http.request({
1598
+ method: "GET",
1599
+ path: `/tags/${tagId}/entities`,
1600
+ params
1601
+ });
1602
+ }
1603
+ };
1604
+
1605
+ // src/resources/lists.ts
1606
+ var ListsResource = class extends ApiResource {
1607
+ constructor(http) {
1608
+ super(http, "/lists");
1609
+ }
1610
+ /** GET /lists — every list, newest first, each with `member_count`. A bare array. */
1611
+ async list() {
1612
+ return this.http.request({ method: "GET", path: this.basePath });
1613
+ }
1614
+ /**
1615
+ * GET /lists/filter-fields — the standard fields, their types and the operators
1616
+ * each accepts for a smart list of this entity type, and whether custom fields
1617
+ * are accepted (E66-S3). A save that breaks these rules is a 400.
1618
+ */
1619
+ async filterFields(entityType) {
1620
+ return this.http.request({
1621
+ method: "GET",
1622
+ path: `${this.basePath}/filter-fields`,
1623
+ params: { entity_type: entityType }
1624
+ });
1625
+ }
1626
+ /** GET /lists/:id — one list with an on-demand `member_count`. */
1627
+ async get(id) {
1628
+ return this.http.request({ method: "GET", path: `${this.basePath}/${id}` });
1629
+ }
1630
+ /** POST /lists */
1631
+ async create(data) {
1632
+ return this.http.request({ method: "POST", path: this.basePath, body: data });
1633
+ }
1634
+ /** PATCH /lists/:id — rename, or replace a smart list's definition. */
1635
+ async update(id, data) {
1636
+ return this.http.request({ method: "PATCH", path: `${this.basePath}/${id}`, body: data });
1637
+ }
1638
+ /** DELETE /lists/:id — soft delete; the records on the list are untouched. */
1639
+ async delete(id) {
1640
+ await this.http.request({ method: "DELETE", path: `${this.basePath}/${id}` });
1641
+ }
1642
+ /** POST /lists/:id/members — static lists only; idempotent on duplicates. */
1643
+ async addMembers(id, members) {
1644
+ return this.http.request({
1645
+ method: "POST",
1646
+ path: `${this.basePath}/${id}/members`,
1647
+ body: { members }
1648
+ });
1649
+ }
1650
+ /** DELETE /lists/:id/members — static lists only. */
1651
+ async removeMembers(id, members) {
1652
+ return this.http.request({
1653
+ method: "DELETE",
1654
+ path: `${this.basePath}/${id}/members`,
1655
+ body: { members }
1656
+ });
1657
+ }
1658
+ /** GET /lists/:id/recipients — people (audience, contact and customer lists), with consent. */
1659
+ async getRecipients(id, params) {
1660
+ return this.http.request({
1661
+ method: "GET",
1662
+ path: `${this.basePath}/${id}/recipients`,
1663
+ params
1664
+ });
1665
+ }
1666
+ /** POST /lists/:id/export — queues a CSV export; a notification links the file when it's ready. */
1667
+ async export(id, options) {
1668
+ return this.http.request({
1669
+ method: "POST",
1670
+ path: `${this.basePath}/${id}/export`,
1671
+ body: options ?? {}
1672
+ });
1673
+ }
1674
+ };
1675
+
1676
+ // src/resources/lead-sources.ts
1677
+ var LeadSourcesResource = class extends ApiResource {
1678
+ constructor(http) {
1679
+ super(http, "/lead-sources");
1680
+ }
1681
+ /** GET /lead-sources — active ones by default, in display order. */
1682
+ async list(options) {
1683
+ const res = await this.http.request({
1684
+ method: "GET",
1685
+ path: this.basePath,
1686
+ ...options?.includeInactive ? { params: { includeInactive: "true" } } : {}
1687
+ });
1688
+ return res.data;
1689
+ }
1690
+ /** POST /lead-sources — 409 on a duplicate key. */
1691
+ async create(data) {
1692
+ const res = await this.http.request({ method: "POST", path: this.basePath, body: data });
1693
+ return res.data;
1694
+ }
1695
+ /** PATCH /lead-sources/:id — label, active flag or order; the key can't change. */
1696
+ async update(id, data) {
1697
+ const res = await this.http.request({
1698
+ method: "PATCH",
1699
+ path: `${this.basePath}/${id}`,
1700
+ body: data
1701
+ });
1702
+ return res.data;
1703
+ }
1704
+ /** DELETE /lead-sources/:id — soft delete. */
1705
+ async delete(id) {
1706
+ await this.http.request({ method: "DELETE", path: `${this.basePath}/${id}` });
1707
+ }
1708
+ };
1709
+
1710
+ // src/resources/tasks.ts
1711
+ var TaskResource = class extends ApiResource {
1712
+ constructor(http) {
1713
+ super(http, "/tasks");
1714
+ }
1715
+ async list(params) {
1716
+ return this.http.request({
1717
+ method: "GET",
1718
+ path: this.basePath,
1719
+ params
1720
+ });
1721
+ }
1722
+ /** GET /tasks/:id */
1723
+ async get(id) {
1724
+ return this.http.request({ method: "GET", path: `${this.basePath}/${id}` });
1725
+ }
1726
+ /** POST /tasks. Pass `idempotencyKey` to make a retry safe (E64-S6). */
1727
+ async create(data, options) {
1728
+ return this.http.request({
1729
+ method: "POST",
1730
+ path: this.basePath,
1731
+ body: data,
1732
+ ...options?.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}
1733
+ });
1734
+ }
1735
+ /** PATCH /tasks/:id — non-terminal fields only; terminal status changes use the action methods. */
1736
+ async update(id, data) {
1737
+ return this.http.request({ method: "PATCH", path: `${this.basePath}/${id}`, body: data });
1738
+ }
1739
+ /**
1740
+ * POST /tasks/:id/complete — fires the linked workflow transition (best-effort).
1741
+ * The task always completes; `workflow_trigger` says whether the next step ran.
1742
+ */
1743
+ async complete(id) {
1744
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/complete` });
1745
+ }
1746
+ /** POST /tasks/:id/cancel */
1747
+ async cancel(id) {
1748
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/cancel` });
1749
+ }
1750
+ /** POST /tasks/:id/reopen — the sanctioned resurrect of a completed/cancelled task. */
1751
+ async reopen(id) {
1752
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/reopen` });
1753
+ }
1754
+ };
1755
+
1756
+ // src/resources/record-views.ts
1757
+ var RecordViewsResource = class {
1758
+ constructor(http) {
1759
+ this.http = http;
1760
+ this.basePath = "/record-views";
1761
+ }
1762
+ /** POST /record-views — record that the calling user opened this record. Resolves on 204. */
1763
+ async touch(input) {
1764
+ await this.http.request({ method: "POST", path: this.basePath, body: input });
1765
+ }
1766
+ /** GET /record-views/recent — the calling user's most recently viewed records, newest first. */
1767
+ async recent(params) {
1768
+ return this.http.request({
1769
+ method: "GET",
1770
+ path: `${this.basePath}/recent`,
1771
+ params: toQueryParams(params)
1772
+ });
1773
+ }
1774
+ };
1775
+
1776
+ // src/resources/modules.ts
1777
+ var ModulesResource = class {
1778
+ constructor(http) {
1779
+ this.http = http;
1780
+ this.basePath = "/modules";
1781
+ }
1782
+ /** GET /modules — one entry per registered module key, in canonical order. */
1783
+ async list() {
1784
+ const res = await this.http.request({
1785
+ method: "GET",
1786
+ path: this.basePath
1787
+ });
1788
+ return res.data;
1789
+ }
1790
+ };
1791
+
1792
+ // src/resources/plan.ts
1793
+ var PlanResource = class {
1794
+ constructor(http) {
1795
+ this.http = http;
1796
+ this.basePath = "/plan";
1797
+ }
1798
+ /** GET /plan — plan, billing status and the plan's ceiling. */
1799
+ async get() {
1800
+ const res = await this.http.request({
1801
+ method: "GET",
1802
+ path: this.basePath
1803
+ });
1804
+ return res.data;
1805
+ }
1806
+ };
1807
+
1808
+ // src/resources/me.ts
1809
+ var MeResource = class {
1810
+ constructor(http) {
1811
+ this.http = http;
1812
+ this.basePath = "/me";
1813
+ }
1814
+ /**
1815
+ * GET /me/abilities — the caller's effective ability: for an API key, the key
1816
+ * role intersected with its acting agent's live role (`actingRole`).
1817
+ */
1818
+ async abilities() {
1819
+ return this.http.request({
1820
+ method: "GET",
1821
+ path: `${this.basePath}/abilities`
1822
+ });
1823
+ }
1824
+ };
1825
+
1826
+ // src/resources/roles.ts
1827
+ var RolesResource = class {
1828
+ constructor(http) {
1829
+ this.http = http;
1830
+ this.basePath = "/roles";
1831
+ }
1832
+ /** GET /roles — every role (not `system_agent`) with user and change counts. */
1833
+ async list() {
1834
+ return this.http.request({ method: "GET", path: this.basePath });
1835
+ }
1836
+ /** GET /roles/:key — one role's permission matrix, summary and grant version. */
1837
+ async get(key) {
1838
+ return this.http.request({
1839
+ method: "GET",
1840
+ path: `${this.basePath}/${encodeURIComponent(key)}`
1841
+ });
1842
+ }
1843
+ /**
1844
+ * PUT /roles/:key/grants — sparse per-cell changes, all validated before any
1845
+ * is written. 422 `GRANT_REQUIRED` / `GRANT_NOT_DELEGABLE` for locked cells,
1846
+ * `CONFIRMATION_REQUIRED` when a money action is granted without
1847
+ * `confirm: true` + `reason`, `ROLE_NOT_TUNABLE` for admin; 409
1848
+ * `ROLE_VERSION_CONFLICT` on a stale `baseVersion`. Returns the updated role.
1849
+ */
1850
+ async updateGrants(key, body) {
1851
+ return this.http.request({
1852
+ method: "PUT",
1853
+ path: `${this.basePath}/${encodeURIComponent(key)}/grants`,
1854
+ body
1855
+ });
1856
+ }
1857
+ /** DELETE /roles/:key/grants — back to the Planes defaults. Returns the reset role. */
1858
+ async reset(key) {
1859
+ return this.http.request({
1860
+ method: "DELETE",
1861
+ path: `${this.basePath}/${encodeURIComponent(key)}/grants`
1862
+ });
1863
+ }
1864
+ /** GET /roles/history — the change log, newest first; page with `cursor`. */
1865
+ async history(params) {
1866
+ return this.http.request({
1867
+ method: "GET",
1868
+ path: `${this.basePath}/history`,
1869
+ ...params ? { params } : {}
1870
+ });
1871
+ }
1872
+ };
1873
+
1874
+ // src/resources/invoice-settings.ts
1875
+ var InvoiceSettingsResource = class {
1876
+ constructor(http) {
1877
+ this.http = http;
1878
+ this.basePath = "/admin/invoice-settings";
1879
+ }
1880
+ /**
1881
+ * GET /admin/invoice-settings/offline-instructions — the plain-text
1882
+ * instructions shown on the pay page when online payment is unavailable,
1883
+ * or null when none are set.
1884
+ */
1885
+ async getOfflineInstructions() {
1886
+ const res = await this.http.request({
1887
+ method: "GET",
1888
+ path: `${this.basePath}/offline-instructions`
1889
+ });
1890
+ return res.instructions;
1891
+ }
1892
+ /**
1893
+ * PUT /admin/invoice-settings/offline-instructions — store plain text
1894
+ * (trimmed, at most 2,000 characters); null or blank clears it. Returns the
1895
+ * stored value.
1896
+ */
1897
+ async setOfflineInstructions(text) {
1898
+ const body = { instructions: text };
1899
+ const res = await this.http.request({
1900
+ method: "PUT",
1901
+ path: `${this.basePath}/offline-instructions`,
1902
+ body
1903
+ });
1904
+ return res.instructions;
1905
+ }
1906
+ /**
1907
+ * GET /admin/invoice-settings/overdue-offsets — the days after the due date
1908
+ * at which `invoice.overdue` fires, ascending (default `[3, 7, 14]`).
1909
+ */
1910
+ async getOverdueOffsets() {
1911
+ const res = await this.http.request({
1912
+ method: "GET",
1913
+ path: `${this.basePath}/overdue-offsets`
1914
+ });
1915
+ return res.offsets;
1916
+ }
1917
+ /**
1918
+ * PUT /admin/invoice-settings/overdue-offsets — replace the offsets: 1 to 5
1919
+ * unique whole days, each 1–90. Returns them sorted ascending. Admin only.
1920
+ */
1921
+ async setOverdueOffsets(offsets) {
1922
+ const body = { offsets };
1923
+ const res = await this.http.request({
1924
+ method: "PUT",
1925
+ path: `${this.basePath}/overdue-offsets`,
1926
+ body
1927
+ });
1928
+ return res.offsets;
1929
+ }
1930
+ /**
1931
+ * GET /admin/invoice-settings/attach-pdf — whether invoice emails carry the
1932
+ * invoice PDF (on unless an admin turned it off).
1933
+ */
1934
+ async getAttachPdf() {
1935
+ const res = await this.http.request({
1936
+ method: "GET",
1937
+ path: `${this.basePath}/attach-pdf`
1938
+ });
1939
+ return res.enabled;
1940
+ }
1941
+ /**
1942
+ * PUT /admin/invoice-settings/attach-pdf — turn the PDF attachment on
1943
+ * invoice emails on or off. Returns the stored value.
1944
+ */
1945
+ async setAttachPdf(enabled) {
1946
+ const body = { enabled };
1947
+ const res = await this.http.request({
1948
+ method: "PUT",
1949
+ path: `${this.basePath}/attach-pdf`,
1950
+ body
1951
+ });
1952
+ return res.enabled;
1953
+ }
1954
+ };
1955
+
1956
+ // src/resources/invoice-reminders.ts
1957
+ var InvoiceRemindersResource = class {
1958
+ constructor(http) {
1959
+ this.http = http;
1960
+ this.basePath = "/admin/invoice-reminders";
1961
+ }
1962
+ /** GET /admin/invoice-reminders — the rules, ascending by offset, and the overdue offsets. */
1963
+ async list() {
1964
+ return this.http.request({
1965
+ method: "GET",
1966
+ path: this.basePath
1967
+ });
1968
+ }
1969
+ /**
1970
+ * PUT /admin/invoice-reminders — replace the WHOLE rule set (a rule left out
1971
+ * is deleted): up to 5 rules at unique offsets. Templates may use only
1972
+ * `{{customerName}}`, `{{invoiceNumber}}`, `{{amountDue}}`, `{{total}}`,
1973
+ * `{{dueDate}}`, `{{daysOverdue}}` and `{{companyName}}`; any other is a 422
1974
+ * `REMINDER_TEMPLATE_INVALID` listing each one. Returns the stored set.
1975
+ */
1976
+ async update(rules) {
1977
+ return this.http.request({
1978
+ method: "PUT",
1979
+ path: this.basePath,
1980
+ body: { rules }
1981
+ });
1982
+ }
1983
+ /**
1984
+ * POST /admin/invoice-reminders/preview — render a subject and body exactly
1985
+ * as the reminder email would, against an invoice or a sample. Sends nothing.
1986
+ */
1987
+ async preview(params) {
1988
+ return this.http.request({
1989
+ method: "POST",
1990
+ path: `${this.basePath}/preview`,
1991
+ body: params
1992
+ });
1993
+ }
1994
+ };
1995
+
1996
+ // src/resources/event-automations.ts
1997
+ var EventAutomationsResource = class {
1998
+ constructor(http) {
1999
+ this.http = http;
2000
+ }
2001
+ // Each request spells its path out in full (no computed base path) so the
2002
+ // API's SDK route-parity audit (sdk-route-parity-audit.spec.ts) can read it.
2003
+ /** GET — enabled and disabled automations, oldest first, optionally by event type or owner. */
2004
+ async list(params = {}) {
2005
+ const query = {};
2006
+ if (params.owner_tag) query["owner_tag"] = params.owner_tag;
2007
+ if (params.event_type) query["event_type"] = params.event_type;
2008
+ const res = await this.http.request({
2009
+ method: "GET",
2010
+ path: "/admin/event-automations",
2011
+ params: query
2012
+ });
2013
+ return res.data;
2014
+ }
2015
+ /** GET /:id — 404 when it doesn't exist or was deleted. */
2016
+ async get(id) {
2017
+ return this.http.request({
2018
+ method: "GET",
2019
+ path: `/admin/event-automations/${encodeURIComponent(id)}`
2020
+ });
2021
+ }
2022
+ /**
2023
+ * POST — create (201). 400 `VALIDATION_FAILED` for a bad body, or a 400
2024
+ * naming the step whose `action_type` isn't allowed in automations.
2025
+ */
2026
+ async create(input) {
2027
+ return this.http.request({
2028
+ method: "POST",
2029
+ path: "/admin/event-automations",
2030
+ body: input
2031
+ });
2032
+ }
2033
+ /**
2034
+ * PATCH /:id — only the fields sent change. Sending `actions` replaces the
2035
+ * list: keep each existing step's `id` so a step that already ran isn't run
2036
+ * again. `{ enabled: false }` switches it off.
2037
+ */
2038
+ async update(id, input) {
2039
+ return this.http.request({
2040
+ method: "PATCH",
2041
+ path: `/admin/event-automations/${encodeURIComponent(id)}`,
2042
+ body: input
2043
+ });
2044
+ }
2045
+ /** DELETE /:id — soft delete; returns `{ id }` (200). */
2046
+ async delete(id) {
2047
+ return this.http.request({
2048
+ method: "DELETE",
2049
+ path: `/admin/event-automations/${encodeURIComponent(id)}`
2050
+ });
2051
+ }
2052
+ };
2053
+
2054
+ // src/resources/web-forms.ts
2055
+ var WebFormsResource = class {
2056
+ constructor(http) {
2057
+ this.http = http;
2058
+ this.submissions = new WebFormSubmissionsResource(http);
2059
+ }
2060
+ // Each request spells its path out in full so the API's SDK route-parity
2061
+ // audit (sdk-route-parity-audit.spec.ts) can read it.
2062
+ /** GET — every form not archived, newest first. */
2063
+ async list() {
2064
+ const res = await this.http.request({ method: "GET", path: "/admin/web-forms" });
2065
+ return res.data;
2066
+ }
2067
+ /** GET /trade-options — the active trades a `trade` question offers, by current name. */
2068
+ async tradeOptions() {
2069
+ const res = await this.http.request({ method: "GET", path: "/admin/web-forms/trade-options" });
2070
+ return res.data;
2071
+ }
2072
+ /** GET /:id */
2073
+ async get(id) {
2074
+ return this.http.request({ method: "GET", path: `/admin/web-forms/${encodeURIComponent(id)}` });
2075
+ }
2076
+ /** POST — create (201) with its default routing. Pass `recipient_agent_ids`. */
2077
+ async create(input) {
2078
+ return this.http.request({ method: "POST", path: "/admin/web-forms", body: input });
2079
+ }
2080
+ /** PATCH /:id — only the fields sent change. `active: false` switches the form off. */
2081
+ async update(id, input) {
2082
+ return this.http.request({
2083
+ method: "PATCH",
2084
+ path: `/admin/web-forms/${encodeURIComponent(id)}`,
2085
+ body: input
2086
+ });
2087
+ }
2088
+ /** DELETE /:id — archive: the public URL stops working and routing stops. Returns `{ id }`. */
2089
+ async archive(id) {
2090
+ return this.http.request({ method: "DELETE", path: `/admin/web-forms/${encodeURIComponent(id)}` });
2091
+ }
2092
+ /** POST /:id/rotate-key — a new public key; the old embed stops working at once. */
2093
+ async rotateKey(id) {
2094
+ return this.http.request({
2095
+ method: "POST",
2096
+ path: `/admin/web-forms/${encodeURIComponent(id)}/rotate-key`
2097
+ });
2098
+ }
2099
+ };
2100
+ var WebFormSubmissionsResource = class {
2101
+ constructor(http) {
2102
+ this.http = http;
2103
+ }
2104
+ /** GET /submissions — the first page, newest first, with routing state. Use `listPage` to read on. */
2105
+ async list(params = {}) {
2106
+ return (await this.listPage(params)).data;
2107
+ }
2108
+ /**
2109
+ * GET /submissions — one page plus `next`, which is null on the last page.
2110
+ * Pass `next`'s `before` and `before_id` back in to read the following page.
2111
+ */
2112
+ async listPage(params = {}) {
2113
+ const query = {};
2114
+ for (const [k, v] of Object.entries(params)) if (v !== void 0) query[k] = v;
2115
+ const res = await this.http.request({
2116
+ method: "GET",
2117
+ path: "/admin/web-forms/submissions",
2118
+ params: query
2119
+ });
2120
+ return { data: res.data, next: res.next ?? null };
2121
+ }
2122
+ /** GET /submissions/:id — answers as seen, plus each routing step. */
2123
+ async get(id) {
2124
+ return this.http.request({
2125
+ method: "GET",
2126
+ path: `/admin/web-forms/submissions/${encodeURIComponent(id)}`
2127
+ });
2128
+ }
2129
+ /** PATCH /submissions/:id — set triage status. */
2130
+ async update(id, input) {
2131
+ return this.http.request({
2132
+ method: "PATCH",
2133
+ path: `/admin/web-forms/submissions/${encodeURIComponent(id)}`,
2134
+ body: input
2135
+ });
2136
+ }
2137
+ /** POST /submissions/:id/route — retry failed steps, run never-run ones (not email, text or webhook: `skipped`); safe to repeat. */
2138
+ async route(id) {
2139
+ return this.http.request({
2140
+ method: "POST",
2141
+ path: `/admin/web-forms/submissions/${encodeURIComponent(id)}/route`
2142
+ });
2143
+ }
2144
+ };
2145
+
2146
+ // src/resources/contact-sequences.ts
2147
+ var ContactSequencesResource = class {
2148
+ constructor(http) {
2149
+ this.http = http;
2150
+ this.basePath = "/contact-sequences";
2151
+ }
2152
+ /** GET /contact-sequences — `{ data, meta: { total } }`, name-sorted, max 100. */
2153
+ async list() {
2154
+ return this.http.request({
2155
+ method: "GET",
2156
+ path: this.basePath
2157
+ });
2158
+ }
2159
+ };
2160
+
2161
+ // src/resources/enrollments.ts
2162
+ var EnrollmentsResource = class {
2163
+ constructor(http) {
2164
+ this.http = http;
2165
+ }
2166
+ /**
2167
+ * POST /contacts/:id/enrollments — `{ workflow_id }`. 409 if the contact is
2168
+ * already active in the sequence; 422 if the sequence has no published version.
2169
+ */
2170
+ async enroll(contactId, workflowId) {
2171
+ return this.http.request({
2172
+ method: "POST",
2173
+ path: `/contacts/${contactId}/enrollments`,
2174
+ body: { workflow_id: workflowId }
2175
+ });
2176
+ }
2177
+ /** GET /contacts/:id/enrollments — a bare array, newest first; optional `status` filter. */
2178
+ async list(contactId, params) {
2179
+ return this.http.request({
2180
+ method: "GET",
2181
+ path: `/contacts/${contactId}/enrollments`,
2182
+ ...params ? { params } : {}
2183
+ });
2184
+ }
2185
+ /**
2186
+ * POST /enrollments/:id/exit — no body; the exit reason is recorded as
2187
+ * `'manual'`. Idempotent: an already-ended enrollment is returned unchanged.
2188
+ */
2189
+ async exit(enrollmentId) {
2190
+ return this.http.request({
2191
+ method: "POST",
2192
+ path: `/enrollments/${enrollmentId}/exit`
2193
+ });
2194
+ }
2195
+ };
2196
+
2197
+ // src/resources/workflow-event-rules.ts
2198
+ var WorkflowEventRulesResource = class {
2199
+ constructor(http, workflowId) {
2200
+ this.http = http;
2201
+ this.workflowId = workflowId;
2202
+ }
2203
+ // Each request spells its path out in full (no computed base path) so the
2204
+ // API's SDK route-parity audit (sdk-route-parity-audit.spec.ts) can read it.
2205
+ /** GET — a bare array of the workflow's live rules, newest first. 404 `WORKFLOW_NOT_FOUND`. */
2206
+ async list() {
2207
+ return this.http.request({
2208
+ method: "GET",
2209
+ path: `/admin/workflows/${encodeURIComponent(this.workflowId)}/event-rules`
2210
+ });
2211
+ }
2212
+ /**
2213
+ * POST — add a rule (201). `when` defaults to `{}` and `enabled` to true; use
2214
+ * `when: {}` for the creation types in `WORKFLOW_EVENT_RULE_MATCH_ALL_EVENT_TYPES`.
2215
+ * 400 `VALIDATION_FAILED` for a bad body; 404 `WORKFLOW_NOT_FOUND`.
2216
+ */
2217
+ async create(input) {
2218
+ return this.http.request({
2219
+ method: "POST",
2220
+ path: `/admin/workflows/${encodeURIComponent(this.workflowId)}/event-rules`,
2221
+ body: input
2222
+ });
2223
+ }
2224
+ /** PATCH /:id — only the fields sent change (at least one). 404 `EVENT_RULE_NOT_FOUND`. */
2225
+ async update(ruleId, input) {
2226
+ return this.http.request({
2227
+ method: "PATCH",
2228
+ path: `/admin/workflows/${encodeURIComponent(this.workflowId)}/event-rules/${encodeURIComponent(ruleId)}`,
2229
+ body: input
2230
+ });
2231
+ }
2232
+ /** DELETE /:id — soft delete; returns `{ id }` (200). 404 `EVENT_RULE_NOT_FOUND`. */
2233
+ async delete(ruleId) {
2234
+ return this.http.request({
2235
+ method: "DELETE",
2236
+ path: `/admin/workflows/${encodeURIComponent(this.workflowId)}/event-rules/${encodeURIComponent(ruleId)}`
2237
+ });
2238
+ }
2239
+ };
2240
+
2241
+ // src/resources/workflows.ts
2242
+ var WorkflowsResource = class {
2243
+ constructor(http) {
2244
+ this.http = http;
2245
+ this.basePath = "/workflows";
2246
+ this.adminPath = "/admin/workflows";
2247
+ }
2248
+ /**
2249
+ * GET /workflows/:id/stages — the ordered stages of one workflow version. Pass
2250
+ * a record's instance `workflowId` (e.g. from `GET /opportunities/:id/workflow`)
2251
+ * to get the stages of the version that record is pinned to, even an archived
2252
+ * one. 404 for an unknown or draft id; 403 if the caller cannot read the
2253
+ * workflow's record type.
2254
+ */
2255
+ async getStages(workflowId) {
2256
+ return this.http.request({
2257
+ method: "GET",
2258
+ path: `${this.basePath}/${encodeURIComponent(workflowId)}/stages`
2259
+ });
2260
+ }
2261
+ /**
2262
+ * GET /workflows/transitions — transition summaries of every published
2263
+ * workflow, or with `workflowId` of that one version (published or archived;
2264
+ * an unknown, draft or other-tenant id returns an empty list). Each summary
2265
+ * carries `workflow_id`, `workflow_version`, `lineage_workflow_id` and
2266
+ * `automatic_only`. Only pipelines whose record type the caller can read
2267
+ * are listed; an unreadable `workflowId` returns an empty list, not 403.
2268
+ */
2269
+ async listTransitions(params = {}) {
2270
+ const query = {};
2271
+ if (params.entityTypes && params.entityTypes.length > 0) query["entity_types"] = params.entityTypes.join(",");
2272
+ if (params.workflowId) query["workflow_id"] = params.workflowId;
2273
+ return this.http.request({
2274
+ method: "GET",
2275
+ path: `${this.basePath}/transitions`,
2276
+ params: query
2277
+ });
2278
+ }
2279
+ /**
2280
+ * POST /admin/workflows/:wid/transitions — add a transition to a draft
2281
+ * workflow. Pass `automaticOnly: true` for an edge only automation should
2282
+ * fire (e.g. an event rule advancing on "contract sent").
2283
+ */
2284
+ async createTransition(workflowId, input) {
2285
+ return this.http.request({
2286
+ method: "POST",
2287
+ path: `${this.adminPath}/${encodeURIComponent(workflowId)}/transitions`,
2288
+ body: input
2289
+ });
2290
+ }
2291
+ /**
2292
+ * The event rules of one workflow (`/admin/workflows/:wid/event-rules`) —
2293
+ * "advance automatically when…". Any version's id works; rules are keyed by
2294
+ * the lineage root.
2295
+ */
2296
+ eventRules(workflowId) {
2297
+ return new WorkflowEventRulesResource(this.http, workflowId);
2298
+ }
2299
+ /** PUT /admin/workflows/:wid/transitions/:tid — update a draft workflow's transition. */
2300
+ async updateTransition(workflowId, transitionId, input) {
2301
+ return this.http.request({
2302
+ method: "PUT",
2303
+ path: `${this.adminPath}/${encodeURIComponent(workflowId)}/transitions/${encodeURIComponent(transitionId)}`,
2304
+ body: input
2305
+ });
2306
+ }
2307
+ };
2308
+
2309
+ // src/resources/service-schedules.ts
2310
+ var ServiceSchedulesResource = class {
2311
+ constructor(http) {
2312
+ this.http = http;
2313
+ }
2314
+ // Each request spells its path out in full (no computed base path) so the
2315
+ // API's SDK route-parity audit (sdk-route-parity-audit.spec.ts) can read it.
2316
+ /** GET — the schedules of one customer or opportunity. */
2317
+ async list(subject_type, subject_id) {
2318
+ return this.http.request({
2319
+ method: "GET",
2320
+ path: "/service-schedules",
2321
+ params: { subject_type, subject_id }
2322
+ });
2323
+ }
2324
+ /** GET /:id — 404 when it doesn't exist or was deleted. */
2325
+ async get(id) {
2326
+ return this.http.request({
2327
+ method: "GET",
2328
+ path: `/service-schedules/${encodeURIComponent(id)}`
2329
+ });
2330
+ }
2331
+ /**
2332
+ * POST — create (201). The horizon's visits are generated straight away.
2333
+ * 400 `INVALID_RECURRENCE_RULE`, `SERVICE_TRADE_REQUIRED` or a validation error.
2334
+ */
2335
+ async create(input) {
2336
+ return this.http.request({
2337
+ method: "POST",
2338
+ path: "/service-schedules",
2339
+ body: input
2340
+ });
2341
+ }
2342
+ /**
2343
+ * PATCH /:id — only the fields sent change. A cadence, time, crew, duration
2344
+ * or horizon change regenerates future visits from today (`effective_from`,
2345
+ * which must be today) and reports it in `regeneration`; a visit someone changed is never
2346
+ * touched and is listed under `regeneration.protected`. The edit and its
2347
+ * regeneration succeed or fail together. 400 `INVALID_EFFECTIVE_FROM` for any
2348
+ * date but today.
2349
+ */
2350
+ async update(id, input) {
2351
+ return this.http.request({
2352
+ method: "PATCH",
2353
+ path: `/service-schedules/${encodeURIComponent(id)}`,
2354
+ body: input
2355
+ });
2356
+ }
2357
+ /** POST /:id/preview-update — what `update` with the same input would do. Writes nothing. */
2358
+ async previewUpdate(id, input) {
2359
+ return this.http.request({
2360
+ method: "POST",
2361
+ path: `/service-schedules/${encodeURIComponent(id)}/preview-update`,
2362
+ body: input
2363
+ });
2364
+ }
2365
+ /** PATCH /:id/status — pause, resume (`active`) or end. Resume generates the horizon at once. */
2366
+ async setStatus(id, status) {
2367
+ return this.http.request({
2368
+ method: "PATCH",
2369
+ path: `/service-schedules/${encodeURIComponent(id)}/status`,
2370
+ body: { status }
2371
+ });
2372
+ }
2373
+ /** DELETE /:id — soft-delete (204). */
2374
+ async delete(id) {
2375
+ await this.http.request({
2376
+ method: "DELETE",
2377
+ path: `/service-schedules/${encodeURIComponent(id)}`
2378
+ });
2379
+ }
2380
+ /**
2381
+ * POST /conflicts/preview — before booking people, see who is already on
2382
+ * another event (`conflicts`) and who would be outside their working hours
2383
+ * (`working_hours`). Read-only and warn-only: nothing is ever blocked. Give
2384
+ * exactly one of `windows` (single booking) or `schedule` (a cadence). 400 on
2385
+ * invalid input, INVALID_RECURRENCE_RULE, INVALID_TIMEZONE or
2386
+ * TOO_MANY_WINDOWS (> 400).
2387
+ */
2388
+ async previewConflicts(request) {
2389
+ return this.http.request({
2390
+ method: "POST",
2391
+ path: "/service-schedules/conflicts/preview",
2392
+ body: request
2393
+ });
2394
+ }
2395
+ /** GET /settings/crew-roles — which agent roles count as assignable crew. */
2396
+ async getCrewRoles() {
2397
+ return this.http.request({
2398
+ method: "GET",
2399
+ path: "/service-schedules/settings/crew-roles"
2400
+ });
2401
+ }
2402
+ /** PUT /settings/crew-roles — set the assignable roles (an override of the default). */
2403
+ async setCrewRoles(roles) {
2404
+ return this.http.request({
2405
+ method: "PUT",
2406
+ path: "/service-schedules/settings/crew-roles",
2407
+ body: { roles }
2408
+ });
2409
+ }
2410
+ /** GET /settings/crew — assignable crew with their home-base status. */
2411
+ async listCrew() {
2412
+ const res = await this.http.request({
2413
+ method: "GET",
2414
+ path: "/service-schedules/settings/crew"
2415
+ });
2416
+ return res.crew;
2417
+ }
2418
+ /** PUT /settings/crew/:agentId/home-address — set and geocode a crew member's home base. */
2419
+ async setCrewHomeAddress(agentId, address) {
2420
+ return this.http.request({
2421
+ method: "PUT",
2422
+ path: `/service-schedules/settings/crew/${encodeURIComponent(agentId)}/home-address`,
2423
+ body: { address }
2424
+ });
2425
+ }
2426
+ };
2427
+
2428
+ // src/resources/billing-schedules.ts
2429
+ var BillingScheduleResource = class extends BaseResource {
2430
+ constructor(http) {
2431
+ super(http, "/admin/billing-schedules");
2432
+ }
2433
+ /** GET /admin/billing-schedules — list rows (no lines; `line_count` and `next_amount` instead). */
2434
+ async list(params) {
2435
+ return this.http.request({
2436
+ method: "GET",
2437
+ path: this.basePath,
2438
+ params: toQueryParams(params)
2439
+ });
2440
+ }
2441
+ /** GET /admin/billing-schedules/:id — the schedule with its lines and next 3 periods. */
2442
+ async get(id) {
2443
+ return this.http.request({
2444
+ method: "GET",
2445
+ path: `${this.basePath}/${encodeURIComponent(id)}`
2446
+ });
2447
+ }
2448
+ /**
2449
+ * POST /admin/billing-schedules. `timezone` defaults to the tenant's. A
2450
+ * backdated `start_date` needs `backfill` ('skip' | 'draft'), else 400
2451
+ * `BACKFILL_REQUIRED`; `collection: 'autopay'` without a platform-managed
2452
+ * Stripe connection and a saved default card is 422 `AUTOPAY_UNAVAILABLE`
2453
+ * (`reason` `no_connect` | `no_saved_method`).
2454
+ */
2455
+ async create(data) {
2456
+ return this.http.request({
2457
+ method: "POST",
2458
+ path: this.basePath,
2459
+ body: data
2460
+ });
2461
+ }
2462
+ /**
2463
+ * PATCH /admin/billing-schedules/:id — partial. `lines` replaces every line
2464
+ * from `effective_from` (default: the next period not yet invoiced) as a new
2465
+ * line version. 409 `CADENCE_LOCKED`; 422 `EFFECTIVE_DATE_IN_GENERATED_PERIOD`
2466
+ * for a date inside an invoiced period.
2467
+ */
2468
+ async update(id, data) {
2469
+ return this.http.request({
2470
+ method: "PATCH",
2471
+ path: `${this.basePath}/${encodeURIComponent(id)}`,
2472
+ body: data
2473
+ });
2474
+ }
2475
+ /** DELETE /admin/billing-schedules/:id — only a schedule that never invoiced (else 409 `SCHEDULE_HAS_INVOICES`). */
2476
+ async delete(id) {
2477
+ await this.http.request({
2478
+ method: "DELETE",
2479
+ path: `${this.basePath}/${encodeURIComponent(id)}`
2480
+ });
2481
+ }
2482
+ /** GET /admin/billing-schedules/:id/versions — line version history, newest effective date first. */
2483
+ async listVersions(id) {
2484
+ return this.http.request({
2485
+ method: "GET",
2486
+ path: `${this.basePath}/${encodeURIComponent(id)}/versions`
2487
+ });
2488
+ }
2489
+ /**
2490
+ * POST /admin/billing-schedules/:id/adjustments — add a one-off amount
2491
+ * (signed; negative is a credit) to the schedule's next generated invoice.
2492
+ * Billed exactly once; no automatic proration. 422 `ADJUSTMENT_INVALID`
2493
+ * (zero, or the next invoice would go below zero) or `SCHEDULE_NOT_ACTIVE`.
2494
+ */
2495
+ async addAdjustment(id, data) {
2496
+ return this.http.request({
2497
+ method: "POST",
2498
+ path: `${this.basePath}/${encodeURIComponent(id)}/adjustments`,
2499
+ body: data
2500
+ });
2501
+ }
2502
+ /** GET /admin/billing-schedules/:id/adjustments — oldest first; default pending and consumed. */
2503
+ async listAdjustments(id, params) {
2504
+ return this.http.request({
2505
+ method: "GET",
2506
+ path: `${this.basePath}/${encodeURIComponent(id)}/adjustments`,
2507
+ params: toQueryParams(params)
2508
+ });
2509
+ }
2510
+ /**
2511
+ * DELETE /admin/billing-schedules/:id/adjustments/:adjustmentId — cancel a
2512
+ * pending adjustment (it never bills). Returns it; 409
2513
+ * `ADJUSTMENT_ALREADY_CONSUMED` once an invoice carries it.
2514
+ */
2515
+ async cancelAdjustment(id, adjustmentId) {
2516
+ return this.http.request({
2517
+ method: "DELETE",
2518
+ path: `${this.basePath}/${encodeURIComponent(id)}/adjustments/${encodeURIComponent(adjustmentId)}`
2519
+ });
2520
+ }
2521
+ /** POST /admin/billing-schedules/:id/pause — 409 `INVALID_STATUS_TRANSITION` unless active. */
2522
+ async pause(id) {
2523
+ return this.http.request({
2524
+ method: "POST",
2525
+ path: `${this.basePath}/${encodeURIComponent(id)}/pause`
2526
+ });
2527
+ }
2528
+ /** POST /admin/billing-schedules/:id/resume — periods that fell due while paused are skipped. */
2529
+ async resume(id) {
2530
+ return this.http.request({
2531
+ method: "POST",
2532
+ path: `${this.basePath}/${encodeURIComponent(id)}/resume`
2533
+ });
2534
+ }
2535
+ /** POST /admin/billing-schedules/:id/end — no further periods generate. */
2536
+ async end(id) {
2537
+ return this.http.request({
2538
+ method: "POST",
2539
+ path: `${this.basePath}/${encodeURIComponent(id)}/end`
2540
+ });
2541
+ }
2542
+ /** GET /admin/billing-schedules/:id/preview — the next `count` (1–24, default 6) periods from the first unbilled one. */
2543
+ async preview(id, params) {
2544
+ return this.http.request({
2545
+ method: "GET",
2546
+ path: `${this.basePath}/${encodeURIComponent(id)}/preview`,
2547
+ params: toQueryParams(params)
2548
+ });
2549
+ }
2550
+ /** GET /admin/billing-schedules/:id/periods — the period ledger, newest first. */
2551
+ async periods(id, params) {
2552
+ return this.http.request({
2553
+ method: "GET",
2554
+ path: `${this.basePath}/${encodeURIComponent(id)}/periods`,
2555
+ params: toQueryParams(params)
2556
+ });
2557
+ }
2558
+ /**
2559
+ * GET /admin/billing-schedules/periods/needs-review — tenant-wide: needs_review
2560
+ * rows plus failed and stuck (pending over 2h) deliveries.
2561
+ */
2562
+ async needsReview(params) {
2563
+ return this.http.request({
2564
+ method: "GET",
2565
+ path: `${this.basePath}/periods/needs-review`,
2566
+ params: toQueryParams(params)
2567
+ });
2568
+ }
2569
+ /**
2570
+ * GET /admin/billing-schedules/autopay-summary — what disconnecting Stripe
2571
+ * would touch: live autopay schedules, the distinct customers on them, and
2572
+ * active saved cards on the current Stripe connection. On disconnect, autopay
2573
+ * schedules that can no longer charge switch to emailed pay links.
2574
+ */
2575
+ async autopaySummary() {
2576
+ return this.http.request({
2577
+ method: "GET",
2578
+ path: `${this.basePath}/autopay-summary`
2579
+ });
2580
+ }
2581
+ /**
2582
+ * POST /admin/billing-schedules/:id/generate-now — bill the current due
2583
+ * period now. Idempotent (`already_generated`); 409 `NOTHING_DUE` or
2584
+ * `SCHEDULE_NOT_ACTIVE`.
2585
+ */
2586
+ async generateNow(id) {
2587
+ return this.http.request({
2588
+ method: "POST",
2589
+ path: `${this.basePath}/${encodeURIComponent(id)}/generate-now`
2590
+ });
2591
+ }
2592
+ /**
2593
+ * POST /admin/billing-schedules/:id/periods/:periodStart/skip — skip one
2594
+ * period (`periodStart` is `YYYY-MM-DD`). Returns the skipped ledger row;
2595
+ * 400 `NOT_A_PERIOD`, 409 `PERIOD_ALREADY_INVOICED`.
2596
+ */
2597
+ async skipPeriod(id, periodStart, data = {}) {
2598
+ return this.http.request({
2599
+ method: "POST",
2600
+ path: `${this.basePath}/${encodeURIComponent(id)}/periods/${encodeURIComponent(periodStart)}/skip`,
2601
+ body: data
2602
+ });
2603
+ }
2604
+ /**
2605
+ * POST /admin/billing-schedules/:id/periods/:periodStart/regenerate — re-bill
2606
+ * a period whose invoice was voided (new draft on the same ledger row).
2607
+ * 409 `INVOICE_NOT_VOID` or `CHECKOUT_IN_FLIGHT`.
2608
+ */
2609
+ async regeneratePeriod(id, periodStart) {
2610
+ return this.http.request({
2611
+ method: "POST",
2612
+ path: `${this.basePath}/${encodeURIComponent(id)}/periods/${encodeURIComponent(periodStart)}/regenerate`
2613
+ });
2614
+ }
2615
+ };
2616
+
2617
+ // src/resources/custom-fields.ts
2618
+ var CustomFieldsResource = class {
2619
+ constructor(http) {
2620
+ this.http = http;
2621
+ }
2622
+ /** List definitions, optionally narrowed to one entity type. */
2623
+ async list(params) {
2624
+ return this.http.request({
2625
+ method: "GET",
2626
+ path: "/custom-fields",
2627
+ params
2628
+ });
2629
+ }
2630
+ /** GET /admin/custom-fields — the same list through the admin route (Manage grant). */
2631
+ async listAll(params) {
2632
+ return this.http.request({
2633
+ method: "GET",
2634
+ path: "/admin/custom-fields",
2635
+ params
2636
+ });
2637
+ }
2638
+ /** GET /admin/custom-fields/:id */
2639
+ async get(id) {
2640
+ return this.http.request({
2641
+ method: "GET",
2642
+ path: `/admin/custom-fields/${id}`
2643
+ });
2644
+ }
2645
+ /**
2646
+ * POST /admin/custom-fields — define a new field. 400 for `job`, `vendor` or
2647
+ * `agent` (those records can't hold values yet, PRD D6). A `fieldKey` must be
2648
+ * unique per entity type: check `listAll({ entity_type, include_inactive: true })` first.
2649
+ */
2650
+ async create(data) {
2651
+ return this.http.request({
2652
+ method: "POST",
2653
+ path: "/admin/custom-fields",
2654
+ body: data
2655
+ });
2656
+ }
2657
+ /** PATCH /admin/custom-fields/:id — `fieldKey` and `entityType` can't change. */
2658
+ async update(id, data) {
2659
+ return this.http.request({
2660
+ method: "PATCH",
2661
+ path: `/admin/custom-fields/${id}`,
2662
+ body: data
2663
+ });
2664
+ }
2665
+ /**
2666
+ * DELETE /admin/custom-fields/:id — deactivates the definition (204). Records
2667
+ * keep their stored values; `list({ include_inactive: true })` still shows it,
2668
+ * and `update(id, { active: true })` brings it back.
2669
+ */
2670
+ async deactivate(id) {
2671
+ await this.http.request({
2672
+ method: "DELETE",
2673
+ path: `/admin/custom-fields/${id}`
2674
+ });
2675
+ }
2676
+ };
2677
+
2678
+ // src/resources/ortto.ts
2679
+ var OrttoResource = class {
2680
+ constructor(http) {
2681
+ this.http = http;
2682
+ this.basePath = "/admin/integrations/ortto";
2683
+ }
2684
+ /** GET /admin/integrations/ortto/mappings — live mappings with their list names. */
2685
+ async listMappings() {
2686
+ const res = await this.http.request({
2687
+ method: "GET",
2688
+ path: `${this.basePath}/mappings`
2689
+ });
2690
+ return res.data;
2691
+ }
2692
+ /** GET /admin/integrations/ortto/audiences — the connected account's audiences (cached 60 s). */
2693
+ async listAudiences(params) {
2694
+ const res = await this.http.request({
2695
+ method: "GET",
2696
+ path: `${this.basePath}/audiences`,
2697
+ params
2698
+ });
2699
+ return res.data;
2700
+ }
2701
+ /** POST /admin/integrations/ortto/mappings — 409 when the list already has a mapping. */
2702
+ async createMapping(data) {
2703
+ const res = await this.http.request({
2704
+ method: "POST",
2705
+ path: `${this.basePath}/mappings`,
2706
+ body: data
2707
+ });
2708
+ return res.data;
2709
+ }
2710
+ /** PATCH /admin/integrations/ortto/mappings/:id — `ortto_tag` and/or `create_unmatched`. */
2711
+ async updateMapping(id, data) {
2712
+ const res = await this.http.request({
2713
+ method: "PATCH",
2714
+ path: `${this.basePath}/mappings/${id}`,
2715
+ body: data
2716
+ });
2717
+ return res.data;
2718
+ }
2719
+ /**
2720
+ * DELETE /admin/integrations/ortto/mappings/:id (204). A pull list becomes
2721
+ * editable again and keeps its members; a push tag is NOT removed from Ortto.
2722
+ */
2723
+ async deleteMapping(id) {
2724
+ await this.http.request({
2725
+ method: "DELETE",
2726
+ path: `${this.basePath}/mappings/${id}`
2727
+ });
2728
+ }
2729
+ /**
2730
+ * POST /admin/integrations/ortto/sync (202) — queue a sync for one mapping or
2731
+ * the whole connection. Never calls Ortto in-request.
2732
+ */
2733
+ async sync(data = {}) {
2734
+ const res = await this.http.request({
2735
+ method: "POST",
2736
+ path: `${this.basePath}/sync`,
2737
+ body: data
2738
+ });
2739
+ return res.data;
2740
+ }
2741
+ /** GET /admin/integrations/ortto/sync-status — 404 when Ortto is not connected. */
2742
+ async syncStatus() {
2743
+ const res = await this.http.request({
2744
+ method: "GET",
2745
+ path: `${this.basePath}/sync-status`
2746
+ });
2747
+ return res.data;
2748
+ }
2749
+ };
2750
+
2751
+ // src/resources/webhook-subscriptions.ts
2752
+ var WebhookSubscriptionsResource = class extends ApiResource {
2753
+ constructor(http) {
2754
+ super(http, "/admin/webhooks");
2755
+ }
2756
+ /** POST /admin/webhooks — the returned `secret` is shown only this once. */
2757
+ async create(data) {
2758
+ return this.http.request({ method: "POST", path: this.basePath, body: data });
2759
+ }
2760
+ /** GET /admin/webhooks */
2761
+ async list(params) {
2762
+ return this.http.request({
2763
+ method: "GET",
2764
+ path: this.basePath,
2765
+ params
2766
+ });
2767
+ }
2768
+ /** GET /admin/webhooks/:id */
2769
+ async get(id) {
2770
+ return this.http.request({ method: "GET", path: `${this.basePath}/${id}` });
2771
+ }
2772
+ /** PATCH /admin/webhooks/:id */
2773
+ async update(id, data) {
2774
+ return this.http.request({ method: "PATCH", path: `${this.basePath}/${id}`, body: data });
2775
+ }
2776
+ /** DELETE /admin/webhooks/:id */
2777
+ async delete(id) {
2778
+ return this.http.request({ method: "DELETE", path: `${this.basePath}/${id}` });
2779
+ }
2780
+ /** POST /admin/webhooks/:id/test — sends one signed test event to the URL now. */
2781
+ async test(id) {
2782
+ return this.http.request({ method: "POST", path: `${this.basePath}/${id}/test` });
2783
+ }
2784
+ /**
2785
+ * POST /admin/webhooks/:id/rotate-secret — replaces the signing secret and
2786
+ * returns the new one, shown only this once. New deliveries are signed with
2787
+ * it, but deliveries already queued (and their retries, for several minutes)
2788
+ * keep the old one. `verifyWebhookSignature` checks one secret, so for a few
2789
+ * minutes have your receiver try the new secret and fall back to the old one.
2790
+ */
2791
+ async rotateSecret(id) {
2792
+ return this.http.request({
2793
+ method: "POST",
2794
+ path: `${this.basePath}/${id}/rotate-secret`
2795
+ });
2796
+ }
2797
+ /** GET /admin/webhooks/:id/deliveries — newest first. */
2798
+ async listDeliveries(id, params) {
2799
+ return this.http.request({
2800
+ method: "GET",
2801
+ path: `${this.basePath}/${id}/deliveries`,
2802
+ params
2803
+ });
2804
+ }
2805
+ /**
2806
+ * POST /admin/webhooks/:id/deliveries/:deliveryId/retry — queues a new
2807
+ * delivery of that event (202). The receiver sees the event again, so make
2808
+ * it idempotent on the event id.
2809
+ */
2810
+ async retryDelivery(id, deliveryId) {
2811
+ return this.http.request({
2812
+ method: "POST",
2813
+ path: `${this.basePath}/${id}/deliveries/${deliveryId}/retry`
2814
+ });
2815
+ }
2816
+ };
2817
+
2818
+ // src/resources/users.ts
2819
+ var UsersResource = class extends ApiResource {
2820
+ constructor(http) {
2821
+ super(http, "/users");
2822
+ }
2823
+ /** GET /users — paged, with email, role, status and org fields (read grant on users). */
2824
+ async list(params) {
2825
+ return this.http.request({
2826
+ method: "GET",
2827
+ path: this.basePath,
2828
+ params
2829
+ });
2830
+ }
2831
+ /**
2832
+ * GET /users/directory — active users' ids, names and roles, for pickers and
2833
+ * for resolving an assignee. Every role can read it.
2834
+ */
2835
+ async directory(params) {
2836
+ return this.http.request({
2837
+ method: "GET",
2838
+ path: `${this.basePath}/directory`,
2839
+ params
2840
+ });
2841
+ }
2842
+ /**
2843
+ * GET /users/:id/working-hours — the user's own weekly hours and the tenant
2844
+ * default. A non-admin caller may read only their own (403 otherwise).
2845
+ */
2846
+ async getWorkingHours(id) {
2847
+ return this.http.request({ method: "GET", path: `${this.basePath}/${id}/working-hours` });
2848
+ }
2849
+ };
2850
+
2851
+ // src/resources/teams.ts
2852
+ var TeamsResource = class extends ApiResource {
2853
+ constructor(http) {
2854
+ super(http, "/teams");
2855
+ }
2856
+ /** GET /teams — every team, with `member_count`. */
2857
+ async list() {
2858
+ return this.http.request({ method: "GET", path: this.basePath });
2859
+ }
2860
+ /** GET /teams/:id — one team, with `members`. */
2861
+ async get(id) {
2862
+ return this.http.request({ method: "GET", path: `${this.basePath}/${id}` });
2863
+ }
2864
+ };
2865
+
2866
+ // src/webhooks.ts
2867
+ function verifyWebhookSignature(payload, signature, secret) {
2868
+ if (!signature || !secret || !payload) {
2869
+ return false;
2870
+ }
2871
+ const prefix = "sha256=";
2872
+ if (!signature.startsWith(prefix)) {
2873
+ return false;
2874
+ }
2875
+ const receivedHex = signature.slice(prefix.length);
2876
+ if (!receivedHex) {
2877
+ return false;
2878
+ }
2879
+ const expectedHmac = createHmac("sha256", secret).update(payload).digest("hex");
2880
+ const receivedBuf = Buffer.from(receivedHex, "hex");
2881
+ const expectedBuf = Buffer.from(expectedHmac, "hex");
2882
+ if (receivedBuf.length !== expectedBuf.length) {
2883
+ return false;
2884
+ }
2885
+ return timingSafeEqual(receivedBuf, expectedBuf);
2886
+ }
2887
+ function parseWebhookEvent(body, signature, secret) {
2888
+ if (!verifyWebhookSignature(body, signature, secret)) {
2889
+ throw new WebhookVerificationError();
2890
+ }
2891
+ return JSON.parse(body);
2892
+ }
2893
+
2894
+ // src/webhook-router.ts
2895
+ var WebhookRouter = class {
2896
+ constructor() {
2897
+ /** pattern (composite key / entity wildcard / '*') → registered handlers. */
2898
+ this.handlers = /* @__PURE__ */ new Map();
2899
+ }
2900
+ /**
2901
+ * Register a handler for an event pattern.
2902
+ *
2903
+ * @param pattern - `"{entity_type}.{event_type}"` (e.g. `opportunity.created`),
2904
+ * an entity wildcard `"{entity_type}.*"` (e.g. `opportunity.*`), or the
2905
+ * global wildcard `"*"`. Matching is exact-string against the derived key;
2906
+ * see the class docs for the dotted-`event_type` shape.
2907
+ * @param handler - Invoked with the full {@link WebhookDelivery} on a match.
2908
+ * @returns `this`, for chaining.
2909
+ */
2910
+ on(pattern, handler) {
2911
+ const existing = this.handlers.get(pattern);
2912
+ if (existing) {
2913
+ existing.push(handler);
2914
+ } else {
2915
+ this.handlers.set(pattern, [handler]);
2916
+ }
2917
+ return this;
2918
+ }
2919
+ /**
2920
+ * Verify, parse, and dispatch a webhook delivery.
2921
+ *
2922
+ * The signature is verified first: on failure this throws
2923
+ * {@link WebhookVerificationError} and dispatches nothing. On success it
2924
+ * dispatches to every matching handler — specific key, then entity wildcard,
2925
+ * then global — awaiting async handlers before resolving.
2926
+ *
2927
+ * @param input - The raw `{ body, signature, secret }`.
2928
+ * @returns The parsed {@link WebhookDelivery}.
2929
+ * @throws WebhookVerificationError if the signature is invalid.
2930
+ */
2931
+ async process(input) {
2932
+ const delivery = parseWebhookEvent(input.body, input.signature, input.secret);
2933
+ const { entity_type, event_type } = delivery.event;
2934
+ const patterns = [`${entity_type}.${event_type}`, `${entity_type}.*`, "*"];
2935
+ for (const pattern of patterns) {
2936
+ const matched = this.handlers.get(pattern);
2937
+ if (!matched) continue;
2938
+ for (const handler of matched) {
2939
+ await handler(delivery);
2940
+ }
2941
+ }
2942
+ return delivery;
2943
+ }
2944
+ };
2945
+
2946
+ // src/client.ts
2947
+ var PlanesClient = class {
2948
+ constructor(config) {
2949
+ const hasOAuthCreds = Boolean(config.clientId) || Boolean(config.clientSecret);
2950
+ const modes = [
2951
+ config.accessToken ? "accessToken" : null,
2952
+ config.apiKey ? "apiKey" : null,
2953
+ hasOAuthCreds ? "clientId+clientSecret" : null
2954
+ ].filter((m) => m !== null);
2955
+ if (modes.length === 0) {
2956
+ throw new Error(
2957
+ "PlanesClient requires one auth mode: accessToken, apiKey, or clientId + clientSecret"
2958
+ );
2959
+ }
2960
+ if (modes.length > 1) {
2961
+ throw new Error(
2962
+ `PlanesClient requires exactly one auth mode, not multiple (got: ${modes.join(", ")})`
2963
+ );
2964
+ }
2965
+ if (hasOAuthCreds && (!config.clientId || !config.clientSecret)) {
2966
+ throw new Error("PlanesClient OAuth mode requires both clientId and clientSecret");
2967
+ }
2968
+ this.http = new HttpClient(config);
2969
+ }
2970
+ get opportunities() {
2971
+ if (!this._opportunities) {
2972
+ this._opportunities = new OpportunityResource(this.http);
2973
+ }
2974
+ return this._opportunities;
2975
+ }
2976
+ get customers() {
2977
+ if (!this._customers) {
2978
+ this._customers = new CustomerResource(this.http);
2979
+ }
2980
+ return this._customers;
2981
+ }
2982
+ get properties() {
2983
+ if (!this._properties) {
2984
+ this._properties = new PropertyResource(this.http);
2985
+ }
2986
+ return this._properties;
2987
+ }
2988
+ get calendarEvents() {
2989
+ if (!this._calendarEvents) {
2990
+ this._calendarEvents = new CalendarEventResource(this.http);
2991
+ }
2992
+ return this._calendarEvents;
2993
+ }
2994
+ get contracts() {
2995
+ if (!this._contracts) {
2996
+ this._contracts = new ContractResource(this.http);
2997
+ }
2998
+ return this._contracts;
2999
+ }
3000
+ get jobs() {
3001
+ if (!this._jobs) {
3002
+ this._jobs = new JobResource(this.http);
3003
+ }
3004
+ return this._jobs;
3005
+ }
3006
+ get estimates() {
3007
+ if (!this._estimates) {
3008
+ this._estimates = new EstimateResource(this.http);
3009
+ }
3010
+ return this._estimates;
3011
+ }
3012
+ get invoices() {
3013
+ if (!this._invoices) {
3014
+ this._invoices = new InvoiceResource(this.http);
3015
+ }
3016
+ return this._invoices;
3017
+ }
3018
+ get inventory() {
3019
+ if (!this._inventory) {
3020
+ this._inventory = new InventoryResource(this.http);
3021
+ }
3022
+ return this._inventory;
3023
+ }
3024
+ get contacts() {
3025
+ if (!this._contacts) {
3026
+ this._contacts = new ContactResource(this.http);
3027
+ }
3028
+ return this._contacts;
3029
+ }
3030
+ get activities() {
3031
+ if (!this._activities) {
3032
+ this._activities = new ActivityResource(this.http);
3033
+ }
3034
+ return this._activities;
3035
+ }
3036
+ get communications() {
3037
+ if (!this._communications) {
3038
+ this._communications = new CommunicationsResource(this.http);
3039
+ }
3040
+ return this._communications;
3041
+ }
3042
+ /** Logged meetings — manual + provider-synced, with company matching (E55). */
3043
+ get conversations() {
3044
+ if (!this._conversations) {
3045
+ this._conversations = new ConversationsResource(this.http);
3046
+ }
3047
+ return this._conversations;
3048
+ }
3049
+ get gmail() {
3050
+ if (!this._gmail) {
3051
+ this._gmail = new GmailResource(this.http);
3052
+ }
3053
+ return this._gmail;
3054
+ }
3055
+ get documents() {
3056
+ if (!this._documents) {
3057
+ this._documents = new DocumentsResource(this.http);
3058
+ }
3059
+ return this._documents;
3060
+ }
3061
+ get tags() {
3062
+ if (!this._tags) {
3063
+ this._tags = new TagResource(this.http);
3064
+ }
3065
+ return this._tags;
3066
+ }
3067
+ get lists() {
3068
+ if (!this._lists) {
3069
+ this._lists = new ListsResource(this.http);
3070
+ }
3071
+ return this._lists;
3072
+ }
3073
+ get leadSources() {
3074
+ if (!this._leadSources) {
3075
+ this._leadSources = new LeadSourcesResource(this.http);
3076
+ }
3077
+ return this._leadSources;
3078
+ }
3079
+ get tasks() {
3080
+ if (!this._tasks) {
3081
+ this._tasks = new TaskResource(this.http);
3082
+ }
3083
+ return this._tasks;
3084
+ }
3085
+ /** Record views — the "recently viewed" beacon + read (E41-F7). */
3086
+ get recordViews() {
3087
+ if (!this._recordViews) {
3088
+ this._recordViews = new RecordViewsResource(this.http);
3089
+ }
3090
+ return this._recordViews;
3091
+ }
3092
+ /** Module status — which modules are active for the caller's tenant (E51-F1-S1). */
3093
+ get modules() {
3094
+ if (!this._modules) {
3095
+ this._modules = new ModulesResource(this.http);
3096
+ }
3097
+ return this._modules;
3098
+ }
3099
+ /** The tenant's plan, billing status and plan ceiling — `plan.get()` (E54-F1-S2). */
3100
+ get plan() {
3101
+ if (!this._plan) {
3102
+ this._plan = new PlanResource(this.http);
3103
+ }
3104
+ return this._plan;
3105
+ }
3106
+ /** The authenticated caller — `me.abilities()` (E52-F1-S3). */
3107
+ get me() {
3108
+ if (!this._me) {
3109
+ this._me = new MeResource(this.http);
3110
+ }
3111
+ return this._me;
3112
+ }
3113
+ /** Settings → Roles, admin only — `roles.list/get/updateGrants/reset/history` (E52-F2-S5). */
3114
+ get roles() {
3115
+ if (!this._roles) {
3116
+ this._roles = new RolesResource(this.http);
3117
+ }
3118
+ return this._roles;
3119
+ }
3120
+ /** Invoice settings — `invoiceSettings.getOfflineInstructions/setOfflineInstructions` (E56-F5-S4). */
3121
+ get invoiceSettings() {
3122
+ if (!this._invoiceSettings) {
3123
+ this._invoiceSettings = new InvoiceSettingsResource(this.http);
3124
+ }
3125
+ return this._invoiceSettings;
3126
+ }
3127
+ /** Payment reminder settings, admin only — `invoiceReminders.list/update/preview` (E56-F8-S6). */
3128
+ get invoiceReminders() {
3129
+ if (!this._invoiceReminders) {
3130
+ this._invoiceReminders = new InvoiceRemindersResource(this.http);
3131
+ }
3132
+ return this._invoiceReminders;
3133
+ }
3134
+ /** Event automations, admin only — `eventAutomations.list/get/create/update/delete` (E60-S2). */
3135
+ get eventAutomations() {
3136
+ if (!this._eventAutomations) {
3137
+ this._eventAutomations = new EventAutomationsResource(this.http);
3138
+ }
3139
+ return this._eventAutomations;
3140
+ }
3141
+ /** Web forms and their submissions, admin only — `webForms.list/get/create/update/archive/rotateKey`, `webForms.submissions.list/get/update/route` (E60-S6). */
3142
+ get webForms() {
3143
+ if (!this._webForms) {
3144
+ this._webForms = new WebFormsResource(this.http);
3145
+ }
3146
+ return this._webForms;
3147
+ }
3148
+ /** Published sequences a contact can be enrolled in (E51-F2-S6). */
3149
+ get contactSequences() {
3150
+ if (!this._contactSequences) {
3151
+ this._contactSequences = new ContactSequencesResource(this.http);
3152
+ }
3153
+ return this._contactSequences;
3154
+ }
3155
+ /** Enroll a contact in a sequence, list its enrollments, exit one (E51-F2-S8). */
3156
+ get enrollments() {
3157
+ if (!this._enrollments) {
3158
+ this._enrollments = new EnrollmentsResource(this.http);
3159
+ }
3160
+ return this._enrollments;
3161
+ }
3162
+ /** Tenant-readable workflow reads — a workflow version's ordered stages. */
3163
+ get workflows() {
3164
+ if (!this._workflows) {
3165
+ this._workflows = new WorkflowsResource(this.http);
3166
+ }
3167
+ return this._workflows;
3168
+ }
3169
+ get serviceSchedules() {
3170
+ if (!this._serviceSchedules) {
3171
+ this._serviceSchedules = new ServiceSchedulesResource(this.http);
3172
+ }
3173
+ return this._serviceSchedules;
3174
+ }
3175
+ /**
3176
+ * Recurring billing schedules (E56-F3) — CRUD, pause/resume/end, preview,
3177
+ * the period ledger, Needs review, generate-now, skip and regenerate.
3178
+ */
3179
+ get billingSchedules() {
3180
+ if (!this._billingSchedules) {
3181
+ this._billingSchedules = new BillingScheduleResource(this.http);
3182
+ }
3183
+ return this._billingSchedules;
3184
+ }
3185
+ get customFields() {
3186
+ if (!this._customFields) {
3187
+ this._customFields = new CustomFieldsResource(this.http);
3188
+ }
3189
+ return this._customFields;
3190
+ }
3191
+ /** Ortto connector — list mappings, audiences, manual sync, sync status (E53). Admin-only. */
3192
+ get ortto() {
3193
+ if (!this._ortto) {
3194
+ this._ortto = new OrttoResource(this.http);
3195
+ }
3196
+ return this._ortto;
3197
+ }
3198
+ /**
3199
+ * Webhook subscriptions — where entity events are delivered (E64-S10). Admin
3200
+ * grants and the `open_api` feature. Not `webhooks`: that is the event router.
3201
+ */
3202
+ get webhookSubscriptions() {
3203
+ if (!this._webhookSubscriptions) {
3204
+ this._webhookSubscriptions = new WebhookSubscriptionsResource(this.http);
3205
+ }
3206
+ return this._webhookSubscriptions;
3207
+ }
3208
+ /** The tenant's users, read-only: list and directory (E64-S10). */
3209
+ get users() {
3210
+ if (!this._users) {
3211
+ this._users = new UsersResource(this.http);
3212
+ }
3213
+ return this._users;
3214
+ }
3215
+ /** Teams, read-only (E64-S10). */
3216
+ get teams() {
3217
+ if (!this._teams) {
3218
+ this._teams = new TeamsResource(this.http);
3219
+ }
3220
+ return this._teams;
3221
+ }
3222
+ /**
3223
+ * Ergonomic webhook event router — `client.webhooks.on(pattern, handler)`
3224
+ * plus `client.webhooks.process({ body, signature, secret })`. Auth-independent
3225
+ * (the signing secret is supplied per `.process()` call), so it is created
3226
+ * lazily without the HTTP client. See {@link WebhookRouter}.
3227
+ */
3228
+ get webhooks() {
3229
+ if (!this._webhooks) {
3230
+ this._webhooks = new WebhookRouter();
3231
+ }
3232
+ return this._webhooks;
3233
+ }
3234
+ };
3235
+
3236
+ // src/client-entry.ts
3237
+ var SESSION_MODE = "session";
3238
+ var PlanesClient2 = class extends PlanesClient {
3239
+ constructor(config) {
3240
+ if (typeof config?.getAccessToken !== "function") {
3241
+ throw new Error("PlanesClient (client entry) requires getAccessToken");
3242
+ }
3243
+ super({
3244
+ accessToken: SESSION_MODE,
3245
+ getAccessToken: config.getAccessToken,
3246
+ ...config.baseUrl !== void 0 ? { baseUrl: config.baseUrl } : {},
3247
+ ...config.onUnauthorized !== void 0 ? { onUnauthorized: config.onUnauthorized } : {},
3248
+ ...config.fetch !== void 0 ? { fetch: config.fetch } : {},
3249
+ ...config.timeout !== void 0 ? { timeout: config.timeout } : {},
3250
+ ...config.retryOnRateLimit !== void 0 ? { retryOnRateLimit: config.retryOnRateLimit } : {},
3251
+ ...config.maxRetries !== void 0 ? { maxRetries: config.maxRetries } : {}
3252
+ });
3253
+ }
3254
+ };
3255
+ //# sourceMappingURL=client.js.map