@scalar/cli 2.7.1 → 2.10.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.
Files changed (94) hide show
  1. package/README.md +475 -80
  2. package/chunks/action-4GZI2M5B.js +62 -0
  3. package/chunks/action-4W5GUGEG.js +63 -0
  4. package/chunks/{action-HJYZCPUN.js → action-5LF4XYHX.js} +10 -7
  5. package/chunks/{action-SRBN7N3R.js → action-5N3P43MD.js} +17 -12
  6. package/chunks/{action-RBOLLIGX.js → action-5RL4NWUZ.js} +17 -17
  7. package/chunks/{action-SNPOOW6S.js → action-657A4K2D.js} +16 -16
  8. package/chunks/{action-EOAVVL52.js → action-7XOHYWYM.js} +11 -14
  9. package/chunks/{action-AQRPFQKI.js → action-CABLS46Q.js} +9 -7
  10. package/chunks/{action-F7A2K74G.js → action-CB55NWAU.js} +9 -13
  11. package/chunks/{action-5SK5NE7E.js → action-DKDRAIKV.js} +11 -14
  12. package/chunks/{action-7PEQXDWT.js → action-DTEO4YNX.js} +127 -20
  13. package/chunks/{action-BAQYJ6UE.js → action-EAUTQ77U.js} +27 -23
  14. package/chunks/{action-QYGOPSTY.js → action-FBRY5JKU.js} +16 -16
  15. package/chunks/{action-VOFDW3U2.js → action-GFLRD7LO.js} +6 -5
  16. package/chunks/{action-LPVITMWA.js → action-GWYYTUTM.js} +4 -3
  17. package/chunks/{action-4NGK5XMD.js → action-HT42NUUX.js} +29 -24
  18. package/chunks/action-JEYDBB3P.js +147 -0
  19. package/chunks/{action-E4YSRFGT.js → action-KDUFU7TZ.js} +11 -13
  20. package/chunks/{action-BRSSC2SR.js → action-LYCNT3KA.js} +29 -10
  21. package/chunks/{action-CA4QYPI6.js → action-OJ2NK25F.js} +4 -8
  22. package/chunks/{action-NVI5DWFP.js → action-PAM2EZ22.js} +4 -8
  23. package/chunks/action-PPTFYZWD.js +1552 -0
  24. package/chunks/{action-OX2566BE.js → action-R4PGILN4.js} +30 -26
  25. package/chunks/{action-CPLH2CQ5.js → action-TOBU74JH.js} +23 -19
  26. package/chunks/action-U2L5DCFG.js +91 -0
  27. package/chunks/{action-H6OUJWWM.js → action-UUL6SWV4.js} +11 -14
  28. package/chunks/{action-T5XMJXPO.js → action-X7BA7PQQ.js} +10 -8
  29. package/chunks/{action-LVDU6YOI.js → action-XLE37MZL.js} +16 -16
  30. package/chunks/{action-BOZNBCNZ.js → action-XOADBXSX.js} +16 -12
  31. package/chunks/{action-SCOXTCPR.js → action-YSVTZVKV.js} +38 -19
  32. package/chunks/{action-YRX6SN5F.js → action-ZFI77WA5.js} +8 -6
  33. package/chunks/{action-ATGZOWSH.js → action-ZKA3RR3S.js} +15 -11
  34. package/chunks/actions-3SAMH7A5.js +182 -0
  35. package/chunks/{agent-ASPV3R5U.js → agent-2ESZI7NO.js} +7 -5
  36. package/chunks/{asyncapi-H4FU6GPC.js → asyncapi-4HGVM3PR.js} +14 -10
  37. package/chunks/{build.action-6V6GXI3X.js → build.action-VBGFGACM.js} +21 -19
  38. package/chunks/chunk-35Z7VTJT.js +453 -0
  39. package/chunks/chunk-36LXIJIZ.js +52 -0
  40. package/chunks/{chunk-BIKOD3SG.js → chunk-43WALAW3.js} +251 -103
  41. package/chunks/{chunk-C2KAWRIX.js → chunk-5ENKYZA4.js} +1 -1
  42. package/chunks/{chunk-ZJVYOZFB.js → chunk-5SMP756H.js} +2 -2
  43. package/chunks/{chunk-5JLVQVKO.js → chunk-6M7TL2G2.js} +146 -148
  44. package/chunks/chunk-6PSYZO3U.js +24 -0
  45. package/chunks/{chunk-ISXH6Q7I.js → chunk-ATNTXKMS.js} +45 -274
  46. package/chunks/{chunk-BDEPNGTO.js → chunk-BIMLCGKS.js} +1 -1
  47. package/chunks/{chunk-HGOD6THU.js → chunk-CWVYOXXM.js} +2 -19
  48. package/chunks/chunk-DFOZG7ZV.js +15 -0
  49. package/chunks/chunk-DHZW7Q7U.js +133 -0
  50. package/chunks/{chunk-R5LK6VPY.js → chunk-G4HRW2FZ.js} +13 -20
  51. package/chunks/{chunk-KCCFN4F7.js → chunk-GLWTVLKM.js} +29 -29
  52. package/chunks/{chunk-5UHLAJQD.js → chunk-GYRQPDTK.js} +24 -10
  53. package/chunks/chunk-H467HDVV.js +24 -0
  54. package/chunks/chunk-IPZP3VRA.js +327 -0
  55. package/chunks/{chunk-LG7IFACX.js → chunk-JXGF5EHC.js} +152 -18
  56. package/chunks/chunk-K2HIB5BA.js +92 -0
  57. package/chunks/{chunk-FDC2IESH.js → chunk-KHF2QXBG.js} +1352 -8327
  58. package/chunks/{chunk-IMG35UXX.js → chunk-KZNRQVMY.js} +1 -1
  59. package/chunks/{chunk-OJ2EWIJH.js → chunk-MC4EMNOR.js} +5 -1
  60. package/chunks/{chunk-YILQODZF.js → chunk-MMWSCTDB.js} +7 -4
  61. package/chunks/{chunk-6XWCMJDB.js → chunk-MNNGUUKJ.js} +12 -11
  62. package/chunks/chunk-NAC63XJF.js +10 -0
  63. package/chunks/{chunk-XXSQUBXS.js → chunk-UDBSV3CK.js} +107 -453
  64. package/chunks/{chunk-IKT5F47M.js → chunk-VVRUSQCY.js} +11 -11
  65. package/chunks/{chunk-2PPRO2QB.js → chunk-VYFGRLVQ.js} +1 -1
  66. package/chunks/{chunk-GPNB7ISG.js → chunk-WB6PWTMU.js} +5 -13
  67. package/chunks/{chunk-4X47MN6Q.js → chunk-WDIWLXLV.js} +3 -15
  68. package/chunks/{chunk-6YPQGVF4.js → chunk-WIEXQUTD.js} +1 -1
  69. package/chunks/{chunk-W24BETFG.js → chunk-XAGJJNQW.js} +3 -3
  70. package/chunks/{chunk-2DSVF5AD.js → chunk-ZGNDXPLU.js} +3 -3
  71. package/chunks/{chunk-XEDGMZJD.js → chunk-ZGVZU6L2.js} +81 -25
  72. package/chunks/{chunk-QXQZVEDC.js → chunk-ZKJPLWRJ.js} +2 -2
  73. package/chunks/{chunk-MLSZVVTT.js → chunk-ZYBLQ5CT.js} +13 -7
  74. package/chunks/{create.action-P6DLCK4W.js → create.action-DBNIS665.js} +21 -19
  75. package/chunks/{delete.action-HJKRRHE2.js → delete.action-GBOZC45K.js} +21 -19
  76. package/chunks/{delete.action-Z3GAA4ZN.js → delete.action-K7BLK7DK.js} +21 -19
  77. package/chunks/{get.action-IT4EHAV4.js → get.action-N3JOY3OU.js} +17 -12
  78. package/chunks/get.action-QHKMYZBK.js +91 -0
  79. package/chunks/{list.action-WLIAO5UW.js → list.action-6SSO3JVN.js} +45 -15
  80. package/chunks/{list.action-2FU5UZNH.js → list.action-TJCS6UEY.js} +41 -21
  81. package/chunks/{publish.action-T4J4DRXR.js → publish.action-T24VHRMR.js} +29 -24
  82. package/chunks/query-WKATAJJ6.js +129 -0
  83. package/chunks/scripts-VIBLGKYG.js +102 -0
  84. package/chunks/{update.action-3OVS3HWC.js → update.action-OGYNBXRU.js} +24 -19
  85. package/chunks/{update.action-MY7QPSSU.js → update.action-VOE6PH5F.js} +24 -19
  86. package/docs.html +1363 -320
  87. package/index.js +417 -174
  88. package/package.json +14 -13
  89. package/skills/scalar-cli/SKILL.md +13 -1
  90. package/template.md +157 -15
  91. package/chunks/action-JAHFRYWZ.js +0 -423
  92. package/chunks/action-N7BA5I3E.js +0 -229
  93. package/chunks/chunk-CWCETP6H.js +0 -610
  94. package/chunks/chunk-K74E42RV.js +0 -7311
@@ -0,0 +1,453 @@
1
+ import { createRequire as $$cR } from "node:module"; const require = $$cR(import.meta.url);
2
+ import {
3
+ config
4
+ } from "./chunk-WB6PWTMU.js";
5
+ import {
6
+ roleSchema
7
+ } from "./chunk-GYRQPDTK.js";
8
+ import {
9
+ output
10
+ } from "./chunk-T5HJUAWB.js";
11
+ import {
12
+ emailSchema,
13
+ external_exports,
14
+ zod_default
15
+ } from "./chunk-VVRUSQCY.js";
16
+
17
+ // ../../packages/entities/dist/token/token.js
18
+ var accessTokenPayloadSchema = external_exports.object({
19
+ userIndex: external_exports.string(),
20
+ userUid: external_exports.string().brand(),
21
+ // Brand only — `.brand()` keeps the runtime `z.string()` validation (no
22
+ // `.min()`), so parsed tokens stay byte-identical while gaining the Team brand.
23
+ teamUid: external_exports.string().brand(),
24
+ email: emailSchema.nullable(),
25
+ role: roleSchema.optional(),
26
+ exp: external_exports.number().int()
27
+ }).meta({ id: "access-token-payload" });
28
+ var healthTokenPayloadSchema = external_exports.object({
29
+ svc: external_exports.string().optional(),
30
+ iat: external_exports.number().int().optional(),
31
+ exp: external_exports.number().int()
32
+ }).meta({ id: "health-token-payload" });
33
+ var edgeCacheSyncTokenPayloadSchema = external_exports.object({
34
+ svc: external_exports.literal("watcher-edge-cache-sync"),
35
+ iat: external_exports.number().int().optional(),
36
+ exp: external_exports.number().int()
37
+ }).meta({
38
+ id: "edge-cache-sync-token-payload"
39
+ });
40
+ var personalTokenPayloadSchema = external_exports.object({
41
+ uid: external_exports.string(),
42
+ teamUid: external_exports.string(),
43
+ userIndex: external_exports.string(),
44
+ iat: external_exports.number(),
45
+ exp: external_exports.number()
46
+ }).meta({ id: "personal-token-payload" });
47
+ var docsAgentTokenSchema = external_exports.object({
48
+ uid: external_exports.string(),
49
+ publishUid: external_exports.string(),
50
+ projectUid: external_exports.string(),
51
+ teamUid: external_exports.string(),
52
+ mcpServerId: external_exports.string(),
53
+ mcpInstallationId: external_exports.string(),
54
+ iat: external_exports.number(),
55
+ exp: external_exports.number()
56
+ }).meta({ id: "docs-agent-token" });
57
+
58
+ // ../../packages/entities/dist/token/payload.js
59
+ var tokenResponseSchema = external_exports.object({
60
+ refreshToken: external_exports.string(),
61
+ accessToken: external_exports.string()
62
+ }).meta({ id: "token-response" });
63
+
64
+ // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/runtime/base64url.js
65
+ import { Buffer as Buffer2 } from "node:buffer";
66
+
67
+ // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/lib/buffer_utils.js
68
+ var encoder = new TextEncoder();
69
+ var decoder = new TextDecoder();
70
+ var MAX_INT32 = 2 ** 32;
71
+
72
+ // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/runtime/base64url.js
73
+ function normalize(input) {
74
+ let encoded = input;
75
+ if (encoded instanceof Uint8Array) {
76
+ encoded = decoder.decode(encoded);
77
+ }
78
+ return encoded;
79
+ }
80
+ var decode = (input) => new Uint8Array(Buffer2.from(normalize(input), "base64url"));
81
+
82
+ // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/util/errors.js
83
+ var JOSEError = class extends Error {
84
+ static code = "ERR_JOSE_GENERIC";
85
+ code = "ERR_JOSE_GENERIC";
86
+ constructor(message, options) {
87
+ super(message, options);
88
+ this.name = this.constructor.name;
89
+ Error.captureStackTrace?.(this, this.constructor);
90
+ }
91
+ };
92
+ var JWTInvalid = class extends JOSEError {
93
+ static code = "ERR_JWT_INVALID";
94
+ code = "ERR_JWT_INVALID";
95
+ };
96
+
97
+ // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/lib/is_object.js
98
+ function isObjectLike(value) {
99
+ return typeof value === "object" && value !== null;
100
+ }
101
+ function isObject(input) {
102
+ if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
103
+ return false;
104
+ }
105
+ if (Object.getPrototypeOf(input) === null) {
106
+ return true;
107
+ }
108
+ let proto = input;
109
+ while (Object.getPrototypeOf(proto) !== null) {
110
+ proto = Object.getPrototypeOf(proto);
111
+ }
112
+ return Object.getPrototypeOf(input) === proto;
113
+ }
114
+
115
+ // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/util/base64url.js
116
+ var decode2 = decode;
117
+
118
+ // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/util/decode_protected_header.js
119
+ function decodeProtectedHeader(token) {
120
+ let protectedB64u;
121
+ if (typeof token === "string") {
122
+ const parts = token.split(".");
123
+ if (parts.length === 3 || parts.length === 5) {
124
+ ;
125
+ [protectedB64u] = parts;
126
+ }
127
+ } else if (typeof token === "object" && token) {
128
+ if ("protected" in token) {
129
+ protectedB64u = token.protected;
130
+ } else {
131
+ throw new TypeError("Token does not contain a Protected Header");
132
+ }
133
+ }
134
+ try {
135
+ if (typeof protectedB64u !== "string" || !protectedB64u) {
136
+ throw new Error();
137
+ }
138
+ const result = JSON.parse(decoder.decode(decode2(protectedB64u)));
139
+ if (!isObject(result)) {
140
+ throw new Error();
141
+ }
142
+ return result;
143
+ } catch {
144
+ throw new TypeError("Invalid Token or Protected Header formatting");
145
+ }
146
+ }
147
+
148
+ // ../../node_modules/.pnpm/jose@5.9.6/node_modules/jose/dist/node/esm/util/decode_jwt.js
149
+ function decodeJwt(jwt) {
150
+ if (typeof jwt !== "string")
151
+ throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
152
+ const { 1: payload, length } = jwt.split(".");
153
+ if (length === 5)
154
+ throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
155
+ if (length !== 3)
156
+ throw new JWTInvalid("Invalid JWT");
157
+ if (!payload)
158
+ throw new JWTInvalid("JWTs must contain a payload");
159
+ let decoded;
160
+ try {
161
+ decoded = decode2(payload);
162
+ } catch {
163
+ throw new JWTInvalid("Failed to base64url decode the payload");
164
+ }
165
+ let result;
166
+ try {
167
+ result = JSON.parse(decoder.decode(decoded));
168
+ } catch {
169
+ throw new JWTInvalid("Failed to parse the decoded payload as JSON");
170
+ }
171
+ if (!isObject(result))
172
+ throw new JWTInvalid("Invalid JWT Claims Set");
173
+ return result;
174
+ }
175
+
176
+ // ../../packages/tokens/dist/error.js
177
+ function TokenError(msg, code) {
178
+ const err = new Error(msg);
179
+ err.code = code;
180
+ return err;
181
+ }
182
+
183
+ // ../../packages/tokens/dist/index.js
184
+ function validatePayload(data, schema) {
185
+ const result = schema.safeParse(data);
186
+ if (!result.success) {
187
+ console.error("Invalid token payload:");
188
+ console.error(result.error.issues);
189
+ throw TokenError("Invalid token payload", "invalid-payload");
190
+ }
191
+ return result.data;
192
+ }
193
+ function decode3(token, schema = external_exports.any()) {
194
+ return validatePayload(decodeJwt(token), schema);
195
+ }
196
+
197
+ // src/helpers/metadata.ts
198
+ import fs from "node:fs/promises";
199
+ import os from "node:os";
200
+ import path from "node:path";
201
+ var SCALAR_METADATA_FILE_NAME = ".scalar-config";
202
+ var METADATA_FILE_PATH = path.join(
203
+ os.homedir(),
204
+ SCALAR_METADATA_FILE_NAME
205
+ );
206
+ var authSchema = external_exports.union([
207
+ external_exports.object({
208
+ accessToken: external_exports.string(),
209
+ refreshToken: external_exports.string()
210
+ }),
211
+ external_exports.object({
212
+ accessToken: external_exports.string(),
213
+ personalToken: external_exports.string()
214
+ })
215
+ ]);
216
+ var metadataSchema = external_exports.object({
217
+ lastUpdateCheck: external_exports.number(),
218
+ lastKnownVersion: external_exports.string(),
219
+ auth: authSchema.nullable().default(null)
220
+ });
221
+ var metadataCache = null;
222
+ var getMetadataMtimeMs = async () => (await fs.stat(METADATA_FILE_PATH).catch(() => null))?.mtimeMs ?? null;
223
+ var writeQueue = Promise.resolve();
224
+ var setMetadata = async (metadata) => {
225
+ const write = writeQueue.then(async () => {
226
+ const currentMetadata = await getMetadata();
227
+ const updatedMetadata = { ...currentMetadata, ...metadata };
228
+ const tmpPath = `${METADATA_FILE_PATH}.${process.pid}.tmp`;
229
+ await fs.writeFile(tmpPath, JSON.stringify(updatedMetadata));
230
+ await fs.rename(tmpPath, METADATA_FILE_PATH);
231
+ metadataCache = {
232
+ mtimeMs: await getMetadataMtimeMs(),
233
+ data: updatedMetadata
234
+ };
235
+ });
236
+ writeQueue = write.catch(() => {
237
+ });
238
+ return write;
239
+ };
240
+ var fileExists = async (path2) => !!await fs.stat(path2).catch(() => false);
241
+ var readMetadataFile = async () => {
242
+ const metadata = await fileExists(METADATA_FILE_PATH) ? await fs.readFile(METADATA_FILE_PATH, { encoding: "utf-8" }) : "{}";
243
+ try {
244
+ return metadataSchema.partial().parse(JSON.parse(metadata));
245
+ } catch {
246
+ return {};
247
+ }
248
+ };
249
+ var getMetadata = async () => {
250
+ const mtimeMs = await getMetadataMtimeMs();
251
+ if (metadataCache && metadataCache.mtimeMs === mtimeMs) {
252
+ return metadataCache.data;
253
+ }
254
+ const data = await readMetadataFile();
255
+ metadataCache = { mtimeMs, data };
256
+ return data;
257
+ };
258
+
259
+ // ../../packages/oauth/dist/scopes.js
260
+ var SCOPES = [
261
+ "consumer:docs",
262
+ "consumer:registry",
263
+ "consumer:mcp",
264
+ "consumer:sdk",
265
+ "platform:read",
266
+ "platform:write",
267
+ "platform:admin",
268
+ /** A first-party session: the dashboard's, the CLI's, a personal token's. Never granted to another client */
269
+ "platform:session"
270
+ ];
271
+ var PLATFORM_ROLES = ["owner", "admin", "editor", "viewer"];
272
+
273
+ // ../../packages/oauth/dist/claims.js
274
+ var ACCESS_TOKEN_TYP = "at+jwt";
275
+ var ACCESS_TOKEN_TTL_SECONDS = 15 * 60;
276
+ var PERSONAL_TOKEN_ACCESS_TTL_SECONDS = 12 * 60 * 60;
277
+ var address = external_exports.string().regex(/^[^@\s]+@[^@\s]+$/);
278
+ var commonClaims = {
279
+ /** The host the flow ran on: the shared auth host, or a customer's own domain */
280
+ iss: external_exports.url(),
281
+ aud: external_exports.union([external_exports.string().min(1), external_exports.array(external_exports.string().min(1)).min(1)]),
282
+ sub: external_exports.string().min(1),
283
+ exp: external_exports.number().int(),
284
+ iat: external_exports.number().int(),
285
+ client_id: external_exports.string().min(1),
286
+ /**
287
+ * Granted scopes. An array under `scp`, not a `scope` string: the apps
288
+ * behind the exchange bridge validate `scope` against core's old
289
+ * `read | write | admin` values and would reject the token.
290
+ */
291
+ scp: external_exports.array(external_exports.enum(SCOPES)),
292
+ /** The refresh family the token came from, or the credential for one that has none */
293
+ fid: external_exports.string().min(1)
294
+ };
295
+ var consumerClaimsSchema = external_exports.object({
296
+ ...commonClaims,
297
+ kind: external_exports.literal("consumer"),
298
+ email: address,
299
+ /** The namespace signed in to, without the `@` */
300
+ ns: external_exports.string().min(1),
301
+ teamUid: external_exports.string().min(1),
302
+ /**
303
+ * What the reader was admitted to: one docs project, registry record or
304
+ * MCP installation, or the namespace's own pages. Several of these share a
305
+ * host and so an audience, and access is granted to each on its own, so a
306
+ * resource server checks this against what is being read.
307
+ */
308
+ res: external_exports.object({
309
+ kind: external_exports.enum(["project", "registry", "mcp", "namespace"]),
310
+ uid: external_exports.string().min(1).optional()
311
+ }),
312
+ /** How the person proved the address */
313
+ via: external_exports.enum(["email", "google", "microsoft", "sso", "scalar"]),
314
+ /** The SAML connection that vouched, when `via` is `sso` */
315
+ idp: external_exports.string().min(1).optional()
316
+ });
317
+ var platformClaimsSchema = external_exports.object({
318
+ ...commonClaims,
319
+ kind: external_exports.literal("platform"),
320
+ userIndex: external_exports.string(),
321
+ userUid: external_exports.string().min(1),
322
+ teamUid: external_exports.string().min(1),
323
+ email: address.nullable(),
324
+ /** The member's role, already lowered to what the scopes allow */
325
+ role: external_exports.enum(PLATFORM_ROLES).optional(),
326
+ /** The service a token was exchanged for, when one acts for the person (RFC 8693) */
327
+ act: external_exports.object({ sub: external_exports.string().min(1) }).optional()
328
+ });
329
+ var accessTokenClaimsSchema = external_exports.discriminatedUnion("kind", [
330
+ consumerClaimsSchema,
331
+ platformClaimsSchema
332
+ ]);
333
+
334
+ // ../../packages/oauth/dist/verify.js
335
+ var MAX_AGE_MS = 5 * 6e4;
336
+ function isAccessToken(token) {
337
+ try {
338
+ return decodeProtectedHeader(token).typ === ACCESS_TOKEN_TYP;
339
+ } catch {
340
+ return false;
341
+ }
342
+ }
343
+
344
+ // src/helpers/auth.ts
345
+ var eventListeners = [];
346
+ var addEventListener = (callback) => {
347
+ eventListeners.push(callback);
348
+ };
349
+ var fireCallbacks = (auth) => eventListeners.forEach((callback) => callback(auth));
350
+ var setAuthData = async (authData) => {
351
+ await setMetadata({ auth: authData });
352
+ fireCallbacks(authData);
353
+ };
354
+ var getAuthData = async (opts) => {
355
+ const { noExit } = opts ?? {};
356
+ const { auth } = await getMetadata();
357
+ if (!auth) {
358
+ if (noExit) throw new Error("Authorization required");
359
+ return output.error().title("Authorization required").message("Please login before running this command.").exit("error");
360
+ }
361
+ const { email, role, teamUid, exp } = decode3(
362
+ auth.accessToken,
363
+ accessTokenPayloadSchema
364
+ );
365
+ const isExpired = exp * 1e3 < Date.now() || !isAccessToken(auth.accessToken);
366
+ if (!isExpired) {
367
+ return { ...auth, email, role, teamUid, addEventListener };
368
+ }
369
+ try {
370
+ if ("refreshToken" in auth) {
371
+ const updatedAuth2 = await refreshToken(auth.refreshToken);
372
+ return { ...updatedAuth2, email, role, teamUid, addEventListener };
373
+ }
374
+ const updatedAuth = await generateAccessByPersonalToken({
375
+ personalToken: auth.personalToken
376
+ });
377
+ return { ...updatedAuth, email, role, teamUid, addEventListener };
378
+ } catch {
379
+ if (noExit) throw new Error("Session expired, please login again.");
380
+ return output.error().title("Expired session").message("Session expired, please login again.").exit("error");
381
+ }
382
+ };
383
+ var clearAuthData = async () => {
384
+ await setMetadata({ auth: null });
385
+ };
386
+ var CLI_CLIENT_ID = "scalar-cli";
387
+ var tokenResponseSchema2 = zod_default.object({
388
+ access_token: zod_default.string(),
389
+ refresh_token: zod_default.string().optional()
390
+ });
391
+ var requestTokens = async (form) => {
392
+ const result = await fetch(`${config.auth.origin}/_scalar/oauth/token`, {
393
+ method: "POST",
394
+ body: new URLSearchParams(form),
395
+ // Fail fast instead of hanging every authed command on a slow network
396
+ signal: AbortSignal.timeout(1e4)
397
+ });
398
+ const body = await result.json().catch(() => ({}));
399
+ if (!result.ok) {
400
+ throw new Error(body.error_description ?? "Could not get a token");
401
+ }
402
+ return tokenResponseSchema2.parse(body);
403
+ };
404
+ var refreshToken = async (token, teamUid) => {
405
+ const tokens = await requestTokens({
406
+ grant_type: "refresh_token",
407
+ refresh_token: token,
408
+ client_id: CLI_CLIENT_ID,
409
+ ...teamUid && { team: teamUid }
410
+ });
411
+ const auth = {
412
+ accessToken: tokens.access_token,
413
+ refreshToken: tokens.refresh_token ?? token
414
+ };
415
+ await setAuthData(auth);
416
+ return auth;
417
+ };
418
+ var generateAccessByPersonalToken = async ({
419
+ personalToken
420
+ }) => {
421
+ const tokens = await requestTokens({
422
+ grant_type: "client_credentials",
423
+ client_secret: personalToken
424
+ });
425
+ const auth = { accessToken: tokens.access_token, personalToken };
426
+ await setAuthData(auth);
427
+ return auth;
428
+ };
429
+ var logout = async () => {
430
+ const { auth } = await getMetadata();
431
+ if (auth && "refreshToken" in auth) {
432
+ await fetch(`${config.auth.origin}/_scalar/oauth/revoke`, {
433
+ method: "POST",
434
+ body: new URLSearchParams({ token: auth.refreshToken }),
435
+ signal: AbortSignal.timeout(1e4)
436
+ }).catch(() => void 0);
437
+ }
438
+ await clearAuthData();
439
+ };
440
+
441
+ export {
442
+ accessTokenPayloadSchema,
443
+ decode3 as decode,
444
+ setMetadata,
445
+ getMetadata,
446
+ setAuthData,
447
+ getAuthData,
448
+ CLI_CLIENT_ID,
449
+ requestTokens,
450
+ refreshToken,
451
+ generateAccessByPersonalToken,
452
+ logout
453
+ };
@@ -0,0 +1,52 @@
1
+ import { createRequire as $$cR } from "node:module"; const require = $$cR(import.meta.url);
2
+ import {
3
+ isUrl
4
+ } from "./chunk-4ORL4MST.js";
5
+ import {
6
+ output
7
+ } from "./chunk-T5HJUAWB.js";
8
+
9
+ // src/helpers/node-version.ts
10
+ import semver from "semver";
11
+ function checkNodeVersion() {
12
+ const currentVersion = process.version;
13
+ if (!semver.satisfies(currentVersion, ">=24")) {
14
+ output.error().title("Node.js version incompatible").message(
15
+ `Current Node.js version: ${currentVersion}
16
+ Minimum required version: ${">=24"}
17
+ Please upgrade your Node.js version and try again.
18
+ Visit https://nodejs.org to download the latest version.`
19
+ ).exit("error");
20
+ }
21
+ }
22
+
23
+ // src/helpers/watch-file.ts
24
+ import fs from "node:fs";
25
+ import path from "node:path";
26
+ import chokidar from "chokidar";
27
+ var watchFile = async (file, callback, options) => {
28
+ if (isUrl(file)) {
29
+ setInterval(callback, 5e3);
30
+ return;
31
+ }
32
+ const absoluteFilePath = path.resolve(file);
33
+ if (!fs.existsSync(absoluteFilePath)) {
34
+ throw new Error(`File ${absoluteFilePath} does not exist`);
35
+ }
36
+ output.info().title(`Watch ${file}`).print();
37
+ const watcher = chokidar.watch(absoluteFilePath, { persistent: true });
38
+ watcher.on("change", () => {
39
+ callback();
40
+ });
41
+ if (options?.immediate) {
42
+ callback();
43
+ }
44
+ return {
45
+ unsubscribe: () => watcher.close()
46
+ };
47
+ };
48
+
49
+ export {
50
+ checkNodeVersion,
51
+ watchFile
52
+ };