pingcode-cli-unofficial 2.1.0 → 2.3.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.
@@ -3359,6 +3359,7 @@ function errorPayload(error) {
3359
3359
  const message = error instanceof Error ? error.message : String(error);
3360
3360
  const payload = { kind, message: redactSnippet(redactUrl(message)), exit };
3361
3361
  if (error instanceof PingcodeError && error.code !== void 0) payload.code = error.code;
3362
+ if (error instanceof PingcodeError && error.hint !== void 0) payload.hint = error.hint;
3362
3363
  return payload;
3363
3364
  }
3364
3365
  function printError(error, mode) {
@@ -3425,7 +3426,7 @@ var VERSION;
3425
3426
  var init_version = __esm({
3426
3427
  "src/version.ts"() {
3427
3428
  "use strict";
3428
- VERSION = "2.1.0";
3429
+ VERSION = "2.3.0";
3429
3430
  }
3430
3431
  });
3431
3432
 
@@ -3610,12 +3611,33 @@ function coerceConfig(raw) {
3610
3611
  if (token !== void 0) config.token = token;
3611
3612
  const userToken = coerceUserToken(record.userToken);
3612
3613
  if (userToken !== void 0) config.userToken = userToken;
3614
+ const patToken = coercePatToken(record.patToken);
3615
+ if (patToken !== void 0) config.patToken = patToken;
3613
3616
  const authMode = asAuthMode(record.authMode);
3614
3617
  if (authMode !== void 0) config.authMode = authMode;
3615
3618
  return config;
3616
3619
  }
3617
3620
  function asAuthMode(raw) {
3618
- return raw === "enterprise" || raw === "user" ? raw : void 0;
3621
+ return raw === "enterprise" || raw === "user" || raw === "pat" ? raw : void 0;
3622
+ }
3623
+ function normalizeToken(raw) {
3624
+ return raw.trim().replace(/^Bearer\s+/i, "").trim();
3625
+ }
3626
+ function coercePatToken(raw) {
3627
+ if (typeof raw !== "object" || raw === null) return void 0;
3628
+ const record = raw;
3629
+ if (asAuthMode(record.kind) !== "pat") return void 0;
3630
+ const base = coerceTokenBase(record);
3631
+ if (base === void 0) return void 0;
3632
+ const token = {
3633
+ ...base,
3634
+ accessToken: normalizeToken(base.accessToken),
3635
+ kind: "pat",
3636
+ unrefreshable: true
3637
+ };
3638
+ const scope = asString(record.scope);
3639
+ if (scope !== void 0) token.scope = scope;
3640
+ return token;
3619
3641
  }
3620
3642
  function coerceUserToken(raw) {
3621
3643
  if (typeof raw !== "object" || raw === null) return void 0;
@@ -3672,8 +3694,32 @@ function resolveSettings(input) {
3672
3694
  readEnv(env, ENV_USER_CLIENT_SECRET),
3673
3695
  file.userClientSecret
3674
3696
  ).value;
3675
- const authMode = inferAuthMode(file);
3676
- const activeToken = authMode === "user" ? file.userToken : file.token;
3697
+ const envTokenRaw = readEnv(env, ENV_TOKEN);
3698
+ const envToken = envTokenRaw === void 0 ? void 0 : normalizeToken(envTokenRaw);
3699
+ const authMode = envToken !== void 0 ? "pat" : inferAuthMode(file);
3700
+ let activeToken;
3701
+ let tokenSource;
3702
+ const envPatToken = envToken === void 0 ? void 0 : {
3703
+ accessToken: envToken,
3704
+ expiresAtMs: 0,
3705
+ obtainedAtMs: 0,
3706
+ kind: "pat",
3707
+ unrefreshable: true
3708
+ };
3709
+ if (envPatToken !== void 0) {
3710
+ activeToken = envPatToken;
3711
+ tokenSource = "env";
3712
+ } else if (authMode === "pat") {
3713
+ activeToken = file.patToken;
3714
+ tokenSource = activeToken === void 0 ? "none" : "file";
3715
+ } else if (authMode === "user") {
3716
+ activeToken = file.userToken;
3717
+ tokenSource = activeToken === void 0 ? "none" : "file";
3718
+ } else {
3719
+ activeToken = file.token;
3720
+ tokenSource = activeToken === void 0 ? "none" : "file";
3721
+ }
3722
+ const tokenRefreshable = activeToken !== void 0 && activeToken.unrefreshable !== true && activeToken.kind !== "pat" && authMode !== "pat";
3677
3723
  return {
3678
3724
  host,
3679
3725
  apiBase,
@@ -3682,6 +3728,9 @@ function resolveSettings(input) {
3682
3728
  userClientId,
3683
3729
  userClientSecret,
3684
3730
  token: activeToken,
3731
+ patToken: envPatToken ?? file.patToken,
3732
+ tokenSource,
3733
+ tokenRefreshable,
3685
3734
  authMode,
3686
3735
  sources: {
3687
3736
  host: hostSource,
@@ -3693,6 +3742,7 @@ function resolveSettings(input) {
3693
3742
  }
3694
3743
  function inferAuthMode(file) {
3695
3744
  if (file.authMode !== void 0) return file.authMode;
3745
+ if (file.patToken !== void 0) return "pat";
3696
3746
  if (file.userToken !== void 0) return "user";
3697
3747
  if (file.token !== void 0) return "enterprise";
3698
3748
  return "user";
@@ -3731,7 +3781,7 @@ function isNotFound(error) {
3731
3781
  function errorMessage(error) {
3732
3782
  return error instanceof Error ? error.message : String(error);
3733
3783
  }
3734
- var DEFAULT_HOST, CONFIG_DIR_MODE, CONFIG_FILE_MODE, ENV_CONFIG_DIR, ENV_HOST, ENV_CLIENT_ID, ENV_CLIENT_SECRET, ENV_USER_CLIENT_ID, ENV_USER_CLIENT_SECRET;
3784
+ var DEFAULT_HOST, CONFIG_DIR_MODE, CONFIG_FILE_MODE, ENV_CONFIG_DIR, ENV_HOST, ENV_CLIENT_ID, ENV_CLIENT_SECRET, ENV_USER_CLIENT_ID, ENV_USER_CLIENT_SECRET, ENV_TOKEN;
3735
3785
  var init_config = __esm({
3736
3786
  "src/core/config.ts"() {
3737
3787
  "use strict";
@@ -3746,6 +3796,7 @@ var init_config = __esm({
3746
3796
  ENV_CLIENT_SECRET = "PINGCODE_CLIENT_SECRET";
3747
3797
  ENV_USER_CLIENT_ID = "PINGCODE_USER_CLIENT_ID";
3748
3798
  ENV_USER_CLIENT_SECRET = "PINGCODE_USER_CLIENT_SECRET";
3799
+ ENV_TOKEN = "PINGCODE_TOKEN";
3749
3800
  }
3750
3801
  });
3751
3802
 
@@ -3827,10 +3878,10 @@ function buildContext(input) {
3827
3878
  const override = input.credentials;
3828
3879
  const activeClientId = mode === "user" ? override?.clientId ?? settings2.userClientId ?? settings2.clientId : override?.clientId ?? settings2.clientId;
3829
3880
  const activeClientSecret = mode === "user" ? override?.clientSecret ?? settings2.userClientSecret ?? settings2.clientSecret : override?.clientSecret ?? settings2.clientSecret;
3830
- const activeToken = mode === "user" ? file.userToken : file.token;
3881
+ const activeToken = mode === "pat" ? settings2.patToken : mode === "user" ? file.userToken : file.token;
3831
3882
  const ctx = createContext({
3832
3883
  apiBase: settings2.apiBase,
3833
- credentials: { clientId: activeClientId, clientSecret: activeClientSecret },
3884
+ credentials: mode === "pat" ? {} : { clientId: activeClientId, clientSecret: activeClientSecret },
3834
3885
  auth: {
3835
3886
  token: activeToken,
3836
3887
  clampWarned: false,
@@ -3844,7 +3895,8 @@ function buildContext(input) {
3844
3895
  env,
3845
3896
  // Mode-aware persist (D5): route by the token's kind to the right slot and
3846
3897
  // stamp the active mode. saveConfig re-reads + merges, so this writes only
3847
- // the owned field (never a whole stale Config).
3898
+ // the owned field (never a whole stale Config). A PAT is never refreshed, so
3899
+ // this only ever fires from `auth login --mode pat`.
3848
3900
  persistToken: (token) => {
3849
3901
  if (token.kind === "user") {
3850
3902
  saveConfig(
@@ -3854,6 +3906,8 @@ function buildContext(input) {
3854
3906
  },
3855
3907
  env
3856
3908
  );
3909
+ } else if (token.kind === "pat") {
3910
+ saveConfig({ patToken: { ...token, kind: "pat", unrefreshable: true }, authMode: "pat" }, env);
3857
3911
  } else {
3858
3912
  saveConfig({ token, authMode: "enterprise" }, env);
3859
3913
  }
@@ -5107,8 +5161,37 @@ async function refreshUserToken(ctx, refreshToken) {
5107
5161
  ctx.persistToken?.(token);
5108
5162
  return token;
5109
5163
  }
5164
+ function setPersonalAccessToken(ctx, raw, options = {}) {
5165
+ const accessToken = normalizeToken(raw);
5166
+ if (accessToken === "") {
5167
+ throw new AuthError("the personal access token is empty", { hint: PAT_HINT });
5168
+ }
5169
+ const now = ctx.now();
5170
+ const token = {
5171
+ accessToken,
5172
+ expiresAtMs: 0,
5173
+ obtainedAtMs: now,
5174
+ kind: "pat",
5175
+ unrefreshable: true
5176
+ };
5177
+ ctx.auth.token = token;
5178
+ ctx.auth.mode = "pat";
5179
+ if (options.persist !== false) ctx.persistToken?.(token);
5180
+ return token;
5181
+ }
5182
+ function personalAccessToken(ctx, force) {
5183
+ const accessToken = ctx.auth.token?.accessToken ?? "";
5184
+ if (accessToken === "") {
5185
+ throw new AuthError("no personal access token configured", { hint: PAT_HINT });
5186
+ }
5187
+ if (force) {
5188
+ throw new AuthError("PingCode rejected the personal access token (401)", { hint: PAT_HINT });
5189
+ }
5190
+ return accessToken;
5191
+ }
5110
5192
  async function ensureFreshToken(ctx, options = {}) {
5111
5193
  const force = options.force === true;
5194
+ if (ctx.auth.mode === "pat") return personalAccessToken(ctx, force);
5112
5195
  if (force) {
5113
5196
  ctx.auth.inflight = void 0;
5114
5197
  if (ctx.auth.mode !== "user") ctx.auth.token = void 0;
@@ -5123,6 +5206,11 @@ async function ensureFreshToken(ctx, options = {}) {
5123
5206
  return token.accessToken;
5124
5207
  }
5125
5208
  async function acquireForMode(ctx) {
5209
+ if (ctx.auth.mode === "pat") {
5210
+ throw new AuthError("a personal access token cannot be acquired or refreshed", {
5211
+ hint: PAT_HINT
5212
+ });
5213
+ }
5126
5214
  if (ctx.auth.mode === "user") {
5127
5215
  const refreshToken = ctx.auth.token?.refreshToken;
5128
5216
  if (refreshToken === void 0) {
@@ -5142,16 +5230,18 @@ function clearToken(ctx) {
5142
5230
  ctx.auth.token = void 0;
5143
5231
  ctx.auth.inflight = void 0;
5144
5232
  }
5145
- var THIRTY_DAYS_MS, REFRESH_WINDOW_MS, TOKEN_PATH;
5233
+ var THIRTY_DAYS_MS, REFRESH_WINDOW_MS, TOKEN_PATH, PAT_HINT;
5146
5234
  var init_auth = __esm({
5147
5235
  "src/core/auth.ts"() {
5148
5236
  "use strict";
5237
+ init_config();
5149
5238
  init_errors();
5150
5239
  init_redact();
5151
5240
  init_wire();
5152
5241
  THIRTY_DAYS_MS = 30 * 24 * 3600 * 1e3;
5153
5242
  REFRESH_WINDOW_MS = 12e4;
5154
5243
  TOKEN_PATH = "/v1/auth/token";
5244
+ PAT_HINT = "personal access tokens cannot be renewed by this CLI: check that it is not expired or revoked, that its scopes cover this endpoint, or create a new token in PingCode personal settings and run `pingcode auth login --mode pat --token <token>` (or set PINGCODE_TOKEN)";
5155
5245
  }
5156
5246
  });
5157
5247
 
@@ -8014,11 +8104,11 @@ function isPlaceholder2(segment) {
8014
8104
  }
8015
8105
  function refuseUserTokenEndpoint(ctx, candidates) {
8016
8106
  if (!candidates.every((entry2) => entry2.tokenType === "USER")) return;
8017
- if (ctx.auth.mode === "user") return;
8107
+ if (ctx.auth.mode === "user" || ctx.auth.mode === "pat") return;
8018
8108
  const entry = candidates[0];
8019
8109
  if (entry === void 0) return;
8020
8110
  throw new UsageError(
8021
- `${entry.method} ${entry.path} requires a \u7528\u6237\u4EE4\u724C (user token), but the active token is an \u4F01\u4E1A\u4EE4\u724C (enterprise) \u2014 run \`pingcode auth login --mode user\` to hold a user token`,
8111
+ `${entry.method} ${entry.path} requires a \u7528\u6237\u4EE4\u724C (user token), but the active token is an \u4F01\u4E1A\u4EE4\u724C (enterprise) \u2014 run \`pingcode auth login --mode user\`, or use a personal access token with --mode pat / PINGCODE_TOKEN`,
8022
8112
  {
8023
8113
  hint: "seven endpoints are user-token-only \u2014 /v1/myself, /v1/permission/my/* and /v1/permission/check/*. GET /v1/permission/points does work with the enterprise token. " + AUTHORIZE_HINT
8024
8114
  }
@@ -8476,6 +8566,7 @@ function parseWorkItem(raw) {
8476
8566
  if (single !== void 0) versions = [single];
8477
8567
  }
8478
8568
  const properties = typeof record.properties === "object" && record.properties !== null && !Array.isArray(record.properties) ? record.properties : void 0;
8569
+ const sprint = parseRef(record.sprint);
8479
8570
  return {
8480
8571
  ...record,
8481
8572
  id: asString2(record.id) ?? "",
@@ -8486,12 +8577,12 @@ function parseWorkItem(raw) {
8486
8577
  title: asString2(record.title),
8487
8578
  description: asString2(record.description),
8488
8579
  type: parseWorkItemTypeField(record.type),
8489
- state: parseRef(record.state),
8580
+ state: parseWorkItemStateField(record.state),
8490
8581
  priority: parseRef(record.priority),
8491
8582
  assignee: parseRef(record.assignee),
8492
8583
  project: parseRef(record.project),
8493
8584
  parent: parseRef(record.parent),
8494
- sprint: parseRef(record.sprint),
8585
+ sprint,
8495
8586
  board: parseRef(record.board),
8496
8587
  entry: parseRef(record.entry),
8497
8588
  swimlane: parseRef(record.swimlane),
@@ -8511,7 +8602,8 @@ function parseWorkItem(raw) {
8511
8602
  remaining_workload: asNumber(record.remaining_workload),
8512
8603
  properties,
8513
8604
  is_archived: asBooleanFlag(record.is_archived),
8514
- is_deleted: asBooleanFlag(record.is_deleted)
8605
+ is_deleted: asBooleanFlag(record.is_deleted),
8606
+ sprint_id: asString2(record.sprint_id) ?? sprint?.id
8515
8607
  };
8516
8608
  }
8517
8609
  function parseWorkItemType(raw) {
@@ -8527,6 +8619,10 @@ function parseWorkItemTypeField(raw) {
8527
8619
  if (typeof raw === "string" && raw !== "") return raw;
8528
8620
  return parseRef(raw);
8529
8621
  }
8622
+ function parseWorkItemStateField(raw) {
8623
+ if (typeof raw === "string" && raw !== "") return raw;
8624
+ return parseRef(raw);
8625
+ }
8530
8626
  function parseWorkItemState(raw) {
8531
8627
  const record = asRecord(raw);
8532
8628
  return {
@@ -9897,12 +9993,15 @@ var init_oauth = __esm({
9897
9993
  // src/cli/commands/auth.ts
9898
9994
  import { createInterface } from "readline/promises";
9899
9995
  function registerAuthCommands(program2) {
9900
- const auth = program2.command("auth").description("authenticate against PingCode (enterprise app or user token)");
9996
+ const auth = program2.command("auth").description("authenticate against PingCode (enterprise app, user token or personal access token)");
9901
9997
  addGlobalOptions(
9902
9998
  auth.command("login").description("acquire a token (user token by default) and verify it").option("--client-id <id>", "app client id (or PINGCODE_CLIENT_ID)").option("--client-secret <secret>", "app client secret (or PINGCODE_CLIENT_SECRET)").option("--save", "also store the client id/secret in the config file (mode 0600)").option(
9903
9999
  "--mode <mode>",
9904
- "auth mode: user (authorization_code, default) or enterprise (client_credentials)"
9905
- ).option("--code <code>", "authorization code (skips the interactive paste)"),
10000
+ "auth mode: user (authorization_code, default), enterprise (client_credentials) or pat (personal access token)"
10001
+ ).option("--code <code>", "authorization code (skips the interactive paste)").option(
10002
+ "--token <token>",
10003
+ "personal access token for --mode pat (or PINGCODE_TOKEN; skips the hidden prompt)"
10004
+ ),
9906
10005
  { hidden: true }
9907
10006
  ).action(async (flags, command) => {
9908
10007
  await runLogin(flags, command);
@@ -9914,7 +10013,7 @@ function registerAuthCommands(program2) {
9914
10013
  await runStatus(flags, command);
9915
10014
  });
9916
10015
  addGlobalOptions(
9917
- auth.command("logout").description("clear the active token slot (both with --all) and the metadata cache").option("--all", "clear both the enterprise and user token slots (and authMode)"),
10016
+ auth.command("logout").description("clear the active token slot (all three with --all) and the metadata cache").option("--all", "clear the enterprise, user and personal-token slots (and authMode)"),
9918
10017
  { hidden: true }
9919
10018
  ).action((flags, command) => {
9920
10019
  runLogout(flags, command);
@@ -9923,6 +10022,10 @@ function registerAuthCommands(program2) {
9923
10022
  async function runLogin(flags, command) {
9924
10023
  const probe = contextFor(command);
9925
10024
  const authMode = await resolveMode(flags.mode, probe.ctx.json);
10025
+ if (authMode === "pat") {
10026
+ await runLoginPat(flags, command);
10027
+ return;
10028
+ }
9926
10029
  let built = contextFor(
9927
10030
  command,
9928
10031
  { clientId: flags.clientId, clientSecret: flags.clientSecret },
@@ -9976,12 +10079,52 @@ async function runLogin(flags, command) {
9976
10079
  clearMetadataCache(ctx);
9977
10080
  finishLogin(built, flags, { authMode, tokenKind, user, verifiedWith, token });
9978
10081
  }
10082
+ async function runLoginPat(flags, command) {
10083
+ const built = contextFor(command, void 0, "pat");
10084
+ const { ctx, settings: settings2 } = built;
10085
+ const stored = ctx.auth.token?.accessToken;
10086
+ const provided = flags.token !== void 0 && flags.token !== "" ? flags.token : void 0;
10087
+ const source = provided !== void 0 ? "flag" : stored === void 0 ? "prompt" : settings2.tokenSource === "env" ? "env" : "file";
10088
+ const raw = provided ?? stored ?? await loginHooks.readToken(ctx.json);
10089
+ clearToken(ctx);
10090
+ const token = setPersonalAccessToken(ctx, raw, { persist: false });
10091
+ const verified = await verifyPatToken(ctx);
10092
+ ctx.persistToken?.(token);
10093
+ clearMetadataCache(ctx);
10094
+ finishLogin(built, flags, {
10095
+ authMode: "pat",
10096
+ tokenKind: "pat",
10097
+ tokenSource: source,
10098
+ token,
10099
+ ...verified
10100
+ });
10101
+ }
10102
+ async function verifyPatToken(ctx) {
10103
+ try {
10104
+ const me = await getMyself(ctx);
10105
+ const user = { id: me.id };
10106
+ if (me.name !== void 0) user.name = me.name;
10107
+ if (me.display_name !== void 0) user.display_name = me.display_name;
10108
+ if (me.username !== void 0) user.username = me.username;
10109
+ return { verifiedWith: "GET /v1/myself", user };
10110
+ } catch (error) {
10111
+ if (!(error instanceof PermissionError)) throw error;
10112
+ }
10113
+ try {
10114
+ const projectsTotal = await verifyAccess(ctx);
10115
+ return { verifiedWith: "GET /v1/pjm/projects?page_size=1", projectsTotal };
10116
+ } catch (error) {
10117
+ if (!(error instanceof PermissionError)) throw error;
10118
+ return {};
10119
+ }
10120
+ }
9979
10121
  function finishLogin(built, flags, outcome) {
9980
10122
  const { settings: settings2, file } = built;
9981
10123
  const save = flags.save === true;
9982
10124
  const patch = { host: settings2.host };
9983
10125
  let storeId = false;
9984
10126
  let storeSecret = false;
10127
+ const isPat = outcome.authMode === "pat";
9985
10128
  if (outcome.authMode === "user") {
9986
10129
  const userId = flags.clientId ?? settings2.userClientId;
9987
10130
  if (userId !== void 0) {
@@ -10001,16 +10144,25 @@ function finishLogin(built, flags, outcome) {
10001
10144
  storeSecret = true;
10002
10145
  }
10003
10146
  }
10004
- } else {
10147
+ } else if (!isPat) {
10005
10148
  storeId = shouldPersistSecret(settings2.sources.clientId, save);
10006
10149
  storeSecret = shouldPersistSecret(settings2.sources.clientSecret, save);
10007
10150
  if (storeId) patch.clientId = settings2.clientId;
10008
10151
  if (storeSecret) patch.clientSecret = settings2.clientSecret;
10009
10152
  }
10010
10153
  saveConfig(patch, process.env);
10011
- const alreadyInFile = outcome.authMode === "user" ? file.userClientId !== void 0 && file.userClientSecret !== void 0 : file.clientId !== void 0 && file.clientSecret !== void 0;
10154
+ const alreadyInFile = isPat ? true : outcome.authMode === "user" ? file.userClientId !== void 0 && file.userClientSecret !== void 0 : file.clientId !== void 0 && file.clientSecret !== void 0;
10012
10155
  const credentialsStored = alreadyInFile || storeId && storeSecret;
10013
10156
  const mode = modeOf(built.ctx);
10157
+ const effectiveSource = isPat ? outcome.tokenSource ?? "none" : "file";
10158
+ const refreshable = !isPat;
10159
+ if (isPat && outcome.verifiedWith === void 0) {
10160
+ errLine(
10161
+ paint.yellow(
10162
+ "stored, but no granted scope allowed a live check \u2014 a 401 will still fail hard, and `auth status --check` will tell you when that happens"
10163
+ )
10164
+ );
10165
+ }
10014
10166
  if (mode.json) {
10015
10167
  printJson({
10016
10168
  ok: true,
@@ -10018,33 +10170,42 @@ function finishLogin(built, flags, outcome) {
10018
10170
  kind: outcome.tokenKind,
10019
10171
  host: settings2.host,
10020
10172
  api_base: settings2.apiBase,
10021
- client_id: maskIdentifier(settings2.clientId),
10022
- credentials_stored: credentialsStored,
10173
+ client_id: isPat ? null : maskIdentifier(settings2.clientId),
10174
+ credentials_stored: isPat ? false : credentialsStored,
10023
10175
  ...outcome.user === void 0 ? {} : { user: outcome.user },
10024
10176
  ...outcome.projectsTotal === void 0 ? {} : { projects_total: outcome.projectsTotal },
10025
- token_expires_at: Math.floor(outcome.token.expiresAtMs / 1e3),
10026
- verified_with: outcome.verifiedWith
10177
+ // A PAT's validity is set in PingCode and unknown to us — never invent one.
10178
+ token_expires_at: isPat ? null : Math.floor(outcome.token.expiresAtMs / 1e3),
10179
+ token_source: effectiveSource,
10180
+ token_refreshable: refreshable,
10181
+ verified_with: outcome.verifiedWith ?? null
10027
10182
  });
10028
10183
  return;
10029
10184
  }
10030
10185
  const fields = [
10031
10186
  ["host", settings2.host],
10032
- ["api base", settings2.apiBase],
10033
- ["client id", maskIdentifier(settings2.clientId)],
10034
- ["mode", outcome.authMode],
10035
- ["token kind", outcome.tokenKind]
10187
+ ["api base", settings2.apiBase]
10036
10188
  ];
10189
+ if (isPat) {
10190
+ fields.push(["token source", effectiveSource]);
10191
+ } else {
10192
+ fields.push(["client id", maskIdentifier(settings2.clientId)]);
10193
+ }
10194
+ fields.push(["mode", outcome.authMode], ["token kind", outcome.tokenKind]);
10037
10195
  if (outcome.user !== void 0) {
10038
10196
  fields.push(["user", outcome.user.display_name ?? outcome.user.name ?? outcome.user.username ?? outcome.user.id]);
10039
10197
  }
10040
10198
  if (outcome.projectsTotal !== void 0) {
10041
10199
  fields.push(["projects visible", String(outcome.projectsTotal)]);
10042
10200
  }
10043
- fields.push(["token expires", formatTimestamp(Math.floor(outcome.token.expiresAtMs / 1e3))]);
10201
+ fields.push([
10202
+ "token expires",
10203
+ isPat ? "unknown \u2014 set by the token in PingCode personal settings" : formatTimestamp(Math.floor(outcome.token.expiresAtMs / 1e3))
10204
+ ]);
10044
10205
  fields.push(["config file", configFilePath(process.env)]);
10045
10206
  printFields(fields);
10046
- errLine(paint.green("authenticated"));
10047
- if (!credentialsStored) {
10207
+ errLine(paint.green(outcome.verifiedWith === void 0 ? "token stored" : "authenticated"));
10208
+ if (!isPat && !credentialsStored) {
10048
10209
  errLine(
10049
10210
  paint.dim(
10050
10211
  "the client id/secret were not written to disk (pass --save to store them); the token was stored, but a re-login will be needed once it expires"
@@ -10053,9 +10214,9 @@ function finishLogin(built, flags, outcome) {
10053
10214
  }
10054
10215
  }
10055
10216
  async function resolveMode(flag, json) {
10056
- if (flag === "enterprise" || flag === "user") return flag;
10217
+ if (flag === "enterprise" || flag === "user" || flag === "pat") return flag;
10057
10218
  if (flag !== void 0) {
10058
- throw new UsageError(`--mode must be "enterprise" or "user", got "${flag}"`);
10219
+ throw new UsageError(`--mode must be "enterprise", "user" or "pat", got "${flag}"`);
10059
10220
  }
10060
10221
  return await loginHooks.selectMode(json);
10061
10222
  }
@@ -10069,12 +10230,13 @@ async function runStatus(flags, command) {
10069
10230
  const { ctx, settings: settings2, file } = contextFor(command);
10070
10231
  const mode = modeOf(ctx);
10071
10232
  const token = settings2.token;
10072
- const expiresAt = token === void 0 ? void 0 : Math.floor(token.expiresAtMs / 1e3);
10233
+ const expiresAt = token === void 0 || !settings2.tokenRefreshable ? void 0 : Math.floor(token.expiresAtMs / 1e3);
10073
10234
  const authMode = settings2.authMode;
10074
- const tokenKind = token?.kind ?? "enterprise";
10235
+ const tokenKind = token?.kind ?? (authMode === "pat" ? "pat" : "enterprise");
10236
+ const fresh = settings2.tokenRefreshable ? tokenIsFresh(token, ctx.now()) : null;
10075
10237
  let check;
10076
10238
  if (flags.check === true) {
10077
- if (authMode === "user") {
10239
+ if (authMode === "user" || authMode === "pat") {
10078
10240
  const me = await getMyself(ctx);
10079
10241
  check = { ok: true, endpoint: "GET /v1/myself", user: me.display_name ?? me.name ?? me.username ?? me.id };
10080
10242
  } else {
@@ -10095,39 +10257,57 @@ async function runStatus(flags, command) {
10095
10257
  credentials_stored: file.clientId !== void 0 && file.clientSecret !== void 0,
10096
10258
  token_present: token !== void 0,
10097
10259
  token_kind: tokenKind,
10098
- token_fresh: tokenIsFresh(token, ctx.now()),
10260
+ token_source: settings2.tokenSource,
10261
+ token_refreshable: settings2.tokenRefreshable,
10262
+ token_fresh: fresh,
10099
10263
  token_expires_at: expiresAt ?? null,
10100
10264
  token_scope: token?.scope ?? null,
10101
10265
  // User-slot refresh-token presence (AC8) — boolean only, never the value.
10102
10266
  user_token_present: file.userToken !== void 0,
10103
10267
  user_refresh_token_present: file.userToken?.refreshToken !== void 0,
10268
+ // Personal-token slot presence — boolean only, never the value.
10269
+ pat_token_present: file.patToken !== void 0,
10270
+ env_token_present: settings2.tokenSource === "env" && authMode === "pat",
10104
10271
  config_file: configFilePath(process.env),
10105
10272
  ...check === void 0 ? {} : { check }
10106
10273
  });
10107
10274
  return;
10108
10275
  }
10109
- printFields([
10276
+ const fields = [
10110
10277
  ["host", settings2.host],
10111
- ["api base", settings2.apiBase],
10112
- ["client id", `${maskIdentifier(settings2.clientId)} (${settings2.sources.clientId})`],
10113
- [
10114
- "client secret",
10115
- settings2.clientSecret === void 0 ? "(not set)" : `(set, ${settings2.sources.clientSecret})`
10116
- ],
10278
+ ["api base", settings2.apiBase]
10279
+ ];
10280
+ if (authMode === "pat") {
10281
+ fields.push(["token source", settings2.tokenSource]);
10282
+ } else {
10283
+ fields.push(
10284
+ ["client id", `${maskIdentifier(settings2.clientId)} (${settings2.sources.clientId})`],
10285
+ [
10286
+ "client secret",
10287
+ settings2.clientSecret === void 0 ? "(not set)" : `(set, ${settings2.sources.clientSecret})`
10288
+ ]
10289
+ );
10290
+ }
10291
+ fields.push(
10117
10292
  ["auth mode", authMode],
10118
10293
  [
10119
10294
  "token",
10120
- token === void 0 ? "(none) \u2014 run `pingcode auth login`" : tokenIsFresh(token, ctx.now()) ? `present (${tokenKind})` : `present but stale (${tokenKind}) \u2014 it will be re-acquired on the next call`
10295
+ token === void 0 ? "(none) \u2014 run `pingcode auth login`" : fresh === null ? `present (${tokenKind}; not refreshable)` : fresh ? `present (${tokenKind})` : `present but stale (${tokenKind}) \u2014 it will be re-acquired on the next call`
10296
+ ],
10297
+ [
10298
+ "token expires",
10299
+ expiresAt === void 0 ? authMode === "pat" && token !== void 0 ? "unknown \u2014 set by the token in PingCode personal settings" : "" : formatTimestamp(expiresAt)
10121
10300
  ],
10122
- ["token expires", expiresAt === void 0 ? "" : formatTimestamp(expiresAt)],
10123
10301
  ["token scope", token?.scope ?? ""],
10124
10302
  ["user slot", file.userToken === void 0 ? "(none)" : "present (with refresh token)"],
10303
+ ["personal token slot", file.patToken === void 0 ? "(none)" : "present (not refreshable)"],
10125
10304
  ["config file", configFilePath(process.env)],
10126
10305
  [
10127
10306
  "live check",
10128
10307
  check === void 0 ? "(skipped \u2014 pass --check)" : check.endpoint === "GET /v1/myself" ? `ok \xB7 signed in as ${check.user} via ${check.endpoint}` : `ok \xB7 ${check.projects_total} project(s) visible via ${check.endpoint}`
10129
10308
  ]
10130
- ]);
10309
+ );
10310
+ printFields(fields);
10131
10311
  }
10132
10312
  function runLogout(flags, command) {
10133
10313
  const { ctx, settings: settings2 } = contextFor(command);
@@ -10136,14 +10316,38 @@ function runLogout(flags, command) {
10136
10316
  let cleared;
10137
10317
  if (all) {
10138
10318
  saveConfig(
10139
- { host: settings2.host, token: null, userToken: null, authMode: null, clientId: null, clientSecret: null },
10319
+ {
10320
+ host: settings2.host,
10321
+ token: null,
10322
+ userToken: null,
10323
+ patToken: null,
10324
+ authMode: null,
10325
+ clientId: null,
10326
+ clientSecret: null,
10327
+ userClientId: null,
10328
+ userClientSecret: null
10329
+ },
10140
10330
  process.env
10141
10331
  );
10142
- cleared = ["token", "user_token", "auth_mode", "client_id", "client_secret", "metadata_cache"];
10332
+ cleared = [
10333
+ "token",
10334
+ "user_token",
10335
+ "pat_token",
10336
+ "auth_mode",
10337
+ "client_id",
10338
+ "client_secret",
10339
+ "user_client_id",
10340
+ "user_client_secret",
10341
+ "metadata_cache"
10342
+ ];
10143
10343
  } else {
10144
- const slot = settings2.authMode === "user" ? "userToken" : "token";
10344
+ const slot = settings2.authMode === "pat" ? "patToken" : settings2.authMode === "user" ? "userToken" : "token";
10145
10345
  saveConfig({ [slot]: null, authMode: null }, process.env);
10146
- cleared = [slot === "userToken" ? "user_token" : "token", "auth_mode", "metadata_cache"];
10346
+ cleared = [
10347
+ slot === "patToken" ? "pat_token" : slot === "userToken" ? "user_token" : "token",
10348
+ "auth_mode",
10349
+ "metadata_cache"
10350
+ ];
10147
10351
  }
10148
10352
  clearToken(ctx);
10149
10353
  clearMetadataCache(ctx);
@@ -10158,8 +10362,10 @@ function runLogout(flags, command) {
10158
10362
  errLine(`cleared ${cleared.join(", ")} (${configFilePath(process.env)})`);
10159
10363
  }
10160
10364
  function missingCredential(what) {
10365
+ const flag = what === "client id" ? "--client-id" : what === "personal access token" ? "--token" : "--client-secret";
10366
+ const env = what === "client id" ? "PINGCODE_CLIENT_ID" : what === "personal access token" ? "PINGCODE_TOKEN" : "PINGCODE_CLIENT_SECRET";
10161
10367
  return new UsageError(`no ${what} available`, {
10162
- hint: `pass --${what === "client id" ? "client-id" : "client-secret"}, set PINGCODE_${what === "client id" ? "CLIENT_ID" : "CLIENT_SECRET"}, or run the command from a terminal to be prompted`
10368
+ hint: `pass ${flag}, set ${env}, or run the command from a terminal to be prompted`
10163
10369
  });
10164
10370
  }
10165
10371
  async function promptVisible(question, json) {
@@ -10173,9 +10379,9 @@ async function promptVisible(question, json) {
10173
10379
  rl.close();
10174
10380
  }
10175
10381
  }
10176
- async function promptHidden(question, json) {
10382
+ async function promptHidden(question, json, what = "client secret") {
10177
10383
  const input = process.stdin;
10178
- if (json || input.isTTY !== true) throw missingCredential("client secret");
10384
+ if (json || input.isTTY !== true) throw missingCredential(what);
10179
10385
  process.stderr.write(question);
10180
10386
  input.setRawMode(true);
10181
10387
  input.resume();
@@ -10211,7 +10417,7 @@ async function promptHidden(question, json) {
10211
10417
  input.on("data", onData);
10212
10418
  });
10213
10419
  const trimmed = value.trim();
10214
- if (trimmed === "") throw missingCredential("client secret");
10420
+ if (trimmed === "") throw missingCredential(what);
10215
10421
  return trimmed;
10216
10422
  }
10217
10423
  async function readPasteFromTerminal(json) {
@@ -10227,6 +10433,12 @@ async function readPasteFromTerminal(json) {
10227
10433
  rl.close();
10228
10434
  }
10229
10435
  }
10436
+ async function readTokenFromTerminal(json) {
10437
+ if (json || process.stdin.isTTY !== true) throw missingCredential("personal access token");
10438
+ const token = await promptHidden("personal access token: ", json, "personal access token");
10439
+ if (token.trim() === "") throw missingCredential("personal access token");
10440
+ return token;
10441
+ }
10230
10442
  async function promptChoice(question, choices, defaultKey) {
10231
10443
  const rl = createInterface({ input: process.stdin, output: process.stderr });
10232
10444
  try {
@@ -10253,6 +10465,7 @@ async function defaultSelectMode(json) {
10253
10465
  if (json || process.stdin.isTTY !== true) return "user";
10254
10466
  return await promptChoice("auth mode", [
10255
10467
  { key: "user", label: "authorization_code \u2014 acts as you (default)" },
10468
+ { key: "pat", label: "personal access token \u2014 paste a token, no app needed" },
10256
10469
  { key: "enterprise", label: "client_credentials \u2014 app/admin identity" }
10257
10470
  ], "user");
10258
10471
  }
@@ -10273,7 +10486,8 @@ var init_auth2 = __esm({
10273
10486
  init_common();
10274
10487
  loginHooks = {
10275
10488
  selectMode: defaultSelectMode,
10276
- readPaste: readPasteFromTerminal
10489
+ readPaste: readPasteFromTerminal,
10490
+ readToken: readTokenFromTerminal
10277
10491
  };
10278
10492
  }
10279
10493
  });
@@ -11822,7 +12036,7 @@ function registerTicketCommands(parent) {
11822
12036
  await runGet3(target, command);
11823
12037
  });
11824
12038
  addGlobalOptions(
11825
- group2.command("create").description("create a ticket (--type is required by the API, unlike idea)").requiredOption("--product <name|id>", "product name, identifier or id").requiredOption("--type <name|id>", "ticket type \u2014 list them with `meta ticket-types`").requiredOption("--title <text>", "title, max 255 characters").option("--description <text>", "description").option("--assignee <name|id>", "assignee \u2014 must be a member of this product").option("--priority <name|id>", "priority").option("--channel <name|id>", "submission channel \u2014 can only be set here, never patched").option("--set <key=value>", SET_HELP2, collectValue),
12039
+ group2.command("create").description("create a ticket (--type is required by the API, unlike idea)").requiredOption("--product <name|id>", "product name, identifier or id").requiredOption("--type <name|id>", "ticket type \u2014 list them with `meta ticket-types`").requiredOption("--title <text>", "title, max 255 characters").option("--description <text>", "description").option("--assignee <name|id>", "assignee \u2014 must be a member of this product").option("--priority <name|id>", "priority").option("--channel <name|id>", 'submission channel \u2014 use "internal" for the web default (server-decided)').option("--customer <name|id>", "customer \u5BA2\u6237 \u2014 scoped to this product").option("--set <key=value>", SET_HELP2, collectValue),
11826
12040
  { hidden: true }
11827
12041
  ).action(async (flags, command) => {
11828
12042
  await runCreate3(flags, command);
@@ -11935,12 +12149,31 @@ async function runCreate3(flags, command) {
11935
12149
  const { ctx } = contextFor(command);
11936
12150
  const title = requireFlag(flags.title, "--title");
11937
12151
  const assignments = parseSetFlags(flags.set, SET_HINT3);
12152
+ let internalFallbackUsed = false;
11938
12153
  const resolve = async (attemptCtx) => {
11939
12154
  const product = await resolveProduct(attemptCtx, flags.product);
11940
12155
  const type = await resolveTicketType(attemptCtx, product.id, flags.type);
11941
12156
  const assignee = flags.assignee === void 0 ? void 0 : await resolveProductMember(attemptCtx, product.id, flags.assignee);
11942
12157
  const priority = flags.priority === void 0 ? void 0 : await resolveTicketPriority(attemptCtx, product.id, flags.priority);
11943
- const channel = flags.channel === void 0 ? void 0 : await resolveTicketChannel(attemptCtx, product.id, flags.channel);
12158
+ let channel;
12159
+ if (flags.channel !== void 0) {
12160
+ try {
12161
+ channel = await resolveTicketChannel(attemptCtx, product.id, flags.channel);
12162
+ } catch (raw) {
12163
+ const isInternal = raw instanceof UsageError && typeof flags.channel === "string" && flags.channel.trim().toLowerCase() === "internal";
12164
+ const noMatch = isInternal && raw.message.startsWith("no ticket channel matches");
12165
+ if (noMatch) {
12166
+ channel = void 0;
12167
+ if (!internalFallbackUsed) {
12168
+ internalFallbackUsed = true;
12169
+ errLine(paint.dim(`channel "internal" is the web default \u2014 letting the server decide`));
12170
+ }
12171
+ } else {
12172
+ throw raw;
12173
+ }
12174
+ }
12175
+ }
12176
+ const customer = flags.customer === void 0 ? void 0 : await resolveTicketCustomer(attemptCtx, product.id, flags.customer);
11944
12177
  const properties = await resolveProperties2(attemptCtx, product.id, assignments);
11945
12178
  const input = {
11946
12179
  product_id: product.id,
@@ -11950,10 +12183,11 @@ async function runCreate3(flags, command) {
11950
12183
  ...assignee === void 0 ? {} : { assignee_id: assignee.id },
11951
12184
  ...priority === void 0 ? {} : { priority_id: priority.id },
11952
12185
  ...channel === void 0 ? {} : { channel_id: channel.id },
12186
+ ...customer === void 0 ? {} : { customer_id: customer.id },
11953
12187
  ...properties.value === void 0 ? {} : { properties: properties.value }
11954
12188
  };
11955
12189
  return {
11956
- resolutions: present([product, type, assignee, priority, channel, ...properties.resolutions]),
12190
+ resolutions: present([product, type, assignee, priority, channel, customer, ...properties.resolutions]),
11957
12191
  value: input
11958
12192
  };
11959
12193
  };
@@ -12233,14 +12467,21 @@ function registerProductPlanCommands(parent) {
12233
12467
  }
12234
12468
  function registerProductMetaCommands(parent) {
12235
12469
  const meta = parent.command("meta").description("ids you need before writing: every ship lookup is scoped to one product");
12236
- function productScoped(name, description, load, columns) {
12470
+ function productScoped(name, description, load, columns, onError) {
12237
12471
  addGlobalOptions(
12238
12472
  meta.command(name).description(description).requiredOption("--product <name|id>", "product name, identifier such as SLC, or id"),
12239
12473
  { hidden: true }
12240
12474
  ).action(async (flags, command) => {
12241
12475
  const { ctx } = contextFor(command);
12242
12476
  const resolved = await resolveProduct(ctx, flags.product);
12243
- printCollection(await load(ctx, resolved.id), columns, modeOf(ctx));
12477
+ try {
12478
+ printCollection(await load(ctx, resolved.id), columns, modeOf(ctx));
12479
+ } catch (raw) {
12480
+ if (onError !== void 0) {
12481
+ await onError(raw);
12482
+ }
12483
+ throw raw;
12484
+ }
12244
12485
  });
12245
12486
  }
12246
12487
  productScoped(
@@ -12283,7 +12524,18 @@ function registerProductMetaCommands(parent) {
12283
12524
  "ticket-states",
12284
12525
  "ticket states of a product (values for --state / state_id)",
12285
12526
  listTicketStates,
12286
- SHIP_STATE_COLUMNS
12527
+ SHIP_STATE_COLUMNS,
12528
+ async (raw) => {
12529
+ if (raw instanceof ApiError && raw.status !== void 0 && raw.status >= 500) {
12530
+ throw new ApiError(raw.message, {
12531
+ code: raw.code,
12532
+ status: raw.status,
12533
+ cause: raw,
12534
+ hint: "The endpoint is currently unavailable (server error); creating a ticket does not need it \u2014 the initial state is decided by the server; only `ticket transition` and `list --state` need it."
12535
+ });
12536
+ }
12537
+ throw raw;
12538
+ }
12287
12539
  );
12288
12540
  productScoped(
12289
12541
  "ticket-priorities",
@@ -12381,6 +12633,7 @@ var init_product = __esm({
12381
12633
  "use strict";
12382
12634
  init_ship2();
12383
12635
  init_metadata();
12636
+ init_errors();
12384
12637
  init_paginate();
12385
12638
  init_globals();
12386
12639
  init_common();
@@ -13548,6 +13801,10 @@ function typeLabelOf(type) {
13548
13801
  if (typeof type === "string") return type;
13549
13802
  return refName(type);
13550
13803
  }
13804
+ function stateLabelOf(state) {
13805
+ if (typeof state === "string") return state;
13806
+ return refName(state);
13807
+ }
13551
13808
  function registerWorkItemCommands(parent) {
13552
13809
  const group2 = parent.command("work-item").description("work items (scopes pcp:read:pjm:workitem / pcp:write:pjm:workitem)");
13553
13810
  addGlobalOptions(
@@ -14267,7 +14524,7 @@ function printWorkItem(item, ctx, verb) {
14267
14524
  ["id", item.id],
14268
14525
  ["title", item.title ?? ""],
14269
14526
  ["type", typeLabelOf(item.type)],
14270
- ["state", refName(item.state)],
14527
+ ["state", stateLabelOf(item.state)],
14271
14528
  ["priority", refName(item.priority)],
14272
14529
  ["assignee", refName(item.assignee)],
14273
14530
  ["project", refName(item.project)],
@@ -14578,7 +14835,7 @@ var init_workItem = __esm({
14578
14835
  { header: "IDENTIFIER", value: (item) => item.identifier ?? item.short_id ?? item.id },
14579
14836
  { header: "TITLE", value: (item) => item.title ?? "", flex: true },
14580
14837
  { header: "TYPE", value: (item) => typeLabelOf(item.type) },
14581
- { header: "STATE", value: (item) => refName(item.state) },
14838
+ { header: "STATE", value: (item) => stateLabelOf(item.state) },
14582
14839
  { header: "ASSIGNEE", value: (item) => refName(item.assignee) },
14583
14840
  { header: "END", value: (item) => timestampCell(item.end_at) }
14584
14841
  ];