@perspectask/sdk 0.0.6 → 0.0.7

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/index.cjs CHANGED
@@ -30,10 +30,17 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ CLI_CLIENT_ID: () => CLI_CLIENT_ID,
34
+ DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
35
+ OAuthTokenError: () => OAuthTokenError,
33
36
  PerspecTask: () => PerspecTask,
34
37
  PullRequests: () => PullRequests,
35
38
  Tasks: () => Tasks,
36
39
  default: () => index_default,
40
+ refreshTokens: () => refreshTokens,
41
+ revokeTokens: () => revokeTokens,
42
+ startDeviceLogin: () => startDeviceLogin,
43
+ waitForDeviceLogin: () => waitForDeviceLogin,
37
44
  zCreateTaskBody: () => zCreateTaskBody,
38
45
  zCreateTaskResponse: () => zCreateTaskResponse,
39
46
  zGetTaskPath: () => zGetTaskPath,
@@ -938,6 +945,116 @@ var PullRequests = class {
938
945
  }
939
946
  };
940
947
 
948
+ // src/oauth.ts
949
+ var CLI_CLIENT_ID = "perspectask-cli";
950
+ var DEFAULT_BASE_URL = "https://api.perspectask.com/v1";
951
+ var DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
952
+ var SLOW_DOWN_STEP_SECONDS = 5;
953
+ var OAuthTokenError = class extends Error {
954
+ constructor(code, message) {
955
+ super(message);
956
+ this.code = code;
957
+ this.name = "OAuthTokenError";
958
+ }
959
+ code;
960
+ };
961
+ function oauthUrl(baseUrl, path) {
962
+ return new URL(path, new URL(baseUrl ?? DEFAULT_BASE_URL).origin).toString();
963
+ }
964
+ async function postForm(url, params, fetchImpl = fetch) {
965
+ const response = await fetchImpl(url, {
966
+ method: "POST",
967
+ headers: {
968
+ "Content-Type": "application/x-www-form-urlencoded",
969
+ Accept: "application/json"
970
+ },
971
+ body: new URLSearchParams(params).toString()
972
+ });
973
+ const body = await response.json().catch(() => ({}));
974
+ if (!response.ok) {
975
+ throw new OAuthTokenError(
976
+ typeof body.error === "string" ? body.error : `http_${response.status}`,
977
+ typeof body.error_description === "string" ? body.error_description : `OAuth request failed (${response.status})`
978
+ );
979
+ }
980
+ return body;
981
+ }
982
+ function toTokens(body) {
983
+ return {
984
+ accessToken: String(body.access_token),
985
+ refreshToken: String(body.refresh_token),
986
+ expiresAt: Date.now() + Number(body.expires_in) * 1e3,
987
+ scope: typeof body.scope === "string" ? body.scope : ""
988
+ };
989
+ }
990
+ async function startDeviceLogin(options = {}) {
991
+ const body = await postForm(
992
+ oauthUrl(options.baseUrl, "/oauth/device"),
993
+ {
994
+ client_id: CLI_CLIENT_ID,
995
+ ...options.scope ? { scope: options.scope } : {},
996
+ ...options.deviceName ? { device_name: options.deviceName } : {}
997
+ },
998
+ options.fetch
999
+ );
1000
+ return {
1001
+ deviceCode: String(body.device_code),
1002
+ userCode: String(body.user_code),
1003
+ verificationUri: String(body.verification_uri),
1004
+ verificationUriComplete: String(body.verification_uri_complete),
1005
+ expiresIn: Number(body.expires_in),
1006
+ interval: Number(body.interval)
1007
+ };
1008
+ }
1009
+ async function waitForDeviceLogin(login, options = {}) {
1010
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1011
+ let interval = login.interval;
1012
+ for (; ; ) {
1013
+ await sleep(interval * 1e3);
1014
+ try {
1015
+ return toTokens(
1016
+ await postForm(
1017
+ oauthUrl(options.baseUrl, "/oauth/token"),
1018
+ {
1019
+ grant_type: DEVICE_CODE_GRANT_TYPE,
1020
+ device_code: login.deviceCode,
1021
+ client_id: CLI_CLIENT_ID
1022
+ },
1023
+ options.fetch
1024
+ )
1025
+ );
1026
+ } catch (error) {
1027
+ if (!(error instanceof OAuthTokenError)) throw error;
1028
+ if (error.code === "authorization_pending") continue;
1029
+ if (error.code === "slow_down") {
1030
+ interval += SLOW_DOWN_STEP_SECONDS;
1031
+ continue;
1032
+ }
1033
+ throw error;
1034
+ }
1035
+ }
1036
+ }
1037
+ async function refreshTokens(refreshToken, options = {}) {
1038
+ return toTokens(
1039
+ await postForm(
1040
+ oauthUrl(options.baseUrl, "/oauth/token"),
1041
+ {
1042
+ grant_type: "refresh_token",
1043
+ refresh_token: refreshToken,
1044
+ client_id: CLI_CLIENT_ID
1045
+ },
1046
+ options.fetch
1047
+ )
1048
+ );
1049
+ }
1050
+ async function revokeTokens(token, options = {}) {
1051
+ await postForm(
1052
+ oauthUrl(options.baseUrl, "/oauth/revoke"),
1053
+ { token, client_id: CLI_CLIENT_ID },
1054
+ options.fetch
1055
+ ).catch(() => void 0);
1056
+ }
1057
+
941
1058
  // src/generated/zod.gen.ts
942
1059
  var z = __toESM(require("zod/mini"), 1);
943
1060
  var zTask = z.object({
@@ -1018,6 +1135,13 @@ var zPullRequest = z.object({
1018
1135
  preview_url: z.optional(z.string().register(z.globalRegistry, {
1019
1136
  description: "Latest successful preview deployment (Vercel, Netlify, \u2026). Omitted when there is none."
1020
1137
  })),
1138
+ preview_status: z.optional(z.enum([
1139
+ "building",
1140
+ "ready",
1141
+ "failed"
1142
+ ]).register(z.globalRegistry, {
1143
+ description: "State of the preview deploy of the PR's head commit: `building` while it deploys, `ready` when it's live, `failed` when it broke. `preview_url` stays the last successful preview meanwhile. Omitted when no deploy was seen for that commit."
1144
+ })),
1021
1145
  linked_by: z.enum(["auto", "manual"]).register(z.globalRegistry, {
1022
1146
  description: "`auto` = linked by the pt- code in the PR; `manual` = linked by URL."
1023
1147
  })
@@ -1163,14 +1287,20 @@ var PerspecTask = class {
1163
1287
  */
1164
1288
  tasks;
1165
1289
  constructor(options) {
1290
+ const { apiKey } = options;
1166
1291
  const client2 = createClient(
1167
1292
  createConfig({
1168
- baseUrl: options.baseUrl ?? "https://api.perspectask.com/v1",
1169
- headers: {
1170
- Authorization: `Bearer ${options.apiKey}`
1171
- }
1293
+ baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,
1294
+ ...options.fetch ? { fetch: options.fetch } : {},
1295
+ ...typeof apiKey === "string" ? { headers: { Authorization: `Bearer ${apiKey}` } } : {}
1172
1296
  })
1173
1297
  );
1298
+ if (typeof apiKey === "function") {
1299
+ client2.interceptors.request.use(async (request) => {
1300
+ request.headers.set("Authorization", `Bearer ${await apiKey()}`);
1301
+ return request;
1302
+ });
1303
+ }
1174
1304
  this.tasks = createTasksNamespace(client2);
1175
1305
  }
1176
1306
  };
@@ -1202,9 +1332,16 @@ function createTasksNamespace(client2) {
1202
1332
  var index_default = PerspecTask;
1203
1333
  // Annotate the CommonJS export names for ESM import in node:
1204
1334
  0 && (module.exports = {
1335
+ CLI_CLIENT_ID,
1336
+ DEFAULT_BASE_URL,
1337
+ OAuthTokenError,
1205
1338
  PerspecTask,
1206
1339
  PullRequests,
1207
1340
  Tasks,
1341
+ refreshTokens,
1342
+ revokeTokens,
1343
+ startDeviceLogin,
1344
+ waitForDeviceLogin,
1208
1345
  zCreateTaskBody,
1209
1346
  zCreateTaskResponse,
1210
1347
  zGetTaskPath,