@astrojs/db 0.14.0 → 0.14.2

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.
@@ -1,3 +1,4 @@
1
+ import { type ManagedAppToken } from '@astrojs/studio';
1
2
  import type { AstroConfig, AstroIntegration } from 'astro';
2
3
  import './types.js';
3
4
  export type VitePlugin = Required<AstroConfig['vite']>['plugins'][number];
@@ -7,6 +8,7 @@ export type RemoteDatabaseInfo = {
7
8
  url: string;
8
9
  };
9
10
  export declare function getRemoteDatabaseInfo(): RemoteDatabaseInfo;
11
+ export declare function getManagedRemoteToken(token?: string, dbInfo?: RemoteDatabaseInfo): Promise<ManagedAppToken>;
10
12
  export declare function getDbDirectoryUrl(root: URL | string): URL;
11
13
  export declare function defineDbIntegration(integration: AstroIntegration): AstroIntegration;
12
14
  export type Result<T> = {
@@ -1,5 +1,4 @@
1
1
  import { existsSync } from "node:fs";
2
- import { getManagedAppTokenOrExit } from "@astrojs/studio";
3
2
  import { LibsqlError } from "@libsql/client";
4
3
  import { green } from "kleur/colors";
5
4
  import {
@@ -13,6 +12,7 @@ import {
13
12
  getStudioVirtualModContents
14
13
  } from "../../../integration/vite-plugin-db.js";
15
14
  import { bundleFile, importBundledFile } from "../../../load-file.js";
15
+ import { getManagedRemoteToken } from "../../../utils.js";
16
16
  async function cmd({
17
17
  astroConfig,
18
18
  dbConfig,
@@ -30,7 +30,7 @@ async function cmd({
30
30
  }
31
31
  let virtualModContents;
32
32
  if (flags.remote) {
33
- const appToken = await getManagedAppTokenOrExit(flags.token);
33
+ const appToken = await getManagedRemoteToken(flags.token);
34
34
  virtualModContents = getStudioVirtualModContents({
35
35
  tables: dbConfig.tables ?? {},
36
36
  appToken: appToken.token,
@@ -1,10 +1,12 @@
1
- import { getManagedAppTokenOrExit } from "@astrojs/studio";
2
1
  import { sql } from "drizzle-orm";
3
2
  import prompts from "prompts";
4
3
  import { createRemoteDatabaseClient } from "../../../../runtime/index.js";
5
4
  import { safeFetch } from "../../../../runtime/utils.js";
6
5
  import { MIGRATION_VERSION } from "../../../consts.js";
7
- import { getRemoteDatabaseInfo } from "../../../utils.js";
6
+ import {
7
+ getManagedRemoteToken,
8
+ getRemoteDatabaseInfo
9
+ } from "../../../utils.js";
8
10
  import {
9
11
  createCurrentSnapshot,
10
12
  createEmptySnapshot,
@@ -18,8 +20,12 @@ async function cmd({
18
20
  }) {
19
21
  const isDryRun = flags.dryRun;
20
22
  const isForceReset = flags.forceReset;
21
- const appToken = await getManagedAppTokenOrExit(flags.token);
22
- const productionSnapshot = await getProductionCurrentSnapshot({ appToken: appToken.token });
23
+ const dbInfo = getRemoteDatabaseInfo();
24
+ const appToken = await getManagedRemoteToken(flags.token, dbInfo);
25
+ const productionSnapshot = await getProductionCurrentSnapshot({
26
+ dbInfo,
27
+ appToken: appToken.token
28
+ });
23
29
  const currentSnapshot = createCurrentSnapshot(dbConfig);
24
30
  const isFromScratch = !productionSnapshot;
25
31
  const { queries: migrationQueries, confirmations } = await getMigrationQueries({
@@ -54,6 +60,7 @@ async function cmd({
54
60
  console.log(`Pushing database schema updates...`);
55
61
  await pushSchema({
56
62
  statements: migrationQueries,
63
+ dbInfo,
57
64
  appToken: appToken.token,
58
65
  isDryRun,
59
66
  currentSnapshot
@@ -64,6 +71,7 @@ async function cmd({
64
71
  }
65
72
  async function pushSchema({
66
73
  statements,
74
+ dbInfo,
67
75
  appToken,
68
76
  isDryRun,
69
77
  currentSnapshot
@@ -77,7 +85,6 @@ async function pushSchema({
77
85
  console.info("[DRY RUN] Batch query:", JSON.stringify(requestBody, null, 2));
78
86
  return new Response(null, { status: 200 });
79
87
  }
80
- const dbInfo = getRemoteDatabaseInfo();
81
88
  return dbInfo.type === "studio" ? pushToStudio(requestBody, appToken, dbInfo.url) : pushToDb(requestBody, appToken, dbInfo.url);
82
89
  }
83
90
  async function pushToDb(requestBody, appToken, remoteUrl) {
@@ -1,4 +1,3 @@
1
- import { getManagedAppTokenOrExit } from "@astrojs/studio";
2
1
  import { sql } from "drizzle-orm";
3
2
  import {
4
3
  createLocalDatabaseClient,
@@ -7,7 +6,7 @@ import {
7
6
  import { normalizeDatabaseUrl } from "../../../../runtime/index.js";
8
7
  import { DB_PATH } from "../../../consts.js";
9
8
  import { SHELL_QUERY_MISSING_ERROR } from "../../../errors.js";
10
- import { getAstroEnv, getRemoteDatabaseInfo } from "../../../utils.js";
9
+ import { getAstroEnv, getManagedRemoteToken, getRemoteDatabaseInfo } from "../../../utils.js";
11
10
  async function cmd({
12
11
  flags,
13
12
  astroConfig
@@ -19,7 +18,7 @@ async function cmd({
19
18
  }
20
19
  const dbInfo = getRemoteDatabaseInfo();
21
20
  if (flags.remote) {
22
- const appToken = await getManagedAppTokenOrExit(flags.token);
21
+ const appToken = await getManagedRemoteToken(flags.token, dbInfo);
23
22
  const db = createRemoteDatabaseClient({
24
23
  dbType: dbInfo.type,
25
24
  remoteUrl: dbInfo.url,
@@ -1,4 +1,4 @@
1
- import { getManagedAppTokenOrExit } from "@astrojs/studio";
1
+ import { getManagedRemoteToken, getRemoteDatabaseInfo } from "../../../utils.js";
2
2
  import {
3
3
  createCurrentSnapshot,
4
4
  createEmptySnapshot,
@@ -11,8 +11,12 @@ async function cmd({
11
11
  flags
12
12
  }) {
13
13
  const isJson = flags.json;
14
- const appToken = await getManagedAppTokenOrExit(flags.token);
15
- const productionSnapshot = await getProductionCurrentSnapshot({ appToken: appToken.token });
14
+ const dbInfo = getRemoteDatabaseInfo();
15
+ const appToken = await getManagedRemoteToken(flags.token, dbInfo);
16
+ const productionSnapshot = await getProductionCurrentSnapshot({
17
+ dbInfo,
18
+ appToken: appToken.token
19
+ });
16
20
  const currentSnapshot = createCurrentSnapshot(dbConfig);
17
21
  const { queries: migrationQueries, confirmations } = await getMigrationQueries({
18
22
  oldSnapshot: productionSnapshot || createEmptySnapshot(),
@@ -1,4 +1,5 @@
1
1
  import type { DBConfig, DBSnapshot, ResolvedDBTable } from '../types.js';
2
+ import type { RemoteDatabaseInfo } from '../utils.js';
2
3
  export declare function getMigrationQueries({ oldSnapshot, newSnapshot, reset, }: {
3
4
  oldSnapshot: DBSnapshot;
4
5
  newSnapshot: DBSnapshot;
@@ -16,6 +17,7 @@ export declare function getTableChangeQueries({ tableName, oldTable, newTable, }
16
17
  confirmations: string[];
17
18
  }>;
18
19
  export declare function getProductionCurrentSnapshot(options: {
20
+ dbInfo: RemoteDatabaseInfo;
19
21
  appToken: string;
20
22
  }): Promise<DBSnapshot | undefined>;
21
23
  export declare function createCurrentSnapshot({ tables }: DBConfig): DBSnapshot;
@@ -1,9 +1,10 @@
1
+ import { stripVTControlCharacters } from "node:util";
2
+ import { LibsqlError } from "@libsql/client";
1
3
  import deepDiff from "deep-diff";
2
4
  import { sql } from "drizzle-orm";
3
5
  import { SQLiteAsyncDialect } from "drizzle-orm/sqlite-core";
4
6
  import * as color from "kleur/colors";
5
7
  import { customAlphabet } from "nanoid";
6
- import stripAnsi from "strip-ansi";
7
8
  import { hasPrimaryKey } from "../../runtime/index.js";
8
9
  import { createRemoteDatabaseClient } from "../../runtime/index.js";
9
10
  import { isSerializedSQL } from "../../runtime/types.js";
@@ -20,7 +21,6 @@ import {
20
21
  schemaTypeToSqlType
21
22
  } from "../queries.js";
22
23
  import { columnSchema } from "../schemas.js";
23
- import { getRemoteDatabaseInfo } from "../utils.js";
24
24
  const sqlite = new SQLiteAsyncDialect();
25
25
  const genTempTableName = customAlphabet("abcdefghijklmnopqrstuvwxyz", 10);
26
26
  async function getMigrationQueries({
@@ -305,8 +305,7 @@ function hasRuntimeDefault(column) {
305
305
  return !!(column.schema.default && isSerializedSQL(column.schema.default));
306
306
  }
307
307
  function getProductionCurrentSnapshot(options) {
308
- const dbInfo = getRemoteDatabaseInfo();
309
- return dbInfo.type === "studio" ? getStudioCurrentSnapshot(options.appToken, dbInfo.url) : getDbCurrentSnapshot(options.appToken, dbInfo.url);
308
+ return options.dbInfo.type === "studio" ? getStudioCurrentSnapshot(options.appToken, options.dbInfo.url) : getDbCurrentSnapshot(options.appToken, options.dbInfo.url);
310
309
  }
311
310
  async function getDbCurrentSnapshot(appToken, remoteUrl) {
312
311
  const client = createRemoteDatabaseClient({
@@ -321,7 +320,13 @@ async function getDbCurrentSnapshot(appToken, remoteUrl) {
321
320
  );
322
321
  return JSON.parse(res.snapshot);
323
322
  } catch (error) {
324
- if (error.code === "SQLITE_UNKNOWN") {
323
+ if (error instanceof LibsqlError && // If the schema was never pushed to the database yet the table won't exist.
324
+ // Treat a missing snapshot table as an empty table.
325
+ // When connecting to a remote database in that condition
326
+ // the query will fail with the following error code and message.
327
+ (error.code === "SQLITE_UNKNOWN" && error.message === "SQLITE_UNKNOWN: SQLite error: no such table: _astro_db_snapshot" || // When connecting to a local or in-memory database that does not have a snapshot table yet
328
+ // the query will fail with the following error code and message.
329
+ error.code === "SQLITE_ERROR" && error.message === "SQLITE_ERROR: no such table: _astro_db_snapshot")) {
325
330
  return;
326
331
  }
327
332
  throw error;
@@ -378,7 +383,7 @@ function formatDataLossMessage(confirmations, isColor = true) {
378
383
  );
379
384
  let finalMessage = messages.join("\n");
380
385
  if (!isColor) {
381
- finalMessage = stripAnsi(finalMessage);
386
+ finalMessage = stripVTControlCharacters(finalMessage);
382
387
  }
383
388
  return finalMessage;
384
389
  }
@@ -27,7 +27,7 @@ function printHelp({
27
27
  message.push(
28
28
  linebreak(),
29
29
  ` ${bgGreen(black(` ${commandName} `))} ${green(
30
- `v${"0.14.0"}`
30
+ `v${"0.14.2"}`
31
31
  )} ${headline}`
32
32
  );
33
33
  }
@@ -2,7 +2,6 @@ import { existsSync } from "node:fs";
2
2
  import { mkdir, writeFile } from "node:fs/promises";
3
3
  import { dirname } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
- import { getManagedAppTokenOrExit } from "@astrojs/studio";
6
5
  import { LibsqlError } from "@libsql/client";
7
6
  import { blue, yellow } from "kleur/colors";
8
7
  import {
@@ -16,7 +15,7 @@ import { CONFIG_FILE_NAMES, DB_PATH } from "../consts.js";
16
15
  import { EXEC_DEFAULT_EXPORT_ERROR, EXEC_ERROR } from "../errors.js";
17
16
  import { resolveDbConfig } from "../load-file.js";
18
17
  import { SEED_DEV_FILE_NAME } from "../queries.js";
19
- import { getDbDirectoryUrl } from "../utils.js";
18
+ import { getDbDirectoryUrl, getManagedRemoteToken } from "../utils.js";
20
19
  import { fileURLIntegration } from "./file-url.js";
21
20
  import { getDtsContent } from "./typegen.js";
22
21
  import {
@@ -24,7 +23,7 @@ import {
24
23
  vitePluginDb
25
24
  } from "./vite-plugin-db.js";
26
25
  function astroDBIntegration() {
27
- let connectToStudio = false;
26
+ let connectToRemote = false;
28
27
  let configFileDependencies = [];
29
28
  let root;
30
29
  let appToken;
@@ -57,11 +56,11 @@ function astroDBIntegration() {
57
56
  if (command === "preview") return;
58
57
  let dbPlugin = void 0;
59
58
  const args = parseArgs(process.argv.slice(3));
60
- connectToStudio = process.env.ASTRO_INTERNAL_TEST_REMOTE || args["remote"];
61
- if (connectToStudio) {
62
- appToken = await getManagedAppTokenOrExit();
59
+ connectToRemote = process.env.ASTRO_INTERNAL_TEST_REMOTE || args["remote"];
60
+ if (connectToRemote) {
61
+ appToken = await getManagedRemoteToken();
63
62
  dbPlugin = vitePluginDb({
64
- connectToStudio,
63
+ connectToStudio: connectToRemote,
65
64
  appToken: appToken.token,
66
65
  tables,
67
66
  root: config.root,
@@ -95,7 +94,7 @@ function astroDBIntegration() {
95
94
  seedFiles.get = () => integrationSeedPaths;
96
95
  configFileDependencies = dependencies;
97
96
  const localDbUrl = new URL(DB_PATH, config.root);
98
- if (!connectToStudio && !existsSync(localDbUrl)) {
97
+ if (!connectToRemote && !existsSync(localDbUrl)) {
99
98
  await mkdir(dirname(fileURLToPath(localDbUrl)), { recursive: true });
100
99
  await writeFile(localDbUrl, "");
101
100
  }
@@ -120,9 +119,9 @@ function astroDBIntegration() {
120
119
  });
121
120
  setTimeout(() => {
122
121
  logger.info(
123
- connectToStudio ? "Connected to remote database." : "New local database created."
122
+ connectToRemote ? "Connected to remote database." : "New local database created."
124
123
  );
125
- if (connectToStudio) return;
124
+ if (connectToRemote) return;
126
125
  const localSeedPaths = SEED_DEV_FILE_NAME.map(
127
126
  (name) => new URL(name, getDbDirectoryUrl(root))
128
127
  );
@@ -134,12 +133,12 @@ function astroDBIntegration() {
134
133
  }, 100);
135
134
  },
136
135
  "astro:build:start": async ({ logger }) => {
137
- if (!connectToStudio && !databaseFileEnvDefined() && (output === "server" || output === "hybrid")) {
136
+ if (!connectToRemote && !databaseFileEnvDefined() && (output === "server" || output === "hybrid")) {
138
137
  const message = `Attempting to build without the --remote flag or the ASTRO_DATABASE_FILE environment variable defined. You probably want to pass --remote to astro build.`;
139
138
  const hint = "Learn more connecting to Studio: https://docs.astro.build/en/guides/astro-db/#connect-to-astro-studio";
140
139
  throw new AstroDbError(message, hint);
141
140
  }
142
- logger.info("database: " + (connectToStudio ? yellow("remote") : blue("local database.")));
141
+ logger.info("database: " + (connectToRemote ? yellow("remote") : blue("local database.")));
143
142
  },
144
143
  "astro:build:setup": async ({ vite }) => {
145
144
  tempViteServer = await getTempViteServer({ viteConfig: vite });
@@ -107,7 +107,11 @@ function getStudioVirtualModContents({
107
107
  }
108
108
  function dbUrlArg() {
109
109
  const dbStr = JSON.stringify(dbInfo.url);
110
- return dbInfo.type === "studio" ? `import.meta.env.ASTRO_STUDIO_REMOTE_DB_URL ?? ${dbStr}` : `import.meta.env.ASTRO_DB_REMOTE_URL ?? ${dbStr}`;
110
+ if (isBuild) {
111
+ return dbInfo.type === "studio" ? `import.meta.env.ASTRO_STUDIO_REMOTE_DB_URL ?? ${dbStr}` : `import.meta.env.ASTRO_DB_REMOTE_URL ?? ${dbStr}`;
112
+ } else {
113
+ return dbStr;
114
+ }
111
115
  }
112
116
  return `
113
117
  import {asDrizzleTable, createRemoteDatabaseClient} from ${RUNTIME_IMPORT};
@@ -1,3 +1,4 @@
1
+ import { type ManagedAppToken } from '@astrojs/studio';
1
2
  import type { AstroConfig, AstroIntegration } from 'astro';
2
3
  import './types.js';
3
4
  export type VitePlugin = Required<AstroConfig['vite']>['plugins'][number];
@@ -7,6 +8,7 @@ export type RemoteDatabaseInfo = {
7
8
  url: string;
8
9
  };
9
10
  export declare function getRemoteDatabaseInfo(): RemoteDatabaseInfo;
11
+ export declare function getManagedRemoteToken(token?: string, dbInfo?: RemoteDatabaseInfo): Promise<ManagedAppToken>;
10
12
  export declare function getDbDirectoryUrl(root: URL | string): URL;
11
13
  export declare function defineDbIntegration(integration: AstroIntegration): AstroIntegration;
12
14
  export type Result<T> = {
@@ -1,4 +1,4 @@
1
- import { getAstroStudioEnv } from "@astrojs/studio";
1
+ import { getAstroStudioEnv, getManagedAppTokenOrExit } from "@astrojs/studio";
2
2
  import { loadEnv } from "vite";
3
3
  import "./types.js";
4
4
  function getAstroEnv(envMode = "") {
@@ -23,6 +23,18 @@ function getRemoteDatabaseInfo() {
23
23
  url: "https://db.services.astro.build"
24
24
  };
25
25
  }
26
+ function getManagedRemoteToken(token, dbInfo) {
27
+ dbInfo ??= getRemoteDatabaseInfo();
28
+ if (dbInfo.type === "studio") {
29
+ return getManagedAppTokenOrExit(token);
30
+ }
31
+ const astroEnv = getAstroEnv();
32
+ return Promise.resolve({
33
+ token: token ?? astroEnv.ASTRO_DB_APP_TOKEN,
34
+ renew: () => Promise.resolve(),
35
+ destroy: () => Promise.resolve()
36
+ });
37
+ }
26
38
  function getDbDirectoryUrl(root) {
27
39
  return new URL("db/", root);
28
40
  }
@@ -38,6 +50,7 @@ export {
38
50
  defineDbIntegration,
39
51
  getAstroEnv,
40
52
  getDbDirectoryUrl,
53
+ getManagedRemoteToken,
41
54
  getRemoteDatabaseInfo,
42
55
  mapObject
43
56
  };
@@ -31,15 +31,21 @@ const remoteResultSchema = z.object({
31
31
  });
32
32
  function createRemoteDatabaseClient(options) {
33
33
  const remoteUrl = new URL(options.remoteUrl);
34
- return options.dbType === "studio" ? createStudioDatabaseClient(options.appToken, remoteUrl) : createRemoteLibSQLClient(options.appToken, remoteUrl);
34
+ return options.dbType === "studio" ? createStudioDatabaseClient(options.appToken, remoteUrl) : createRemoteLibSQLClient(options.appToken, remoteUrl, options.remoteUrl.toString());
35
35
  }
36
- function createRemoteLibSQLClient(appToken, remoteDbURL) {
36
+ function createRemoteLibSQLClient(appToken, remoteDbURL, rawUrl) {
37
37
  const options = Object.fromEntries(remoteDbURL.searchParams.entries());
38
38
  remoteDbURL.search = "";
39
+ let url = remoteDbURL.toString();
40
+ if (remoteDbURL.protocol === "memory:") {
41
+ url = ":memory:";
42
+ } else if (remoteDbURL.protocol === "file:" && remoteDbURL.pathname.startsWith("/") && !rawUrl.startsWith("file:/")) {
43
+ url = "file:" + remoteDbURL.pathname.substring(1);
44
+ }
39
45
  const client = createClient({
40
46
  ...options,
41
47
  authToken: appToken,
42
- url: remoteDbURL.protocol === "memory:" ? ":memory:" : remoteDbURL.toString()
48
+ url
43
49
  });
44
50
  return drizzleLibsql(client);
45
51
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrojs/db",
3
- "version": "0.14.0",
3
+ "version": "0.14.2",
4
4
  "description": "Add libSQL and Astro Studio support to your Astro site",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -62,7 +62,7 @@
62
62
  "astro-integration"
63
63
  ],
64
64
  "dependencies": {
65
- "@libsql/client": "^0.10.0",
65
+ "@libsql/client": "^0.14.0",
66
66
  "async-listen": "^3.0.1",
67
67
  "deep-diff": "^1.0.2",
68
68
  "drizzle-orm": "^0.31.2",
@@ -72,7 +72,6 @@
72
72
  "open": "^10.1.0",
73
73
  "ora": "^8.1.0",
74
74
  "prompts": "^2.4.2",
75
- "strip-ansi": "^7.1.0",
76
75
  "yargs-parser": "^21.1.1",
77
76
  "zod": "^3.23.8",
78
77
  "@astrojs/studio": "0.1.1"
@@ -82,9 +81,9 @@
82
81
  "@types/prompts": "^2.4.9",
83
82
  "@types/yargs-parser": "^21.0.3",
84
83
  "cheerio": "1.0.0",
85
- "typescript": "^5.5.4",
86
- "vite": "^5.4.2",
87
- "astro": "4.15.0",
84
+ "typescript": "^5.6.2",
85
+ "vite": "^5.4.8",
86
+ "astro": "4.15.12",
88
87
  "astro-scripts": "0.0.14"
89
88
  },
90
89
  "scripts": {