### Install and Run Application
Source: https://github.com/dexie/dexie.js/blob/master/samples/angular/README.md
Commands to install dependencies and start the development server.
```bash
npm install
npm start
```
--------------------------------
### Clone and Install Dexie.js
Source: https://github.com/dexie/dexie.js/blob/master/CONTRIBUTING.md
Clone your fork of Dexie.js, install dependencies using pnpm, and build the project. This is the initial setup for local development.
```bash
git clone https://github.com/YOUR-USERNAME/Dexie.js.git dexie
cd dexie
pnpm install
pnpm run build
```
--------------------------------
### Install Dexie.Observable
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Observable/README.md
Install the required packages via npm.
```bash
npm install dexie --save
npm install dexie-observable --save
```
--------------------------------
### Install dexie-export-import
Source: https://github.com/dexie/dexie.js/blob/master/addons/dexie-export-import/README.md
Install the dexie and dexie-export-import packages using npm.
```bash
npm install dexie
npm install dexie-export-import
```
--------------------------------
### Install via bower
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Observable/dist/README.md
Install the dexie package which includes the observable addon, and verify the file structure.
```bash
$ bower install dexie --save
$ ls bower_components/dexie/addons/Dexie.Observable/dist
dexie-observable.js dexie-observable.js.map dexie-observable.min.js dexie-observable.min.js.map
```
--------------------------------
### Start Development Server
Source: https://github.com/dexie/dexie.js/blob/master/samples/vue/README.md
Use this command to launch the development server. The app will auto-reload on source file changes.
```bash
npm run dev
```
--------------------------------
### Install Dependencies with npm
Source: https://github.com/dexie/dexie.js/blob/master/samples/vue/README.md
Run this command in your terminal to install the project's dependencies before running the application.
```bash
npm install
```
--------------------------------
### Install Dexie Syncable dependencies
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Syncable/README.md
Install the required packages via npm.
```bash
npm install dexie --save
npm install dexie-observable --save
npm install dexie-syncable --save
```
--------------------------------
### Dexie.js Hello World (Vanilla JS)
Source: https://github.com/dexie/dexie.js/blob/master/README.md
Basic setup and usage of Dexie.js with modern ES modules. Import Dexie and declare/use your database schema.
```html
```
--------------------------------
### Install Dependencies
Source: https://github.com/dexie/dexie.js/blob/master/CONTRIBUTING.md
Installs all necessary dependencies for Dexie.js development using the pnpm package manager.
```bash
# To install pnpm, see https://pnpm.io/installation
pnpm install
```
--------------------------------
### Install Dexie.js, Y.js, and y-dexie
Source: https://github.com/dexie/dexie.js/blob/master/addons/y-dexie/README.md
Install the necessary packages using npm to integrate Dexie.js with Y.js.
```bash
npm install dexie
npm install yjs
npm install y-dexie
```
--------------------------------
### Install via npm
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Observable/dist/README.md
Use npm to add the dexie-observable package to your project dependencies.
```bash
npm install dexie-observable --save
```
--------------------------------
### Install Dexie Syncable via npm
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Syncable/dist/README.md
Use this command to install the dexie-syncable package using npm.
```bash
npm install dexie-syncable --save
```
--------------------------------
### Install Dexie Cloud dependencies
Source: https://github.com/dexie/dexie.js/blob/master/addons/dexie-cloud/README.md
Use npm to install the latest versions of dexie and the dexie-cloud-addon.
```bash
npm install dexie@latest
npm install dexie-cloud-addon@latest
```
--------------------------------
### Build Dexie.js Project
Source: https://github.com/dexie/dexie.js/blob/master/dist/README.md
Follow these steps to build the Dexie.js project from source. Ensure you have run 'npm install' first.
```bash
npm run build
```
--------------------------------
### Dexie.js Database Observation Setup
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Observable/README.md
Include Dexie.js and Dexie-observable.min.js. Initialize a new Dexie database, define its version and stores, and set up a listener for 'changes' events to handle object creation, updates, and deletions.
```html
```
--------------------------------
### Install Dexie.js via npm
Source: https://github.com/dexie/dexie.js/blob/master/README.md
Install the Dexie.js library using npm. This is the primary package for using Dexie.js in your project.
```bash
npm install dexie
```
--------------------------------
### Install Dexie via Bower
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Syncable/dist/README.md
Install the main Dexie package via bower, which includes the syncable addon in newer versions.
```bash
bower install dexie --save
```
--------------------------------
### Start Development Server
Source: https://github.com/dexie/dexie.js/blob/master/samples/dexie-cloud-todo-app/README.md
Runs the app in development mode using Vite. It includes fast Hot Module Replacement (HMR) for automatic reloads on code changes. Accessible at http://localhost:3000.
```bash
npm run dev
```
```bash
npm start
```
--------------------------------
### Install Dexie Cloud Addon
Source: https://github.com/dexie/dexie.js/blob/master/README.md
Install the Dexie Cloud addon using npm. This package provides sync, authentication, and real-time collaboration features for Dexie.js applications.
```bash
npm install dexie-cloud-addon
```
--------------------------------
### Enable Observable on Existing Database
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Observable/README.md
Perform a schema upgrade to allow the addon to install its internal tables.
```javascript
import Dexie from 'dexie';
import 'dexie-observable';
var db = new Dexie('myExistingDb');
db.version(1).stores(... existing schema ...);
// Now, add another version, just to trigger an upgrade for Dexie.Observable
db.version(2).stores({}); // No need to add / remove tables. This is just to allow the addon to install its tables.
```
--------------------------------
### Upgrade Existing Database for Syncable
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Syncable/README.md
Add a new version to an existing database to allow the addon to install its internal tables.
```javascript
import Dexie from 'dexie';
import 'dexie-observable';
import 'dexie-syncable';
import 'your-sync-protocol-implementation';
var db = new Dexie('myExistingDb');
db.version(1).stores(... existing schema ...);
// Now, add another version, just to trigger an upgrade for Dexie.Syncable
db.version(2).stores({}); // No need to add / remove tables. This is just to allow the addon to install its tables.
```
--------------------------------
### Build Dexie.js Project
Source: https://github.com/dexie/dexie.js/blob/master/README.md
Install dependencies and build the Dexie.js project using pnpm. This command is typically used for development or contributing to the Dexie.js library.
```bash
pnpm install
pnpm run build
```
--------------------------------
### Define Database Schema
Source: https://github.com/dexie/dexie.js/blob/master/samples/angular/README.md
Setup the Dexie database instance with typed tables and versioning.
```typescript
import Dexie, { type EntityTable } from 'dexie';
interface TodoItem {
id: number;
title: string;
done: boolean;
}
const db = new Dexie('MyApp') as Dexie & {
todoItems: EntityTable;
};
db.version(1).stores({
todoItems: '++id',
});
export { db };
```
--------------------------------
### Dexie Syncable files in Bower components
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Syncable/dist/README.md
Lists the distribution files for dexie-syncable after installation via bower.
```bash
$ ls bower_components/dexie/addons/Dexie.Syncable/dist
dexie-syncable.js dexie-syncable.js.map dexie-syncable.min.js dexie-syncable.min.js.map
```
--------------------------------
### Basic Y.Doc Access and Manipulation
Source: https://github.com/dexie/dexie.js/blob/master/addons/y-dexie/README.md
Demonstrates how to fetch an object, get its Y.Doc, load it using DexieYProvider, manipulate the document, and then release the provider.
```typescript
import { db } from './db.js';
import { DexieYProvider } from 'y-dexie';
// 1. Fetch an object
const friend = await db.friends.get(friendId);
// 2. Get a reference to the notes Y.Doc
const doc = friend.notes;
// 3. Aquire a DexieYProvider
const provider = DexieYProvider.load(doc);
// 4. Load the document
await provider.whenLoaded;
// Manipulate
doc.getText().insert(0, 'hello world');
doc.getMap('myMap').set('key', 'value');
...
// Read contents
const rootText = doc.getText(); // 'hello world'
const subMap = doc.getMap('myMap').get('key'); // 'value'
// 5. When done using the document, release it
DexieYProvider.release(doc); // Decreases ref-count and destroys doc if not accessed anymore.
```
--------------------------------
### Link Dexie.js Locally
Source: https://github.com/dexie/dexie.js/blob/master/CONTRIBUTING.md
Link the globally installed Dexie.js package to your local development environment. This allows changes in your Dexie.js clone to reflect in your app.
```bash
npm link # Or yarn link or pnpm link --global depending on what package manager you are using.
```
--------------------------------
### Configure Dexie with Dexie Cloud Addon
Source: https://github.com/dexie/dexie.js/blob/master/README.md
Initialize Dexie with the Dexie Cloud addon and configure the database URL. This setup enables sync and authentication for your Dexie application.
```typescript
import Dexie from 'dexie';
import dexieCloud from 'dexie-cloud-addon';
const db = new Dexie('MyDatabase', { addons: [dexieCloud] });
db.version(1).stores({ items: '@id, title' });
db.cloud.configure({ databaseUrl: 'https://.dexie.cloud' });
```
--------------------------------
### Example Dexie Exported JSON File
Source: https://github.com/dexie/dexie.js/blob/master/addons/dexie-export-import/README.md
A sample JSON file representing data exported from a Dexie.js database, illustrating the DexieExportJsonStructure.
```json
{
"formatName": "dexie",
"formatVersion": 1,
"data": {
"databaseName": "dexie-export-import-basic-tests",
"databaseVersion": 1,
"tables": [
{
"name": "outbound",
"schema": "",
"rowCount": 2
},
{
"name": "inbound",
"schema": "++id",
"rowCount": 3
}
],
"data": [{
"tableName": "outbound",
"inbound": false,
"rows": [
[
1,
{
"foo": "bar"
}
],
[
2,
{
"bar": "foo"
}
]
]
},{
"tableName": "inbound",
"inbound": true,
"rows": [
{
"id": 1,
"date": 1,
"fullBlob": {
"type": "",
"data": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w=="
},
"binary": {
"buffer": "AQID",
"byteOffset": 0,
"length": 3
},
"text": "foo",
"bool": false,
"$types": {
"date": "date",
"fullBlob": "blob2",
"binary": "uint8array2",
"binary.buffer": "arraybuffer"
}
},
{
"id": 2,
"foo": "bar"
},
{
"id": 3,
"bar": "foo"
}
]
}]
}
}
```
--------------------------------
### Dexie.js Hello World (React + TypeScript)
Source: https://github.com/dexie/dexie.js/blob/master/README.md
Example of integrating Dexie.js with React and TypeScript using `dexie-react-hooks`. Defines TypeScript interfaces for entities and uses `useLiveQuery` for reactive data fetching.
```tsx
import React from 'react';
import { Dexie, type EntityTable } from 'dexie';
import { useLiveQuery } from 'dexie-react-hooks';
// Typing for your entities (hint is to move this to its own module)
export interface Friend {
id: number;
name: string;
age: number;
}
// Database declaration (move this to its own module also)
export const db = new Dexie('FriendDatabase') as Dexie & {
friends: EntityTable;
};
db.version(1).stores({
friends: '++id, age',
});
// Component:
export function MyDexieReactComponent() {
const youngFriends = useLiveQuery(() =>
db.friends
.where('age')
.below(30)
.toArray()
);
return (
<>
My young friends
{youngFriends?.map((f) => (
Name: {f.name}, Age: {f.age}
))}
>
);
}
```
--------------------------------
### Watch for Changes and Rebuild
Source: https://github.com/dexie/dexie.js/blob/master/CONTRIBUTING.md
Starts a watcher process that automatically rebuilds Dexie.js whenever source files change. This is useful for continuous development.
```bash
pnpm run watch
```
--------------------------------
### WebWorker Test Setup for Dexie.js
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Syncable/test/integration/test-syncable-dexie-tests.html
Configures the WebWorker source file and necessary imports for Dexie.js, Dexie.Observable, and Dexie.Syncable. This hack allows WebWorker tests to run in different environments.
```javascript
window.workerSource = "worker.js";
window.workerImports = [
"../dist/dexie.js",
"../addons/Dexie.Observable/dist/dexie-observable.js",
"../addons/Dexie.Syncable/dist/dexie-syncable.js"
];
```
--------------------------------
### Build from source
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Observable/dist/README.md
Clone the repository and run the build scripts to generate the addon files locally.
```bash
git clone https://github.com/YOUR-USERNAME/Dexie.js.git
cd Dexie.js
npm install
cd addons/Dexie.Observable
npm run build # or npm run watch
```
--------------------------------
### Dexie.js Hello World (Legacy Script Tags)
Source: https://github.com/dexie/dexie.js/blob/master/README.md
Demonstrates Dexie.js usage with traditional script tags, suitable for older projects or environments without module support. Uses Promises for asynchronous operations.
```html
```
--------------------------------
### Create a cloud database via CLI
Source: https://github.com/dexie/dexie.js/blob/master/addons/dexie-cloud/README.md
Run this command in your terminal to initialize a new cloud database project.
```bash
npx dexie-cloud create
```
--------------------------------
### Initialize and Query Dexie Database
Source: https://github.com/dexie/dexie.js/blob/master/samples/vanilla-js/hello-world-modern.html
Demonstrates importing Dexie, defining a schema, and performing basic add and query operations within a try-catch block.
```javascript
import Dexie from 'https://unpkg.com/dexie@latest/dist/modern/dexie.min.mjs'; // // Declare Database // const db = new Dexie('FriendDatabase'); db.version(1).stores({ friends: '++id, name, age', }); // // Manipulate and Query Database // try { let id = await db.friends.add({ name: 'Josephine', age: 21, }); alert(`Successfully added a friend with id ${id}`); let youngFriends = await db.friends.where('age').below(25).toArray(); alert(`My young friends: ${JSON.stringify(youngFriends)}`); } catch (error) { alert(`Oops, error: ${error}`); }
```
--------------------------------
### Initialize Dexie DB and liveQuery
Source: https://github.com/dexie/dexie.js/blob/master/samples/liveQuery/liveQuery.html
Sets up a Dexie database named 'MyDatabase' with a 'friends' table and initializes a liveQuery to observe friends within a specific age range. Requires Dexie import.
```javascript
import Dexie, { liveQuery } from 'dexie';
const db = new Dexie('MyDatabase');
db.version(1).stores({
friends: '++id, name, age',
});
const friendsObservable = liveQuery(() => db.friends.where('age').between(50, 75).toArray());
const subscription = friendsObservable.subscribe({
next: (result) => console.log('Got result:', JSON.stringify(result)),
error: (error) => console.error(error),
});
```
--------------------------------
### Build Dexie Syncable from Source
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Syncable/dist/README.md
Steps to clone the Dexie.js repository and build the syncable addon from source using npm.
```bash
git clone https://github.com/YOUR-USERNAME/Dexie.js.git
cd Dexie.js
npm install
cd addons/Dexie.Syncable
npm run build # or npm run watch
```
--------------------------------
### Build and Preview Production Build
Source: https://github.com/dexie/dexie.js/blob/master/samples/dexie-cloud-todo-app/README.md
Builds the app for production and then serves the production build locally for testing. This is useful for verifying the app's behavior, including service worker functionality, before deployment.
```bash
npm run build && npm run preview
```
--------------------------------
### Initialize Dexie Cloud database
Source: https://github.com/dexie/dexie.js/blob/master/addons/dexie-cloud/README.md
Configure a Dexie instance with the cloud addon and set the database URL.
```typescript
import { Dexie } from 'dexie';
import dexieCloud from 'dexie-cloud-addon';
const db = new Dexie('dbname', { addons: [dexieCloud]});
db.version(1).stores({
yourTable: '@primKeyProp, indexedProp1, indexedProp2, ...'
});
db.cloud.configure({
databaseUrl: 'https://.dexie.cloud'
})
```
--------------------------------
### Initialize Dexie.Observable
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Observable/README.md
Import the library to enable the db.on('changes') event.
```js
import Dexie from 'dexie';
import 'dexie-observable';
// Use Dexie as normally - but you can also subscribe to db.on('changes').
```
--------------------------------
### Read First 100 Bytes of a Blob
Source: https://github.com/dexie/dexie.js/blob/master/addons/dexie-export-import/README.md
Slices a Blob to get the first 100 bytes. This is a preliminary step for reading Blobs in chunks.
```javascript
const firstPart = blob.slice(0,100);
```
--------------------------------
### Configure Public URL for Deployment
Source: https://github.com/dexie/dexie.js/blob/master/samples/dexie-cloud-todo-app/README.md
Use environment variables to set the base path for builds, supporting both subdirectories and relative paths.
```bash
# For deployment in subdirectory
PUBLIC_URL=/my-app npm run build
# For relative paths (e.g., GitHub Pages without custom domain)
PUBLIC_URL=. npm run build
```
--------------------------------
### Create or Connect to Dexie Cloud DB
Source: https://github.com/dexie/dexie.js/blob/master/samples/dexie-cloud-todo-app/README.md
Use this command to either create a new Dexie Cloud database or connect to an existing one. This is a prerequisite for configuring the application.
```bash
npx dexie-cloud create
```
```bash
npx dexie-cloud connect
```
--------------------------------
### Connect to Sync Server
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Syncable/README.md
Establish a connection to the synchronization server using a registered protocol.
```javascript
// This example uses the WebSocketSyncProtocol included in earlier steps.
db.syncable.connect ("websocket", "https://syncserver.com/sync");
db.syncable.on('statusChanged', function (newStatus, url) {
console.log ("Sync Status changed: " + Dexie.Syncable.StatusTexts[newStatus]);
});
```
--------------------------------
### Equivalent `try...finally` block for `using`
Source: https://github.com/dexie/dexie.js/blob/master/addons/y-dexie/README.md
Shows the equivalent manual `try...finally` block for managing DexieYProvider resources, which the `using` keyword simplifies.
```typescript
const provider = DexieYProvider.load(doc);
try {
await provider.whenLoaded;
...
} finally {
DexieYProvider.release(doc);
}
```
--------------------------------
### Basic Usage: Import/Export with Dexie.js
Source: https://github.com/dexie/dexie.js/blob/master/addons/dexie-export-import/README.md
Demonstrates the basic import and export operations using Dexie.js. Import from a Blob or File to a Dexie instance, or export a Dexie instance to a Blob. Also shows how to import from a Blob to an existing Dexie instance.
```javascript
import { Dexie } from "dexie";
import "dexie-export-import";
//
// Import from Blob or File to Dexie instance:
//
const db = await Dexie.import(blob, [options]);
//
// Export to Blob
//
const blob = await db.export([options]);
//
// Import from Blob or File to existing Dexie instance
//
await db.import(blob, [options]);
```
--------------------------------
### Configure App with .env.local
Source: https://github.com/dexie/dexie.js/blob/master/samples/dexie-cloud-todo-app/README.md
This script configures the application by creating a .env.local file, which connects the ToDo app to your Dexie Cloud database. Alternatively, you can manually set the VITE_DBURL environment variable.
```bash
./configure-app.sh
```
--------------------------------
### Run Vitest Tests with UI
Source: https://github.com/dexie/dexie.js/blob/master/samples/dexie-cloud-todo-app/README.md
Launches the Vitest UI interface for an enhanced testing experience, providing a graphical way to interact with and manage tests.
```bash
npm run test:ui
```
--------------------------------
### Run Tests for Dexie.js
Source: https://github.com/dexie/dexie.js/blob/master/dist/README.md
Execute the test suite to ensure the library is functioning correctly.
```bash
npm test
```
--------------------------------
### Initialize Console for Logging
Source: https://github.com/dexie/dexie.js/blob/master/samples/open-existing-db/dump-databases.html
Replaces the default console to display log messages within a textarea element on the page. This is preparation for the database dumping sample.
```javascript
function Console() {
this.textarea = document.createElement('textarea');
this.log = function (txt, type) {
if (type) this.textarea.value += type + " ";
this.textarea.value += txt + "\n";
}
this.error = function (txt) {
this.log(txt, "ERROR!");
}
}
window.console = new Console();
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('consoleArea').appendChild(console.textarea);
});
```
--------------------------------
### Build Dexie.js
Source: https://github.com/dexie/dexie.js/blob/master/CONTRIBUTING.md
Compiles the Dexie.js source code into distributable files. This command should be run after making changes to the source code.
```bash
pnpm run build
```
--------------------------------
### Watch for Changes During Development
Source: https://github.com/dexie/dexie.js/blob/master/dist/README.md
Run this command to continuously build Dexie.js as you make changes, useful for active development.
```bash
npm run watch
```
--------------------------------
### Test Dexie.js Project
Source: https://github.com/dexie/dexie.js/blob/master/README.md
Run tests for the Dexie.js project using pnpm. This command is essential for verifying the integrity and functionality of the library.
```bash
pnpm test
```
--------------------------------
### Dexie.import()
Source: https://github.com/dexie/dexie.js/blob/master/addons/dexie-export-import/README.md
Static method to import a database from a Blob, returning a new Dexie instance.
```APIDOC
## [METHOD] Dexie.import()
### Description
Static method to import a database from a Blob, creating and returning a new Dexie instance.
### Method
Static Method
### Parameters
#### Request Body
- **blob** (Blob) - Required - The source Blob or File.
- **options** (StaticImportOptions) - Optional - Configuration options for the import process.
### Response
#### Success Response (200)
- **db** (Dexie) - The resulting Dexie database instance.
```
--------------------------------
### Import Dexie Syncable
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Syncable/README.md
Import the necessary modules to enable synchronization functionality.
```javascript
import Dexie from 'dexie';
import 'dexie-syncable'; // will import dexie-observable as well.
```
--------------------------------
### Deploy to GitHub Pages
Source: https://github.com/dexie/dexie.js/blob/master/samples/dexie-cloud-todo-app/README.md
Deploys the built application to the gh-pages branch of the GitHub repository. This makes the PWA accessible at a public URL.
```bash
npm run deploy
```
--------------------------------
### Configure OAuth for Web SPA
Source: https://github.com/dexie/dexie.js/blob/master/addons/dexie-cloud/TODO-SOCIALAUTH.md
Initializes the database connection and handles OAuth redirects automatically via URL parameters.
```typescript
// Configure database
db.cloud.configure({
databaseUrl: 'https://mydb.dexie.cloud'
});
// OAuth callback is handled automatically!
// When page loads with ?dxc-auth=..., the addon:
// 1. Detects the parameter in configure()
// 2. Cleans up the URL immediately
// 3. Completes login in db.on('ready')
// To manually initiate OAuth (e.g., from custom UI):
await db.cloud.login({ provider: 'google' });
// Page redirects to OAuth provider, then back with auth code
```
--------------------------------
### Add Database Manually
Source: https://github.com/dexie/dexie.js/blob/master/samples/open-existing-db/dump-databases.html
Prompts the user for a database name and attempts to open it, adding it to a special '__dbnames' database if successful. This is useful for databases not automatically discovered.
```javascript
function addDatabase(ev) {
const dbname = prompt("Enter name of a database on this origin (" + location.host + ")");
if (!dbname) return;
console.log("Trying to open " + dbname);
return new Dexie(dbname, {addons: []}).open().then(function (db) {
console.log("Database " + dbname + " found. Adding it to __dbnames db");
db.close();
}).then(function () {
return new Dexie ("__dbnames", {addons: []}).open();
}).then(function (db) {
return db.table("dbnames").put({name: dbname}).then(function(){
db.close();
});
}).then(function(){
console.log("Succcessfully added " + dbname + ". Please reload page to dump it!");
}).catch(function (error) {
console.error(error);
});
}
```
--------------------------------
### Dexie.import() Options
Source: https://github.com/dexie/dexie.js/blob/master/addons/dexie-export-import/README.md
Configuration options for importing data into a Dexie database.
```APIDOC
## Dexie.import() Options
### Description
Defines the configuration for the import process, including transaction handling, chunk sizes, and data filtering.
### Parameters
#### Request Body
- **noTransaction** (boolean) - Optional - If true, disables transaction wrapping for the import.
- **chunkSizeBytes** (number) - Optional - Size of chunks in bytes (Default: 1MB).
- **filter** (function) - Optional - Callback to filter tables or rows during import.
- **progressCallback** (function) - Optional - Callback to track import progress.
- **acceptMissingTables** (boolean) - Optional - Allows importing even if tables are missing.
- **acceptVersionDiff** (boolean) - Optional - Allows importing despite database version differences.
- **acceptNameDiff** (boolean) - Optional - Allows importing despite database name differences.
- **acceptChangedPrimaryKey** (boolean) - Optional - Allows importing despite primary key changes.
- **overwriteValues** (boolean) - Optional - Overwrites existing values during import.
- **clearTablesBeforeImport** (boolean) - Optional - Clears tables before starting the import process.
```
--------------------------------
### Run Dexie.js Tests
Source: https://github.com/dexie/dexie.js/blob/master/CONTRIBUTING.md
Executes the test suite for Dexie.js using pnpm. It's recommended to run tests before submitting a pull request.
```bash
pnpm test
```
--------------------------------
### Link Dexie.js to Your App
Source: https://github.com/dexie/dexie.js/blob/master/CONTRIBUTING.md
Link the locally developed Dexie.js package to your application's node_modules. This ensures your app uses your modified version of Dexie.js.
```bash
npm link dexie # Or yarn link dexie / pnpm link dexie depending on your package manager.
```
--------------------------------
### Export and Import Database with Dexie Addon
Source: https://github.com/dexie/dexie.js/blob/master/addons/dexie-export-import/README.md
Use these functions to export an entire Dexie database to a Blob or import a database from a file. Ensure 'dexie-export-import' is imported.
```javascript
import { Dexie } from 'dexie';
import 'dexie-export-import';
async function exportDatabase(databaseName) {
const db = await new Dexie(databaseName).open();
const blob = await db.export();
return blob;
}
async function importDatabase(file) {
const db = await Dexie.import(file);
return db.backendDB();
}
```
--------------------------------
### Using the `using` Keyword with DexieYProvider
Source: https://github.com/dexie/dexie.js/blob/master/addons/y-dexie/README.md
Utilizes the ES2023 `using` keyword for automatic resource management of DexieYProvider, ensuring `release()` is called.
```typescript
using provider = DexieYProvider.load(doc);
await provider.whenLoaded;
...
```
--------------------------------
### Initiate OAuth with Custom URL Scheme
Source: https://github.com/dexie/dexie.js/blob/master/addons/dexie-cloud/oauth_flow.md
For Capacitor or native apps, use this to open the OAuth flow in the system or in-app browser. The custom scheme `myapp://` tells Dexie Cloud to redirect back via deep link.
```javascript
// Open in system browser or in-app browser
Browser.open({
url: `https://.dexie.cloud/oauth/login/google?redirect_uri=${encodeURIComponent('myapp://')}`
});
```
--------------------------------
### Configure Dexie DB with Y.js and Dexie Cloud
Source: https://github.com/dexie/dexie.js/blob/master/addons/y-dexie/README.md
Declare your Dexie database and configure it to use the y-dexie and dexie-cloud addons. Ensure your database URL is correctly set in the `db.cloud.configure` method.
```typescript
import { Dexie } from 'dexie';
import yDexie from 'y-dexie';
import dexieCloud, { DexieCloudTable } from 'dexie-cloud-addon';
import type * as Y from 'yjs';
interface Friend {
id: string;
name: string;
age: number;
notes: Y.Doc;
}
const db = new Dexie('myDB', { addons: [yDexie, dexieCloud] }) as Dexie & {
friends: DexieCloudTable
}
db.version(1).stores({
friends: "
@id,
name,
age,
notes: Y.Doc", // each friend as a 'notes' document
});
db.cloud.configure({
databaseUrl: 'https://xxxxx.dexie.cloud' // Obtained from CLI: `npx dexie-cloud create`
});
```
--------------------------------
### Run Watch Command
Source: https://github.com/dexie/dexie.js/blob/master/README.md
Execute the watch command using pnpm. This is typically used for development to automatically recompile code changes.
```bash
pnpm run watch
```
--------------------------------
### Configure OAuth for Capacitor
Source: https://github.com/dexie/dexie.js/blob/master/addons/dexie-cloud/TODO-SOCIALAUTH.md
Sets up a custom redirect URI and manually handles deep-link callbacks for native mobile environments.
```typescript
// Configure with custom URL scheme
db.cloud.configure({
databaseUrl: 'https://mydb.dexie.cloud',
oauthRedirectUri: 'myapp://'
});
// Handle deep link in app
App.addListener('appUrlOpen', async ({ url }) => {
const callback = handleOAuthCallback(url);
if (callback) {
await db.cloud.login({
oauthCode: callback.code,
provider: callback.provider
});
}
});
// Initiate login (opens system browser)
await db.cloud.login({ provider: 'google' });
```
--------------------------------
### Whitelist PWA URL for Dexie Cloud
Source: https://github.com/dexie/dexie.js/blob/master/samples/dexie-cloud-todo-app/README.md
After deploying, whitelist your PWA's URL with Dexie Cloud to ensure proper functionality. Replace 'your-github-username' with your actual GitHub username.
```bash
npx dexie-cloud whitelist https://your-github-username.github.io
```
--------------------------------
### Render Data with New Control Flow
Source: https://github.com/dexie/dexie.js/blob/master/samples/angular/README.md
Use Angular's @for and @empty syntax to display database records.
```html
@for (item of items(); track item.id) {
{{ item.title }}
} @empty {
No items yet
}
```
--------------------------------
### Define Schema with UUID Primary Keys
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Syncable/README.md
Use the $$ prefix in schema definitions to enable UUID-based primary keys for synchronization.
```javascript
var db = new Dexie("MySyncedDB");
db.version(1).stores({
friends: "$$oid,name,shoeSize",
pets: "$$oid,name,kind"
});
```
--------------------------------
### db.import()
Source: https://github.com/dexie/dexie.js/blob/master/addons/dexie-export-import/README.md
Imports data from a Blob into an existing Dexie database instance.
```APIDOC
## [METHOD] db.import()
### Description
Imports data from a provided Blob or File into an existing Dexie database instance.
### Method
Instance Method
### Parameters
#### Request Body
- **blob** (Blob) - Required - The source Blob or File containing the database data.
- **options** (ImportOptions) - Optional - Configuration options for the import process.
### Response
#### Success Response (200)
- **void** - Returns a promise that resolves when the import is complete.
```
--------------------------------
### Dexie.export()
Source: https://github.com/dexie/dexie.js/blob/master/addons/dexie-export-import/README.md
Exports an existing Dexie database instance to a Blob.
```APIDOC
## [METHOD] db.export()
### Description
Exports the contents of a Dexie database instance to a Blob.
### Method
Instance Method
### Parameters
#### Request Body
- **options** (ExportOptions) - Optional - Configuration options for the export process.
### Response
#### Success Response (200)
- **blob** (Blob) - The exported database content.
### Request Example
const blob = await db.export({ /* options */ });
```
--------------------------------
### Include Required Sources in HTML
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Syncable/README.md
Include the required script files in your HTML document.
```html
...
```
--------------------------------
### Handle Authorization Code in Web and Capacitor
Source: https://github.com/dexie/dexie.js/blob/master/addons/dexie-cloud/oauth_flow.md
Implementations for extracting and decoding the dxc-auth parameter from URLs in browser and native environments.
```js
// Pseudocode for dexie-cloud-addon implementation
function configure(options) {
// Only check in DOM environment, not workers
if (typeof window !== 'undefined' && window.location) {
const encoded = new URLSearchParams(location.search).get('dxc-auth');
if (encoded) {
// Decode base64url (unpadded) to JSON
const padded = encoded + '='.repeat((4 - (encoded.length % 4)) % 4);
const base64 = padded.replace(/-/g, '+').replace(/_/g, '/');
const payload = JSON.parse(atob(base64));
const { code, provider, state, error } = payload;
// Clean up URL immediately (remove dxc-auth param)
const url = new URL(location.href);
url.searchParams.delete('dxc-auth');
history.replaceState(null, '', url.toString());
if (!error) {
// Schedule token exchange (processed in db.on('ready'))
setTimeout(() => {
// Perform token exchange with options.databaseUrl
}, 0);
}
}
}
}
```
```js
// Capacitor example
App.addListener('appUrlOpen', ({ url }) => {
const parsedUrl = new URL(url);
const encoded = parsedUrl.searchParams.get('dxc-auth');
if (encoded) {
const padded = encoded + '='.repeat((4 - (encoded.length % 4)) % 4);
const base64 = padded.replace(/-/g, '+').replace(/_/g, '/');
const payload = JSON.parse(atob(base64));
const { code, provider, state, error } = payload;
// Proceed to token exchange
}
});
```
--------------------------------
### Dexie.js CRUD Operations with liveQuery
Source: https://github.com/dexie/dexie.js/blob/master/samples/liveQuery/liveQuery.html
Performs a sequence of add, update, and delete operations on the 'friends' table, demonstrating how liveQuery automatically reflects these changes. Includes utility for simulating delays between operations.
```javascript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await sleep(1000);
console.log('1. Adding friend');
const friendId = await db.friends.add({ name: 'Magdalena', age: 54 });
await sleep(1000);
console.log('2. Changing age to 99');
await db.friends.update(friendId, { age: 99 });
await sleep(1000);
console.log('3. Changing age to 55');
await db.friends.update(friendId, { age: 55 });
await sleep(1000);
console.log("4. Setting property 'foo' to 'bar'");
await db.friends.update(friendId, { foo: 'bar' });
await sleep(1000);
console.log('5. Deleting friend');
await db.friends.delete(friendId);
subscription.unsubscribe();
```
--------------------------------
### Use useDocument Hook with LiveQuery
Source: https://github.com/dexie/dexie.js/blob/master/addons/y-dexie/README.md
This React component demonstrates using `useLiveQuery` to fetch data and `useDocument` to access the Y.js document for collaborative editing. The `provider` is only available after the initial data load.
```tsx
import { useLiveQuery, useDocument } from 'dexie-react-hooks';
function MyComponent(friendId: number) {
// Query comment object:
const friend = useLiveQuery(() => db.friends.get(friendId));
// Use it's document property (friend is undefined on intial render)
const provider = useDocument(friend?.notes);
// Pass provider and document to some Y.js compliant code in the ecosystem of such (unless undefined)...
return provider
?
: null;
}
```
--------------------------------
### Declare and Manipulate Dexie.js Database
Source: https://github.com/dexie/dexie.js/blob/master/samples/vanilla-js/hello-world.html
This snippet demonstrates how to declare a database schema with a 'friends' table and then add a record, followed by a query to retrieve friends younger than 25. It includes basic error handling.
```javascript
// // Declare Database // var db = new Dexie('FriendDatabase'); db.version(1).stores({
friends: '++id, name, age',
});
// // Manipulate and Query Database // db.friends.add({
name: 'Josephine',
age: 21,
}).then((id) => {
alert(`Successfully added a friend with id ${id}`);
}).then(() => {
return db.friends.where('age').below(25).toArray();
}).then((youngFriends) => {
alert(`My young friends: ${JSON.stringify(youngFriends)}`);
}).catch((error) => {
alert(`Oops, error: ${error}`);
});
```
--------------------------------
### Dexie.Syncable Non-Static Methods
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Syncable/README.md
Methods available on a Dexie database instance for managing syncable connections and configurations.
```APIDOC
## db.syncable.connect
### Description
Create a persistent two-way sync connection with the given URL.
### Method
Instance method
### Endpoint
N/A (Instance method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
db.syncable.connect(protocol, url, options);
```
### Response
None
```
```APIDOC
## db.syncable.disconnect
### Description
Stop syncing with the given URL but keep revision states until next connect.
### Method
Instance method
### Endpoint
N/A (Instance method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
db.syncable.disconnect(url);
```
### Response
None
```
```APIDOC
## db.syncable.delete
### Description
Delete all states and change queue for the given URL.
### Method
Instance method
### Endpoint
N/A (Instance method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
db.syncable.delete(url);
```
### Response
None
```
```APIDOC
## db.syncable.list
### Description
List the URLs of each remote node we have a state saved for.
### Method
Instance method
### Endpoint
N/A (Instance method)
### Parameters
None
### Request Example
```javascript
db.syncable.list().then(urls => console.log(urls));
```
### Response
#### Success Response (200)
- **urls** (Array) - An array of URLs for which sync states are saved.
```
```APIDOC
## db.syncable.setFilter
### Description
Ignore certain objects from being synced defined by the given filter.
### Method
Instance method
### Endpoint
N/A (Instance method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
db.syncable.setFilter(criteria, filter);
```
### Response
None
```
```APIDOC
## db.syncable.getStatus
### Description
Get sync status for the given URL.
### Method
Instance method
### Endpoint
N/A (Instance method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
db.syncable.getStatus(url).then(status => console.log(status));
```
### Response
#### Success Response (200)
- **status** (number) - The current sync status code.
```
```APIDOC
## db.syncable.getOptions
### Description
Get the options object for the given URL.
### Method
Instance method
### Endpoint
N/A (Instance method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
db.syncable.getOptions(url).then(options => console.log(options));
```
### Response
#### Success Response (200)
- **options** (object) - The options object associated with the sync URL.
```
--------------------------------
### Dump All Databases Schema
Source: https://github.com/dexie/dexie.js/blob/master/samples/open-existing-db/dump-databases.html
Iterates through all known databases at the current origin and logs their schema definitions to the console. This code can be extended to dump database objects or monitor live changes.
```javascript
console.log("Dumping Databases");
console.log("=================");
Dexie.getDatabaseNames(function (databaseNames) {
if (databaseNames.length === 0) {
console.log("Could not find databases on current origin.");
console.log("Was your database created without using Dexie? Try the [Add database] button above!");
} else {
dump(databaseNames);
}
function dump(databaseNames) {
if (databaseNames.length > 0) {
var db = new Dexie(databaseNames[0]);
db.open().then(function () {
console.log("var db = new Dexie('" + db.name + "');");
console.log("db.version(" + db.verno + ").stores({");
db.tables.forEach(function (table, i) {
var primKeyAndIndexes = [table.schema.primKey].concat(table.schema.indexes);
var schemaSyntax = primKeyAndIndexes.map(function (index) {
return index.src;
}).join(',');
console.log(" " + table.name + ": " + "'" + schemaSyntax + "'" + (i < db.tables.length - 1 ? "," : ""));
});
console.log("});\n");
}).finally(function () {
db.close();
dump(databaseNames.slice(1));
});
} else {
console.log("Finished dumping databases");
console.log("==========================");
console.log("Hint: Is your DB not listed? Try using the [Add database] button above!");
}
}
});
```
--------------------------------
### db.on('changes') Event
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Observable/README.md
Subscribe to database changes occurring locally or in other browser windows.
```APIDOC
## Event: db.on('changes')
### Description
Subscribe to any database changes no matter if they occur locally or in other browser windows. This enables web applications to react to database changes and update their views accordingly.
### Parameters
- **changes** (Array) - Required - Array of changes that have occurred in the database since the last time the event was triggered.
- **partial** (Boolean) - Required - True if the array does not contain all changes; the callback will be triggered again with the remaining changes.
```
--------------------------------
### Configure WebWorker environment for Dexie.Observable tests
Source: https://github.com/dexie/dexie.js/blob/master/addons/Dexie.Observable/test/integration/test-observable-dexie-tests.html
Sets the worker source and required library imports for testing Dexie.Observable in a WebWorker context.
```javascript
// Hack for making the WebWorker test behave also here... window.workerSource = "worker.js"; window.workerImports = ["../dist/dexie.js", "../addons/Dexie.Observable/dist/dexie-observable.js"];
```
--------------------------------
### Dexie.export() Options
Source: https://github.com/dexie/dexie.js/blob/master/addons/dexie-export-import/README.md
Configuration options for exporting data from a Dexie database.
```APIDOC
## Dexie.export() Options
### Description
Defines the configuration for the export process, including transaction handling, row chunking, and formatting.
### Parameters
#### Request Body
- **noTransaction** (boolean) - Optional - If true, disables transaction wrapping for the export.
- **numRowsPerChunk** (number) - Optional - Number of rows to process per chunk (Default: 2000).
- **prettyJson** (boolean) - Optional - If true, formats the output JSON with indentation.
- **filter** (function) - Optional - Callback to filter tables or rows during export.
- **progressCallback** (function) - Optional - Callback to track export progress.
```
--------------------------------
### Initiate Google OAuth Redirect
Source: https://github.com/dexie/dexie.js/blob/master/addons/dexie-cloud/oauth_flow.md
Use this for web SPAs to redirect the user to Google for authentication. The `redirect_uri` parameter specifies where Dexie Cloud should redirect after authentication, and it can be any page in your app.
```javascript
window.location.href = `https://.dexie.cloud/oauth/login/google?redirect_uri=${encodeURIComponent(location.href)}`;
```