@harperfast/skills 1.9.0 → 1.10.0
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,13 +40,13 @@ export const rules = {
|
|
|
40
40
|
"deploying-to-harper-fabric": "---\nname: deploying-to-harper-fabric\ndescription: How to deploy a Harper application to the Harper Fabric cloud.\nmetadata:\n mode: generate\n sources:\n - reference/v5/components/applications.md#Remote Management\n - >-\n fabric/cluster-creation-management.md#Connecting the Harper CLI to a\n Cluster\n sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819\n inputHash: ccdefbbf8f3b8657\n---\n\n# Deploying to Harper Fabric\n\nInstructions for the agent to follow when deploying a Harper application to the Harper Fabric cloud using the Harper CLI.\n\n## When to Use\n\nApply this rule when deploying a Harper application to a remote Harper instance or Harper Fabric cluster. This covers interactive deployments, CI/CD pipelines, and any scenario where the agent must push a local or remote package to a target environment.\n\n## How It Works\n\n1. **Authenticate with the remote target**: Run `harper login` once to store an authentication token. The CLI writes `HARPER_CLI_TARGET` to a local `.env` so subsequent commands do not need credentials repeated. Find the **Application URL** on the cluster's **Config → Overview** page (see [creating-a-fabric-account-and-cluster.md](creating-a-fabric-account-and-cluster.md)).\n\n ```bash\n harper login <Application URL>\n # Provide cluster username and password when prompted\n ```\n\n2. **Deploy the application**: Run `harper deploy` with the required parameters. After logging in, no credentials are needed inline.\n\n ```bash\n harper deploy \\\n project=<name> \\\n package=<package> \\\n target=<remote> \\\n restart=true \\\n replicated=true\n ```\n\n3. **Choose a package source**: Set the `package` parameter to any valid npm dependency value, or omit it to package and deploy the current local directory.\n\n | Value | Effect |\n | ---------------------------------------------------- | ------------------------------------------------ |\n | _(omitted)_ | Packages and deploys the current local directory |\n | `\"@harperdb/status-check\"` | npm package |\n | `\"HarperDB/status-check\"` | GitHub repo (short form) |\n | `\"https://github.com/HarperDB/status-check\"` | GitHub repo (full URL) |\n | `\"git+ssh://git@github.com:HarperDB/secret-app.git\"` | Private repo via SSH |\n | `\"https://example.com/application.tar.gz\"` | Remote tarball |\n\n For git tags, use the `semver` directive for reliable versioning:\n\n ```\n HarperDB/application-template#semver:v1.0.0\n ```\n\n4. **Authenticate for CI/CD pipelines**: Use environment variables instead of interactive login. Set credentials before running `harper deploy`.\n\n ```bash\n export HARPER_CLI_USERNAME=<username>\n export HARPER_CLI_PASSWORD=<password>\n harper deploy \\\n project=<name> \\\n package=<package> \\\n target=<remote> \\\n restart=true \\\n replicated=true\n ```\n\n5. **Register SSH keys for private repos**: Before deploying from an SSH-based private repository, use the Add SSH Key operation to register the key with the remote instance.\n\n## Examples\n\n**Interactive login then deploy (recommended):**\n\n```bash\n# Log in once\nharper login <remote>\n# Provide your username and password when prompted\n\n# Subsequently deploy without credentials\nharper deploy \\\n project=<name> \\\n package=<package> \\\n target=<remote> \\\n restart=true \\\n replicated=true\n```\n\n**Deploy with inline credentials (not recommended for production):**\n\n```bash\nharper deploy \\\n project=<name> \\\n package=<package> \\\n username=<username> \\\n password=<password> \\\n target=<remote> \\\n restart=true \\\n replicated=true\n```\n\n**Deploy a specific GitHub release by semver tag:**\n\n```bash\nharper deploy \\\n project=my-app \\\n package=\"HarperDB/application-template#semver:v1.0.0\" \\\n target=<remote> \\\n restart=true \\\n replicated=true\n```\n\n## Notes\n\n- Always prefer `harper login` for interactive use and environment variables (`HARPER_CLI_USERNAME`, `HARPER_CLI_PASSWORD`) for CI/CD. Avoid inline `username`/`password` parameters in production.\n- Omitting `package` causes the CLI to package the current local directory. Specifying a local file path creates a symlink, so changes are picked up between restarts without redeploying.\n- Harper generates a `package.json` from component configurations and resolves dependencies using a form of `npm install`.\n- For SSH-based private repos, register keys with the Add SSH Key operation before deploying.\n",
|
|
41
41
|
"extending-tables": "---\nname: extending-tables\ndescription: How to add custom logic to automatically generated table resources in Harper.\nmetadata:\n mode: synthesized\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",
|
|
42
42
|
"handling-binary-data": "---\nname: handling-binary-data\ndescription: How to store and serve binary data like images or audio in Harper.\nmetadata:\n mode: synthesized\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",
|
|
43
|
-
"load-env": "---\nname: load-env\ndescription: >-\n How to load environment variables from .env files into a Harper application\n using the loadEnv plugin.\nmetadata:\n mode: generate\n sources:\n - reference/v5/environment-variables/overview.md\n sourceCommit:
|
|
43
|
+
"load-env": "---\nname: load-env\ndescription: >-\n How to load environment variables from .env files into a Harper application\n using the loadEnv plugin.\nmetadata:\n mode: generate\n sources:\n - reference/v5/environment-variables/overview.md\n sourceCommit: 42231db17c025a4a455e3d91875fad4084a01cb5\n inputHash: fe610fc245226357\n---\n\n# Load Environment Variables with loadEnv\n\nInstructions for the agent to follow when loading environment variables from `.env` files into a Harper application using the `loadEnv` plugin.\n\n## When to Use\n\nApply this rule when a Harper application needs to load secrets or configuration values from `.env` files into `process.env` at startup. Use it whenever hardcoding values must be avoided and environment-specific configuration must be supplied to Harper components.\n\n## How It Works\n\n1. **Declare `loadEnv` in `config.yaml`**: Add `loadEnv` as a top-level key. It is built into Harper and requires no installation.\n\n ```yaml\n loadEnv:\n files: '.env'\n ```\n\n2. **Place `loadEnv` first**: Always list `loadEnv` before any other components in `config.yaml` so that environment variables are available on `process.env` before dependent components start.\n\n ```yaml\n # config.yaml — loadEnv must come first\n loadEnv:\n files: '.env'\n\n rest: true\n\n myApp:\n files: './src/*.js'\n ```\n\n3. **Configure the `files` option**: Provide one or more paths or glob patterns pointing to the env files to load. This option is required.\n\n4. **Set `override` if needed**: By default, existing environment variables take precedence over values in `.env` files. Set `override: true` to reverse this and have loaded values win.\n\n ```yaml\n loadEnv:\n files: '.env'\n override: true\n ```\n\n5. **Load multiple files when required**: Supply a list of files or a glob pattern. Files are loaded in the order specified.\n ```yaml\n loadEnv:\n files:\n - '.env'\n - '.env.local'\n ```\n or\n ```yaml\n loadEnv:\n files: 'env-vars/*'\n ```\n\n### Configuration Options\n\n| Option | Type | Required | Description |\n| ---------- | -------------------- | -------- | -------------------------------------------------------------------------------------- |\n| `files` | `string \\| string[]` | **Yes** | Path(s) or glob pattern(s) to the env file(s) to load. |\n| `override` | `boolean` | No | If `true`, loaded values override existing environment variables. Defaults to `false`. |\n\n## Examples\n\n**Minimal setup — single `.env` file:**\n\n```yaml\nloadEnv:\n files: '.env'\n```\n\n**Full `config.yaml` with load order, multiple files, and override:**\n\n```yaml\n# config.yaml — loadEnv must come first\nloadEnv:\n files:\n - '.env'\n - '.env.local'\n override: true\n\nrest: true\n\nmyApp:\n files: './src/*.js'\n```\n\n**Glob pattern:**\n\n```yaml\nloadEnv:\n files: 'env-vars/*'\n```\n\n## Notes\n\n- `loadEnv` is built into Harper — do not install it separately; only declare it in `config.yaml`.\n- Because Harper is a single-process application, variables loaded onto `process.env` are shared across all components.\n- Without `override: true`, variables already set in the shell or container environment will not be overwritten by values in `.env` files.\n- `files` is the only required option; omitting it will produce an invalid configuration.\n",
|
|
44
44
|
"logging": "---\nname: logging\ndescription: >-\n Best practices for logging in Harper, including console capture, the granular\n logger interface, and programmatic log retrieval.\nmetadata:\n mode: generate\n sources:\n - reference/v5/logging/overview.md\n - reference/v5/logging/api.md\n sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819\n inputHash: 46cd384598304e3b\n---\n\n# Harper Logging\n\nInstructions for the agent to follow when implementing logging in Harper applications, including direct logger usage, tagged loggers, and console capture behavior.\n\n## When to Use\n\nApply this rule when writing any JavaScript component, plugin, or resource that needs to emit structured log entries, filter logs by component, or capture existing `console.log` output into Harper's log system. Use it whenever you need to understand log levels, log entry format, or the `logger` global API.\n\n## How It Works\n\n1. **Use the `logger` global directly** — `logger` is available in all JavaScript components without any imports. Call the method matching the desired severity level:\n\n ```javascript\n logger.trace('detailed trace message');\n logger.debug('debug info', { someContext: 'value' });\n logger.info('informational message');\n logger.warn('potential issue');\n logger.error('error occurred', error);\n logger.fatal('fatal error');\n logger.notify('server is ready');\n ```\n\n Only entries at or above the configured `logging.level` (or `logging.external.level`) are written to `hdb.log`.\n\n2. **Create a tagged logger with `withTag(`** — Call `logger.withTag(tag)` once per module or class to get a `TaggedLogger` scoped to that tag. This prefixes every log entry with the tag, making log output filterable by component.\n\n ```javascript\n const log = logger.withTag('my-resource');\n ```\n\n Because `TaggedLogger` methods for disabled levels are `null`, always use optional chaining (`?.`) when calling them:\n\n ```javascript\n log.debug?.('Fetching record', { id });\n log.warn?.('Record not found', { id });\n log.error?.('Failed to update record', err);\n ```\n\n `TaggedLogger` does not have a `withTag()` method.\n\n3. **Understand the interface contracts** — `MainLogger` always has all methods defined:\n\n ```typescript\n interface MainLogger {\n \ttrace(...messages: any[]): void;\n \tdebug(...messages: any[]): void;\n \tinfo(...messages: any[]): void;\n \twarn(...messages: any[]): void;\n \terror(...messages: any[]): void;\n \tfatal(...messages: any[]): void;\n \tnotify(...messages: any[]): void;\n \twithTag(tag: string): TaggedLogger;\n }\n ```\n\n `TaggedLogger` methods may be `null`:\n\n ```typescript\n interface TaggedLogger {\n \ttrace: ((...messages: any[]) => void) | null;\n \tdebug: ((...messages: any[]) => void) | null;\n \tinfo: ((...messages: any[]) => void) | null;\n \twarn: ((...messages: any[]) => void) | null;\n \terror: ((...messages: any[]) => void) | null;\n \tfatal: ((...messages: any[]) => void) | null;\n \tnotify: ((...messages: any[]) => void) | null;\n }\n ```\n\n4. **Know the log levels** — From least to most severe:\n\n | Level | Description |\n | -------- | -------------------------------------------------------------------- |\n | `trace` | Highly detailed internal execution tracing. |\n | `debug` | Diagnostic information useful during development. |\n | `info` | General operational events. |\n | `warn` | Potential issues that don't prevent normal operation. |\n | `error` | Errors that affect specific operations. |\n | `fatal` | Critical errors causing process termination. |\n | `notify` | Important operational milestones. Always logged regardless of level. |\n\n The default log level is `warn`. Setting a level includes that level and all more-severe levels.\n\n5. **Enable console capture when porting existing code** — When `logging.console: true` is set, writes via `console.log`, `console.warn`, `console.error`, etc. are appended verbatim to `hdb.log`. Captured lines do **not** pass through `logger`'s level filter. Prefer `logger` directly in production code so that level filtering and tagging apply. Console capture is intended as a convenience for porting existing code and for debugging.\n\n6. **Know where logs are written** — All standard log output goes to `<ROOTPATH>/log/hdb.log` (default: `~/hdb/log/hdb.log`). To also log to `stdout`/`stderr`, set `logging.stdStreams: true`.\n\n## Examples\n\n### Basic logging in a resource\n\n```javascript\nexport class MyResource extends Resource {\n\tasync get(id) {\n\t\tlogger.debug('Fetching record', { id });\n\t\tconst record = await super.get(id);\n\t\tif (!record) {\n\t\t\tlogger.warn('Record not found', { id });\n\t\t}\n\t\treturn record;\n\t}\n\n\tasync put(record) {\n\t\tlogger.info('Updating record', { id: record.id });\n\t\ttry {\n\t\t\treturn await super.put(record);\n\t\t} catch (err) {\n\t\t\tlogger.error('Failed to update record', err);\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n```\n\n### Tagged logging with `withTag()`\n\n```javascript\nconst log = logger.withTag('my-resource');\n\nexport class MyResource extends Resource {\n\tasync get(id) {\n\t\tlog.debug?.('Fetching record', { id });\n\t\tconst record = await super.get(id);\n\t\tif (!record) {\n\t\t\tlog.warn?.('Record not found', { id });\n\t\t}\n\t\treturn record;\n\t}\n\n\tasync put(record) {\n\t\tlog.info?.('Updating record', { id: record.id });\n\t\ttry {\n\t\t\treturn await super.put(record);\n\t\t} catch (err) {\n\t\t\tlog.error?.('Failed to update record', err);\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n```\n\nTagged entries appear in `hdb.log` with the tag in the header:\n\n```\n2023-03-09T14:25:05.269Z [info] [my-resource]: Updating record\n```\n\n## Notes\n\n- All log output is written to `<ROOTPATH>/log/hdb.log`. The `logger` global writes to this file at the configured `logging.external` level.\n- Log entry format for `logger`: `<timestamp> [<level>] [<thread>/<id>]: <message>`\n- Log entry format for `TaggedLogger`: `<timestamp> [<level>] [<tag>]: <message>`\n- `console.log` output is only forwarded to `hdb.log` when `logging.console: true` is explicitly set; it is not forwarded by default.\n- When logging to standard streams, run Harper in the foreground (`harper`, not `harper start`).\n- `TaggedLogger` is bound to the configured log level at creation time — always use `?.` on its methods.\n",
|
|
45
45
|
"programmatic-table-requests": "---\nname: programmatic-table-requests\ndescription: How to interact with Harper tables programmatically using the `tables` object.\nmetadata:\n mode: synthesized\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",
|
|
46
46
|
"querying-rest-apis": "---\nname: querying-rest-apis\ndescription: 'How to use query parameters to filter, sort, and paginate Harper REST APIs.'\nmetadata:\n mode: generate\n sources:\n - reference/v5/rest/querying.md\n sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819\n inputHash: 9f8c981a629ef606\n---\n\n# Querying REST APIs\n\nInstructions for the agent to filter, sort, select, and paginate Harper REST API collections using URL query parameters.\n\n## When to Use\n\nApply this rule when building or modifying code that queries Harper REST endpoints with filtering, sorting, field selection, or pagination. Use it whenever constructing URLs against collection paths exposed by Harper's automatic REST interface (see [automatic-apis.md](automatic-apis.md)).\n\n## How It Works\n\n1. **Filter by attribute**: Add query parameters matching attribute names and values. The queried attribute must be indexed.\n\n ```\n GET /Product/?category=software\n GET /Product/?category=software&inStock=true\n ```\n\n2. **Apply comparison operators (FIQL syntax)**: Use FIQL operators directly in query parameter values.\n\n | Operator | Meaning |\n | ------------ | -------------------------------------- |\n | `==` | Equal |\n | `=lt=` | Less than |\n | `=le=` | Less than or equal |\n | `=gt=` | Greater than |\n | `=ge=` | Greater than or equal |\n | `=ne=`, `!=` | Not equal |\n | `=ct=` | Contains (strings) |\n | `=sw=` | Starts with (strings) |\n | `=ew=` | Ends with (strings) |\n | `=`, `===` | Strict equality (no type conversion) |\n | `!==` | Strict inequality (no type conversion) |\n\n ```\n GET /Product/?price=gt=100\n GET /Product/?price=le=20\n GET /Product/?name==Keyboard*\n GET /Product/?category=software&price=gt=100&price=lt=200\n ```\n\n For date fields, URL-encode colons as `%3A`:\n\n ```\n GET /Product/?listDate=gt=2017-03-08T09%3A30%3A00.000Z\n ```\n\n3. **Chain conditions for range queries**: Omit the attribute name on the second condition to apply it to the same attribute. Only `gt`/`ge` combined with `lt`/`le` is supported.\n\n ```\n GET /Product/?price=gt=100<=200\n ```\n\n4. **Combine conditions with OR logic**: Use `|` instead of `&`.\n\n ```\n GET /Product/?rating=5|featured=true\n ```\n\n5. **Group conditions**: Use parentheses or square brackets to control order of operations. Prefer square brackets when constructing queries from user input, since standard URI encoding safely encodes `[` and `]`.\n\n ```\n GET /Product/?rating=5|(price=gt=100&price=lt=200)\n GET /Product/?rating=5&[tag=fast|tag=scalable|tag=efficient]\n ```\n\n Construct grouped queries from JavaScript:\n\n ```javascript\n let url = `/Product/?rating=5&[${tags.map(encodeURIComponent).join('|')}]`;\n ```\n\n6. **Select specific properties with `select(`**: Use `select()` to control which fields are returned.\n\n | Syntax | Returns |\n | -------------------------------------- | ------------------------------------------- |\n | `?select(property)` | Values of a single property directly |\n | `?select(property1,property2)` | Objects with only the specified properties |\n | `?select([property1,property2])` | Arrays of property values |\n | `?select(property1,)` | Objects with a single specified property |\n | `?select(property{subProp1,subProp2})` | Nested objects with specific sub-properties |\n\n ```\n GET /Product/?category=software&select(name)\n GET /Product/?brand.name=Microsoft&select(name,brand{name})\n ```\n\n7. **Limit results with `limit(`**: Use `limit(end)` or `limit(start,end)` to paginate.\n\n ```\n GET /Product/?rating=gt=3&inStock=true&select(rating,name)&limit(20)\n GET /Product/?rating=gt=3&limit(10,30)\n ```\n\n8. **Sort results with `sort(`**: Use `sort(property)` or `sort(+property,-property,...)`. Prefix `+` or no prefix = ascending; `-` = descending.\n\n ```\n GET /Product/?rating=gt=3&sort(+name)\n GET /Product/?sort(+rating,-price)\n ```\n\n9. **Query across relationships**: Use dot-syntax to filter by related table attributes. Relationships must be defined in the schema using `@relation`.\n\n ```\n GET /Product/?brand.name=Microsoft\n GET /Brand/?products.name=Keyboard\n ```\n\n Use `select()` to include relationship attributes in the response (they are not included by default):\n\n ```\n GET /Product/?brand.name=Microsoft&select(name,brand{name})\n ```\n\n10. **Access a specific property by URL**: Append the property name with dot syntax to the record ID. Only works for properties declared in the schema.\n ```\n GET /MyTable/123.propertyName\n ```\n\n## Examples\n\n**Range filter with select and limit:**\n\n```\nGET /Product/?category=software&price=gt=100&price=lt=200&select(name,price)&limit(20)\n```\n\n**Sort descending with multiple fields:**\n\n```\nGET /Product/?sort(+rating,-price)\n```\n\n**OR logic with grouping:**\n\n```\nGET /Product/?price=lt=100|[rating=5&[tag=fast|tag=scalable|tag=efficient]&inStock=true]\n```\n\n**Relationship join with nested select:**\n\n```\nGET /Product/?brand.name=Microsoft&select(name,brand{name,id})\n```\n\n**Schema defining a relationship for join queries:**\n\n```graphql\ntype Product @table @export {\n\tid: Long @primaryKey\n\tname: String\n\tbrandId: Long @indexed\n\tbrand: Brand @relation(from: \"brandId\")\n}\ntype Brand @table @export {\n\tid: Long @primaryKey\n\tname: String\n\tproducts: [Product] @relation(to: \"brandId\")\n}\n```\n\n**Many-to-many relationship query:**\n\n```graphql\ntype Product @table @export {\n\tid: Long @primaryKey\n\tname: String\n\tresellerIds: [Long] @indexed\n\tresellers: [Reseller] @relation(from: \"resellerId\")\n}\n```\n\n```\nGET /Product/?resellers.name=Cool Shop&select(id,name,resellers{name,id})\n```\n\n**Type conversion with explicit prefix:**\n\n```\nGET /Product/?price==number:123\nGET /Product/?active==boolean:true\nGET /Product/?listDate==date:2024-01-05T20%3A07%3A27.955Z\n```\n\n## Notes\n\n- Only indexed attributes can be used as the primary filter; additional unindexed attributes can be combined with `&` once at least one indexed attribute is present.\n- For null value queries, use `?attribute=null`. Indexes must have been created with null indexing support; existing indexes must be removed and re-added to support null queries.\n- FIQL comparators (`==`, `!=`, `=gt=`, etc.) apply automatic type conversion based on value syntax or schema-declared type. Strict operators (`=`, `===`, `!==`) skip automatic type conversion.\n- Filtering by a related attribute produces INNER JOIN behavior (only records with a matching related record are returned). Using `select()` on a relationship without a filter produces LEFT JOIN behavior.\n- The array order of foreign key values in many-to-many relationships is preserved when resolving the relationship.\n- See [automatic-apis.md](automatic-apis.md) for how Harper tables are automatically exposed as REST endpoints.\n",
|
|
47
47
|
"real-time-apps": "---\nname: real-time-apps\ndescription: How to build real-time features in Harper using WebSockets and Pub/Sub.\nmetadata:\n mode: generate\n sources:\n - reference/v5/rest/websockets.md\n sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819\n inputHash: a8afd4d3a52f77ba\n---\n\n# Real-Time Apps with WebSockets and Pub/Sub\n\nInstructions for the agent to follow when building real-time features in Harper using WebSockets and Pub/Sub.\n\n## When to Use\n\nApply this rule when implementing any feature that requires real-time bidirectional communication, live data streaming, or push-based updates in a Harper application. This includes chat, live dashboards, sensor feeds, and any scenario where clients must receive resource changes as they happen.\n\n## How It Works\n\n1. **Enable WebSocket support**: WebSocket support is enabled automatically when the `rest` plugin is enabled. To explicitly disable it, set the following in your config:\n\n ```yaml\n rest:\n webSocket: false\n ```\n\n2. **Connect a client to a resource**: A WebSocket connection to a resource URL automatically subscribes to that resource. When the record changes or a message is published to it, the connection receives the update.\n\n ```javascript\n let ws = new WebSocket('wss://server/my-resource/341');\n ws.onmessage = (event) => {\n \tlet data = JSON.parse(event.data);\n };\n ```\n\n `new WebSocket('wss://server/my-resource/341')` accesses the resource defined for `my-resource` with record id `341` and subscribes to it.\n\n3. **Implement a custom `connect()` handler**: Override the `connect(incomingMessages)` method on a resource class to control WebSocket behavior. The method must return an async iterable (or generator) that produces messages to send to the client. See [automatic-apis.md](automatic-apis.md) for more on defining resource classes.\n\n4. **Use the default `connect()` for event-style access**: Call `super.connect()` to get a streaming iterable that provides:\n - A `send(message)` method for pushing outgoing messages\n - A `close` event for cleanup on disconnect\n\n5. **Handle message ordering in distributed environments**: Harper delivers messages to local subscribers immediately without inter-node coordination delay.\n\n | Message Type | Behavior |\n | -------------------------------------------------------- | ----------------------------------------------------------------------- |\n | Non-retained (no `retain` flag) | Every message delivered in order received; suitable for chat |\n | Retained (published with `retain`, or PUT/updated in DB) | Only the latest-timestamp message is kept; suitable for sensor readings |\n\n6. **Use MQTT over WebSockets** when needed by setting the sub-protocol header:\n ```\n Sec-WebSocket-Protocol: mqtt\n ```\n\n## Examples\n\n**Simple echo server** — override `connect(incomingMessages)` to yield each incoming message back to the client:\n\n```javascript\nexport class Echo extends Resource {\n\tasync *connect(incomingMessages) {\n\t\tfor await (let message of incomingMessages) {\n\t\t\tyield message; // echo each message back\n\t\t}\n\t}\n}\n```\n\n**Custom connect with timer and event-style access** — use `super.connect()` to get the outgoing stream, push periodic messages, echo incoming messages, and clean up on disconnect:\n\n```javascript\nexport class Example extends Resource {\n\tconnect(incomingMessages) {\n\t\tlet outgoingMessages = super.connect();\n\n\t\tlet timer = setInterval(() => {\n\t\t\toutgoingMessages.send({ greeting: 'hi again!' });\n\t\t}, 1000);\n\n\t\tincomingMessages.on('data', (message) => {\n\t\t\toutgoingMessages.send(message); // echo incoming messages\n\t\t});\n\n\t\toutgoingMessages.on('close', () => {\n\t\t\tclearInterval(timer);\n\t\t});\n\n\t\treturn outgoingMessages;\n\t}\n}\n```\n\n## Notes\n\n- WebSocket connections target a resource URL path. By default, connecting to a resource subscribes to changes for that resource.\n- The `connect(incomingMessages)` method **must** return an async iterable or generator; returning a plain value will not work.\n- `super.connect()` returns a streaming iterable with `send(message)` and a `close` event — use this when you need to push messages outside of the incoming message loop.\n- For one-way real-time streaming without bidirectional communication, consider Server-Sent Events instead.\n- For full pub/sub capabilities, Harper also supports MQTT; set `Sec-WebSocket-Protocol: mqtt` to use MQTT over WebSockets.\n",
|
|
48
48
|
"schema-design-tooling": "---\nname: schema-design-tooling\ndescription: >-\n Best practices for Harper schema design, including core directives and GraphQL\n tooling configuration.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/schema.md#Overview\n - reference/v5/database/schema.md#Type Directives\n - reference/v5/database/schema.md#Field Directives\n sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819\n inputHash: 4faa3baed7cfa854\n---\n\n# Schema Design and Tooling\n\nInstructions for the agent to follow when designing Harper schemas, applying core directives, and configuring GraphQL tooling.\n\n## When to Use\n\nApply this rule when creating or modifying Harper schema files, configuring `graphqlSchema` in `config.yaml`, or deciding which directives to apply to tables and fields. Use it any time a component needs tables, indexes, primary keys, or exported endpoints defined.\n\n## How It Works\n\n1. **Create a GraphQL schema file** with Harper-specific directives. Name it (e.g., `schema.graphql`) and place it in your component directory.\n\n ```graphql\n type Dog @table {\n \tid: Long @primaryKey\n \tname: String\n \tbreed: String\n \tage: Int\n }\n\n type Breed @table {\n \tid: Long @primaryKey\n \tname: String @indexed\n }\n ```\n\n2. **Register the schema in `config.yaml`** using the `graphqlSchema` plugin key:\n\n ```yaml\n graphqlSchema:\n files: 'schema.graphql'\n ```\n\n Both plugins and applications can specify schemas this way.\n\n3. **Mark every table type with `@table`**. The type name becomes the table name by default. Use optional arguments to override behavior:\n\n | Argument | Type | Default | Description |\n | -------------- | --------- | ----------------------------- | ------------------------------------------------------------- |\n | `table` | `String` | type name | Override the table name |\n | `database` | `String` | `\"data\"` | Database to place the table in |\n | `expiration` | `Int` | — | Seconds until a record goes stale |\n | `eviction` | `Int` | `0` | Additional seconds after `expiration` before physical removal |\n | `scanInterval` | `Int` | `(expiration + eviction) / 4` | Seconds between eviction scans |\n | `replicate` | `Boolean` | `true` | Enable replication of this table |\n\n4. **Designate a primary key on every table** using `@primaryKey`. Primary keys must be unique; duplicate-key inserts are rejected. If no key is provided on insert, Harper auto-generates one:\n - `String` or `ID` → UUID string\n - `Int`, `Long`, or `Any` → auto-incrementing integer\n\n Prefer `Long` or `Any` for auto-generated numeric keys; `Int` is 32-bit and may be insufficient for large tables.\n\n5. **Index fields that need fast querying** with `@indexed`. This is required for filtering by that attribute in REST queries, SQL, or NoSQL operations. If the field value is an array, each element is individually indexed.\n\n ```graphql\n type Product @table {\n \tid: Long @primaryKey\n \tcategory: String @indexed\n \tprice: Float @indexed\n }\n ```\n\n6. **Expose a table as an external resource endpoint** with `@export`. This makes the table accessible via REST, MQTT, and other interfaces. The optional `name` parameter sets the URL path segment; without it, the type name is used.\n\n ```graphql\n type MyTable @table @export(name: \"my-table\") {\n \tid: Long @primaryKey\n }\n ```\n\n7. **Restrict extra properties** with `@sealed` when records must not include attributes beyond those declared. By default, Harper allows additional properties.\n\n ```graphql\n type StrictRecord @table @sealed {\n \tid: Long @primaryKey\n \tname: String\n }\n ```\n\n8. **Configure expiration, eviction, and scan behavior** together when building caching tables. These three arguments control the full record lifecycle:\n - `expiration` — record becomes stale; next request triggers a source fetch\n - `eviction` — additional time after `expiration` before physical removal\n - `scanInterval` — how often Harper scans for records to evict; clock-aligned, not startup-aligned\n\n## Examples\n\n**Caching table with tuned expiration:**\n\n```graphql\n# Expire after 5 minutes, evict after 1 hour, scan every 10 minutes\ntype WeatherCache @table(expiration: 300, eviction: 3300, scanInterval: 600) {\n\tid: ID @primaryKey\n\ttemperature: Float\n}\n```\n\n**Table in a named database with expiration and an indexed field:**\n\n```graphql\ntype Event @table(database: \"analytics\", expiration: 86400) {\n\tid: Long @primaryKey\n\tname: String @indexed\n}\n```\n\n**Session cache with auto-expiry:**\n\n```graphql\ntype Session @table(expiration: 3600) {\n\tid: Long @primaryKey\n\tuserId: String\n}\n```\n\n**Table with audit timestamps:**\n\n```graphql\ntype Order @table @export(name: \"orders\") {\n\tid: Long @primaryKey\n\tcreatedAt: Long @createdTime\n\tupdatedAt: Long @updatedTime\n\tstatus: String @indexed\n}\n```\n\n**Overriding the table name and disabling replication:**\n\n```graphql\ntype Product @table(table: \"products\") {\n\tid: Long @primaryKey\n\tname: String\n}\n\ntype LocalRecord @table(replicate: false) {\n\tid: Long @primaryKey\n\tvalue: String\n}\n```\n\n## Notes\n\n- Use unique `database` names in plugins and applications to avoid table naming collisions, since all tables default to the `\"data\"` database.\n- Eviction removes non-indexed record data but does **not** remove a record from its secondary indexes. Indexes remain functional for evicted records; Harper fetches the full record from the source on demand when a query matches an evicted record.\n- `scanInterval` is clock-aligned to the server's local timezone. The server's startup time does not affect when eviction runs.\n- If replication is disabled on a table and later re-enabled, it will not catch up on writes made while replication was disabled.\n- Null values are indexed by `@indexed` fields, enabling queries such as `GET /Product/?category=null`.\n",
|
|
49
|
-
"serving-web-content": "---\nname: serving-web-content\ndescription: How to serve static files and integrated Vite/React applications in Harper.\nmetadata:\n mode: synthesized\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\
|
|
49
|
+
"serving-web-content": "---\nname: serving-web-content\ndescription: How to serve static files and integrated Vite/React applications in Harper.\nmetadata:\n mode: synthesized\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/Vue app) directly from your Harper instance — either plain static files or an integrated Vite app with hot module replacement (HMR) in development and a real production build when deployed.\n\n## How It Works\n\nThere are two building blocks. Harper's built-in `static` plugin **serves** files; the `@harperfast/vite` plugin **builds** (and, for SSR, **renders**) a Vite app. For a Vite app they work **together** — the plugin builds into a directory and `static` serves that same directory.\n\n### Option A: Static plugin only (simple, pre-built assets)\n\nFor a plain static site or already-built assets, use `static` on its own:\n\n```yaml\nstatic:\n files: 'web/*'\n```\n\n- Place files in a `web/` folder in the project root; they are served from the root URL (e.g. `http://localhost:9926/index.html`).\n- Static files are matched first; if none matches, Harper falls through to your resource and table APIs.\n\n### Option B: Vite plugin + static plugin (integrated Vite app)\n\n> **Renamed in v1:** the plugin was previously `@harperfast/vite-plugin`. From `1.0.0` on it is **`@harperfast/vite`** (same key and `package`). It now pairs with the `static` plugin instead of building into `web/` itself.\n\n`@harperfast/vite` **builds** your app — in `harper dev` it runs Vite in middleware mode with HMR; in `harper run` it runs `vite build` and rebuilds when watched files change (and renders HTML for SSR). The `static` plugin **serves** the built output. Point both at the same directory (`output`, default `dist`) — that shared directory is the only contract between them.\n\n**SPA `config.yaml`** — list the plugin first so its dev server wins in `harper dev`; `notFound` + `fallthrough: false` makes client-side routing work:\n\n```yaml\n'@harperfast/vite':\n package: '@harperfast/vite'\n files: 'src/**/*'\n output: 'dist'\n\nstatic:\n files: 'dist/**'\n notFound:\n file: 'index.html'\n statusCode: 200\n fallthrough: false\n```\n\n**SSR `config.yaml`** — add an `ssr` entry so the plugin renders `index.html`, and set `index: false` on `static` so it serves assets only:\n\n```yaml\n'@harperfast/vite':\n package: '@harperfast/vite'\n files: 'src/**/*'\n output: 'dist'\n ssr: 'src/entry-server.tsx'\n\nstatic:\n files: 'dist/**'\n index: false\n```\n\n- Install dependencies: `npm install --save-dev vite @harperfast/vite @vitejs/plugin-react` (swap in your framework's Vite plugin, e.g. `@vitejs/plugin-vue`).\n- Then `harper dev .` runs the app with HMR and `harper run .` runs the production build. Vite does _not_ need to be executed separately.\n\n## Deploying to Production\n\nBecause `@harperfast/vite` builds on the node and `static` serves the output, deploy the component as-is — no manual build-and-move step is needed:\n\n```json\n{\n\t\"scripts\": {\n\t\t\"dev\": \"harper dev .\",\n\t\t\"start\": \"harper run .\",\n\t\t\"deploy\": \"harper deploy_component . restart=true replicated=true\"\n\t}\n}\n```\n\nOn deploy the plugin runs `vite build` at startup (and rebuilds when `files` change) while `static` serves the result. If you prefer to build in CI, commit the build output, point `static` at it, and omit `files` so the plugin stays idle while `static` serves the prebuilt assets. Either way, `npm create harper@latest` scaffolds a working setup for you.\n",
|
|
50
50
|
"typescript-type-stripping": "---\nname: typescript-type-stripping\ndescription: How to run TypeScript files directly in Harper without a build step.\nmetadata:\n mode: generate\n sources:\n - reference/v5/components/javascript-environment.md#TypeScript Support\n sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819\n inputHash: 4e6bd8b610edd595\n---\n\n# TypeScript Type Stripping in Harper\n\nInstructions for the agent to run `.ts` files directly in Harper without a build step using Node.js's built-in type stripping.\n\n## When to Use\n\nApply this rule when writing Harper resource files in TypeScript. Use it any time you need to reference `.ts` source files from `config.yaml` or import between local TypeScript modules in a Harper project.\n\n## How It Works\n\n1. **Ensure Node.js version**: Require Node.js 22.6 or later. Type stripping is unavailable on earlier versions.\n\n2. **Point `jsResource` at `.ts` files**: The `jsResource` plugin loads both `.js` and `.ts` files. Set its `files` glob in `config.yaml` to target your `.ts` source files:\n\n ```yaml\n jsResource:\n files: 'resources/*.ts'\n ```\n\n3. **Use explicit `.ts` extensions in local imports**: Node's loader does not resolve `'./helper'` to `'./helper.ts'`, so always include the full extension:\n\n ```typescript\n import { helper } from './helper.ts';\n ```\n\n4. **Stay within type-stripping limits**: Only type annotations and declarations are removed. Do not use enums with runtime values, namespaces with runtime semantics, or any other features that require code transformation beyond type stripping.\n\n## Examples\n\nA complete Harper resource written in TypeScript, using imports from the `harper` package:\n\n```typescript\nimport { type RequestTargetOrId, Resource, tables } from 'harper';\n\nexport class MyResource extends Resource {\n\tasync get(target?: RequestTargetOrId): Promise<{ message: string }> {\n\t\treturn { message: 'Hello from TS' };\n\t}\n}\n```\n\nPaired `config.yaml` entry loading the file via `jsResource`:\n\n```yaml\njsResource:\n files: 'resources/*.ts'\n```\n\n## Notes\n\n- No build step or transpiler is required — Harper runs `.ts` files directly.\n- Type imports (e.g., `import { type RequestTargetOrId }`) from the `harper` package work as usual.\n- Unsupported TypeScript features include: enums with runtime values, namespaces with runtime semantics, and anything requiring code transformation beyond simple type stripping.\n",
|
|
51
51
|
"using-blob-datatype": "---\nname: using-blob-datatype\ndescription: How to use the Blob data type for efficient binary storage in Harper.\nmetadata:\n mode: synthesized\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",
|
|
52
52
|
"vector-indexing": "---\nname: vector-indexing\ndescription: How to enable and query vector indexes for similarity search in Harper.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/schema.md#Vector Indexing\n sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819\n inputHash: 3732961c671aac00\n---\n\n# Vector Indexing\n\nInstructions for the agent to follow when enabling and querying vector indexes for similarity search in Harper using the HNSW algorithm.\n\n## When to Use\n\nApply this rule when adding a vector index to a Harper table schema or writing similarity search queries against high-dimensional vector fields. Use it whenever you need approximate nearest-neighbor search, distance-threshold filtering, or distance-scored results.\n\n## How It Works\n\n1. **Declare the vector index on a `[Float]` field**: Add `@indexed(type: \"HNSW\")` to any `[Float]` attribute in a `@table` type. See [adding-tables-with-schemas.md](adding-tables-with-schemas.md) for general schema setup.\n\n ```graphql\n type Document @table {\n \tid: Long @primaryKey\n \ttextEmbeddings: [Float] @indexed(type: \"HNSW\")\n }\n ```\n\n2. **Query by nearest neighbors using `sort`**: Call `Document.search()` with a `sort` object containing `attribute` (the indexed field name) and `target` (the query vector). Include `limit` to cap results.\n\n ```javascript\n let results = Document.search({\n \tsort: { attribute: 'textEmbeddings', target: searchVector },\n \tlimit: 5,\n });\n ```\n\n3. **Combine with filter conditions**: Add a `conditions` array alongside `sort` to pre-filter records before ranking by similarity.\n\n ```javascript\n let results = Document.search({\n \tconditions: [{ attribute: 'price', comparator: 'lt', value: 50 }],\n \tsort: { attribute: 'textEmbeddings', target: searchVector },\n \tlimit: 5,\n });\n ```\n\n4. **Filter by distance threshold**: To return only records within a similarity cutoff (without ranking), place `target` directly on the condition alongside `comparator` and `value`. Omit `sort`.\n\n ```javascript\n let results = Document.search({\n \tconditions: {\n \t\tattribute: 'textEmbeddings',\n \t\tcomparator: 'lt',\n \t\tvalue: 0.1,\n \t\ttarget: searchVector,\n \t},\n });\n ```\n\n5. **Include computed distance in results**: Use the special `$distance` field in `select` to return the distance from the target vector. Works with both `sort`-based and `conditions`-based queries.\n\n ```javascript\n let results = Document.search({\n \tselect: ['name', '$distance'],\n \tsort: { attribute: 'textEmbeddings', target: searchVector },\n \tlimit: 5,\n });\n ```\n\n6. **Tune HNSW parameters**: Pass additional parameters to `@indexed(type: \"HNSW\", ...)` to control index quality and performance.\n\n | Parameter | Default | Description |\n | ---------------------- | ----------------- | --------------------------------------------------------------------------------------------------- |\n | `distance` | `\"cosine\"` | Distance function: `\"euclidean\"` or `\"cosine\"` (negative cosine similarity) |\n | `efConstruction` | `100` | Max nodes explored during index construction. Higher = better recall, lower = better performance |\n | `M` | `16` | Preferred connections per graph layer. Higher = more space, better recall for high-dimensional data |\n | `optimizeRouting` | `0.5` | Heuristic aggressiveness for omitting redundant connections (0 = off, 1 = most aggressive) |\n | `mL` | computed from `M` | Normalization factor for level generation |\n | `efSearchConstruction` | `50` | Max nodes explored during search |\n\n## Examples\n\n**Schema with custom HNSW parameters:**\n\n```graphql\ntype Document @table {\n\tid: Long @primaryKey\n\ttextEmbeddings: [Float]\n\t\t@indexed(type: \"HNSW\", distance: \"euclidean\", optimizeRouting: 0, efSearchConstruction: 100)\n}\n```\n\n**Nearest-neighbor search with distance score:**\n\n```javascript\nlet results = Document.search({\n\tselect: ['name', '$distance'],\n\tsort: { attribute: 'textEmbeddings', target: searchVector },\n\tlimit: 5,\n});\n```\n\n**Distance-threshold filter (no ranking):**\n\n```javascript\nlet results = Document.search({\n\tconditions: {\n\t\tattribute: 'textEmbeddings',\n\t\tcomparator: 'lt',\n\t\tvalue: 0.1,\n\t\ttarget: searchVector,\n\t},\n});\n```\n\n## Notes\n\n- The default `distance` function is `cosine`. Pass `distance: \"euclidean\"` to switch.\n- `efConstruction` controls index build quality; raising it improves recall at the cost of build time.\n- `$distance` is available in both `sort`-based ranking and `conditions`-based threshold queries.\n- Use the threshold (`conditions` + `target`) form when you want to bound result quality by a similarity cutoff rather than ranking by similarity.\n"
|
|
@@ -1617,59 +1617,78 @@ Instructions for the agent to follow when serving web content from Harper.
|
|
|
1617
1617
|
|
|
1618
1618
|
#### When to Use
|
|
1619
1619
|
|
|
1620
|
-
Use this skill when you need to serve a frontend (HTML, CSS, JS, or a React app) directly from your Harper instance.
|
|
1620
|
+
Use this skill when you need to serve a frontend (HTML, CSS, JS, or a React/Vue app) directly from your Harper instance — either plain static files or an integrated Vite app with hot module replacement (HMR) in development and a real production build when deployed.
|
|
1621
1621
|
|
|
1622
1622
|
#### How It Works
|
|
1623
1623
|
|
|
1624
|
-
|
|
1625
|
-
2. **Option A: Static Plugin (Simple)**:
|
|
1626
|
-
- Add to `config.yaml`:
|
|
1627
|
-
```yaml
|
|
1628
|
-
static:
|
|
1629
|
-
files: 'web/*'
|
|
1630
|
-
```
|
|
1631
|
-
- Place files in a `web/` folder in the project root.
|
|
1632
|
-
- Files are served at the root URL (e.g., `http://localhost:9926/index.html`).
|
|
1633
|
-
3. **Option B: Vite Plugin (Advanced/Development)**:
|
|
1634
|
-
- Add to `config.yaml`:
|
|
1635
|
-
```yaml
|
|
1636
|
-
'@harperfast/vite-plugin':
|
|
1637
|
-
package: '@harperfast/vite-plugin'
|
|
1638
|
-
```
|
|
1639
|
-
- Ensure `vite.config.ts` and `index.html` are in the project root.
|
|
1624
|
+
There are two building blocks. Harper's built-in `static` plugin **serves** files; the `@harperfast/vite` plugin **builds** (and, for SSR, **renders**) a Vite app. For a Vite app they work **together** — the plugin builds into a directory and `static` serves that same directory.
|
|
1640
1625
|
|
|
1641
|
-
|
|
1642
|
-
import vue from '@vitejs/plugin-vue';
|
|
1643
|
-
import path from 'node:path';
|
|
1644
|
-
import { defineConfig } from 'vite';
|
|
1645
|
-
|
|
1646
|
-
// https://vite.dev/config/
|
|
1647
|
-
export default defineConfig({
|
|
1648
|
-
plugins: [vue()],
|
|
1649
|
-
resolve: {
|
|
1650
|
-
alias: {
|
|
1651
|
-
'@': path.resolve(import.meta.dirname, './src'),
|
|
1652
|
-
},
|
|
1653
|
-
},
|
|
1654
|
-
build: {
|
|
1655
|
-
outDir: 'web',
|
|
1656
|
-
emptyOutDir: true,
|
|
1657
|
-
rolldownOptions: {
|
|
1658
|
-
external: ['**/*.test.*', '**/*.spec.*'],
|
|
1659
|
-
},
|
|
1660
|
-
},
|
|
1661
|
-
});
|
|
1662
|
-
```
|
|
1626
|
+
##### Option A: Static plugin only (simple, pre-built assets)
|
|
1663
1627
|
|
|
1664
|
-
|
|
1665
|
-
- Then `harper run .` will start up Harper and Vite with HMR. Vite does _not_ need to be executed separately.
|
|
1628
|
+
For a plain static site or already-built assets, use `static` on its own:
|
|
1666
1629
|
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1630
|
+
```yaml
|
|
1631
|
+
static:
|
|
1632
|
+
files: 'web/*'
|
|
1633
|
+
```
|
|
1634
|
+
|
|
1635
|
+
- Place files in a `web/` folder in the project root; they are served from the root URL (e.g. `http://localhost:9926/index.html`).
|
|
1636
|
+
- Static files are matched first; if none matches, Harper falls through to your resource and table APIs.
|
|
1637
|
+
|
|
1638
|
+
##### Option B: Vite plugin + static plugin (integrated Vite app)
|
|
1639
|
+
|
|
1640
|
+
> **Renamed in v1:** the plugin was previously `@harperfast/vite-plugin`. From `1.0.0` on it is **`@harperfast/vite`** (same key and `package`). It now pairs with the `static` plugin instead of building into `web/` itself.
|
|
1641
|
+
|
|
1642
|
+
`@harperfast/vite` **builds** your app — in `harper dev` it runs Vite in middleware mode with HMR; in `harper run` it runs `vite build` and rebuilds when watched files change (and renders HTML for SSR). The `static` plugin **serves** the built output. Point both at the same directory (`output`, default `dist`) — that shared directory is the only contract between them.
|
|
1643
|
+
|
|
1644
|
+
**SPA `config.yaml`** — list the plugin first so its dev server wins in `harper dev`; `notFound` + `fallthrough: false` makes client-side routing work:
|
|
1645
|
+
|
|
1646
|
+
```yaml
|
|
1647
|
+
'@harperfast/vite':
|
|
1648
|
+
package: '@harperfast/vite'
|
|
1649
|
+
files: 'src/**/*'
|
|
1650
|
+
output: 'dist'
|
|
1651
|
+
|
|
1652
|
+
static:
|
|
1653
|
+
files: 'dist/**'
|
|
1654
|
+
notFound:
|
|
1655
|
+
file: 'index.html'
|
|
1656
|
+
statusCode: 200
|
|
1657
|
+
fallthrough: false
|
|
1658
|
+
```
|
|
1659
|
+
|
|
1660
|
+
**SSR `config.yaml`** — add an `ssr` entry so the plugin renders `index.html`, and set `index: false` on `static` so it serves assets only:
|
|
1661
|
+
|
|
1662
|
+
```yaml
|
|
1663
|
+
'@harperfast/vite':
|
|
1664
|
+
package: '@harperfast/vite'
|
|
1665
|
+
files: 'src/**/*'
|
|
1666
|
+
output: 'dist'
|
|
1667
|
+
ssr: 'src/entry-server.tsx'
|
|
1668
|
+
|
|
1669
|
+
static:
|
|
1670
|
+
files: 'dist/**'
|
|
1671
|
+
index: false
|
|
1672
|
+
```
|
|
1673
|
+
|
|
1674
|
+
- Install dependencies: `npm install --save-dev vite @harperfast/vite @vitejs/plugin-react` (swap in your framework's Vite plugin, e.g. `@vitejs/plugin-vue`).
|
|
1675
|
+
- Then `harper dev .` runs the app with HMR and `harper run .` runs the production build. Vite does _not_ need to be executed separately.
|
|
1676
|
+
|
|
1677
|
+
#### Deploying to Production
|
|
1678
|
+
|
|
1679
|
+
Because `@harperfast/vite` builds on the node and `static` serves the output, deploy the component as-is — no manual build-and-move step is needed:
|
|
1680
|
+
|
|
1681
|
+
```json
|
|
1682
|
+
{
|
|
1683
|
+
"scripts": {
|
|
1684
|
+
"dev": "harper dev .",
|
|
1685
|
+
"start": "harper run .",
|
|
1686
|
+
"deploy": "harper deploy_component . restart=true replicated=true"
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
```
|
|
1690
|
+
|
|
1691
|
+
On deploy the plugin runs `vite build` at startup (and rebuilds when `files` change) while `static` serves the result. If you prefer to build in CI, commit the build output, point `static` at it, and omit `files` so the plugin stays idle while `static` serves the prebuilt assets. Either way, `npm create harper@latest` scaffolds a working setup for you.
|
|
1673
1692
|
|
|
1674
1693
|
### 4.5 Harper Logging
|
|
1675
1694
|
|
|
@@ -1833,20 +1852,18 @@ Instructions for the agent to follow when loading environment variables from `.e
|
|
|
1833
1852
|
|
|
1834
1853
|
#### When to Use
|
|
1835
1854
|
|
|
1836
|
-
Apply this rule when a Harper application needs to load secrets or configuration values from `.env` files into `process.env` at startup. Use it whenever
|
|
1855
|
+
Apply this rule when a Harper application needs to load secrets or configuration values from `.env` files into `process.env` at startup. Use it whenever hardcoding values must be avoided and environment-specific configuration must be supplied to Harper components.
|
|
1837
1856
|
|
|
1838
1857
|
#### How It Works
|
|
1839
1858
|
|
|
1840
|
-
1. **Declare `loadEnv` in `config.yaml`**: Add `loadEnv`
|
|
1859
|
+
1. **Declare `loadEnv` in `config.yaml`**: Add `loadEnv` as a top-level key. It is built into Harper and requires no installation.
|
|
1841
1860
|
|
|
1842
1861
|
```yaml
|
|
1843
1862
|
loadEnv:
|
|
1844
1863
|
files: '.env'
|
|
1845
1864
|
```
|
|
1846
1865
|
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
2. **Place `loadEnv` first**: Always declare `loadEnv` before any other components in `config.yaml` so environment variables are available before dependent components start. Because Harper is single-process, variables loaded onto `process.env` are shared across all components.
|
|
1866
|
+
2. **Place `loadEnv` first**: Always list `loadEnv` before any other components in `config.yaml` so that environment variables are available on `process.env` before dependent components start.
|
|
1850
1867
|
|
|
1851
1868
|
```yaml
|
|
1852
1869
|
# config.yaml — loadEnv must come first
|
|
@@ -1859,7 +1876,9 @@ Apply this rule when a Harper application needs to load secrets or configuration
|
|
|
1859
1876
|
files: './src/*.js'
|
|
1860
1877
|
```
|
|
1861
1878
|
|
|
1862
|
-
3. **
|
|
1879
|
+
3. **Configure the `files` option**: Provide one or more paths or glob patterns pointing to the env files to load. This option is required.
|
|
1880
|
+
|
|
1881
|
+
4. **Set `override` if needed**: By default, existing environment variables take precedence over values in `.env` files. Set `override: true` to reverse this and have loaded values win.
|
|
1863
1882
|
|
|
1864
1883
|
```yaml
|
|
1865
1884
|
loadEnv:
|
|
@@ -1867,22 +1886,36 @@ Apply this rule when a Harper application needs to load secrets or configuration
|
|
|
1867
1886
|
override: true
|
|
1868
1887
|
```
|
|
1869
1888
|
|
|
1870
|
-
|
|
1889
|
+
5. **Load multiple files when required**: Supply a list of files or a glob pattern. Files are loaded in the order specified.
|
|
1871
1890
|
```yaml
|
|
1872
1891
|
loadEnv:
|
|
1873
1892
|
files:
|
|
1874
1893
|
- '.env'
|
|
1875
1894
|
- '.env.local'
|
|
1876
1895
|
```
|
|
1877
|
-
|
|
1896
|
+
or
|
|
1878
1897
|
```yaml
|
|
1879
1898
|
loadEnv:
|
|
1880
1899
|
files: 'env-vars/*'
|
|
1881
1900
|
```
|
|
1882
1901
|
|
|
1902
|
+
##### Configuration Options
|
|
1903
|
+
|
|
1904
|
+
| Option | Type | Required | Description |
|
|
1905
|
+
| ---------- | -------------------- | -------- | -------------------------------------------------------------------------------------- |
|
|
1906
|
+
| `files` | `string \| string[]` | **Yes** | Path(s) or glob pattern(s) to the env file(s) to load. |
|
|
1907
|
+
| `override` | `boolean` | No | If `true`, loaded values override existing environment variables. Defaults to `false`. |
|
|
1908
|
+
|
|
1883
1909
|
#### Examples
|
|
1884
1910
|
|
|
1885
|
-
|
|
1911
|
+
**Minimal setup — single `.env` file:**
|
|
1912
|
+
|
|
1913
|
+
```yaml
|
|
1914
|
+
loadEnv:
|
|
1915
|
+
files: '.env'
|
|
1916
|
+
```
|
|
1917
|
+
|
|
1918
|
+
**Full `config.yaml` with load order, multiple files, and override:**
|
|
1886
1919
|
|
|
1887
1920
|
```yaml
|
|
1888
1921
|
# config.yaml — loadEnv must come first
|
|
@@ -1898,19 +1931,16 @@ myApp:
|
|
|
1898
1931
|
files: './src/*.js'
|
|
1899
1932
|
```
|
|
1900
1933
|
|
|
1901
|
-
|
|
1934
|
+
**Glob pattern:**
|
|
1902
1935
|
|
|
1903
1936
|
```yaml
|
|
1904
1937
|
loadEnv:
|
|
1905
|
-
files: '
|
|
1906
|
-
|
|
1907
|
-
myApp:
|
|
1908
|
-
files: './src/*.js'
|
|
1938
|
+
files: 'env-vars/*'
|
|
1909
1939
|
```
|
|
1910
1940
|
|
|
1911
1941
|
#### Notes
|
|
1912
1942
|
|
|
1913
|
-
- `loadEnv` is built into Harper —
|
|
1914
|
-
-
|
|
1915
|
-
- Without `override: true`, variables already
|
|
1916
|
-
- `
|
|
1943
|
+
- `loadEnv` is built into Harper — do not install it separately; only declare it in `config.yaml`.
|
|
1944
|
+
- Because Harper is a single-process application, variables loaded onto `process.env` are shared across all components.
|
|
1945
|
+
- Without `override: true`, variables already set in the shell or container environment will not be overwritten by values in `.env` files.
|
|
1946
|
+
- `files` is the only required option; omitting it will produce an invalid configuration.
|
|
@@ -7,8 +7,8 @@ metadata:
|
|
|
7
7
|
mode: generate
|
|
8
8
|
sources:
|
|
9
9
|
- reference/v5/environment-variables/overview.md
|
|
10
|
-
sourceCommit:
|
|
11
|
-
inputHash:
|
|
10
|
+
sourceCommit: 42231db17c025a4a455e3d91875fad4084a01cb5
|
|
11
|
+
inputHash: fe610fc245226357
|
|
12
12
|
---
|
|
13
13
|
|
|
14
14
|
# Load Environment Variables with loadEnv
|
|
@@ -17,20 +17,18 @@ Instructions for the agent to follow when loading environment variables from `.e
|
|
|
17
17
|
|
|
18
18
|
## When to Use
|
|
19
19
|
|
|
20
|
-
Apply this rule when a Harper application needs to load secrets or configuration values from `.env` files into `process.env` at startup. Use it whenever
|
|
20
|
+
Apply this rule when a Harper application needs to load secrets or configuration values from `.env` files into `process.env` at startup. Use it whenever hardcoding values must be avoided and environment-specific configuration must be supplied to Harper components.
|
|
21
21
|
|
|
22
22
|
## How It Works
|
|
23
23
|
|
|
24
|
-
1. **Declare `loadEnv` in `config.yaml`**: Add `loadEnv`
|
|
24
|
+
1. **Declare `loadEnv` in `config.yaml`**: Add `loadEnv` as a top-level key. It is built into Harper and requires no installation.
|
|
25
25
|
|
|
26
26
|
```yaml
|
|
27
27
|
loadEnv:
|
|
28
28
|
files: '.env'
|
|
29
29
|
```
|
|
30
30
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
2. **Place `loadEnv` first**: Always declare `loadEnv` before any other components in `config.yaml` so environment variables are available before dependent components start. Because Harper is single-process, variables loaded onto `process.env` are shared across all components.
|
|
31
|
+
2. **Place `loadEnv` first**: Always list `loadEnv` before any other components in `config.yaml` so that environment variables are available on `process.env` before dependent components start.
|
|
34
32
|
|
|
35
33
|
```yaml
|
|
36
34
|
# config.yaml — loadEnv must come first
|
|
@@ -43,7 +41,9 @@ Apply this rule when a Harper application needs to load secrets or configuration
|
|
|
43
41
|
files: './src/*.js'
|
|
44
42
|
```
|
|
45
43
|
|
|
46
|
-
3. **
|
|
44
|
+
3. **Configure the `files` option**: Provide one or more paths or glob patterns pointing to the env files to load. This option is required.
|
|
45
|
+
|
|
46
|
+
4. **Set `override` if needed**: By default, existing environment variables take precedence over values in `.env` files. Set `override: true` to reverse this and have loaded values win.
|
|
47
47
|
|
|
48
48
|
```yaml
|
|
49
49
|
loadEnv:
|
|
@@ -51,22 +51,36 @@ Apply this rule when a Harper application needs to load secrets or configuration
|
|
|
51
51
|
override: true
|
|
52
52
|
```
|
|
53
53
|
|
|
54
|
-
|
|
54
|
+
5. **Load multiple files when required**: Supply a list of files or a glob pattern. Files are loaded in the order specified.
|
|
55
55
|
```yaml
|
|
56
56
|
loadEnv:
|
|
57
57
|
files:
|
|
58
58
|
- '.env'
|
|
59
59
|
- '.env.local'
|
|
60
60
|
```
|
|
61
|
-
|
|
61
|
+
or
|
|
62
62
|
```yaml
|
|
63
63
|
loadEnv:
|
|
64
64
|
files: 'env-vars/*'
|
|
65
65
|
```
|
|
66
66
|
|
|
67
|
+
### Configuration Options
|
|
68
|
+
|
|
69
|
+
| Option | Type | Required | Description |
|
|
70
|
+
| ---------- | -------------------- | -------- | -------------------------------------------------------------------------------------- |
|
|
71
|
+
| `files` | `string \| string[]` | **Yes** | Path(s) or glob pattern(s) to the env file(s) to load. |
|
|
72
|
+
| `override` | `boolean` | No | If `true`, loaded values override existing environment variables. Defaults to `false`. |
|
|
73
|
+
|
|
67
74
|
## Examples
|
|
68
75
|
|
|
69
|
-
|
|
76
|
+
**Minimal setup — single `.env` file:**
|
|
77
|
+
|
|
78
|
+
```yaml
|
|
79
|
+
loadEnv:
|
|
80
|
+
files: '.env'
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
**Full `config.yaml` with load order, multiple files, and override:**
|
|
70
84
|
|
|
71
85
|
```yaml
|
|
72
86
|
# config.yaml — loadEnv must come first
|
|
@@ -82,19 +96,16 @@ myApp:
|
|
|
82
96
|
files: './src/*.js'
|
|
83
97
|
```
|
|
84
98
|
|
|
85
|
-
|
|
99
|
+
**Glob pattern:**
|
|
86
100
|
|
|
87
101
|
```yaml
|
|
88
102
|
loadEnv:
|
|
89
|
-
files: '
|
|
90
|
-
|
|
91
|
-
myApp:
|
|
92
|
-
files: './src/*.js'
|
|
103
|
+
files: 'env-vars/*'
|
|
93
104
|
```
|
|
94
105
|
|
|
95
106
|
## Notes
|
|
96
107
|
|
|
97
|
-
- `loadEnv` is built into Harper —
|
|
98
|
-
-
|
|
99
|
-
- Without `override: true`, variables already
|
|
100
|
-
- `
|
|
108
|
+
- `loadEnv` is built into Harper — do not install it separately; only declare it in `config.yaml`.
|
|
109
|
+
- Because Harper is a single-process application, variables loaded onto `process.env` are shared across all components.
|
|
110
|
+
- Without `override: true`, variables already set in the shell or container environment will not be overwritten by values in `.env` files.
|
|
111
|
+
- `files` is the only required option; omitting it will produce an invalid configuration.
|
|
@@ -11,56 +11,75 @@ Instructions for the agent to follow when serving web content from Harper.
|
|
|
11
11
|
|
|
12
12
|
## When to Use
|
|
13
13
|
|
|
14
|
-
Use this skill when you need to serve a frontend (HTML, CSS, JS, or a React app) directly from your Harper instance.
|
|
14
|
+
Use this skill when you need to serve a frontend (HTML, CSS, JS, or a React/Vue app) directly from your Harper instance — either plain static files or an integrated Vite app with hot module replacement (HMR) in development and a real production build when deployed.
|
|
15
15
|
|
|
16
16
|
## How It Works
|
|
17
17
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
18
|
+
There are two building blocks. Harper's built-in `static` plugin **serves** files; the `@harperfast/vite` plugin **builds** (and, for SSR, **renders**) a Vite app. For a Vite app they work **together** — the plugin builds into a directory and `static` serves that same directory.
|
|
19
|
+
|
|
20
|
+
### Option A: Static plugin only (simple, pre-built assets)
|
|
21
|
+
|
|
22
|
+
For a plain static site or already-built assets, use `static` on its own:
|
|
23
|
+
|
|
24
|
+
```yaml
|
|
25
|
+
static:
|
|
26
|
+
files: 'web/*'
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
- Place files in a `web/` folder in the project root; they are served from the root URL (e.g. `http://localhost:9926/index.html`).
|
|
30
|
+
- Static files are matched first; if none matches, Harper falls through to your resource and table APIs.
|
|
31
|
+
|
|
32
|
+
### Option B: Vite plugin + static plugin (integrated Vite app)
|
|
33
|
+
|
|
34
|
+
> **Renamed in v1:** the plugin was previously `@harperfast/vite-plugin`. From `1.0.0` on it is **`@harperfast/vite`** (same key and `package`). It now pairs with the `static` plugin instead of building into `web/` itself.
|
|
35
|
+
|
|
36
|
+
`@harperfast/vite` **builds** your app — in `harper dev` it runs Vite in middleware mode with HMR; in `harper run` it runs `vite build` and rebuilds when watched files change (and renders HTML for SSR). The `static` plugin **serves** the built output. Point both at the same directory (`output`, default `dist`) — that shared directory is the only contract between them.
|
|
37
|
+
|
|
38
|
+
**SPA `config.yaml`** — list the plugin first so its dev server wins in `harper dev`; `notFound` + `fallthrough: false` makes client-side routing work:
|
|
39
|
+
|
|
40
|
+
```yaml
|
|
41
|
+
'@harperfast/vite':
|
|
42
|
+
package: '@harperfast/vite'
|
|
43
|
+
files: 'src/**/*'
|
|
44
|
+
output: 'dist'
|
|
45
|
+
|
|
46
|
+
static:
|
|
47
|
+
files: 'dist/**'
|
|
48
|
+
notFound:
|
|
49
|
+
file: 'index.html'
|
|
50
|
+
statusCode: 200
|
|
51
|
+
fallthrough: false
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
**SSR `config.yaml`** — add an `ssr` entry so the plugin renders `index.html`, and set `index: false` on `static` so it serves assets only:
|
|
55
|
+
|
|
56
|
+
```yaml
|
|
57
|
+
'@harperfast/vite':
|
|
58
|
+
package: '@harperfast/vite'
|
|
59
|
+
files: 'src/**/*'
|
|
60
|
+
output: 'dist'
|
|
61
|
+
ssr: 'src/entry-server.tsx'
|
|
62
|
+
|
|
63
|
+
static:
|
|
64
|
+
files: 'dist/**'
|
|
65
|
+
index: false
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
- Install dependencies: `npm install --save-dev vite @harperfast/vite @vitejs/plugin-react` (swap in your framework's Vite plugin, e.g. `@vitejs/plugin-vue`).
|
|
69
|
+
- Then `harper dev .` runs the app with HMR and `harper run .` runs the production build. Vite does _not_ need to be executed separately.
|
|
70
|
+
|
|
71
|
+
## Deploying to Production
|
|
72
|
+
|
|
73
|
+
Because `@harperfast/vite` builds on the node and `static` serves the output, deploy the component as-is — no manual build-and-move step is needed:
|
|
74
|
+
|
|
75
|
+
```json
|
|
76
|
+
{
|
|
77
|
+
"scripts": {
|
|
78
|
+
"dev": "harper dev .",
|
|
79
|
+
"start": "harper run .",
|
|
80
|
+
"deploy": "harper deploy_component . restart=true replicated=true"
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
On deploy the plugin runs `vite build` at startup (and rebuilds when `files` change) while `static` serves the result. If you prefer to build in CI, commit the build output, point `static` at it, and omit `files` so the plugin stays idle while `static` serves the prebuilt assets. Either way, `npm create harper@latest` scaffolds a working setup for you.
|