@terros-inc/sdk 1.0.17 → 1.0.18

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/README.md CHANGED
@@ -1,8 +1,72 @@
1
1
  # Terros SDK
2
2
 
3
- Typescript SDK & API client interface for the Terros Sales platform.
3
+ TypeScript SDK and API client for the Terros Sales platform, and the runtime helpers for Terros Connect scripts.
4
+
5
+ The [Terros Connect guide](https://docs.terros.com/docs/info/connect) covers how to create an app, write and publish scripts, and install them.
4
6
 
5
7
  ## Requirements
6
8
 
7
- - Node.js 24 or newer
8
- - A Terros API key with access to the platform
9
+ - Node.js 24
10
+ - A Terros API key, or a `terros auth login` sign-in from the [CLI](../cli/README.md). A Connect script needs neither: Terros passes it a key.
11
+
12
+ ## Connect Scripts
13
+
14
+ Wrap a script's function in `wrapConnectHandler` and export it as `handler`:
15
+
16
+ ```ts
17
+ import { wrapConnectHandler, type AccountWebhook, type CustomFieldId } from '@terros-inc/sdk'
18
+
19
+ type ScriptConfig = { fieldId: CustomFieldId; value: string }
20
+
21
+ export const handler = wrapConnectHandler<AccountWebhook, void, ScriptConfig>(async (input, client) => {
22
+ const { payload, config } = input.context
23
+ if (payload.action === 'remove') return
24
+ const { fieldId, value } = config.scriptConfig
25
+ // The update below is itself an account change, which runs this script again.
26
+ if (payload.data.customFieldMap?.[fieldId] === value) return
27
+ await client.account.update({ account: { accountId: payload.data.id, customFieldsPatch: { [fieldId]: value } } })
28
+ })
29
+ ```
30
+
31
+ The function gets:
32
+
33
+ - `input.runId`: the run's ID, `ConnectRun.<id>`
34
+ - `input.context.payload`: what triggered the run
35
+ - `input.context.config.scriptConfig`: the install's values for the script's config fields
36
+ - `input.context.config.secrets`: the install's values for the secrets in the script's `authSchema`
37
+ - `client`: a `TerrosClient` signed in with the key Terros passed for this run. `wrapConnectHandler` removes that key from `input` before your function runs.
38
+
39
+ ## TerrosClient
40
+
41
+ `new TerrosClient()` groups API calls by resource: `account`, `account.status`, `apiHistory`, `area`, `calendar`, `calendar.event`, `company`, `connect`, `plan`, `team` and `user`. Each method posts its input to the API path of the same name, so `client.account.upsert(input)` calls `/account/upsert`, and returns the response. `plan` methods always send `version: 2`, the API's stage-based plan shape; plans exist only for weeks and quarters (`PLAN_PERIOD_TYPES`). The [API reference](https://docs.terros.com) documents each path's fields.
42
+
43
+ A failed call throws. When the API answers with an error, the thrown error's `name` is `TerrosApiError` and its `code` is the API's error code, such as `NotFound`.
44
+
45
+ Constructor options: `apiKey`, `authType` (`ApiKey`, the default, or `ConnectKey`), `baseUrl` and `impersonateUserId`. With no `apiKey`, the client uses the key from the environment (below), then the CLI's saved sign-in.
46
+
47
+ ## Backend Host and Keys
48
+
49
+ The client picks its host from `TERROS_ENV` (or `TERROS_API_ENDPOINT`), defaulting to `https://api.terros.com`; a `baseUrl` overrides both. It accepts a `baseUrl` only on `https://api.terros.com`, `https://api.<stage>.terros.com` or `http://localhost[:port]`, with no path prefix, port (except on localhost), credentials or query. Anything else throws when the client is constructed, so a key is never sent to another host. When no key is passed, production reads `TERROS_API_KEY` and any other environment reads `TERROS_API_KEY_STAGE_<NAME>` (name upper-cased, hyphens as underscores; `TERROS_API_KEY_PORT_<port>` for localhost).
50
+
51
+ ## PermanentError
52
+
53
+ Throw `PermanentError` from a Connect script when the same input cannot succeed on a later run: bad config, a missing location, an invalid link, or a non-retryable 4xx. The Node.js Lambda runtime reports that thrown error as a `FunctionError` with `errorType` `PermanentError`. The execution engine acknowledges it without retrying or sending it to a dead-letter queue, and logs a terminal failure.
54
+
55
+ Throw a normal `Error` for a transient failure, such as a timeout, a network error, HTTP 429, or a 5xx. The engine logs it as a failed run. It does not retry failed runs today, so write scripts that are safe to run again for the same record.
56
+
57
+ ```ts
58
+ import { PermanentError, wrapConnectHandler } from '@terros-inc/sdk'
59
+
60
+ export const handler = wrapConnectHandler(async (input) => {
61
+ const locationId = input.context.config.scriptConfig.locationId
62
+ if (!locationId) throw new PermanentError('scriptConfig.locationId is required')
63
+ })
64
+ ```
65
+
66
+ ### IntegrationError
67
+
68
+ `IntegrationError` is a `PermanentError` the customer's side caused, so only the customer can fix it: the install's config or credentials, a payload sent to the wrong script slug, or a third party rejecting the request with a non-retryable 4xx such as bad credentials. It is not retried either, and the execution engine counts it as an integration failure: it stays visible in the run's logs and metrics but does not alarm Terros. Every other failure, a `PermanentError` or a plain `Error` included, counts as a Terros failure, so throw `IntegrationError` only when you know the cause is on the customer's side.
69
+
70
+ ```ts
71
+ if (response.status === 400) throw new IntegrationError('The third party rejected the install credentials')
72
+ ```
package/dist/index.d.mts CHANGED
@@ -18,19 +18,27 @@ type TerrosClientConfig = {
18
18
  apiKey?: string;
19
19
  authType?: 'ApiKey' | 'ConnectKey';
20
20
  baseUrl?: string;
21
- analytics?: TerrosHeaderMetadata;
21
+ analytics?: TerrosHeaderMetadata; /** The user to act as; defaults to `TERROS_IMPERSONATE`. An empty string acts as the signed-in user. */
22
22
  impersonateUserId?: string;
23
+ /**
24
+ * A sign-in token to send instead of an API key or the saved login, for one request that needs a scope the saved
25
+ * login lacks. It is never saved.
26
+ */
27
+ accessToken?: string;
23
28
  };
24
29
  declare class TerrosApiClient {
25
30
  private readonly baseUrl;
31
+ private readonly stateDir;
32
+ private readonly signInRefusal;
26
33
  private readonly authStrategy;
27
34
  private readonly analytics;
28
35
  private readonly impersonateUserId;
29
36
  constructor(config?: TerrosClientConfig);
30
37
  call<Success>(route: ApiRoute, input: object): Promise<Success>;
38
+ get<Success>(route: ApiRoute): Promise<Success>;
39
+ private request;
31
40
  private getAuthorizationHeader;
32
41
  private determineAuthStrategy;
33
- private determineBaseUrl;
34
42
  }
35
43
  //#endregion
36
44
  //#region src/models/shared.d.ts
@@ -157,6 +165,10 @@ type LatLng = {
157
165
  latitude: number;
158
166
  longitude: number;
159
167
  };
168
+ type PinPlacement = {
169
+ source: 'first_american' | 'amazon_location' | 'supplied_coordinates' | 'unknown';
170
+ precision: 'house' | 'street' | 'zip' | 'custom_coordinates' | 'unknown';
171
+ };
160
172
  type Address = {
161
173
  country: 'US' | 'CA' | 'PR';
162
174
  countrySubd: string;
@@ -493,9 +505,6 @@ type RoleData = AuditProps & {
493
505
  roleType?: 'admin' | 'manager' | 'recruit' | null;
494
506
  description?: string;
495
507
  assignment?: 'user' | 'team';
496
- avatarBlurhash?: string;
497
- avatarUrl?: string;
498
- uploadAvatarUrl?: string;
499
508
  canAssign?: boolean;
500
509
  isDeleted?: boolean;
501
510
  };
@@ -784,6 +793,14 @@ type UserManagerSuccess = ApiSuccess<{
784
793
  primaryManager?: TinyUser;
785
794
  }>;
786
795
  //#endregion
796
+ //#region src/models/user/names.d.ts
797
+ /**
798
+ * The name the Terros app shows for a user: their trimmed preferred name, else their trimmed first name.
799
+ * Mirrors `getPreferredName` in the Sales app's shared `common` package, which this public SDK cannot depend
800
+ * on; keep the two in step.
801
+ */
802
+ declare function getPreferredName(user: Pick<TinyUser, 'firstName' | 'preferredName'> | undefined): string;
803
+ //#endregion
787
804
  //#region src/models/account/model.d.ts
788
805
  type AccountId = `Account:${string}` | `Account.${string}`;
789
806
  type AccountStatusId = `AS.${string}`;
@@ -834,6 +851,10 @@ type UnsavedAccountNote = {
834
851
  userId: UserId;
835
852
  noteId?: NoteId;
836
853
  };
854
+ /** A note sent to account/upsert; the server writes it as the actor, else the authenticated user, when userId is omitted. */
855
+ type UpsertAccountNote = Omit<UnsavedAccountNote, 'userId'> & {
856
+ userId?: UserId;
857
+ };
837
858
  type AccountNote = UnsavedAccountNote & {
838
859
  noteId: NoteId;
839
860
  };
@@ -905,7 +926,8 @@ type AccountData = Omit<UnsavedAccount, 'contacts' | 'notes'> & {
905
926
  recruitId?: UserId;
906
927
  ownerHistory?: UserHistory;
907
928
  closerHistory?: UserHistory;
908
- editable?: boolean;
929
+ editable?: boolean; /** How an imported account pin was placed; older pins return unknown values. */
930
+ pinPlacement?: PinPlacement;
909
931
  };
910
932
  type AccountSortBy = 'createdDate' | 'lastActionDate' | 'lastUpdatedDate' | `CF.${string}`;
911
933
  type AccountSortOrder = 'asc' | 'desc';
@@ -1033,7 +1055,13 @@ type AccountAddSuccess = ApiSuccess<{
1033
1055
  account: AccountData;
1034
1056
  duplicate?: boolean;
1035
1057
  }>;
1036
- type AccountPartialUpdateInput = Partial<Omit<AccountData, 'accountId' | 'contacts' | 'notes'>> & {
1058
+ type AccountPartialUpdateInput = Partial<Omit<AccountData, 'accountId' | 'contacts' | 'notes' | 'externalLeadId'>> & {
1059
+ /** `null` clears it. */externalLeadId?: string | null;
1060
+ /**
1061
+ * Custom field values to change. Unlike `customFields`, which replaces the whole map, fields left out keep their
1062
+ * stored values, including fields the caller cannot view, and `null` clears one field. Send one or the other.
1063
+ */
1064
+ customFieldsPatch?: CustomFieldMap;
1037
1065
  actorId?: UserIdentifier;
1038
1066
  checkpoints?: WorkflowStageId[];
1039
1067
  hooks?: AccountHooksInput;
@@ -1046,6 +1074,12 @@ type AccountUpdateInput = {
1046
1074
  account: AccountPartialUpdateInput & {
1047
1075
  accountId: AccountId;
1048
1076
  };
1077
+ /**
1078
+ * Save only while the account has no `externalLeadId`; otherwise nothing is saved and the call fails with
1079
+ * `Conflict`. Set it with a placeholder `externalLeadId` to claim the account before creating the external record,
1080
+ * so two concurrent runs cannot both create it.
1081
+ */
1082
+ onlyIfNoExternalLeadId?: boolean;
1049
1083
  };
1050
1084
  type AccountUpdateSuccess = ApiSuccess<{
1051
1085
  account: AccountData;
@@ -1116,8 +1150,8 @@ type AccountUpsertInput = {
1116
1150
  externalLeadId?: string;
1117
1151
  test?: boolean;
1118
1152
  teamId?: TeamId;
1119
- customFields?: CustomFieldMap;
1120
- notes?: UnsavedAccountNote[];
1153
+ customFields?: CustomFieldMap; /** A note without `userId` is written as `actorId`, else the authenticated user. */
1154
+ notes?: UpsertAccountNote[];
1121
1155
  };
1122
1156
  opts?: {
1123
1157
  /** Defaults to true. */createCustomLocation?: boolean;
@@ -1151,6 +1185,45 @@ type AccountStatusRemoveInput = {
1151
1185
  statusId: AccountStatusId;
1152
1186
  };
1153
1187
  //#endregion
1188
+ //#region src/models/apiHistory/model.d.ts
1189
+ type ApiHistoryItem = {
1190
+ requestId: string;
1191
+ companyId: CompanyId; /** the user who made the request, or the owner of the API key that made it */
1192
+ userId?: UserId;
1193
+ endpoint: string; /** HTTP status stored with the completed request; typed API errors are stored as 200 */
1194
+ status: number;
1195
+ latency?: number;
1196
+ errorType?: string;
1197
+ error?: string;
1198
+ timestamp: number; /** redacted and truncated */
1199
+ requestBody?: unknown;
1200
+ };
1201
+ //#endregion
1202
+ //#region src/models/apiHistory/api.d.ts
1203
+ type ApiHistoryStartInput = {
1204
+ companyId: CompanyId; /** only requests with stored typed error responses */
1205
+ errorsOnly?: boolean; /** API path, for example `/account/add` */
1206
+ endpoint?: string; /** user or API-key owner */
1207
+ userId?: UserId; /** ISO 8601 timestamp; the query covers at most the last seven days */
1208
+ since?: string;
1209
+ limit?: number;
1210
+ };
1211
+ type ApiHistoryStartSuccess = ApiSuccess<{
1212
+ queryId: string;
1213
+ effectiveSince: string;
1214
+ sinceClipped: boolean;
1215
+ }>;
1216
+ type ApiHistoryStatusInput = {
1217
+ queryId: string;
1218
+ };
1219
+ type ApiHistoryStatusSuccess = ApiSuccess<{
1220
+ state: 'running' | 'succeeded' | 'failed';
1221
+ error?: string;
1222
+ requests?: ApiHistoryItem[];
1223
+ effectiveSince?: string;
1224
+ sinceClipped?: boolean;
1225
+ }>;
1226
+ //#endregion
1154
1227
  //#region src/models/area/model.d.ts
1155
1228
  type AreaId = `Area.${string}`;
1156
1229
  type AreaAssignmentType = 'user' | 'team' | 'company' | 'draft';
@@ -1312,7 +1385,7 @@ type IncomingScript = ScriptBase & {
1312
1385
  };
1313
1386
  type OutgoingScript = ScriptBase & {
1314
1387
  type: 'outgoing';
1315
- dataType: 'Account' | 'Company' | 'User' | 'Event';
1388
+ dataType: 'Account' | 'Company' | 'User' | 'Event' | 'Screenshot';
1316
1389
  };
1317
1390
  type ScheduledScript = ScriptBase & {
1318
1391
  type: 'scheduled';
@@ -1381,6 +1454,104 @@ type AppGetSuccess = ApiSuccess<{
1381
1454
  app: AppData;
1382
1455
  versions: AppVersionData[];
1383
1456
  }>;
1457
+ type AppUpdateInput = {
1458
+ app: AppData & {
1459
+ /** Markdown shown on the app's marketplace Documentation tab. */documentation?: string;
1460
+ };
1461
+ };
1462
+ type AppUpdateSuccess = ApiSuccess<{
1463
+ app: AppData;
1464
+ }>;
1465
+ //#endregion
1466
+ //#region src/models/plan/model.d.ts
1467
+ type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
1468
+ type WeekOfYear = `0${Exclude<Digit, 0>}` | `${1 | 2 | 3 | 4}${Digit}` | `5${0 | 1 | 2}`;
1469
+ /** A week as `W<year>|<week 01-52>`, such as `W2026|47`. */
1470
+ type WeeklyPeriodValue = `W${number}|${WeekOfYear}`;
1471
+ /** A quarter as `Q<year>|<quarter 1-4>`, such as `Q2026|4`. */
1472
+ type QuarterlyPeriodValue = `Q${number}|${1 | 2 | 3 | 4}`;
1473
+ type PlanPeriodValue = WeeklyPeriodValue | QuarterlyPeriodValue;
1474
+ /** Plans exist only for weeks and quarters. */
1475
+ declare const PLAN_PERIOD_TYPES: readonly ["week", "quarter"];
1476
+ type PlanPeriodType = (typeof PLAN_PERIOD_TYPES)[number];
1477
+ type PlanPeriod = {
1478
+ periodType: 'week';
1479
+ period: WeeklyPeriodValue;
1480
+ } | {
1481
+ periodType: 'quarter';
1482
+ period: QuarterlyPeriodValue;
1483
+ };
1484
+ /** A plan belongs to a user or to a team, such as an office. */
1485
+ type PlanScope = {
1486
+ scope: 'user';
1487
+ scopeId: UserId;
1488
+ } | {
1489
+ scope: 'team';
1490
+ scopeId: TeamId;
1491
+ };
1492
+ type PlanScopeId = UserId | TeamId;
1493
+ type PlanStatus = 'Pending' | 'Submitted' | 'Approved' | 'Rejected' | 'Closed';
1494
+ /** `Pitch`, an account status ID (`AS.`), or a workflow stage ID (`S.`). */
1495
+ type PlanStageId = 'Pitch' | `S.${string}` | `AS.${string}`;
1496
+ type PlanMilestone = 'Pitch' | 'Lead' | 'Set' | 'Sit' | 'Closed' | 'Approved' | 'Permit Submitted' | 'Permit Approved' | 'Installed' | 'Archived' | 'Do Not Contact';
1497
+ /** One stage target of a plan. Dashboards show `quantityRequired` as the stage's target when `pricePerUnit` is unset. */
1498
+ type PlanStageData = {
1499
+ milestone: PlanMilestone;
1500
+ stageId?: PlanStageId;
1501
+ conversionRate: number;
1502
+ quantityRequired?: number;
1503
+ pricePerUnit?: number;
1504
+ actual?: number;
1505
+ pace?: number;
1506
+ };
1507
+ type DailyPlan = {
1508
+ /** ISO 8601 date, such as `2026-11-19`. */date: string;
1509
+ working?: number;
1510
+ targetPitches?: number;
1511
+ workingHours?: {
1512
+ startTime: number;
1513
+ endTime: number;
1514
+ };
1515
+ };
1516
+ /** The plan fields a caller sets; the server sets the audit fields. */
1517
+ type PlanFields = {
1518
+ status: PlanStatus;
1519
+ days: DailyPlan[];
1520
+ comments?: string;
1521
+ targetIncome?: number;
1522
+ workflowId?: `WF.${string}`;
1523
+ setter?: PlanStageData[];
1524
+ closer?: PlanStageData[];
1525
+ selfgen?: PlanStageData[];
1526
+ questionsAndAnswers?: {
1527
+ question: string;
1528
+ answer?: string;
1529
+ }[];
1530
+ };
1531
+ type PlanData = AuditProps & PlanFields & PlanPeriod & PlanScope;
1532
+ //#endregion
1533
+ //#region src/models/plan/api.d.ts
1534
+ type PlanListInput = {
1535
+ /** Omit to use the authenticated user. */scopeId?: PlanScopeId;
1536
+ period?: PlanPeriodValue; /** With a team `scopeId`, list each member's plan for `period` (default: the current quarter). */
1537
+ includeTeamMembers?: boolean;
1538
+ };
1539
+ type PlanListSuccess = ApiSuccess<{
1540
+ plans: PlanData[];
1541
+ }>;
1542
+ type PlanGetInput = {
1543
+ /** Omit to use the authenticated user. */scopeId?: PlanScopeId;
1544
+ period: PlanPeriodValue;
1545
+ };
1546
+ type PlanGetSuccess = ApiSuccess<{
1547
+ plan: PlanData;
1548
+ }>;
1549
+ type PlanAddInput = {
1550
+ plan: PlanFields & PlanPeriod & PlanScope;
1551
+ };
1552
+ type PlanUpdateInput = {
1553
+ /** Picks the plan by scope and period; the other fields given replace the stored ones. */planData: Partial<PlanFields> & PlanPeriod & PlanScope;
1554
+ };
1384
1555
  //#endregion
1385
1556
  //#region src/models/webhook.d.ts
1386
1557
  type WebhookAuditProps = {
@@ -1406,8 +1577,30 @@ type CompanyWebhookData = WebhookAuditProps & Omit<CompanyData, 'companyId'> & {
1406
1577
  id: CompanyId;
1407
1578
  };
1408
1579
  type CompanyWebhook = WebhookPayload<'Company', CompanyWebhookData, 'id'>;
1409
- type AccountWebhookData = WebhookAuditProps & Omit<AccountData, 'accountId' | 'resident'> & {
1580
+ type AccountWebhookWorkflowState = {
1581
+ workflowId: WorkflowId;
1582
+ stageId: WorkflowStageId;
1583
+ actionId?: WorkflowActionId;
1584
+ stageName?: string;
1585
+ actionName?: string;
1586
+ sourceStage?: string;
1587
+ };
1588
+ /**
1589
+ * The Account webhook payload as Terros sends it. It is not AccountData: the homeowner is `resident`,
1590
+ * the address is `address` and custom fields are `customFieldMap`.
1591
+ */
1592
+ type AccountWebhookData = WebhookAuditProps & {
1410
1593
  id: AccountId;
1594
+ accountStatus?: string;
1595
+ workflowState?: AccountWebhookWorkflowState;
1596
+ owner?: SmallUser;
1597
+ closer?: SmallUser;
1598
+ address?: SmallAddress;
1599
+ resident?: TinyResidentData;
1600
+ note?: string;
1601
+ notes?: AccountNote[];
1602
+ externalLeadId?: string;
1603
+ customFieldMap?: CustomFieldMap;
1411
1604
  };
1412
1605
  type AccountWebhook = WebhookPayload<'Account', AccountWebhookData, 'id'>;
1413
1606
  //#endregion
@@ -1435,6 +1628,14 @@ declare class AccountClient {
1435
1628
  upsert(input: AccountUpsertInput): Promise<AccountUpsertSuccess>;
1436
1629
  }
1437
1630
  //#endregion
1631
+ //#region src/clients/apiHistory.d.ts
1632
+ declare class ApiHistoryClient {
1633
+ private readonly api;
1634
+ constructor(api: TerrosApiClient);
1635
+ start(input: ApiHistoryStartInput): Promise<ApiHistoryStartSuccess>;
1636
+ status(input: ApiHistoryStatusInput): Promise<ApiHistoryStatusSuccess>;
1637
+ }
1638
+ //#endregion
1438
1639
  //#region src/clients/area.d.ts
1439
1640
  declare class AreaClient {
1440
1641
  private readonly api;
@@ -1485,6 +1686,7 @@ declare class ConnectAppClient {
1485
1686
  private readonly api;
1486
1687
  constructor(api: TerrosApiClient);
1487
1688
  get(input: AppGetInput): Promise<AppGetSuccess>;
1689
+ update(input: AppUpdateInput): Promise<AppUpdateSuccess>;
1488
1690
  }
1489
1691
  declare class ConnectAppVersionClient {
1490
1692
  private readonly api;
@@ -1506,6 +1708,18 @@ declare class ConnectClient {
1506
1708
  constructor(api: TerrosApiClient);
1507
1709
  }
1508
1710
  //#endregion
1711
+ //#region src/clients/plan.d.ts
1712
+ declare class PlanClient {
1713
+ private readonly api;
1714
+ constructor(api: TerrosApiClient);
1715
+ list(input?: PlanListInput): Promise<PlanListSuccess>;
1716
+ get(input: PlanGetInput): Promise<PlanGetSuccess>;
1717
+ add({
1718
+ plan
1719
+ }: PlanAddInput): Promise<PlanGetSuccess>;
1720
+ update(input: PlanUpdateInput): Promise<PlanGetSuccess>;
1721
+ }
1722
+ //#endregion
1509
1723
  //#region src/clients/team.d.ts
1510
1724
  declare class TeamClient {
1511
1725
  private readonly api;
@@ -1539,13 +1753,15 @@ declare class UserClient {
1539
1753
  //#region src/client.d.ts
1540
1754
  declare class TerrosClient {
1541
1755
  readonly account: AccountClient;
1756
+ readonly apiHistory: ApiHistoryClient;
1542
1757
  readonly area: AreaClient;
1543
1758
  readonly calendar: CalendarClient;
1544
1759
  readonly company: CompanyClient;
1545
1760
  readonly connect: ConnectClient;
1761
+ readonly plan: PlanClient;
1546
1762
  readonly team: TeamClient;
1547
1763
  readonly user: UserClient;
1548
- constructor(config?: TerrosClientConfig);
1764
+ constructor(config?: Omit<TerrosClientConfig, 'accessToken'>);
1549
1765
  }
1550
1766
  //#endregion
1551
1767
  //#region src/connect/handler.d.ts
@@ -1569,4 +1785,33 @@ type ConnectExecutionInput<Payload, ScriptConfig extends ConnectScriptConfig> =
1569
1785
  type WrappedHandler<Input, Result, ScriptConfig extends ConnectScriptConfig = Record<string, string>> = (input: ConnectExecutionInput<Input, ScriptConfig>) => Promise<Result>;
1570
1786
  declare function wrapConnectHandler<Input, Result = void, ScriptConfig extends ConnectScriptConfig = Record<string, string>>(handler: ConnectHandlerFunction<Input, Result, ScriptConfig>): WrappedHandler<Input, Result, ScriptConfig>;
1571
1787
  //#endregion
1572
- export { AccessStatus, AccountAddInput, AccountAddSuccess, AccountContact, AccountData, AccountDataResponse, AccountGetInput, AccountGetSuccess, AccountHooksInput, AccountId, AccountListInput, AccountListSuccess, AccountMatchInput, AccountMatchSuccess, AccountNote, AccountPartialUpdateInput, AccountRemoveInput, AccountSortBy, AccountSortOrder, AccountStatusAddInput, AccountStatusAddSuccess, AccountStatusCode, AccountStatusData, AccountStatusId, AccountStatusListInput, AccountStatusListSuccess, AccountStatusRemoveInput, AccountStatusSearchInput, AccountStatusUpdateInput, AccountStatusUpdateSuccess, AccountUpdateBatchInput, AccountUpdateBatchSuccess, AccountUpdateInput, AccountUpdateSuccess, AccountUpsertInput, AccountUpsertSuccess, AccountUserDetails, AccountWebhook, AccountWebhookData, Address, AppData, AppGetInput, AppGetSuccess, AppId, AppVersionData, AppVersionId, AreaAddInput, AreaAddSuccess, AreaAssignInput, AreaAssignmentConfig, AreaAssignmentType, AreaData, AreaFilters, AreaGetInput, AreaGetSuccess, AreaId, AreaJobInfo, AreaListInput, AreaListSortBy, AreaListSortOrder, AreaListSuccess, AreaRemoveInput, AreaRunHistoryEntry, AreaRunType, AreaScheduleEntry, AreaSortCursor, AreaStateName, AreaUpdateInput, AreaUpdateSuccess, AttachmentId, AuditLog, AuditProps, AuthSchemaField, AvailableCloser, BillingMethod, BulkModifyAccountsAction, BulkModifyAccountsInput, CalendarAvailabilityInput, CalendarAvailabilitySuccess, CalendarClosersInput, CalendarClosersSuccess, CalendarEventAddInput, CalendarEventAddSuccess, CalendarEventConfirmInput, CalendarEventConfirmSuccess, CalendarEventData, CalendarEventDataWithDetails, CalendarEventGetInput, CalendarEventGetSuccess, CalendarEventId, CalendarEventListInput, CalendarEventListSuccess, CalendarEventLocation, CalendarEventRemoveInput, CalendarEventUpdateInput, CalendarEventUpdateSuccess, CalendarEventUpsertInput, CalendarEventUpsertSuccess, CalendarTimeslotsInput, CalendarTimeslotsSuccess, CloserSettings, CloserStatus, CompanyAddInput, CompanyAddSuccess, CompanyData, CompanyGetInput, CompanyGetSuccess, CompanyId, CompanyIndustry, CompanyKind, CompanyListInput, CompanyListSuccess, CompanyRemoveInput, CompanyRemoveSuccess, CompanySetupInput, CompanySetupSuccess, CompanySize, CompanyUpdateInput, CompanyUpdateSuccess, CompanyWebhook, CompanyWebhookData, ConfigSchemaField, ConnectHandlerFunction, ContactId, CustomFieldFilter, CustomFieldFilterValue, CustomFieldId, CustomFieldMap, CustomFieldType, DemoState, DispositionId, ElasticFilter, EntityId, EventOutcomeHistory, EventOutcomeId, EventType, IncomingScript, InterviewId, LatLng, LocationId, ManualAccessOverride, MeetingTime, NoteId, NotificationPreference, OutgoingScript, PartialAddress, PartialCompanyData, PartialTeamData, PermissionMap, RangeFilter, RoleData, RoleId, ScheduledScript, ScriptAddInput, ScriptAddSuccess, ScriptBase, ScriptData, SmallAddress, SmallCloser, SmallUser, SortCursor, SpecialtyAttachments, StatusHistoryItem, SyncedCalendarEvent, TagId, TeamAddInput, TeamAddSuccess, TeamData, TeamDownlineInput, TeamDownlineSuccess, TeamGetInput, TeamGetSuccess, TeamId, TeamListInput, TeamListSuccess, TeamMemberData, TeamRemoveInput, TeamRemoveSuccess, TeamUpdateData, TeamUpdateInput, TeamUpdateSuccess, TerrosClient, TinyAccountStatus, TinyCloser, TinyCompany, TinyResidentData, TinyRole, TinyTeam, TinyUser, TinyWorkflowAccount, UnsavedAccount, UnsavedAccountContact, UnsavedAccountNote, UnsavedAccountStatus, UnsavedAppVersion, UnsavedArea, UnsavedCalendarEventData, UnsavedCompany, UnsavedScript, UnsavedTeam, UnsavedUser, UpsertLatLng, UpsertTinyResidentData, UserAddInput, UserAddSuccess, UserBulkUpdateInput, UserBulkUpdateSuccess, UserClosersInput, UserClosersSuccess, UserData, UserGetInput, UserGetSuccess, UserHistory, UserId, UserIdentifier, UserListInput, UserListSuccess, UserManagerInput, UserManagerSuccess, UserPreferences, UserProfileData, UserProfileInput, UserProfileSuccess, UserRemoveInput, UserReportInput, UserReportSuccess, UserSearchInput, UserSearchSuccess, UserTeamData, UserTeamsByLevel, UserTimezoneInput, UserUpdateInput, UserUpdateSuccess, UserWebhook, UserWebhookData, VersionAddInput, VersionAddSuccess, VersionGetInput, VersionGetSuccess, VersionUpdateInput, VersionUpdateSuccess, WebhookAddUpdatePayload, WebhookAuditProps, WebhookPayload, WebhookRemovePayload, Weekday, WorkflowActionId, WorkflowHistoryItem, WorkflowId, WorkflowStageId, wrapConnectHandler };
1788
+ //#region src/connect/permanentError.d.ts
1789
+ /**
1790
+ * A terminal Connect AppScript failure.
1791
+ *
1792
+ * Thrown from the script Lambda, the Node.js runtime reports a `FunctionError`
1793
+ * whose `errorType` is exactly `PermanentError`. The execution engine acknowledges
1794
+ * that without an SQS retry or a dead-letter queue and logs a terminal failure.
1795
+ *
1796
+ * Throw this when the same input cannot succeed on a later run: bad config, a
1797
+ * missing location, an invalid link, or a non-retryable 4xx. Throw a normal
1798
+ * `Error` for a transient failure (timeout, network error, HTTP 429, or 5xx) so
1799
+ * the run stays retryable.
1800
+ */
1801
+ declare class PermanentError extends Error {
1802
+ readonly name: string;
1803
+ constructor(message: string, options?: ErrorOptions);
1804
+ }
1805
+ /**
1806
+ * A terminal failure caused on the customer's side of the integration, not by Terros.
1807
+ *
1808
+ * Throw it when only the customer can fix the failure: the install's config or credentials, a payload sent to the
1809
+ * wrong script slug, or a third party rejecting the request with a non-retryable 4xx such as bad credentials. The
1810
+ * execution engine treats it as a `PermanentError` (no retry, no dead-letter queue) and counts it as an integration
1811
+ * failure, which stays visible but does not alarm Terros on-call. Every other failure counts against Terros.
1812
+ */
1813
+ declare class IntegrationError extends PermanentError {
1814
+ readonly name: string;
1815
+ }
1816
+ //#endregion
1817
+ export { AccessStatus, AccountAddInput, AccountAddSuccess, AccountContact, AccountData, AccountDataResponse, AccountGetInput, AccountGetSuccess, AccountHooksInput, AccountId, AccountListInput, AccountListSuccess, AccountMatchInput, AccountMatchSuccess, AccountNote, AccountPartialUpdateInput, AccountRemoveInput, AccountSortBy, AccountSortOrder, AccountStatusAddInput, AccountStatusAddSuccess, AccountStatusCode, AccountStatusData, AccountStatusId, AccountStatusListInput, AccountStatusListSuccess, AccountStatusRemoveInput, AccountStatusSearchInput, AccountStatusUpdateInput, AccountStatusUpdateSuccess, AccountUpdateBatchInput, AccountUpdateBatchSuccess, AccountUpdateInput, AccountUpdateSuccess, AccountUpsertInput, AccountUpsertSuccess, AccountUserDetails, AccountWebhook, AccountWebhookData, AccountWebhookWorkflowState, Address, ApiHistoryItem, ApiHistoryStartInput, ApiHistoryStartSuccess, ApiHistoryStatusInput, ApiHistoryStatusSuccess, AppData, AppGetInput, AppGetSuccess, AppId, AppUpdateInput, AppUpdateSuccess, AppVersionData, AppVersionId, AreaAddInput, AreaAddSuccess, AreaAssignInput, AreaAssignmentConfig, AreaAssignmentType, AreaData, AreaFilters, AreaGetInput, AreaGetSuccess, AreaId, AreaJobInfo, AreaListInput, AreaListSortBy, AreaListSortOrder, AreaListSuccess, AreaRemoveInput, AreaRunHistoryEntry, AreaRunType, AreaScheduleEntry, AreaSortCursor, AreaStateName, AreaUpdateInput, AreaUpdateSuccess, AttachmentId, AuditLog, AuditProps, AuthSchemaField, AvailableCloser, BillingMethod, BulkModifyAccountsAction, BulkModifyAccountsInput, CalendarAvailabilityInput, CalendarAvailabilitySuccess, CalendarClosersInput, CalendarClosersSuccess, CalendarEventAddInput, CalendarEventAddSuccess, CalendarEventConfirmInput, CalendarEventConfirmSuccess, CalendarEventData, CalendarEventDataWithDetails, CalendarEventGetInput, CalendarEventGetSuccess, CalendarEventId, CalendarEventListInput, CalendarEventListSuccess, CalendarEventLocation, CalendarEventRemoveInput, CalendarEventUpdateInput, CalendarEventUpdateSuccess, CalendarEventUpsertInput, CalendarEventUpsertSuccess, CalendarTimeslotsInput, CalendarTimeslotsSuccess, CloserSettings, CloserStatus, CompanyAddInput, CompanyAddSuccess, CompanyData, CompanyGetInput, CompanyGetSuccess, CompanyId, CompanyIndustry, CompanyKind, CompanyListInput, CompanyListSuccess, CompanyRemoveInput, CompanyRemoveSuccess, CompanySetupInput, CompanySetupSuccess, CompanySize, CompanyUpdateInput, CompanyUpdateSuccess, CompanyWebhook, CompanyWebhookData, ConfigSchemaField, ConnectHandlerFunction, ContactId, CustomFieldFilter, CustomFieldFilterValue, CustomFieldId, CustomFieldMap, CustomFieldType, DailyPlan, DemoState, DispositionId, ElasticFilter, EntityId, EventOutcomeHistory, EventOutcomeId, EventType, IncomingScript, IntegrationError, InterviewId, LatLng, LocationId, ManualAccessOverride, MeetingTime, NoteId, NotificationPreference, OutgoingScript, PLAN_PERIOD_TYPES, PartialAddress, PartialCompanyData, PartialTeamData, PermanentError, PermissionMap, PinPlacement, PlanAddInput, PlanData, PlanFields, PlanGetInput, PlanGetSuccess, PlanListInput, PlanListSuccess, PlanMilestone, PlanPeriod, PlanPeriodType, PlanPeriodValue, PlanScope, PlanScopeId, PlanStageData, PlanStageId, PlanStatus, PlanUpdateInput, QuarterlyPeriodValue, RangeFilter, RoleData, RoleId, ScheduledScript, ScriptAddInput, ScriptAddSuccess, ScriptBase, ScriptData, SmallAddress, SmallCloser, SmallUser, SortCursor, SpecialtyAttachments, StatusHistoryItem, SyncedCalendarEvent, TagId, TeamAddInput, TeamAddSuccess, TeamData, TeamDownlineInput, TeamDownlineSuccess, TeamGetInput, TeamGetSuccess, TeamId, TeamListInput, TeamListSuccess, TeamMemberData, TeamRemoveInput, TeamRemoveSuccess, TeamUpdateData, TeamUpdateInput, TeamUpdateSuccess, TerrosClient, TinyAccountStatus, TinyCloser, TinyCompany, TinyResidentData, TinyRole, TinyTeam, TinyUser, TinyWorkflowAccount, UnsavedAccount, UnsavedAccountContact, UnsavedAccountNote, UnsavedAccountStatus, UnsavedAppVersion, UnsavedArea, UnsavedCalendarEventData, UnsavedCompany, UnsavedScript, UnsavedTeam, UnsavedUser, UpsertAccountNote, UpsertLatLng, UpsertTinyResidentData, UserAddInput, UserAddSuccess, UserBulkUpdateInput, UserBulkUpdateSuccess, UserClosersInput, UserClosersSuccess, UserData, UserGetInput, UserGetSuccess, UserHistory, UserId, UserIdentifier, UserListInput, UserListSuccess, UserManagerInput, UserManagerSuccess, UserPreferences, UserProfileData, UserProfileInput, UserProfileSuccess, UserRemoveInput, UserReportInput, UserReportSuccess, UserSearchInput, UserSearchSuccess, UserTeamData, UserTeamsByLevel, UserTimezoneInput, UserUpdateInput, UserUpdateSuccess, UserWebhook, UserWebhookData, VersionAddInput, VersionAddSuccess, VersionGetInput, VersionGetSuccess, VersionUpdateInput, VersionUpdateSuccess, WebhookAddUpdatePayload, WebhookAuditProps, WebhookPayload, WebhookRemovePayload, Weekday, WeeklyPeriodValue, WorkflowActionId, WorkflowHistoryItem, WorkflowId, WorkflowStageId, getPreferredName, wrapConnectHandler };
package/dist/index.mjs CHANGED
@@ -1,28 +1,130 @@
1
+ import { setTimeout } from "node:timers/promises";
1
2
  import { join } from "node:path";
3
+ import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
4
+ import { randomUUID } from "node:crypto";
2
5
  import { homedir, platform, release } from "node:os";
3
- import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
4
6
  //#region ../packages/connect-common/dist/models.js
7
+ /** An API failure that preserves its machine-readable error code for CLI and MCP callers. */
8
+ var TerrosApiError = class extends Error {
9
+ code;
10
+ response;
11
+ constructor(response) {
12
+ super(response.message ? `${response.error}: ${response.message}` : response.error);
13
+ this.name = "TerrosApiError";
14
+ this.code = response.error;
15
+ this.response = response;
16
+ }
17
+ };
5
18
  function isResponseError(response) {
6
19
  return typeof response === "object" && response !== null && response.type === "error" && Boolean(response.error);
7
20
  }
8
21
  //#endregion
22
+ //#region ../packages/connect-common/dist/environment.js
23
+ const STAGE_NAME = /^[a-z][a-z0-9-]*$/;
24
+ const STACK_HOST = /^api\.([a-z][a-z0-9-]*)\.terros\.com$/;
25
+ /**
26
+ * Picks the backend from `TERROS_ENV` (the CLI's `--env` flag sets it) or `TERROS_API_ENDPOINT`. Only Terros hosts
27
+ * (`https://api.terros.com`, `https://api.<stage>.terros.com`) and `http://localhost` are accepted, because every
28
+ * environment sends its own saved sign-in or API key to its host and nothing else may receive one. A stack other than
29
+ * production gets its own state directory, so a staging sign-in or schema is never sent to production, nor the reverse.
30
+ */
31
+ function resolveEnvironment(env = process.env) {
32
+ const requested = env.TERROS_ENV?.trim().toLowerCase();
33
+ const selected = requested === "production" ? "prod" : requested;
34
+ if (env.TERROS_ENV !== void 0 && !selected) throw new Error("TERROS_ENV (or --env) is blank. Use prod, staging, or a stack name.");
35
+ if (selected && !STAGE_NAME.test(selected)) throw new Error(`Unknown environment "${selected}". Use prod, staging, or a developer stack name such as "alex".`);
36
+ const endpoint = env.TERROS_API_ENDPOINT?.trim();
37
+ const backend = endpoint ? parseEndpoint(endpoint) : { name: selected || "prod" };
38
+ if (selected === "localhost" && !("baseUrl" in backend && backend.baseUrl.startsWith("http://localhost"))) throw new Error("--env localhost needs TERROS_API_ENDPOINT=http://localhost:<port> to say which port.");
39
+ if (selected && (backend.name !== selected || selected !== "localhost" && "baseUrl" in backend && backend.baseUrl !== (selected === "prod" ? "https://api.terros.com" : `https://api.${selected}.terros.com`))) throw new Error("TERROS_ENV (or --env) conflicts with TERROS_API_ENDPOINT: they pick different backends.");
40
+ const configDir = join(homedir(), ".config", "terros");
41
+ const { name } = backend;
42
+ return {
43
+ name,
44
+ baseUrl: "baseUrl" in backend ? backend.baseUrl : name === "prod" ? "https://api.terros.com" : `https://api.${name}.terros.com`,
45
+ stateDir: name === "prod" ? configDir : "baseUrl" in backend && backend.baseUrl.startsWith("http://localhost") ? join(configDir, "env", "localhost", `port-${new URL(backend.baseUrl).port || "80"}`) : join(configDir, "env", name)
46
+ };
47
+ }
48
+ function parseEndpoint(endpoint) {
49
+ const unsupported = /* @__PURE__ */ new Error(`Unsupported API host "${endpoint}". Use https://api.terros.com, https://api.<stage>.terros.com or http://localhost.`);
50
+ let url;
51
+ try {
52
+ url = new URL(/^https?:\/\//i.test(endpoint) ? endpoint : `https://${endpoint}`);
53
+ } catch {
54
+ throw unsupported;
55
+ }
56
+ if (url.username || url.password || url.search || url.hash || url.pathname !== "/") throw unsupported;
57
+ if (url.protocol === "http:" && url.hostname === "localhost") return {
58
+ name: "localhost",
59
+ baseUrl: url.origin
60
+ };
61
+ if (url.protocol !== "https:" || url.port) throw unsupported;
62
+ if (url.hostname === "api.terros.com") return {
63
+ name: "prod",
64
+ baseUrl: url.origin
65
+ };
66
+ const stage = STACK_HOST.exec(url.hostname)?.[1];
67
+ if (!stage || stage === "prod") throw unsupported;
68
+ return {
69
+ name: stage,
70
+ baseUrl: url.origin
71
+ };
72
+ }
73
+ function environmentApiKeyVariable(environment) {
74
+ const url = new URL(environment.baseUrl);
75
+ if (url.protocol === "http:") return `TERROS_API_KEY_PORT_${url.port || "80"}`;
76
+ return environment.name === "prod" ? "TERROS_API_KEY" : `TERROS_API_KEY_STAGE_${environment.name.toUpperCase().replaceAll("-", "_")}`;
77
+ }
78
+ function environmentApiKey(environment, env = process.env) {
79
+ return env[environmentApiKeyVariable(environment)];
80
+ }
81
+ /**
82
+ * Shared staging already accepts production tokens, so signing in there adds no exposure and is how staff get a key.
83
+ * A developer's own stack or localhost is someone's personal server: a token sent there is valid against production.
84
+ */
85
+ function interactiveSignInRefusal(environment) {
86
+ if (environment.name === "prod" || environment.name === "staging") return void 0;
87
+ return `Interactive sign-in is only available for production and staging, because ${environment.name} is not a shared Terros backend and a sign-in sent to it would be a production credential. Use an API key: set ${environmentApiKeyVariable(environment)}.`;
88
+ }
89
+ //#endregion
9
90
  //#region ../packages/connect-common/dist/oauth/constants.js
10
91
  const AUTH0_CLIENT_ID = "Aj2tDQZgcN8de0k4jvsndHILsLvyDh5o";
11
92
  const AUTH0_DOMAIN = "https://auth.terros.com";
12
93
  //#endregion
13
94
  //#region ../packages/connect-common/dist/oauth/auth0.js
95
+ const AUTH_REQUIRED_MESSAGES = {
96
+ expired: "Your Terros session has expired. Run `terros auth login` to sign in again.",
97
+ "signed-out": "You're not signed in to Terros. Run `terros auth login` to sign in."
98
+ };
99
+ /** The user has to sign in again; its message is the whole story, so callers print it as is and never wrap it. */
100
+ var AuthRequiredError = class extends Error {
101
+ reason;
102
+ constructor(reason) {
103
+ super(AUTH_REQUIRED_MESSAGES[reason]);
104
+ this.name = "AuthRequiredError";
105
+ this.reason = reason;
106
+ }
107
+ };
14
108
  async function refreshTokens(refreshToken) {
15
- const res = await fetch(`${AUTH0_DOMAIN}/oauth/token`, {
16
- method: "POST",
17
- headers: { "Content-Type": "application/json" },
18
- body: JSON.stringify({
19
- client_id: AUTH0_CLIENT_ID,
20
- grant_type: "refresh_token",
21
- refresh_token: refreshToken
22
- })
23
- });
109
+ let res;
110
+ try {
111
+ res = await fetch(`${AUTH0_DOMAIN}/oauth/token`, {
112
+ method: "POST",
113
+ headers: { "Content-Type": "application/json" },
114
+ body: JSON.stringify({
115
+ client_id: AUTH0_CLIENT_ID,
116
+ grant_type: "refresh_token",
117
+ refresh_token: refreshToken
118
+ })
119
+ });
120
+ } catch (cause) {
121
+ throw new Error("Unable to reach Terros sign-in to refresh the session; check your connection and try again", { cause });
122
+ }
24
123
  if (res.ok) return await res.json();
25
- throw new Error("Unable to refresh token, it may be expired. Run `terros auth login` to sign in again");
124
+ const body = await res.json().catch(() => void 0);
125
+ const error = body !== null && typeof body === "object" ? body.error : void 0;
126
+ if (error === "invalid_grant") throw new AuthRequiredError("expired");
127
+ throw new Error(`Unable to refresh the Terros session: sign-in answered ${res.status}${error ? ` ${error}` : ""}`);
26
128
  }
27
129
  //#endregion
28
130
  //#region ../packages/connect-common/dist/oauth/tokens.js
@@ -30,24 +132,103 @@ const AUTH_DIR_MODE = 448;
30
132
  const AUTH_FILE_MODE = 384;
31
133
  const SECOND = 1e3;
32
134
  const MINUTE = 60 * SECOND;
33
- async function getTokens() {
34
- const tokens = await readTokens();
135
+ const LOCK_RETRY_MS = 50;
136
+ const LOCK_TIMEOUT_MS = MINUTE;
137
+ const LOCK_OWNER = /^(\d+):([\w-]+)$/;
138
+ const pendingRefresh = /* @__PURE__ */ new Map();
139
+ let deadRefreshToken;
140
+ async function getTokens(stateDir = resolveEnvironment().stateDir) {
141
+ const tokens = await readTokens(stateDir);
35
142
  if (tokens === null) return null;
36
143
  if (areTokensValid(tokens)) return tokens;
37
- return await saveTokens(await refreshTokens(tokens.refresh_token));
144
+ let pending = pendingRefresh.get(stateDir);
145
+ if (!pending) {
146
+ pending = withAuthLock(stateDir, () => refreshSavedTokens(stateDir)).finally(() => {
147
+ pendingRefresh.delete(stateDir);
148
+ });
149
+ pendingRefresh.set(stateDir, pending);
150
+ }
151
+ return await pending;
152
+ }
153
+ async function refreshSavedTokens(stateDir) {
154
+ const tokens = await readTokens(stateDir);
155
+ if (tokens === null || areTokensValid(tokens)) return tokens;
156
+ if (tokens.refresh_token === void 0) return null;
157
+ if (tokens.refresh_token === deadRefreshToken) throw new AuthRequiredError("expired");
158
+ const response = await refreshTokens(tokens.refresh_token).catch((error) => {
159
+ if (error instanceof AuthRequiredError) deadRefreshToken = tokens.refresh_token;
160
+ throw error;
161
+ });
162
+ return await writeTokens(stateDir, {
163
+ ...response,
164
+ refresh_token: response.refresh_token ?? tokens.refresh_token
165
+ });
166
+ }
167
+ async function withAuthLock(stateDir, run) {
168
+ const lockFile = `${await getAuthFilePath(stateDir)}.lock`;
169
+ const owner = `${process.pid}:${randomUUID()}`;
170
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
171
+ while (!await tryLock(lockFile, owner)) {
172
+ if (Date.now() > deadline) throw new Error(`Timed out waiting for another terros command to renew the sign-in (lock file: ${lockFile})`);
173
+ await setTimeout(LOCK_RETRY_MS);
174
+ }
175
+ try {
176
+ return await run();
177
+ } finally {
178
+ await removeLock(lockFile, owner);
179
+ }
180
+ }
181
+ async function tryLock(lockFile, owner) {
182
+ try {
183
+ await writeFile(lockFile, owner, {
184
+ flag: "wx",
185
+ mode: AUTH_FILE_MODE
186
+ });
187
+ return true;
188
+ } catch (e) {
189
+ if (e.code !== "EEXIST") throw e;
190
+ }
191
+ const holder = await readFile(lockFile, "utf-8").catch(() => null);
192
+ if (holder !== null && await isDeadLock(lockFile, holder)) await removeDeadLock(lockFile, holder);
193
+ return false;
194
+ }
195
+ async function removeDeadLock(lockFile, holder) {
196
+ const guard = `${lockFile}.${LOCK_OWNER.exec(holder)?.[2] ?? "unowned"}`;
197
+ if (!await tryLock(guard, `${process.pid}:${randomUUID()}`)) return;
198
+ try {
199
+ if (await isDeadLock(lockFile, holder)) await removeLock(lockFile, holder);
200
+ } finally {
201
+ await rm(guard, { force: true });
202
+ }
203
+ }
204
+ async function removeLock(lockFile, owner) {
205
+ if (await readFile(lockFile, "utf-8").catch(() => null) === owner) await rm(lockFile, { force: true });
206
+ }
207
+ async function isDeadLock(lockFile, holder) {
208
+ const pid = LOCK_OWNER.exec(holder)?.[1];
209
+ if (pid === void 0) {
210
+ const stats = await stat(lockFile).catch(() => null);
211
+ return stats !== null && Date.now() - stats.mtimeMs > LOCK_TIMEOUT_MS;
212
+ }
213
+ try {
214
+ process.kill(Number(pid), 0);
215
+ return false;
216
+ } catch (e) {
217
+ return e.code !== "EPERM";
218
+ }
38
219
  }
39
220
  function areTokensValid(tokens) {
40
221
  return tokens.expires_at > Date.now() + MINUTE * 5;
41
222
  }
42
- async function readTokens() {
223
+ async function readTokens(stateDir = resolveEnvironment().stateDir) {
43
224
  try {
44
- const file = await readFile(await getAuthFilePath(), "utf-8");
225
+ const file = await readFile(await getAuthFilePath(stateDir), "utf-8");
45
226
  return JSON.parse(file);
46
227
  } catch (e) {
47
228
  return null;
48
229
  }
49
230
  }
50
- async function saveTokens(tokenResponse) {
231
+ async function writeTokens(stateDir, tokenResponse) {
51
232
  const expiresAt = Date.now() + tokenResponse.expires_in * SECOND;
52
233
  const savedTokens = {
53
234
  access_token: tokenResponse.access_token,
@@ -56,13 +237,19 @@ async function saveTokens(tokenResponse) {
56
237
  token_type: tokenResponse.token_type,
57
238
  expires_at: expiresAt
58
239
  };
59
- const authFile = await getAuthFilePath();
60
- await writeFile(authFile, JSON.stringify(savedTokens), { mode: AUTH_FILE_MODE });
61
- await chmod(authFile, AUTH_FILE_MODE);
240
+ const authFile = await getAuthFilePath(stateDir);
241
+ const tempFile = `${authFile}.${randomUUID()}.tmp`;
242
+ try {
243
+ await writeFile(tempFile, JSON.stringify(savedTokens), { mode: AUTH_FILE_MODE });
244
+ await chmod(tempFile, AUTH_FILE_MODE);
245
+ await rename(tempFile, authFile);
246
+ } catch (e) {
247
+ await rm(tempFile, { force: true });
248
+ throw e;
249
+ }
62
250
  return savedTokens;
63
251
  }
64
- async function getAuthFilePath() {
65
- const configPath = join(homedir(), ".config", "terros");
252
+ async function getAuthFilePath(configPath) {
66
253
  await mkdir(configPath, {
67
254
  recursive: true,
68
255
  mode: AUTH_DIR_MODE
@@ -87,19 +274,29 @@ function getAnalyticsHeaders(override = {}) {
87
274
  }
88
275
  //#endregion
89
276
  //#region ../packages/connect-common/dist/terrosApiClient.js
90
- const PROD_BASE_URL = "https://api.terros.com";
91
277
  var TerrosApiClient = class {
92
278
  baseUrl;
279
+ stateDir;
280
+ signInRefusal;
93
281
  authStrategy;
94
282
  analytics;
95
283
  impersonateUserId;
96
284
  constructor(config = {}) {
97
- this.baseUrl = this.determineBaseUrl(config);
285
+ const environment = config.baseUrl ? resolveEnvironment({ TERROS_API_ENDPOINT: config.baseUrl }) : resolveEnvironment();
286
+ this.baseUrl = environment.baseUrl;
287
+ this.stateDir = environment.stateDir;
288
+ this.signInRefusal = interactiveSignInRefusal(environment);
98
289
  this.analytics = getAnalyticsHeaders(config.analytics);
99
- this.authStrategy = this.determineAuthStrategy(config);
290
+ this.authStrategy = this.determineAuthStrategy(config, environment);
100
291
  this.impersonateUserId = config.impersonateUserId ?? readProcessEnv("TERROS_IMPERSONATE");
101
292
  }
102
293
  async call(route, input) {
294
+ return this.request(route, "POST", input);
295
+ }
296
+ async get(route) {
297
+ return this.request(route, "GET");
298
+ }
299
+ async request(route, method, input) {
103
300
  let response;
104
301
  try {
105
302
  const authorization = await this.getAuthorizationHeader();
@@ -109,33 +306,43 @@ var TerrosApiClient = class {
109
306
  authorization
110
307
  };
111
308
  if (this.impersonateUserId) headers.impersonate_user_id = this.impersonateUserId;
112
- response = await fetch(`${this.baseUrl}/${route}`, {
113
- method: "POST",
309
+ response = await fetch(`${this.baseUrl}/${route.replace(/^\//, "")}`, {
310
+ method,
114
311
  headers,
115
312
  body: JSON.stringify(input)
116
313
  });
117
314
  } catch (cause) {
118
- throw new Error(`Request to ${route} failed`, { cause });
315
+ if (cause instanceof AuthRequiredError) throw cause;
316
+ throw new Error(`Request to ${route} failed: ${cause instanceof Error ? cause.message : cause}`, { cause });
317
+ }
318
+ if (!response.ok) {
319
+ const message = this.authStrategy.type === "apikey" && (response.status === 401 || response.status === 403) ? "Invalid or unauthorized API key" : response.statusText;
320
+ throw Object.assign(new Error(message), { status: response.status });
119
321
  }
120
- if (!response.ok) throw new Error(response.statusText);
121
322
  const output = await response.json();
122
- if (isResponseError(output)) throw new Error(output.message ?? output.error);
323
+ if (isResponseError(output)) throw new TerrosApiError(output);
123
324
  return output;
124
325
  }
125
326
  async getAuthorizationHeader() {
126
327
  if (this.authStrategy.type === "apikey") return `${this.authStrategy.authType} ${this.authStrategy.apiKey}`;
127
- const cliTokens = await getTokens();
128
- if (cliTokens === null) throw new Error("No authorization found. Log in with Terros CLI or provide an API key via environment variables or client config.");
328
+ if (this.authStrategy.type === "bearer") return `Bearer ${this.authStrategy.accessToken}`;
329
+ if (this.signInRefusal) throw new Error(this.signInRefusal);
330
+ const cliTokens = await getTokens(this.stateDir);
331
+ if (cliTokens === null) throw new AuthRequiredError("signed-out");
129
332
  return `Bearer ${cliTokens.access_token}`;
130
333
  }
131
- determineAuthStrategy(config) {
334
+ determineAuthStrategy(config, environment) {
335
+ if (config.accessToken) return {
336
+ type: "bearer",
337
+ accessToken: config.accessToken
338
+ };
132
339
  const authType = config.authType ?? "ApiKey";
133
340
  if (config.apiKey) return {
134
341
  type: "apikey",
135
342
  apiKey: config.apiKey,
136
343
  authType
137
344
  };
138
- const apiKeyFromEnv = readProcessEnv("TERROS_API_KEY");
345
+ const apiKeyFromEnv = environmentApiKey(environment);
139
346
  if (apiKeyFromEnv) return {
140
347
  type: "apikey",
141
348
  apiKey: apiKeyFromEnv,
@@ -143,13 +350,6 @@ var TerrosApiClient = class {
143
350
  };
144
351
  return { type: "oauth" };
145
352
  }
146
- determineBaseUrl(config) {
147
- if (config.baseUrl) return config.baseUrl;
148
- const envEndpoint = readProcessEnv("TERROS_API_ENDPOINT");
149
- if (!envEndpoint) return PROD_BASE_URL;
150
- if (/^https?:\/\//i.test(envEndpoint)) return envEndpoint;
151
- return `https://${envEndpoint}`;
152
- }
153
353
  };
154
354
  function readProcessEnv(key) {
155
355
  if (typeof globalThis.process === "undefined") return void 0;
@@ -157,7 +357,7 @@ function readProcessEnv(key) {
157
357
  }
158
358
  //#endregion
159
359
  //#region package.json
160
- var version = "1.0.17";
360
+ var version = "1.0.18";
161
361
  //#endregion
162
362
  //#region src/clients/account.ts
163
363
  var AccountStatusClient = class {
@@ -214,6 +414,20 @@ var AccountClient = class {
214
414
  }
215
415
  };
216
416
  //#endregion
417
+ //#region src/clients/apiHistory.ts
418
+ var ApiHistoryClient = class {
419
+ api;
420
+ constructor(api) {
421
+ this.api = api;
422
+ }
423
+ start(input) {
424
+ return this.api.call("apiHistory/start", input);
425
+ }
426
+ status(input) {
427
+ return this.api.call("apiHistory/status", input);
428
+ }
429
+ };
430
+ //#endregion
217
431
  //#region src/clients/area.ts
218
432
  var AreaClient = class {
219
433
  api;
@@ -321,6 +535,9 @@ var ConnectAppClient = class {
321
535
  get(input) {
322
536
  return this.api.call("connect/app/get", input);
323
537
  }
538
+ update(input) {
539
+ return this.api.call("connect/app/update", input);
540
+ }
324
541
  };
325
542
  var ConnectAppVersionClient = class {
326
543
  api;
@@ -359,6 +576,42 @@ var ConnectClient = class {
359
576
  }
360
577
  };
361
578
  //#endregion
579
+ //#region src/clients/plan.ts
580
+ const VERSION = 2;
581
+ var PlanClient = class {
582
+ api;
583
+ constructor(api) {
584
+ this.api = api;
585
+ }
586
+ list(input = {}) {
587
+ return this.api.call("plan/list", {
588
+ ...input,
589
+ version: VERSION
590
+ });
591
+ }
592
+ get(input) {
593
+ return this.api.call("plan/get", {
594
+ ...input,
595
+ version: VERSION
596
+ });
597
+ }
598
+ add({ plan }) {
599
+ return this.api.call("plan/add", {
600
+ plan: {
601
+ ...plan,
602
+ opinions: { self: { milestones: {} } }
603
+ },
604
+ version: VERSION
605
+ });
606
+ }
607
+ update(input) {
608
+ return this.api.call("plan/update", {
609
+ ...input,
610
+ version: VERSION
611
+ });
612
+ }
613
+ };
614
+ //#endregion
362
615
  //#region src/clients/team.ts
363
616
  var TeamClient = class {
364
617
  api;
@@ -432,10 +685,12 @@ var UserClient = class {
432
685
  //#region src/client.ts
433
686
  var TerrosClient = class {
434
687
  account;
688
+ apiHistory;
435
689
  area;
436
690
  calendar;
437
691
  company;
438
692
  connect;
693
+ plan;
439
694
  team;
440
695
  user;
441
696
  constructor(config = {}) {
@@ -444,10 +699,12 @@ var TerrosClient = class {
444
699
  analytics: { "Terros-App-Version": version }
445
700
  });
446
701
  this.account = new AccountClient(api);
702
+ this.apiHistory = new ApiHistoryClient(api);
447
703
  this.area = new AreaClient(api);
448
704
  this.calendar = new CalendarClient(api);
449
705
  this.company = new CompanyClient(api);
450
706
  this.connect = new ConnectClient(api);
707
+ this.plan = new PlanClient(api);
451
708
  this.team = new TeamClient(api);
452
709
  this.user = new UserClient(api);
453
710
  }
@@ -466,4 +723,49 @@ function wrapConnectHandler(handler) {
466
723
  };
467
724
  }
468
725
  //#endregion
469
- export { TerrosClient, wrapConnectHandler };
726
+ //#region src/connect/permanentError.ts
727
+ /**
728
+ * A terminal Connect AppScript failure.
729
+ *
730
+ * Thrown from the script Lambda, the Node.js runtime reports a `FunctionError`
731
+ * whose `errorType` is exactly `PermanentError`. The execution engine acknowledges
732
+ * that without an SQS retry or a dead-letter queue and logs a terminal failure.
733
+ *
734
+ * Throw this when the same input cannot succeed on a later run: bad config, a
735
+ * missing location, an invalid link, or a non-retryable 4xx. Throw a normal
736
+ * `Error` for a transient failure (timeout, network error, HTTP 429, or 5xx) so
737
+ * the run stays retryable.
738
+ */
739
+ var PermanentError = class extends Error {
740
+ name = "PermanentError";
741
+ constructor(message, options) {
742
+ super(message, options);
743
+ }
744
+ };
745
+ /**
746
+ * A terminal failure caused on the customer's side of the integration, not by Terros.
747
+ *
748
+ * Throw it when only the customer can fix the failure: the install's config or credentials, a payload sent to the
749
+ * wrong script slug, or a third party rejecting the request with a non-retryable 4xx such as bad credentials. The
750
+ * execution engine treats it as a `PermanentError` (no retry, no dead-letter queue) and counts it as an integration
751
+ * failure, which stays visible but does not alarm Terros on-call. Every other failure counts against Terros.
752
+ */
753
+ var IntegrationError = class extends PermanentError {
754
+ name = "IntegrationError";
755
+ };
756
+ //#endregion
757
+ //#region src/models/plan/model.ts
758
+ /** Plans exist only for weeks and quarters. */
759
+ const PLAN_PERIOD_TYPES = ["week", "quarter"];
760
+ //#endregion
761
+ //#region src/models/user/names.ts
762
+ /**
763
+ * The name the Terros app shows for a user: their trimmed preferred name, else their trimmed first name.
764
+ * Mirrors `getPreferredName` in the Sales app's shared `common` package, which this public SDK cannot depend
765
+ * on; keep the two in step.
766
+ */
767
+ function getPreferredName(user) {
768
+ return user?.preferredName?.trim() || user?.firstName?.trim() || "";
769
+ }
770
+ //#endregion
771
+ export { IntegrationError, PLAN_PERIOD_TYPES, PermanentError, TerrosClient, getPreferredName, wrapConnectHandler };
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "@types/node": "^24.13.2",
10
10
  "tsdown": "^0.22.3",
11
11
  "typescript": "^6.0.3",
12
- "vitest": "^4.1.10"
12
+ "vitest": "^4.1.12"
13
13
  },
14
14
  "engines": {
15
15
  "node": "^24"
@@ -39,7 +39,7 @@
39
39
  "sideEffects": false,
40
40
  "type": "module",
41
41
  "types": "./dist/index.d.mts",
42
- "version": "1.0.17",
42
+ "version": "1.0.18",
43
43
  "scripts": {
44
44
  "build": "tsdown",
45
45
  "test": "vitest run"