@harperfast/skills 1.4.6 → 1.4.8

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
@@ -40,7 +40,7 @@ export const rules = {
40
40
  "extending-tables": "---\nname: extending-tables\ndescription: How to add custom logic to automatically generated table resources in Harper.\n---\n\n# Extending Tables\n\nInstructions for the agent to follow when extending table resources in Harper.\n\n## When to Use\n\nUse this skill when you need to add custom validation, side effects (like webhooks), data transformation, or custom access control to the standard CRUD operations of a Harper table.\n\n## How It Works\n\n1. **Define the Table in GraphQL**: In your `.graphql` schema, define the table using the `@table` directive. **Do not** use `@export` if you plan to extend it.\n ```graphql\n type MyTable @table {\n \tid: ID @primaryKey\n \tname: String\n }\n ```\n2. **Create the Extension File**: Create a `.ts` file in your `resources/` directory.\n3. **Extend the Table Resource**: Export a class that extends `tables.YourTableName`:\n\n ```typescript\n import { type RequestTargetOrId, tables } from 'harper';\n\n export class MyTable extends tables.MyTable {\n \tasync post(target: RequestTargetOrId, record: any) {\n \t\t// Custom logic here\n \t\tif (!record.name) {\n \t\t\tthrow new Error('Name required');\n \t\t}\n \t\treturn super.post(target, record);\n \t}\n }\n ```\n\n4. **Override Methods**: Override `get`, `post`, `put`, `patch`, or `delete` as needed. Always call `super[method]` to maintain default Harper functionality unless you intend to replace it entirely.\n5. **Implement Logic**: Use overrides for validation, side effects, or transforming data before/after database operations.\n",
41
41
  "handling-binary-data": "---\nname: handling-binary-data\ndescription: How to store and serve binary data like images or audio in Harper.\n---\n\n# Handling Binary Data\n\nInstructions for the agent to follow when handling binary data in Harper.\n\n## When to Use\n\nUse this skill when you need to store binary files (images, audio, etc.) in the database or serve them back to clients via REST endpoints.\n\n## How It Works\n\n1. **Store Binary Data**: In your resource's `post` or `put` method, convert incoming data to Buffers and then to Blobs using `createBlob` from Harper's globals. Include the MIME type if available:\n\n ```typescript\n async post(target, record) {\n if (record.data) {\n record.data = createBlob(Buffer.from(record.data, record.encoding || 'base64'), {\n type: record.contentType || 'application/octet-stream',\n });\n }\n return super.post(target, record);\n }\n ```\n\n2. **Serve Binary Data**: In your resource's `get` method, return a response object with the appropriate `Content-Type` and the binary data in the `body`:\n ```typescript\n async get(target) {\n const record = await super.get(target);\n if (record?.data) {\n return {\n status: 200,\n headers: { 'Content-Type': record.data.type || 'application/octet-stream' },\n body: record.data,\n };\n }\n return record;\n }\n ```\n3. **Use the Blob Type**: Ensure your GraphQL schema uses the `Blob` scalar for binary fields.\n",
42
42
  "logging": "---\nname: logging\ndescription: Best practices for logging in Harper, including console capture, the granular logger interface, and programmatic log retrieval.\n---\n\n# Logging Best Practices\n\nHarper provides a robust logging system that captures standard output and offers a granular, tagged logging interface for both local and deployed environments.\n\n## Standard Console Logging\n\nThe simplest way to log in Harper is using standard JavaScript console methods. `console.log()`, `console.warn()`, `console.error()`, and `console.trace()` are automatically captured by Harper and can be viewed in the logs.\n\n- `console.log(...)`: Captured as `stdout` level in Harper logs.\n- `console.warn(...)`: Captured as `stderr` level in Harper logs.\n- `console.error(...)`: Captured as `stderr` level in Harper logs.\n- `console.trace(...)`: Captured as `stdout` level in Harper logs (includes stack trace).\n\n## Harper Logger\n\nFor more granularity and better organization, use Harper's built-in `logger`. You can use the global `logger` object or import it from the `harper` package.\n\n### Log Levels\n\nThe Harper `logger` supports the following levels (ordered by increasing severity):\n\n- `trace`\n- `debug`\n- `info`\n- `warn`\n- `error`\n- `fatal`\n- `notify`\n\n### Usage\n\n```typescript\nimport { logger, loggerWithTag } from 'harper';\n\n// Basic logging\nlogger.info('Application started');\nlogger.error('An error occurred', error);\n\n// Tagged logging for better filtering (Namespacing)\nconst authLogger = loggerWithTag('auth');\nauthLogger.debug('User login attempt', { userId: '123' });\n```\n\nUsing `loggerWithTag` is highly recommended for grouping related logs, making them much easier to filter and analyze in the Harper Studio or via the API.\n\n## Programmatic Log Retrieval\n\nYou can programmatically read logs from a deployed Harper instance using the `read_log` operation. This is useful for building custom monitoring tools or debugging dashboards.\n\n### `read_log` Operation\n\nThe `read_log` operation is a POST request to the Harper instance.\n\n**Example Request:**\n\n```json\n{\n\t\"operation\": \"read_log\",\n\t\"limit\": 100,\n\t\"start\": 0,\n\t\"level\": \"error\",\n\t\"order\": \"desc\",\n\t\"from\": \"2024-01-01T00:00:00.000Z\",\n\t\"until\": \"2024-01-02T00:00:00.000Z\"\n}\n```\n\n### Parameters\n\n- `limit`: Number of log entries to return.\n- `start`: Offset for pagination.\n- `level`: Filter by log level (`info`, `error`, `warn`, `debug`, `trace`, `notify`, `fatal`, `stdout`, `stderr`).\n- `from`: ISO 8601 timestamp to start reading from.\n- `until`: ISO 8601 timestamp to stop reading at.\n- `order`: Sort order, either `asc` or `desc`.\n- `replicated`: (Boolean) Include logs from replicated nodes in a cluster.\n\n### Log Entry Structure\n\nEach log entry returned by `read_log` typically includes:\n\n- `level`: The severity level of the log.\n- `timestamp`: When the log was recorded.\n- `thread`: The execution thread.\n- `tags`: An array of tags (e.g., from `loggerWithTag`).\n- `node`: The node name in a Harper cluster.\n- `message`: The logged content.\n",
43
- "programmatic-table-requests": "---\nname: programmatic-table-requests\ndescription: How to interact with Harper tables programmatically using the `tables` object.\n---\n\n# Programmatic Table Requests\n\nInstructions for the agent to follow when interacting with Harper tables via code.\n\n## When to Use\n\nUse this skill when you need to perform database operations (CRUD, search, subscribe) from within Harper Resources or scripts.\n\n## How It Works\n\n1. **Access the Table**: Use the global `tables` object followed by your table name (e.g., `tables.MyTable`).\n2. **Perform CRUD Operations**:\n - **Get**: `await tables.MyTable.get(id)` for a single record or `await tables.MyTable.get({ conditions: [...] })` for multiple.\n - **Create**: `await tables.MyTable.post(record)` (auto-generates ID) or `await tables.MyTable.put(id, record)`.\n - **Update**: `await tables.MyTable.patch(id, partialRecord)` for partial updates.\n - **Delete**: `await tables.MyTable.delete(id)`.\n3. **Use Updatable Records for Atomic Ops**: Call `update(id)` to get a reference, then use `addTo` or `subtractFrom` for atomic increments/decrements:\n ```typescript\n const stats = await tables.Stats.update('daily');\n stats.addTo('viewCount', 1);\n ```\n4. **Search and Stream**: Use `search(query)` for efficient streaming of large result sets:\n ```typescript\n for await (const record of tables.MyTable.search({ conditions: [...] })) {\n // process record\n }\n ```\n5. **Real-time Subscriptions**: Use `subscribe(query)` to listen for changes:\n ```typescript\n for await (const event of tables.MyTable.subscribe(query)) {\n \t// handle event\n }\n ```\n6. **Publish Events**: Use `publish(id, message)` to trigger subscriptions without necessarily persisting data.\n\n## Cautions\n\nBe very careful when performing updates and deletions! You may be dealing with live production data. The wrong request to delete, without approval from a human, could be devastating to a business. Always use the proper approval process.\n",
43
+ "programmatic-table-requests": "---\nname: programmatic-table-requests\ndescription: How to interact with Harper tables programmatically using the `tables` object.\n---\n\n# Programmatic Table Requests\n\nInstructions for the agent to follow when interacting with Harper tables via code.\n\n## When to Use\n\nUse this skill when you need to perform database operations (CRUD, search, subscribe) from within Harper Resources or scripts.\n\n## How It Works\n\n1. **Access the Table**: Use the global `tables` object followed by your table name (e.g., `tables.MyTable`).\n2. **Perform CRUD Operations**:\n - **Get**: `await tables.MyTable.get(id)` for a single record or `await tables.MyTable.get({ conditions: [...] })` for multiple.\n - **Create**: `await tables.MyTable.post(record)` (auto-generates ID) or `await tables.MyTable.put(id, record)`.\n - **Update**: `await tables.MyTable.patch(id, partialRecord)` for partial updates.\n - **Delete**: `await tables.MyTable.delete(id)`.\n3. **Use Updatable Records for Atomic Ops**: Call `update(id)` to get a reference, then use `addTo` or `subtractFrom` for atomic increments/decrements:\n ```typescript\n const stats = await tables.Stats.update('daily');\n stats.addTo('viewCount', 1);\n ```\n4. **Search and Stream**: Use `search(query)` for efficient streaming of large result sets:\n ```typescript\n for await (const record of tables.MyTable.search({ conditions: [...] })) {\n // process record\n }\n ```\n See the [Query Conditions](#query-conditions) section below for the full query object reference.\n5. **Real-time Subscriptions**: Use `subscribe(query)` to listen for changes:\n ```typescript\n for await (const event of tables.MyTable.subscribe(query)) {\n \t// handle event\n }\n ```\n6. **Publish Events**: Use `publish(id, message)` to trigger subscriptions without necessarily persisting data.\n\n## Query Conditions\n\nWhen passing a query to `search()`, `get()`, or `subscribe()`, use a query object with a `conditions` array.\n\n### Condition Object Shape\n\n| Property | Description |\n| ------------ | ------------------------------------------------------------------------------------------ |\n| `attribute` | Field name, or array of field names to traverse a relationship (e.g., `['brand', 'name']`) |\n| `value` | The value to compare against |\n| `comparator` | One of the comparator strings below (default: `equals`) |\n| `operator` | `and` (default) or `or` — applies to a nested `conditions` block |\n| `conditions` | Nested array of condition objects for complex AND/OR logic |\n\n### Comparator Values\n\nUse these exact strings — incorrect comparator names will silently fail or error:\n\n| Comparator | Meaning |\n| -------------------- | ---------------------------------------------------------- |\n| `equals` | Exact match (default) |\n| `not_equal` | Not equal |\n| `greater_than` | `>` |\n| `greater_than_equal` | `>=` |\n| `less_than` | `<` |\n| `less_than_equal` | `<=` |\n| `starts_with` | String starts with value |\n| `contains` | String contains value |\n| `ends_with` | String ends with value |\n| `between` | Value is between two bounds (pass `value` as `[min, max]`) |\n\n### Query Object Parameters\n\n| Property | Description |\n| ------------ | ------------------------------------------------------------------------------------ |\n| `conditions` | Array of condition objects |\n| `limit` | Maximum number of records to return |\n| `offset` | Number of records to skip (for pagination) |\n| `select` | Array of attribute names to return; supports `$id` and `$updatedtime` |\n| `sort` | Object with `attribute`, `descending` (bool), and optional `next` for secondary sort |\n\n### Examples\n\n**Simple filter:**\n\n```javascript\nfor await (const record of tables.Product.search({\n conditions: [{ attribute: 'price', comparator: 'less_than', value: 100 }],\n limit: 20,\n})) { ... }\n```\n\n**AND + nested OR:**\n\n```javascript\nfor await (const record of tables.Product.search({\n conditions: [\n { attribute: 'price', comparator: 'less_than', value: 100 },\n {\n operator: 'or',\n conditions: [\n { attribute: 'rating', comparator: 'greater_than', value: 4 },\n { attribute: 'featured', value: true },\n ],\n },\n ],\n})) { ... }\n```\n\n**Relationship traversal:**\n\n```javascript\nfor await (const record of tables.Book.search({\n conditions: [{ attribute: ['brand', 'name'], comparator: 'equals', value: 'Harper' }],\n})) { ... }\n```\n\n**Sort and paginate:**\n\n```javascript\nfor await (const record of tables.Product.search({\n conditions: [{ attribute: 'inStock', value: true }],\n sort: { attribute: 'price', descending: false },\n limit: 10,\n offset: 20,\n})) { ... }\n```\n\n## Cautions\n\nBe very careful when performing updates and deletions! You may be dealing with live production data. The wrong request to delete, without approval from a human, could be devastating to a business. Always use the proper approval process.\n",
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",
@@ -30,6 +30,7 @@ Use this skill when you need to perform database operations (CRUD, search, subsc
30
30
  // process record
31
31
  }
32
32
  ```
33
+ See the [Query Conditions](#query-conditions) section below for the full query object reference.
33
34
  5. **Real-time Subscriptions**: Use `subscribe(query)` to listen for changes:
34
35
  ```typescript
35
36
  for await (const event of tables.MyTable.subscribe(query)) {
@@ -38,6 +39,94 @@ Use this skill when you need to perform database operations (CRUD, search, subsc
38
39
  ```
39
40
  6. **Publish Events**: Use `publish(id, message)` to trigger subscriptions without necessarily persisting data.
40
41
 
42
+ ## Query Conditions
43
+
44
+ When passing a query to `search()`, `get()`, or `subscribe()`, use a query object with a `conditions` array.
45
+
46
+ ### Condition Object Shape
47
+
48
+ | Property | Description |
49
+ | ------------ | ------------------------------------------------------------------------------------------ |
50
+ | `attribute` | Field name, or array of field names to traverse a relationship (e.g., `['brand', 'name']`) |
51
+ | `value` | The value to compare against |
52
+ | `comparator` | One of the comparator strings below (default: `equals`) |
53
+ | `operator` | `and` (default) or `or` — applies to a nested `conditions` block |
54
+ | `conditions` | Nested array of condition objects for complex AND/OR logic |
55
+
56
+ ### Comparator Values
57
+
58
+ Use these exact strings — incorrect comparator names will silently fail or error:
59
+
60
+ | Comparator | Meaning |
61
+ | -------------------- | ---------------------------------------------------------- |
62
+ | `equals` | Exact match (default) |
63
+ | `not_equal` | Not equal |
64
+ | `greater_than` | `>` |
65
+ | `greater_than_equal` | `>=` |
66
+ | `less_than` | `<` |
67
+ | `less_than_equal` | `<=` |
68
+ | `starts_with` | String starts with value |
69
+ | `contains` | String contains value |
70
+ | `ends_with` | String ends with value |
71
+ | `between` | Value is between two bounds (pass `value` as `[min, max]`) |
72
+
73
+ ### Query Object Parameters
74
+
75
+ | Property | Description |
76
+ | ------------ | ------------------------------------------------------------------------------------ |
77
+ | `conditions` | Array of condition objects |
78
+ | `limit` | Maximum number of records to return |
79
+ | `offset` | Number of records to skip (for pagination) |
80
+ | `select` | Array of attribute names to return; supports `$id` and `$updatedtime` |
81
+ | `sort` | Object with `attribute`, `descending` (bool), and optional `next` for secondary sort |
82
+
83
+ ### Examples
84
+
85
+ **Simple filter:**
86
+
87
+ ```javascript
88
+ for await (const record of tables.Product.search({
89
+ conditions: [{ attribute: 'price', comparator: 'less_than', value: 100 }],
90
+ limit: 20,
91
+ })) { ... }
92
+ ```
93
+
94
+ **AND + nested OR:**
95
+
96
+ ```javascript
97
+ for await (const record of tables.Product.search({
98
+ conditions: [
99
+ { attribute: 'price', comparator: 'less_than', value: 100 },
100
+ {
101
+ operator: 'or',
102
+ conditions: [
103
+ { attribute: 'rating', comparator: 'greater_than', value: 4 },
104
+ { attribute: 'featured', value: true },
105
+ ],
106
+ },
107
+ ],
108
+ })) { ... }
109
+ ```
110
+
111
+ **Relationship traversal:**
112
+
113
+ ```javascript
114
+ for await (const record of tables.Book.search({
115
+ conditions: [{ attribute: ['brand', 'name'], comparator: 'equals', value: 'Harper' }],
116
+ })) { ... }
117
+ ```
118
+
119
+ **Sort and paginate:**
120
+
121
+ ```javascript
122
+ for await (const record of tables.Product.search({
123
+ conditions: [{ attribute: 'inStock', value: true }],
124
+ sort: { attribute: 'price', descending: false },
125
+ limit: 10,
126
+ offset: 20,
127
+ })) { ... }
128
+ ```
129
+
41
130
  ## Cautions
42
131
 
43
132
  Be very careful when performing updates and deletions! You may be dealing with live production data. The wrong request to delete, without approval from a human, could be devastating to a business. Always use the proper approval process.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@harperfast/skills",
3
- "version": "1.4.6",
3
+ "version": "1.4.8",
4
4
  "description": "Best practices for making awesome Harper apps with your favorite Agent",
5
5
  "keywords": [],
6
6
  "homepage": "https://github.com/harperfast",