New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@astrojs/db

Package Overview
Dependencies
Maintainers
3
Versions
149
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@astrojs/db - npm Package Compare versions

Comparing version 0.13.2-alpha.0 to 0.13.2-alpha.1

8

dist/_internal/core/utils.d.ts

@@ -0,1 +1,2 @@

import { type ManagedAppToken } from '@astrojs/studio';
import type { AstroConfig, AstroIntegration } from 'astro';

@@ -5,3 +6,8 @@ import './types.js';

export declare function getAstroEnv(envMode?: string): Record<`ASTRO_${string}`, string>;
export declare function getRemoteDatabaseUrl(): string;
export type RemoteDatabaseInfo = {
type: 'libsql' | 'studio';
url: string;
};
export declare function getRemoteDatabaseInfo(): RemoteDatabaseInfo;
export declare function getManagedRemoteToken(token?: string, dbInfo?: RemoteDatabaseInfo): Promise<ManagedAppToken>;
export declare function getDbDirectoryUrl(root: URL | string): URL;

@@ -8,0 +14,0 @@ export declare function defineDbIntegration(integration: AstroIntegration): AstroIntegration;

4

dist/core/cli/commands/execute/index.js
import { existsSync } from "node:fs";
import { getManagedAppTokenOrExit } from "@astrojs/studio";
import { LibsqlError } from "@libsql/client";

@@ -16,2 +15,3 @@ import { green } from "kleur/colors";

import { bundleFile, importBundledFile } from "../../../load-file.js";
import { getManagedRemoteToken } from "../../../utils.js";
async function cmd({

@@ -34,3 +34,3 @@ astroConfig,

if (flags.remote) {
const appToken = await getManagedAppTokenOrExit(flags.token);
const appToken = await getManagedRemoteToken(flags.token);
virtualModContents = getStudioVirtualModContents({

@@ -37,0 +37,0 @@ tables: dbConfig.tables ?? {},

@@ -15,3 +15,2 @@ import { mkdir, writeFile } from "node:fs/promises";

import { safeFetch } from "../../../../runtime/utils.js";
import {} from "../../../utils.js";
async function cmd() {

@@ -18,0 +17,0 @@ const sessionToken = await getSessionIdFromFile();

import type { AstroConfig } from 'astro';
import type { Arguments } from 'yargs-parser';
import { type DBConfig } from '../../../types.js';
import type { DBConfig } from '../../../types.js';
export declare function cmd({ dbConfig, flags, }: {

@@ -5,0 +5,0 @@ astroConfig: AstroConfig;

@@ -1,8 +0,11 @@

import { getManagedAppTokenOrExit } from "@astrojs/studio";
import { sql } from "drizzle-orm";
import prompts from "prompts";
import { createRemoteDatabaseClient } from "../../../../runtime/index.js";
import { safeFetch } from "../../../../runtime/utils.js";
import { MIGRATION_VERSION } from "../../../consts.js";
import {} from "../../../types.js";
import { getRemoteDatabaseUrl } from "../../../utils.js";
import {
getManagedRemoteToken,
getRemoteDatabaseInfo
} from "../../../utils.js";
import {
createCurrentSnapshot,

@@ -20,4 +23,8 @@ createEmptySnapshot,

const isForceReset = flags.forceReset;
const appToken = await getManagedAppTokenOrExit(flags.token);
const productionSnapshot = await getProductionCurrentSnapshot({ appToken: appToken.token });
const dbInfo = getRemoteDatabaseInfo();
const appToken = await getManagedRemoteToken(flags.token, dbInfo);
const productionSnapshot = await getProductionCurrentSnapshot({
dbInfo,
appToken: appToken.token
});
const currentSnapshot = createCurrentSnapshot(dbConfig);

@@ -57,2 +64,3 @@ const isFromScratch = !productionSnapshot;

statements: migrationQueries,
dbInfo,
appToken: appToken.token,

@@ -68,2 +76,3 @@ isDryRun,

statements,
dbInfo,
appToken,

@@ -82,3 +91,27 @@ isDryRun,

}
const url = new URL("/db/push", getRemoteDatabaseUrl());
return dbInfo.type === "studio" ? pushToStudio(requestBody, appToken, dbInfo.url) : pushToDb(requestBody, appToken, dbInfo.url);
}
async function pushToDb(requestBody, appToken, remoteUrl) {
const client = createRemoteDatabaseClient({
dbType: "libsql",
appToken,
remoteUrl
});
await client.run(sql`create table if not exists _astro_db_snapshot (
id INTEGER PRIMARY KEY AUTOINCREMENT,
version TEXT,
snapshot BLOB
);`);
await client.transaction(async (tx) => {
for (const stmt of requestBody.sql) {
await tx.run(sql.raw(stmt));
}
await tx.run(sql`insert into _astro_db_snapshot (version, snapshot) values (
${requestBody.version},
${JSON.stringify(requestBody.snapshot)}
)`);
});
}
async function pushToStudio(requestBody, appToken, remoteUrl) {
const url = new URL("/db/push", remoteUrl);
const response = await safeFetch(

@@ -85,0 +118,0 @@ url,

@@ -1,2 +0,1 @@

import { getManagedAppTokenOrExit } from "@astrojs/studio";
import { sql } from "drizzle-orm";

@@ -10,3 +9,3 @@ import {

import { SHELL_QUERY_MISSING_ERROR } from "../../../errors.js";
import { getAstroEnv, getRemoteDatabaseUrl } from "../../../utils.js";
import { getAstroEnv, getManagedRemoteToken, getRemoteDatabaseInfo } from "../../../utils.js";
async function cmd({

@@ -21,5 +20,10 @@ flags,

}
const dbInfo = getRemoteDatabaseInfo();
if (flags.remote) {
const appToken = await getManagedAppTokenOrExit(flags.token);
const db = createRemoteDatabaseClient(appToken.token, getRemoteDatabaseUrl());
const appToken = await getManagedRemoteToken(flags.token, dbInfo);
const db = createRemoteDatabaseClient({
dbType: dbInfo.type,
remoteUrl: dbInfo.url,
appToken: appToken.token
});
const result = await db.run(sql.raw(query));

@@ -34,3 +38,3 @@ await appToken.destroy();

);
const db = createLocalDatabaseClient({ dbUrl });
const db = createLocalDatabaseClient({ dbUrl, enableTransations: dbInfo.type === "libsql" });
const result = await db.run(sql.raw(query));

@@ -37,0 +41,0 @@ console.log(result);

@@ -1,2 +0,2 @@

import { getManagedAppTokenOrExit } from "@astrojs/studio";
import { getManagedRemoteToken, getRemoteDatabaseInfo } from "../../../utils.js";
import {

@@ -14,4 +14,8 @@ createCurrentSnapshot,

const isJson = flags.json;
const appToken = await getManagedAppTokenOrExit(flags.token);
const productionSnapshot = await getProductionCurrentSnapshot({ appToken: appToken.token });
const dbInfo = getRemoteDatabaseInfo();
const appToken = await getManagedRemoteToken(flags.token, dbInfo);
const productionSnapshot = await getProductionCurrentSnapshot({
dbInfo,
appToken: appToken.token
});
const currentSnapshot = createCurrentSnapshot(dbConfig);

@@ -18,0 +22,0 @@ const { queries: migrationQueries, confirmations } = await getMigrationQueries({

@@ -1,2 +0,3 @@

import { type DBConfig, type DBSnapshot, type ResolvedDBTable } from '../types.js';
import type { DBConfig, DBSnapshot, ResolvedDBTable } from '../types.js';
import type { RemoteDatabaseInfo } from '../utils.js';
export declare function getMigrationQueries({ oldSnapshot, newSnapshot, reset, }: {

@@ -18,3 +19,4 @@ oldSnapshot: DBSnapshot;

}>;
export declare function getProductionCurrentSnapshot({ appToken, }: {
export declare function getProductionCurrentSnapshot(options: {
dbInfo: RemoteDatabaseInfo;
appToken: string;

@@ -21,0 +23,0 @@ }): Promise<DBSnapshot | undefined>;

import deepDiff from "deep-diff";
import { sql } from "drizzle-orm";
import { SQLiteAsyncDialect } from "drizzle-orm/sqlite-core";

@@ -7,2 +8,3 @@ import * as color from "kleur/colors";

import { hasPrimaryKey } from "../../runtime/index.js";
import { createRemoteDatabaseClient } from "../../runtime/index.js";
import { isSerializedSQL } from "../../runtime/types.js";

@@ -22,5 +24,2 @@ import { safeFetch } from "../../runtime/utils.js";

import { columnSchema } from "../schemas.js";
import {
} from "../types.js";
import { getRemoteDatabaseUrl } from "../utils.js";
const sqlite = new SQLiteAsyncDialect();

@@ -309,6 +308,26 @@ const genTempTableName = customAlphabet("abcdefghijklmnopqrstuvwxyz", 10);

}
async function getProductionCurrentSnapshot({
appToken
}) {
const url = new URL("/db/schema", getRemoteDatabaseUrl());
function getProductionCurrentSnapshot(options) {
return options.dbInfo.type === "studio" ? getStudioCurrentSnapshot(options.appToken, options.dbInfo.url) : getDbCurrentSnapshot(options.appToken, options.dbInfo.url);
}
async function getDbCurrentSnapshot(appToken, remoteUrl) {
const client = createRemoteDatabaseClient({
dbType: "libsql",
appToken,
remoteUrl
});
try {
const res = await client.get(
// Latest snapshot
sql`select snapshot from _astro_db_snapshot order by id desc limit 1;`
);
return JSON.parse(res.snapshot);
} catch (error) {
if (error.code === "SQLITE_UNKNOWN") {
return;
}
throw error;
}
}
async function getStudioCurrentSnapshot(appToken, remoteUrl) {
const url = new URL("/db/schema", remoteUrl);
const response = await safeFetch(

@@ -315,0 +334,0 @@ url,

@@ -30,3 +30,3 @@ import { bgGreen, bgWhite, black, bold, dim, green } from "kleur/colors";

` ${bgGreen(black(` ${commandName} `))} ${green(
`v${"0.13.2-alpha.0"}`
`v${"0.13.2-alpha.1"}`
)} ${headline}`

@@ -33,0 +33,0 @@ );

@@ -5,3 +5,2 @@ import { existsSync } from "node:fs";

import { fileURLToPath } from "node:url";
import { getManagedAppTokenOrExit } from "@astrojs/studio";
import { LibsqlError } from "@libsql/client";

@@ -20,3 +19,3 @@ import { blue, yellow } from "kleur/colors";

import { SEED_DEV_FILE_NAME } from "../queries.js";
import { getDbDirectoryUrl } from "../utils.js";
import { getDbDirectoryUrl, getManagedRemoteToken } from "../utils.js";
import { fileURLIntegration } from "./file-url.js";

@@ -29,3 +28,3 @@ import { getDtsContent } from "./typegen.js";

function astroDBIntegration() {
let connectToStudio = false;
let connectToRemote = false;
let configFileDependencies = [];

@@ -63,7 +62,7 @@ let root;

const args = parseArgs(process.argv.slice(3));
connectToStudio = process.env.ASTRO_INTERNAL_TEST_REMOTE || args["remote"];
if (connectToStudio) {
appToken = await getManagedAppTokenOrExit();
connectToRemote = process.env.ASTRO_INTERNAL_TEST_REMOTE || args["remote"];
if (connectToRemote) {
appToken = await getManagedRemoteToken();
dbPlugin = vitePluginDb({
connectToStudio,
connectToStudio: connectToRemote,
appToken: appToken.token,

@@ -102,3 +101,3 @@ tables,

const localDbUrl = new URL(DB_PATH, config.root);
if (!connectToStudio && !existsSync(localDbUrl)) {
if (!connectToRemote && !existsSync(localDbUrl)) {
await mkdir(dirname(fileURLToPath(localDbUrl)), { recursive: true });

@@ -128,5 +127,5 @@ await writeFile(localDbUrl, "");

logger.info(
connectToStudio ? "Connected to remote database." : "New local database created."
connectToRemote ? "Connected to remote database." : "New local database created."
);
if (connectToStudio) return;
if (connectToRemote) return;
const localSeedPaths = SEED_DEV_FILE_NAME.map(

@@ -143,3 +142,3 @@ (name) => new URL(name, getDbDirectoryUrl(root))

"astro:build:start": async ({ logger }) => {
if (!connectToStudio && !databaseFileEnvDefined() && (output === "server" || output === "hybrid")) {
if (!connectToRemote && !databaseFileEnvDefined() && (output === "server" || output === "hybrid")) {
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.`;

@@ -149,3 +148,3 @@ const hint = "Learn more connecting to Studio: https://docs.astro.build/en/guides/astro-db/#connect-to-astro-studio";

}
logger.info("database: " + (connectToStudio ? yellow("remote") : blue("local database.")));
logger.info("database: " + (connectToRemote ? yellow("remote") : blue("local database.")));
},

@@ -152,0 +151,0 @@ "astro:build:setup": async ({ vite }) => {

@@ -10,3 +10,7 @@ import { existsSync } from "node:fs";

import { SEED_DEV_FILE_NAME, getCreateIndexQueries, getCreateTableQuery } from "../queries.js";
import { getAstroEnv, getDbDirectoryUrl, getRemoteDatabaseUrl } from "../utils.js";
import {
getAstroEnv,
getDbDirectoryUrl,
getRemoteDatabaseInfo
} from "../utils.js";
const resolved = {

@@ -74,2 +78,3 @@ module: "\0" + VIRTUAL_MODULE_ID,

}) {
const dbInfo = getRemoteDatabaseInfo();
const dbUrl = new URL(DB_PATH, root);

@@ -80,3 +85,3 @@ return `

const dbUrl = normalizeDatabaseUrl(import.meta.env.ASTRO_DATABASE_FILE, ${JSON.stringify(dbUrl)});
export const db = createLocalDatabaseClient({ dbUrl });
export const db = createLocalDatabaseClient({ dbUrl, enableTransactions: ${dbInfo.url === "libsql"} });

@@ -93,8 +98,10 @@ export * from ${RUNTIME_VIRTUAL_IMPORT};

}) {
const dbInfo = getRemoteDatabaseInfo();
function appTokenArg() {
if (isBuild) {
const envPrefix = dbInfo.type === "studio" ? "ASTRO_STUDIO" : "ASTRO_DB";
if (output === "server") {
return "process.env.ASTRO_STUDIO_APP_TOKEN";
return `process.env.${envPrefix}_APP_TOKEN`;
} else {
return `process.env.ASTRO_STUDIO_APP_TOKEN ?? ${JSON.stringify(appToken)}`;
return `process.env.${envPrefix}_APP_TOKEN ?? ${JSON.stringify(appToken)}`;
}

@@ -106,4 +113,4 @@ } else {

function dbUrlArg() {
const dbStr = JSON.stringify(getRemoteDatabaseUrl());
return `import.meta.env.ASTRO_STUDIO_REMOTE_DB_URL ?? ${dbStr}`;
const dbStr = JSON.stringify(dbInfo.url);
return dbInfo.type === "studio" ? `import.meta.env.ASTRO_STUDIO_REMOTE_DB_URL ?? ${dbStr}` : `import.meta.env.ASTRO_DB_REMOTE_URL ?? ${dbStr}`;
}

@@ -113,3 +120,7 @@ return `

export const db = await createRemoteDatabaseClient(${appTokenArg()}, ${dbUrlArg()});
export const db = await createRemoteDatabaseClient({
dbType: ${JSON.stringify(dbInfo.type)},
remoteUrl: ${dbUrlArg()},
appToken: ${appTokenArg()},
});

@@ -130,5 +141,6 @@ export * from ${RUNTIME_VIRTUAL_IMPORT};

async function recreateTables({ tables, root }) {
const dbInfo = getRemoteDatabaseInfo();
const { ASTRO_DATABASE_FILE } = getAstroEnv();
const dbUrl = normalizeDatabaseUrl(ASTRO_DATABASE_FILE, new URL(DB_PATH, root).href);
const db = createLocalDatabaseClient({ dbUrl });
const db = createLocalDatabaseClient({ dbUrl, enableTransations: dbInfo.type === "libsql" });
const setupQueries = [];

@@ -135,0 +147,0 @@ for (const [name, table] of Object.entries(tables.get() ?? {})) {

@@ -119,2 +119,3 @@ import { existsSync } from "node:fs";

"import.meta.env.ASTRO_STUDIO_REMOTE_DB_URL": "undefined",
"import.meta.env.ASTRO_DB_REMOTE_DB_URL": "undefined",
"import.meta.env.ASTRO_DATABASE_FILE": JSON.stringify(ASTRO_DATABASE_FILE ?? "")

@@ -121,0 +122,0 @@ },

@@ -1,2 +0,1 @@

import {} from "drizzle-orm";
import { SQLiteAsyncDialect } from "drizzle-orm/sqlite-core";

@@ -3,0 +2,0 @@ import { bold } from "kleur/colors";

@@ -0,1 +1,2 @@

import { type ManagedAppToken } from '@astrojs/studio';
import type { AstroConfig, AstroIntegration } from 'astro';

@@ -5,3 +6,8 @@ import './types.js';

export declare function getAstroEnv(envMode?: string): Record<`ASTRO_${string}`, string>;
export declare function getRemoteDatabaseUrl(): string;
export type RemoteDatabaseInfo = {
type: 'libsql' | 'studio';
url: string;
};
export declare function getRemoteDatabaseInfo(): RemoteDatabaseInfo;
export declare function getManagedRemoteToken(token?: string, dbInfo?: RemoteDatabaseInfo): Promise<ManagedAppToken>;
export declare function getDbDirectoryUrl(root: URL | string): URL;

@@ -8,0 +14,0 @@ export declare function defineDbIntegration(integration: AstroIntegration): AstroIntegration;

@@ -1,2 +0,2 @@

import { getAstroStudioEnv } from "@astrojs/studio";
import { getAstroStudioEnv, getManagedAppTokenOrExit } from "@astrojs/studio";
import { loadEnv } from "vite";

@@ -8,6 +8,32 @@ import "./types.js";

}
function getRemoteDatabaseUrl() {
const env = getAstroStudioEnv();
return env.ASTRO_STUDIO_REMOTE_DB_URL || "https://db.services.astro.build";
function getRemoteDatabaseInfo() {
const astroEnv = getAstroEnv();
const studioEnv = getAstroStudioEnv();
if (studioEnv.ASTRO_STUDIO_REMOTE_DB_URL)
return {
type: "studio",
url: studioEnv.ASTRO_STUDIO_REMOTE_DB_URL
};
if (astroEnv.ASTRO_DB_REMOTE_URL)
return {
type: "libsql",
url: astroEnv.ASTRO_DB_REMOTE_URL
};
return {
type: "studio",
url: "https://db.services.astro.build"
};
}
function getManagedRemoteToken(token, dbInfo) {
dbInfo ??= getRemoteDatabaseInfo();
if (dbInfo.type === "studio") {
return getManagedAppTokenOrExit(token);
}
const astroEnv = getAstroEnv();
return Promise.resolve({
token: token ?? astroEnv.ASTRO_DB_APP_TOKEN,
renew: () => Promise.resolve(),
destroy: () => Promise.resolve()
});
}
function getDbDirectoryUrl(root) {

@@ -28,4 +54,5 @@ return new URL("db/", root);

getDbDirectoryUrl,
getRemoteDatabaseUrl,
getManagedRemoteToken,
getRemoteDatabaseInfo,
mapObject
};
import type { LibSQLDatabase } from 'drizzle-orm/libsql';
import { type SqliteRemoteDatabase } from 'drizzle-orm/sqlite-proxy';
export declare function createLocalDatabaseClient({ dbUrl }: {
type LocalDbClientOptions = {
dbUrl: string;
}): LibSQLDatabase;
export declare function createRemoteDatabaseClient(appToken: string, remoteDbURL: string): SqliteRemoteDatabase<Record<string, never>>;
enableTransations: boolean;
};
export declare function createLocalDatabaseClient(options: LocalDbClientOptions): LibSQLDatabase;
type RemoteDbClientOptions = {
dbType: 'studio' | 'libsql';
appToken: string;
remoteUrl: string | URL;
};
export declare function createRemoteDatabaseClient(options: RemoteDbClientOptions): SqliteRemoteDatabase<Record<string, never>> | LibSQLDatabase<Record<string, never>>;
export {};

@@ -16,7 +16,9 @@ import { createClient } from "@libsql/client";

}
function createLocalDatabaseClient({ dbUrl }) {
const url = isWebContainer ? "file:content.db" : dbUrl;
function createLocalDatabaseClient(options) {
const url = isWebContainer ? "file:content.db" : options.dbUrl;
const client = createClient({ url });
const db = drizzleLibsql(client);
applyTransactionNotSupported(db);
if (!options.enableTransations) {
applyTransactionNotSupported(db);
}
return db;

@@ -31,3 +33,17 @@ }

});
function createRemoteDatabaseClient(appToken, remoteDbURL) {
function createRemoteDatabaseClient(options) {
const remoteUrl = new URL(options.remoteUrl);
return options.dbType === "studio" ? createStudioDatabaseClient(options.appToken, remoteUrl) : createRemoteLibSQLClient(options.appToken, remoteUrl);
}
function createRemoteLibSQLClient(appToken, remoteDbURL) {
const options = Object.fromEntries(remoteDbURL.searchParams.entries());
remoteDbURL.search = "";
const client = createClient({
...options,
authToken: appToken,
url: remoteDbURL.protocol === "memory:" ? ":memory:" : remoteDbURL.toString()
});
return drizzleLibsql(client);
}
function createStudioDatabaseClient(appToken, remoteDbURL) {
if (appToken == null) {

@@ -34,0 +50,0 @@ throw new Error(`Cannot create a remote client: missing app token.`);

import { type ColumnDataType } from 'drizzle-orm';
import { type LibSQLDatabase } from 'drizzle-orm/libsql';
import type { LibSQLDatabase } from 'drizzle-orm/libsql';
import type { DBColumn, DBTable } from '../core/types.js';

@@ -4,0 +4,0 @@ export type Database = Omit<LibSQLDatabase, 'transaction'>;

import { sql } from "drizzle-orm";
import {} from "drizzle-orm/libsql";
import {

@@ -4,0 +3,0 @@ customType,

{
"name": "@astrojs/db",
"version": "0.13.2-alpha.0",
"version": "0.13.2-alpha.1",
"description": "Add libSQL and Astro Studio support to your Astro site",

@@ -65,3 +65,3 @@ "license": "MIT",

"dependencies": {
"@libsql/client": "^0.9.0",
"@libsql/client": "^0.10.0",
"async-listen": "^3.0.1",

@@ -74,3 +74,3 @@ "deep-diff": "^1.0.2",

"open": "^10.1.0",
"ora": "^8.0.1",
"ora": "^8.1.0",
"prompts": "^2.4.2",

@@ -88,5 +88,5 @@ "strip-ansi": "^7.1.0",

"typescript": "^5.5.4",
"vite": "^5.4.1",
"astro": "5.0.0-alpha.1",
"astro-scripts": "0.0.14"
"vite": "^5.4.2",
"astro-scripts": "0.0.14",
"astro": "5.0.0-alpha.4"
},

@@ -93,0 +93,0 @@ "scripts": {

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc