vibedgames 0.8.0 → 0.9.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 (40) hide show
  1. package/README.md +14 -6
  2. package/dist/THIRD_PARTY_NOTICES.txt +58 -6
  3. package/dist/{chunk-FNYBZNW2.js → chunk-25BAMW5X.js} +3 -1
  4. package/dist/{chunk-SAANBZ25.js → chunk-2VUUMXAQ.js} +4 -4
  5. package/dist/{chunk-XK5RZQMX.js → chunk-355VG7EO.js} +14 -13
  6. package/dist/{chunk-I6O4HIDY.js → chunk-3HUWAJQH.js} +76 -61
  7. package/dist/{chunk-2QBYTIMH.js → chunk-5535KDYI.js} +1 -1
  8. package/dist/chunk-56OY4TEP.js +20125 -0
  9. package/dist/{chunk-XDC7QGOF.js → chunk-6EWHKL7Z.js} +14 -6
  10. package/dist/{chunk-6FZPPUQH.js → chunk-7CXMMC5S.js} +1 -1
  11. package/dist/chunk-7QZSDU52.js +26 -0
  12. package/dist/{chunk-AZGENOOR.js → chunk-AXTLPJ2F.js} +5 -4
  13. package/dist/{chunk-IO6OM6WM.js → chunk-BMTHAVMS.js} +7 -33
  14. package/dist/{chunk-CU7UY5YJ.js → chunk-D2RF35HJ.js} +1 -1
  15. package/dist/chunk-FC233UKH.js +170 -0
  16. package/dist/{chunk-CAKBGDCY.js → chunk-GKDUYJ7R.js} +5 -0
  17. package/dist/{chunk-TYVYWBY6.js → chunk-H3IPLBXQ.js} +9 -8
  18. package/dist/{chunk-TMK6V5FV.js → chunk-HNRVSBRK.js} +7 -7
  19. package/dist/chunk-K2U7L4RU.js +183 -0
  20. package/dist/{chunk-PQDBCZRT.js → chunk-KZBZNTM4.js} +203 -153
  21. package/dist/{chunk-GUF6ADBF.js → chunk-LXS3NJYD.js} +8 -7
  22. package/dist/{chunk-W5XP4ZVU.js → chunk-LY2GQ32S.js} +11 -10
  23. package/dist/{chunk-K5SC6SXO.js → chunk-NDHXM4PL.js} +5 -5
  24. package/dist/{chunk-HASKWB6B.js → chunk-OD2MNYXD.js} +48 -22
  25. package/dist/{chunk-JT2AU24K.js → chunk-QARXJGI5.js} +1 -1
  26. package/dist/{chunk-RYFO3ZPO.js → chunk-RXHTGX7C.js} +9 -2
  27. package/dist/chunk-ST5FC2W3.js +95 -0
  28. package/dist/chunk-TBQ5BU3Q.js +39 -0
  29. package/dist/{chunk-RIGKOLNN.js → chunk-UFR6G6BL.js} +40 -65
  30. package/dist/{chunk-CZPKN32Z.js → chunk-US6QZICZ.js} +10 -10
  31. package/dist/{chunk-Y552BNFZ.js → chunk-UXCWSWWX.js} +7 -7
  32. package/dist/chunk-UZM6OSW5.js +113 -0
  33. package/dist/{chunk-FL6IFBUF.js → chunk-WSRIF6K4.js} +4 -4
  34. package/dist/chunk-X75Y7LUW.js +126 -0
  35. package/dist/chunk-Z5TFZQ5U.js +2478 -0
  36. package/dist/{chunk-H4NBRFBY.js → chunk-ZCYWDKYP.js} +30 -5
  37. package/dist/index.js +30 -19
  38. package/package.json +6 -5
  39. package/dist/chunk-RNBUX5VF.js +0 -68
  40. package/dist/chunk-X4ZABSCN.js +0 -415
@@ -5,16 +5,20 @@ const require = __createRequire(import.meta.url);
5
5
  var __filename = __fileURLToPath(import.meta.url);
6
6
  var __dirname = __pathDirname(__filename);
7
7
  import {
8
- clearConfig
9
- } from "./chunk-RYFO3ZPO.js";
10
- import "./chunk-J6PKNPI2.js";
8
+ revokeLogin
9
+ } from "./chunk-K2U7L4RU.js";
10
+ import {
11
+ clearConfig,
12
+ getConfig
13
+ } from "./chunk-RXHTGX7C.js";
11
14
  import {
12
15
  consola
13
- } from "./chunk-CU7UY5YJ.js";
16
+ } from "./chunk-D2RF35HJ.js";
17
+ import "./chunk-J6PKNPI2.js";
14
18
  import {
15
19
  defineCommand
16
20
  } from "./chunk-MBXCVCC4.js";
17
- import "./chunk-CAKBGDCY.js";
21
+ import "./chunk-GKDUYJ7R.js";
18
22
 
19
23
  // src/commands/logout.ts
20
24
  var logoutCommand = defineCommand({
@@ -22,7 +26,11 @@ var logoutCommand = defineCommand({
22
26
  description: "Log out of vibedgames",
23
27
  name: "logout"
24
28
  },
25
- run: () => {
29
+ run: async () => {
30
+ const config = getConfig();
31
+ if (config) {
32
+ await revokeLogin(config);
33
+ }
26
34
  clearConfig();
27
35
  consola.success("Logged out");
28
36
  }
@@ -6,7 +6,7 @@ var __filename = __fileURLToPath(import.meta.url);
6
6
  var __dirname = __pathDirname(__filename);
7
7
  import {
8
8
  getConfigDir
9
- } from "./chunk-RYFO3ZPO.js";
9
+ } from "./chunk-RXHTGX7C.js";
10
10
  import {
11
11
  isJsonObject,
12
12
  isJsonString
@@ -0,0 +1,26 @@
1
+ import { createRequire as __createRequire } from "node:module";
2
+ import { dirname as __pathDirname } from "node:path";
3
+ import { fileURLToPath as __fileURLToPath } from "node:url";
4
+ const require = __createRequire(import.meta.url);
5
+ var __filename = __fileURLToPath(import.meta.url);
6
+ var __dirname = __pathDirname(__filename);
7
+ import {
8
+ FACTORY_PACKAGE,
9
+ factoryCommand,
10
+ installedFactoryVersion,
11
+ runFactory,
12
+ updateFactory
13
+ } from "./chunk-ZCYWDKYP.js";
14
+ import "./chunk-TBQ5BU3Q.js";
15
+ import "./chunk-5535KDYI.js";
16
+ import "./chunk-D2RF35HJ.js";
17
+ import "./chunk-J6PKNPI2.js";
18
+ import "./chunk-MBXCVCC4.js";
19
+ import "./chunk-GKDUYJ7R.js";
20
+ export {
21
+ FACTORY_PACKAGE,
22
+ factoryCommand,
23
+ installedFactoryVersion,
24
+ runFactory,
25
+ updateFactory
26
+ };
@@ -7,15 +7,16 @@ var __dirname = __pathDirname(__filename);
7
7
  import {
8
8
  initCommand,
9
9
  reportSkills
10
- } from "./chunk-IO6OM6WM.js";
11
- import "./chunk-2QBYTIMH.js";
10
+ } from "./chunk-BMTHAVMS.js";
12
11
  import "./chunk-VFFOT7KD.js";
13
12
  import "./chunk-PEUP4MZR.js";
13
+ import "./chunk-TBQ5BU3Q.js";
14
+ import "./chunk-5535KDYI.js";
14
15
  import "./chunk-RZ4DIJQW.js";
16
+ import "./chunk-D2RF35HJ.js";
15
17
  import "./chunk-J6PKNPI2.js";
16
- import "./chunk-CU7UY5YJ.js";
17
18
  import "./chunk-MBXCVCC4.js";
18
- import "./chunk-CAKBGDCY.js";
19
+ import "./chunk-GKDUYJ7R.js";
19
20
  export {
20
21
  initCommand,
21
22
  reportSkills
@@ -4,9 +4,6 @@ import { fileURLToPath as __fileURLToPath } from "node:url";
4
4
  const require = __createRequire(import.meta.url);
5
5
  var __filename = __fileURLToPath(import.meta.url);
6
6
  var __dirname = __pathDirname(__filename);
7
- import {
8
- require_cross_spawn
9
- } from "./chunk-2QBYTIMH.js";
10
7
  import {
11
8
  So
12
9
  } from "./chunk-VFFOT7KD.js";
@@ -16,48 +13,27 @@ import {
16
13
  globalInstallArgs,
17
14
  globalInstallCommand
18
15
  } from "./chunk-PEUP4MZR.js";
16
+ import {
17
+ isMissingCommand,
18
+ run
19
+ } from "./chunk-TBQ5BU3Q.js";
19
20
  import {
20
21
  assertKnownFlags
21
22
  } from "./chunk-RZ4DIJQW.js";
23
+ import {
24
+ consola
25
+ } from "./chunk-D2RF35HJ.js";
22
26
  import {
23
27
  isJsonObject,
24
28
  isJsonString
25
29
  } from "./chunk-J6PKNPI2.js";
26
- import {
27
- consola
28
- } from "./chunk-CU7UY5YJ.js";
29
30
  import {
30
31
  defineCommand
31
32
  } from "./chunk-MBXCVCC4.js";
32
- import {
33
- __toESM
34
- } from "./chunk-CAKBGDCY.js";
35
33
 
36
34
  // src/commands/init.ts
37
35
  import path2 from "node:path";
38
36
 
39
- // src/lib/run.ts
40
- var import_cross_spawn = __toESM(require_cross_spawn(), 1);
41
- var isMissingCommand = (result) => result.code !== 0 && /ENOENT|not found|not recognized/iu.test(result.output);
42
- var run = (cmd, args) => (
43
- // oxlint-disable-next-line promise/avoid-new -- child_process.spawn is event-based
44
- new Promise((resolve) => {
45
- const chunks = [];
46
- const child = (0, import_cross_spawn.default)(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
47
- const collect = (c) => {
48
- chunks.push(c);
49
- };
50
- child.stdout?.on("data", collect);
51
- child.stderr?.on("data", collect);
52
- child.on("error", (err) => resolve({ code: 1, output: `${err.message}
53
- ` }));
54
- child.on(
55
- "close",
56
- (code) => resolve({ code: code ?? 1, output: Buffer.concat(chunks).toString("utf-8") })
57
- );
58
- })
59
- );
60
-
61
37
  // src/lib/skills-install.ts
62
38
  import {
63
39
  cpSync,
@@ -456,8 +432,6 @@ var initCommand = defineCommand({
456
432
  });
457
433
 
458
434
  export {
459
- isMissingCommand,
460
- run,
461
435
  syncSkills,
462
436
  settleSync,
463
437
  findInstall,
@@ -1084,7 +1084,7 @@ function createConsola2(options = {}) {
1084
1084
  defaults: { level },
1085
1085
  stdout: process.stdout,
1086
1086
  stderr: process.stderr,
1087
- prompt: (...args) => import("./chunk-JT2AU24K.js").then((m) => m.prompt(...args)),
1087
+ prompt: (...args) => import("./chunk-QARXJGI5.js").then((m) => m.prompt(...args)),
1088
1088
  reporters: options.reporters || [
1089
1089
  options.fancy ?? !(T || R) ? new FancyReporter() : new BasicReporter()
1090
1090
  ],
@@ -0,0 +1,170 @@
1
+ import { createRequire as __createRequire } from "node:module";
2
+ import { dirname as __pathDirname } from "node:path";
3
+ import { fileURLToPath as __fileURLToPath } from "node:url";
4
+ const require = __createRequire(import.meta.url);
5
+ var __filename = __fileURLToPath(import.meta.url);
6
+ var __dirname = __pathDirname(__filename);
7
+ import {
8
+ authErrorCode,
9
+ createClient
10
+ } from "./chunk-KZBZNTM4.js";
11
+ import "./chunk-K2U7L4RU.js";
12
+ import "./chunk-Z4Z24FWO.js";
13
+ import "./chunk-PEUP4MZR.js";
14
+ import {
15
+ getToken
16
+ } from "./chunk-RXHTGX7C.js";
17
+ import {
18
+ outputArgs,
19
+ writeStructured
20
+ } from "./chunk-ZYCSYJWX.js";
21
+ import {
22
+ assertKnownFlags
23
+ } from "./chunk-RZ4DIJQW.js";
24
+ import {
25
+ consola
26
+ } from "./chunk-D2RF35HJ.js";
27
+ import "./chunk-J6PKNPI2.js";
28
+ import {
29
+ defineCommand
30
+ } from "./chunk-MBXCVCC4.js";
31
+ import "./chunk-GKDUYJ7R.js";
32
+
33
+ // src/commands/deployments.ts
34
+ var requireLogin = () => {
35
+ if (!getToken()) {
36
+ consola.warn("Not logged in. Run `vg login` to authenticate.");
37
+ process.exit(1);
38
+ }
39
+ };
40
+ var fail = (doing, code, message) => {
41
+ if (code === "UNAUTHORIZED") {
42
+ consola.warn("Not authenticated. Run `vg login`, or check your VG_TOKEN / API key.");
43
+ } else {
44
+ consola.error(`${doing}: ${message}`);
45
+ }
46
+ process.exit(1);
47
+ };
48
+ var listGames = async () => {
49
+ try {
50
+ const { games } = await createClient().deploy.list();
51
+ return games;
52
+ } catch (error) {
53
+ return fail(
54
+ "Could not list your games",
55
+ authErrorCode(error),
56
+ error instanceof Error ? error.message : String(error)
57
+ );
58
+ }
59
+ };
60
+ var formatBytes = (n) => {
61
+ if (n < 1024 * 1024) {
62
+ return `${(n / 1024).toFixed(1)} KB`;
63
+ }
64
+ return `${(n / (1024 * 1024)).toFixed(1)} MB`;
65
+ };
66
+ var listArgs = { ...outputArgs };
67
+ var listCommand = defineCommand({
68
+ args: listArgs,
69
+ meta: {
70
+ description: "List your games and their live deployments (the default).",
71
+ name: "list"
72
+ },
73
+ run: async ({ args, rawArgs }) => {
74
+ assertKnownFlags(rawArgs, listArgs);
75
+ requireLogin();
76
+ const games = await listGames();
77
+ const rows = games.map((g) => ({
78
+ bytes: g.deployment?.totalBytes ?? null,
79
+ deployed_at: g.deployment?.createdAt.toISOString() ?? null,
80
+ files: g.deployment?.fileCount ?? null,
81
+ id: g.id,
82
+ name: g.name,
83
+ slug: g.slug,
84
+ status: g.deployment?.status ?? null
85
+ }));
86
+ if (writeStructured({ games: rows }, args)) {
87
+ return;
88
+ }
89
+ if (rows.length === 0) {
90
+ consola.log("No games yet. Ship one with `vg deploy`.");
91
+ return;
92
+ }
93
+ for (const row of rows) {
94
+ const live = row.files === null || row.bytes === null ? "not deployed" : `${row.files} files, ${formatBytes(row.bytes)}, ${row.deployed_at ?? ""}`;
95
+ consola.log(`${row.slug} ${live}`);
96
+ }
97
+ }
98
+ });
99
+ var deleteArgs = {
100
+ slug: {
101
+ description: "Slug of the game to delete.",
102
+ required: true,
103
+ type: "positional"
104
+ },
105
+ yes: {
106
+ description: "Delete without asking. Required when there is no TTY (e.g. a coding agent).",
107
+ type: "boolean"
108
+ },
109
+ ...outputArgs
110
+ };
111
+ var deleteCommand = defineCommand({
112
+ args: deleteArgs,
113
+ meta: {
114
+ description: "Permanently delete one of your games and all of its deployed files.",
115
+ name: "delete"
116
+ },
117
+ run: async ({ args, rawArgs }) => {
118
+ assertKnownFlags(rawArgs, deleteArgs);
119
+ requireLogin();
120
+ const games = await listGames();
121
+ const game = games.find((g) => g.slug === args.slug);
122
+ if (!game) {
123
+ consola.error(`You have no game "${args.slug}". List yours with \`vg deployments\`.`);
124
+ process.exit(1);
125
+ }
126
+ if (!args.yes) {
127
+ if (!process.stdin.isTTY) {
128
+ consola.error(`Deleting is permanent: pass --yes to delete ${args.slug}.`);
129
+ process.exit(2);
130
+ }
131
+ const confirmed = await consola.prompt(
132
+ `Permanently delete ${args.slug} and all of its files?`,
133
+ { type: "confirm" }
134
+ );
135
+ if (confirmed !== true) {
136
+ consola.info("Nothing deleted.");
137
+ return;
138
+ }
139
+ }
140
+ try {
141
+ await createClient().deploy.delete({ gameId: game.id });
142
+ } catch (error) {
143
+ fail(
144
+ `Could not delete ${args.slug}`,
145
+ authErrorCode(error),
146
+ error instanceof Error ? error.message : String(error)
147
+ );
148
+ }
149
+ if (writeStructured({ deleted: true, slug: args.slug }, args)) {
150
+ return;
151
+ }
152
+ consola.success(`Deleted ${args.slug}.`);
153
+ }
154
+ });
155
+ var deploymentsCommand = defineCommand({
156
+ // Declared so citty skips `--field <value>` when looking for a subcommand.
157
+ args: outputArgs,
158
+ default: "list",
159
+ meta: {
160
+ description: "List your games, or delete one.",
161
+ name: "deployments"
162
+ },
163
+ subCommands: {
164
+ delete: deleteCommand,
165
+ list: listCommand
166
+ }
167
+ });
168
+ export {
169
+ deploymentsCommand
170
+ };
@@ -23,6 +23,10 @@ var __commonJS = (cb, mod) => function __require2() {
23
23
  throw mod = 0, e;
24
24
  }
25
25
  };
26
+ var __export = (target, all) => {
27
+ for (var name in all)
28
+ __defProp(target, name, { get: all[name], enumerable: true });
29
+ };
26
30
  var __copyProps = (to, from, except, desc) => {
27
31
  if (from && typeof from === "object" || typeof from === "function") {
28
32
  for (let key of __getOwnPropNames(from))
@@ -43,5 +47,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
43
47
  export {
44
48
  __require,
45
49
  __commonJS,
50
+ __export,
46
51
  __toESM
47
52
  };
@@ -7,9 +7,13 @@ var __dirname = __pathDirname(__filename);
7
7
  import {
8
8
  authErrorCode,
9
9
  createClient
10
- } from "./chunk-PQDBCZRT.js";
10
+ } from "./chunk-KZBZNTM4.js";
11
+ import "./chunk-K2U7L4RU.js";
11
12
  import "./chunk-Z4Z24FWO.js";
12
13
  import "./chunk-PEUP4MZR.js";
14
+ import {
15
+ getToken
16
+ } from "./chunk-RXHTGX7C.js";
13
17
  import {
14
18
  outputArgs,
15
19
  writeStructured
@@ -17,17 +21,14 @@ import {
17
21
  import {
18
22
  assertKnownFlags
19
23
  } from "./chunk-RZ4DIJQW.js";
20
- import {
21
- getToken
22
- } from "./chunk-RYFO3ZPO.js";
23
- import "./chunk-J6PKNPI2.js";
24
24
  import {
25
25
  consola
26
- } from "./chunk-CU7UY5YJ.js";
26
+ } from "./chunk-D2RF35HJ.js";
27
+ import "./chunk-J6PKNPI2.js";
27
28
  import {
28
29
  defineCommand
29
30
  } from "./chunk-MBXCVCC4.js";
30
- import "./chunk-CAKBGDCY.js";
31
+ import "./chunk-GKDUYJ7R.js";
31
32
 
32
33
  // src/commands/whoami.ts
33
34
  var whoamiArgs = { ...outputArgs };
@@ -50,7 +51,7 @@ var whoamiCommand = defineCommand({
50
51
  if (writeStructured({ email: user.email, id: user.id, name: user.name }, args)) {
51
52
  return;
52
53
  }
53
- consola.log(`${user.name} (${user.email})`);
54
+ consola.log(user.email ? `${user.name} (${user.email})` : user.name);
54
55
  } catch (error) {
55
56
  const code = authErrorCode(error);
56
57
  if (code === "UNAUTHORIZED" || code === "FORBIDDEN") {
@@ -7,27 +7,27 @@ var __dirname = __pathDirname(__filename);
7
7
  import {
8
8
  So
9
9
  } from "./chunk-VFFOT7KD.js";
10
- import {
11
- SLUG_RE
12
- } from "./chunk-ZI6PKVXG.js";
13
10
  import {
14
11
  PACKAGE_ROOT
15
12
  } from "./chunk-Z4Z24FWO.js";
16
13
  import "./chunk-PEUP4MZR.js";
14
+ import {
15
+ SLUG_RE
16
+ } from "./chunk-ZI6PKVXG.js";
17
17
  import {
18
18
  assertKnownFlags
19
19
  } from "./chunk-RZ4DIJQW.js";
20
+ import {
21
+ consola
22
+ } from "./chunk-D2RF35HJ.js";
20
23
  import {
21
24
  isJsonObject,
22
25
  isJsonString
23
26
  } from "./chunk-J6PKNPI2.js";
24
- import {
25
- consola
26
- } from "./chunk-CU7UY5YJ.js";
27
27
  import {
28
28
  defineCommand
29
29
  } from "./chunk-MBXCVCC4.js";
30
- import "./chunk-CAKBGDCY.js";
30
+ import "./chunk-GKDUYJ7R.js";
31
31
 
32
32
  // src/commands/new.ts
33
33
  import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
@@ -0,0 +1,183 @@
1
+ import { createRequire as __createRequire } from "node:module";
2
+ import { dirname as __pathDirname } from "node:path";
3
+ import { fileURLToPath as __fileURLToPath } from "node:url";
4
+ const require = __createRequire(import.meta.url);
5
+ var __filename = __fileURLToPath(import.meta.url);
6
+ var __dirname = __pathDirname(__filename);
7
+ import {
8
+ getConfig,
9
+ saveConfig
10
+ } from "./chunk-RXHTGX7C.js";
11
+ import {
12
+ isJsonNumber,
13
+ isJsonObject,
14
+ isJsonString
15
+ } from "./chunk-J6PKNPI2.js";
16
+
17
+ // ../../packages/contract/src/auth/oauth-scopes.ts
18
+ var OAUTH_SCOPES = {
19
+ "credits:read": "See your credit balance",
20
+ "credits:write": "Buy credits and redeem credit codes",
21
+ "games:read": "See your games and download their source",
22
+ "games:write": "Deploy, update and delete your games",
23
+ generate: "Generate images, audio, video and 3D with your credits",
24
+ playtest: "Let a model playtest your games"
25
+ };
26
+
27
+ // ../../packages/contract/src/cli.ts
28
+ var CLI_VERSION_HEADER = "x-vg-cli";
29
+ var CLI_OAUTH_CLIENT_ID = "vibedgames-cli";
30
+ var CLI_OAUTH_SCOPES = [
31
+ "openid",
32
+ "profile",
33
+ "email",
34
+ "offline_access",
35
+ ...Object.keys(OAUTH_SCOPES)
36
+ ];
37
+
38
+ // src/lib/oauth.ts
39
+ var DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
40
+ var EXPIRY_MARGIN_MS = 6e4;
41
+ var apiResource = (baseUrl) => `${new URL(baseUrl).origin}/api`;
42
+ var authUrl = (baseUrl, path) => `${new URL(baseUrl).origin}/api/auth${path}`;
43
+ var OAuthError = class extends Error {
44
+ code;
45
+ constructor(code, description) {
46
+ super(description ? `${code}: ${description}` : code);
47
+ this.code = code;
48
+ this.name = "OAuthError";
49
+ }
50
+ };
51
+ var postForm = async (url, body) => {
52
+ const res = await fetch(url, {
53
+ body: new URLSearchParams(body),
54
+ headers: { accept: "application/json" },
55
+ method: "POST"
56
+ });
57
+ let data = null;
58
+ try {
59
+ data = await res.json();
60
+ } catch {
61
+ }
62
+ if (!isJsonObject(data)) {
63
+ throw new OAuthError("server_error", `HTTP ${res.status}`);
64
+ }
65
+ if (!res.ok) {
66
+ const { error, error_description: description } = data;
67
+ throw new OAuthError(
68
+ isJsonString(error) ? error : "server_error",
69
+ isJsonString(description) ? description : `HTTP ${res.status}`
70
+ );
71
+ }
72
+ return data;
73
+ };
74
+ var requestDeviceCode = async (baseUrl) => {
75
+ const data = await postForm(authUrl(baseUrl, "/device/code"), {
76
+ client_id: CLI_OAUTH_CLIENT_ID,
77
+ resource: apiResource(baseUrl),
78
+ scope: CLI_OAUTH_SCOPES.join(" ")
79
+ });
80
+ const {
81
+ device_code: deviceCode,
82
+ expires_in: expiresIn,
83
+ interval,
84
+ user_code: userCode,
85
+ verification_uri: verificationUri,
86
+ verification_uri_complete: verificationUriComplete
87
+ } = data;
88
+ if (!isJsonString(deviceCode) || !isJsonString(userCode) || !isJsonString(verificationUri)) {
89
+ throw new OAuthError("server_error", "malformed device authorization response");
90
+ }
91
+ return {
92
+ deviceCode,
93
+ expiresIn: isJsonNumber(expiresIn) ? expiresIn : 600,
94
+ interval: isJsonNumber(interval) ? interval : 5,
95
+ userCode,
96
+ verificationUri,
97
+ verificationUriComplete: isJsonString(verificationUriComplete) ? verificationUriComplete : verificationUri
98
+ };
99
+ };
100
+ var toConfig = (baseUrl, data, previousRefresh) => {
101
+ const { access_token: token, expires_in: expiresIn, refresh_token: refreshToken } = data;
102
+ if (!isJsonString(token)) {
103
+ throw new OAuthError("server_error", "token response carries no access_token");
104
+ }
105
+ return {
106
+ baseUrl,
107
+ expiresAt: isJsonNumber(expiresIn) ? Date.now() + expiresIn * 1e3 : void 0,
108
+ refreshToken: isJsonString(refreshToken) ? refreshToken : previousRefresh,
109
+ token
110
+ };
111
+ };
112
+ var pollDeviceToken = async (baseUrl, deviceCode) => toConfig(
113
+ baseUrl,
114
+ await postForm(authUrl(baseUrl, "/oauth2/token"), {
115
+ client_id: CLI_OAUTH_CLIENT_ID,
116
+ device_code: deviceCode,
117
+ grant_type: DEVICE_CODE_GRANT_TYPE
118
+ })
119
+ );
120
+ var needsRefresh = (config, now = Date.now()) => Boolean(config.refreshToken && config.expiresAt && config.expiresAt - EXPIRY_MARGIN_MS <= now);
121
+ var refresh = async (config) => {
122
+ const next = toConfig(
123
+ config.baseUrl,
124
+ await postForm(authUrl(config.baseUrl, "/oauth2/token"), {
125
+ client_id: CLI_OAUTH_CLIENT_ID,
126
+ grant_type: "refresh_token",
127
+ refresh_token: config.refreshToken,
128
+ resource: apiResource(config.baseUrl)
129
+ }),
130
+ config.refreshToken
131
+ );
132
+ saveConfig(next);
133
+ return next;
134
+ };
135
+ var refreshing = null;
136
+ var getAccessToken = async () => {
137
+ if (process.env.VG_TOKEN) {
138
+ return process.env.VG_TOKEN;
139
+ }
140
+ const config = getConfig();
141
+ if (!config) {
142
+ return null;
143
+ }
144
+ if (!needsRefresh(config) || !config.refreshToken) {
145
+ return config.token;
146
+ }
147
+ refreshing ??= refresh({ ...config, refreshToken: config.refreshToken });
148
+ try {
149
+ const next = await refreshing;
150
+ return next.token;
151
+ } catch (error) {
152
+ if (error instanceof OAuthError && error.code === "invalid_grant") {
153
+ throw new Error("Your login has expired or was disconnected. Run `vg login` again.", {
154
+ cause: error
155
+ });
156
+ }
157
+ throw error;
158
+ } finally {
159
+ refreshing = null;
160
+ }
161
+ };
162
+ var revokeLogin = async (config) => {
163
+ if (!config.refreshToken) {
164
+ return;
165
+ }
166
+ try {
167
+ await postForm(authUrl(config.baseUrl, "/oauth2/revoke"), {
168
+ client_id: CLI_OAUTH_CLIENT_ID,
169
+ token: config.refreshToken,
170
+ token_type_hint: "refresh_token"
171
+ });
172
+ } catch {
173
+ }
174
+ };
175
+
176
+ export {
177
+ CLI_VERSION_HEADER,
178
+ OAuthError,
179
+ requestDeviceCode,
180
+ pollDeviceToken,
181
+ getAccessToken,
182
+ revokeLogin
183
+ };