@astrojs/db 0.4.1 → 0.6.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 (57) hide show
  1. package/dist/core/cli/commands/execute/index.d.ts +8 -0
  2. package/dist/core/cli/commands/execute/index.js +32 -0
  3. package/dist/core/cli/commands/link/index.d.ts +20 -8
  4. package/dist/core/cli/commands/link/index.js +191 -31
  5. package/dist/core/cli/commands/login/index.d.ts +4 -2
  6. package/dist/core/cli/commands/login/index.js +31 -22
  7. package/dist/core/cli/commands/logout/index.d.ts +1 -6
  8. package/dist/core/cli/commands/logout/index.js +1 -1
  9. package/dist/core/cli/commands/push/index.d.ts +4 -2
  10. package/dist/core/cli/commands/push/index.js +30 -170
  11. package/dist/core/cli/commands/shell/index.d.ts +4 -2
  12. package/dist/core/cli/commands/shell/index.js +3 -1
  13. package/dist/core/cli/commands/verify/index.d.ts +4 -2
  14. package/dist/core/cli/commands/verify/index.js +23 -37
  15. package/dist/core/cli/index.d.ts +1 -1
  16. package/dist/core/cli/index.js +26 -17
  17. package/dist/core/cli/migration-queries.d.ts +8 -13
  18. package/dist/core/cli/migration-queries.js +65 -121
  19. package/dist/core/consts.d.ts +2 -0
  20. package/dist/core/consts.js +4 -0
  21. package/dist/core/errors.d.ts +9 -7
  22. package/dist/core/errors.js +44 -43
  23. package/dist/core/integration/file-url.js +2 -5
  24. package/dist/core/integration/index.js +56 -112
  25. package/dist/core/integration/typegen.js +3 -13
  26. package/dist/core/integration/vite-plugin-db.d.ts +9 -5
  27. package/dist/core/integration/vite-plugin-db.js +66 -23
  28. package/dist/core/integration/vite-plugin-inject-env-ts.d.ts +1 -1
  29. package/dist/core/load-file.d.ts +31 -0
  30. package/dist/core/load-file.js +98 -0
  31. package/dist/core/tokens.js +1 -1
  32. package/dist/core/types.d.ts +1148 -5306
  33. package/dist/core/types.js +19 -85
  34. package/dist/core/utils.d.ts +1 -0
  35. package/dist/core/utils.js +4 -0
  36. package/dist/index.d.ts +2 -3
  37. package/dist/index.js +3 -5
  38. package/dist/runtime/config.d.ts +147 -0
  39. package/dist/runtime/config.js +42 -0
  40. package/dist/runtime/db-client.d.ts +2 -9
  41. package/dist/runtime/db-client.js +8 -39
  42. package/dist/runtime/index.d.ts +5 -4
  43. package/dist/runtime/index.js +12 -10
  44. package/dist/{core → runtime}/queries.d.ts +20 -17
  45. package/dist/{core → runtime}/queries.js +67 -91
  46. package/dist/runtime/types.d.ts +3 -3
  47. package/dist/utils.d.ts +1 -0
  48. package/dist/utils.js +4 -0
  49. package/index.d.ts +5 -3
  50. package/package.json +20 -5
  51. package/config-augment.d.ts +0 -4
  52. package/dist/core/cli/commands/gen/index.d.ts +0 -6
  53. package/dist/core/cli/commands/gen/index.js +0 -39
  54. package/dist/core/cli/migrations.d.ts +0 -34
  55. package/dist/core/cli/migrations.js +0 -129
  56. package/dist/core/integration/load-astro-config.d.ts +0 -6
  57. package/dist/core/integration/load-astro-config.js +0 -79
@@ -0,0 +1,8 @@
1
+ import type { AstroConfig } from 'astro';
2
+ import type { Arguments } from 'yargs-parser';
3
+ import { type DBConfig } from '../../../types.js';
4
+ export declare function cmd({ astroConfig, dbConfig, flags, }: {
5
+ astroConfig: AstroConfig;
6
+ dbConfig: DBConfig;
7
+ flags: Arguments;
8
+ }): Promise<void>;
@@ -0,0 +1,32 @@
1
+ import { existsSync } from "node:fs";
2
+ import { FILE_NOT_FOUND_ERROR, MISSING_EXECUTE_PATH_ERROR } from "../../../errors.js";
3
+ import { getStudioVirtualModContents } from "../../../integration/vite-plugin-db.js";
4
+ import { bundleFile, importBundledFile } from "../../../load-file.js";
5
+ import { getManagedAppTokenOrExit } from "../../../tokens.js";
6
+ import {} from "../../../types.js";
7
+ async function cmd({
8
+ astroConfig,
9
+ dbConfig,
10
+ flags
11
+ }) {
12
+ const filePath = flags._[4];
13
+ if (typeof filePath !== "string") {
14
+ console.error(MISSING_EXECUTE_PATH_ERROR);
15
+ process.exit(1);
16
+ }
17
+ const fileUrl = new URL(filePath, astroConfig.root);
18
+ if (!existsSync(fileUrl)) {
19
+ console.error(FILE_NOT_FOUND_ERROR(filePath));
20
+ process.exit(1);
21
+ }
22
+ const appToken = await getManagedAppTokenOrExit(flags.token);
23
+ const virtualModContents = getStudioVirtualModContents({
24
+ tables: dbConfig.tables ?? {},
25
+ appToken: appToken.token
26
+ });
27
+ const { code } = await bundleFile({ virtualModContents, root: astroConfig.root, fileUrl });
28
+ await importBundledFile({ code, root: astroConfig.root });
29
+ }
30
+ export {
31
+ cmd
32
+ };
@@ -1,8 +1,20 @@
1
- import type { AstroConfig } from 'astro';
2
- import type { Arguments } from 'yargs-parser';
3
- export declare function cmd({ flags }: {
4
- config: AstroConfig;
5
- flags: Arguments;
6
- }): Promise<void>;
7
- export declare function promptProjectName(defaultName?: string): Promise<string>;
8
- export declare function promptWorkspaceName(defaultName?: string): Promise<string>;
1
+ export declare function cmd(): Promise<void>;
2
+ export declare function createNewProject({ workspaceId, name, region, }: {
3
+ workspaceId: string;
4
+ name: string;
5
+ region: string;
6
+ }): Promise<{
7
+ id: string;
8
+ idName: string;
9
+ }>;
10
+ export declare function promptExistingProjectName({ workspaceId }: {
11
+ workspaceId: string;
12
+ }): Promise<{
13
+ id: string;
14
+ idName: string;
15
+ }>;
16
+ export declare function promptBegin(): Promise<void>;
17
+ export declare function promptLinkExisting(): Promise<boolean>;
18
+ export declare function promptLinkNew(): Promise<boolean>;
19
+ export declare function promptNewProjectName(): Promise<string>;
20
+ export declare function promptNewProjectRegion(): Promise<string>;
@@ -1,29 +1,94 @@
1
1
  import { mkdir, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { basename } from "node:path";
4
+ import { slug } from "github-slugger";
2
5
  import { bgRed, cyan } from "kleur/colors";
6
+ import ora from "ora";
3
7
  import prompts from "prompts";
8
+ import { MISSING_SESSION_ID_ERROR } from "../../../errors.js";
4
9
  import { PROJECT_ID_FILE, getSessionIdFromFile } from "../../../tokens.js";
5
10
  import { getAstroStudioUrl } from "../../../utils.js";
6
- import { MISSING_SESSION_ID_ERROR } from "../../../errors.js";
7
- async function cmd({ flags }) {
8
- const linkUrl = new URL(getAstroStudioUrl() + "/auth/cli/link");
11
+ async function cmd() {
9
12
  const sessionToken = await getSessionIdFromFile();
10
13
  if (!sessionToken) {
11
14
  console.error(MISSING_SESSION_ID_ERROR);
12
15
  process.exit(1);
13
16
  }
14
- let body = { id: flags._[4] };
15
- if (!body.id) {
16
- const workspaceIdName = await promptWorkspaceName();
17
- const projectIdName = await promptProjectName();
18
- body = { projectIdName, workspaceIdName };
17
+ const getWorkspaceIdAsync = getWorkspaceId();
18
+ await promptBegin();
19
+ const isLinkExisting = await promptLinkExisting();
20
+ if (isLinkExisting) {
21
+ const workspaceId = await getWorkspaceIdAsync;
22
+ const existingProjectData = await promptExistingProjectName({ workspaceId });
23
+ return await linkProject(existingProjectData.id);
24
+ }
25
+ const isLinkNew = await promptLinkNew();
26
+ if (isLinkNew) {
27
+ const workspaceId = await getWorkspaceIdAsync;
28
+ const newProjectName = await promptNewProjectName();
29
+ const newProjectRegion = await promptNewProjectRegion();
30
+ const spinner = ora("Creating new project...").start();
31
+ const newProjectData = await createNewProject({
32
+ workspaceId,
33
+ name: newProjectName,
34
+ region: newProjectRegion
35
+ });
36
+ await new Promise((r) => setTimeout(r, 4e3));
37
+ spinner.succeed("Project created!");
38
+ return await linkProject(newProjectData.id);
19
39
  }
40
+ }
41
+ async function linkProject(id) {
42
+ await mkdir(new URL(".", PROJECT_ID_FILE), { recursive: true });
43
+ await writeFile(PROJECT_ID_FILE, `${id}`);
44
+ console.info("Project linked.");
45
+ }
46
+ async function getWorkspaceId() {
47
+ const linkUrl = new URL(getAstroStudioUrl() + "/api/cli/workspaces.list");
48
+ const response = await fetch(linkUrl, {
49
+ method: "POST",
50
+ headers: {
51
+ Authorization: `Bearer ${await getSessionIdFromFile()}`,
52
+ "Content-Type": "application/json"
53
+ }
54
+ });
55
+ if (!response.ok) {
56
+ if (response.status === 401) {
57
+ console.error(
58
+ `${bgRed("Unauthorized")}
59
+
60
+ Are you logged in?
61
+ Run ${cyan(
62
+ "astro db login"
63
+ )} to authenticate and then try linking again.
64
+
65
+ `
66
+ );
67
+ process.exit(1);
68
+ }
69
+ console.error(`Failed to fetch user workspace: ${response.status} ${response.statusText}`);
70
+ process.exit(1);
71
+ }
72
+ const { data, success } = await response.json();
73
+ if (!success) {
74
+ console.error(`Failed to fetch user's workspace.`);
75
+ process.exit(1);
76
+ }
77
+ return data[0].id;
78
+ }
79
+ async function createNewProject({
80
+ workspaceId,
81
+ name,
82
+ region
83
+ }) {
84
+ const linkUrl = new URL(getAstroStudioUrl() + "/api/cli/projects.create");
20
85
  const response = await fetch(linkUrl, {
21
86
  method: "POST",
22
87
  headers: {
23
88
  Authorization: `Bearer ${await getSessionIdFromFile()}`,
24
89
  "Content-Type": "application/json"
25
90
  },
26
- body: JSON.stringify(body)
91
+ body: JSON.stringify({ workspaceId, name, region })
27
92
  });
28
93
  if (!response.ok) {
29
94
  if (response.status === 401) {
@@ -39,40 +104,135 @@ async function cmd({ flags }) {
39
104
  );
40
105
  process.exit(1);
41
106
  }
42
- console.error(`Failed to link project: ${response.status} ${response.statusText}`);
107
+ console.error(`Failed to create project: ${response.status} ${response.statusText}`);
43
108
  process.exit(1);
44
109
  }
45
- const { data } = await response.json();
46
- await mkdir(new URL(".", PROJECT_ID_FILE), { recursive: true });
47
- await writeFile(PROJECT_ID_FILE, `${data.id}`);
48
- console.info("Project linked.");
110
+ const { data, success } = await response.json();
111
+ if (!success) {
112
+ console.error(`Failed to create project.`);
113
+ process.exit(1);
114
+ }
115
+ return { id: data.id, idName: data.idName };
49
116
  }
50
- async function promptProjectName(defaultName) {
51
- const { projectName } = await prompts({
52
- type: "text",
53
- name: "projectName",
54
- message: "Project ID",
55
- initial: defaultName
117
+ async function promptExistingProjectName({ workspaceId }) {
118
+ const linkUrl = new URL(getAstroStudioUrl() + "/api/cli/projects.list");
119
+ const response = await fetch(linkUrl, {
120
+ method: "POST",
121
+ headers: {
122
+ Authorization: `Bearer ${await getSessionIdFromFile()}`,
123
+ "Content-Type": "application/json"
124
+ },
125
+ body: JSON.stringify({ workspaceId })
126
+ });
127
+ if (!response.ok) {
128
+ if (response.status === 401) {
129
+ console.error(
130
+ `${bgRed("Unauthorized")}
131
+
132
+ Are you logged in?
133
+ Run ${cyan(
134
+ "astro db login"
135
+ )} to authenticate and then try linking again.
136
+
137
+ `
138
+ );
139
+ process.exit(1);
140
+ }
141
+ console.error(`Failed to fetch projects: ${response.status} ${response.statusText}`);
142
+ process.exit(1);
143
+ }
144
+ const { data, success } = await response.json();
145
+ if (!success) {
146
+ console.error(`Failed to fetch projects.`);
147
+ process.exit(1);
148
+ }
149
+ const { projectId } = await prompts({
150
+ type: "autocomplete",
151
+ name: "projectId",
152
+ message: "What is your project name?",
153
+ limit: 5,
154
+ choices: data.map((p) => ({ title: p.name, value: p.id }))
56
155
  });
57
- if (typeof projectName !== "string") {
156
+ if (typeof projectId !== "string") {
157
+ console.log("Canceled.");
58
158
  process.exit(0);
59
159
  }
60
- return projectName;
160
+ const selectedProjectData = data.find((p) => p.id === projectId);
161
+ return selectedProjectData;
61
162
  }
62
- async function promptWorkspaceName(defaultName) {
63
- const { workspaceName } = await prompts({
163
+ async function promptBegin() {
164
+ const prettyCwd = process.cwd().replace(homedir(), "~");
165
+ const { begin } = await prompts({
166
+ type: "confirm",
167
+ name: "begin",
168
+ message: `Link "${prettyCwd}" with Astro Studio?`,
169
+ initial: true
170
+ });
171
+ if (!begin) {
172
+ console.log("Canceled.");
173
+ process.exit(0);
174
+ }
175
+ }
176
+ async function promptLinkExisting() {
177
+ const { linkExisting } = await prompts({
178
+ type: "confirm",
179
+ name: "linkExisting",
180
+ message: `Link with an existing project in Astro Studio?`,
181
+ initial: true
182
+ });
183
+ return !!linkExisting;
184
+ }
185
+ async function promptLinkNew() {
186
+ const { linkNew } = await prompts({
187
+ type: "confirm",
188
+ name: "linkNew",
189
+ message: `Create a new project in Astro Studio?`,
190
+ initial: true
191
+ });
192
+ if (!linkNew) {
193
+ console.log("Canceled.");
194
+ process.exit(0);
195
+ }
196
+ return true;
197
+ }
198
+ async function promptNewProjectName() {
199
+ const { newProjectName } = await prompts({
64
200
  type: "text",
65
- name: "workspaceName",
66
- message: "Workspace ID",
67
- initial: defaultName
201
+ name: "newProjectName",
202
+ message: `What is your new project's name?`,
203
+ initial: basename(process.cwd()),
204
+ format: (val) => slug(val)
205
+ });
206
+ if (!newProjectName) {
207
+ console.log("Canceled.");
208
+ process.exit(0);
209
+ }
210
+ return newProjectName;
211
+ }
212
+ async function promptNewProjectRegion() {
213
+ const { newProjectRegion } = await prompts({
214
+ type: "select",
215
+ name: "newProjectRegion",
216
+ message: `Where should your new database live?`,
217
+ choices: [
218
+ { title: "North America (East)", value: "NorthAmericaEast" },
219
+ { title: "North America (West)", value: "NorthAmericaWest" }
220
+ ],
221
+ initial: 0
68
222
  });
69
- if (typeof workspaceName !== "string") {
223
+ if (!newProjectRegion) {
224
+ console.log("Canceled.");
70
225
  process.exit(0);
71
226
  }
72
- return workspaceName;
227
+ return newProjectRegion;
73
228
  }
74
229
  export {
75
230
  cmd,
76
- promptProjectName,
77
- promptWorkspaceName
231
+ createNewProject,
232
+ promptBegin,
233
+ promptExistingProjectName,
234
+ promptLinkExisting,
235
+ promptLinkNew,
236
+ promptNewProjectName,
237
+ promptNewProjectRegion
78
238
  };
@@ -1,6 +1,8 @@
1
1
  import type { AstroConfig } from 'astro';
2
2
  import type { Arguments } from 'yargs-parser';
3
- export declare function cmd({ flags }: {
4
- config: AstroConfig;
3
+ import type { DBConfig } from '../../../types.js';
4
+ export declare function cmd({ flags, }: {
5
+ astroConfig: AstroConfig;
6
+ dbConfig: DBConfig;
5
7
  flags: Arguments;
6
8
  }): Promise<void>;
@@ -1,41 +1,50 @@
1
- import { cyan } from "kleur/colors";
2
1
  import { mkdir, writeFile } from "node:fs/promises";
3
- import { createServer } from "node:http";
4
- import ora from "ora";
5
- import { getAstroStudioUrl } from "../../../utils.js";
2
+ import { createServer as _createServer } from "node:http";
3
+ import { listen } from "async-listen";
4
+ import { cyan } from "kleur/colors";
6
5
  import open from "open";
6
+ import ora from "ora";
7
7
  import { SESSION_LOGIN_FILE } from "../../../tokens.js";
8
- function serveAndResolveSession() {
8
+ import { getAstroStudioUrl } from "../../../utils.js";
9
+ async function createServer() {
9
10
  let resolve, reject;
10
- const sessionPromise = new Promise((_resolve, _reject) => {
11
- resolve = _resolve;
12
- reject = _reject;
13
- });
14
- const server = createServer((req, res) => {
15
- res.writeHead(200);
16
- res.end();
11
+ const server = _createServer((req, res) => {
17
12
  const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
18
- const session = url.searchParams.get("session");
19
- if (!session) {
20
- reject();
13
+ const sessionParam = url.searchParams.get("session");
14
+ res.statusCode = 302;
15
+ if (!sessionParam) {
16
+ res.setHeader("location", getAstroStudioUrl() + "/auth/cli/error");
17
+ reject(new Error("Failed to log in"));
21
18
  } else {
22
- resolve(session);
19
+ res.setHeader("location", getAstroStudioUrl() + "/auth/cli/success");
20
+ resolve(sessionParam);
23
21
  }
24
- }).listen(5710, "localhost");
25
- return sessionPromise.finally(() => {
22
+ res.end();
23
+ });
24
+ const { port } = await listen(server, 0, "127.0.0.1");
25
+ const serverUrl = `http://localhost:${port}`;
26
+ const sessionPromise = new Promise((_resolve, _reject) => {
27
+ resolve = _resolve;
28
+ reject = _reject;
29
+ }).finally(() => {
26
30
  server.closeAllConnections();
27
31
  server.close();
28
32
  });
33
+ return { url: serverUrl, promise: sessionPromise };
29
34
  }
30
- async function cmd({ flags }) {
35
+ async function cmd({
36
+ flags
37
+ }) {
31
38
  let session = flags.session;
32
- const loginUrl = getAstroStudioUrl() + "/auth/cli";
33
39
  if (!session) {
34
- console.log(`Opening ${cyan(loginUrl)} in your browser...`);
40
+ const { url, promise } = await createServer();
41
+ const loginUrl = getAstroStudioUrl() + "/auth/cli/login?returnTo=" + encodeURIComponent(url);
42
+ console.log(`Opening the following URL in your browser...`);
43
+ console.log(cyan(loginUrl));
35
44
  console.log(`If something goes wrong, copy-and-paste the URL into your browser.`);
36
45
  open(loginUrl);
37
46
  const spinner = ora("Waiting for confirmation...");
38
- session = await serveAndResolveSession();
47
+ session = await promise;
39
48
  spinner.succeed("Successfully logged in!");
40
49
  }
41
50
  await mkdir(new URL(".", SESSION_LOGIN_FILE), { recursive: true });
@@ -1,6 +1 @@
1
- import type { AstroConfig } from 'astro';
2
- import type { Arguments } from 'yargs-parser';
3
- export declare function cmd({}: {
4
- config: AstroConfig;
5
- flags: Arguments;
6
- }): Promise<void>;
1
+ export declare function cmd(): Promise<void>;
@@ -1,6 +1,6 @@
1
1
  import { unlink } from "node:fs/promises";
2
2
  import { SESSION_LOGIN_FILE } from "../../../tokens.js";
3
- async function cmd({}) {
3
+ async function cmd() {
4
4
  await unlink(SESSION_LOGIN_FILE);
5
5
  console.log("Successfully logged out of Astro Studio.");
6
6
  }
@@ -1,6 +1,8 @@
1
1
  import type { AstroConfig } from 'astro';
2
2
  import type { Arguments } from 'yargs-parser';
3
- export declare function cmd({ config, flags }: {
4
- config: AstroConfig;
3
+ import { type DBConfig } from '../../../types.js';
4
+ export declare function cmd({ dbConfig, flags, }: {
5
+ astroConfig: AstroConfig;
6
+ dbConfig: DBConfig;
5
7
  flags: Arguments;
6
8
  }): Promise<void>;