@perspectask/sdk 0.0.5 → 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,17 +30,33 @@ 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,
37
+ PullRequests: () => PullRequests,
34
38
  Tasks: () => Tasks,
35
39
  default: () => index_default,
40
+ refreshTokens: () => refreshTokens,
41
+ revokeTokens: () => revokeTokens,
42
+ startDeviceLogin: () => startDeviceLogin,
43
+ waitForDeviceLogin: () => waitForDeviceLogin,
36
44
  zCreateTaskBody: () => zCreateTaskBody,
37
45
  zCreateTaskResponse: () => zCreateTaskResponse,
38
46
  zGetTaskPath: () => zGetTaskPath,
39
47
  zGetTaskQuery: () => zGetTaskQuery,
40
48
  zGetTaskResponse: () => zGetTaskResponse,
49
+ zLinkTaskPullRequestBody: () => zLinkTaskPullRequestBody,
50
+ zLinkTaskPullRequestPath: () => zLinkTaskPullRequestPath,
51
+ zLinkTaskPullRequestResponse: () => zLinkTaskPullRequestResponse,
52
+ zListTaskPullRequestsPath: () => zListTaskPullRequestsPath,
53
+ zListTaskPullRequestsResponse: () => zListTaskPullRequestsResponse,
41
54
  zListTasksQuery: () => zListTasksQuery,
42
55
  zListTasksResponse: () => zListTasksResponse,
56
+ zPullRequest: () => zPullRequest,
43
57
  zTask: () => zTask,
58
+ zUnlinkTaskPullRequestPath: () => zUnlinkTaskPullRequestPath,
59
+ zUnlinkTaskPullRequestResponse: () => zUnlinkTaskPullRequestResponse,
44
60
  zUpdateTaskBody: () => zUpdateTaskBody,
45
61
  zUpdateTaskPath: () => zUpdateTaskPath,
46
62
  zUpdateTaskResponse: () => zUpdateTaskResponse
@@ -886,6 +902,158 @@ var Tasks = class {
886
902
  });
887
903
  }
888
904
  };
905
+ var PullRequests = class {
906
+ /**
907
+ * List pull requests linked to a task
908
+ *
909
+ * The GitHub pull requests linked to this task, with their state, CI result, review decision and preview deploy, kept up to date by GitHub webhooks. Needs the PerspecTask GitHub app installed on the repository (Account → GitHub in the web app).
910
+ */
911
+ static listTaskPullRequests(options) {
912
+ return (options.client ?? client).get({
913
+ security: [{ scheme: "bearer", type: "http" }],
914
+ url: "/tasks/{id}/pull-requests",
915
+ ...options
916
+ });
917
+ }
918
+ /**
919
+ * Link a pull request to a task
920
+ *
921
+ * Link a PR by its URL. Usually unnecessary: a PR whose title, branch or description contains the task's `pr_token` links itself. Linking an already-linked PR refreshes it. Needs the PerspecTask GitHub app installed on the repository (Account → GitHub in the web app). Answers 404 with `code: "not_installed"` when the app isn't on that repository or your GitHub account can't read it.
922
+ */
923
+ static linkTaskPullRequest(options) {
924
+ return (options.client ?? client).post({
925
+ security: [{ scheme: "bearer", type: "http" }],
926
+ url: "/tasks/{id}/pull-requests",
927
+ ...options,
928
+ headers: {
929
+ "Content-Type": "application/json",
930
+ ...options.headers
931
+ }
932
+ });
933
+ }
934
+ /**
935
+ * Unlink a pull request from a task
936
+ *
937
+ * Remove a link (`prId` is the `id` from the list). It stays unlinked: later pushes to the PR do not link it again, only linking it by URL does.
938
+ */
939
+ static unlinkTaskPullRequest(options) {
940
+ return (options.client ?? client).delete({
941
+ security: [{ scheme: "bearer", type: "http" }],
942
+ url: "/tasks/{id}/pull-requests/{prId}",
943
+ ...options
944
+ });
945
+ }
946
+ };
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
+ }
889
1057
 
890
1058
  // src/generated/zod.gen.ts
891
1059
  var z = __toESM(require("zod/mini"), 1);
@@ -893,6 +1061,9 @@ var zTask = z.object({
893
1061
  id: z.optional(z.string().check(z.regex(/^[0-9a-fA-F]{3,32}$|^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/)).register(z.globalRegistry, {
894
1062
  description: 'Short id: the minimum unique prefix of the task UUID (e.g. "a3f"). Accepted anywhere an id is.'
895
1063
  })),
1064
+ pr_token: z.optional(z.string().check(z.regex(/^pt-[0-9a-f]{7,32}$/)).register(z.globalRegistry, {
1065
+ description: 'Put this code (e.g. "pt-a3f91c2") in a GitHub pull request title or branch name and the PR links itself to this task (needs the PerspecTask GitHub app on the repo). It is longer than the short id on purpose, so it stays unambiguous as more tasks are added. Returned on single-task responses (get, create, update), not on lists.'
1066
+ })),
896
1067
  title: z.optional(z.string()),
897
1068
  description: z.optional(z.string()),
898
1069
  encrypted: z.optional(z.boolean().register(z.globalRegistry, {
@@ -933,6 +1104,48 @@ var zTask = z.object({
933
1104
  children: z.optional(z.array(z.union([z.string().check(z.regex(/^[0-9a-fA-F]{3,32}$|^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/)), z.lazy(() => zTask)]))),
934
1105
  parents: z.optional(z.array(z.string().check(z.regex(/^[0-9a-fA-F]{3,32}$|^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/))))
935
1106
  });
1107
+ var zPullRequest = z.object({
1108
+ id: z.uuid().register(z.globalRegistry, {
1109
+ description: "Id of this task\u2194PR link. Pass it to unlink."
1110
+ }),
1111
+ repo: z.string(),
1112
+ number: z.int(),
1113
+ title: z.string(),
1114
+ url: z.string().register(z.globalRegistry, {
1115
+ description: "The PR on github.com."
1116
+ }),
1117
+ state: z.enum([
1118
+ "open",
1119
+ "closed",
1120
+ "merged"
1121
+ ]),
1122
+ draft: z.optional(z.literal(true).register(z.globalRegistry, {
1123
+ description: "Only present when the PR is a draft."
1124
+ })),
1125
+ checks: z.optional(z.enum([
1126
+ "pending",
1127
+ "success",
1128
+ "failure"
1129
+ ]).register(z.globalRegistry, {
1130
+ description: "Combined CI result of the PR's head commit (check runs + commit statuses). Omitted when the commit has no CI."
1131
+ })),
1132
+ review: z.optional(z.enum(["approved", "changes_requested"]).register(z.globalRegistry, {
1133
+ description: "Reviewers' current decision. Omitted when nobody approved or requested changes."
1134
+ })),
1135
+ preview_url: z.optional(z.string().register(z.globalRegistry, {
1136
+ description: "Latest successful preview deployment (Vercel, Netlify, \u2026). Omitted when there is none."
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
+ })),
1145
+ linked_by: z.enum(["auto", "manual"]).register(z.globalRegistry, {
1146
+ description: "`auto` = linked by the pt- code in the PR; `manual` = linked by URL."
1147
+ })
1148
+ });
936
1149
  var zListTasksQuery = z.object({
937
1150
  includeEncrypted: z.optional(z.boolean().register(z.globalRegistry, {
938
1151
  description: "Defaults to false. In tree mode, encrypted tasks are pruned UNLESS they lie on the path to an unencrypted task \u2014 so an encrypted parent of a readable task is kept (with `encrypted: true` and no title/description keys) to preserve structure, while fully-encrypted branches are hidden. In flat mode, encrypted tasks are simply omitted. Set to true to include ALL end-to-end-encrypted tasks for full visibility."
@@ -1041,6 +1254,30 @@ var zUpdateTaskPath = z.object({
1041
1254
  id: z.string().check(z.regex(/^[0-9a-fA-F]{3,32}$|^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/))
1042
1255
  });
1043
1256
  var zUpdateTaskResponse = zTask;
1257
+ var zListTaskPullRequestsPath = z.object({
1258
+ id: z.string().check(z.regex(/^[0-9a-fA-F]{3,32}$|^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/))
1259
+ });
1260
+ var zListTaskPullRequestsResponse = z.array(zPullRequest).register(z.globalRegistry, {
1261
+ description: "Linked pull requests (oldest first)"
1262
+ });
1263
+ var zLinkTaskPullRequestBody = z.object({
1264
+ url: z.string().check(z.minLength(1)).register(z.globalRegistry, {
1265
+ description: "The pull request: `https://github.com/owner/repo/pull/123` or `owner/repo#123`."
1266
+ })
1267
+ });
1268
+ var zLinkTaskPullRequestPath = z.object({
1269
+ id: z.string().check(z.regex(/^[0-9a-fA-F]{3,32}$|^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/))
1270
+ });
1271
+ var zLinkTaskPullRequestResponse = zPullRequest;
1272
+ var zUnlinkTaskPullRequestPath = z.object({
1273
+ id: z.string().check(z.regex(/^[0-9a-fA-F]{3,32}$|^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/)),
1274
+ prId: z.uuid().register(z.globalRegistry, {
1275
+ description: "The link id (`id` from the pull request list)."
1276
+ })
1277
+ });
1278
+ var zUnlinkTaskPullRequestResponse = z.void().register(z.globalRegistry, {
1279
+ description: "Unlinked"
1280
+ });
1044
1281
 
1045
1282
  // src/index.ts
1046
1283
  var PerspecTask = class {
@@ -1050,14 +1287,20 @@ var PerspecTask = class {
1050
1287
  */
1051
1288
  tasks;
1052
1289
  constructor(options) {
1290
+ const { apiKey } = options;
1053
1291
  const client2 = createClient(
1054
1292
  createConfig({
1055
- baseUrl: options.baseUrl ?? "https://api.perspectask.com/v1",
1056
- headers: {
1057
- Authorization: `Bearer ${options.apiKey}`
1058
- }
1293
+ baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,
1294
+ ...options.fetch ? { fetch: options.fetch } : {},
1295
+ ...typeof apiKey === "string" ? { headers: { Authorization: `Bearer ${apiKey}` } } : {}
1059
1296
  })
1060
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
+ }
1061
1304
  this.tasks = createTasksNamespace(client2);
1062
1305
  }
1063
1306
  };
@@ -1070,22 +1313,51 @@ function createTasksNamespace(client2) {
1070
1313
  /** Create a task (`title` required). Wraps `Tasks.createTask`. */
1071
1314
  create: (body) => Tasks.createTask({ client: client2, body }),
1072
1315
  /** Update editable fields on a task by id. Wraps `Tasks.updateTask`. */
1073
- update: (id, body) => Tasks.updateTask({ client: client2, path: { id }, body })
1316
+ update: (id, body) => Tasks.updateTask({ client: client2, path: { id }, body }),
1317
+ /**
1318
+ * GitHub pull requests linked to a task. Usually you don't need these: put
1319
+ * the task's `pr_token` (e.g. `pt-a3f91c2`, on `tasks.get`) in a PR title
1320
+ * or branch name and the PR links itself.
1321
+ */
1322
+ pullRequests: {
1323
+ /** List the task's linked PRs (state, checks, review, preview). Wraps `PullRequests.listTaskPullRequests`. */
1324
+ list: (id) => PullRequests.listTaskPullRequests({ client: client2, path: { id } }),
1325
+ /** Link a PR by URL (`https://github.com/o/r/pull/12` or `o/r#12`). Wraps `PullRequests.linkTaskPullRequest`. */
1326
+ link: (id, url) => PullRequests.linkTaskPullRequest({ client: client2, path: { id }, body: { url } }),
1327
+ /** Unlink by the link `id` from `list`. Wraps `PullRequests.unlinkTaskPullRequest`. */
1328
+ unlink: (id, prId) => PullRequests.unlinkTaskPullRequest({ client: client2, path: { id, prId } })
1329
+ }
1074
1330
  };
1075
1331
  }
1076
1332
  var index_default = PerspecTask;
1077
1333
  // Annotate the CommonJS export names for ESM import in node:
1078
1334
  0 && (module.exports = {
1335
+ CLI_CLIENT_ID,
1336
+ DEFAULT_BASE_URL,
1337
+ OAuthTokenError,
1079
1338
  PerspecTask,
1339
+ PullRequests,
1080
1340
  Tasks,
1341
+ refreshTokens,
1342
+ revokeTokens,
1343
+ startDeviceLogin,
1344
+ waitForDeviceLogin,
1081
1345
  zCreateTaskBody,
1082
1346
  zCreateTaskResponse,
1083
1347
  zGetTaskPath,
1084
1348
  zGetTaskQuery,
1085
1349
  zGetTaskResponse,
1350
+ zLinkTaskPullRequestBody,
1351
+ zLinkTaskPullRequestPath,
1352
+ zLinkTaskPullRequestResponse,
1353
+ zListTaskPullRequestsPath,
1354
+ zListTaskPullRequestsResponse,
1086
1355
  zListTasksQuery,
1087
1356
  zListTasksResponse,
1357
+ zPullRequest,
1088
1358
  zTask,
1359
+ zUnlinkTaskPullRequestPath,
1360
+ zUnlinkTaskPullRequestResponse,
1089
1361
  zUpdateTaskBody,
1090
1362
  zUpdateTaskPath,
1091
1363
  zUpdateTaskResponse