remove: outdated examples from the examples directory
### Changes: - Deleted the following outdated example files from the `examples` directory: - `buildTimeRegistration.js` - `conduitAugmentationExample.js` - `configurationTest.js` - `dataInspectionExample.js` - `import-graphTypes.js` - `browser-server-search/index.html` ### Purpose: These example files were removed as they were no longer relevant or up-to-date with the current state of the project. This cleanup ensures that users referencing examples have access to accurate and relevant documentation and code, reducing potential confusion.
This commit is contained in:
parent
f6059d9484
commit
6cedde94b0
16 changed files with 0 additions and 2718 deletions
|
|
@ -1,67 +0,0 @@
|
|||
<div align="center">
|
||||
<img src="../brainy.png" alt="Brainy Logo" width="200"/>
|
||||
|
||||
# Brainy Examples
|
||||
</div>
|
||||
|
||||
This directory contains examples demonstrating various features and use cases of the Brainy vector graph database.
|
||||
|
||||
## Browser-Server Search Example
|
||||
|
||||
The [browser-server-search](./browser-server-search/) example demonstrates how to use Brainy in a browser, call a server-hosted version for search, store the results locally, and then perform further searches against the local instance.
|
||||
|
||||
This approach allows you to:
|
||||
- Search a server-hosted Brainy instance from a browser
|
||||
- Store the search results in a local Brainy instance
|
||||
- Perform further searches against the local instance without needing to query the server again
|
||||
- Add data to both local and server instances
|
||||
|
||||
See the [browser-server-search README](./browser-server-search/README.md) for detailed instructions.
|
||||
|
||||
## Other Examples
|
||||
|
||||
### Augmentation Examples
|
||||
|
||||
- [conduitAugmentationExample.js](./conduitAugmentationExample.js) - Demonstrates how to use conduit augmentations for syncing Brainy instances
|
||||
- [memoryAugmentationExample.js](./memoryAugmentationExample.js) - Shows how to use memory augmentations for custom storage
|
||||
|
||||
### Pipeline Examples
|
||||
|
||||
- [sequentialPipelineExample.js](./sequentialPipelineExample.js) - Demonstrates the sequential pipeline for processing data
|
||||
|
||||
### Demo
|
||||
|
||||
- [demo.html](./demo.html) - A web demo showcasing Brainy's capabilities
|
||||
|
||||
### Configuration Examples
|
||||
|
||||
- [configurationTest.js](./configurationTest.js) - Shows how to configure Brainy with custom options
|
||||
- [readOnlyTest.js](./readOnlyTest.js) - Demonstrates using Brainy in read-only mode
|
||||
- [buildTimeRegistration.js](./buildTimeRegistration.js) - Shows how to register augmentations at build time
|
||||
|
||||
### Data Inspection
|
||||
|
||||
- [dataInspectionExample.js](./dataInspectionExample.js) - Demonstrates how to inspect data stored in Brainy
|
||||
|
||||
## Running the Examples
|
||||
|
||||
Most JavaScript examples can be run using Node.js:
|
||||
|
||||
```bash
|
||||
node examples/sequentialPipelineExample.js
|
||||
```
|
||||
|
||||
For HTML examples, you can open them directly in a browser or serve them using a local HTTP server:
|
||||
|
||||
```bash
|
||||
# Using a simple HTTP server
|
||||
npx http-server
|
||||
```
|
||||
|
||||
Then navigate to the appropriate URL in your browser (e.g., http://localhost:8080/examples/demo.html).
|
||||
|
||||
## Creating Your Own Examples
|
||||
|
||||
Feel free to use these examples as a starting point for your own projects. You can copy and modify them to suit your needs.
|
||||
|
||||
If you create an example that might be useful to others, consider contributing it back to the Brainy project!
|
||||
|
|
@ -1,191 +0,0 @@
|
|||
<div align="center">
|
||||
<img src="../../brainy.png" alt="Brainy Logo" width="200"/>
|
||||
|
||||
# Brainy Browser-Server Search Example
|
||||
</div>
|
||||
|
||||
This example demonstrates how to use Brainy in a browser, call a server-hosted version for search, store the results locally, and then perform further searches against the local instance.
|
||||
|
||||
## Overview
|
||||
|
||||
The solution consists of:
|
||||
|
||||
1. A `BrainyServerSearch` class that handles the connection to the server and local storage
|
||||
2. An HTML interface for testing the functionality
|
||||
3. Server-side setup using the Brainy cloud wrapper
|
||||
|
||||
This approach allows you to:
|
||||
- Search a server-hosted Brainy instance from a browser
|
||||
- Store the search results in a local Brainy instance
|
||||
- Perform further searches against the local instance without needing to query the server again
|
||||
- Add data to both local and server instances
|
||||
|
||||
## How It Works
|
||||
|
||||
1. The browser creates a local Brainy instance
|
||||
2. It connects to the server-hosted Brainy instance using WebSocket
|
||||
3. When a search is performed:
|
||||
- The query is sent to the server
|
||||
- The server returns the search results
|
||||
- The results are stored in the local Brainy instance
|
||||
- The results are displayed to the user
|
||||
4. Subsequent searches can be performed against the local instance
|
||||
5. A combined search mode first checks the local instance and then queries the server only if needed
|
||||
|
||||
## Setup Instructions
|
||||
|
||||
### Server Setup
|
||||
|
||||
1. Set up the Brainy cloud wrapper:
|
||||
|
||||
```bash
|
||||
# Clone the repository if you haven't already
|
||||
git clone https://github.com/soulcraft/brainy.git
|
||||
cd brainy/cloud-wrapper
|
||||
|
||||
# Install dependencies
|
||||
npm install --legacy-peer-deps
|
||||
|
||||
# Configure the server
|
||||
cp .env.example .env
|
||||
# Edit .env to configure your environment
|
||||
|
||||
# Build and start the server
|
||||
npm run build
|
||||
npm run start
|
||||
```
|
||||
|
||||
2. Note the WebSocket URL of your server (e.g., `wss://your-server.com/ws` or `ws://localhost:3000/ws` for local development)
|
||||
|
||||
### Client Setup
|
||||
|
||||
1. Copy the example files to your project:
|
||||
|
||||
```bash
|
||||
cp -r examples/browser-server-search your-project/
|
||||
```
|
||||
|
||||
2. Include the Brainy library in your project:
|
||||
|
||||
```bash
|
||||
npm install @soulcraft/brainy --legacy-peer-deps
|
||||
```
|
||||
|
||||
3. Open the HTML file in a browser or serve it using a local server:
|
||||
|
||||
```bash
|
||||
# Using a simple HTTP server
|
||||
cd your-project
|
||||
npx http-server
|
||||
```
|
||||
|
||||
4. Navigate to http://localhost:8080/browser-server-search/ in your browser
|
||||
|
||||
5. Enter the WebSocket URL of your server and start using the example
|
||||
|
||||
## Usage
|
||||
|
||||
### Using the HTML Interface
|
||||
|
||||
1. Enter the WebSocket URL of your Brainy server
|
||||
2. Click "Connect" to establish a connection
|
||||
3. Enter a search query and click one of the search buttons:
|
||||
- "Search Server" - Search the server and store results locally
|
||||
- "Search Local" - Search only the local instance
|
||||
- "Search Combined" - Search local first, then server if needed
|
||||
4. To add data, enter text in the "Add Data" field and click "Add to Both"
|
||||
|
||||
### Using the BrainyServerSearch Class in Your Code
|
||||
|
||||
```javascript
|
||||
import { BrainyServerSearch } from './index.js';
|
||||
|
||||
// Create a new instance
|
||||
const brainySearch = new BrainyServerSearch('wss://your-brainy-server.com/ws');
|
||||
|
||||
// Initialize and connect
|
||||
await brainySearch.init();
|
||||
|
||||
// Search the server and store results locally
|
||||
const serverResults = await brainySearch.searchServer('machine learning', 5);
|
||||
|
||||
// Search the local instance
|
||||
const localResults = await brainySearch.searchLocal('machine learning', 5);
|
||||
|
||||
// Perform a combined search
|
||||
const combinedResults = await brainySearch.searchCombined('neural networks', 5);
|
||||
|
||||
// Add data to both local and server
|
||||
const id = await brainySearch.add('Deep learning is a subset of machine learning', {
|
||||
noun: 'Concept',
|
||||
category: 'AI',
|
||||
tags: ['deep learning', 'neural networks']
|
||||
});
|
||||
|
||||
// Close the connection when done
|
||||
await brainySearch.close();
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### BrainyServerSearch Class
|
||||
|
||||
#### Constructor
|
||||
|
||||
```javascript
|
||||
const brainySearch = new BrainyServerSearch(serverUrl);
|
||||
```
|
||||
|
||||
- `serverUrl` (string): WebSocket URL of the Brainy server
|
||||
|
||||
#### Methods
|
||||
|
||||
- `init()`: Initialize the local Brainy instance and connect to the server
|
||||
- `searchServer(query, limit = 10)`: Search the server-hosted Brainy instance, store results locally, and return them
|
||||
- `searchLocal(query, limit = 10)`: Search the local Brainy instance
|
||||
- `searchCombined(query, limit = 10)`: Search both server and local instances, combine results, and store server results locally
|
||||
- `add(data, metadata = {})`: Add data to both local and server instances
|
||||
- `close()`: Close the connection to the server
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
### Custom Embedding Function
|
||||
|
||||
You can customize the embedding function used by the local Brainy instance:
|
||||
|
||||
```javascript
|
||||
import { createSimpleEmbeddingFunction } from '@soulcraft/brainy';
|
||||
|
||||
// In your code, before calling init():
|
||||
brainySearch.setEmbeddingFunction(createSimpleEmbeddingFunction());
|
||||
```
|
||||
|
||||
### Persistent Storage
|
||||
|
||||
To enable persistent storage for the local Brainy instance:
|
||||
|
||||
```javascript
|
||||
// In your code, before calling init():
|
||||
brainySearch.setStorageOptions({
|
||||
requestPersistentStorage: true
|
||||
});
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Connection Issues
|
||||
|
||||
- Ensure the server is running and accessible
|
||||
- Check that the WebSocket URL is correct
|
||||
- Verify that your browser supports WebSockets
|
||||
- Check for CORS issues if the server is on a different domain
|
||||
|
||||
### Search Issues
|
||||
|
||||
- Ensure the server has data to search
|
||||
- Check that the query is not empty
|
||||
- Verify that the server is properly configured for search
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
|
|
@ -1,254 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Brainy Browser-Server Search Example</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
h1, h2 {
|
||||
color: #333;
|
||||
}
|
||||
pre {
|
||||
background-color: #f5f5f5;
|
||||
padding: 10px;
|
||||
border-radius: 5px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
button {
|
||||
background-color: #4CAF50;
|
||||
border: none;
|
||||
color: white;
|
||||
padding: 10px 20px;
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
font-size: 16px;
|
||||
margin: 4px 2px;
|
||||
cursor: pointer;
|
||||
border-radius: 5px;
|
||||
}
|
||||
input[type="text"] {
|
||||
padding: 10px;
|
||||
width: 70%;
|
||||
margin-right: 10px;
|
||||
border-radius: 5px;
|
||||
border: 1px solid #ddd;
|
||||
}
|
||||
.result-container {
|
||||
margin-top: 20px;
|
||||
border: 1px solid #ddd;
|
||||
padding: 10px;
|
||||
border-radius: 5px;
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.log {
|
||||
margin-top: 10px;
|
||||
color: #666;
|
||||
}
|
||||
.error {
|
||||
color: red;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div style="display: flex; align-items: center; margin-bottom: 20px;">
|
||||
<img src="../../brainy.png" alt="Brainy Logo" width="100" style="margin-right: 20px;"/>
|
||||
<h1>Brainy Browser-Server Search Example</h1>
|
||||
</div>
|
||||
|
||||
<p>
|
||||
This example demonstrates how to use Brainy in a browser, call a server-hosted version for search,
|
||||
store the results locally, and then perform further searches against the local instance.
|
||||
</p>
|
||||
|
||||
<div>
|
||||
<h2>Server URL</h2>
|
||||
<input type="text" id="serverUrl" value="wss://your-brainy-server.com/ws" placeholder="WebSocket URL of your Brainy server">
|
||||
<button id="connectBtn">Connect</button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2>Search</h2>
|
||||
<input type="text" id="searchQuery" placeholder="Enter search query">
|
||||
<button id="searchServerBtn">Search Server</button>
|
||||
<button id="searchLocalBtn">Search Local</button>
|
||||
<button id="searchCombinedBtn">Search Combined</button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2>Add Data</h2>
|
||||
<input type="text" id="addData" placeholder="Enter text to add">
|
||||
<button id="addBtn">Add to Both</button>
|
||||
</div>
|
||||
|
||||
<div class="result-container">
|
||||
<h2>Results</h2>
|
||||
<pre id="results">Connect to a server to begin...</pre>
|
||||
</div>
|
||||
|
||||
<div class="log" id="log"></div>
|
||||
|
||||
<!-- Import the Brainy library -->
|
||||
<script type="module">
|
||||
// Import the BrainyServerSearch class
|
||||
import { BrainyServerSearch } from './index.js';
|
||||
|
||||
// Global variables
|
||||
let brainySearch = null;
|
||||
|
||||
// DOM elements
|
||||
const serverUrlInput = document.getElementById('serverUrl');
|
||||
const connectBtn = document.getElementById('connectBtn');
|
||||
const searchQueryInput = document.getElementById('searchQuery');
|
||||
const searchServerBtn = document.getElementById('searchServerBtn');
|
||||
const searchLocalBtn = document.getElementById('searchLocalBtn');
|
||||
const searchCombinedBtn = document.getElementById('searchCombinedBtn');
|
||||
const addDataInput = document.getElementById('addData');
|
||||
const addBtn = document.getElementById('addBtn');
|
||||
const resultsElement = document.getElementById('results');
|
||||
const logElement = document.getElementById('log');
|
||||
|
||||
// Helper functions
|
||||
function log(message, isError = false) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = message;
|
||||
if (isError) {
|
||||
div.classList.add('error');
|
||||
}
|
||||
logElement.appendChild(div);
|
||||
logElement.scrollTop = logElement.scrollHeight;
|
||||
}
|
||||
|
||||
function displayResults(results) {
|
||||
resultsElement.textContent = JSON.stringify(results, null, 2);
|
||||
}
|
||||
|
||||
// Event handlers
|
||||
connectBtn.addEventListener('click', async () => {
|
||||
const serverUrl = serverUrlInput.value.trim();
|
||||
if (!serverUrl) {
|
||||
log('Please enter a server URL', true);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
log(`Connecting to ${serverUrl}...`);
|
||||
brainySearch = new BrainyServerSearch(serverUrl);
|
||||
await brainySearch.init();
|
||||
log('Connected successfully!');
|
||||
displayResults({ status: 'Connected', serverUrl });
|
||||
} catch (error) {
|
||||
log(`Connection error: ${error.message}`, true);
|
||||
displayResults({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
searchServerBtn.addEventListener('click', async () => {
|
||||
if (!brainySearch) {
|
||||
log('Please connect to a server first', true);
|
||||
return;
|
||||
}
|
||||
|
||||
const query = searchQueryInput.value.trim();
|
||||
if (!query) {
|
||||
log('Please enter a search query', true);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
log(`Searching server for "${query}"...`);
|
||||
const results = await brainySearch.searchServer(query, 5);
|
||||
log(`Found ${results.length} results from server`);
|
||||
displayResults(results);
|
||||
} catch (error) {
|
||||
log(`Search error: ${error.message}`, true);
|
||||
displayResults({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
searchLocalBtn.addEventListener('click', async () => {
|
||||
if (!brainySearch) {
|
||||
log('Please connect to a server first', true);
|
||||
return;
|
||||
}
|
||||
|
||||
const query = searchQueryInput.value.trim();
|
||||
if (!query) {
|
||||
log('Please enter a search query', true);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
log(`Searching local database for "${query}"...`);
|
||||
const results = await brainySearch.searchLocal(query, 5);
|
||||
log(`Found ${results.length} results locally`);
|
||||
displayResults(results);
|
||||
} catch (error) {
|
||||
log(`Search error: ${error.message}`, true);
|
||||
displayResults({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
searchCombinedBtn.addEventListener('click', async () => {
|
||||
if (!brainySearch) {
|
||||
log('Please connect to a server first', true);
|
||||
return;
|
||||
}
|
||||
|
||||
const query = searchQueryInput.value.trim();
|
||||
if (!query) {
|
||||
log('Please enter a search query', true);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
log(`Performing combined search for "${query}"...`);
|
||||
const results = await brainySearch.searchCombined(query, 5);
|
||||
log(`Found ${results.length} combined results`);
|
||||
displayResults(results);
|
||||
} catch (error) {
|
||||
log(`Search error: ${error.message}`, true);
|
||||
displayResults({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
addBtn.addEventListener('click', async () => {
|
||||
if (!brainySearch) {
|
||||
log('Please connect to a server first', true);
|
||||
return;
|
||||
}
|
||||
|
||||
const data = addDataInput.value.trim();
|
||||
if (!data) {
|
||||
log('Please enter data to add', true);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
log(`Adding data: "${data}"...`);
|
||||
const id = await brainySearch.add(data, {
|
||||
noun: 'Concept',
|
||||
category: 'UserInput',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
log(`Added data with ID: ${id}`);
|
||||
displayResults({ success: true, id, data });
|
||||
} catch (error) {
|
||||
log(`Add error: ${error.message}`, true);
|
||||
displayResults({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Initial log
|
||||
log('Ready to connect to a Brainy server');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,278 +0,0 @@
|
|||
// Browser-Server Search Example
|
||||
// This example demonstrates how to use Brainy in a browser, call a server-hosted version for search,
|
||||
// store the results locally, and then perform further searches against the local instance.
|
||||
|
||||
import {
|
||||
BrainyData,
|
||||
augmentationPipeline,
|
||||
createConduitAugmentation,
|
||||
NounType
|
||||
} from '@soulcraft/brainy';
|
||||
|
||||
/**
|
||||
* BrainyServerSearch class
|
||||
* Provides functionality to search a server-hosted Brainy instance and store results locally
|
||||
*/
|
||||
class BrainyServerSearch {
|
||||
constructor(serverUrl) {
|
||||
this.serverUrl = serverUrl;
|
||||
this.localDb = null;
|
||||
this.wsConduit = null;
|
||||
this.connection = null;
|
||||
this.isInitialized = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the local Brainy instance and connect to the server
|
||||
*/
|
||||
async init() {
|
||||
if (this.isInitialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Initialize local Brainy instance
|
||||
this.localDb = new BrainyData();
|
||||
await this.localDb.init();
|
||||
|
||||
// Create a WebSocket conduit augmentation
|
||||
this.wsConduit = await createConduitAugmentation('websocket', 'server-search-conduit');
|
||||
|
||||
// Register the augmentation with the pipeline
|
||||
augmentationPipeline.register(this.wsConduit);
|
||||
|
||||
// Connect to the server
|
||||
const connectionResult = await augmentationPipeline.executeConduitPipeline(
|
||||
'establishConnection',
|
||||
[this.serverUrl, { protocols: 'brainy-sync' }]
|
||||
);
|
||||
|
||||
if (connectionResult[0] && (await connectionResult[0]).success) {
|
||||
this.connection = (await connectionResult[0]).data;
|
||||
console.log('Connected to server:', this.serverUrl);
|
||||
this.isInitialized = true;
|
||||
} else {
|
||||
throw new Error('Failed to connect to server');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize BrainyServerSearch:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search the server-hosted Brainy instance, store results locally, and return them
|
||||
* @param {string} query - The search query
|
||||
* @param {number} limit - Maximum number of results to return
|
||||
* @returns {Promise<Array>} - Search results
|
||||
*/
|
||||
async searchServer(query, limit = 10) {
|
||||
await this.ensureInitialized();
|
||||
|
||||
try {
|
||||
// Create a search request
|
||||
const readResult = await augmentationPipeline.executeConduitPipeline(
|
||||
'readData',
|
||||
[{
|
||||
connectionId: this.connection.connectionId,
|
||||
query: {
|
||||
type: 'search',
|
||||
query: query,
|
||||
limit: limit
|
||||
}
|
||||
}]
|
||||
);
|
||||
|
||||
if (readResult[0] && (await readResult[0]).success) {
|
||||
const searchResults = (await readResult[0]).data;
|
||||
|
||||
// Store the results in the local Brainy instance
|
||||
for (const result of searchResults) {
|
||||
// Check if the noun already exists in the local database
|
||||
const existingNoun = await this.localDb.get(result.id);
|
||||
|
||||
if (!existingNoun) {
|
||||
// Add the noun to the local database
|
||||
await this.localDb.add(result.vector, result.metadata);
|
||||
}
|
||||
}
|
||||
|
||||
return searchResults;
|
||||
} else {
|
||||
const error = readResult[0] ? (await readResult[0]).error : 'Unknown error';
|
||||
throw new Error(`Failed to search server: ${error}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error searching server:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search the local Brainy instance
|
||||
* @param {string} query - The search query
|
||||
* @param {number} limit - Maximum number of results to return
|
||||
* @returns {Promise<Array>} - Search results
|
||||
*/
|
||||
async searchLocal(query, limit = 10) {
|
||||
await this.ensureInitialized();
|
||||
|
||||
try {
|
||||
return await this.localDb.searchText(query, limit);
|
||||
} catch (error) {
|
||||
console.error('Error searching local database:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search both server and local instances, combine results, and store server results locally
|
||||
* @param {string} query - The search query
|
||||
* @param {number} limit - Maximum number of results to return
|
||||
* @returns {Promise<Array>} - Combined search results
|
||||
*/
|
||||
async searchCombined(query, limit = 10) {
|
||||
await this.ensureInitialized();
|
||||
|
||||
try {
|
||||
// Search local first
|
||||
const localResults = await this.searchLocal(query, limit);
|
||||
|
||||
// If we have enough local results, return them
|
||||
if (localResults.length >= limit) {
|
||||
return localResults;
|
||||
}
|
||||
|
||||
// Otherwise, search server for additional results
|
||||
const serverResults = await this.searchServer(query, limit - localResults.length);
|
||||
|
||||
// Combine results, removing duplicates
|
||||
const combinedResults = [...localResults];
|
||||
const localIds = new Set(localResults.map(r => r.id));
|
||||
|
||||
for (const result of serverResults) {
|
||||
if (!localIds.has(result.id)) {
|
||||
combinedResults.push(result);
|
||||
}
|
||||
}
|
||||
|
||||
return combinedResults;
|
||||
} catch (error) {
|
||||
console.error('Error performing combined search:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add data to both local and server instances
|
||||
* @param {string|Array} data - Text or vector to add
|
||||
* @param {Object} metadata - Metadata for the data
|
||||
* @returns {Promise<string>} - ID of the added data
|
||||
*/
|
||||
async add(data, metadata = {}) {
|
||||
await this.ensureInitialized();
|
||||
|
||||
try {
|
||||
// Add to local first
|
||||
const id = await this.localDb.add(data, metadata);
|
||||
|
||||
// Get the vector and metadata
|
||||
const noun = await this.localDb.get(id);
|
||||
|
||||
// Add to server
|
||||
await augmentationPipeline.executeConduitPipeline(
|
||||
'writeData',
|
||||
[{
|
||||
connectionId: this.connection.connectionId,
|
||||
data: {
|
||||
type: 'addNoun',
|
||||
vector: noun.vector,
|
||||
metadata: noun.metadata
|
||||
}
|
||||
}]
|
||||
);
|
||||
|
||||
return id;
|
||||
} catch (error) {
|
||||
console.error('Error adding data:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the instance is initialized
|
||||
*/
|
||||
async ensureInitialized() {
|
||||
if (!this.isInitialized) {
|
||||
await this.init();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the connection to the server
|
||||
*/
|
||||
async close() {
|
||||
if (this.connection) {
|
||||
try {
|
||||
await this.wsConduit.closeWebSocket(this.connection.connectionId);
|
||||
this.connection = null;
|
||||
} catch (error) {
|
||||
console.error('Error closing connection:', error);
|
||||
}
|
||||
}
|
||||
|
||||
this.isInitialized = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Example usage
|
||||
async function runExample() {
|
||||
// Create a BrainyServerSearch instance
|
||||
const brainySearch = new BrainyServerSearch('wss://your-brainy-server.com/ws');
|
||||
|
||||
try {
|
||||
// Initialize
|
||||
await brainySearch.init();
|
||||
|
||||
// Search the server and store results locally
|
||||
console.log('Searching server for "machine learning"...');
|
||||
const serverResults = await brainySearch.searchServer('machine learning', 5);
|
||||
console.log('Server results:', serverResults);
|
||||
|
||||
// Now search locally - this should return the results we just stored
|
||||
console.log('Searching local database for "machine learning"...');
|
||||
const localResults = await brainySearch.searchLocal('machine learning', 5);
|
||||
console.log('Local results:', localResults);
|
||||
|
||||
// Search for something related but different
|
||||
console.log('Searching local database for "artificial intelligence"...');
|
||||
const aiResults = await brainySearch.searchLocal('artificial intelligence', 5);
|
||||
console.log('AI results:', aiResults);
|
||||
|
||||
// Perform a combined search
|
||||
console.log('Performing combined search for "neural networks"...');
|
||||
const combinedResults = await brainySearch.searchCombined('neural networks', 5);
|
||||
console.log('Combined results:', combinedResults);
|
||||
|
||||
// Add new data to both local and server
|
||||
console.log('Adding new data...');
|
||||
const id = await brainySearch.add('Deep learning is a subset of machine learning', {
|
||||
noun: NounType.Concept,
|
||||
category: 'AI',
|
||||
tags: ['deep learning', 'neural networks']
|
||||
});
|
||||
console.log('Added data with ID:', id);
|
||||
|
||||
// Close the connection
|
||||
await brainySearch.close();
|
||||
|
||||
} catch (error) {
|
||||
console.error('Example failed:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// In a browser environment, you would call this when the page loads
|
||||
// runExample();
|
||||
|
||||
// Export for use in other modules
|
||||
export { BrainyServerSearch };
|
||||
|
|
@ -1,184 +0,0 @@
|
|||
/**
|
||||
* Example: Registering Augmentations at Build Time
|
||||
*
|
||||
* This example demonstrates how to register custom augmentations at build time
|
||||
* using the Brainy library's augmentation registry system.
|
||||
*/
|
||||
|
||||
// Import the augmentation registry and types from Brainy
|
||||
import {
|
||||
registerAugmentation,
|
||||
AugmentationType,
|
||||
BrainyAugmentations
|
||||
} from '../dist/index.js';
|
||||
|
||||
// Define a custom sense augmentation
|
||||
class CustomTextSenseAugmentation {
|
||||
constructor() {
|
||||
this.name = 'CustomTextSenseAugmentation';
|
||||
this.enabled = true;
|
||||
this.type = AugmentationType.SENSE;
|
||||
}
|
||||
|
||||
// Required IAugmentation methods
|
||||
async initialize() {
|
||||
console.log('Initializing CustomTextSenseAugmentation');
|
||||
return true;
|
||||
}
|
||||
|
||||
async shutDown() {
|
||||
console.log('Shutting down CustomTextSenseAugmentation');
|
||||
return true;
|
||||
}
|
||||
|
||||
getStatus() {
|
||||
return {
|
||||
name: this.name,
|
||||
enabled: this.enabled,
|
||||
type: this.type,
|
||||
status: 'ready'
|
||||
};
|
||||
}
|
||||
|
||||
// ISenseAugmentation methods
|
||||
async processRawData(rawData, dataType) {
|
||||
console.log(`Processing ${dataType} data: ${rawData.substring(0, 50)}...`);
|
||||
|
||||
// Simple implementation to extract nouns and verbs
|
||||
const words = rawData.split(' ');
|
||||
const nouns = words.filter(word => word.length > 4);
|
||||
const verbs = words.filter(word => word.endsWith('ing'));
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: { nouns, verbs }
|
||||
};
|
||||
}
|
||||
|
||||
async listenToFeed(feedUrl, callback) {
|
||||
console.log(`Listening to feed at ${feedUrl}`);
|
||||
|
||||
// In a real implementation, this would set up a listener
|
||||
// For this example, we'll just call the callback once
|
||||
setTimeout(() => {
|
||||
callback({
|
||||
success: true,
|
||||
data: { message: 'Feed update received' }
|
||||
});
|
||||
}, 1000);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: { feedId: 'example-feed-1' }
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Define a custom memory augmentation
|
||||
class CustomMemoryAugmentation {
|
||||
constructor() {
|
||||
this.name = 'CustomMemoryAugmentation';
|
||||
this.enabled = true;
|
||||
this.type = AugmentationType.MEMORY;
|
||||
this.storage = new Map();
|
||||
}
|
||||
|
||||
// Required IAugmentation methods
|
||||
async initialize() {
|
||||
console.log('Initializing CustomMemoryAugmentation');
|
||||
return true;
|
||||
}
|
||||
|
||||
async shutDown() {
|
||||
console.log('Shutting down CustomMemoryAugmentation');
|
||||
this.storage.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
getStatus() {
|
||||
return {
|
||||
name: this.name,
|
||||
enabled: this.enabled,
|
||||
type: this.type,
|
||||
status: 'ready',
|
||||
itemCount: this.storage.size
|
||||
};
|
||||
}
|
||||
|
||||
// IMemoryAugmentation methods
|
||||
async storeData(key, data, options = {}) {
|
||||
console.log(`Storing data with key: ${key}`);
|
||||
this.storage.set(key, data);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: { key }
|
||||
};
|
||||
}
|
||||
|
||||
async retrieveData(key, options = {}) {
|
||||
console.log(`Retrieving data with key: ${key}`);
|
||||
const data = this.storage.get(key);
|
||||
|
||||
return {
|
||||
success: !!data,
|
||||
data: data || null,
|
||||
error: !data ? 'Key not found' : undefined
|
||||
};
|
||||
}
|
||||
|
||||
async updateData(key, data, options = {}) {
|
||||
console.log(`Updating data with key: ${key}`);
|
||||
|
||||
if (!this.storage.has(key)) {
|
||||
return {
|
||||
success: false,
|
||||
data: null,
|
||||
error: 'Key not found'
|
||||
};
|
||||
}
|
||||
|
||||
this.storage.set(key, data);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: { key }
|
||||
};
|
||||
}
|
||||
|
||||
async deleteData(key, options = {}) {
|
||||
console.log(`Deleting data with key: ${key}`);
|
||||
|
||||
const existed = this.storage.has(key);
|
||||
this.storage.delete(key);
|
||||
|
||||
return {
|
||||
success: existed,
|
||||
data: { deleted: existed },
|
||||
error: !existed ? 'Key not found' : undefined
|
||||
};
|
||||
}
|
||||
|
||||
async listDataKeys(pattern = '*', options = {}) {
|
||||
console.log(`Listing data keys with pattern: ${pattern}`);
|
||||
|
||||
// Simple implementation that returns all keys
|
||||
// A real implementation would filter by pattern
|
||||
const keys = Array.from(this.storage.keys());
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: { keys }
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Register the augmentations with the registry
|
||||
// This will make them available to the Brainy library at runtime
|
||||
const textSenseAugmentation = registerAugmentation(new CustomTextSenseAugmentation());
|
||||
const memoryAugmentation = registerAugmentation(new CustomMemoryAugmentation());
|
||||
|
||||
console.log('Custom augmentations registered successfully');
|
||||
|
||||
// Export the registered augmentations for use in the application
|
||||
export { textSenseAugmentation, memoryAugmentation };
|
||||
|
|
@ -1,236 +0,0 @@
|
|||
/**
|
||||
* Conduit Augmentation Example
|
||||
*
|
||||
* This example demonstrates how to use the conduit augmentations to sync Brainy instances:
|
||||
*
|
||||
* - WebSocket Conduit: For syncing between browsers and servers, or between servers.
|
||||
* WebSockets cannot be used for direct browser-to-browser communication without a server in the middle.
|
||||
*
|
||||
* - WebRTC Conduit: For direct peer-to-peer syncing between browsers.
|
||||
* This is the recommended approach for browser-to-browser communication.
|
||||
*/
|
||||
|
||||
import {
|
||||
BrainyData,
|
||||
augmentationPipeline,
|
||||
createConduitAugmentation,
|
||||
NounType,
|
||||
VerbType
|
||||
} from '@soulcraft/brainy';
|
||||
|
||||
/**
|
||||
* Example of using WebSocket conduit augmentation to sync Brainy instances
|
||||
*/
|
||||
async function webSocketSyncExample() {
|
||||
console.log('Starting WebSocket sync example...');
|
||||
|
||||
// Create and initialize the database
|
||||
const db = new BrainyData();
|
||||
await db.init();
|
||||
|
||||
// Create a WebSocket conduit augmentation
|
||||
const wsConduit = await createConduitAugmentation('websocket', 'websocket-sync-example');
|
||||
|
||||
// Register the augmentation with the pipeline
|
||||
augmentationPipeline.register(wsConduit);
|
||||
|
||||
// Add some data to the local database
|
||||
const catId = await db.add("Cats are independent pets", {
|
||||
noun: NounType.Thing,
|
||||
category: 'animal'
|
||||
});
|
||||
|
||||
const dogId = await db.add("Dogs are loyal companions", {
|
||||
noun: NounType.Thing,
|
||||
category: 'animal'
|
||||
});
|
||||
|
||||
// Add a relationship between items
|
||||
await db.addVerb(catId, dogId, undefined, {
|
||||
type: VerbType.RelatedTo,
|
||||
metadata: {
|
||||
description: 'Both are common household pets'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Added sample data to local database');
|
||||
|
||||
try {
|
||||
// Connect to another Brainy instance (server or browser)
|
||||
// Note: You need to have a WebSocket server running at this URL
|
||||
const connectionResult = await augmentationPipeline.executeConduitPipeline(
|
||||
'establishConnection',
|
||||
['wss://your-websocket-server.com/brainy-sync', { protocols: 'brainy-sync' }]
|
||||
);
|
||||
|
||||
if (connectionResult[0] && (await connectionResult[0]).success) {
|
||||
const connection = (await connectionResult[0]).data;
|
||||
console.log('Connected to remote Brainy instance:', connection.url);
|
||||
|
||||
// Read data from the remote instance
|
||||
const readResult = await augmentationPipeline.executeConduitPipeline(
|
||||
'readData',
|
||||
[{ connectionId: connection.connectionId, query: { type: 'getAllNouns' } }]
|
||||
);
|
||||
|
||||
// Process and add the received data to the local instance
|
||||
if (readResult[0] && (await readResult[0]).success) {
|
||||
const remoteNouns = (await readResult[0]).data;
|
||||
console.log(`Received ${remoteNouns.length} nouns from remote instance`);
|
||||
|
||||
for (const noun of remoteNouns) {
|
||||
await db.add(noun.vector, noun.metadata);
|
||||
}
|
||||
|
||||
console.log('Added remote nouns to local database');
|
||||
}
|
||||
|
||||
// Set up real-time sync by monitoring the stream
|
||||
await wsConduit.monitorStream(connection.connectionId, async (data) => {
|
||||
console.log('Received data from stream:', data.type);
|
||||
|
||||
// Handle incoming data (e.g., new nouns, verbs, updates)
|
||||
if (data.type === 'newNoun') {
|
||||
await db.add(data.vector, data.metadata);
|
||||
console.log('Added new noun from remote instance:', data.id);
|
||||
} else if (data.type === 'newVerb') {
|
||||
await db.addVerb(data.sourceId, data.targetId, data.vector, data.options);
|
||||
console.log('Added new verb from remote instance:', data.id);
|
||||
}
|
||||
});
|
||||
|
||||
// Add a new noun and send it to the remote instance
|
||||
const birdId = await db.add("Birds are fascinating creatures", {
|
||||
noun: NounType.Thing,
|
||||
category: 'animal'
|
||||
});
|
||||
|
||||
const birdData = await db.get(birdId);
|
||||
|
||||
// Send the new noun to the remote instance
|
||||
await augmentationPipeline.executeConduitPipeline(
|
||||
'writeData',
|
||||
[
|
||||
{
|
||||
connectionId: connection.connectionId,
|
||||
data: {
|
||||
type: 'newNoun',
|
||||
id: birdId,
|
||||
vector: birdData.vector,
|
||||
metadata: birdData.metadata
|
||||
}
|
||||
}
|
||||
]
|
||||
);
|
||||
|
||||
console.log('Sent new noun to remote instance:', birdId);
|
||||
|
||||
// Close the connection when done
|
||||
await wsConduit.closeWebSocket(connection.connectionId);
|
||||
console.log('Closed connection to remote instance');
|
||||
} else {
|
||||
console.error('Failed to connect to remote instance');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error in WebSocket sync example:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Example of using WebRTC conduit augmentation for peer-to-peer sync
|
||||
*/
|
||||
async function webRTCSyncExample() {
|
||||
console.log('Starting WebRTC sync example...');
|
||||
|
||||
// Create and initialize the database
|
||||
const db = new BrainyData();
|
||||
await db.init();
|
||||
|
||||
// Create a WebRTC conduit augmentation
|
||||
const webrtcConduit = await createConduitAugmentation('webrtc', 'webrtc-sync-example');
|
||||
|
||||
// Register the augmentation with the pipeline
|
||||
augmentationPipeline.register(webrtcConduit);
|
||||
|
||||
try {
|
||||
// Connect to a peer using a signaling server
|
||||
// Note: You need to have a signaling server running and another peer to connect to
|
||||
const connectionResult = await augmentationPipeline.executeConduitPipeline(
|
||||
'establishConnection',
|
||||
[
|
||||
'peer-id-to-connect-to',
|
||||
{
|
||||
signalServerUrl: 'wss://your-signal-server.com',
|
||||
localPeerId: 'my-peer-id',
|
||||
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
|
||||
}
|
||||
]
|
||||
);
|
||||
|
||||
if (connectionResult[0] && (await connectionResult[0]).success) {
|
||||
const connection = (await connectionResult[0]).data;
|
||||
console.log('Connected to peer:', connection.url);
|
||||
|
||||
// Set up real-time sync by monitoring the stream
|
||||
await webrtcConduit.monitorStream(connection.connectionId, async (data) => {
|
||||
console.log('Received data from peer:', data.type);
|
||||
|
||||
// Handle incoming data (e.g., new nouns, verbs, updates)
|
||||
if (data.type === 'newNoun') {
|
||||
await db.add(data.vector, data.metadata);
|
||||
console.log('Added new noun from peer:', data.id);
|
||||
} else if (data.type === 'newVerb') {
|
||||
await db.addVerb(data.sourceId, data.targetId, data.vector, data.options);
|
||||
console.log('Added new verb from peer:', data.id);
|
||||
}
|
||||
});
|
||||
|
||||
// Add a new noun and send it to the peer
|
||||
const fishId = await db.add("Fish are aquatic animals", {
|
||||
noun: NounType.Thing,
|
||||
category: 'animal'
|
||||
});
|
||||
|
||||
const fishData = await db.get(fishId);
|
||||
|
||||
// Send the new noun to the peer
|
||||
await augmentationPipeline.executeConduitPipeline(
|
||||
'writeData',
|
||||
[
|
||||
{
|
||||
connectionId: connection.connectionId,
|
||||
data: {
|
||||
type: 'newNoun',
|
||||
id: fishId,
|
||||
vector: fishData.vector,
|
||||
metadata: fishData.metadata
|
||||
}
|
||||
}
|
||||
]
|
||||
);
|
||||
|
||||
console.log('Sent new noun to peer:', fishId);
|
||||
|
||||
// Close the connection when done
|
||||
await webrtcConduit.closeWebSocket(connection.connectionId);
|
||||
console.log('Closed connection to peer');
|
||||
} else {
|
||||
console.error('Failed to connect to peer');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error in WebRTC sync example:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Run the examples
|
||||
async function runExamples() {
|
||||
try {
|
||||
await webSocketSyncExample();
|
||||
console.log('\n-----------------------------------\n');
|
||||
await webRTCSyncExample();
|
||||
} catch (error) {
|
||||
console.error('Error running examples:', error);
|
||||
}
|
||||
}
|
||||
|
||||
runExamples();
|
||||
|
|
@ -1,74 +0,0 @@
|
|||
// Configuration Test Script
|
||||
// This script tests the automatic configuration detection features of the library
|
||||
|
||||
const { BrainyData } = require('../dist/index.js');
|
||||
|
||||
async function testDefaultConfiguration() {
|
||||
console.log('Testing default configuration...');
|
||||
|
||||
// Create a database with no configuration
|
||||
const db = new BrainyData();
|
||||
await db.init();
|
||||
|
||||
// Add a test vector
|
||||
const id = await db.add('This is a test vector', { test: true });
|
||||
console.log(`Added test vector with ID: ${id}`);
|
||||
|
||||
// Get the vector back
|
||||
const vector = await db.get(id);
|
||||
console.log('Retrieved vector:', vector.metadata);
|
||||
|
||||
// Get storage status
|
||||
const status = await db.status();
|
||||
console.log('Storage status:', status);
|
||||
|
||||
// Clean up
|
||||
await db.clear();
|
||||
console.log('Database cleared');
|
||||
|
||||
console.log('Default configuration test completed successfully!');
|
||||
}
|
||||
|
||||
async function testStorageConfiguration() {
|
||||
console.log('\nTesting storage configuration...');
|
||||
|
||||
// Create a database with storage configuration
|
||||
const db = new BrainyData({
|
||||
storage: {
|
||||
// Force in-memory storage for testing
|
||||
forceMemoryStorage: true
|
||||
}
|
||||
});
|
||||
await db.init();
|
||||
|
||||
// Add a test vector
|
||||
const id = await db.add('This is a test vector with storage config', { test: true });
|
||||
console.log(`Added test vector with ID: ${id}`);
|
||||
|
||||
// Get the vector back
|
||||
const vector = await db.get(id);
|
||||
console.log('Retrieved vector:', vector.metadata);
|
||||
|
||||
// Get storage status
|
||||
const status = await db.status();
|
||||
console.log('Storage status:', status);
|
||||
|
||||
// Clean up
|
||||
await db.clear();
|
||||
console.log('Database cleared');
|
||||
|
||||
console.log('Storage configuration test completed successfully!');
|
||||
}
|
||||
|
||||
async function runTests() {
|
||||
try {
|
||||
await testDefaultConfiguration();
|
||||
await testStorageConfiguration();
|
||||
console.log('\nAll tests completed successfully!');
|
||||
} catch (error) {
|
||||
console.error('Error running tests:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Run the tests
|
||||
runTests();
|
||||
|
|
@ -1,145 +0,0 @@
|
|||
/**
|
||||
* Data Inspection Example
|
||||
*
|
||||
* This example demonstrates how to view and inspect the data stored in Brainy
|
||||
* to verify it's working correctly.
|
||||
*/
|
||||
|
||||
import { BrainyData, createSimpleEmbeddingFunction } from '../dist/index.js';
|
||||
|
||||
async function runExample() {
|
||||
try {
|
||||
console.log('Brainy Data Inspection Example');
|
||||
console.log('==============================\n');
|
||||
|
||||
// Create a new Brainy database with a simple embedding function
|
||||
console.log('Creating and initializing Brainy database...');
|
||||
const simpleEmbedding = createSimpleEmbeddingFunction();
|
||||
const db = new BrainyData({
|
||||
embeddingFunction: simpleEmbedding
|
||||
});
|
||||
await db.init();
|
||||
console.log('Database initialized successfully!\n');
|
||||
|
||||
// Add sample data - using text that will be automatically embedded to vectors
|
||||
console.log('Adding sample data to the database...');
|
||||
const catId = await db.add("Cat is a small domesticated carnivorous mammal", { type: 'mammal', name: 'cat' });
|
||||
const dogId = await db.add("Dog is a domesticated carnivore of the family Canidae", { type: 'mammal', name: 'dog' });
|
||||
const fishId = await db.add("Fish are aquatic animals that live in water", { type: 'fish', name: 'fish' });
|
||||
|
||||
// Add more text data
|
||||
const lionDescId = await db.add("Lions are large cats with a golden mane", { type: 'mammal', name: 'lion' });
|
||||
const tigerDescId = await db.add("Tigers are large cats with striped fur", { type: 'mammal', name: 'tiger' });
|
||||
|
||||
// Add an edge between cat and lion (they're related)
|
||||
const edgeId = await db.addEdge(catId, lionDescId, undefined, {
|
||||
type: 'related',
|
||||
weight: 0.8,
|
||||
metadata: { relationship: 'same family' }
|
||||
});
|
||||
|
||||
console.log('Sample data added successfully!\n');
|
||||
|
||||
// Method 1: Check database status
|
||||
console.log('Method 1: Check Database Status');
|
||||
console.log('-------------------------------');
|
||||
const status = await db.status();
|
||||
console.log('Storage Type:', status.type);
|
||||
console.log('Used Space:', status.used, 'bytes');
|
||||
console.log('Storage Quota:', status.quota, 'bytes');
|
||||
console.log('Number of Items:', db.size());
|
||||
console.log('Additional Details:', JSON.stringify(status.details, null, 2));
|
||||
console.log();
|
||||
|
||||
// Method 2: Retrieve specific items by ID
|
||||
console.log('Method 2: Retrieve Specific Items by ID');
|
||||
console.log('--------------------------------------');
|
||||
const cat = await db.get(catId);
|
||||
console.log('Cat Item:');
|
||||
console.log('- ID:', cat.id);
|
||||
console.log('- Vector:', cat.vector);
|
||||
console.log('- Metadata:', JSON.stringify(cat.metadata, null, 2));
|
||||
console.log();
|
||||
|
||||
// Method 3: Search for similar items
|
||||
console.log('Method 3: Search for Similar Items');
|
||||
console.log('----------------------------------');
|
||||
const searchResults = await db.search("cat", 3);
|
||||
console.log('Search Results:');
|
||||
searchResults.forEach((result, index) => {
|
||||
console.log(`Result ${index + 1}:`);
|
||||
console.log('- ID:', result.id);
|
||||
console.log('- Score:', result.score);
|
||||
console.log('- Metadata:', JSON.stringify(result.metadata, null, 2));
|
||||
});
|
||||
console.log();
|
||||
|
||||
// Method 4: Text search
|
||||
console.log('Method 4: Text Search');
|
||||
console.log('--------------------');
|
||||
const textResults = await db.searchText('cat', 2);
|
||||
console.log('Text Search Results:');
|
||||
textResults.forEach((result, index) => {
|
||||
console.log(`Result ${index + 1}:`);
|
||||
console.log('- ID:', result.id);
|
||||
console.log('- Score:', result.score);
|
||||
console.log('- Metadata:', JSON.stringify(result.metadata, null, 2));
|
||||
});
|
||||
console.log();
|
||||
|
||||
// Method 5: Get all edges
|
||||
console.log('Method 5: Get All Edges');
|
||||
console.log('----------------------');
|
||||
const allEdges = await db.getAllEdges();
|
||||
console.log('All Edges:');
|
||||
allEdges.forEach((edge, index) => {
|
||||
console.log(`Edge ${index + 1}:`);
|
||||
console.log('- ID:', edge.id);
|
||||
console.log('- Source ID:', edge.sourceId);
|
||||
console.log('- Target ID:', edge.targetId);
|
||||
console.log('- Type:', edge.type);
|
||||
console.log('- Weight:', edge.weight);
|
||||
console.log('- Metadata:', JSON.stringify(edge.metadata, null, 2));
|
||||
});
|
||||
console.log();
|
||||
|
||||
// Method 6: Get edges by source
|
||||
console.log('Method 6: Get Edges by Source');
|
||||
console.log('----------------------------');
|
||||
const catEdges = await db.getEdgesBySource(catId);
|
||||
console.log(`Edges from Cat (${catId}):`);
|
||||
catEdges.forEach((edge, index) => {
|
||||
console.log(`Edge ${index + 1}:`);
|
||||
console.log('- ID:', edge.id);
|
||||
console.log('- Target ID:', edge.targetId);
|
||||
console.log('- Type:', edge.type);
|
||||
});
|
||||
console.log();
|
||||
|
||||
// Method 7: Advanced search with noun types and verbs
|
||||
console.log('Method 7: Advanced Search with Noun Types and Verbs');
|
||||
console.log('--------------------------------------------------');
|
||||
const advancedResults = await db.search("cat", 3, {
|
||||
nounTypes: ['mammal'],
|
||||
includeVerbs: true
|
||||
});
|
||||
console.log('Advanced Search Results:');
|
||||
advancedResults.forEach((result, index) => {
|
||||
console.log(`Result ${index + 1}:`);
|
||||
console.log('- ID:', result.id);
|
||||
console.log('- Score:', result.score);
|
||||
console.log('- Metadata:', JSON.stringify(result.metadata, null, 2));
|
||||
if (result.metadata && result.metadata.associatedVerbs) {
|
||||
console.log('- Associated Verbs:', result.metadata.associatedVerbs.length);
|
||||
}
|
||||
});
|
||||
console.log();
|
||||
|
||||
console.log('Example completed successfully!');
|
||||
} catch (error) {
|
||||
console.error('Error running example:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Run the example
|
||||
runExample();
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
// Example of importing only the graphTypes module
|
||||
import { GraphNoun, GraphVerb, NounType, VerbType } from '@soulcraft/brainy/types/graphTypes';
|
||||
|
||||
// This demonstrates that we can import just the graphTypes
|
||||
// without importing the rest of the library
|
||||
console.log('Successfully imported graphTypes');
|
||||
|
||||
// Example usage of the imported types
|
||||
const exampleNoun = {
|
||||
id: '123',
|
||||
createdBy: {
|
||||
augmentation: 'test',
|
||||
version: '1.0',
|
||||
model: 'test-model',
|
||||
modelVersion: '1.0'
|
||||
},
|
||||
noun: NounType.Person,
|
||||
createdAt: { seconds: Date.now() / 1000, nanoseconds: 0 },
|
||||
updatedAt: { seconds: Date.now() / 1000, nanoseconds: 0 }
|
||||
};
|
||||
|
||||
console.log('Example noun type:', exampleNoun.noun);
|
||||
console.log('Available noun types:', Object.values(NounType));
|
||||
console.log('Available verb types:', Object.values(VerbType));
|
||||
|
|
@ -1,205 +0,0 @@
|
|||
/**
|
||||
* LLM Augmentation Example
|
||||
*
|
||||
* This example demonstrates how to use the LLM augmentation to create, train, test,
|
||||
* export, and deploy an LLM model from the data in Brainy (nouns and verbs).
|
||||
*/
|
||||
|
||||
import { BrainyData, augmentationPipeline } from '@soulcraft/brainy'
|
||||
import { createLLMAugmentations } from '@soulcraft/brainy/src/augmentations/llmAugmentations.js'
|
||||
|
||||
// Main function to run the example
|
||||
async function runLLMExample() {
|
||||
console.log('Starting LLM Augmentation Example')
|
||||
|
||||
try {
|
||||
// Initialize Brainy
|
||||
const db = new BrainyData()
|
||||
await db.init()
|
||||
|
||||
// Add some sample data if the database is empty
|
||||
await populateSampleData(db)
|
||||
|
||||
// Create LLM augmentations
|
||||
const { cognition, activation } = await createLLMAugmentations({
|
||||
cognitionName: 'my-llm-cognition',
|
||||
activationName: 'my-llm-activation',
|
||||
brainyDb: db
|
||||
})
|
||||
|
||||
// Register augmentations with the pipeline
|
||||
augmentationPipeline.register(cognition)
|
||||
augmentationPipeline.register(activation)
|
||||
|
||||
console.log('LLM augmentations registered successfully')
|
||||
|
||||
// Create a simple LLM model
|
||||
const createModelResult = await cognition.createModel({
|
||||
name: 'my-first-llm',
|
||||
description: 'A simple LLM model trained on Brainy data',
|
||||
modelType: 'simple',
|
||||
vocabSize: 5000,
|
||||
embeddingDim: 64,
|
||||
hiddenDim: 128,
|
||||
numLayers: 1,
|
||||
maxSequenceLength: 50,
|
||||
epochs: 5
|
||||
})
|
||||
|
||||
if (!createModelResult.success) {
|
||||
throw new Error(`Failed to create model: ${createModelResult.error}`)
|
||||
}
|
||||
|
||||
const { modelId } = createModelResult.data
|
||||
console.log(`Created model with ID: ${modelId}`)
|
||||
|
||||
// Train the model
|
||||
console.log('Training model...')
|
||||
const trainResult = await cognition.trainModel(modelId, {
|
||||
maxSamples: 100,
|
||||
validationSplit: 0.2,
|
||||
earlyStoppingPatience: 2
|
||||
})
|
||||
|
||||
if (!trainResult.success) {
|
||||
throw new Error(`Failed to train model: ${trainResult.error}`)
|
||||
}
|
||||
|
||||
console.log('Model trained successfully')
|
||||
console.log('Training metrics:', trainResult.data.metadata.performance)
|
||||
|
||||
// Test the model
|
||||
console.log('Testing model...')
|
||||
const testResult = await cognition.testModel(modelId, {
|
||||
testSize: 20,
|
||||
generateSamples: true,
|
||||
sampleCount: 3
|
||||
})
|
||||
|
||||
if (!testResult.success) {
|
||||
throw new Error(`Failed to test model: ${testResult.error}`)
|
||||
}
|
||||
|
||||
console.log('Model tested successfully')
|
||||
console.log('Test metrics:', testResult.data.metrics)
|
||||
|
||||
if (testResult.data.samples) {
|
||||
console.log('Sample predictions:')
|
||||
for (const sample of testResult.data.samples) {
|
||||
console.log(`Input: "${sample.input}"`)
|
||||
console.log(`Expected: "${sample.expected}"`)
|
||||
console.log(`Generated: "${sample.generated}"`)
|
||||
console.log('---')
|
||||
}
|
||||
}
|
||||
|
||||
// Generate text with the model
|
||||
console.log('Generating text...')
|
||||
const generateResult = await cognition.generateText(modelId, 'What is a', {
|
||||
temperature: 0.7,
|
||||
topK: 5
|
||||
})
|
||||
|
||||
if (generateResult.success) {
|
||||
console.log(`Generated text: "${generateResult.data}"`)
|
||||
} else {
|
||||
console.error(`Failed to generate text: ${generateResult.error}`)
|
||||
}
|
||||
|
||||
// Export the model
|
||||
console.log('Exporting model...')
|
||||
const exportResult = await cognition.exportModel(modelId, {
|
||||
format: 'json',
|
||||
includeMetadata: true,
|
||||
includeVocab: true
|
||||
})
|
||||
|
||||
if (!exportResult.success) {
|
||||
throw new Error(`Failed to export model: ${exportResult.error}`)
|
||||
}
|
||||
|
||||
console.log(`Model exported in ${exportResult.data.format} format`)
|
||||
|
||||
// Deploy the model (browser example)
|
||||
console.log('Deploying model to browser...')
|
||||
const deployResult = await cognition.deployModel(modelId, {
|
||||
target: 'browser'
|
||||
})
|
||||
|
||||
if (!deployResult.success) {
|
||||
throw new Error(`Failed to deploy model: ${deployResult.error}`)
|
||||
}
|
||||
|
||||
console.log(`Model deployed to ${deployResult.data.deploymentTarget}`)
|
||||
console.log(`Deployment status: ${deployResult.data.status}`)
|
||||
|
||||
// Using the activation augmentation through the pipeline
|
||||
console.log('Using activation augmentation through pipeline...')
|
||||
|
||||
// Create a new model through the pipeline
|
||||
const pipelineCreateResult = await augmentationPipeline.executeCognitionPipeline(
|
||||
'createModel',
|
||||
[{
|
||||
name: 'pipeline-llm',
|
||||
modelType: 'transformer',
|
||||
numHeads: 2,
|
||||
numLayers: 1
|
||||
}]
|
||||
)
|
||||
|
||||
if (pipelineCreateResult[0] && (await pipelineCreateResult[0]).success) {
|
||||
const pipelineModelId = (await pipelineCreateResult[0]).data.modelId
|
||||
console.log(`Created model through pipeline with ID: ${pipelineModelId}`)
|
||||
|
||||
// Train the model through the pipeline
|
||||
const pipelineTrainResult = await augmentationPipeline.executeCognitionPipeline(
|
||||
'trainModel',
|
||||
[pipelineModelId, { maxSamples: 50 }]
|
||||
)
|
||||
|
||||
if (pipelineTrainResult[0] && (await pipelineTrainResult[0]).success) {
|
||||
console.log('Model trained through pipeline successfully')
|
||||
}
|
||||
}
|
||||
|
||||
console.log('LLM Augmentation Example completed successfully')
|
||||
} catch (error) {
|
||||
console.error('Error in LLM Augmentation Example:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to populate sample data
|
||||
async function populateSampleData(db) {
|
||||
const status = await db.status()
|
||||
|
||||
// Only add sample data if the database is empty
|
||||
if (status.nounCount === 0) {
|
||||
console.log('Adding sample data to Brainy...')
|
||||
|
||||
// Add some nouns (entities)
|
||||
const cat = await db.add('Cats are independent pets', { noun: 'thing', category: 'animal' })
|
||||
const dog = await db.add('Dogs are loyal companions', { noun: 'thing', category: 'animal' })
|
||||
const house = await db.add('Houses provide shelter for people', { noun: 'place', category: 'building' })
|
||||
const john = await db.add('John is a software developer', { noun: 'person', category: 'professional' })
|
||||
const mary = await db.add('Mary is a data scientist', { noun: 'person', category: 'professional' })
|
||||
const coding = await db.add('Coding is the process of creating software', { noun: 'concept', category: 'technology' })
|
||||
const meeting = await db.add('Team meetings are held every Monday', { noun: 'event', category: 'work' })
|
||||
|
||||
// Add some verbs (relationships)
|
||||
await db.addVerb(john, house, { verb: 'owns', description: 'John owns the house' })
|
||||
await db.addVerb(john, dog, { verb: 'owns', description: 'John owns a dog' })
|
||||
await db.addVerb(mary, cat, { verb: 'owns', description: 'Mary owns a cat' })
|
||||
await db.addVerb(john, coding, { verb: 'created', description: 'John created code' })
|
||||
await db.addVerb(mary, coding, { verb: 'created', description: 'Mary created code' })
|
||||
await db.addVerb(john, meeting, { verb: 'created', description: 'John organized the meeting' })
|
||||
await db.addVerb(mary, meeting, { verb: 'memberOf', description: 'Mary is part of the meeting' })
|
||||
await db.addVerb(john, mary, { verb: 'worksWith', description: 'John works with Mary' })
|
||||
|
||||
console.log('Sample data added successfully')
|
||||
} else {
|
||||
console.log('Database already contains data, skipping sample data creation')
|
||||
}
|
||||
}
|
||||
|
||||
// Run the example
|
||||
runLLMExample().catch(console.error)
|
||||
|
|
@ -1,268 +0,0 @@
|
|||
/**
|
||||
* Example: Using Memory Augmentations for Data Storage
|
||||
*
|
||||
* This example demonstrates how to use the different memory augmentation implementations
|
||||
* for storing and retrieving data in Brainy.
|
||||
*
|
||||
* The example shows:
|
||||
* 1. Using the default memory augmentation (auto-selected based on environment)
|
||||
* 2. Using specific storage types (Memory, FileSystem, OPFS)
|
||||
*/
|
||||
|
||||
import {
|
||||
registerAugmentation,
|
||||
initializeAugmentationPipeline,
|
||||
createMemoryAugmentation
|
||||
} from '../dist/index.js'
|
||||
|
||||
// Example 1: Using the default memory augmentation
|
||||
async function useDefaultMemoryAugmentation() {
|
||||
console.log('Setting up default memory augmentation...')
|
||||
|
||||
// Create the memory augmentation with automatic storage selection
|
||||
const memoryAug = await createMemoryAugmentation('brainy-default-memory')
|
||||
|
||||
// Register the augmentation
|
||||
registerAugmentation(memoryAug)
|
||||
|
||||
// Initialize the augmentation pipeline
|
||||
initializeAugmentationPipeline()
|
||||
|
||||
// Initialize the augmentation
|
||||
await memoryAug.initialize()
|
||||
|
||||
console.log('Default memory augmentation initialized successfully')
|
||||
console.log('Storage type:', await getStorageType(memoryAug))
|
||||
|
||||
// Store some data
|
||||
await storeAndRetrieveData(memoryAug)
|
||||
|
||||
return memoryAug
|
||||
}
|
||||
|
||||
// Example 2: Using in-memory storage explicitly
|
||||
async function useInMemoryStorage() {
|
||||
console.log('Setting up in-memory storage...')
|
||||
|
||||
// Create the memory augmentation with in-memory storage
|
||||
const memoryAug = await createMemoryAugmentation('brainy-memory-storage', {
|
||||
storageType: 'memory'
|
||||
})
|
||||
|
||||
// Register the augmentation
|
||||
registerAugmentation(memoryAug)
|
||||
|
||||
// Initialize the augmentation
|
||||
await memoryAug.initialize()
|
||||
|
||||
console.log('In-memory storage initialized successfully')
|
||||
|
||||
// Store some data
|
||||
await storeAndRetrieveData(memoryAug)
|
||||
|
||||
return memoryAug
|
||||
}
|
||||
|
||||
// Example 3: Using file system storage (Node.js environments)
|
||||
async function useFileSystemStorage() {
|
||||
console.log('Setting up file system storage...')
|
||||
|
||||
try {
|
||||
// Create the memory augmentation with file system storage
|
||||
const memoryAug = await createMemoryAugmentation('brainy-filesystem-storage', {
|
||||
storageType: 'filesystem',
|
||||
rootDirectory: './data' // Store data in a 'data' directory
|
||||
})
|
||||
|
||||
// Register the augmentation
|
||||
registerAugmentation(memoryAug)
|
||||
|
||||
// Initialize the augmentation
|
||||
await memoryAug.initialize()
|
||||
|
||||
console.log('File system storage initialized successfully')
|
||||
|
||||
// Store some data
|
||||
await storeAndRetrieveData(memoryAug)
|
||||
|
||||
return memoryAug
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize file system storage:', error)
|
||||
console.log('This might be because you are not in a Node.js environment')
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// Example 4: Using OPFS storage (browser environments)
|
||||
async function useOPFSStorage() {
|
||||
console.log('Setting up OPFS storage...')
|
||||
|
||||
try {
|
||||
// Create the memory augmentation with OPFS storage
|
||||
const memoryAug = await createMemoryAugmentation('brainy-opfs-storage', {
|
||||
storageType: 'opfs',
|
||||
requestPersistentStorage: true
|
||||
})
|
||||
|
||||
// Register the augmentation
|
||||
registerAugmentation(memoryAug)
|
||||
|
||||
// Initialize the augmentation
|
||||
await memoryAug.initialize()
|
||||
|
||||
console.log('OPFS storage initialized successfully')
|
||||
|
||||
// Store some data
|
||||
await storeAndRetrieveData(memoryAug)
|
||||
|
||||
return memoryAug
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize OPFS storage:', error)
|
||||
console.log('This might be because you are not in a browser environment or OPFS is not supported')
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to store and retrieve data
|
||||
async function storeAndRetrieveData(memoryAug) {
|
||||
console.log('Storing and retrieving data...')
|
||||
|
||||
// Store data
|
||||
const userData = {
|
||||
name: 'John Doe',
|
||||
email: 'john@example.com',
|
||||
preferences: {
|
||||
theme: 'dark',
|
||||
fontSize: 14,
|
||||
notifications: true
|
||||
},
|
||||
// Add a vector for search testing
|
||||
vector: [0.1, 0.2, 0.3, 0.4, 0.5]
|
||||
}
|
||||
|
||||
const storeResponse = await memoryAug.storeData('user-1', userData)
|
||||
console.log('Store response:', storeResponse)
|
||||
|
||||
// Store more data with vectors for search testing
|
||||
await memoryAug.storeData('user-2', {
|
||||
name: 'Jane Smith',
|
||||
email: 'jane@example.com',
|
||||
preferences: {
|
||||
theme: 'light',
|
||||
fontSize: 16,
|
||||
notifications: false
|
||||
},
|
||||
vector: [0.2, 0.3, 0.4, 0.5, 0.6]
|
||||
})
|
||||
|
||||
await memoryAug.storeData('user-3', {
|
||||
name: 'Bob Johnson',
|
||||
email: 'bob@example.com',
|
||||
preferences: {
|
||||
theme: 'dark',
|
||||
fontSize: 12,
|
||||
notifications: true
|
||||
},
|
||||
vector: [0.3, 0.4, 0.5, 0.6, 0.7]
|
||||
})
|
||||
|
||||
// Retrieve data
|
||||
const retrieveResponse = await memoryAug.retrieveData('user-1')
|
||||
console.log('Retrieve response:', retrieveResponse)
|
||||
|
||||
// Update data
|
||||
const updateResponse = await memoryAug.updateData('user-1', {
|
||||
...userData,
|
||||
preferences: {
|
||||
...userData.preferences,
|
||||
theme: 'light'
|
||||
}
|
||||
})
|
||||
console.log('Update response:', updateResponse)
|
||||
|
||||
// Retrieve updated data
|
||||
const retrieveUpdatedResponse = await memoryAug.retrieveData('user-1')
|
||||
console.log('Retrieved updated data:', retrieveUpdatedResponse)
|
||||
|
||||
// Test search functionality
|
||||
await searchData(memoryAug)
|
||||
|
||||
// Delete data
|
||||
const deleteResponse = await memoryAug.deleteData('user-1')
|
||||
console.log('Delete response:', deleteResponse)
|
||||
await memoryAug.deleteData('user-2')
|
||||
await memoryAug.deleteData('user-3')
|
||||
|
||||
// Verify deletion
|
||||
const retrieveAfterDeleteResponse = await memoryAug.retrieveData('user-1')
|
||||
console.log('Retrieve after delete response:', retrieveAfterDeleteResponse)
|
||||
}
|
||||
|
||||
// Helper function to test search functionality
|
||||
async function searchData(memoryAug) {
|
||||
console.log('\nTesting search functionality...')
|
||||
|
||||
// Create a query vector
|
||||
const queryVector = [0.2, 0.3, 0.4, 0.5, 0.6]
|
||||
|
||||
try {
|
||||
// Search for similar vectors
|
||||
console.log('Searching for similar vectors...')
|
||||
const searchResponse = await memoryAug.search(queryVector, 2)
|
||||
|
||||
if (searchResponse.success) {
|
||||
console.log('Search results:')
|
||||
for (const result of searchResponse.data) {
|
||||
console.log(`- ID: ${result.id}, Score: ${result.score.toFixed(4)}`)
|
||||
if (result.data) {
|
||||
console.log(` Name: ${result.data.name}, Email: ${result.data.email}`)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.error('Search failed:', searchResponse.error)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error during search:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to get storage type
|
||||
async function getStorageType(memoryAug) {
|
||||
// This is a bit of a hack to determine the storage type
|
||||
// In a real application, you might want to add a method to the augmentation
|
||||
// to return the storage type directly
|
||||
const constructorName = memoryAug.constructor.name
|
||||
return constructorName
|
||||
}
|
||||
|
||||
// Run the examples
|
||||
async function runExamples() {
|
||||
console.log('Running memory augmentation examples...')
|
||||
|
||||
// Example 1: Default memory augmentation
|
||||
const defaultMemory = await useDefaultMemoryAugmentation()
|
||||
await defaultMemory.shutDown()
|
||||
|
||||
// Example 2: In-memory storage
|
||||
const inMemoryStorage = await useInMemoryStorage()
|
||||
await inMemoryStorage.shutDown()
|
||||
|
||||
// Example 3: File system storage
|
||||
const fileSystemStorage = await useFileSystemStorage()
|
||||
if (fileSystemStorage) {
|
||||
await fileSystemStorage.shutDown()
|
||||
}
|
||||
|
||||
// Example 4: OPFS storage
|
||||
const opfsStorage = await useOPFSStorage()
|
||||
if (opfsStorage) {
|
||||
await opfsStorage.shutDown()
|
||||
}
|
||||
|
||||
console.log('All examples completed')
|
||||
}
|
||||
|
||||
// Run the examples
|
||||
runExamples().catch(error => {
|
||||
console.error('Error running examples:', error)
|
||||
})
|
||||
|
|
@ -1,72 +0,0 @@
|
|||
/**
|
||||
* Read-Only Mode Test
|
||||
*
|
||||
* This example demonstrates how to use the read-only mode feature of BrainyData.
|
||||
*/
|
||||
|
||||
import { BrainyData } from '../dist/index.js';
|
||||
|
||||
async function testReadOnlyMode() {
|
||||
console.log('Testing read-only mode...');
|
||||
|
||||
// Test 1: Create a database in read-only mode
|
||||
console.log('\nTest 1: Create a database in read-only mode');
|
||||
const readOnlyDb = new BrainyData({ readOnly: true });
|
||||
await readOnlyDb.init();
|
||||
|
||||
console.log('Database initialized in read-only mode');
|
||||
console.log('Is read-only:', readOnlyDb.isReadOnly());
|
||||
|
||||
// Try to add data (should throw an error)
|
||||
try {
|
||||
console.log('Attempting to add data to read-only database...');
|
||||
await readOnlyDb.add([0.1, 0.2, 0.3], { name: 'test' });
|
||||
console.log('ERROR: Add operation succeeded but should have failed!');
|
||||
} catch (error) {
|
||||
console.log('Expected error caught:', error.message);
|
||||
}
|
||||
|
||||
// Test 2: Toggle read-only mode at runtime
|
||||
console.log('\nTest 2: Toggle read-only mode at runtime');
|
||||
const db = new BrainyData();
|
||||
await db.init();
|
||||
|
||||
console.log('Database initialized in writable mode');
|
||||
console.log('Is read-only:', db.isReadOnly());
|
||||
|
||||
// Add data while writable
|
||||
console.log('Adding data while writable...');
|
||||
const itemId = await db.add([0.1, 0.2, 0.3], { name: 'test' });
|
||||
console.log('Added item with ID:', itemId);
|
||||
|
||||
// Set to read-only mode
|
||||
console.log('Setting database to read-only mode');
|
||||
db.setReadOnly(true);
|
||||
console.log('Is read-only:', db.isReadOnly());
|
||||
|
||||
// Try to delete data (should throw an error)
|
||||
try {
|
||||
console.log('Attempting to delete data from read-only database...');
|
||||
await db.delete(itemId);
|
||||
console.log('ERROR: Delete operation succeeded but should have failed!');
|
||||
} catch (error) {
|
||||
console.log('Expected error caught:', error.message);
|
||||
}
|
||||
|
||||
// Set back to writable mode
|
||||
console.log('Setting database back to writable mode');
|
||||
db.setReadOnly(false);
|
||||
console.log('Is read-only:', db.isReadOnly());
|
||||
|
||||
// Delete data (should succeed)
|
||||
console.log('Deleting data while writable...');
|
||||
const deleteResult = await db.delete(itemId);
|
||||
console.log('Delete result:', deleteResult);
|
||||
|
||||
console.log('\nAll tests completed successfully!');
|
||||
}
|
||||
|
||||
// Run the tests
|
||||
testReadOnlyMode().catch(error => {
|
||||
console.error('Test failed:', error);
|
||||
});
|
||||
|
|
@ -1,58 +0,0 @@
|
|||
/**
|
||||
* Example rollup configuration for using the Brainy augmentation registry
|
||||
*
|
||||
* This example shows how to configure rollup to automatically discover and register
|
||||
* augmentations at build time.
|
||||
*/
|
||||
|
||||
import resolve from '@rollup/plugin-node-resolve';
|
||||
import commonjs from '@rollup/plugin-commonjs';
|
||||
import typescript from '@rollup/plugin-typescript';
|
||||
import { createAugmentationRegistryRollupPlugin } from '../dist/index.js';
|
||||
|
||||
export default {
|
||||
// Entry point for the application
|
||||
input: 'src/index.js',
|
||||
|
||||
// Output configuration
|
||||
output: {
|
||||
file: 'dist/bundle.js',
|
||||
format: 'esm',
|
||||
sourcemap: true
|
||||
},
|
||||
|
||||
// Plugins
|
||||
plugins: [
|
||||
// Resolve node modules
|
||||
resolve(),
|
||||
|
||||
// Convert CommonJS modules to ES6
|
||||
commonjs(),
|
||||
|
||||
// Process TypeScript files
|
||||
typescript(),
|
||||
|
||||
// Augmentation Registry Plugin
|
||||
// This plugin will automatically discover and register augmentations
|
||||
// from files that match the specified pattern
|
||||
createAugmentationRegistryRollupPlugin({
|
||||
// Pattern to match files containing augmentations
|
||||
// This will match any file ending with 'augmentation.js' or 'augmentation.ts'
|
||||
pattern: /augmentation\.(js|ts)$/,
|
||||
|
||||
// Options for the loader
|
||||
options: {
|
||||
// Automatically initialize augmentations after loading
|
||||
autoInitialize: true,
|
||||
|
||||
// Log debug information during loading
|
||||
debug: true
|
||||
}
|
||||
})
|
||||
],
|
||||
|
||||
// External dependencies that should not be bundled
|
||||
external: [
|
||||
'brainy'
|
||||
]
|
||||
};
|
||||
|
|
@ -1,235 +0,0 @@
|
|||
/**
|
||||
* Sequential Pipeline Example
|
||||
*
|
||||
* This example demonstrates how to use the sequential pipeline to process data
|
||||
* through a sequence of augmentations: ISense -> IMemory -> ICognition -> IConduit -> IActivation -> IPerception
|
||||
*/
|
||||
|
||||
import {
|
||||
sequentialPipeline,
|
||||
registerAugmentation,
|
||||
initializeAugmentationPipeline,
|
||||
createMemoryAugmentation
|
||||
} from '../dist/index.js';
|
||||
|
||||
// Create a simple ISense augmentation
|
||||
const senseAugmentation = {
|
||||
name: 'SimpleSense',
|
||||
description: 'A simple sense augmentation for testing',
|
||||
enabled: true,
|
||||
|
||||
async initialize() {},
|
||||
async shutDown() {},
|
||||
async getStatus() { return 'active'; },
|
||||
|
||||
processRawData(rawData, dataType) {
|
||||
console.log(`[SimpleSense] Processing ${dataType} data: ${rawData}`);
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
nouns: ['example', 'test', 'data'],
|
||||
verbs: ['process', 'analyze', 'test']
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
async listenToFeed(feedUrl, callback) {
|
||||
console.log(`[SimpleSense] Listening to feed: ${feedUrl}`);
|
||||
}
|
||||
};
|
||||
|
||||
// Create a simple ICognition augmentation
|
||||
const cognitionAugmentation = {
|
||||
name: 'SimpleCognition',
|
||||
description: 'A simple cognition augmentation for testing',
|
||||
enabled: true,
|
||||
|
||||
async initialize() {},
|
||||
async shutDown() {},
|
||||
async getStatus() { return 'active'; },
|
||||
|
||||
reason(query, context) {
|
||||
console.log(`[SimpleCognition] Reasoning about: ${query}`);
|
||||
console.log(`[SimpleCognition] Context:`, context);
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
inference: 'This is test data that needs to be processed',
|
||||
confidence: 0.85
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
infer(dataSubset) {
|
||||
return {
|
||||
success: true,
|
||||
data: { result: 'inferred data' }
|
||||
};
|
||||
},
|
||||
|
||||
executeLogic(ruleId, input) {
|
||||
return {
|
||||
success: true,
|
||||
data: true
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// Create a simple IConduit augmentation
|
||||
const conduitAugmentation = {
|
||||
name: 'SimpleConduit',
|
||||
description: 'A simple conduit augmentation for testing',
|
||||
enabled: true,
|
||||
|
||||
async initialize() {},
|
||||
async shutDown() {},
|
||||
async getStatus() { return 'active'; },
|
||||
|
||||
establishConnection(targetSystemId, config) {
|
||||
console.log(`[SimpleConduit] Establishing connection to: ${targetSystemId}`);
|
||||
return {
|
||||
success: true,
|
||||
data: { connectionId: 'test-connection' }
|
||||
};
|
||||
},
|
||||
|
||||
readData(query, options) {
|
||||
return {
|
||||
success: true,
|
||||
data: { result: 'read data' }
|
||||
};
|
||||
},
|
||||
|
||||
writeData(data, options) {
|
||||
console.log(`[SimpleConduit] Writing data:`, data);
|
||||
return {
|
||||
success: true,
|
||||
data: { written: true }
|
||||
};
|
||||
},
|
||||
|
||||
async monitorStream(streamId, callback) {
|
||||
console.log(`[SimpleConduit] Monitoring stream: ${streamId}`);
|
||||
}
|
||||
};
|
||||
|
||||
// Create a simple IActivation augmentation
|
||||
const activationAugmentation = {
|
||||
name: 'SimpleActivation',
|
||||
description: 'A simple activation augmentation for testing',
|
||||
enabled: true,
|
||||
|
||||
async initialize() {},
|
||||
async shutDown() {},
|
||||
async getStatus() { return 'active'; },
|
||||
|
||||
triggerAction(actionName, parameters) {
|
||||
console.log(`[SimpleActivation] Triggering action: ${actionName}`);
|
||||
console.log(`[SimpleActivation] Parameters:`, parameters);
|
||||
return {
|
||||
success: true,
|
||||
data: { triggered: true }
|
||||
};
|
||||
},
|
||||
|
||||
generateOutput(knowledgeId, format) {
|
||||
return {
|
||||
success: true,
|
||||
data: 'Generated output'
|
||||
};
|
||||
},
|
||||
|
||||
interactExternal(systemId, payload) {
|
||||
return {
|
||||
success: true,
|
||||
data: { result: 'external interaction' }
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// Create a simple IPerception augmentation
|
||||
const perceptionAugmentation = {
|
||||
name: 'SimplePerception',
|
||||
description: 'A simple perception augmentation for testing',
|
||||
enabled: true,
|
||||
|
||||
async initialize() {},
|
||||
async shutDown() {},
|
||||
async getStatus() { return 'active'; },
|
||||
|
||||
interpret(nouns, verbs, context) {
|
||||
console.log(`[SimplePerception] Interpreting nouns:`, nouns);
|
||||
console.log(`[SimplePerception] Interpreting verbs:`, verbs);
|
||||
console.log(`[SimplePerception] Context:`, context);
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
interpretation: 'This is a test data sample that needs processing and analysis',
|
||||
confidence: 0.9
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
organize(data, criteria) {
|
||||
return {
|
||||
success: true,
|
||||
data: { organized: true }
|
||||
};
|
||||
},
|
||||
|
||||
generateVisualization(data, visualizationType) {
|
||||
return {
|
||||
success: true,
|
||||
data: 'Visualization data'
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
async function runExample() {
|
||||
try {
|
||||
// Register augmentations
|
||||
registerAugmentation(senseAugmentation);
|
||||
registerAugmentation(cognitionAugmentation);
|
||||
registerAugmentation(conduitAugmentation);
|
||||
registerAugmentation(activationAugmentation);
|
||||
registerAugmentation(perceptionAugmentation);
|
||||
|
||||
// Create and register a memory augmentation
|
||||
const memoryAugmentation = await createMemoryAugmentation('SimpleMemory', { storageType: 'memory' });
|
||||
registerAugmentation(memoryAugmentation);
|
||||
|
||||
// Initialize the augmentation pipeline
|
||||
initializeAugmentationPipeline();
|
||||
|
||||
// Initialize the sequential pipeline
|
||||
await sequentialPipeline.initialize();
|
||||
|
||||
console.log('Processing data through the sequential pipeline...');
|
||||
|
||||
// Process data through the sequential pipeline
|
||||
const result = await sequentialPipeline.processData(
|
||||
'This is a test message',
|
||||
'text'
|
||||
);
|
||||
|
||||
console.log('\nPipeline execution result:');
|
||||
console.log('Success:', result.success);
|
||||
console.log('Data:', result.data);
|
||||
|
||||
if (result.error) {
|
||||
console.log('Error:', result.error);
|
||||
}
|
||||
|
||||
console.log('\nStage results:');
|
||||
for (const stage in result.stageResults) {
|
||||
console.log(`${stage}:`, result.stageResults[stage].success);
|
||||
}
|
||||
|
||||
console.log('\nExample completed successfully!');
|
||||
} catch (error) {
|
||||
console.error('Error running example:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Run the example
|
||||
runExample();
|
||||
|
|
@ -1,346 +0,0 @@
|
|||
/**
|
||||
* Server Search Augmentation Example
|
||||
*
|
||||
* This example demonstrates how to use the ServerSearchConduitAugmentation and
|
||||
* ServerSearchActivationAugmentation to search a server-hosted Brainy instance,
|
||||
* store results locally, and perform further searches against the local instance.
|
||||
*/
|
||||
|
||||
import {
|
||||
BrainyData,
|
||||
augmentationPipeline,
|
||||
AugmentationType,
|
||||
NounType
|
||||
} from '@soulcraft/brainy'
|
||||
|
||||
// Import the server search augmentations
|
||||
import {
|
||||
ServerSearchConduitAugmentation,
|
||||
ServerSearchActivationAugmentation,
|
||||
createServerSearchAugmentations
|
||||
} from '../src/augmentations/serverSearchAugmentations.js'
|
||||
|
||||
/**
|
||||
* Example 1: Using the factory function
|
||||
*
|
||||
* This is the simplest way to use the server search augmentations.
|
||||
* The factory function creates both augmentations, links them together,
|
||||
* and connects to the server.
|
||||
*/
|
||||
async function example1() {
|
||||
console.log('Example 1: Using the factory function')
|
||||
|
||||
try {
|
||||
// Create the augmentations and connect to the server
|
||||
const { conduit, activation, connection } = await createServerSearchAugmentations(
|
||||
'wss://your-brainy-server.com/ws',
|
||||
{ protocols: 'brainy-sync' }
|
||||
)
|
||||
|
||||
// Register the augmentations with the pipeline
|
||||
augmentationPipeline.register(conduit)
|
||||
augmentationPipeline.register(activation)
|
||||
|
||||
console.log('Connected to server with connection ID:', connection.connectionId)
|
||||
|
||||
// Search the server and store results locally
|
||||
console.log('Searching server for "machine learning"...')
|
||||
const serverSearchResult = await conduit.searchServer(
|
||||
connection.connectionId,
|
||||
'machine learning',
|
||||
5
|
||||
)
|
||||
|
||||
if (serverSearchResult.success) {
|
||||
console.log('Server search results:', serverSearchResult.data)
|
||||
} else {
|
||||
console.error('Server search failed:', serverSearchResult.error)
|
||||
}
|
||||
|
||||
// Now search locally - this should return the results we just stored
|
||||
console.log('Searching local database for "machine learning"...')
|
||||
const localSearchResult = await conduit.searchLocal('machine learning', 5)
|
||||
|
||||
if (localSearchResult.success) {
|
||||
console.log('Local search results:', localSearchResult.data)
|
||||
} else {
|
||||
console.error('Local search failed:', localSearchResult.error)
|
||||
}
|
||||
|
||||
// Perform a combined search
|
||||
console.log('Performing combined search for "neural networks"...')
|
||||
const combinedSearchResult = await conduit.searchCombined(
|
||||
connection.connectionId,
|
||||
'neural networks',
|
||||
5
|
||||
)
|
||||
|
||||
if (combinedSearchResult.success) {
|
||||
console.log('Combined search results:', combinedSearchResult.data)
|
||||
} else {
|
||||
console.error('Combined search failed:', combinedSearchResult.error)
|
||||
}
|
||||
|
||||
// Add data to both local and server
|
||||
console.log('Adding data to both local and server...')
|
||||
const addResult = await conduit.addToBoth(
|
||||
connection.connectionId,
|
||||
'Deep learning is a subset of machine learning',
|
||||
{
|
||||
noun: NounType.Concept,
|
||||
category: 'AI',
|
||||
tags: ['deep learning', 'neural networks']
|
||||
}
|
||||
)
|
||||
|
||||
if (addResult.success) {
|
||||
console.log('Added data with ID:', addResult.data)
|
||||
} else {
|
||||
console.error('Failed to add data:', addResult.error)
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Example 1 failed:', error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Example 2: Using the activation augmentation
|
||||
*
|
||||
* This example demonstrates how to use the activation augmentation
|
||||
* to trigger actions related to server search.
|
||||
*/
|
||||
async function example2() {
|
||||
console.log('\nExample 2: Using the activation augmentation')
|
||||
|
||||
try {
|
||||
// Create the augmentations and connect to the server
|
||||
const { conduit, activation, connection } = await createServerSearchAugmentations(
|
||||
'wss://your-brainy-server.com/ws',
|
||||
{ protocols: 'brainy-sync' }
|
||||
)
|
||||
|
||||
// Register the augmentations with the pipeline
|
||||
augmentationPipeline.register(conduit)
|
||||
augmentationPipeline.register(activation)
|
||||
|
||||
console.log('Connected to server with connection ID:', connection.connectionId)
|
||||
|
||||
// Use the activation augmentation to search the server
|
||||
console.log('Using activation to search server for "machine learning"...')
|
||||
const serverSearchAction = activation.triggerAction('searchServer', {
|
||||
connectionId: connection.connectionId,
|
||||
query: 'machine learning',
|
||||
limit: 5
|
||||
})
|
||||
|
||||
if (serverSearchAction.success) {
|
||||
// The data property contains a promise that will resolve to the search results
|
||||
const serverSearchResult = await serverSearchAction.data
|
||||
console.log('Server search results:', serverSearchResult)
|
||||
} else {
|
||||
console.error('Server search action failed:', serverSearchAction.error)
|
||||
}
|
||||
|
||||
// Use the activation augmentation to search locally
|
||||
console.log('Using activation to search local database for "machine learning"...')
|
||||
const localSearchAction = activation.triggerAction('searchLocal', {
|
||||
query: 'machine learning',
|
||||
limit: 5
|
||||
})
|
||||
|
||||
if (localSearchAction.success) {
|
||||
const localSearchResult = await localSearchAction.data
|
||||
console.log('Local search results:', localSearchResult)
|
||||
} else {
|
||||
console.error('Local search action failed:', localSearchAction.error)
|
||||
}
|
||||
|
||||
// Use the activation augmentation to perform a combined search
|
||||
console.log('Using activation to perform combined search for "neural networks"...')
|
||||
const combinedSearchAction = activation.triggerAction('searchCombined', {
|
||||
connectionId: connection.connectionId,
|
||||
query: 'neural networks',
|
||||
limit: 5
|
||||
})
|
||||
|
||||
if (combinedSearchAction.success) {
|
||||
const combinedSearchResult = await combinedSearchAction.data
|
||||
console.log('Combined search results:', combinedSearchResult)
|
||||
} else {
|
||||
console.error('Combined search action failed:', combinedSearchAction.error)
|
||||
}
|
||||
|
||||
// Use the activation augmentation to add data to both local and server
|
||||
console.log('Using activation to add data to both local and server...')
|
||||
const addAction = activation.triggerAction('addToBoth', {
|
||||
connectionId: connection.connectionId,
|
||||
data: 'Deep learning is a subset of machine learning',
|
||||
metadata: {
|
||||
noun: NounType.Concept,
|
||||
category: 'AI',
|
||||
tags: ['deep learning', 'neural networks']
|
||||
}
|
||||
})
|
||||
|
||||
if (addAction.success) {
|
||||
const addResult = await addAction.data
|
||||
console.log('Added data with ID:', addResult)
|
||||
} else {
|
||||
console.error('Add action failed:', addAction.error)
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Example 2 failed:', error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Example 3: Using the augmentation pipeline
|
||||
*
|
||||
* This example demonstrates how to use the augmentation pipeline
|
||||
* to execute the conduit and activation augmentations.
|
||||
*/
|
||||
async function example3() {
|
||||
console.log('\nExample 3: Using the augmentation pipeline')
|
||||
|
||||
try {
|
||||
// Create the augmentations and connect to the server
|
||||
const { conduit, activation, connection } = await createServerSearchAugmentations(
|
||||
'wss://your-brainy-server.com/ws',
|
||||
{ protocols: 'brainy-sync' }
|
||||
)
|
||||
|
||||
// Register the augmentations with the pipeline
|
||||
augmentationPipeline.register(conduit)
|
||||
augmentationPipeline.register(activation)
|
||||
|
||||
console.log('Connected to server with connection ID:', connection.connectionId)
|
||||
|
||||
// Use the augmentation pipeline to search the server
|
||||
console.log('Using pipeline to search server...')
|
||||
const conduitResults = await augmentationPipeline.executeConduitPipeline(
|
||||
'searchServer',
|
||||
[connection.connectionId, 'machine learning', 5]
|
||||
)
|
||||
|
||||
if (conduitResults.length > 0 && (await conduitResults[0]).success) {
|
||||
console.log('Server search results:', (await conduitResults[0]).data)
|
||||
} else {
|
||||
console.error('Server search failed')
|
||||
}
|
||||
|
||||
// Use the augmentation pipeline to trigger the search action
|
||||
console.log('Using pipeline to trigger search action...')
|
||||
const activationResults = await augmentationPipeline.executeActivationPipeline(
|
||||
'triggerAction',
|
||||
['searchLocal', { query: 'machine learning', limit: 5 }]
|
||||
)
|
||||
|
||||
if (activationResults.length > 0 && (await activationResults[0]).success) {
|
||||
const actionResult = (await activationResults[0]).data
|
||||
if (actionResult.success) {
|
||||
const searchResult = await actionResult.data
|
||||
console.log('Local search results:', searchResult)
|
||||
}
|
||||
} else {
|
||||
console.error('Search action failed')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Example 3 failed:', error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Example 4: Creating and using the augmentations manually
|
||||
*
|
||||
* This example demonstrates how to create and use the augmentations
|
||||
* without using the factory function.
|
||||
*/
|
||||
async function example4() {
|
||||
console.log('\nExample 4: Creating and using the augmentations manually')
|
||||
|
||||
try {
|
||||
// Create a local Brainy instance
|
||||
const localDb = new BrainyData()
|
||||
await localDb.init()
|
||||
|
||||
// Create the conduit augmentation
|
||||
const conduit = new ServerSearchConduitAugmentation('manual-server-search-conduit')
|
||||
conduit.setLocalDb(localDb)
|
||||
await conduit.initialize()
|
||||
|
||||
// Create the activation augmentation
|
||||
const activation = new ServerSearchActivationAugmentation('manual-server-search-activation')
|
||||
activation.setConduitAugmentation(conduit)
|
||||
await activation.initialize()
|
||||
|
||||
// Register the augmentations with the pipeline
|
||||
augmentationPipeline.register(conduit)
|
||||
augmentationPipeline.register(activation)
|
||||
|
||||
// Connect to the server
|
||||
console.log('Connecting to server...')
|
||||
const connectionResult = await conduit.establishConnection(
|
||||
'wss://your-brainy-server.com/ws',
|
||||
{ protocols: 'brainy-sync' }
|
||||
)
|
||||
|
||||
if (!connectionResult.success || !connectionResult.data) {
|
||||
throw new Error(`Failed to connect to server: ${connectionResult.error}`)
|
||||
}
|
||||
|
||||
const connection = connectionResult.data
|
||||
console.log('Connected to server with connection ID:', connection.connectionId)
|
||||
|
||||
// Store the connection in the activation augmentation
|
||||
activation.storeConnection(connection.connectionId, connection)
|
||||
|
||||
// Search the server
|
||||
console.log('Searching server for "machine learning"...')
|
||||
const serverSearchResult = await conduit.searchServer(
|
||||
connection.connectionId,
|
||||
'machine learning',
|
||||
5
|
||||
)
|
||||
|
||||
if (serverSearchResult.success) {
|
||||
console.log('Server search results:', serverSearchResult.data)
|
||||
} else {
|
||||
console.error('Server search failed:', serverSearchResult.error)
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Example 4 failed:', error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run all examples
|
||||
*/
|
||||
async function runExamples() {
|
||||
// Initialize the augmentation pipeline
|
||||
await augmentationPipeline.initialize()
|
||||
|
||||
// Run the examples
|
||||
await example1()
|
||||
await example2()
|
||||
await example3()
|
||||
await example4()
|
||||
|
||||
// Shut down the augmentation pipeline
|
||||
await augmentationPipeline.shutDown()
|
||||
}
|
||||
|
||||
// Run the examples
|
||||
// runExamples().catch(console.error)
|
||||
|
||||
// Export for use in other modules
|
||||
export {
|
||||
example1,
|
||||
example2,
|
||||
example3,
|
||||
example4,
|
||||
runExamples
|
||||
}
|
||||
|
|
@ -1,81 +0,0 @@
|
|||
/**
|
||||
* Example webpack configuration for using the Brainy augmentation registry
|
||||
*
|
||||
* This example shows how to configure webpack to automatically discover and register
|
||||
* augmentations at build time.
|
||||
*/
|
||||
|
||||
const path = require('path');
|
||||
const { createAugmentationRegistryPlugin } = require('../dist/index.js');
|
||||
|
||||
module.exports = {
|
||||
// Entry point for the application
|
||||
entry: './src/index.js',
|
||||
|
||||
// Output configuration
|
||||
output: {
|
||||
path: path.resolve(__dirname, 'dist'),
|
||||
filename: 'bundle.js',
|
||||
},
|
||||
|
||||
// Module rules for processing different file types
|
||||
module: {
|
||||
rules: [
|
||||
// Process JavaScript files with babel
|
||||
{
|
||||
test: /\.js$/,
|
||||
exclude: /node_modules/,
|
||||
use: {
|
||||
loader: 'babel-loader',
|
||||
options: {
|
||||
presets: ['@babel/preset-env']
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// Process TypeScript files
|
||||
{
|
||||
test: /\.ts$/,
|
||||
exclude: /node_modules/,
|
||||
use: {
|
||||
loader: 'ts-loader'
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
// Resolve file extensions
|
||||
resolve: {
|
||||
extensions: ['.js', '.ts']
|
||||
},
|
||||
|
||||
// Plugins
|
||||
plugins: [
|
||||
// Augmentation Registry Plugin
|
||||
// This plugin will automatically discover and register augmentations
|
||||
// from files that match the specified pattern
|
||||
createAugmentationRegistryPlugin({
|
||||
// Pattern to match files containing augmentations
|
||||
// This will match any file ending with 'augmentation.js' or 'augmentation.ts'
|
||||
pattern: /augmentation\.(js|ts)$/,
|
||||
|
||||
// Options for the loader
|
||||
options: {
|
||||
// Automatically initialize augmentations after loading
|
||||
autoInitialize: true,
|
||||
|
||||
// Log debug information during loading
|
||||
debug: true
|
||||
}
|
||||
})
|
||||
],
|
||||
|
||||
// Development server configuration
|
||||
devServer: {
|
||||
static: {
|
||||
directory: path.join(__dirname, 'public'),
|
||||
},
|
||||
compress: true,
|
||||
port: 9000,
|
||||
}
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue