Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@sqlitecloud/drivers

Package Overview
Dependencies
Maintainers
2
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@sqlitecloud/drivers - npm Package Compare versions

Comparing version 0.0.56 to 1.0.122

6

lib/drivers/connection-ws.js

@@ -30,5 +30,5 @@ "use strict";

this.config = config;
const connectionString = this.config.connectionString;
const gatewayUrl = ((_a = this.config) === null || _a === void 0 ? void 0 : _a.gatewayUrl) || `${this.config.host === 'localhost' ? 'ws' : 'wss'}://${this.config.host}:4000`;
this.socket = (0, socket_io_client_1.io)(gatewayUrl, { auth: { token: connectionString } });
const connectionstring = this.config.connectionstring;
const gatewayUrl = ((_a = this.config) === null || _a === void 0 ? void 0 : _a.gatewayurl) || `${this.config.host === 'localhost' ? 'ws' : 'wss'}://${this.config.host}:4000`;
this.socket = (0, socket_io_client_1.io)(gatewayUrl, { auth: { token: connectionstring } });
}

@@ -35,0 +35,0 @@ callback === null || callback === void 0 ? void 0 : callback.call(this, null);

@@ -11,3 +11,3 @@ /**

export declare abstract class SQLiteCloudConnection {
/** Parse and validate provided connectionString or configuration */
/** Parse and validate provided connectionstring or configuration */
constructor(config: SQLiteCloudConfig | string, callback?: ErrorCallback);

@@ -33,4 +33,14 @@ /** Configuration passed by client or extracted from connection string */

sendCommands(commands: string, callback?: ResultsCallback): this;
/**
* Sql is a promise based API for executing SQL statements. You can
* pass a simple string with a SQL statement or a template string
* using backticks and parameters in ${parameter} format. These parameters
* will be properly escaped and quoted like when using a prepared statement.
* @param sql A sql string or a template string in `backticks` format
* @returns An array of rows in case of selections or an object with
* metadata in case of insert, update, delete.
*/
sql(sql: TemplateStringsArray | string, ...values: any[]): Promise<any>;
/** Disconnect from server, release transport. */
abstract close(): this;
}

@@ -5,2 +5,11 @@ "use strict";

*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -17,3 +26,3 @@ exports.SQLiteCloudConnection = void 0;

class SQLiteCloudConnection {
/** Parse and validate provided connectionString or configuration */
/** Parse and validate provided connectionstring or configuration */
constructor(config, callback) {

@@ -23,3 +32,3 @@ /** Operations are serialized by waiting an any pending promises */

if (typeof config === 'string') {
this.config = (0, utilities_1.validateConfiguration)({ connectionString: config });
this.config = (0, utilities_1.validateConfiguration)({ connectionstring: config });
}

@@ -59,3 +68,3 @@ else {

message = (0, utilities_2.anonimizeCommand)(message);
console.log(`${new Date().toISOString()} ${this.config.clientId}: ${message}`, ...optionalParams);
console.log(`${new Date().toISOString()} ${this.config.clientid}: ${message}`, ...optionalParams);
}

@@ -84,3 +93,49 @@ }

}
/**
* Sql is a promise based API for executing SQL statements. You can
* pass a simple string with a SQL statement or a template string
* using backticks and parameters in ${parameter} format. These parameters
* will be properly escaped and quoted like when using a prepared statement.
* @param sql A sql string or a template string in `backticks` format
* @returns An array of rows in case of selections or an object with
* metadata in case of insert, update, delete.
*/
sql(sql, ...values) {
return __awaiter(this, void 0, void 0, function* () {
let preparedSql = '';
// sql is a TemplateStringsArray, the 'raw' property is specific to TemplateStringsArray
if (Array.isArray(sql) && 'raw' in sql) {
sql.forEach((string, i) => {
preparedSql += string + (i < values.length ? '?' : '');
});
preparedSql = (0, utilities_1.prepareSql)(preparedSql, ...values);
}
else {
if (typeof sql === 'string') {
if ((values === null || values === void 0 ? void 0 : values.length) > 0) {
preparedSql = (0, utilities_1.prepareSql)(sql, ...values);
}
else {
preparedSql = sql;
}
}
else {
throw new Error('Invalid sql');
}
}
return new Promise((resolve, reject) => {
this.sendCommands(preparedSql, (error, results) => {
if (error) {
reject(error);
}
else {
// metadata for operations like insert, update, delete?
const context = (0, utilities_2.getUpdateResults)(results);
resolve(context ? context : results);
}
});
});
});
}
}
exports.SQLiteCloudConnection = SQLiteCloudConnection;

@@ -61,3 +61,3 @@ "use strict";

this.connections = [];
this.config = typeof config === 'string' ? { connectionString: config } : config;
this.config = typeof config === 'string' ? { connectionstring: config } : config;
// mode is optional and so is callback

@@ -89,3 +89,3 @@ // https://github.com/TryGhost/node-sqlite3/wiki/API#new-sqlite3databasefilename--mode--callback

// connect using websocket if tls is not supported or if explicitly requested
const useWebsocket = utilities_2.isBrowser || ((_b = this.config) === null || _b === void 0 ? void 0 : _b.useWebsocket) || ((_c = this.config) === null || _c === void 0 ? void 0 : _c.gatewayUrl);
const useWebsocket = utilities_2.isBrowser || ((_b = this.config) === null || _b === void 0 ? void 0 : _b.usewebsocket) || ((_c = this.config) === null || _c === void 0 ? void 0 : _c.gatewayurl);
if (useWebsocket) {

@@ -215,3 +215,3 @@ // socket.io transport works in both node.js and browser environments and connects via SQLite Cloud Gateway

const context = this.processContext(results);
callback === null || callback === void 0 ? void 0 : callback.call(context || this, null, context ? undefined : results);
callback === null || callback === void 0 ? void 0 : callback.call(context || this, null, context ? context : results);
}

@@ -218,0 +218,0 @@ });

@@ -11,7 +11,10 @@ /**

export declare const DEFAULT_PORT = 9960;
/** Configuration for SQLite cloud connection */
/**
* Configuration for SQLite cloud connection
* @note Options are all lowecase so they 1:1 compatible with C SDK
*/
export interface SQLiteCloudConfig {
/** Connection string in the form of sqlitecloud://user:password@host:port/database?options */
connectionString?: string;
/** User name is required unless connectionString is provided */
connectionstring?: string;
/** User name is required unless connectionstring is provided */
username?: string;

@@ -21,4 +24,6 @@ /** Password is required unless connection string is provided */

/** True if password is hashed, default is false */
passwordHashed?: boolean;
/** Host name is required unless connectionString is provided, eg: xxx.sqlitecloud.io */
password_hashed?: boolean;
/** API key can be provided instead of username and password */
apikey?: string;
/** Host name is required unless connectionstring is provided, eg: xxx.sqlitecloud.io */
host?: string;

@@ -33,25 +38,27 @@ /** Port number for tls socket */

database?: string;
/** Flag to tell the server to zero-terminate strings */
zerotext?: boolean;
/** Create the database if it doesn't exist? */
createDatabase?: boolean;
create?: boolean;
/** Database will be created in memory */
dbMemory?: boolean;
memory?: boolean;
compression?: boolean;
/** Request for immediate responses from the server node without waiting for linerizability guarantees */
nonlinearizable?: boolean;
non_linearizable?: boolean;
/** Server should send BLOB columns */
noBlob?: boolean;
noblob?: boolean;
/** Do not send columns with more than max_data bytes */
maxData?: number;
maxdata?: number;
/** Server should chunk responses with more than maxRows */
maxRows?: number;
maxrows?: number;
/** Server should limit total number of rows in a set to maxRowset */
maxRowset?: number;
maxrowset?: number;
/** Custom options and configurations for tls socket, eg: additional certificates */
tlsOptions?: tls.ConnectionOptions;
tlsoptions?: tls.ConnectionOptions;
/** True if we should force use of SQLite Cloud Gateway and websocket connections, default: true in browsers, false in node.js */
useWebsocket?: boolean;
usewebsocket?: boolean;
/** Url where we can connect to a SQLite Cloud Gateway that has a socket.io deamon waiting to connect, eg. wss://host:4000 */
gatewayUrl?: string;
gatewayurl?: string;
/** Optional identifier used for verbose logging */
clientId?: string;
clientid?: string;
/** True if connection should enable debug logs */

@@ -89,3 +96,3 @@ verbose?: boolean;

/** Basic types that can be returned by SQLiteCloud APIs */
export type SQLiteCloudDataTypes = string | number | boolean | Record<string | number, unknown> | Buffer | null | undefined;
export type SQLiteCloudDataTypes = string | number | bigint | boolean | Record<string | number, unknown> | Buffer | null | undefined;
/** Custom error reported by SQLiteCloud drivers */

@@ -92,0 +99,0 @@ export declare class SQLiteCloudError extends Error {

@@ -14,2 +14,4 @@ import { SQLiteCloudConfig, SQLiteCloudDataTypes } from './types';

export declare function prepareSql(sql: string, ...params: (SQLiteCloudDataTypes | SQLiteCloudDataTypes[])[]): string;
/** Converts results of an update or insert call into a more meaning full result set */
export declare function getUpdateResults(results?: any): Record<string, any> | undefined;
/**

@@ -29,5 +31,11 @@ * Many of the methods in our API may contain a callback as their last argument.

export declare function validateConfiguration(config: SQLiteCloudConfig): SQLiteCloudConfig;
/** Parse connectionString like sqlitecloud://username:password@host:port/database?option1=xxx&option2=xxx into its components */
export declare function parseConnectionString(connectionString: string): SQLiteCloudConfig;
/**
* Parse connectionstring like sqlitecloud://username:password@host:port/database?option1=xxx&option2=xxx
* or sqlitecloud://host.sqlite.cloud:8860/chinook.sqlite?apikey=mIiLARzKm9XBVllbAzkB1wqrgijJ3Gx0X5z1Agm3xBo
* into its basic components.
*/
export declare function parseconnectionstring(connectionstring: string): SQLiteCloudConfig;
/** Returns true if value is 1 or true */
export declare function parseBoolean(value: string | boolean | null | undefined): boolean;
/** Returns true if value is 1 or true */
export declare function parseBooleanToZeroOne(value: string | boolean | null | undefined): 0 | 1;

@@ -6,4 +6,5 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.parseBoolean = exports.parseConnectionString = exports.validateConfiguration = exports.popCallback = exports.prepareSql = exports.escapeSqlParameter = exports.getInitializationCommands = exports.anonimizeError = exports.anonimizeCommand = exports.isNode = exports.isBrowser = void 0;
exports.parseBooleanToZeroOne = exports.parseBoolean = exports.parseconnectionstring = exports.validateConfiguration = exports.popCallback = exports.getUpdateResults = exports.prepareSql = exports.escapeSqlParameter = exports.getInitializationCommands = exports.anonimizeError = exports.anonimizeCommand = exports.isNode = exports.isBrowser = void 0;
const types_1 = require("./types");
const types_2 = require("./types");
//

@@ -38,5 +39,11 @@ // determining running environment, thanks to browser-or-node

// first user authentication, then all other commands
let commands = `AUTH USER ${config.username || ''} ${config.passwordHashed ? 'HASH' : 'PASSWORD'} ${config.password || ''}; `;
let commands = '';
if (config.apikey) {
commands = `AUTH APIKEY ${config.apikey}; `;
}
else {
commands = `AUTH USER ${config.username || ''} ${config.password_hashed ? 'HASH' : 'PASSWORD'} ${config.password || ''}; `;
}
if (config.database) {
if (config.createDatabase && !config.dbMemory) {
if (config.create && !config.memory) {
commands += `CREATE DATABASE ${config.database} IF NOT EXISTS; `;

@@ -49,16 +56,19 @@ }

}
if (config.nonlinearizable) {
if (config.zerotext) {
commands += 'SET CLIENT KEY ZEROTEXT TO 1; ';
}
if (config.non_linearizable) {
commands += 'SET CLIENT KEY NONLINEARIZABLE TO 1; ';
}
if (config.noBlob) {
if (config.noblob) {
commands += 'SET CLIENT KEY NOBLOB TO 1; ';
}
if (config.maxData) {
commands += `SET CLIENT KEY MAXDATA TO ${config.maxData}; `;
if (config.maxdata) {
commands += `SET CLIENT KEY MAXDATA TO ${config.maxdata}; `;
}
if (config.maxRows) {
commands += `SET CLIENT KEY MAXROWS TO ${config.maxRows}; `;
if (config.maxrows) {
commands += `SET CLIENT KEY MAXROWS TO ${config.maxrows}; `;
}
if (config.maxRowset) {
commands += `SET CLIENT KEY MAXROWSET TO ${config.maxRowset}; `;
if (config.maxrowset) {
commands += `SET CLIENT KEY MAXROWSET TO ${config.maxrowset}; `;
}

@@ -78,3 +88,3 @@ return commands;

}
if (typeof param === 'number') {
if (typeof param === 'number' || typeof param === 'bigint') {
return param.toString();

@@ -135,2 +145,24 @@ }

exports.prepareSql = prepareSql;
/** Converts results of an update or insert call into a more meaning full result set */
function getUpdateResults(results) {
if (results) {
if (Array.isArray(results) && results.length > 0) {
switch (results[0]) {
case types_2.SQLiteCloudArrayType.ARRAY_TYPE_SQLITE_EXEC:
return {
type: results[0],
index: results[1],
lastID: results[2],
changes: results[3],
totalChanges: results[4],
finalized: results[5],
//
rowId: results[2] // same as lastId
};
}
}
}
return undefined;
}
exports.getUpdateResults = getUpdateResults;
/**

@@ -162,4 +194,4 @@ * Many of the methods in our API may contain a callback as their last argument.

console.assert(config, 'SQLiteCloudConnection.validateConfiguration - missing config');
if (config.connectionString) {
config = Object.assign(Object.assign(Object.assign({}, config), parseConnectionString(config.connectionString)), { connectionString: config.connectionString // keep original connection string
if (config.connectionstring) {
config = Object.assign(Object.assign(Object.assign({}, config), parseconnectionstring(config.connectionstring)), { connectionstring: config.connectionstring // keep original connection string
});

@@ -170,17 +202,23 @@ }

config.timeout = config.timeout && config.timeout > 0 ? config.timeout : types_1.DEFAULT_TIMEOUT;
config.clientId || (config.clientId = 'SQLiteCloud');
config.clientid || (config.clientid = 'SQLiteCloud');
config.verbose = parseBoolean(config.verbose);
config.noBlob = parseBoolean(config.noBlob);
config.noblob = parseBoolean(config.noblob);
config.compression = parseBoolean(config.compression);
config.createDatabase = parseBoolean(config.createDatabase);
config.nonlinearizable = parseBoolean(config.nonlinearizable);
config.create = parseBoolean(config.create);
config.non_linearizable = parseBoolean(config.non_linearizable);
config.insecure = parseBoolean(config.insecure);
if (!config.username || !config.password || !config.host) {
const hasCredentials = (config.username && config.password) || config.apikey;
if (!config.host || !hasCredentials) {
console.error('SQLiteCloudConnection.validateConfiguration - missing arguments', config);
throw new types_1.SQLiteCloudError('The user, password and host arguments must be specified.', { errorCode: 'ERR_MISSING_ARGS' });
throw new types_1.SQLiteCloudError('The user, password and host arguments or the ?apikey= must be specified.', { errorCode: 'ERR_MISSING_ARGS' });
}
if (!config.connectionString) {
if (!config.connectionstring) {
// build connection string from configuration, values are already validated
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
config.connectionString = `sqlitecloud://${encodeURIComponent(config.username)}:${encodeURIComponent(config.password)}@${config.host}:${config.port}/${config.database}`;
if (config.apikey) {
config.connectionstring = `sqlitecloud://${config.host}:${config.port}/${config.database || ''}?apikey=${config.apikey}`;
}
else {
config.connectionstring = `sqlitecloud://${encodeURIComponent(config.username || '')}:${encodeURIComponent(config.password || '')}@${config.host}:${config.port}/${config.database}`;
}
}

@@ -190,4 +228,8 @@ return config;

exports.validateConfiguration = validateConfiguration;
/** Parse connectionString like sqlitecloud://username:password@host:port/database?option1=xxx&option2=xxx into its components */
function parseConnectionString(connectionString) {
/**
* Parse connectionstring like sqlitecloud://username:password@host:port/database?option1=xxx&option2=xxx
* or sqlitecloud://host.sqlite.cloud:8860/chinook.sqlite?apikey=mIiLARzKm9XBVllbAzkB1wqrgijJ3Gx0X5z1Agm3xBo
* into its basic components.
*/
function parseconnectionstring(connectionstring) {
try {

@@ -199,9 +241,18 @@ // The URL constructor throws a TypeError if the URL is not valid.

// so we need to replace it with https: to make it work
const knownProtocolUrl = connectionString.replace('sqlitecloud:', 'https:');
const knownProtocolUrl = connectionstring.replace('sqlitecloud:', 'https:');
const url = new URL(knownProtocolUrl);
// all lowecase options
const options = {};
url.searchParams.forEach((value, key) => {
options[key] = value;
options[key.toLowerCase().replaceAll('-', '_')] = value;
});
const config = Object.assign({ username: decodeURIComponent(url.username), password: decodeURIComponent(url.password), host: url.hostname, port: url.port ? parseInt(url.port) : undefined }, options);
// either you use an apikey or username and password
if (config.apikey) {
if (config.username || config.password) {
console.warn('SQLiteCloudConnection.parseconnectionstring - apikey and username/password are both specified, using apikey');
}
delete config.username;
delete config.password;
}
const database = url.pathname.replace('/', ''); // pathname is database name, remove the leading slash

@@ -214,6 +265,6 @@ if (database) {

catch (error) {
throw new types_1.SQLiteCloudError(`Invalid connection string: ${connectionString}`);
throw new types_1.SQLiteCloudError(`Invalid connection string: ${connectionstring}`);
}
}
exports.parseConnectionString = parseConnectionString;
exports.parseconnectionstring = parseconnectionstring;
/** Returns true if value is 1 or true */

@@ -227,1 +278,9 @@ function parseBoolean(value) {

exports.parseBoolean = parseBoolean;
/** Returns true if value is 1 or true */
function parseBooleanToZeroOne(value) {
if (typeof value === 'string') {
return value.toLowerCase() === 'true' || value === '1' ? 1 : 0;
}
return value ? 1 : 0;
}
exports.parseBooleanToZeroOne = parseBooleanToZeroOne;

@@ -6,2 +6,2 @@ export { Database } from './drivers/database';

export { SQLiteCloudRowset, SQLiteCloudRow } from './drivers/rowset';
export { escapeSqlParameter, prepareSql, parseConnectionString, validateConfiguration } from './drivers/utilities';
export { escapeSqlParameter, prepareSql, parseconnectionstring, validateConfiguration } from './drivers/utilities';

@@ -6,3 +6,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.validateConfiguration = exports.parseConnectionString = exports.prepareSql = exports.escapeSqlParameter = exports.SQLiteCloudRow = exports.SQLiteCloudRowset = exports.SQLiteCloudError = exports.SQLiteCloudConnection = exports.Statement = exports.Database = void 0;
exports.validateConfiguration = exports.parseconnectionstring = exports.prepareSql = exports.escapeSqlParameter = exports.SQLiteCloudRow = exports.SQLiteCloudRowset = exports.SQLiteCloudError = exports.SQLiteCloudConnection = exports.Statement = exports.Database = void 0;
// include ONLY packages used by drivers

@@ -26,3 +26,3 @@ // do NOT include anything related to gateway or bun or express

Object.defineProperty(exports, "prepareSql", { enumerable: true, get: function () { return utilities_1.prepareSql; } });
Object.defineProperty(exports, "parseConnectionString", { enumerable: true, get: function () { return utilities_1.parseConnectionString; } });
Object.defineProperty(exports, "parseconnectionstring", { enumerable: true, get: function () { return utilities_1.parseconnectionstring; } });
Object.defineProperty(exports, "validateConfiguration", { enumerable: true, get: function () { return utilities_1.validateConfiguration; } });
{
"name": "@sqlitecloud/drivers",
"version": "0.0.56",
"version": "1.0.122",
"description": "SQLiteCloud drivers for Typescript/Javascript in edge, web and node clients",

@@ -12,3 +12,3 @@ "main": "./lib/index.js",

"test": "jest --coverage",
"build": "rm -rf ./lib/ && tsc --project tsconfig.build.json && npx webpack && cp ./lib/sqlitecloud.drivers.js ./public/ && cp ./lib/sqlitecloud.drivers.dev.js ./public/",
"build": "rm -rf ./lib/ && tsc --project tsconfig.build.json && npx webpack",
"publish": "npm run build && npm publish --access public",

@@ -19,6 +19,3 @@ "prettier": "prettier --write 'src/**/*'",

"npmgui": "npx npm-gui@latest",
"gateway-dev": "bun --watch ./src/gateway/gateway.ts",
"gateway-start": "bun --smol run ./src/gateway/gateway.ts",
"gateway-test": "bun test ./src/gateway/connection-bun.test.ts --watch --coverage --timeout 2000",
"gateway-build": "./scripts/gateway-build.sh"
"prepare": "husky"
},

@@ -31,3 +28,3 @@ "repository": {

"author": {
"name": "SQLiteCloud, Inc.",
"name": "SQLite Cloud, Inc.",
"email": "support@sqlitecloud.io",

@@ -72,2 +69,3 @@ "url": "https://sqlitecloud.io/"

"express": "^4.18.2",
"husky": "^9.0.11",
"jest": "^29.7.0",

@@ -97,2 +95,2 @@ "prettier": "^2.2.1",

}
}
}

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

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