@harperfast/skills 1.3.0 → 1.3.2

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/README.md CHANGED
@@ -12,6 +12,17 @@ npx skills add harperfast/skills
12
12
 
13
13
  Re-run this command later if you want to get the latest updates from us.
14
14
 
15
+ ### Manual Installation
16
+
17
+ If your corporate network prevents the `skills` CLI from downloading the skills, you can install them manually:
18
+
19
+ 1. Download the repository as a ZIP file from [GitHub](https://github.com/HarperFast/skills) (Code > Download ZIP).
20
+ 2. Extract the contents of the ZIP file.
21
+ 3. Copy the skill folders (e.g., `harper-best-practices`) into your project's agent configuration directory:
22
+ - **Junie, Cursor, Windsurf:** `.agent/skills`
23
+ - **Claude Desktop:** `.claude/skills`
24
+ - **Other Agents:** Refer to your agent's documentation for its skills/rules directory.
25
+
15
26
  ## Available Skills
16
27
 
17
28
  ### [Harper Best Practices](harper-best-practices/SKILL.md)
package/dist/index.js CHANGED
@@ -33,13 +33,13 @@ export const rules = {
33
33
  "checking-authentication": "---\nname: checking-authentication\ndescription: How to handle user authentication and sessions in Harper Resources.\n---\n\n# Checking Authentication\n\nInstructions for the agent to follow when handling authentication and sessions.\n\n## When to Use\n\nUse this skill when you need to implement sign-in/sign-out functionality, protect specific resource endpoints, or identify the currently logged-in user in a Harper application.\n\n## How It Works\n\n1. **Configure Harper for Sessions**: Ensure `harperdb-config.yaml` has sessions enabled and local auto-authorization disabled for testing:\n ```yaml\n authentication:\n authorizeLocal: false\n enableSessions: true\n ```\n2. **Implement Sign In**: Use `this.getContext().login(username, password)` to create a session:\n ```typescript\n async post(_target, data) {\n const context = this.getContext();\n try {\n await context.login(data.username, data.password);\n } catch {\n return new Response('Invalid credentials', { status: 403 });\n }\n return new Response('Logged in', { status: 200 });\n }\n ```\n3. **Identify Current User**: Use `this.getCurrentUser()` to access session data:\n ```typescript\n async get() {\n const user = this.getCurrentUser?.();\n if (!user) return new Response(null, { status: 401 });\n return { username: user.username, role: user.role };\n }\n ```\n4. **Implement Sign Out**: Use `this.getContext().logout()` or delete the session from context:\n ```typescript\n async post() {\n const context = this.getContext();\n await context.session?.delete?.(context.session.id);\n return new Response('Logged out', { status: 200 });\n }\n ```\n5. **Protect Routes**: In your Resource, use `allowRead()`, `allowUpdate()`, etc., to enforce authorization logic based on `this.getCurrentUser()`. For privileged actions, verify `user.role.permission.super_user`.\n\n## Examples\n\n### Sign In Implementation\n\n```typescript\nasync post(_target, data) {\n const context = this.getContext();\n try {\n await context.login(data.username, data.password);\n } catch {\n return new Response('Invalid credentials', { status: 403 });\n }\n return new Response('Logged in', { status: 200 });\n}\n```\n\n### Identify Current User\n\n```typescript\nasync get() {\n const user = this.getCurrentUser?.();\n if (!user) return new Response(null, { status: 401 });\n return { username: user.username, role: user.role };\n}\n```\n\n### Sign Out Implementation\n\n```typescript\nasync post() {\n const context = this.getContext();\n await context.session?.delete?.(context.session.id);\n return new Response('Logged out', { status: 200 });\n}\n```\n\n## Status code conventions used here\n\n- 200: Successful operation. For `GET /me`, a `200` with empty body means “not signed in”.\n- 400: Missing required fields (e.g., username/password on sign-in).\n- 401: No current session for an action that requires one (e.g., sign out when not signed in).\n- 403: Authenticated but not authorized (bad credentials on login attempt, or insufficient privileges).\n\n## Client considerations\n\n- Sessions are cookie-based; the server handles setting and reading the cookie via Harper. If you make cross-origin requests, ensure the appropriate `credentials` mode and CORS settings.\n- If developing locally, double-check the server config still has `authentication.authorizeLocal: false` to avoid accidental superuser bypass.\n\n## Token-based auth (JWT + refresh token) for non-browser clients\n\nCookie-backed sessions are great for browser flows. For CLI tools, mobile apps, or other non-browser clients, it’s often easier to use **explicit tokens**:\n\n- **JWT (`operation_token`)**: short-lived bearer token used to authorize API requests.\n- **Refresh token (`refresh_token`)**: longer-lived token used to mint a new JWT when it expires.\n\nThis project includes two Resource patterns for that flow:\n\n### Issuing tokens: `IssueTokens`\n\n**Description / use case:** Generate `{ refreshToken, jwt }` either:\n\n- with an existing Authorization token (either Basic Auth or a JWT) and you want to issue new tokens, or\n- from an explicit `{ username, password }` payload (useful for direct “login” from a CLI/mobile client).\n\n```javascript\nexport class IssueTokens extends Resource {\n\tstatic loadAsInstance = false;\n\n\tasync get(target) {\n\t\tconst { refresh_token: refreshToken, operation_token: jwt } =\n\t\t\tawait databases.system.hdb_user.operation(\n\t\t\t\t{ operation: 'create_authentication_tokens' },\n\t\t\t\tthis.getContext(),\n\t\t\t);\n\t\treturn { refreshToken, jwt };\n\t}\n\n\tasync post(target, data) {\n\t\tif (!data.username || !data.password) {\n\t\t\tthrow new Error('username and password are required');\n\t\t}\n\n\t\tconst { refresh_token: refreshToken, operation_token: jwt } =\n\t\t\tawait databases.system.hdb_user.operation({\n\t\t\t\toperation: 'create_authentication_tokens',\n\t\t\t\tusername: data.username,\n\t\t\t\tpassword: data.password,\n\t\t\t});\n\t\treturn { refreshToken, jwt };\n\t}\n}\n```\n\n**Recommended documentation notes to include:**\n\n- `GET` variant: intended for “I already have an Authorization token, give me new tokens”.\n- `POST` variant: intended for “I have credentials, give me tokens”.\n- Response shape:\n - `refreshToken`: store securely (long-lived).\n - `jwt`: attach to requests (short-lived).\n\n### Refreshing a JWT: `RefreshJWT`\n\n**Description / use case:** When the JWT expires, the client uses the refresh token to get a new JWT without re-supplying username/password.\n\n```javascript\nexport class RefreshJWT extends Resource {\n\tstatic loadAsInstance = false;\n\n\tasync post(target, data) {\n\t\tif (!data.refreshToken) {\n\t\t\tthrow new Error('refreshToken is required');\n\t\t}\n\n\t\tconst { operation_token: jwt } = await databases.system.hdb_user.operation({\n\t\t\toperation: 'refresh_operation_token',\n\t\t\trefresh_token: data.refreshToken,\n\t\t});\n\t\treturn { jwt };\n\t}\n}\n```\n\n**Recommended documentation notes to include:**\n\n- Requires `refreshToken` in the request body.\n- Returns a new `{ jwt }`.\n- If refresh fails (expired/revoked), client must re-authenticate (e.g., call `IssueTokens.post` again).\n\n### Suggested client flow (high-level)\n\n1. **Sign in (token flow)**\n - POST /IssueTokens/ with a body of `{ \"username\": \"your username\", \"password\": \"your password\" }` or GET /IssueTokens/ with an existing Authorization token.\n - Receive `{ jwt, refreshToken }` in the response\n2. **Call protected APIs**\n - Send the JWT with each request in the Authorization header (as your auth mechanism expects)\n3. **JWT expires**\n - POST /RefreshJWT/ with a body of `{ \"refreshToken\": \"your refresh token\" }`.\n - Receive `{ jwt }` in the response and continue\n\n## Quick checklist\n\n- [ ] Public endpoints explicitly `allowRead`/`allowCreate` as needed.\n- [ ] Sign-in uses `context.login` and handles 400/403 correctly.\n- [ ] Protected routes call `ensureSuperUser(this.getCurrentUser())` (or another role check) before doing work.\n- [ ] Sign-out verifies a session and deletes it.\n- [ ] `authentication.authorizeLocal` is `false` and `enableSessions` is `true` in Harper config.\n- [ ] If using tokens: `IssueTokens` issues `{ jwt, refreshToken }`, `RefreshJWT` refreshes `{ jwt }` with a `refreshToken`.\n",
34
34
  "creating-a-fabric-account-and-cluster": "---\nname: creating-a-fabric-account-and-cluster\ndescription: How to create a Harper Fabric account, organization, and cluster.\n---\n\n# Creating a Harper Fabric Account and Cluster\n\nFollow these steps to set up your Harper Fabric environment for deployment.\n\n## How It Works\n\n1. **Sign Up/In**: Go to [https://fabric.harper.fast/](https://fabric.harper.fast/) and sign up or sign in.\n2. **Create an Organization**: Create an organization (org) to manage your projects.\n3. **Create a Cluster**: Create a new cluster. This can be on the free tier, no credit card required.\n4. **Set Credentials**: During setup, set the cluster username and password to finish configuring it.\n5. **Get Application URL**: Navigate to the **Config** tab and copy the **Application URL**.\n6. **Configure Environment**: Update your `.env` file or GitHub Actions secrets with cluster-specific credentials.\n7. **Next Steps**: See the [deploying-to-harper-fabric](deploying-to-harper-fabric.md) rule for detailed instructions on deploying your application successfully.\n\n## Examples\n\n### Environment Configuration\n\n```bash\nCLI_TARGET_USERNAME='YOUR_CLUSTER_USERNAME'\nCLI_TARGET_PASSWORD='YOUR_CLUSTER_PASSWORD'\nCLI_TARGET='YOUR_CLUSTER_URL'\n```\n",
35
35
  "creating-harper-apps": "---\nname: creating-harper-apps\ndescription: How to initialize a new Harper application using the CLI.\n---\n\n# Creating Harper Applications\n\nThe fastest way to start a new Harper project is using the `create-harper` CLI tool. This command initializes a project with a standard folder structure, essential configuration files, and basic schema definitions.\n\n## When to Use\n\nUse this command when starting a new Harper application or adding a new Harper microservice to an existing architecture.\n\n## Commands\n\nInitialize a project using your preferred package manager:\n\n### NPM\n\n```bash\nnpm create harper@latest\n```\n\n### PNPM\n\n```bash\npnpm create harper@latest\n```\n\n### Bun\n\n```bash\nbun create harper@latest\n```\n\n## Options\n\nYou can specify the project name and template directly:\n\n```bash\nnpm create harper@latest my-app --template default\n```\n\n## Next Steps\n\n1. **Configure Environment**: Set up your `.env` file with local or cloud credentials.\n2. **Define Schema**: Modify `schema.graphql` to fit your application's data model.\n3. **Start Development**: Run `npm run dev` to start the local Harper instance.\n4. **Deploy**: Use `npm run deploy` to push your application to Harper Fabric.\n",
36
- "custom-resources": "---\nname: custom-resources\ndescription: How to define custom REST endpoints with JavaScript or TypeScript in Harper.\n---\n\n# Custom Resources\n\nInstructions for the agent to follow when creating custom resources in Harper.\n\n## When to Use\n\nUse this skill when the automatic CRUD operations provided by `@table @export` are insufficient, and you need custom logic, third-party API integration, or specialized data handling for your REST endpoints.\n\n## How It Works\n\n1. **Check if a Custom Resource is Necessary**: Verify if [Automatic APIs](./automatic-apis.md) or [Extending Tables](./extending-tables.md) can satisfy the requirement first.\n2. **Create the Resource File**: Create a `.ts` or `.js` file in the directory specified by `jsResource` in `config.yaml` (typically `resources/`).\n3. **Define the Resource Class**: Export a class extending `Resource` from `harperdb`:\n\n ```typescript\n import { type RequestTargetOrId, Resource } from 'harperdb';\n\n export class MyResource extends Resource {\n \tasync get(target?: RequestTargetOrId) {\n \t\treturn { message: 'Hello from custom GET!' };\n \t}\n }\n ```\n\n4. **Implement HTTP Methods**: Add methods like `get`, `post`, `put`, `patch`, or `delete` to handle corresponding requests. Note that paths are **case-sensitive** and match the class name.\n5. **Access Tables (Optional)**: Import and use the `tables` object to interact with your data:\n ```typescript\n import { tables } from 'harperdb';\n // ... inside a method\n const results = await tables.MyTable.list();\n ```\n6. **Configure Loading**: Ensure `config.yaml` points to your resource files (e.g., `jsResource: { files: 'resources/*.ts' }`).\n",
36
+ "custom-resources": "---\nname: custom-resources\ndescription: How to define custom REST endpoints with JavaScript or TypeScript in Harper.\n---\n\n# Custom Resources\n\nInstructions for the agent to follow when creating custom resources in Harper.\n\n## When to Use\n\nUse this skill when the automatic CRUD operations provided by `@table @export` are insufficient, and you need custom logic, third-party API integration, or specialized data handling for your REST endpoints.\n\n## How It Works\n\n1. **Check if a Custom Resource is Necessary**: Verify if [Automatic APIs](./automatic-apis.md) or [Extending Tables](./extending-tables.md) can satisfy the requirement first.\n2. **Create the Resource File**: Create a `.ts` or `.js` file in the directory specified by `jsResource` in `config.yaml` (typically `resources/`).\n3. **Define the Resource Class**: Export a class extending `Resource` from `harperdb`:\n\n ```typescript\n import { type RequestTargetOrId, Resource } from 'harperdb';\n\n export class MyResource extends Resource {\n \tasync get(target?: RequestTargetOrId) {\n \t\treturn { message: 'Hello from custom GET!' };\n \t}\n }\n ```\n\n4. **Implement HTTP Methods**: Add methods like `get`, `post`, `put`, `patch`, or `delete` to handle corresponding requests.\n5. **Route Nesting and Naming**: You can control the URL structure by how you export your resources:\n - **Direct Class Export**: `export class Foo extends Resource` creates endpoints at `/Foo/`. Class names are case-sensitive in the URL.\n - **Nested Objects**: `export const Bar = { Foo };` creates endpoints at `/Bar/Foo/`.\n - **Lowercase and Hyphens**: Use object keys to define custom paths: `export const bar = { 'foo-baz': Foo };` exposes endpoints at `/bar/foo-baz/`.\n6. **Access Tables (Optional)**: Import and use the `tables` object to interact with your data:\n ```typescript\n import { tables } from 'harperdb';\n // ... inside a method\n const results = await tables.MyTable.list();\n ```\n7. **Configure Loading**: Ensure `config.yaml` points to your resource files (e.g., `jsResource: { files: 'resources/*.ts' }`).\n",
37
37
  "defining-relationships": "---\nname: defining-relationships\ndescription: How to define and use relationships between tables in Harper using GraphQL.\n---\n\n# Defining Relationships\n\nInstructions for the agent to follow when defining relationships between Harper tables.\n\n## When to Use\n\nUse this skill when you need to link data across different tables, enabling automatic joins and efficient related-data fetching via REST APIs.\n\n## How It Works\n\n1. **Identify the Relationship Type**: Determine if it's one-to-one, many-to-one, or one-to-many.\n2. **Use the `@relationship` Directive**: Apply it to a field in your GraphQL schema.\n - **Many-to-One (Current table holds FK)**: Use `from`.\n ```graphql\n type Book @table @export {\n \tauthorId: ID\n \tauthor: Author @relationship(from: \"authorId\")\n }\n ```\n - **One-to-Many (Related table holds FK)**: Use `to` and an array type.\n ```graphql\n type Author @table @export {\n \tbooks: [Book] @relationship(to: \"authorId\")\n }\n ```\n3. **Query with Relationships**: Use dot syntax in REST API calls for filtering or the `select()` operator for including related data.\n - Example Filter: `GET /Book/?author.name=Harper`\n - Example Select: `GET /Author/?select(name,books(title))`\n",
38
38
  "deploying-to-harper-fabric": "---\nname: deploying-to-harper-fabric\ndescription: How to deploy a Harper application to the Harper Fabric cloud.\n---\n\n# Deploying to Harper Fabric\n\nInstructions for the agent to follow when deploying to Harper Fabric.\n\n## When to Use\n\nUse this skill when you are ready to move your Harper application from local development to a cloud-hosted environment.\n\n## How It Works\n\n1. **Sign up**: Follow the [creating-a-fabric-account-and-cluster](creating-a-fabric-account-and-cluster.md) rule to create a Harper Fabric account, organization, and cluster.\n2. **Configure Environment**: Add your cluster credentials and cluster application URL to `.env`:\n ```bash\n CLI_TARGET_USERNAME='YOUR_CLUSTER_USERNAME'\n CLI_TARGET_PASSWORD='YOUR_CLUSTER_PASSWORD'\n CLI_TARGET='YOUR_CLUSTER_URL'\n ```\n3. **Deploy From Local Environment**: Run `npm run deploy`.\n4. **Set up CI/CD**: Configure `.github/workflows/deploy.yaml` and set repository secrets for automated deployments.\n\n## Manual Setup for Existing Apps\n\nIf your application was not created with `npm create harper`, you'll need to manually configure the deployment scripts and CI/CD workflow.\n\n### 1. Update `package.json`\n\nAdd the following scripts and dependencies to your `package.json`:\n\n```json\n{\n\t\"scripts\": {\n\t\t\"deploy\": \"dotenv -- npm run deploy:component\",\n\t\t\"deploy:component\": \"harperdb deploy_component . restart=rolling replicated=true\"\n\t},\n\t\"devDependencies\": {\n\t\t\"dotenv-cli\": \"^11.0.0\",\n\t\t\"harperdb\": \"^4.7.20\"\n\t}\n}\n```\n\n#### Why split the scripts?\n\nThe `deploy` script is separated from `deploy:component` to ensure environment variables from your `.env` file are properly loaded and passed to the Harper CLI.\n\n- `deploy`: Uses `dotenv-cli` to load environment variables (like `CLI_TARGET`, `CLI_TARGET_USERNAME`, and `CLI_TARGET_PASSWORD`) before executing the next command.\n- `deploy:component`: The actual command that performs the deployment.\n\nBy using `dotenv -- npm run deploy:component`, the environment variables are correctly set in the shell session before `harperdb deploy_component` is called, allowing it to authenticate with your cluster.\n\n### 2. Configure GitHub Actions\n\nCreate a `.github/workflows/deploy.yaml` file with the following content:\n\n```yaml\nname: Deploy to Harper Fabric\non:\n workflow_dispatch:\n# push:\n# branches:\n# - main\nconcurrency:\n group: main\n cancel-in-progress: false\njobs:\n deploy:\n runs-on: ubuntu-latest\n steps:\n - name: Checkout code\n uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1\n with:\n fetch-depth: 0\n fetch-tags: true\n - name: Set up Node.js\n uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f # v6.1.0\n with:\n cache: 'npm'\n node-version-file: '.nvmrc'\n - name: Install dependencies\n run: npm ci\n - name: Run unit tests\n run: npm test\n - name: Run lint\n run: npm run lint\n - name: Deploy\n run: npm run deploy\n env:\n CLI_TARGET: ${{ secrets.CLI_TARGET }}\n CLI_TARGET_USERNAME: ${{ secrets.CLI_TARGET_USERNAME }}\n CLI_TARGET_PASSWORD: ${{ secrets.CLI_TARGET_PASSWORD }}\n```\n\nBe sure to set the following repository secrets in your GitHub repository's /settings/secrets/actions:\n\n- `CLI_TARGET`\n- `CLI_TARGET_USERNAME`\n- `CLI_TARGET_PASSWORD`\n",
39
39
  "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 'harperdb';\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",
40
40
  "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",
41
41
  "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",
42
- "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)`: `GET /Table/?limit(20, 10)`.\n6. **Sort Results**: Use `sort()` with `+` (asc) or `-` (desc): `GET /Table/?sort(-price,+name)`.\n7. **Query Relationships**: Use dot syntax for tables linked with `@relationship`: `GET /Book/?author.name=Harper`.\n",
42
+ "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",
43
43
  "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 'harperdb';\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",
44
44
  "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/harperdb/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/harperdb/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",
45
45
  "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/ && dotenv -- npm run deploy:component && rm -Rf deploy\",\n \"deploy:component\": \"(cd deploy && harper deploy_component . project=web restart=rolling replicated=true)\"\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",
@@ -250,11 +250,12 @@ How to use filters, operators, sorting, and pagination in REST requests.
250
250
 
251
251
  #### Query Parameters
252
252
 
253
- - `limit`: Number of records to return.
254
- - `offset`: Number of records to skip.
255
- - `sort`: Field to sort by.
256
- - `order`: `asc` or `desc`.
257
- - `filter`: JSON object for filtering.
253
+ - `limit(count)` or `limit(offset, count)`: Number of records to return and optional skip. Example: `?limit(10)`, `?limit(10, 20)`.
254
+ - `sort(+field1, -field2)`: Fields to sort by. Use `+` for ascending and `-` for descending. Example: `?sort(+name)`, `?sort(-price, +name)`.
255
+ - `select(field1, field2)`: Specific fields to return. Example: `?select(id, name)`.
256
+ - `filter`: Advanced filtering using comparison operators and logic.
257
+ - Operators: `gt`, `ge`, `lt`, `le`, `ne`. Example: `?price=gt=100`.
258
+ - Logic: `&` (AND), `|` (OR), `()` (grouping). Example: `?(category=electronics|category=books)&price=lt=500`.
258
259
 
259
260
  ### 2.3 Real-time Applications
260
261
 
@@ -297,8 +298,13 @@ How to define custom REST endpoints using JavaScript or TypeScript.
297
298
  #### How It Works
298
299
 
299
300
  1. **Create Resource File**: Define your logic in a JS or TS file.
300
- 2. **Export Handlers**: Export functions like `GET`, `POST`, etc.
301
- 3. **Registration**: Ensure the resource is correctly registered in your application configuration.
301
+ 2. **Define Resource Class**: Export a class extending `Resource` from `harperdb`.
302
+ 3. **Implement HTTP Methods**: Add methods like `get`, `post`, `put`, `patch`, or `delete` to handle corresponding requests.
303
+ 4. **Route Nesting and Naming**: You can control the URL structure by how you export your resources:
304
+ - **Direct Class Export**: `export class Foo extends Resource` creates endpoints at `/Foo/`. Class names are case-sensitive in the URL.
305
+ - **Nested Objects**: `export const Bar = { Foo };` creates endpoints at `/Bar/Foo/`.
306
+ - **Lowercase and Hyphens**: Use object keys to define custom paths: `export const bar = { 'foo-baz': Foo };` exposes endpoints at `/bar/foo-baz/`.
307
+ 5. **Registration**: Ensure the resource is correctly registered in your application configuration.
302
308
 
303
309
  ### 3.2 Extending Table Resources
304
310
 
@@ -27,11 +27,15 @@ Use this skill when the automatic CRUD operations provided by `@table @export` a
27
27
  }
28
28
  ```
29
29
 
30
- 4. **Implement HTTP Methods**: Add methods like `get`, `post`, `put`, `patch`, or `delete` to handle corresponding requests. Note that paths are **case-sensitive** and match the class name.
31
- 5. **Access Tables (Optional)**: Import and use the `tables` object to interact with your data:
30
+ 4. **Implement HTTP Methods**: Add methods like `get`, `post`, `put`, `patch`, or `delete` to handle corresponding requests.
31
+ 5. **Route Nesting and Naming**: You can control the URL structure by how you export your resources:
32
+ - **Direct Class Export**: `export class Foo extends Resource` creates endpoints at `/Foo/`. Class names are case-sensitive in the URL.
33
+ - **Nested Objects**: `export const Bar = { Foo };` creates endpoints at `/Bar/Foo/`.
34
+ - **Lowercase and Hyphens**: Use object keys to define custom paths: `export const bar = { 'foo-baz': Foo };` exposes endpoints at `/bar/foo-baz/`.
35
+ 6. **Access Tables (Optional)**: Import and use the `tables` object to interact with your data:
32
36
  ```typescript
33
37
  import { tables } from 'harperdb';
34
38
  // ... inside a method
35
39
  const results = await tables.MyTable.list();
36
40
  ```
37
- 6. **Configure Loading**: Ensure `config.yaml` points to your resource files (e.g., `jsResource: { files: 'resources/*.ts' }`).
41
+ 7. **Configure Loading**: Ensure `config.yaml` points to your resource files (e.g., `jsResource: { files: 'resources/*.ts' }`).
@@ -17,6 +17,11 @@ Use this skill when you need to perform advanced data retrieval (filtering, sort
17
17
  2. **Use Comparison Operators**: Append operators like `gt`, `ge`, `lt`, `le`, `ne` using FIQL-style syntax: `GET /Table/?price=gt=100`.
18
18
  3. **Apply Logic and Grouping**: Use `&` for AND, `|` for OR, and `()` for grouping: `GET /Table/?(rating=5|featured=true)&price=lt=50`.
19
19
  4. **Select Specific Fields**: Use `select()` to limit returned attributes: `GET /Table/?select(name,price)`.
20
- 5. **Paginate Results**: Use `limit(count)` or `limit(offset, count)`: `GET /Table/?limit(20, 10)`.
21
- 6. **Sort Results**: Use `sort()` with `+` (asc) or `-` (desc): `GET /Table/?sort(-price,+name)`.
20
+ 5. **Paginate Results**: Use `limit(count)` or `limit(offset, count)` to set the number of records to return and skip.
21
+ - Example (first 10): `GET /Table/?limit(10)`
22
+ - Example (skip 20, return 10): `GET /Table/?limit(20, 10)`
23
+ 6. **Sort Results**: Use `sort()` with `+` (asc) or `-` (desc) before the field name. Avoid `sort=field` format.
24
+ - Example (asc): `GET /Table/?sort(+name)`
25
+ - Example (desc): `GET /Table/?sort(-price)`
26
+ - Example (combined): `GET /Table/?sort(-price,+name)`
22
27
  7. **Query Relationships**: Use dot syntax for tables linked with `@relationship`: `GET /Book/?author.name=Harper`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@harperfast/skills",
3
- "version": "1.3.0",
3
+ "version": "1.3.2",
4
4
  "description": "Best practices for making awesome Harper apps with your favorite Agent",
5
5
  "keywords": [],
6
6
  "homepage": "https://github.com/harperfast",