Compare commits

..

No commits in common. "3164d5f0641f7317704c4b0d75e339d452ddf1c8" and "f5db419c91a5081c66559a7b7c3274e5af4bd7f1" have entirely different histories.

9 changed files with 208 additions and 533 deletions

3
.gitignore vendored
View File

@ -26,4 +26,5 @@ dist-ssr
.env*
.aider*
src/lib/taylordb.types.ts
src/lib/taylor.types.ts
src/lib/taylor.client.ts

View File

@ -1,6 +1,6 @@
{
"dependencies": {
"@opencode-ai/plugin": "1.0.191",
"@opencode-ai/plugin": "1.0.126",
"@types/micromatch": "^4.0.10",
"axios": "^1.13.2",
"micromatch": "^4.0.8",

View File

@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
import type { Plugin } from "@opencode-ai/plugin";
import { Axios } from "axios";
import { promises as fs } from "fs";
@ -31,71 +30,52 @@ const updateAppStatus = async (status: "Errored" | "Active" | "Pending") => {
);
};
const sessionRetries: Record<string, number> = {};
export const BuildPlugin: Plugin = async ({ client, $ }) => {
export const DevServerHMRPlugin: Plugin = async ({ client, $ }) => {
return {
event: async ({ event }) => {
const isMessagedDone =
event.type === "message.updated" &&
// @ts-ignore
event.properties.info["finish"] === "stop";
if (event.type !== "session.idle") return;
if (!isMessagedDone) return;
// @ts-ignore
const error = event.properties.info["error"];
const isAbortionError = error && error.name === "MessageAbortedError";
const session = await client.session.get({
path: { id: event.properties.sessionID },
});
const isAnyChange =
(await $`git status --porcelain`.quiet()).stdout.toString().trim() !==
"";
session.data?.summary?.files && session.data.summary.files > 0;
console.log({ isAnyChange });
if (!isAnyChange || isAbortionError) {
if (!isAnyChange) {
await updateAppStatus("Active");
return;
}
console.log("Building...");
const result = await $`pnpm build`.quiet().catch((error) => error);
if (result.exitCode !== 0) {
if (!sessionRetries[event.properties.info.sessionID]) {
sessionRetries[event.properties.info.sessionID] = 1;
if (!client.session["tries"]) {
client.session["tries"] = 0;
} else {
sessionRetries[event.properties.info.sessionID]++;
client.session["tries"]++;
}
if (sessionRetries[event.properties.info.sessionID] > 3) {
if (client.session["tries"] > 3) {
await updateAppStatus("Errored");
return;
}
console.log(
`Retrying... ${sessionRetries[event.properties.info.sessionID]}`
);
await client.session.promptAsync({
path: { id: event.properties.info.sessionID },
await client.session.prompt({
path: { id: event.properties.sessionID },
body: {
parts: [
{
type: "text",
text: `While building the project, the following error occurred:\n\n${result.stdout.toString()}\n\nPlease fix the error and try again.`,
text: `While building the project, the following error occurred:\n\n${result.stderr.toString()}\n\nPlease fix the error and try again.`,
},
],
},
});
}
sessionRetries[event.properties.info.sessionID] = 1;
try {
const packageJson = JSON.parse(
await fs.readFile("package.json", "utf-8")
@ -106,30 +86,23 @@ export const BuildPlugin: Plugin = async ({ client, $ }) => {
const newVersion = `${major}.${minor}.${patch + 1}`;
const messages = await client.session.messages({
path: { id: event.properties.info.sessionID },
path: { id: event.properties.sessionID },
});
if (!messages.data) {
return;
}
const currentMessage = messages.data
const title = messages.data
.reverse()
.find(
(message) =>
message.info.role === "user" &&
message.info.summary &&
message.info.summary.title
);
)?.info.summary?.["title"];
if (!currentMessage) {
return;
}
const commitMessage =
// @ts-ignore
currentMessage.info.summary?.["title"] ??
`feat: release version v${newVersion}`;
const commitMessage = title ?? `feat: release version v${newVersion}`;
packageJson.version = newVersion;
@ -138,9 +111,10 @@ export const BuildPlugin: Plugin = async ({ client, $ }) => {
JSON.stringify(packageJson, null, 2)
);
console.log("Pushing");
await $`git config user.name "Taylor AI"`.quiet();
await $`git config user.email "ai@taylordb.io"`.quiet();
await $`git add .`.quiet();
await $`GIT_AUTHOR_NAME="Taylor AI" GIT_AUTHOR_EMAIL="ai@taylordb.io" GIT_COMMITTER_NAME="Taylor AI" GIT_COMMITTER_EMAIL="ai@taylordb.io" git commit -m ${commitMessage}`.quiet();
await $`git commit -m ${commitMessage}`.quiet();
await $`git tag v${newVersion}`.quiet();
await $`git push origin main --tags`.quiet();
} catch (error) {

View File

@ -1,452 +1,222 @@
This package contains the official TypeScript query builder for TaylorDB. It provides a type-safe and intuitive API for building and executing queries against your TaylorDB database.
# TaylorDB Query Builder
## Available Query Builder Methods
The official TypeScript query builder for TaylorDB. It provides a type-safe, fluent, and intuitive API for building and executing queries against your TaylorDB database.
**IMPORTANT FOR AI AGENTS**: The following is a complete list of available methods. Do not assume methods exist that are not listed here.
## Features
### Query Types (Starting Methods)
- **Type-Safe Queries**: Leverage your database schema for full type safety and autocompletion, catching errors at compile-time.
- **Fluent API**: A clean, chainable interface for building complex queries with ease.
- **Full CRUD Support**: Complete implementation for `select`, `insert`, `update`, and `delete` operations.
- **Advanced Filtering**: Filter data with a rich set of operators, nested conditions, and cross-table filters on relations.
- **Complex Selections**: Fetch related data using `with`, select specific columns, or get all columns with `selectAll`.
- **Pagination and Sorting**: Easily paginate and sort your query results.
- **Aggregation Queries**: Perform powerful aggregations with grouping and a variety of aggregate functions.
- **Batch Operations**: Execute multiple queries in a single, efficient request.
- **Real-time Subscriptions**: Subscribe to queries and receive live updates when data changes.
- `selectFrom(tableName)` - Start a SELECT query
- `insertInto(tableName)` - Start an INSERT query
- `update(tableName)` - Start an UPDATE query
- `deleteFrom(tableName)` - Start a DELETE query
- `aggregateFrom(tableName)` - Start an aggregation query
- `batch(queries)` - Execute multiple queries in parallel
- `transaction(callback)` - Execute queries in a transaction
## Installation
### Query Chain Methods
**For SELECT queries (`selectFrom`):**
- `.select(fields)` - Specify fields to select (array of field names)
- `.selectAll()` - Select all fields
- `.where(field, operator, value)` - Add a WHERE condition
- `.orderBy(field, direction)` - Sort results ('asc' or 'desc')
- `.paginate(page, pageSize)` - Paginate results
- `.with(relations)` - Include related records
- `.count()` - **Count records matching the query** (returns `Promise<number>` directly)
- `.execute()` - Execute query and return array of results
- `.executeTakeFirst()` - Execute query and return first result or undefined
**For INSERT queries (`insertInto`):**
- `.values(data)` - Set values to insert
- `.execute()` - Execute insert and return array of inserted records
- `.executeTakeFirst()` - Execute insert and return first inserted record
**For UPDATE queries (`update`):**
- `.set(data)` - Set values to update
- `.where(field, operator, value)` - Add a WHERE condition
- `.execute()` - Execute update and return `{ affectedRecords: number }`
**For DELETE queries (`deleteFrom`):**
- `.where(field, operator, value)` - Add a WHERE condition
- `.execute()` - Execute delete and return `{ affectedRecords: number }`
**For AGGREGATION queries (`aggregateFrom`):**
- `.groupBy(field, direction)` - Group by a field ('asc' or 'desc')
- `.metrics(aggregateFunctions)` - Specify aggregate functions (e.g., `{ total: count('id') }`)
- `.where(field, operator, value)` - Add a WHERE condition
- `.execute()` - Execute aggregation and return array of grouped results
### Aggregate Functions
Import these functions from `@taylordb/query-builder`:
- `count(field)` - Count records
- `sum(field)` - Sum numeric values
- `avg(field)` - Average numeric values
- `min(field)` - Minimum value
- `max(field)` - Maximum value
## Common Mistakes to Avoid
**⚠️ CRITICAL: The following methods DO NOT EXIST and will cause errors:**
- ❌ `.countRecords()` - **DOES NOT EXIST**
- ❌ `.getCount()` - **DOES NOT EXIST**
- ❌ `.length` - **DOES NOT EXIST** on query builder chains
**Note**: `.count()` DOES exist for `selectFrom` queries. See the "Counting Records" section below for proper usage.
## Usage Examples
### Selecting Data
You can select data from a table using the `selectFrom` method. You can specify which fields to return, and you can filter, sort, and paginate the results.
```typescript
const customers = await qb
.selectFrom('customers')
.select(['firstName', 'lastName'])
.where('firstName', '=', 'John')
.orderBy('lastName', 'asc')
.paginate(1, 10)
.execute();
```bash
npm install @taylordb/query-builder
```
### Counting Records
## Getting Started
There are two ways to count records in TaylorDB, each suited for different use cases:
### 1. Generate TypeScript Types
#### Method 1: Using `.count()` on `selectFrom` (Recommended for simple counts)
First, you need to generate a `taylor.types.ts` file from your TaylorDB schema using the CLI. This file will contain the TypeScript definitions for your database schema, enabling the query builder's type-safety features.
**Use this when**: You need a single count value and don't need grouping or multiple metrics.
```typescript
// Count all users - returns a number directly
const totalUsers = await qb
.selectFrom('users')
.count();
console.log(`Total users: ${totalUsers}`);
// Count with filters - respects all WHERE conditions
const activeUsers = await qb
.selectFrom('users')
.where('status', '=', 'active')
.where('age', '>', 18)
.count();
console.log(`Active adult users: ${activeUsers}`);
// Count with relation filters
const usersWithPosts = await qb
.selectFrom('users')
.where('posts', 'isNotEmpty')
.count();
console.log(`Users with posts: ${usersWithPosts}`);
```bash
npx @taylordb/cli generate-schema
```
**Key Points:**
- `.count()` returns `Promise<number>` directly (not an array)
- Works with all `selectFrom` chain methods (`.where()`, `.orderBy()`, etc.)
- Simple and efficient for single count values
- No need to import `count` function or use destructuring
### 2. Create a Query Builder Instance
#### Method 2: Using `aggregateFrom` with `count()` function (For grouped counts or multiple metrics)
**Use this when**: You need counts grouped by field(s) or multiple aggregate metrics.
Once you have your types file, you can create a new query builder instance.
```typescript
import { count } from '@taylordb/query-builder';
import { createQueryBuilder } from '@taylordb/query-builder';
import { TaylorDatabase } from './taylor.types'; // Import the generated types
// Count grouped by status (returns array of results)
const statusCounts = await qb
.aggregateFrom('users')
.groupBy('status', 'asc')
.metrics({
total: count('id'),
})
.execute();
// Find specific status count
const activeCount = statusCounts.find(item => item.status === 'active')?.total || 0;
// Multiple metrics with grouping
const userStats = await qb
.aggregateFrom('users')
.groupBy('status', 'asc')
.metrics({
total: count('id'),
averageAge: avg('age'),
})
.execute();
```
**Key Points:**
- Must import `count` function from `@taylordb/query-builder`
- Returns an array of grouped results
- Use when you need grouping or multiple aggregate functions
- More flexible but slightly more verbose for simple counts
#### When to Use Which Method
- **Use `.count()`** when: You need a single count value (e.g., total users, active orders, etc.)
- **Use `aggregateFrom`** when: You need counts grouped by field(s) or multiple aggregate metrics together
### Inserting Data
You can insert data into a table using the `insertInto` method.
```typescript
const newCustomer = await qb
.insertInto('customers')
.values({
firstName: 'Jane',
lastName: 'Doe',
})
.execute();
```
### Updating Data
You can update data in a table using the `update` method.
```typescript
const { affectedRecords } = await qb
.update('customers')
.set({ lastName: 'Smith' })
.where('id', '=', 1)
.execute();
```
### Deleting Data
You can delete data from a table using the `deleteFrom` method.
```typescript
const { affectedRecords } = await qb
.deleteFrom('customers')
.where('id', '=', 1)
.execute();
```
### Aggregation Queries
You can perform powerful aggregation queries using the `aggregateFrom` method. You can group by one or more fields and specify aggregate functions to apply.
```typescript
import { count, sum, avg, max, min } from '@taylordb/query-builder';
const aggregates = await qb
.aggregateFrom('orders')
.groupBy('status', 'asc')
.metrics({
orderCount: count('id'),
totalRevenue: sum('total'),
averageOrder: avg('total'),
maxOrder: max('total'),
minOrder: min('total'),
})
.execute();
```
### Transactions
You can execute a series of operations within a single atomic transaction. If any operation within the transaction fails, all previous operations will be rolled back.
```typescript
const newCustomer = await qb.transaction(async tx => {
const customer = await tx
.insertInto('customers')
.values({
firstName: 'John',
lastName: 'Doe',
})
.executeTakeFirst();
if (!customer) {
throw new Error('Customer creation failed.');
}
await tx
.insertInto('orders')
.values({
customerId: customer.id,
orderDate: new Date().toISOString(),
total: 100,
})
.execute();
return customer;
const qb = createQueryBuilder<TaylorDatabase>({
baseUrl: 'YOUR_TAYLORDB_BASE_URL',
apiKey: 'YOUR_TAYLORDB_API_KEY',
});
```
### Handling Attachments
## Usage
You can upload files and associate them with your records using the `uploadAttachments` method. This is useful for handling things like user avatars, product images, or any other file-based data.
### Select Queries
First, upload the file(s) to get `Attachment` instances:
#### Basic Select
Select specific columns from a table.
```typescript
const filesToUpload = [
{ file: new Blob(['file content']), name: 'avatar.png' },
];
const attachments = await qb.uploadAttachments(filesToUpload);
```
Then, you can use the returned `Attachment` instances when creating or updating records. The query builder will automatically convert them into the correct format.
```typescript
// Create a new customer with an avatar
const newCustomer = await qb
.insertInto('customers')
.values({
firstName: 'Jane',
lastName: 'Doe',
avatar: attachments[0], // Use the Attachment instance
})
.executeTakeFirst();
// Update an existing customer's avatar
const { affectedRecords } = await qb
.update('customers')
.set({
avatar: attachments[0], // Use the Attachment instance
})
.where('id', '=', 1)
.execute();
```
### Batch Queries
You can execute multiple queries in a single batch request for improved performance. The result will be a tuple that corresponds to the results of each query in the batch.
```typescript
const [customers, newCustomer] = await qb
.batch([
qb.selectFrom('customers').select(['firstName', 'lastName']),
qb.insertInto('customers').values({ firstName: 'John', lastName: 'Doe' }),
])
.execute();
```
## Best Practices for Performance
When working with large databases, optimizing your queries is crucial for fast and efficient data retrieval. Here are some best practices to follow:
### 1. Select Only Necessary Fields
To minimize data transfer and improve query speed, always select only the fields you need. Avoid fetching all columns from a table if you only require a subset of them.
**Bad Practice:**
```typescript
// Fetches all fields for all customers, which can be slow with large tables.
const customers = await qb
.selectFrom('customers')
.selectAll()
.execute();
```
**Good Practice:**
```typescript
// Fetches only the required fields, leading to a faster and more efficient query.
const customers = await qb
.selectFrom('customers')
.select(['firstName', 'lastName', 'email'])
.execute();
```
### 2. Use Aggregations for Metrics and Dashboards
When building dashboards or calculating metrics (e.g., total sales, user counts), it's more efficient to perform aggregations directly in the database rather than fetching raw data and processing it in your application. The `aggregateFrom` method is optimized for this purpose.
**Bad Practice (less efficient):**
```typescript
// Fetches all orders and then calculates the total count in the application.
const orders = await qb
.selectFrom('orders')
.select(['id'])
.execute();
const totalOrders = orders.length;
```
**Good Practice (more efficient):**
```typescript
// For simple counts, use .count() method - simpler and more efficient
const totalOrders = await qb
.selectFrom('orders')
.count();
// Or if you need grouping, use aggregateFrom
import { count } from '@taylordb/query-builder';
const [{ totalOrders }] = await qb
.aggregateFrom('orders')
.metrics({
totalOrders: count('id'),
})
.execute();
```
**Example: Counting records grouped by status**
Use `selectAll()` to fetch all columns.
```typescript
import { count } from '@taylordb/query-builder';
// Count tasks by status - returns array of grouped results
const statusCounts = await qb
.aggregateFrom('tasks')
.groupBy('status', 'asc')
.metrics({
total: count('id'),
})
.execute();
// Extract specific counts
const doneCount = statusCounts.find(item => item.status === 'Done')?.total || 0;
const pendingCount = statusCounts.find(item => item.status === 'Pending')?.total || 0;
```
**Example: Simple counts for individual metrics**
```typescript
// For simple counts without grouping, use .count() method
const totalDone = await qb
.selectFrom('tasks')
.where('status', '=', 'Done')
.count();
const totalPending = await qb
.selectFrom('tasks')
.where('status', '=', 'Pending')
.count();
```
**Alternative: Using batch queries for multiple filtered counts**
```typescript
// If you need multiple simple counts, batch queries can be efficient
const [totalDone, totalPending] = await qb.batch([
qb.selectFrom('tasks').where('status', '=', 'Done').count(),
qb.selectFrom('tasks').where('status', '=', 'Pending').count(),
]);
```
**Note**:
- Use `.count()` for simple single counts (most efficient)
- Use `aggregateFrom` with `groupBy` when you need counts grouped by field(s)
- Use `batch` when you need multiple different filtered counts in parallel
Using aggregations reduces the amount of data transferred over the network and leverages the database's power for calculations, resulting in better performance for your application.
## Recipes
### Select with Relations
You can use the `with` method to fetch related records from a linked table.
```typescript
// Assuming 'customers' has a link field 'orders' to the 'orders' table
const customersWithOrders = await qb
const allCustomerData = await qb
.selectFrom('customers')
.select(['firstName', 'lastName'])
.selectAll()
.execute();
```
#### Filtering
Use `where` and `orWhere` to filter your results.
```typescript
const johns = await qb
.selectFrom('users')
.select(['name', 'email'])
.where('name', '=', 'John Doe')
.orWhere('email', '=', 'john.doe@example.com')
.execute();
```
You can also nest `where` clauses for complex logic.
```typescript
const users = await qb
.selectFrom('users')
.where(qb =>
qb.where('role', '=', 'admin').orWhere('lastActive', '>', '2023-01-01')
)
.execute();
```
#### Fetching Relations
Include related records from linked tables using `with`.
```typescript
// Get users and all fields from their related posts
const usersWithPosts = await qb
.selectFrom('users')
.select(['id', 'name'])
.with(['posts'])
.execute();
```
You can also provide a function to customize the subquery for the relation.
```typescript
// Get users and only the title of their published posts
const usersWithPublishedPosts = await qb
.selectFrom('users')
.select(['id', 'name'])
.with({
orders: qb => qb.select(['orderDate', 'total']),
posts: (qb) => qb.select(['title']).where('isPublished', '=', true),
})
.execute();
```
### Cross-Filters
#### Cross-Table Filtering
You can filter records in one table based on the values in a linked table.
Filter records based on conditions in a related table.
```typescript
// Get all customers who have placed an order with a total greater than 100
const highValueCustomers = await qb
.selectFrom('customers')
.where('orders', 'hasAnyOf', qb => qb.where('total', '>', 100))
// Get users who have at least one published post
const usersWithPublishedPosts = await qb
.selectFrom('users')
.where('posts', 'hasAnyOf', qb => qb.where('isPublished', '=', true))
.execute();
```
### Conditional Updates
You can use `where` clauses to update only the records that match a specific condition.
#### Sorting and Pagination
```typescript
const users = await qb
.selectFrom('users')
.select(['id', 'name'])
.orderBy('name', 'asc')
.paginate(2, 25) // Page 2, 25 items per page
.execute();
```
### Insert Queries
Insert single or multiple records. Use `returning` to get data back from the new records.
```typescript
const newUsers = await qb
.insertInto('users')
.values([
{ name: 'John Doe', email: 'john.doe@example.com' },
{ name: 'Jane Doe', email: 'jane.doe@example.com' },
])
.returning(['id', 'name'])
.execute();
```
### Update Queries
Update records matching a `where` clause.
```typescript
// Update the status of all orders placed before a certain date
const { affectedRecords } = await qb
.update('orders')
.set({ status: 'archived' })
.where('orderDate', '<', '2023-01-01')
.update('users')
.set({ name: 'New Name' })
.where('id', '=', 1)
.execute();
```
### Delete Queries
Delete records matching a `where` clause.
```typescript
const { affectedRecords } = await qb
.deleteFrom('users')
.where('id', '=', 1)
.execute();
```
### Aggregation Queries
Perform powerful aggregations on your data.
```typescript
const userStats = await qb
.aggregateFrom('users')
.groupBy('role', 'asc')
.withAggregates({
id: ['count'],
age: ['avg', 'sum'],
})
.execute();
```
### Batch Queries
Execute multiple queries in a single request for improved performance.
```typescript
const [users, newUser] = await qb.batch([
qb.selectFrom('users').select(['id', 'name']),
qb.insertInto('users').values({ name: 'New User' }).returning(['id']),
]).execute();
```
### Real-time Subscriptions
Subscribe to queries and get real-time updates when data changes.
```typescript
const { unsubscribe } = await qb
.selectFrom('users')
.select(['id', 'name'])
.subscribe((users) => {
console.log('Users updated:', users);
});
// To stop listening for updates
unsubscribe();
```

View File

@ -17,7 +17,7 @@
"@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-tabs": "^1.1.13",
"@taylordb/query-builder": "^0.10.1",
"@taylordb/query-builder": "^0.9.13",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.561.0",

View File

@ -27,8 +27,8 @@ importers:
specifier: ^1.1.13
version: 1.1.13(@types/react-dom@19.2.3(@types/react@19.2.6))(@types/react@19.2.6)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)
'@taylordb/query-builder':
specifier: ^0.10.1
version: 0.10.1
specifier: ^0.9.13
version: 0.9.13
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
@ -1030,11 +1030,11 @@ packages:
peerDependencies:
vite: ^5.2.0 || ^6 || ^7
'@taylordb/query-builder@0.10.1':
resolution: {integrity: sha512-WUyohbO8R+xFC+t+zfTP5VSLakGlBu2gsdWbFWwru4KqLNFW/NCsIvSDhzNObVbtbSgvkf+oVC0li+/z9uZYig==}
'@taylordb/query-builder@0.9.13':
resolution: {integrity: sha512-PpW/uIpDxKhMa7+1iAq1H3bMBpA+ho91AcBlOQ4v6lliax0vVFyLZ9YCcKknEINGy1xsaY2zVDgRg5upNZ2xNw==}
'@taylordb/shared@0.4.4':
resolution: {integrity: sha512-Xykr4I26JapNLePkapBGjz15t9Ep1iLs30VbfCcc2z30x8Qy/2tm+sSa5LcacCP2EaxNVDp2UuYKhZ7kOWBLBQ==}
'@taylordb/shared@0.4.2':
resolution: {integrity: sha512-vYod82anSozreyDi39unHjdlfgBuv7Ga0yhvoH8hQh7/KSc1vb3E3BVnMuVIsYl26fT95uA7IKy4hr3s2cjUKw==}
'@types/babel__core@7.20.5':
resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==}
@ -2872,13 +2872,12 @@ snapshots:
tailwindcss: 4.1.18
vite: 7.2.2(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)
'@taylordb/query-builder@0.10.1':
'@taylordb/query-builder@0.9.13':
dependencies:
'@taylordb/shared': 0.4.4
'@taylordb/shared': 0.4.2
eventemitter3: 5.0.1
fast-json-patch: 3.1.1
json-to-graphql-query: 2.3.0
lodash: 4.17.21
socket.io-client: 4.8.1
zod: 4.1.12
transitivePeerDependencies:
@ -2886,7 +2885,7 @@ snapshots:
- supports-color
- utf-8-validate
'@taylordb/shared@0.4.4':
'@taylordb/shared@0.4.2':
dependencies:
lodash: 4.17.21

View File

@ -1,28 +0,0 @@
import { createQueryBuilder } from "@taylordb/query-builder";
import type { TaylorDatabase } from "./taylordb.types";
let apiKey: string | undefined;
if (typeof window !== "undefined") {
const searchParams = new URLSearchParams(window.location.search);
const apiKeyFromParams = searchParams.get("apiKey");
if (apiKeyFromParams) {
// Store in session storage if found in search params
sessionStorage.setItem("authToken", apiKeyFromParams);
apiKey = apiKeyFromParams;
} else {
// If not in search params, try to get it from session storage
apiKey = sessionStorage.getItem("authToken") ?? undefined;
}
}
if (!apiKey) {
throw new Error("No authentication token found");
}
export const queryBuilder = createQueryBuilder<TaylorDatabase>({
baseUrl: import.meta.env.VITE_TAYLORDB_BASE_URL,
baseId: import.meta.env.VITE_TAYLORDB_BASE_ID,
apiKey,
});

View File

@ -1,39 +0,0 @@
# yaml-language-server: $schema=https://server-vms.develop.taylordb.ai/apps/config-schema/v1
version: 1
project: blank
runtime:
type: node
version: 20
packageManager: pnpm
services:
client:
workDir: .
install:
commands:
- pnpm install
dev:
command: pnpm dev
port: 5173
env:
vars:
NODE_ENV: production
VITE_TAYLORDB_BASE_ID: vars.TAYLORDB_SERVER_ID
VITE_TAYLORDB_BASE_URL: vars.TAYLORDB_EXTERNAL_BASE_URL
taylordb:
types:
- output: src/lib/taylordb.types.ts
format: typescript
onChange:
- pnpm lint
preview:
service: client
routing:
- path: /
service: client

View File

@ -74,10 +74,8 @@ export default defineConfig({
host: true,
port: 5173,
hmr: {
host: "",
protocol: "wss",
clientPort: 443,
path: "/__vite_hmr",
},
},
});