@harperfast/skills 1.4.5 → 1.4.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
|
@@ -44,7 +44,7 @@ export const rules = {
|
|
|
44
44
|
"querying-rest-apis": "---\nname: querying-rest-apis\ndescription: How to use query parameters to filter, sort, and paginate Harper REST APIs.\n---\n\n# Querying REST APIs\n\nInstructions for the agent to follow when querying Harper's REST APIs.\n\n## When to Use\n\nUse this skill when you need to perform advanced data retrieval (filtering, sorting, pagination, joins) using Harper's automatic REST endpoints.\n\n## How It Works\n\n1. **Basic Filtering**: Use attribute names as query parameters: `GET /Table/?key=value`.\n2. **Use Comparison Operators**: Append operators like `gt`, `ge`, `lt`, `le`, `ne` using FIQL-style syntax: `GET /Table/?price=gt=100`.\n3. **Apply Logic and Grouping**: Use `&` for AND, `|` for OR, and `()` for grouping: `GET /Table/?(rating=5|featured=true)&price=lt=50`.\n4. **Select Specific Fields**: Use `select()` to limit returned attributes: `GET /Table/?select(name,price)`.\n5. **Paginate Results**: Use `limit(count)` or `limit(offset, count)` to set the number of records to return and skip.\n - Example (first 10): `GET /Table/?limit(10)`\n - Example (skip 20, return 10): `GET /Table/?limit(20, 10)`\n6. **Sort Results**: Use `sort()` with `+` (asc) or `-` (desc) before the field name. Avoid `sort=field` format.\n - Example (asc): `GET /Table/?sort(+name)`\n - Example (desc): `GET /Table/?sort(-price)`\n - Example (combined): `GET /Table/?sort(-price,+name)`\n7. **Query Relationships**: Use dot syntax for tables linked with `@relationship`: `GET /Book/?author.name=Harper`.\n",
|
|
45
45
|
"real-time-apps": "---\nname: real-time-apps\ndescription: How to build real-time features in Harper using WebSockets and Pub/Sub.\n---\n\n# Real-time Applications\n\nInstructions for the agent to follow when building real-time applications in Harper.\n\n## When to Use\n\nUse this skill when you need to stream live updates to clients, implement chat features, or provide real-time data synchronization between the database and a frontend.\n\n## How It Works\n\n1. **Check Automatic WebSockets**: If you only need to stream table changes, use [Automatic APIs](automatic-apis.md) which provide a WebSocket endpoint for every `@export`ed table.\n2. **Implement `connect` in a Resource**: For custom bi-directional logic, implement the `connect` method.\n3. **Use Pub/Sub**: Use `tables.TableName.subscribe(query)` to listen for specific data changes and stream them to the client.\n4. **Handle SSE**: Ensure your `connect` method gracefully handles cases where `incomingMessages` is null (Server-Sent Events).\n5. **Connect from Client**: Use standard WebSockets (`new WebSocket('wss://...')`) to connect to your resource endpoint. Ensure you use the appropriate scheme (`ws://` for HTTP, `wss://` for HTTPS).\n\n## Examples\n\n### Bi-directional WebSocket Resource\n\n```typescript\nimport { Resource, tables } from 'harper';\n\nexport class MySocket extends Resource {\n\tasync *connect(target, incomingMessages) {\n\t\t// Subscribe to table changes\n\t\tconst subscription = await tables.MyTable.subscribe(target);\n\t\tif (!incomingMessages) {\n\t\t\treturn subscription; // SSE mode\n\t\t}\n\n\t\t// Handle incoming client messages\n\t\tfor await (let message of incomingMessages) {\n\t\t\tyield { received: message };\n\t\t}\n\t}\n}\n```\n",
|
|
46
46
|
"schema-design-tooling": "---\nname: schema-design-tooling\ndescription: Best practices for Harper schema design, including core directives and GraphQL tooling configuration.\n---\n\n# Schema Design & Tooling\n\nHarper uses GraphQL schemas to define database tables, relationships, and APIs. To ensure the best development experience for both humans and AI agents, it's important to understand the core directives and configure your project tooling correctly.\n\n## Core Harper Directives\n\nHarper extends GraphQL with custom directives that define database behavior. These are typically defined in `node_modules/harper/schema.graphql`. If you don't have access to that file, here is a reference of the most important ones:\n\n### Table Definition\n\n- `@table`: Marks a GraphQL type as a Harper database table.\n- `@export`: Automatically generates REST and WebSocket APIs for the table.\n- `@table(expiration: Int)`: Configures a time-to-expire for records in the table (useful for caching).\n\n### Attribute Constraints & Indexing\n\n- `@primaryKey`: Specifies the unique identifier for the table.\n- `@indexed`: Creates a standard index on the field for faster lookups.\n- `@indexed(type: \"HNSW\", distance: \"cosine\" | \"euclidean\" | \"dot\")`: Creates a vector index for similarity search.\n\n### Relationships\n\n- `@relationship(from: String)`: Defines a relationship to another table. `from` specifies the local field holding the foreign key.\n\n### Authentication & Authorization\n\n- `@auth(role: String)`: Restricts access to a table or field based on user roles.\n\n## Configuring GraphQL Tooling\n\nTo get the best IDE support (autocompletion, validation) and to help AI agents understand your schema context, you should create a `graphql.config.yml` file in your project root.\n\nThis file tells GraphQL tools where to find Harper's built-in types and directives alongside your own schema files.\n\n### Creating `graphql.config.yml`\n\nCreate a file named `graphql.config.yml` in your project root with the following content:\n\n```yaml\nschema:\n - 'node_modules/harper/schema.graphql'\n - 'schema.graphql'\n - 'schemas/*.graphql'\n```\n\n### Why this is important:\n\n1. **Shared Directives**: It includes `@table`, `@primaryKey`, etc., so they aren't marked as \"unknown directives\".\n2. **Context for Agents**: When an agent reads your project, seeing this config helps it locate the core Harper definitions, leading to more accurate code generation.\n3. **Consistency**: The `npm create harper@latest` command includes this by default. Manually adding it to existing projects ensures they follow the same standards.\n\n## Example Project Structure\n\nA typical Harper project with proper schema tooling:\n\n```text\nmy-harper-app/\n├── config.yaml\n├── graphql.config.yml\n├── package.json\n├── schema.graphql\n└── resources.js\n```\n",
|
|
47
|
-
"serving-web-content": "---\nname: serving-web-content\ndescription: How to serve static files and integrated Vite/React applications in Harper.\n---\n\n# Serving Web Content\n\nInstructions for the agent to follow when serving web content from Harper.\n\n## When to Use\n\nUse this skill when you need to serve a frontend (HTML, CSS, JS, or a React app) directly from your Harper instance.\n\n## How It Works\n\n1. **Choose a Method**: Decide between the simple Static Plugin or the integrated Vite Plugin.\n2. **Option A: Static Plugin (Simple)**:\n - Add to `config.yaml`:\n ```yaml\n static:\n files: 'web/*'\n ```\n - Place files in a `web/` folder in the project root.\n - Files are served at the root URL (e.g., `http://localhost:9926/index.html`).\n3. **Option B: Vite Plugin (Advanced/Development)**:\n - Add to `config.yaml`:\n ```yaml\n '@harperfast/vite-plugin':\n package: '@harperfast/vite-plugin'\n ```\n - Ensure `vite.config.ts` and `index.html` are in the project root.\n\n ```javascript\n import vue from '@vitejs/plugin-vue';\n import path from 'node:path';\n import { defineConfig } from 'vite';\n\n // https://vite.dev/config/\n export default defineConfig({\n \tplugins: [vue()],\n \tresolve: {\n \t\talias: {\n \t\t\t'@': path.resolve(import.meta.dirname, './src'),\n \t\t},\n \t},\n \tbuild: {\n \t\toutDir: 'web',\n \t\temptyOutDir: true,\n \t\trolldownOptions: {\n \t\t\texternal: ['**/*.test.*', '**/*.spec.*'],\n \t\t},\n \t},\n });\n ```\n\n - Install dependencies: `npm install --save-dev vite @harperfast/vite-plugin`.\n - Then `harper run .` will start up Harper and Vite with HMR. Vite does _not_ need to be executed separately.\n\n4. **Deploy for Production**: For Vite apps, use a build script to generate static files into a `web/` folder and deploy them using the static handler pattern. For example, these scripts in a package.json can perform the necessary steps:\n ```json\n \"build\": \"vite build\",\n \"deploy\": \"rm -Rf deploy && npm run build && mkdir deploy && mv web deploy/ && cp -R deploy-template/* deploy/ && cp -R schemas resources deploy/ &&
|
|
47
|
+
"serving-web-content": "---\nname: serving-web-content\ndescription: How to serve static files and integrated Vite/React applications in Harper.\n---\n\n# Serving Web Content\n\nInstructions for the agent to follow when serving web content from Harper.\n\n## When to Use\n\nUse this skill when you need to serve a frontend (HTML, CSS, JS, or a React app) directly from your Harper instance.\n\n## How It Works\n\n1. **Choose a Method**: Decide between the simple Static Plugin or the integrated Vite Plugin.\n2. **Option A: Static Plugin (Simple)**:\n - Add to `config.yaml`:\n ```yaml\n static:\n files: 'web/*'\n ```\n - Place files in a `web/` folder in the project root.\n - Files are served at the root URL (e.g., `http://localhost:9926/index.html`).\n3. **Option B: Vite Plugin (Advanced/Development)**:\n - Add to `config.yaml`:\n ```yaml\n '@harperfast/vite-plugin':\n package: '@harperfast/vite-plugin'\n ```\n - Ensure `vite.config.ts` and `index.html` are in the project root.\n\n ```javascript\n import vue from '@vitejs/plugin-vue';\n import path from 'node:path';\n import { defineConfig } from 'vite';\n\n // https://vite.dev/config/\n export default defineConfig({\n \tplugins: [vue()],\n \tresolve: {\n \t\talias: {\n \t\t\t'@': path.resolve(import.meta.dirname, './src'),\n \t\t},\n \t},\n \tbuild: {\n \t\toutDir: 'web',\n \t\temptyOutDir: true,\n \t\trolldownOptions: {\n \t\t\texternal: ['**/*.test.*', '**/*.spec.*'],\n \t\t},\n \t},\n });\n ```\n\n - Install dependencies: `npm install --save-dev vite @harperfast/vite-plugin`.\n - Then `harper run .` will start up Harper and Vite with HMR. Vite does _not_ need to be executed separately.\n\n4. **Deploy for Production**: For Vite apps, use a build script to generate static files into a `web/` folder and deploy them using the static handler pattern. For example, these scripts in a package.json can perform the necessary steps:\n ```json\n \"build\": \"vite build\",\n \"deploy\": \"rm -Rf deploy && npm run build && mkdir deploy && mv web deploy/ && cp -R deploy-template/* deploy/ && cp -R schemas resources deploy/ && (cd deploy && harper deploy_component . project=web restart=rolling replicated=true) && rm -Rf deploy\",\n ```\n Then in production, the \"Static Plugin\" option will performantly and securely serve your assets. `npm create harper@latest` scaffolds all of this for you.\n",
|
|
48
48
|
"typescript-type-stripping": "---\nname: typescript-type-stripping\ndescription: How to run TypeScript files directly in Harper without a build step.\n---\n\n# TypeScript Type Stripping\n\nInstructions for the agent to follow when using TypeScript in Harper.\n\n## When to Use\n\nUse this skill when you want to write Harper Resources in TypeScript and have them execute directly in Node.js without an intermediate build or compilation step.\n\n## How It Works\n\n1. **Verify Node.js Version**: Ensure you are using Node.js v22.6.0 or higher.\n2. **Name Files with `.ts`**: Create your resource files in the `resources/` directory with a `.ts` extension.\n3. **Use TypeScript Syntax**: Write your resource classes using standard TypeScript (interfaces, types, etc.).\n ```typescript\n import { Resource } from 'harper';\n export class MyResource extends Resource {\n \tasync get(): Promise<{ message: string }> {\n \t\treturn { message: 'Running TS directly!' };\n \t}\n }\n ```\n4. **Use Explicit Extensions in Imports**: When importing other local modules, include the `.ts` extension: `import { helper } from './helper.ts'`.\n5. **Configure `config.yaml`**: Ensure `jsResource` points to your `.ts` files:\n ```yaml\n jsResource:\n files: 'resources/*.ts'\n ```\n",
|
|
49
49
|
"using-blob-datatype": "---\nname: using-blob-datatype\ndescription: How to use the Blob data type for efficient binary storage in Harper.\n---\n\n# Using Blob Datatype\n\nInstructions for the agent to follow when working with the Blob data type in Harper.\n\n## When to Use\n\nUse this skill when you need to store unstructured or large binary data (media, documents) that is too large for standard JSON fields. Blobs provide efficient storage and integrated streaming support.\n\n## How It Works\n\n1. **Define Blob Fields**: In your GraphQL schema, use the `Blob` type:\n ```graphql\n type MyTable @table {\n \tid: ID @primaryKey\n \tdata: Blob\n }\n ```\n2. **Create and Store Blobs**: Use `createBlob()` from Harper's globals to wrap Buffers or Streams:\n ```javascript\n import { tables } from 'harper';\n const blob = createBlob(largeBuffer);\n await tables.MyTable.put('my-id', { data: blob });\n ```\n3. **Use Streaming (Optional)**: For very large files, pass a stream to `createBlob()` to avoid loading the entire file into memory.\n4. **Read Blob Data**: Retrieve the record and use `.bytes()` or streaming interfaces on the blob field:\n ```javascript\n const record = await tables.MyTable.get('my-id');\n const buffer = await record.data.bytes();\n ```\n5. **Ensure Write Completion**: Use `saveBeforeCommit: true` in `createBlob` options if you need the blob fully written before the record is committed.\n6. **Handle Errors**: Attach error listeners to the blob object to handle streaming failures.\n",
|
|
50
50
|
"vector-indexing": "---\nname: vector-indexing\ndescription: How to enable and query vector indexes for similarity search in Harper.\n---\n\n# Vector Indexing\n\nInstructions for the agent to follow when implementing vector search in Harper.\n\n## When to Use\n\nUse this skill when you need to perform similarity searches on high-dimensional data, such as AI embeddings for semantic search, recommendations, or image retrieval.\n\n## How It Works\n\n1. **Enable Vector Indexing**: In your GraphQL schema, add `@indexed(type: \"HNSW\")` to a numeric array field:\n ```graphql\n type Product @table {\n \tid: ID @primaryKey\n \ttextEmbeddings: [Float] @indexed(type: \"HNSW\")\n }\n ```\n2. **Configure Index Options (Optional)**: Fine-tune the index with parameters like `distance` (`cosine` or `euclidean`), `M`, and `efConstruction`.\n3. **Query with Vector Search**: Use `tables.Table.search()` with a `sort` object containing the `target` vector:\n ```javascript\n const results = await tables.Product.search({\n select: ['name', '$distance'],\n sort: {\n attribute: 'textEmbeddings',\n target: [0.1, 0.2, ...], // query vector\n },\n limit: 5,\n });\n ```\n4. **Filter by Distance**: Use `conditions` with a `target` vector and a `comparator` (e.g., `lt`) to return results within a similarity threshold:\n ```javascript\n const results = await tables.Product.search({\n \tconditions: {\n \t\tattribute: 'textEmbeddings',\n \t\tcomparator: 'lt',\n \t\tvalue: 0.1,\n \t\ttarget: searchVector,\n \t},\n });\n ```\n5. **Generate Embeddings**: Use external services (OpenAI, Ollama) to generate the numeric vectors before storing or searching them in Harper.\n\n```typescript\nimport OpenAI from 'openai';\nimport ollama from 'ollama';\n\nconst { Product } = tables;\nconst openai = new OpenAI();\n// the name of the OpenAI embedding model\nconst OPENAI_EMBEDDING_MODEL = 'text-embedding-3-small';\n\n// the name of the Ollama embedding model\nconst OLLAMA_EMBEDDING_MODEL = 'llama3';\n\nconst SIMILARITY_THRESHOLD = 0.5;\n\nexport class ProductSearch extends Resource {\n\t// based on env variable we choose the appropriate embedding generator\n\tgenerateEmbedding =\n\t\tprocess.env.EMBEDDING_GENERATOR === 'ollama'\n\t\t\t? this._generateOllamaEmbedding\n\t\t\t: this._generateOpenAIEmbedding;\n\n\t/**\n\t * Executes a search query using a generated text embedding and returns the matching products.\n\t *\n\t * @param {Object} data - The input data for the request.\n\t * @param {string} data.prompt - The prompt to generate the text embedding from.\n\t * @return {Promise<Array>} Returns a promise that resolves to an array of products matching the conditions,\n\t * including fields: name, description, price, and $distance.\n\t */\n\tasync post(data) {\n\t\tconst embedding = await this.generateEmbedding(data.prompt);\n\n\t\treturn await Product.search({\n\t\t\tselect: ['name', 'description', 'price', '$distance'],\n\t\t\tconditions: {\n\t\t\t\tattribute: 'textEmbeddings',\n\t\t\t\tcomparator: 'lt',\n\t\t\t\tvalue: SIMILARITY_THRESHOLD,\n\t\t\t\ttarget: embedding[0],\n\t\t\t},\n\t\t\tlimit: 5,\n\t\t});\n\t}\n\n\t/**\n\t * Generates an embedding using the Ollama API.\n\t *\n\t * @param {string} promptData - The input data for which the embedding is to be generated.\n\t * @return {Promise<number[][]>} A promise that resolves to the generated embedding as an array of numbers.\n\t */\n\tasync _generateOllamaEmbedding(promptData) {\n\t\tconst embedding = await ollama.embed({\n\t\t\tmodel: OLLAMA_EMBEDDING_MODEL,\n\t\t\tinput: promptData,\n\t\t});\n\t\treturn embedding?.embeddings;\n\t}\n\n\t/**\n\t * Generates OpenAI embeddings based on the given prompt data.\n\t *\n\t * @param {string} promptData - The input data used for generating the embedding.\n\t * @return {Promise<number[][]>} A promise that resolves to an array of embeddings, where each embedding is an array of floats.\n\t */\n\tasync _generateOpenAIEmbedding(promptData) {\n\t\tconst embedding = await openai.embeddings.create({\n\t\t\tmodel: OPENAI_EMBEDDING_MODEL,\n\t\t\tinput: promptData,\n\t\t\tencoding_format: 'float',\n\t\t});\n\n\t\tlet embeddings = [];\n\t\tembedding.data.forEach((embeddingData) => {\n\t\t\tembeddings.push(embeddingData.embedding);\n\t\t});\n\n\t\treturn embeddings;\n\t}\n}\n```\n\n## Examples\n\nSample request to the `ProductSearch` resource which prompts to find \"shorts for the gym\":\n\n```bash\ncurl -X POST \"http://localhost:9926/ProductSearch/\" \\\n-H \"Accept: application/json\" \\\n-H \"Content-Type: application/json\" \\\n-H \"Authorization: Basic <YOUR_AUTH>\" \\\n-d '{\"prompt\": \"shorts for the gym\"}'\n```\n\n---\n\n## When to Use Vector Indexing\n\nVector indexing is ideal when:\n\n- Storing embedding vectors from ML models\n- Performing semantic or similarity-based search\n- Working with high-dimensional numeric data\n- Exact-match indexes are insufficient\n\n---\n\n## Summary\n\n- Vector indexing enables fast similarity search on numeric arrays\n- Defined using `@indexed(type: \"HNSW\")`\n- Queried using a target vector in search sorting\n- Tunable for performance and accuracy\n"
|
|
@@ -59,7 +59,6 @@ Use this skill when you need to serve a frontend (HTML, CSS, JS, or a React app)
|
|
|
59
59
|
4. **Deploy for Production**: For Vite apps, use a build script to generate static files into a `web/` folder and deploy them using the static handler pattern. For example, these scripts in a package.json can perform the necessary steps:
|
|
60
60
|
```json
|
|
61
61
|
"build": "vite build",
|
|
62
|
-
"deploy": "rm -Rf deploy && npm run build && mkdir deploy && mv web deploy/ && cp -R deploy-template/* deploy/ && cp -R schemas resources deploy/ &&
|
|
63
|
-
"deploy:component": "(cd deploy && harper deploy_component . project=web restart=rolling replicated=true)"
|
|
62
|
+
"deploy": "rm -Rf deploy && npm run build && mkdir deploy && mv web deploy/ && cp -R deploy-template/* deploy/ && cp -R schemas resources deploy/ && (cd deploy && harper deploy_component . project=web restart=rolling replicated=true) && rm -Rf deploy",
|
|
64
63
|
```
|
|
65
64
|
Then in production, the "Static Plugin" option will performantly and securely serve your assets. `npm create harper@latest` scaffolds all of this for you.
|