Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 038c901f4b | |||
| f4cf92e128 | |||
| c8bf38cb81 | |||
| b93d7b229a | |||
| 9912013b0a | |||
| 2ed097e207 | |||
| b0d5b05457 | |||
| de20cfde53 | |||
| 9948db77ea | |||
| c60f05f650 | |||
| 314b076c05 | |||
| 664409b94a | |||
| f3f13e6f35 | |||
| 10c5c8f98e | |||
| d28003779e | |||
| 885a8e1147 | |||
| f0ffe6b234 | |||
| fc869cfc99 | |||
| 7fd2013ef2 | |||
| 0b72c9400f | |||
| eb36c16420 | |||
| 3c8b16d7b1 | |||
| 51e81c7b99 |
@@ -0,0 +1,413 @@
|
||||
name: "e2e-check"
|
||||
description: "Docker-isolated E2E testing of json-cas CLI. Preparer builds from scratch, tester runs scenarios, reporter files bugs."
|
||||
|
||||
roles:
|
||||
preparer:
|
||||
description: "Spins up Docker container, copies repo, installs, builds, runs unit tests"
|
||||
goal: "You set up a clean Docker environment for E2E testing. Your job is to start a container, install deps, build, lint, run unit tests, and initialize a CAS store. Report any setup failures as bugs."
|
||||
capabilities:
|
||||
- docker
|
||||
procedure: |
|
||||
1. Start a detached container:
|
||||
```bash
|
||||
docker run -d --name json-cas-e2e \
|
||||
-v "<repoPath>:/src:ro" \
|
||||
-w /workspace \
|
||||
oven/bun:latest \
|
||||
sleep 3600
|
||||
```
|
||||
|
||||
2. Copy repo and install:
|
||||
```bash
|
||||
docker exec json-cas-e2e bash -c 'cp -r /src/. /workspace/ && cd /workspace && bun install'
|
||||
```
|
||||
✅ exit code 0, no missing peer deps
|
||||
|
||||
3. Build:
|
||||
```bash
|
||||
docker exec json-cas-e2e bash -c 'cd /workspace && bun run build'
|
||||
```
|
||||
✅ exit code 0, no type errors
|
||||
|
||||
4. Lint:
|
||||
```bash
|
||||
docker exec json-cas-e2e bash -c 'cd /workspace && bun run check'
|
||||
```
|
||||
✅ exit code 0
|
||||
|
||||
5. Unit tests:
|
||||
```bash
|
||||
docker exec json-cas-e2e bash -c 'cd /workspace && bun test'
|
||||
```
|
||||
✅ all pass (ignore dist/ false positives)
|
||||
|
||||
6. Init CAS store:
|
||||
```bash
|
||||
docker exec json-cas-e2e bash -c 'mkdir -p /tmp/cas-test && cd /workspace && bun packages/cli-json-cas/src/index.ts --store /tmp/cas-test init && bun packages/cli-json-cas/src/index.ts --store /tmp/cas-test bootstrap'
|
||||
```
|
||||
|
||||
**Any failure here is a high-severity bug** — it means a clean environment can't build/run the project.
|
||||
|
||||
Set $status=ready if all steps pass. Set $status=setup_failed with failures list if anything breaks.
|
||||
|
||||
output: "Setup result summary."
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "ready" }
|
||||
containerName: { type: string }
|
||||
storePath: { type: string }
|
||||
repoPath: { type: string }
|
||||
required: [$status, containerName, storePath, repoPath]
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "setup_failed" }
|
||||
failures:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
title: { type: string }
|
||||
command: { type: string }
|
||||
expected: { type: string }
|
||||
actual: { type: string }
|
||||
severity: { type: string }
|
||||
phase: { type: string }
|
||||
required: [title, command, expected, actual, severity, phase]
|
||||
repoPath: { type: string }
|
||||
required: [$status, failures, repoPath]
|
||||
|
||||
tester:
|
||||
description: "Runs CLI scenarios against the prepared Docker environment"
|
||||
goal: "You are an exploratory QA agent. The Docker container is already running with the project built and a CAS store initialized. Run CLI test scenarios and report bugs."
|
||||
capabilities:
|
||||
- testing
|
||||
- cli
|
||||
procedure: |
|
||||
The container `{{{containerName}}}` is already running with the project built.
|
||||
Store path: `{{{storePath}}}`.
|
||||
|
||||
Run all commands via:
|
||||
```bash
|
||||
docker exec {{{containerName}}} bash -c 'cd /workspace && bun packages/cli-json-cas/src/index.ts --store {{{storePath}}} <subcommand>'
|
||||
```
|
||||
|
||||
Define a shorthand in your notes:
|
||||
`CMD="cd /workspace && bun packages/cli-json-cas/src/index.ts --store {{{storePath}}}"`
|
||||
|
||||
## Phase 1: CAS Core Operations
|
||||
|
||||
1. **bootstrap** — `$CMD bootstrap`
|
||||
Expected: prints meta-schema hash (13-char Base32)
|
||||
|
||||
2. **schema put** — Create `/tmp/test-schema.json` in container, then `$CMD schema put /tmp/test-schema.json`
|
||||
Schema: `{"type":"object","properties":{"name":{"type":"string"},"age":{"type":"number"}},"required":["name"],"additionalProperties":false}`
|
||||
Expected: prints type hash
|
||||
|
||||
3. **schema get** — `$CMD schema get <type-hash>`
|
||||
Expected: returns the schema JSON
|
||||
|
||||
4. **schema list** — `$CMD schema list`
|
||||
Expected: lists registered schemas
|
||||
|
||||
5. **put** — Create data file, `$CMD put <type-hash> /tmp/test-node.json`
|
||||
Data: `{"name":"Alice","age":30}`
|
||||
Expected: prints node hash
|
||||
|
||||
6. **get** — `$CMD get <node-hash>`
|
||||
Expected: returns node JSON
|
||||
|
||||
7. **has (exists)** — `$CMD has <node-hash>`
|
||||
Expected: true
|
||||
|
||||
8. **has (not exists)** — `$CMD has AAAAAAAAAAAAA`
|
||||
Expected: false
|
||||
|
||||
9. **verify** — `$CMD verify <node-hash>`
|
||||
Expected: ok
|
||||
|
||||
10. **refs** — `$CMD refs <node-hash>`
|
||||
Expected: lists refs (may be empty)
|
||||
|
||||
11. **walk** — `$CMD walk <node-hash>`
|
||||
Expected: shows traversal tree
|
||||
|
||||
12. **hash (dry run)** — `$CMD hash <type-hash> /tmp/test-node.json`
|
||||
Expected: same hash as put
|
||||
|
||||
13. **cat** — `$CMD cat <node-hash>`
|
||||
Expected: full node output
|
||||
|
||||
14. **cat --payload** — `$CMD cat <node-hash> --payload`
|
||||
Expected: payload only (no type wrapper)
|
||||
|
||||
## Phase 2: Schema Validation
|
||||
|
||||
1. **Invalid node** — `$CMD put <type-hash> /tmp/bad-node.json` where bad-node = `{"name":123}`
|
||||
Expected: validation error, non-zero exit
|
||||
|
||||
2. **schema validate** — `$CMD schema validate <node-hash>`
|
||||
Expected: valid for good node
|
||||
|
||||
3. **Non-existent schema** — `$CMD put AAAAAAAAAAAAA /tmp/test-node.json`
|
||||
Expected: error about missing schema
|
||||
|
||||
## Phase 3: Variable System
|
||||
|
||||
1. **var set** — `$CMD var set myapp/config <node-hash>`
|
||||
Expected: creates variable
|
||||
|
||||
2. **var get** — `$CMD var get myapp/config --schema <type-hash>`
|
||||
Expected: returns variable
|
||||
|
||||
3. **var list** — `$CMD var list`
|
||||
Expected: shows all variables
|
||||
|
||||
4. **var list prefix** — `$CMD var list myapp/`
|
||||
Expected: filtered results
|
||||
|
||||
5. **var set (update)** — Put a second node, `$CMD var set myapp/config <new-hash>`
|
||||
Expected: upsert succeeds
|
||||
|
||||
6. **var tag** — `$CMD var tag myapp/config --schema <type-hash> env:prod important`
|
||||
Expected: adds tag and label
|
||||
|
||||
7. **var list --tag** — `$CMD var list --tag env:prod`
|
||||
Expected: finds tagged variable
|
||||
|
||||
8. **var list --tag (label)** — `$CMD var list --tag important`
|
||||
Expected: finds labeled variable
|
||||
|
||||
9. **var tag remove** — `$CMD var tag myapp/config --schema <type-hash> :important`
|
||||
Expected: removes label
|
||||
|
||||
10. **var delete** — `$CMD var delete myapp/config`
|
||||
Expected: deletes variable
|
||||
|
||||
11. **var get (deleted)** — `$CMD var get myapp/config --schema <type-hash>`
|
||||
Expected: not found error
|
||||
|
||||
## Phase 4: Template System
|
||||
|
||||
1. **template set** — Create template file, `$CMD template set <type-hash> /tmp/test.liquid`
|
||||
Template: `Name: {{ payload.name }}, Age: {{ payload.age }}`
|
||||
Expected: success
|
||||
|
||||
2. **template get** — `$CMD template get <type-hash>`
|
||||
Expected: returns template text
|
||||
|
||||
3. **template list** — `$CMD template list`
|
||||
Expected: lists templates
|
||||
|
||||
4. **template delete** — `$CMD template delete <type-hash>`
|
||||
Expected: success
|
||||
|
||||
5. **template get (deleted)** — `$CMD template get <type-hash>`
|
||||
Expected: not found error
|
||||
|
||||
## Phase 5: Render
|
||||
|
||||
1. Re-register template, then `$CMD render <node-hash>`
|
||||
Expected: rendered output with payload values filled in
|
||||
|
||||
2. **render --resolution** — `$CMD render <node-hash> --resolution 0.5`
|
||||
Expected: different resolution output
|
||||
|
||||
3. **render (bad hash)** — `$CMD render AAAAAAAAAAAAA`
|
||||
Expected: graceful error, non-zero exit
|
||||
|
||||
## Phase 6: GC
|
||||
|
||||
1. **gc basic** — `$CMD gc`
|
||||
Expected: runs without error
|
||||
|
||||
2. **gc preserves referenced** — Verify `$CMD has <node-hash>` still true
|
||||
|
||||
3. **gc collects orphans** — Put an orphan node (not in any variable), run gc, check it's gone
|
||||
|
||||
## Phase 7: Edge Cases & Error Handling
|
||||
|
||||
1. `$CMD get AAAAAAAAAAAAA` — non-existent
|
||||
2. `$CMD put <type-hash> /nonexistent/file.json` — missing file
|
||||
3. `$CMD var set "" <hash>` — empty name
|
||||
4. `$CMD var set "bad name!" <hash>` — invalid name chars
|
||||
5. `$CMD schema put /tmp/bad-schema.json` — `{"type":"invalid"}`
|
||||
6. `$CMD` with no subcommand — should show help
|
||||
7. `$CMD --store /nonexistent/path get <hash>` — bad store path
|
||||
|
||||
## Recording Results
|
||||
|
||||
For each scenario:
|
||||
- ✅ Pass: works as expected
|
||||
- ❌ Fail: unexpected behavior, crash, wrong output
|
||||
- ⚠️ Questionable: works but confusing UX
|
||||
|
||||
Collect all ❌ and ⚠️. For each, record:
|
||||
- Title (concise description)
|
||||
- Command (exact command run)
|
||||
- Expected behavior
|
||||
- Actual behavior (include actual output)
|
||||
- Severity: critical / high / medium / low
|
||||
- Phase: which test phase
|
||||
|
||||
## CRITICAL: Frontmatter Output Format
|
||||
|
||||
Your response MUST start with YAML frontmatter. The `bugs` field MUST be an array of objects, NOT strings.
|
||||
|
||||
Example of CORRECT frontmatter:
|
||||
```yaml
|
||||
---
|
||||
$status: bugs_found
|
||||
containerName: json-cas-e2e
|
||||
repoPath: /path/to/repo
|
||||
bugs:
|
||||
- title: "put does not validate data against schema"
|
||||
command: "json-cas put <hash> bad-data.json"
|
||||
expected: "Validation error, non-zero exit"
|
||||
actual: "Accepted invalid data, exit 0"
|
||||
severity: "high"
|
||||
phase: "Schema Validation"
|
||||
---
|
||||
```
|
||||
|
||||
Do NOT write bugs as plain strings like `- some bug description`. Each bug MUST be an object with all 6 fields.
|
||||
|
||||
If all tests pass:
|
||||
```yaml
|
||||
---
|
||||
$status: all_passed
|
||||
containerName: json-cas-e2e
|
||||
---
|
||||
```
|
||||
|
||||
output: "Summary of all phases with pass/fail counts. Set $status."
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "bugs_found" }
|
||||
bugs:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
title: { type: string }
|
||||
command: { type: string }
|
||||
expected: { type: string }
|
||||
actual: { type: string }
|
||||
severity: { type: string }
|
||||
phase: { type: string }
|
||||
required: [title, command, expected, actual, severity, phase]
|
||||
containerName: { type: string }
|
||||
repoPath: { type: string }
|
||||
required: [$status, bugs, containerName]
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "all_passed" }
|
||||
containerName: { type: string }
|
||||
required: [$status, containerName]
|
||||
|
||||
reporter:
|
||||
description: "Opens Gitea issues for each bug found by the tester"
|
||||
goal: "You are a bug reporter. You create well-formatted Gitea issues for each bug found during E2E testing."
|
||||
capabilities:
|
||||
- issue-management
|
||||
procedure: |
|
||||
1. Parse the bugs array from the tester's output
|
||||
2. Group bugs by severity (critical first)
|
||||
3. For each bug, create a Gitea issue:
|
||||
```bash
|
||||
tea issues create -r uncaged/json-cas \
|
||||
-t "[E2E] <title>" \
|
||||
-d "## Bug Report (E2E Check)
|
||||
|
||||
**Phase:** <phase>
|
||||
**Severity:** <severity>
|
||||
|
||||
**Command:**
|
||||
\`\`\`
|
||||
<exact command>
|
||||
\`\`\`
|
||||
|
||||
**Expected:** <expected>
|
||||
|
||||
**Actual:** <actual>
|
||||
|
||||
---
|
||||
_Reported by e2e-check workflow (Docker isolated)_"
|
||||
```
|
||||
|
||||
⚠️ If `tea issues create` fails with long body, use Gitea REST API:
|
||||
```bash
|
||||
eval "$(cfg env)" && GITEA_TOKEN=$(cfg get GITEA_TOKEN)
|
||||
curl -s -X POST "https://git.shazhou.work/api/v1/repos/uncaged/json-cas/issues" \
|
||||
-H "Authorization: token $GITEA_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"title":"[E2E] ...","body":"..."}'
|
||||
```
|
||||
|
||||
4. Collect created issue numbers
|
||||
|
||||
output: "List created issues. Set $status."
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "reported" }
|
||||
issues:
|
||||
type: array
|
||||
items: { type: string }
|
||||
required: [$status, issues]
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "partial" }
|
||||
created: { type: number }
|
||||
failed: { type: number }
|
||||
required: [$status, created, failed]
|
||||
|
||||
cleanup:
|
||||
description: "Stops and removes the Docker container"
|
||||
goal: "You clean up the Docker environment after testing is complete."
|
||||
capabilities:
|
||||
- docker
|
||||
procedure: |
|
||||
Stop and remove the container:
|
||||
```bash
|
||||
docker stop {{{containerName}}} && docker rm {{{containerName}}}
|
||||
```
|
||||
|
||||
Verify it's gone:
|
||||
```bash
|
||||
docker ps -a --filter name={{{containerName}}} --format '{{.Names}}'
|
||||
```
|
||||
Expected: empty output.
|
||||
|
||||
output: "Cleanup result."
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "cleaned" }
|
||||
required: [$status]
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "cleanup_failed" }
|
||||
error: { type: string }
|
||||
required: [$status, error]
|
||||
|
||||
graph:
|
||||
$START:
|
||||
_: { role: "preparer", prompt: "Set up Docker environment for E2E testing. Repo at {{{repoPath}}}." }
|
||||
preparer:
|
||||
ready: { role: "tester", prompt: "Environment ready. Container: {{{containerName}}}, store: {{{storePath}}}. Run all test scenarios." }
|
||||
setup_failed: { role: "reporter", prompt: "Setup failures found. File these as bugs: {{{failures}}}" }
|
||||
tester:
|
||||
all_passed: { role: "cleanup", prompt: "All tests passed. Clean up container {{{containerName}}}." }
|
||||
bugs_found: { role: "reporter", prompt: "File these bugs as Gitea issues: {{{bugs}}}" }
|
||||
reporter:
|
||||
reported: { role: "cleanup", prompt: "Bugs filed: {{{issues}}}. Clean up container {{{containerName}}}." }
|
||||
partial: { role: "cleanup", prompt: "Filed {{{created}}} issues, {{{failed}}} failed. Clean up container {{{containerName}}}." }
|
||||
cleanup:
|
||||
cleaned: { role: "$END", prompt: "E2E check complete. Environment cleaned up." }
|
||||
cleanup_failed: { role: "$END", prompt: "E2E check complete but cleanup failed: {{{error}}}" }
|
||||
@@ -51,16 +51,19 @@ roles:
|
||||
output: "A findings report with per-issue root cause and suggested procedure fixes. Set $status to clean or findings (with report hash)."
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "clean" }
|
||||
summary: { type: string }
|
||||
required: [$status, summary]
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "findings" }
|
||||
report: { type: string }
|
||||
targetWorkflow: { type: string }
|
||||
required: [$status, report, targetWorkflow]
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "wrong_project" }
|
||||
workflowName: { type: string }
|
||||
required: [$status, workflowName]
|
||||
@@ -93,12 +96,14 @@ roles:
|
||||
output: "A change plan stored in CAS. Set $status to ready (with plan hash and repoPath) or no_action (if findings don't warrant changes)."
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "ready" }
|
||||
plan: { type: string }
|
||||
repoPath: { type: string }
|
||||
required: [$status, plan, repoPath]
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "no_action" }
|
||||
reason: { type: string }
|
||||
required: [$status, reason]
|
||||
@@ -128,12 +133,14 @@ roles:
|
||||
output: "List all files changed and provide a summary. Set $status to done (with branch/worktree), or failed (with reason)."
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "done" }
|
||||
branch: { type: string }
|
||||
worktree: { type: string }
|
||||
required: [$status, branch, worktree]
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "failed" }
|
||||
reason: { type: string }
|
||||
required: [$status, reason]
|
||||
@@ -157,12 +164,14 @@ roles:
|
||||
output: "Explain your decision. Set $status to approved (with branch/worktree) or rejected (with comments)."
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "approved" }
|
||||
branch: { type: string }
|
||||
worktree: { type: string }
|
||||
required: [$status, branch, worktree]
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "rejected" }
|
||||
comments: { type: string }
|
||||
worktree: { type: string }
|
||||
@@ -191,11 +200,13 @@ roles:
|
||||
output: "Include PR URL on success or error log on failure. Set $status to committed (with prUrl) or hook_failed (with error)."
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "committed" }
|
||||
prUrl: { type: string }
|
||||
required: [$status, prUrl]
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "hook_failed" }
|
||||
error: { type: string }
|
||||
required: [$status, error]
|
||||
|
||||
+22
-11
@@ -26,12 +26,14 @@ roles:
|
||||
output: "Output a brief summary of the test spec. Set $status to ready (with plan hash and repoPath) or insufficient_info."
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "ready" }
|
||||
plan: { type: string }
|
||||
repoPath: { type: string }
|
||||
required: [$status, plan, repoPath]
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "insufficient_info" }
|
||||
required: [$status]
|
||||
developer:
|
||||
@@ -67,12 +69,14 @@ roles:
|
||||
output: "List all files changed and provide a summary. Set $status to done (with branch/worktree), or failed (with reason)."
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "done" }
|
||||
branch: { type: string }
|
||||
worktree: { type: string }
|
||||
required: [$status, branch, worktree]
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "failed" }
|
||||
reason: { type: string }
|
||||
required: [$status, reason]
|
||||
@@ -105,12 +109,14 @@ roles:
|
||||
output: "Explain your decision with specific file/line references. Set $status to approved (with branch/worktree) or rejected (with comments)."
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "approved" }
|
||||
branch: { type: string }
|
||||
worktree: { type: string }
|
||||
required: [$status, branch, worktree]
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "rejected" }
|
||||
comments: { type: string }
|
||||
worktree: { type: string }
|
||||
@@ -133,16 +139,19 @@ roles:
|
||||
output: "Report test results per scenario. Set $status to passed (with branch/worktree), fix_code (with report), or fix_spec (with report)."
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "passed" }
|
||||
branch: { type: string }
|
||||
worktree: { type: string }
|
||||
required: [$status, branch, worktree]
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "fix_code" }
|
||||
report: { type: string }
|
||||
required: [$status, report]
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "fix_spec" }
|
||||
report: { type: string }
|
||||
required: [$status, report]
|
||||
@@ -169,11 +178,13 @@ roles:
|
||||
output: "Include PR URL on success or error log on failure. Set $status to committed (with prUrl) or hook_failed (with error)."
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "committed" }
|
||||
prUrl: { type: string }
|
||||
required: [$status, prUrl]
|
||||
- properties:
|
||||
- type: object
|
||||
properties:
|
||||
$status: { const: "hook_failed" }
|
||||
error: { type: string }
|
||||
required: [$status, error]
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
// Bun Snapshot v1, https://bun.sh/docs/test/snapshots
|
||||
|
||||
exports[`Phase 1: CAS Core 1.6 get returns node JSON (snapshot) 1`] = `
|
||||
{
|
||||
"payload": {
|
||||
"age": 30,
|
||||
"name": "Alice",
|
||||
},
|
||||
"type": "7XX5H51CVD9H0",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Phase 1: CAS Core 1.9 verify returns ok for valid node 1`] = `"ok"`;
|
||||
|
||||
exports[`Phase 1: CAS Core 1.10 refs lists direct references (snapshot) 1`] = `""`;
|
||||
|
||||
exports[`Phase 1: CAS Core 1.11 walk shows traversal tree (snapshot) 1`] = `"ERARPP19YJT05"`;
|
||||
|
||||
exports[`Phase 2: Schema Validation 2.3 put against non-existent schema hash fails 1`] = `"Schema not found: AAAAAAAAAAAAA"`;
|
||||
|
||||
exports[`Phase 3: Variable System 3.1 var set creates variable 1`] = `
|
||||
{
|
||||
"type": "E1D32N3GT69Q8",
|
||||
"value": {
|
||||
"labels": [],
|
||||
"name": "myapp/config",
|
||||
"schema": "7XX5H51CVD9H0",
|
||||
"tags": {},
|
||||
"value": "ERARPP19YJT05",
|
||||
},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Phase 3: Variable System 3.2 var get returns variable 1`] = `
|
||||
{
|
||||
"type": "E1D32N3GT69Q8",
|
||||
"value": {
|
||||
"labels": [],
|
||||
"name": "myapp/config",
|
||||
"schema": "7XX5H51CVD9H0",
|
||||
"tags": {},
|
||||
"value": "ERARPP19YJT05",
|
||||
},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Phase 3: Variable System 3.3 var list shows all variables 1`] = `
|
||||
{
|
||||
"type": "E1D32N3GT69Q8",
|
||||
"value": [
|
||||
{
|
||||
"labels": [],
|
||||
"name": "myapp/config",
|
||||
"schema": "7XX5H51CVD9H0",
|
||||
"tags": {},
|
||||
"value": "ERARPP19YJT05",
|
||||
},
|
||||
],
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Phase 3: Variable System 3.4 var list prefix filters by prefix 1`] = `
|
||||
{
|
||||
"type": "E1D32N3GT69Q8",
|
||||
"value": [
|
||||
{
|
||||
"labels": [],
|
||||
"name": "myapp/config",
|
||||
"schema": "7XX5H51CVD9H0",
|
||||
"tags": {},
|
||||
"value": "ERARPP19YJT05",
|
||||
},
|
||||
],
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Phase 3: Variable System 3.5 var set upsert updates existing variable 1`] = `
|
||||
{
|
||||
"type": "E1D32N3GT69Q8",
|
||||
"value": {
|
||||
"labels": [],
|
||||
"name": "myapp/config",
|
||||
"schema": "7XX5H51CVD9H0",
|
||||
"tags": {},
|
||||
"value": "F68P1BZ46YDXM",
|
||||
},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Phase 3: Variable System 3.6 var tag adds kv tag and label 1`] = `
|
||||
{
|
||||
"type": "E1D32N3GT69Q8",
|
||||
"value": {
|
||||
"labels": [
|
||||
"important",
|
||||
],
|
||||
"name": "myapp/config",
|
||||
"schema": "7XX5H51CVD9H0",
|
||||
"tags": {
|
||||
"env": "prod",
|
||||
},
|
||||
"value": "ERARPP19YJT05",
|
||||
},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Phase 3: Variable System 3.7 var list --tag env:prod filters by kv tag 1`] = `
|
||||
{
|
||||
"type": "E1D32N3GT69Q8",
|
||||
"value": [
|
||||
{
|
||||
"labels": [
|
||||
"important",
|
||||
],
|
||||
"name": "myapp/config",
|
||||
"schema": "7XX5H51CVD9H0",
|
||||
"tags": {
|
||||
"env": "prod",
|
||||
},
|
||||
"value": "ERARPP19YJT05",
|
||||
},
|
||||
],
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Phase 3: Variable System 3.8 var list --tag important filters by label 1`] = `
|
||||
{
|
||||
"type": "E1D32N3GT69Q8",
|
||||
"value": [
|
||||
{
|
||||
"labels": [
|
||||
"important",
|
||||
],
|
||||
"name": "myapp/config",
|
||||
"schema": "7XX5H51CVD9H0",
|
||||
"tags": {
|
||||
"env": "prod",
|
||||
},
|
||||
"value": "ERARPP19YJT05",
|
||||
},
|
||||
],
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Phase 3: Variable System 3.9 var tag remove deletes label 1`] = `
|
||||
{
|
||||
"type": "E1D32N3GT69Q8",
|
||||
"value": {
|
||||
"labels": [],
|
||||
"name": "myapp/config",
|
||||
"schema": "7XX5H51CVD9H0",
|
||||
"tags": {
|
||||
"env": "prod",
|
||||
},
|
||||
"value": "ERARPP19YJT05",
|
||||
},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Phase 3: Variable System 3.10 var delete removes variable 1`] = `
|
||||
{
|
||||
"type": "E1D32N3GT69Q8",
|
||||
"value": [
|
||||
{
|
||||
"labels": [],
|
||||
"name": "myapp/config",
|
||||
"schema": "7XX5H51CVD9H0",
|
||||
"tags": {
|
||||
"env": "prod",
|
||||
},
|
||||
"value": "ERARPP19YJT05",
|
||||
},
|
||||
],
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Phase 3: Variable System 3.11 var get deleted variable returns not found 1`] = `"Error: Variable not found: name=myapp/config, schema=7XX5H51CVD9H0"`;
|
||||
|
||||
exports[`Phase 4: Template System 4.1 template set registers template 1`] = `
|
||||
"{
|
||||
"schemaHash": "7XX5H51CVD9H0",
|
||||
"contentHash": "FC8WACA792B6F"
|
||||
}"
|
||||
`;
|
||||
|
||||
exports[`Phase 4: Template System 4.2 template get returns template text 1`] = `"Name: {{ payload.name }}, Age: {{ payload.age }}"`;
|
||||
|
||||
exports[`Phase 4: Template System 4.3 template list shows registered templates 1`] = `
|
||||
"[
|
||||
{
|
||||
"schemaHash": "7XX5H51CVD9H0",
|
||||
"preview": "Name: {{ payload.name }}, Age: {{ payload.age }}"
|
||||
}
|
||||
]"
|
||||
`;
|
||||
|
||||
exports[`Phase 4: Template System 4.4 template delete removes template 1`] = `
|
||||
"{
|
||||
"deleted": true
|
||||
}"
|
||||
`;
|
||||
|
||||
exports[`Phase 4: Template System 4.5 template get deleted template returns not found 1`] = `"Error: Template not found for schema: 7XX5H51CVD9H0"`;
|
||||
|
||||
exports[`Phase 5: Render 5.1 render fills payload variables 1`] = `"Hello Alice!"`;
|
||||
|
||||
exports[`Phase 5: Render 5.2 render --resolution with different value 1`] = `"Hello Alice!"`;
|
||||
|
||||
exports[`Phase 7: Edge Cases 7.1 get non-existent hash errors gracefully 1`] = `"Node not found: AAAAAAAAAAAAA"`;
|
||||
|
||||
exports[`Phase 7: Edge Cases 7.3 var set empty name errors 1`] = `"Usage: json-cas var set <name> <hash> [--tag <tag>...]"`;
|
||||
|
||||
exports[`Phase 7: Edge Cases 7.4 var set name with invalid chars errors 1`] = `"Error: Invalid variable name "invalid name!": Segment "invalid name!" contains invalid characters (only @, a-z, A-Z, 0-9, ., _, - allowed)"`;
|
||||
|
||||
exports[`Phase 7: Edge Cases 7.5 no subcommand shows help text 1`] = `
|
||||
"Usage: json-cas [--store <path>] [--json] <command> [args]
|
||||
|
||||
Commands:
|
||||
put <type-hash> <file.json> Store node, print hash
|
||||
get <hash> Print node as JSON
|
||||
has <hash> Print true/false
|
||||
verify <hash> Verify integrity + schema, print ok/corrupted/invalid
|
||||
refs <hash> List direct cas_ref edges
|
||||
walk <hash> [--format tree] Recursive traversal
|
||||
hash <type-hash> <file.json> Compute hash without storing (dry run)
|
||||
render <hash> [options] Render node as YAML with resolution decay
|
||||
render --pipe/-p [options] Render { type, value } from stdin
|
||||
list --type <hash-or-alias> List all hashes for a given type
|
||||
var set <name> <hash> [--tag <tag>...] Create/update a variable
|
||||
var get <name> --schema <hash> Get a variable by name + schema
|
||||
var delete <name> [--schema <hash>] Delete variable(s)
|
||||
var list [prefix] [--schema <hash>] [--tag <tag>...] List variables
|
||||
var tag <name> --schema <hash> <operations...> Modify tags/labels
|
||||
template set <schema-hash> <file> | --inline <text> Set template for schema
|
||||
template get <schema-hash> Get template content as raw text
|
||||
template list List all templates
|
||||
template delete <schema-hash> Delete template for schema
|
||||
gc Run garbage collection
|
||||
|
||||
Flags:
|
||||
--store <path> Store directory (default: ~/.uncaged/json-cas)
|
||||
--var-db <path> Variable database path (default: <store>/variables.db)
|
||||
--json Compact JSON output
|
||||
--schema <hash> Schema hash filter for var get/delete/tag/list
|
||||
--tag <tag> Tag/label (can be repeated): key:value (tag), name (label), :name (delete)
|
||||
--inline <text> Inline text content for template set
|
||||
--resolution <n> Initial resolution for render (default: 1.0)
|
||||
--decay <n> Decay factor for render (default: 0.5)
|
||||
--epsilon <n> Cutoff threshold for render (default: 0.01)
|
||||
--pipe, -p Read { type, value } JSON from stdin for render"
|
||||
`;
|
||||
@@ -1,11 +1,36 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import {
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import type { JSONSchema } from "@uncaged/json-cas";
|
||||
import { bootstrap, putSchema } from "@uncaged/json-cas";
|
||||
import { createFsStore, openStore as openFsStore } from "@uncaged/json-cas-fs";
|
||||
|
||||
const pkgPath = resolve(import.meta.dir, "../package.json");
|
||||
const entrypoint = resolve(import.meta.dir, "index.ts");
|
||||
|
||||
/**
|
||||
* Register a schema directly via the library (CLI schema put was removed).
|
||||
* Returns the type hash.
|
||||
*/
|
||||
async function putSchemaFile(
|
||||
storePath: string,
|
||||
schemaFilePath: string,
|
||||
): Promise<string> {
|
||||
const store = await openFsStore(storePath);
|
||||
const schema = JSON.parse(
|
||||
readFileSync(schemaFilePath, "utf-8"),
|
||||
) as JSONSchema;
|
||||
const hash = await putSchema(store, schema);
|
||||
return hash;
|
||||
}
|
||||
|
||||
async function runCli(
|
||||
args: string[],
|
||||
storePath?: string,
|
||||
@@ -23,6 +48,25 @@ async function runCli(
|
||||
return { stdout, stderr, exitCode };
|
||||
}
|
||||
|
||||
async function runCliWithStdin(
|
||||
args: string[],
|
||||
storePath: string,
|
||||
stdin: string,
|
||||
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
|
||||
const finalArgs = ["bun", entrypoint, "--store", storePath, ...args];
|
||||
const proc = Bun.spawn(finalArgs, {
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
stdin: "pipe",
|
||||
});
|
||||
proc.stdin.write(stdin);
|
||||
proc.stdin.end();
|
||||
const exitCode = await proc.exited;
|
||||
const stdout = await new Response(proc.stdout).text();
|
||||
const stderr = await new Response(proc.stderr).text();
|
||||
return { stdout, stderr, exitCode };
|
||||
}
|
||||
|
||||
describe("ucas command alias", () => {
|
||||
test("T1: ucas bin entry exists in package.json", async () => {
|
||||
const pkg = await Bun.file(pkgPath).json();
|
||||
@@ -109,86 +153,6 @@ async function runCliAlias(...args: string[]): Promise<{
|
||||
};
|
||||
}
|
||||
|
||||
describe("@ Alias Resolution - schema get", () => {
|
||||
test("ucas schema get @string should work", async () => {
|
||||
await runCliAlias("init"); // Initialize store
|
||||
|
||||
const { stdout, stderr, exitCode } = await runCliAlias(
|
||||
"schema",
|
||||
"get",
|
||||
"@string",
|
||||
);
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stderr).toBe("");
|
||||
const schema = JSON.parse(stdout);
|
||||
expect(schema).toEqual({ type: "string" });
|
||||
});
|
||||
|
||||
test("ucas schema get @number should work", async () => {
|
||||
await runCliAlias("init");
|
||||
|
||||
const { stdout, exitCode } = await runCliAlias("schema", "get", "@number");
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
const schema = JSON.parse(stdout);
|
||||
expect(schema).toEqual({ type: "number" });
|
||||
});
|
||||
|
||||
test("ucas schema get @object should work", async () => {
|
||||
await runCliAlias("init");
|
||||
|
||||
const { stdout, exitCode } = await runCliAlias("schema", "get", "@object");
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
const schema = JSON.parse(stdout);
|
||||
expect(schema).toEqual({ type: "object" });
|
||||
});
|
||||
|
||||
test("ucas schema get @array should work", async () => {
|
||||
await runCliAlias("init");
|
||||
|
||||
const { stdout, exitCode } = await runCliAlias("schema", "get", "@array");
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
const schema = JSON.parse(stdout);
|
||||
expect(schema).toEqual({ type: "array" });
|
||||
});
|
||||
|
||||
test("ucas schema get @bool should work", async () => {
|
||||
await runCliAlias("init");
|
||||
|
||||
const { stdout, exitCode } = await runCliAlias("schema", "get", "@bool");
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
const schema = JSON.parse(stdout);
|
||||
expect(schema).toEqual({ type: "boolean" });
|
||||
});
|
||||
|
||||
test("ucas schema get @schema should work", async () => {
|
||||
await runCliAlias("init");
|
||||
|
||||
const { stdout, exitCode } = await runCliAlias("schema", "get", "@schema");
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
const schema = JSON.parse(stdout);
|
||||
expect(schema).toHaveProperty("type", "object");
|
||||
expect(schema).toHaveProperty(
|
||||
"description",
|
||||
"json-cas JSON Schema meta-schema",
|
||||
);
|
||||
});
|
||||
|
||||
test("ucas schema get @invalid should fail gracefully", async () => {
|
||||
await runCliAlias("init");
|
||||
|
||||
const { stderr, exitCode } = await runCliAlias("schema", "get", "@invalid");
|
||||
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stderr).toContain("Schema not found");
|
||||
});
|
||||
});
|
||||
|
||||
describe("@ Alias Resolution - put", () => {
|
||||
test("ucas put @string <file> should resolve alias", async () => {
|
||||
await runCliAlias("init");
|
||||
@@ -287,13 +251,14 @@ describe("ucas render command", () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
const { exitCode, stdout } = await runCli(
|
||||
const { exitCode, stderr } = await runCli(
|
||||
["render", "ZZZZZZZZZZZZZ"],
|
||||
tmpStore,
|
||||
);
|
||||
// Missing hash renders as cas: reference
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toContain("cas:ZZZZZZZZZZZZZ");
|
||||
// Missing hash should exit with error
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stderr).toContain("Node not found");
|
||||
expect(stderr).toContain("ZZZZZZZZZZZZZ");
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
@@ -315,6 +280,555 @@ describe("ucas render command", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ---- Issue #50: Schema Validation in put Command ----
|
||||
|
||||
describe("Issue #50: Schema Validation in put", () => {
|
||||
describe("Test Group 1: Valid Data (Regression Tests)", () => {
|
||||
test("T1.1: Valid data matching schema should be accepted", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
// Create schema with required name property
|
||||
const schemaFile = join(tmpStore, "schema.json");
|
||||
writeFileSync(
|
||||
schemaFile,
|
||||
JSON.stringify({
|
||||
type: "object",
|
||||
properties: { name: { type: "string" } },
|
||||
required: ["name"],
|
||||
additionalProperties: false,
|
||||
}),
|
||||
);
|
||||
const schemaHash = await putSchemaFile(tmpStore, schemaFile);
|
||||
|
||||
// Create valid payload
|
||||
const payloadFile = join(tmpStore, "payload.json");
|
||||
writeFileSync(payloadFile, JSON.stringify({ name: "test" }));
|
||||
|
||||
const { stdout, stderr, exitCode } = await runCli(
|
||||
["put", schemaHash.trim(), payloadFile],
|
||||
tmpStore,
|
||||
);
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stderr).toBe("");
|
||||
expect(stdout.trim()).toMatch(/^[0-9A-HJKMNP-TV-Z]{13}$/);
|
||||
|
||||
// Verify node was stored
|
||||
const hash = stdout.trim();
|
||||
const { exitCode: hasExitCode } = await runCli(["has", hash], tmpStore);
|
||||
expect(hasExitCode).toBe(0);
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("T1.2: Valid data with optional properties should be accepted", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
// Schema with optional property
|
||||
const schemaFile = join(tmpStore, "schema.json");
|
||||
writeFileSync(
|
||||
schemaFile,
|
||||
JSON.stringify({
|
||||
type: "object",
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
age: { type: "number" },
|
||||
},
|
||||
required: ["name"],
|
||||
additionalProperties: false,
|
||||
}),
|
||||
);
|
||||
const schemaHash = await putSchemaFile(tmpStore, schemaFile);
|
||||
|
||||
// Payload with only required properties
|
||||
const payloadFile = join(tmpStore, "payload.json");
|
||||
writeFileSync(payloadFile, JSON.stringify({ name: "test" }));
|
||||
|
||||
const { exitCode, stdout } = await runCli(
|
||||
["put", schemaHash.trim(), payloadFile],
|
||||
tmpStore,
|
||||
);
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout.trim()).toMatch(/^[0-9A-HJKMNP-TV-Z]{13}$/);
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("T1.3: Valid data with nested objects should be accepted", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
// Schema with nested structure
|
||||
const schemaFile = join(tmpStore, "schema.json");
|
||||
writeFileSync(
|
||||
schemaFile,
|
||||
JSON.stringify({
|
||||
type: "object",
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
address: {
|
||||
type: "object",
|
||||
properties: {
|
||||
street: { type: "string" },
|
||||
city: { type: "string" },
|
||||
},
|
||||
},
|
||||
},
|
||||
additionalProperties: false,
|
||||
}),
|
||||
);
|
||||
const schemaHash = await putSchemaFile(tmpStore, schemaFile);
|
||||
|
||||
// Payload with nested structure
|
||||
const payloadFile = join(tmpStore, "payload.json");
|
||||
writeFileSync(
|
||||
payloadFile,
|
||||
JSON.stringify({
|
||||
name: "test",
|
||||
address: { street: "123 Main", city: "NYC" },
|
||||
}),
|
||||
);
|
||||
|
||||
const { exitCode, stdout } = await runCli(
|
||||
["put", schemaHash.trim(), payloadFile],
|
||||
tmpStore,
|
||||
);
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout.trim()).toMatch(/^[0-9A-HJKMNP-TV-Z]{13}$/);
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("T1.4: Valid data using @ alias for type-hash should be accepted", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
const payloadFile = join(tmpStore, "payload.json");
|
||||
writeFileSync(payloadFile, JSON.stringify("hello world"));
|
||||
|
||||
const { exitCode, stdout } = await runCli(
|
||||
["put", "@string", payloadFile],
|
||||
tmpStore,
|
||||
);
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout.trim()).toMatch(/^[0-9A-HJKMNP-TV-Z]{13}$/);
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Test Group 2: Type Mismatches (New Validation)", () => {
|
||||
test("T2.1: Wrong property type should be rejected", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
// Schema with name as string
|
||||
const schemaFile = join(tmpStore, "schema.json");
|
||||
writeFileSync(
|
||||
schemaFile,
|
||||
JSON.stringify({
|
||||
type: "object",
|
||||
properties: { name: { type: "string" } },
|
||||
required: ["name"],
|
||||
additionalProperties: false,
|
||||
}),
|
||||
);
|
||||
const schemaHash = await putSchemaFile(tmpStore, schemaFile);
|
||||
|
||||
// Payload with name as number
|
||||
const payloadFile = join(tmpStore, "payload.json");
|
||||
writeFileSync(payloadFile, JSON.stringify({ name: 123 }));
|
||||
|
||||
const { exitCode, stdout, stderr } = await runCli(
|
||||
["put", schemaHash.trim(), payloadFile],
|
||||
tmpStore,
|
||||
);
|
||||
|
||||
expect(exitCode).toBe(1);
|
||||
expect(stdout).toBe("");
|
||||
expect(stderr).toContain("Validation failed");
|
||||
expect(stderr).toContain(schemaHash.trim());
|
||||
expect(stderr).toContain(payloadFile);
|
||||
|
||||
// Verify no node was stored
|
||||
const { stdout: hasOutput } = await runCli(
|
||||
["has", "0000000000000"],
|
||||
tmpStore,
|
||||
);
|
||||
expect(hasOutput.trim()).toBe("false");
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("T2.2: Missing required property should be rejected", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
// Schema with required name
|
||||
const schemaFile = join(tmpStore, "schema.json");
|
||||
writeFileSync(
|
||||
schemaFile,
|
||||
JSON.stringify({
|
||||
type: "object",
|
||||
properties: { name: { type: "string" } },
|
||||
required: ["name"],
|
||||
additionalProperties: false,
|
||||
}),
|
||||
);
|
||||
const schemaHash = await putSchemaFile(tmpStore, schemaFile);
|
||||
|
||||
// Empty payload
|
||||
const payloadFile = join(tmpStore, "payload.json");
|
||||
writeFileSync(payloadFile, JSON.stringify({}));
|
||||
|
||||
const { exitCode, stderr } = await runCli(
|
||||
["put", schemaHash.trim(), payloadFile],
|
||||
tmpStore,
|
||||
);
|
||||
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stderr).toContain("Validation failed");
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("T2.3: Additional properties when disallowed should be rejected", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
// Schema with additionalProperties: false
|
||||
const schemaFile = join(tmpStore, "schema.json");
|
||||
writeFileSync(
|
||||
schemaFile,
|
||||
JSON.stringify({
|
||||
type: "object",
|
||||
properties: { name: { type: "string" } },
|
||||
additionalProperties: false,
|
||||
}),
|
||||
);
|
||||
const schemaHash = await putSchemaFile(tmpStore, schemaFile);
|
||||
|
||||
// Payload with extra property
|
||||
const payloadFile = join(tmpStore, "payload.json");
|
||||
writeFileSync(
|
||||
payloadFile,
|
||||
JSON.stringify({ name: "test", extra: "not allowed" }),
|
||||
);
|
||||
|
||||
const { exitCode, stderr } = await runCli(
|
||||
["put", schemaHash.trim(), payloadFile],
|
||||
tmpStore,
|
||||
);
|
||||
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stderr).toContain("Validation failed");
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("T2.4: Wrong root type should be rejected", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
// Schema expecting array
|
||||
const schemaFile = join(tmpStore, "schema.json");
|
||||
writeFileSync(
|
||||
schemaFile,
|
||||
JSON.stringify({
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
}),
|
||||
);
|
||||
const schemaHash = await putSchemaFile(tmpStore, schemaFile);
|
||||
|
||||
// Payload is an object
|
||||
const payloadFile = join(tmpStore, "payload.json");
|
||||
writeFileSync(payloadFile, JSON.stringify({}));
|
||||
|
||||
const { exitCode, stderr } = await runCli(
|
||||
["put", schemaHash.trim(), payloadFile],
|
||||
tmpStore,
|
||||
);
|
||||
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stderr).toContain("Validation failed");
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("T2.5: Nested type mismatch should be rejected", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
// Schema with nested object
|
||||
const schemaFile = join(tmpStore, "schema.json");
|
||||
writeFileSync(
|
||||
schemaFile,
|
||||
JSON.stringify({
|
||||
type: "object",
|
||||
properties: {
|
||||
user: {
|
||||
type: "object",
|
||||
properties: {
|
||||
age: { type: "number" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const schemaHash = await putSchemaFile(tmpStore, schemaFile);
|
||||
|
||||
// Payload with wrong nested type
|
||||
const payloadFile = join(tmpStore, "payload.json");
|
||||
writeFileSync(
|
||||
payloadFile,
|
||||
JSON.stringify({ user: { age: "not a number" } }),
|
||||
);
|
||||
|
||||
const { exitCode, stderr } = await runCli(
|
||||
["put", schemaHash.trim(), payloadFile],
|
||||
tmpStore,
|
||||
);
|
||||
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stderr).toContain("Validation failed");
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Test Group 3: Schema Errors (Edge Cases)", () => {
|
||||
test("T3.1: Non-existent type-hash should fail gracefully", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
const payloadFile = join(tmpStore, "payload.json");
|
||||
writeFileSync(payloadFile, JSON.stringify({ name: "test" }));
|
||||
|
||||
const { exitCode, stderr } = await runCli(
|
||||
["put", "ZZZZZZZZZZZZZ", payloadFile],
|
||||
tmpStore,
|
||||
);
|
||||
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stderr).toContain("Schema not found");
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("T3.3: Invalid @ alias should fail before validation", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
const payloadFile = join(tmpStore, "payload.json");
|
||||
writeFileSync(payloadFile, JSON.stringify({}));
|
||||
|
||||
const { exitCode, stderr } = await runCli(
|
||||
["put", "@nonexistent", payloadFile],
|
||||
tmpStore,
|
||||
);
|
||||
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stderr).toContain("Schema not found");
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Test Group 4: Integration with Existing Features", () => {
|
||||
test("T4.1: Hash command should not validate (dry-run consistency)", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
// Create schema
|
||||
const schemaFile = join(tmpStore, "schema.json");
|
||||
writeFileSync(
|
||||
schemaFile,
|
||||
JSON.stringify({
|
||||
type: "object",
|
||||
properties: { name: { type: "string" } },
|
||||
required: ["name"],
|
||||
additionalProperties: false,
|
||||
}),
|
||||
);
|
||||
const schemaHash = await putSchemaFile(tmpStore, schemaFile);
|
||||
|
||||
// Invalid payload
|
||||
const payloadFile = join(tmpStore, "payload.json");
|
||||
writeFileSync(payloadFile, JSON.stringify({ name: 123 }));
|
||||
|
||||
// Hash command should succeed even with invalid data
|
||||
const { exitCode, stdout } = await runCli(
|
||||
["hash", schemaHash.trim(), payloadFile],
|
||||
tmpStore,
|
||||
);
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout.trim()).toMatch(/^[0-9A-HJKMNP-TV-Z]{13}$/);
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("T4.2: Validation respects cas_ref format in schemas", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
// Schema with cas_ref format
|
||||
const schemaFile = join(tmpStore, "schema.json");
|
||||
writeFileSync(
|
||||
schemaFile,
|
||||
JSON.stringify({
|
||||
type: "object",
|
||||
properties: {
|
||||
ref: { type: "string", format: "cas_ref" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
const schemaHash = await putSchemaFile(tmpStore, schemaFile);
|
||||
|
||||
// Valid cas_ref
|
||||
const validFile = join(tmpStore, "valid.json");
|
||||
writeFileSync(validFile, JSON.stringify({ ref: "0000000000000" }));
|
||||
|
||||
const { exitCode: validExitCode } = await runCli(
|
||||
["put", schemaHash.trim(), validFile],
|
||||
tmpStore,
|
||||
);
|
||||
expect(validExitCode).toBe(0);
|
||||
|
||||
// Invalid cas_ref (wrong length)
|
||||
const invalidFile = join(tmpStore, "invalid.json");
|
||||
writeFileSync(invalidFile, JSON.stringify({ ref: "short" }));
|
||||
|
||||
const { exitCode: invalidExitCode, stderr } = await runCli(
|
||||
["put", schemaHash.trim(), invalidFile],
|
||||
tmpStore,
|
||||
);
|
||||
expect(invalidExitCode).not.toBe(0);
|
||||
expect(stderr).toContain("Validation failed");
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("T4.3: Schema self-validation still works", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
// Valid schema
|
||||
const schemaFile = join(tmpStore, "schema.json");
|
||||
writeFileSync(
|
||||
schemaFile,
|
||||
JSON.stringify({
|
||||
type: "object",
|
||||
properties: { name: { type: "string" } },
|
||||
}),
|
||||
);
|
||||
|
||||
const hash = await putSchemaFile(tmpStore, schemaFile);
|
||||
expect(hash).toMatch(/^[0-9A-HJKMNP-TV-Z]{13}$/);
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Test Group 5: Error Message Quality", () => {
|
||||
test("T5.1: Error message should be helpful", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
const schemaFile = join(tmpStore, "schema.json");
|
||||
writeFileSync(
|
||||
schemaFile,
|
||||
JSON.stringify({
|
||||
type: "object",
|
||||
properties: { name: { type: "string" } },
|
||||
required: ["name"],
|
||||
}),
|
||||
);
|
||||
const schemaHash = await putSchemaFile(tmpStore, schemaFile);
|
||||
|
||||
const payloadFile = join(tmpStore, "payload.json");
|
||||
writeFileSync(payloadFile, JSON.stringify({ name: 123 }));
|
||||
|
||||
const { stderr } = await runCli(
|
||||
["put", schemaHash.trim(), payloadFile],
|
||||
tmpStore,
|
||||
);
|
||||
|
||||
expect(stderr).toContain("Validation failed");
|
||||
expect(stderr).toContain(schemaHash.trim());
|
||||
expect(stderr).toContain(payloadFile);
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("T5.2: Error should go to stderr, not stdout", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
const schemaFile = join(tmpStore, "schema.json");
|
||||
writeFileSync(
|
||||
schemaFile,
|
||||
JSON.stringify({
|
||||
type: "object",
|
||||
properties: { name: { type: "string" } },
|
||||
}),
|
||||
);
|
||||
const schemaHash = await putSchemaFile(tmpStore, schemaFile);
|
||||
|
||||
const payloadFile = join(tmpStore, "payload.json");
|
||||
writeFileSync(payloadFile, JSON.stringify({ name: 123 }));
|
||||
|
||||
const { stdout, stderr } = await runCli(
|
||||
["put", schemaHash.trim(), payloadFile],
|
||||
tmpStore,
|
||||
);
|
||||
|
||||
expect(stdout).toBe("");
|
||||
expect(stderr.length).toBeGreaterThan(0);
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Suite 6: CLI Integration with Templates", () => {
|
||||
test("6.1 CLI with Template (Default Parameters)", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
@@ -331,10 +845,7 @@ describe("Suite 6: CLI Integration with Templates", () => {
|
||||
properties: { name: { type: "string" } },
|
||||
}),
|
||||
);
|
||||
const { stdout: schemaHash } = await runCli(
|
||||
["schema", "put", schemaFile],
|
||||
tmpStore,
|
||||
);
|
||||
const schemaHash = await putSchemaFile(tmpStore, schemaFile);
|
||||
|
||||
// Create node
|
||||
const nodeFile = join(tmpStore, "node.json");
|
||||
@@ -395,10 +906,7 @@ describe("Suite 6: CLI Integration with Templates", () => {
|
||||
},
|
||||
}),
|
||||
);
|
||||
const { stdout: schemaHash } = await runCli(
|
||||
["schema", "put", schemaFile],
|
||||
tmpStore,
|
||||
);
|
||||
const schemaHash = await putSchemaFile(tmpStore, schemaFile);
|
||||
|
||||
// Create child node
|
||||
const childFile = join(tmpStore, "child.json");
|
||||
@@ -467,10 +975,7 @@ describe("Suite 6: CLI Integration with Templates", () => {
|
||||
properties: { name: { type: "string" } },
|
||||
}),
|
||||
);
|
||||
const { stdout: schemaHash } = await runCli(
|
||||
["schema", "put", schemaFile],
|
||||
tmpStore,
|
||||
);
|
||||
const schemaHash = await putSchemaFile(tmpStore, schemaFile);
|
||||
|
||||
const nodeFile = join(tmpStore, "node.json");
|
||||
writeFileSync(nodeFile, JSON.stringify({ name: "Bob" }));
|
||||
@@ -534,10 +1039,7 @@ describe("Suite 6: CLI Integration with Templates", () => {
|
||||
properties: { name: { type: "string" } },
|
||||
}),
|
||||
);
|
||||
const { stdout: schemaHash } = await runCli(
|
||||
["schema", "put", schemaFile],
|
||||
tmpStore,
|
||||
);
|
||||
const schemaHash = await putSchemaFile(tmpStore, schemaFile);
|
||||
|
||||
const nodeFile = join(tmpStore, "node.json");
|
||||
writeFileSync(nodeFile, JSON.stringify({ name: "Charlie" }));
|
||||
@@ -573,10 +1075,7 @@ describe("Suite 6: CLI Integration with Templates", () => {
|
||||
properties: { name: { type: "string" } },
|
||||
}),
|
||||
);
|
||||
const { stdout: schemaHash } = await runCli(
|
||||
["schema", "put", schemaFile],
|
||||
tmpStore,
|
||||
);
|
||||
const schemaHash = await putSchemaFile(tmpStore, schemaFile);
|
||||
|
||||
const nodeFile = join(tmpStore, "node.json");
|
||||
writeFileSync(nodeFile, JSON.stringify({ name: "Test" }));
|
||||
@@ -596,4 +1095,109 @@ describe("Suite 6: CLI Integration with Templates", () => {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("R8: render with non-existent hash exits with error", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
const { exitCode, stderr, stdout } = await runCli(
|
||||
["render", "AAAAAAAAAAAAA"],
|
||||
tmpStore,
|
||||
);
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stderr).toContain("Node not found");
|
||||
expect(stderr).toContain("AAAAAAAAAAAAA");
|
||||
expect(stdout).toBe("");
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("R9: render with valid hash exits successfully", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
// Get @string type hash via bootstrap
|
||||
const store = createFsStore(tmpStore);
|
||||
const types = await bootstrap(store);
|
||||
const stringType = types["@string"];
|
||||
|
||||
// Create and store a simple string node
|
||||
const nodeFile = join(tmpStore, "test.json");
|
||||
writeFileSync(nodeFile, JSON.stringify("hello world"));
|
||||
const { stdout: nodeHash } = await runCli(
|
||||
["put", stringType, nodeFile],
|
||||
tmpStore,
|
||||
);
|
||||
|
||||
// Render the valid hash
|
||||
const { exitCode, stdout, stderr } = await runCli(
|
||||
["render", nodeHash.trim()],
|
||||
tmpStore,
|
||||
);
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toContain("hello world");
|
||||
expect(stderr).toBe("");
|
||||
expect(stdout).not.toContain("Error");
|
||||
expect(stdout).not.toContain("Node not found");
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("R10: render --pipe with valid envelope succeeds", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
// Get @string type hash via bootstrap
|
||||
const store = createFsStore(tmpStore);
|
||||
const types = await bootstrap(store);
|
||||
const stringType = types["@string"];
|
||||
|
||||
// Create envelope and pipe to render
|
||||
const envelope = JSON.stringify({ type: stringType, value: "test" });
|
||||
const { exitCode, stdout, stderr } = await runCliWithStdin(
|
||||
["render", "--pipe"],
|
||||
tmpStore,
|
||||
envelope,
|
||||
);
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toContain("test");
|
||||
expect(stderr).toBe("");
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("R11: render --pipe with invalid type hash still renders", async () => {
|
||||
const tmpStore = mkdtempSync(join(tmpdir(), "json-cas-test-"));
|
||||
try {
|
||||
await runCli(["init"], tmpStore);
|
||||
|
||||
// Use invalid type hash in envelope
|
||||
const envelope = JSON.stringify({
|
||||
type: "ZZZZZZZZZZZZZ",
|
||||
value: "test",
|
||||
});
|
||||
const { exitCode, stdout, stderr } = await runCliWithStdin(
|
||||
["render", "--pipe"],
|
||||
tmpStore,
|
||||
envelope,
|
||||
);
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toContain("test");
|
||||
expect(stderr).toBe("");
|
||||
} finally {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Store validation tests removed - with auto-bootstrap in Phase 1a,
|
||||
// stores are automatically created and bootstrapped when opened.
|
||||
// Issue #55 validation is no longer applicable.
|
||||
|
||||
@@ -0,0 +1,520 @@
|
||||
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
const entrypoint = resolve(import.meta.dir, "index.ts");
|
||||
|
||||
let tmpStore: string;
|
||||
let varDbPath: string;
|
||||
|
||||
// Shared hashes across phases
|
||||
let typeHash: string;
|
||||
let nodeHash: string;
|
||||
|
||||
beforeAll(() => {
|
||||
tmpStore = mkdtempSync(join(tmpdir(), "json-cas-e2e-"));
|
||||
varDbPath = join(tmpStore, "variables.db");
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
rmSync(tmpStore, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function runCli(
|
||||
args: string[],
|
||||
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
|
||||
const proc = Bun.spawn(
|
||||
["bun", entrypoint, "--store", tmpStore, "--var-db", varDbPath, ...args],
|
||||
{ stdout: "pipe", stderr: "pipe" },
|
||||
);
|
||||
const exitCode = await proc.exited;
|
||||
const stdout = (await new Response(proc.stdout).text()).trim();
|
||||
const stderr = (await new Response(proc.stderr).text()).trim();
|
||||
return { stdout, stderr, exitCode };
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse JSON and strip volatile fields (timestamp, created, updated)
|
||||
* so snapshots are stable across runs.
|
||||
*/
|
||||
function stripVolatile(json: string): unknown {
|
||||
const strip = (v: unknown): unknown => {
|
||||
if (Array.isArray(v)) return v.map(strip);
|
||||
if (v !== null && typeof v === "object") {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [k, val] of Object.entries(v as Record<string, unknown>)) {
|
||||
if (k === "timestamp" || k === "created" || k === "updated") continue;
|
||||
out[k] = strip(val);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
return v;
|
||||
};
|
||||
return strip(JSON.parse(json));
|
||||
}
|
||||
|
||||
// ---- Phase 1: CAS Core ----
|
||||
|
||||
describe("Phase 1: CAS Core", () => {
|
||||
test("1.1 init + put with @object bootstraps store", async () => {
|
||||
const schemaFile = join(tmpStore, "test-schema.json");
|
||||
writeFileSync(
|
||||
schemaFile,
|
||||
JSON.stringify({
|
||||
type: "object",
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
age: { type: "number" },
|
||||
},
|
||||
required: ["name"],
|
||||
additionalProperties: false,
|
||||
}),
|
||||
);
|
||||
// Use putSchema via the library to register schema, since CLI schema put is removed
|
||||
const { openStore: openFsStore } = await import("@uncaged/json-cas-fs");
|
||||
const { putSchema } = await import("@uncaged/json-cas");
|
||||
const store = await openFsStore(tmpStore);
|
||||
const hash = await putSchema(
|
||||
store,
|
||||
JSON.parse(readFileSync(schemaFile, "utf-8")),
|
||||
);
|
||||
typeHash = hash;
|
||||
expect(typeHash).toMatch(/^[0-9A-HJKMNP-TV-Z]{13}$/);
|
||||
});
|
||||
|
||||
test("1.5 put returns node hash", async () => {
|
||||
const nodeFile = join(tmpStore, "test-node.json");
|
||||
writeFileSync(nodeFile, JSON.stringify({ name: "Alice", age: 30 }));
|
||||
const { stdout, exitCode } = await runCli(["put", typeHash, nodeFile]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toMatch(/^[0-9A-HJKMNP-TV-Z]{13}$/);
|
||||
nodeHash = stdout;
|
||||
});
|
||||
|
||||
test("1.6 get returns node JSON (snapshot)", async () => {
|
||||
const { stdout, exitCode } = await runCli(["get", nodeHash]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stripVolatile(stdout)).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("1.7 has returns true for existing node", async () => {
|
||||
const { stdout, exitCode } = await runCli(["has", nodeHash]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toBe("true");
|
||||
});
|
||||
|
||||
test("1.8 has returns false for non-existing hash", async () => {
|
||||
const { stdout, exitCode } = await runCli(["has", "AAAAAAAAAAAAA"]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toBe("false");
|
||||
});
|
||||
|
||||
test("1.9 verify returns ok for valid node", async () => {
|
||||
const { stdout, exitCode } = await runCli(["verify", nodeHash]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("1.10 refs lists direct references (snapshot)", async () => {
|
||||
const { stdout, exitCode } = await runCli(["refs", nodeHash]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("1.11 walk shows traversal tree (snapshot)", async () => {
|
||||
const { stdout, exitCode } = await runCli(["walk", nodeHash]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("1.12 hash dry-run returns same hash as put", async () => {
|
||||
const nodeFile = join(tmpStore, "test-node.json");
|
||||
const { stdout, exitCode } = await runCli(["hash", typeHash, nodeFile]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toBe(nodeHash);
|
||||
});
|
||||
|
||||
test("1.13 list --type returns nodes of that type", async () => {
|
||||
const { stdout, exitCode } = await runCli(["list", "--type", typeHash]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toContain(nodeHash);
|
||||
});
|
||||
});
|
||||
|
||||
// ---- Phase 2: Schema Validation ----
|
||||
|
||||
describe("Phase 2: Schema Validation", () => {
|
||||
test("2.1 put {name:123} against string-schema fails with non-zero exit", async () => {
|
||||
const badFile = join(tmpStore, "bad-node.json");
|
||||
writeFileSync(badFile, JSON.stringify({ name: 123 }));
|
||||
const { stdout, stderr, exitCode } = await runCli([
|
||||
"put",
|
||||
typeHash,
|
||||
badFile,
|
||||
]);
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stdout).toBe("");
|
||||
expect(stderr).toContain("Validation failed");
|
||||
expect(stderr).toContain(typeHash);
|
||||
// Do NOT snapshot stderr — it embeds a machine-specific tmp path
|
||||
});
|
||||
|
||||
test("2.2 verify on valid node returns ok (hash + schema)", async () => {
|
||||
const { stdout, exitCode } = await runCli(["verify", nodeHash]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toBe("ok");
|
||||
});
|
||||
|
||||
test("2.3 put against non-existent schema hash fails", async () => {
|
||||
const nodeFile = join(tmpStore, "test-node.json");
|
||||
const { stderr, exitCode } = await runCli([
|
||||
"put",
|
||||
"AAAAAAAAAAAAA",
|
||||
nodeFile,
|
||||
]);
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stderr).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
// ---- Phase 3: Variable System ----
|
||||
|
||||
describe("Phase 3: Variable System", () => {
|
||||
test("3.1 var set creates variable", async () => {
|
||||
const { exitCode, stdout } = await runCli([
|
||||
"var",
|
||||
"set",
|
||||
"myapp/config",
|
||||
nodeHash,
|
||||
]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stripVolatile(stdout)).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("3.2 var get returns variable", async () => {
|
||||
const { stdout, exitCode } = await runCli([
|
||||
"var",
|
||||
"get",
|
||||
"myapp/config",
|
||||
"--schema",
|
||||
typeHash,
|
||||
]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stripVolatile(stdout)).toMatchSnapshot();
|
||||
expect(stdout).toContain(nodeHash);
|
||||
});
|
||||
|
||||
test("3.3 var list shows all variables", async () => {
|
||||
const { stdout, exitCode } = await runCli(["var", "list"]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stripVolatile(stdout)).toMatchSnapshot();
|
||||
expect(stdout).toContain("myapp/config");
|
||||
});
|
||||
|
||||
test("3.4 var list prefix filters by prefix", async () => {
|
||||
const { stdout, exitCode } = await runCli(["var", "list", "myapp/"]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stripVolatile(stdout)).toMatchSnapshot();
|
||||
expect(stdout).toContain("myapp/config");
|
||||
});
|
||||
|
||||
test("3.5 var set upsert updates existing variable", async () => {
|
||||
const node2File = join(tmpStore, "node2.json");
|
||||
writeFileSync(node2File, JSON.stringify({ name: "Bob", age: 25 }));
|
||||
const { stdout: node2Hash } = await runCli(["put", typeHash, node2File]);
|
||||
const { exitCode, stdout } = await runCli([
|
||||
"var",
|
||||
"set",
|
||||
"myapp/config",
|
||||
node2Hash.trim(),
|
||||
]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stripVolatile(stdout)).toMatchSnapshot();
|
||||
// Restore original value
|
||||
await runCli(["var", "set", "myapp/config", nodeHash]);
|
||||
});
|
||||
|
||||
test("3.6 var tag adds kv tag and label", async () => {
|
||||
const { exitCode, stdout } = await runCli([
|
||||
"var",
|
||||
"tag",
|
||||
"myapp/config",
|
||||
"--schema",
|
||||
typeHash,
|
||||
"env:prod",
|
||||
"important",
|
||||
]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stripVolatile(stdout)).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("3.7 var list --tag env:prod filters by kv tag", async () => {
|
||||
const { stdout, exitCode } = await runCli([
|
||||
"var",
|
||||
"list",
|
||||
"--tag",
|
||||
"env:prod",
|
||||
]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toContain("myapp/config");
|
||||
expect(stripVolatile(stdout)).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("3.8 var list --tag important filters by label", async () => {
|
||||
const { stdout, exitCode } = await runCli([
|
||||
"var",
|
||||
"list",
|
||||
"--tag",
|
||||
"important",
|
||||
]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toContain("myapp/config");
|
||||
expect(stripVolatile(stdout)).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("3.9 var tag remove deletes label", async () => {
|
||||
const { exitCode, stdout } = await runCli([
|
||||
"var",
|
||||
"tag",
|
||||
"myapp/config",
|
||||
"--schema",
|
||||
typeHash,
|
||||
":important",
|
||||
]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stripVolatile(stdout)).toMatchSnapshot();
|
||||
// Verify label is gone
|
||||
const { stdout: listOut } = await runCli([
|
||||
"var",
|
||||
"list",
|
||||
"--tag",
|
||||
"important",
|
||||
]);
|
||||
expect(listOut).not.toContain("myapp/config");
|
||||
});
|
||||
|
||||
test("3.10 var delete removes variable", async () => {
|
||||
const { exitCode, stdout } = await runCli([
|
||||
"var",
|
||||
"delete",
|
||||
"myapp/config",
|
||||
]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stripVolatile(stdout)).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("3.11 var get deleted variable returns not found", async () => {
|
||||
const { stderr, exitCode } = await runCli([
|
||||
"var",
|
||||
"get",
|
||||
"myapp/config",
|
||||
"--schema",
|
||||
typeHash,
|
||||
]);
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stderr).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
// ---- Phase 4: Template System ----
|
||||
|
||||
describe("Phase 4: Template System", () => {
|
||||
test("4.1 template set registers template", async () => {
|
||||
const tmplFile = join(tmpStore, "test.liquid");
|
||||
writeFileSync(tmplFile, "Name: {{ payload.name }}, Age: {{ payload.age }}");
|
||||
const { exitCode, stdout } = await runCli([
|
||||
"template",
|
||||
"set",
|
||||
typeHash,
|
||||
tmplFile,
|
||||
]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("4.2 template get returns template text", async () => {
|
||||
const { stdout, exitCode } = await runCli(["template", "get", typeHash]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toBe("Name: {{ payload.name }}, Age: {{ payload.age }}");
|
||||
expect(stdout).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("4.3 template list shows registered templates", async () => {
|
||||
const { stdout, exitCode } = await runCli(["template", "list"]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toContain(typeHash);
|
||||
expect(stdout).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("4.4 template delete removes template", async () => {
|
||||
const { exitCode, stdout } = await runCli(["template", "delete", typeHash]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("4.5 template get deleted template returns not found", async () => {
|
||||
const { stderr, exitCode } = await runCli(["template", "get", typeHash]);
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stderr).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
// ---- Phase 5: Render ----
|
||||
|
||||
describe("Phase 5: Render", () => {
|
||||
beforeAll(async () => {
|
||||
const tmplFile = join(tmpStore, "render-template.liquid");
|
||||
writeFileSync(tmplFile, "Hello {{ payload.name }}!");
|
||||
await runCli(["template", "set", typeHash, tmplFile]);
|
||||
});
|
||||
|
||||
test("5.1 render fills payload variables", async () => {
|
||||
const { stdout, exitCode } = await runCli(["render", nodeHash]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toBe("Hello Alice!");
|
||||
expect(stdout).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("5.2 render --resolution with different value", async () => {
|
||||
const { stdout, exitCode } = await runCli([
|
||||
"render",
|
||||
nodeHash,
|
||||
"--resolution",
|
||||
"0.5",
|
||||
]);
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stdout).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("5.3 render non-existent hash fails with error", async () => {
|
||||
const { stderr, exitCode } = await runCli(["render", "ZZZZZZZZZZZZZ"]);
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stderr).toContain("Node not found");
|
||||
expect(stderr).toContain("ZZZZZZZZZZZZZ");
|
||||
});
|
||||
});
|
||||
|
||||
// ---- Phase 6: GC ----
|
||||
|
||||
describe("Phase 6: GC", () => {
|
||||
let gcNodeHash: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
// Create a fresh node for GC tests (independent of shared nodeHash)
|
||||
const gcNodeFile = join(tmpStore, "gc-node.json");
|
||||
writeFileSync(gcNodeFile, JSON.stringify({ name: "GcAlice", age: 30 }));
|
||||
const { stdout } = await runCli(["put", typeHash, gcNodeFile]);
|
||||
gcNodeHash = stdout.trim();
|
||||
// Set a var referencing this node so it survives GC during Phase 6
|
||||
await runCli(["var", "set", "gc-test/ref", gcNodeHash]);
|
||||
});
|
||||
|
||||
test("6.1 gc runs without error", async () => {
|
||||
const { exitCode, stdout } = await runCli(["gc"]);
|
||||
expect(exitCode).toBe(0);
|
||||
// Assert structural shape only — exact counts depend on phase history
|
||||
const result = JSON.parse(stdout) as Record<string, unknown>;
|
||||
expect(typeof result.total).toBe("number");
|
||||
expect(typeof result.reachable).toBe("number");
|
||||
expect(typeof result.collected).toBe("number");
|
||||
expect(typeof result.scanned).toBe("number");
|
||||
expect(result.total as number).toBeGreaterThanOrEqual(
|
||||
result.reachable as number,
|
||||
);
|
||||
});
|
||||
|
||||
test("6.2 gc preserves node referenced by a var", async () => {
|
||||
const { exitCode } = await runCli(["gc"]);
|
||||
expect(exitCode).toBe(0);
|
||||
const { stdout } = await runCli(["has", gcNodeHash]);
|
||||
expect(stdout).toBe("true");
|
||||
});
|
||||
|
||||
test("6.3 gc reclaims orphan node", async () => {
|
||||
const orphanFile = join(tmpStore, "orphan.json");
|
||||
writeFileSync(orphanFile, JSON.stringify({ name: "Orphan", age: 99 }));
|
||||
const { stdout: orphanHashRaw } = await runCli([
|
||||
"put",
|
||||
typeHash,
|
||||
orphanFile,
|
||||
]);
|
||||
const orphanHash = orphanHashRaw.trim();
|
||||
|
||||
const { stdout: beforeGc } = await runCli(["has", orphanHash]);
|
||||
expect(beforeGc).toBe("true");
|
||||
|
||||
await runCli(["gc"]);
|
||||
const { stdout: afterGc } = await runCli(["has", orphanHash]);
|
||||
expect(afterGc).toBe("false");
|
||||
});
|
||||
});
|
||||
|
||||
// ---- Phase 7: Edge Cases ----
|
||||
|
||||
describe("Phase 7: Edge Cases", () => {
|
||||
test("7.1 get non-existent hash errors gracefully", async () => {
|
||||
const { stderr, exitCode } = await runCli(["get", "AAAAAAAAAAAAA"]);
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stderr).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("7.2 put with non-existent file errors with ENOENT", async () => {
|
||||
const { stderr, exitCode } = await runCli([
|
||||
"put",
|
||||
typeHash,
|
||||
"/nonexistent/file.json",
|
||||
]);
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stderr).toContain("ENOENT");
|
||||
});
|
||||
|
||||
test("7.3 var set empty name errors", async () => {
|
||||
const { stderr, exitCode } = await runCli(["var", "set", "", nodeHash]);
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stderr.length).toBeGreaterThan(0);
|
||||
expect(stderr).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("7.4 var set name with invalid chars errors", async () => {
|
||||
const { stderr, exitCode } = await runCli([
|
||||
"var",
|
||||
"set",
|
||||
"invalid name!",
|
||||
nodeHash,
|
||||
]);
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stderr.length).toBeGreaterThan(0);
|
||||
expect(stderr).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test("7.5 no subcommand shows help text", async () => {
|
||||
const { stdout, stderr, exitCode: _exitCode } = await runCli([]);
|
||||
const combined = stdout + stderr;
|
||||
expect(combined.length).toBeGreaterThan(0);
|
||||
expect(combined).toMatchSnapshot();
|
||||
expect(combined.toLowerCase()).toContain("usage");
|
||||
});
|
||||
|
||||
test("7.6 --store path is a file errors", async () => {
|
||||
const fileAsStore = join(tmpStore, "not-a-directory");
|
||||
writeFileSync(fileAsStore, "test");
|
||||
const proc = Bun.spawn(
|
||||
[
|
||||
"bun",
|
||||
entrypoint,
|
||||
"--store",
|
||||
fileAsStore,
|
||||
"--var-db",
|
||||
varDbPath,
|
||||
"get",
|
||||
"AAAAAAAAAAAAA",
|
||||
],
|
||||
{ stdout: "pipe", stderr: "pipe" },
|
||||
);
|
||||
const exitCode = await proc.exited;
|
||||
const stderr = (await new Response(proc.stderr).text()).trim();
|
||||
expect(exitCode).not.toBe(0);
|
||||
expect(stderr).toContain("not a directory");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import type { Hash, JSONSchema, Store, VariableStore } from "@uncaged/json-cas";
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
verify,
|
||||
walk,
|
||||
} from "@uncaged/json-cas";
|
||||
import { createFsStore } from "@uncaged/json-cas-fs";
|
||||
import { openStore as openFsStore } from "@uncaged/json-cas-fs";
|
||||
|
||||
// ---- Argument parsing ----
|
||||
|
||||
@@ -40,6 +40,7 @@ const VALUE_FLAGS = new Set([
|
||||
"decay",
|
||||
"epsilon",
|
||||
"inline",
|
||||
"type",
|
||||
]);
|
||||
|
||||
function parseArgs(argv: string[]): { flags: Flags; positional: string[] } {
|
||||
@@ -111,13 +112,17 @@ function readJsonFile(file: string): unknown {
|
||||
}
|
||||
}
|
||||
|
||||
function openStore(): Store {
|
||||
return createFsStore(resolve(storePath));
|
||||
/**
|
||||
* Open the filesystem-backed CAS store.
|
||||
* Automatically creates directory and bootstraps if needed.
|
||||
*/
|
||||
async function openStore(): Promise<Store> {
|
||||
const fullPath = resolve(storePath);
|
||||
return await openFsStore(fullPath);
|
||||
}
|
||||
|
||||
function openVarStore(): VariableStore {
|
||||
const store = openStore();
|
||||
mkdirSync(resolve(storePath), { recursive: true });
|
||||
async function openVarStore(): Promise<VariableStore> {
|
||||
const store = await openStore();
|
||||
return createVariableStore(resolve(varDbPath), store);
|
||||
}
|
||||
|
||||
@@ -128,7 +133,7 @@ function openVarStore(): VariableStore {
|
||||
*/
|
||||
async function resolveTypeHash(typeHashOrAlias: string): Promise<Hash> {
|
||||
if (typeHashOrAlias.startsWith("@")) {
|
||||
const store = openStore();
|
||||
const store = await openStore();
|
||||
const builtinSchemas = await bootstrap(store);
|
||||
const resolvedHash = builtinSchemas[typeHashOrAlias];
|
||||
if (!resolvedHash) {
|
||||
@@ -144,7 +149,7 @@ async function resolveTypeHash(typeHashOrAlias: string): Promise<Hash> {
|
||||
* This is the type hash used in JSON envelopes
|
||||
*/
|
||||
async function getVariableSchemaHash(): Promise<Hash> {
|
||||
const store = openStore();
|
||||
const store = await openStore();
|
||||
|
||||
// Define the Variable JSON Schema (updated for new model with composite key)
|
||||
const variableSchema: JSONSchema = {
|
||||
@@ -222,70 +227,6 @@ function parseTagsLabels(args: string[]): {
|
||||
|
||||
// ---- Commands ----
|
||||
|
||||
async function cmdInit(): Promise<void> {
|
||||
const dir = resolve(storePath);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const store = createFsStore(dir);
|
||||
const builtinSchemas = await bootstrap(store);
|
||||
const metaHash = builtinSchemas["@schema"];
|
||||
console.log(metaHash);
|
||||
}
|
||||
|
||||
async function cmdBootstrap(): Promise<void> {
|
||||
const store = openStore();
|
||||
const builtinSchemas = await bootstrap(store);
|
||||
const metaHash = builtinSchemas["@schema"];
|
||||
console.log(metaHash);
|
||||
}
|
||||
|
||||
async function cmdSchemaPut(args: string[]): Promise<void> {
|
||||
const file = args[0];
|
||||
if (!file) die("Usage: json-cas schema put <file.json>");
|
||||
const schema = readJsonFile(file) as JSONSchema;
|
||||
const store = openStore();
|
||||
const hash = await putSchema(store, schema);
|
||||
console.log(hash);
|
||||
}
|
||||
|
||||
async function cmdSchemaGet(args: string[]): Promise<void> {
|
||||
const hashOrAlias = args[0];
|
||||
if (!hashOrAlias) die("Usage: json-cas schema get <type-hash>");
|
||||
const hash = await resolveTypeHash(hashOrAlias);
|
||||
const store = openStore();
|
||||
const schema = getSchema(store, hash);
|
||||
if (schema === null) die(`Schema not found: ${hashOrAlias}`);
|
||||
out(schema);
|
||||
}
|
||||
|
||||
async function cmdSchemaList(): Promise<void> {
|
||||
const store = openStore();
|
||||
const builtinSchemas = await bootstrap(store);
|
||||
const metaHash = builtinSchemas["@schema"];
|
||||
if (!metaHash) throw new Error("Meta-schema not found");
|
||||
for (const hash of store.listByType(metaHash)) {
|
||||
if (hash === metaHash) continue;
|
||||
const node = store.get(hash);
|
||||
if (node !== null) {
|
||||
const schema = node.payload as JSONSchema;
|
||||
const name =
|
||||
(schema.title as string | undefined) ??
|
||||
(schema.description as string | undefined) ??
|
||||
"(unnamed)";
|
||||
console.log(`${hash} ${name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function cmdSchemaValidate(args: string[]): Promise<void> {
|
||||
const hash = args[0];
|
||||
if (!hash) die("Usage: json-cas schema validate <hash>");
|
||||
const store = openStore();
|
||||
const node = store.get(hash);
|
||||
if (node === null) die(`Node not found: ${hash}`);
|
||||
const valid = validate(store, node);
|
||||
console.log(valid ? "valid" : "invalid");
|
||||
}
|
||||
|
||||
async function cmdPut(args: string[]): Promise<void> {
|
||||
const typeHashOrAlias = args[0];
|
||||
const file = args[1];
|
||||
@@ -293,7 +234,24 @@ async function cmdPut(args: string[]): Promise<void> {
|
||||
die("Usage: json-cas put <type-hash> <file.json>");
|
||||
const typeHash = await resolveTypeHash(typeHashOrAlias);
|
||||
const payload = readJsonFile(file);
|
||||
const store = openStore();
|
||||
const store = await openStore();
|
||||
|
||||
// Check if schema exists
|
||||
const schema = getSchema(store, typeHash);
|
||||
if (schema === null) {
|
||||
console.error(`Schema not found: ${typeHash}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Validate payload against schema before storing
|
||||
const tempNode = { type: typeHash, payload, timestamp: Date.now() };
|
||||
if (!validate(store, tempNode)) {
|
||||
console.error(
|
||||
`Validation failed: payload in ${file} does not match schema ${typeHash}`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const hash = await store.put(typeHash, payload);
|
||||
console.log(hash);
|
||||
}
|
||||
@@ -301,7 +259,7 @@ async function cmdPut(args: string[]): Promise<void> {
|
||||
async function cmdGet(args: string[]): Promise<void> {
|
||||
const hash = args[0];
|
||||
if (!hash) die("Usage: json-cas get <hash>");
|
||||
const store = openStore();
|
||||
const store = await openStore();
|
||||
const node = store.get(hash);
|
||||
if (node === null) die(`Node not found: ${hash}`);
|
||||
out(node);
|
||||
@@ -310,24 +268,29 @@ async function cmdGet(args: string[]): Promise<void> {
|
||||
async function cmdHas(args: string[]): Promise<void> {
|
||||
const hash = args[0];
|
||||
if (!hash) die("Usage: json-cas has <hash>");
|
||||
const store = openStore();
|
||||
const store = await openStore();
|
||||
console.log(String(store.has(hash)));
|
||||
}
|
||||
|
||||
async function cmdVerify(args: string[]): Promise<void> {
|
||||
const hash = args[0];
|
||||
if (!hash) die("Usage: json-cas verify <hash>");
|
||||
const store = openStore();
|
||||
const store = await openStore();
|
||||
const node = store.get(hash);
|
||||
if (node === null) die(`Node not found: ${hash}`);
|
||||
const ok = await verify(hash, node);
|
||||
console.log(ok ? "ok" : "corrupted");
|
||||
if (!ok) {
|
||||
console.log("corrupted");
|
||||
} else {
|
||||
const valid = validate(store, node);
|
||||
console.log(valid ? "ok" : "invalid");
|
||||
}
|
||||
}
|
||||
|
||||
async function cmdRefs(args: string[]): Promise<void> {
|
||||
const hash = args[0];
|
||||
if (!hash) die("Usage: json-cas refs <hash>");
|
||||
const store = openStore();
|
||||
const store = await openStore();
|
||||
const node = store.get(hash);
|
||||
if (node === null) die(`Node not found: ${hash}`);
|
||||
const refHashes = refs(store, node);
|
||||
@@ -339,7 +302,7 @@ async function cmdRefs(args: string[]): Promise<void> {
|
||||
async function cmdWalk(args: string[]): Promise<void> {
|
||||
const hash = args[0];
|
||||
if (!hash) die("Usage: json-cas walk <hash> [--format tree]");
|
||||
const store = openStore();
|
||||
const store = await openStore();
|
||||
const format = flags.format;
|
||||
|
||||
if (format === "tree") {
|
||||
@@ -400,7 +363,7 @@ async function cmdRender(args: string[]): Promise<void> {
|
||||
);
|
||||
}
|
||||
|
||||
const store = openStore();
|
||||
const store = await openStore();
|
||||
|
||||
// Parse numeric options
|
||||
const resolution =
|
||||
@@ -475,7 +438,7 @@ async function cmdRender(args: string[]): Promise<void> {
|
||||
);
|
||||
process.stdout.write(output);
|
||||
} else {
|
||||
const varStore = openVarStore();
|
||||
const varStore = await openVarStore();
|
||||
const output = await renderAsync(store, hash, {
|
||||
resolution,
|
||||
decay,
|
||||
@@ -486,6 +449,9 @@ async function cmdRender(args: string[]): Promise<void> {
|
||||
process.stdout.write(output);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof CasNodeNotFoundError) {
|
||||
die(`Error: Node not found: ${error.hash}`);
|
||||
}
|
||||
if (error instanceof Error) {
|
||||
die(error.message);
|
||||
}
|
||||
@@ -493,19 +459,6 @@ async function cmdRender(args: string[]): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function cmdCat(args: string[]): Promise<void> {
|
||||
const hash = args[0];
|
||||
if (!hash) die("Usage: json-cas cat <hash>");
|
||||
const store = openStore();
|
||||
const node = store.get(hash);
|
||||
if (node === null) die(`Node not found: ${hash}`);
|
||||
if (flags.payload === true) {
|
||||
out(node.payload);
|
||||
} else {
|
||||
out(node);
|
||||
}
|
||||
}
|
||||
|
||||
async function cmdVarSet(args: string[]): Promise<void> {
|
||||
const name = args[0];
|
||||
const value = args[1];
|
||||
@@ -515,7 +468,7 @@ async function cmdVarSet(args: string[]): Promise<void> {
|
||||
die("Usage: json-cas var set <name> <hash> [--tag <tag>...]");
|
||||
}
|
||||
|
||||
const varStore = openVarStore();
|
||||
const varStore = await openVarStore();
|
||||
|
||||
try {
|
||||
// Parse tags/labels from --tag flags
|
||||
@@ -566,7 +519,7 @@ async function cmdVarGet(args: string[]): Promise<void> {
|
||||
die("Usage: json-cas var get <name> --schema <hash>");
|
||||
}
|
||||
|
||||
const varStore = openVarStore();
|
||||
const varStore = await openVarStore();
|
||||
|
||||
try {
|
||||
const variable = varStore.get(name, schema);
|
||||
@@ -588,7 +541,7 @@ async function cmdVarDelete(args: string[]): Promise<void> {
|
||||
die("Usage: json-cas var delete <name> [--schema <hash>]");
|
||||
}
|
||||
|
||||
const varStore = openVarStore();
|
||||
const varStore = await openVarStore();
|
||||
|
||||
try {
|
||||
if (schema !== undefined) {
|
||||
@@ -625,7 +578,7 @@ async function cmdVarTag(args: string[]): Promise<void> {
|
||||
die("Usage: json-cas var tag <name> --schema <hash> <operations...>");
|
||||
}
|
||||
|
||||
const varStore = openVarStore();
|
||||
const varStore = await openVarStore();
|
||||
|
||||
try {
|
||||
const { tags, labels, deleteNames } = parseTagsLabels(tagArgs);
|
||||
@@ -657,7 +610,7 @@ async function cmdVarList(args: string[]): Promise<void> {
|
||||
const schema = flags.schema as string | undefined;
|
||||
const tagFlags = flags.tag;
|
||||
|
||||
const varStore = openVarStore();
|
||||
const varStore = await openVarStore();
|
||||
|
||||
try {
|
||||
// Parse tags/labels from --tag flags
|
||||
@@ -699,8 +652,7 @@ async function cmdTemplateSet(args: string[]): Promise<void> {
|
||||
die("Usage: json-cas template set <schema-hash> <file> | --inline <text>");
|
||||
}
|
||||
|
||||
const store = openStore();
|
||||
mkdirSync(resolve(storePath), { recursive: true });
|
||||
const store = await openStore();
|
||||
const varStore = createVariableStore(resolve(varDbPath), store);
|
||||
|
||||
try {
|
||||
@@ -771,8 +723,7 @@ async function cmdTemplateGet(args: string[]): Promise<void> {
|
||||
die("Usage: json-cas template get <schema-hash>");
|
||||
}
|
||||
|
||||
const store = openStore();
|
||||
mkdirSync(resolve(storePath), { recursive: true });
|
||||
const store = await openStore();
|
||||
const varStore = createVariableStore(resolve(varDbPath), store);
|
||||
|
||||
try {
|
||||
@@ -798,8 +749,7 @@ async function cmdTemplateGet(args: string[]): Promise<void> {
|
||||
}
|
||||
|
||||
async function cmdTemplateList(_args: string[]): Promise<void> {
|
||||
const store = openStore();
|
||||
mkdirSync(resolve(storePath), { recursive: true });
|
||||
const store = await openStore();
|
||||
const varStore = createVariableStore(resolve(varDbPath), store);
|
||||
|
||||
try {
|
||||
@@ -839,8 +789,7 @@ async function cmdTemplateDelete(args: string[]): Promise<void> {
|
||||
die("Usage: json-cas template delete <schema-hash>");
|
||||
}
|
||||
|
||||
const store = openStore();
|
||||
mkdirSync(resolve(storePath), { recursive: true });
|
||||
const store = await openStore();
|
||||
const varStore = createVariableStore(resolve(varDbPath), store);
|
||||
|
||||
try {
|
||||
@@ -860,7 +809,7 @@ async function cmdTemplateDelete(args: string[]): Promise<void> {
|
||||
}
|
||||
|
||||
async function cmdGc(_args: string[]): Promise<void> {
|
||||
const store = createFsStore(storePath);
|
||||
const store = await openStore();
|
||||
const varStore = createVariableStore(varDbPath, store);
|
||||
|
||||
try {
|
||||
@@ -871,27 +820,32 @@ async function cmdGc(_args: string[]): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function cmdList(_args: string[]): Promise<void> {
|
||||
const typeFlag = flags.type;
|
||||
if (typeof typeFlag !== "string")
|
||||
die("Usage: json-cas list --type <hash-or-alias>");
|
||||
const typeHash = await resolveTypeHash(typeFlag);
|
||||
const store = await openStore();
|
||||
for (const hash of store.listByType(typeHash)) {
|
||||
console.log(hash);
|
||||
}
|
||||
}
|
||||
|
||||
function printUsage(): void {
|
||||
console.log(`\
|
||||
Usage: json-cas [--store <path>] [--json] <command> [args]
|
||||
|
||||
Commands:
|
||||
init Create store dir and write bootstrap seed
|
||||
bootstrap Write meta-schema seed, print hash
|
||||
schema put <file.json> Register schema, print type hash
|
||||
schema get <type-hash> Print schema JSON
|
||||
schema list List all schemas (name + hash)
|
||||
schema validate <hash> Validate node against its schema
|
||||
put <type-hash> <file.json> Store node, print hash
|
||||
get <hash> Print node as JSON
|
||||
has <hash> Print true/false
|
||||
verify <hash> Verify integrity, print ok/corrupted
|
||||
verify <hash> Verify integrity + schema, print ok/corrupted/invalid
|
||||
refs <hash> List direct cas_ref edges
|
||||
walk <hash> [--format tree] Recursive traversal
|
||||
hash <type-hash> <file.json> Compute hash without storing (dry run)
|
||||
render <hash> [options] Render node as YAML with resolution decay
|
||||
render --pipe/-p [options] Render { type, value } from stdin
|
||||
cat <hash> [--payload] Output node (--payload for payload only)
|
||||
list --type <hash-or-alias> List all hashes for a given type
|
||||
var set <name> <hash> [--tag <tag>...] Create/update a variable
|
||||
var get <name> --schema <hash> Get a variable by name + schema
|
||||
var delete <name> [--schema <hash>] Delete variable(s)
|
||||
@@ -926,35 +880,6 @@ if (!cmd) {
|
||||
}
|
||||
|
||||
switch (cmd) {
|
||||
case "init":
|
||||
await cmdInit();
|
||||
break;
|
||||
|
||||
case "bootstrap":
|
||||
await cmdBootstrap();
|
||||
break;
|
||||
|
||||
case "schema": {
|
||||
const [sub, ...subRest] = rest;
|
||||
switch (sub) {
|
||||
case "put":
|
||||
await cmdSchemaPut(subRest);
|
||||
break;
|
||||
case "get":
|
||||
await cmdSchemaGet(subRest);
|
||||
break;
|
||||
case "list":
|
||||
await cmdSchemaList();
|
||||
break;
|
||||
case "validate":
|
||||
await cmdSchemaValidate(subRest);
|
||||
break;
|
||||
default:
|
||||
die(`Unknown schema subcommand: ${sub ?? "(none)"}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "put":
|
||||
await cmdPut(rest);
|
||||
break;
|
||||
@@ -987,8 +912,8 @@ switch (cmd) {
|
||||
await cmdRender(rest);
|
||||
break;
|
||||
|
||||
case "cat":
|
||||
await cmdCat(rest);
|
||||
case "list":
|
||||
await cmdList(rest);
|
||||
break;
|
||||
|
||||
case "var": {
|
||||
|
||||
@@ -1 +1 @@
|
||||
export { createFsStore } from "./store.js";
|
||||
export { createFsStore, openStore } from "./store.js";
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs";
|
||||
import {
|
||||
existsSync,
|
||||
mkdtempSync,
|
||||
readdirSync,
|
||||
rmSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { CasNode } from "@uncaged/json-cas";
|
||||
@@ -10,7 +16,7 @@ import {
|
||||
verify,
|
||||
} from "@uncaged/json-cas";
|
||||
|
||||
import { createFsStore } from "./store.js";
|
||||
import { createFsStore, openStore } from "./store.js";
|
||||
|
||||
function makeTmpDir(): string {
|
||||
return mkdtempSync(join(tmpdir(), "json-cas-fs-test-"));
|
||||
@@ -312,3 +318,114 @@ describe("createFsStore – verify on disk-loaded nodes", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
// openStore – async with auto-bootstrap
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
describe("openStore – async with auto-bootstrap", () => {
|
||||
let dir: string;
|
||||
beforeEach(() => {
|
||||
dir = makeTmpDir();
|
||||
});
|
||||
afterEach(() => {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("openStore returns Promise<Store>", async () => {
|
||||
const store = await openStore(dir);
|
||||
expect(store).toBeDefined();
|
||||
expect(typeof store.put).toBe("function");
|
||||
expect(typeof store.get).toBe("function");
|
||||
});
|
||||
|
||||
test("openStore auto-creates directory when it doesn't exist", async () => {
|
||||
const nested = join(dir, "sub", "nested", "store");
|
||||
expect(existsSync(nested)).toBe(false);
|
||||
|
||||
const store = await openStore(nested);
|
||||
expect(existsSync(nested)).toBe(true);
|
||||
|
||||
// Verify store works
|
||||
const typeHash = await computeSelfHash({ name: "t" });
|
||||
const hash = await store.put(typeHash, { x: 1 });
|
||||
expect(store.has(hash)).toBe(true);
|
||||
});
|
||||
|
||||
test("openStore works when directory already exists", async () => {
|
||||
// Pre-create the directory
|
||||
const store1 = await openStore(dir);
|
||||
const typeHash = await computeSelfHash({ name: "t" });
|
||||
await store1.put(typeHash, { x: 1 });
|
||||
|
||||
// Open again
|
||||
const store2 = await openStore(dir);
|
||||
expect(store2.listByType(typeHash)).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("openStore throws error when path exists but is not a directory", async () => {
|
||||
const filePath = join(dir, "not-a-dir");
|
||||
writeFileSync(filePath, "test");
|
||||
|
||||
await expect(openStore(filePath)).rejects.toThrow();
|
||||
});
|
||||
|
||||
test("openStore auto-bootstraps on first open (empty directory)", async () => {
|
||||
const store = await openStore(dir);
|
||||
|
||||
// Check that bootstrap schemas exist
|
||||
const builtinSchemas = await bootstrap(store);
|
||||
const metaHash = builtinSchemas["@schema"];
|
||||
|
||||
expect(metaHash).toBeDefined();
|
||||
expect(store.has(metaHash as string)).toBe(true);
|
||||
|
||||
// Verify all core schemas exist
|
||||
expect(store.has(builtinSchemas["@string"] as string)).toBe(true);
|
||||
expect(store.has(builtinSchemas["@number"] as string)).toBe(true);
|
||||
expect(store.has(builtinSchemas["@object"] as string)).toBe(true);
|
||||
expect(store.has(builtinSchemas["@array"] as string)).toBe(true);
|
||||
expect(store.has(builtinSchemas["@bool"] as string)).toBe(true);
|
||||
expect(store.has(builtinSchemas["@schema"] as string)).toBe(true);
|
||||
});
|
||||
|
||||
test("openStore bootstrap is idempotent on subsequent opens", async () => {
|
||||
const store1 = await openStore(dir);
|
||||
const schemas1 = await bootstrap(store1);
|
||||
const count1 = store1.listAll().length;
|
||||
|
||||
const store2 = await openStore(dir);
|
||||
const schemas2 = await bootstrap(store2);
|
||||
const count2 = store2.listAll().length;
|
||||
|
||||
// Same schemas, same count
|
||||
expect(schemas1).toEqual(schemas2);
|
||||
expect(count1).toBe(count2);
|
||||
});
|
||||
|
||||
test("openStore works on already-bootstrapped store", async () => {
|
||||
// Bootstrap manually first
|
||||
const store1 = createFsStore(dir);
|
||||
const schemas1 = await bootstrap(store1);
|
||||
|
||||
// Open with openStore
|
||||
const store2 = await openStore(dir);
|
||||
const schemas2 = await bootstrap(store2);
|
||||
|
||||
expect(schemas1).toEqual(schemas2);
|
||||
});
|
||||
|
||||
test("openStore auto-bootstraps old store without bootstrap", async () => {
|
||||
// Create a store with some data but no bootstrap
|
||||
const store1 = createFsStore(dir);
|
||||
const typeHash = await computeSelfHash({ name: "custom" });
|
||||
await store1.put(typeHash, { data: "old" });
|
||||
|
||||
// Open with openStore - should auto-bootstrap
|
||||
const store2 = await openStore(dir);
|
||||
const schemas = await bootstrap(store2);
|
||||
|
||||
expect(store2.has(schemas["@schema"] as string)).toBe(true);
|
||||
// Old data still exists
|
||||
expect(store2.listByType(typeHash)).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
renameSync,
|
||||
statSync,
|
||||
unlinkSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
@@ -13,6 +14,7 @@ import type { BootstrapCapableStore, CasNode, Hash } from "@uncaged/json-cas";
|
||||
|
||||
import {
|
||||
BOOTSTRAP_STORE,
|
||||
bootstrap,
|
||||
cborEncode,
|
||||
computeHash,
|
||||
computeSelfHash,
|
||||
@@ -219,3 +221,57 @@ export function createFsStore(dir: string): BootstrapCapableStore {
|
||||
|
||||
return store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a filesystem-backed CAS store with automatic directory creation and bootstrap.
|
||||
* This is an async function that:
|
||||
* 1. Creates the directory (with recursive: true) if it doesn't exist
|
||||
* 2. Validates that the path is actually a directory (not a file)
|
||||
* 3. Creates the store
|
||||
* 4. Runs bootstrap (which is idempotent)
|
||||
*
|
||||
* @param dir - The directory path for the store
|
||||
* @returns A Promise resolving to the BootstrapCapableStore
|
||||
* @throws Error if the path exists but is not a directory
|
||||
*/
|
||||
export async function openStore(dir: string): Promise<BootstrapCapableStore> {
|
||||
// Create directory if it doesn't exist
|
||||
try {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
} catch (error) {
|
||||
if (error instanceof Error && "code" in error) {
|
||||
const nodeError = error as NodeJS.ErrnoException;
|
||||
if (nodeError.code === "EACCES") {
|
||||
throw new Error(`Permission denied: cannot access store at ${dir}`);
|
||||
}
|
||||
if (nodeError.code === "ENOTDIR") {
|
||||
throw new Error(`Path exists but is not a directory: ${dir}`);
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Validate that the path is a directory
|
||||
try {
|
||||
const stats = statSync(dir);
|
||||
if (!stats.isDirectory()) {
|
||||
throw new Error(`Path exists but is not a directory: ${dir}`);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof Error && "code" in error) {
|
||||
const nodeError = error as NodeJS.ErrnoException;
|
||||
if (nodeError.code === "ENOENT") {
|
||||
throw new Error(`Store not found at ${dir}`);
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Create the store
|
||||
const store = createFsStore(dir);
|
||||
|
||||
// Bootstrap (idempotent)
|
||||
await bootstrap(store);
|
||||
|
||||
return store;
|
||||
}
|
||||
|
||||
@@ -1241,3 +1241,609 @@ describe("Suite 8: Performance & Scalability", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Suite 9: E2E Template Variable Rendering (Issue #52)", () => {
|
||||
test("9.1 Direct Property Access - Should Render Empty", async () => {
|
||||
const { store, varStore, cleanup } = await createTempVarStore();
|
||||
|
||||
try {
|
||||
// Create schema for person object
|
||||
const personSchema = await putSchema(store, {
|
||||
type: "object",
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
age: { type: "number" },
|
||||
},
|
||||
});
|
||||
|
||||
// Create node with data
|
||||
const personHash = await store.put(personSchema, {
|
||||
name: "Alice",
|
||||
age: 30,
|
||||
});
|
||||
|
||||
// Register template using direct property access (incorrect syntax)
|
||||
const templateSchema = await putSchema(store, { type: "string" });
|
||||
const templateHash = await store.put(
|
||||
templateSchema,
|
||||
"Name: {{ name }}, Age: {{ age }}",
|
||||
);
|
||||
varStore.set(`@ucas/template/text/${personSchema}`, templateHash);
|
||||
|
||||
// Render - should produce empty values
|
||||
const output = await renderWithTemplate(store, varStore, personHash, {
|
||||
resolution: 1.0,
|
||||
decay: 0.5,
|
||||
epsilon: 0.01,
|
||||
});
|
||||
|
||||
expect(output).toBe("Name: , Age: ");
|
||||
} finally {
|
||||
varStore.close();
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("9.2 Correct Syntax with payload Prefix", async () => {
|
||||
const { store, varStore, cleanup } = await createTempVarStore();
|
||||
|
||||
try {
|
||||
// Create schema for person object
|
||||
const personSchema = await putSchema(store, {
|
||||
type: "object",
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
age: { type: "number" },
|
||||
},
|
||||
});
|
||||
|
||||
// Create node with data
|
||||
const personHash = await store.put(personSchema, {
|
||||
name: "Alice",
|
||||
age: 30,
|
||||
});
|
||||
|
||||
// Register template using correct payload. prefix
|
||||
const templateSchema = await putSchema(store, { type: "string" });
|
||||
const templateHash = await store.put(
|
||||
templateSchema,
|
||||
"Name: {{ payload.name }}, Age: {{ payload.age }}",
|
||||
);
|
||||
varStore.set(`@ucas/template/text/${personSchema}`, templateHash);
|
||||
|
||||
// Render - should produce correct values
|
||||
const output = await renderWithTemplate(store, varStore, personHash, {
|
||||
resolution: 1.0,
|
||||
decay: 0.5,
|
||||
epsilon: 0.01,
|
||||
});
|
||||
|
||||
expect(output).toBe("Name: Alice, Age: 30");
|
||||
} finally {
|
||||
varStore.close();
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("9.3 CLI Render Command - Template Variable Access", async () => {
|
||||
const { store, varStore, cleanup } = await createTempVarStore();
|
||||
|
||||
try {
|
||||
// Create schema and node
|
||||
const personSchema = await putSchema(store, {
|
||||
type: "object",
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
age: { type: "number" },
|
||||
},
|
||||
});
|
||||
|
||||
const personHash = await store.put(personSchema, {
|
||||
name: "Bob",
|
||||
age: 25,
|
||||
});
|
||||
|
||||
// Register template
|
||||
const templateSchema = await putSchema(store, { type: "string" });
|
||||
const templateHash = await store.put(
|
||||
templateSchema,
|
||||
"User: {{ payload.name }}, Age: {{ payload.age }}",
|
||||
);
|
||||
varStore.set(`@ucas/template/text/${personSchema}`, templateHash);
|
||||
|
||||
// This simulates the CLI flow
|
||||
const output = await renderWithTemplate(store, varStore, personHash, {
|
||||
resolution: 1.0,
|
||||
decay: 0.5,
|
||||
epsilon: 0.01,
|
||||
});
|
||||
|
||||
expect(output).toContain("User: Bob");
|
||||
expect(output).toContain("Age: 25");
|
||||
} finally {
|
||||
varStore.close();
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("9.4 Top-Level Primitive Payload - String", async () => {
|
||||
const { store, varStore, cleanup } = await createTempVarStore();
|
||||
|
||||
try {
|
||||
// Create schema for simple string
|
||||
const stringSchema = await putSchema(store, { type: "string" });
|
||||
|
||||
// Create node with string payload
|
||||
const stringHash = await store.put(stringSchema, "Hello World");
|
||||
|
||||
// Register template
|
||||
const templateSchema = await putSchema(store, { type: "string" });
|
||||
const templateHash = await store.put(
|
||||
templateSchema,
|
||||
"Value is: {{ payload }}",
|
||||
);
|
||||
varStore.set(`@ucas/template/text/${stringSchema}`, templateHash);
|
||||
|
||||
// Render
|
||||
const output = await renderWithTemplate(store, varStore, stringHash, {
|
||||
resolution: 1.0,
|
||||
decay: 0.5,
|
||||
epsilon: 0.01,
|
||||
});
|
||||
|
||||
expect(output).toBe("Value is: Hello World");
|
||||
} finally {
|
||||
varStore.close();
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("9.5 Top-Level Primitive Payload - Number", async () => {
|
||||
const { store, varStore, cleanup } = await createTempVarStore();
|
||||
|
||||
try {
|
||||
// Create schema for number
|
||||
const numberSchema = await putSchema(store, { type: "number" });
|
||||
|
||||
// Create node with number payload
|
||||
const numberHash = await store.put(numberSchema, 42);
|
||||
|
||||
// Register template
|
||||
const templateSchema = await putSchema(store, { type: "string" });
|
||||
const templateHash = await store.put(
|
||||
templateSchema,
|
||||
"The answer is {{ payload }}",
|
||||
);
|
||||
varStore.set(`@ucas/template/text/${numberSchema}`, templateHash);
|
||||
|
||||
// Render
|
||||
const output = await renderWithTemplate(store, varStore, numberHash, {
|
||||
resolution: 1.0,
|
||||
decay: 0.5,
|
||||
epsilon: 0.01,
|
||||
});
|
||||
|
||||
expect(output).toBe("The answer is 42");
|
||||
} finally {
|
||||
varStore.close();
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("9.6 Nested Object Property Access", async () => {
|
||||
const { store, varStore, cleanup } = await createTempVarStore();
|
||||
|
||||
try {
|
||||
// Create schema for nested object
|
||||
const userSchema = await putSchema(store, {
|
||||
type: "object",
|
||||
properties: {
|
||||
user: {
|
||||
type: "object",
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
address: {
|
||||
type: "object",
|
||||
properties: {
|
||||
city: { type: "string" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Create node with nested data
|
||||
const userHash = await store.put(userSchema, {
|
||||
user: {
|
||||
name: "Bob",
|
||||
address: {
|
||||
city: "NYC",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Register template with deep property access
|
||||
const templateSchema = await putSchema(store, { type: "string" });
|
||||
const templateHash = await store.put(
|
||||
templateSchema,
|
||||
"User {{ payload.user.name }} lives in {{ payload.user.address.city }}",
|
||||
);
|
||||
varStore.set(`@ucas/template/text/${userSchema}`, templateHash);
|
||||
|
||||
// Render
|
||||
const output = await renderWithTemplate(store, varStore, userHash, {
|
||||
resolution: 1.0,
|
||||
decay: 0.5,
|
||||
epsilon: 0.01,
|
||||
});
|
||||
|
||||
expect(output).toBe("User Bob lives in NYC");
|
||||
} finally {
|
||||
varStore.close();
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("9.7 Array Property Access and Iteration", async () => {
|
||||
const { store, varStore, cleanup } = await createTempVarStore();
|
||||
|
||||
try {
|
||||
// Create schema with array
|
||||
const tagsSchema = await putSchema(store, {
|
||||
type: "object",
|
||||
properties: {
|
||||
tags: {
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Create node with array data
|
||||
const tagsHash = await store.put(tagsSchema, {
|
||||
tags: ["javascript", "typescript", "bun"],
|
||||
});
|
||||
|
||||
// Register template with array iteration
|
||||
const templateSchema = await putSchema(store, { type: "string" });
|
||||
const templateHash = await store.put(
|
||||
templateSchema,
|
||||
"Tags: {% for tag in payload.tags %}{{ tag }}{% unless forloop.last %}, {% endunless %}{% endfor %}",
|
||||
);
|
||||
varStore.set(`@ucas/template/text/${tagsSchema}`, templateHash);
|
||||
|
||||
// Render
|
||||
const output = await renderWithTemplate(store, varStore, tagsHash, {
|
||||
resolution: 1.0,
|
||||
decay: 0.5,
|
||||
epsilon: 0.01,
|
||||
});
|
||||
|
||||
expect(output).toBe("Tags: javascript, typescript, bun");
|
||||
} finally {
|
||||
varStore.close();
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("9.8 Missing Property Access - Graceful Handling", async () => {
|
||||
const { store, varStore, cleanup } = await createTempVarStore();
|
||||
|
||||
try {
|
||||
// Create schema
|
||||
const personSchema = await putSchema(store, {
|
||||
type: "object",
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
},
|
||||
});
|
||||
|
||||
// Create node without age property
|
||||
const personHash = await store.put(personSchema, {
|
||||
name: "Alice",
|
||||
});
|
||||
|
||||
// Register template that references missing property
|
||||
const templateSchema = await putSchema(store, { type: "string" });
|
||||
const templateHash = await store.put(
|
||||
templateSchema,
|
||||
"Name: {{ payload.name }}, Age: {{ payload.age }}",
|
||||
);
|
||||
varStore.set(`@ucas/template/text/${personSchema}`, templateHash);
|
||||
|
||||
// Render - age should be empty
|
||||
const output = await renderWithTemplate(store, varStore, personHash, {
|
||||
resolution: 1.0,
|
||||
decay: 0.5,
|
||||
epsilon: 0.01,
|
||||
});
|
||||
|
||||
expect(output).toBe("Name: Alice, Age: ");
|
||||
} finally {
|
||||
varStore.close();
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("9.9 Null Property Value Rendering", async () => {
|
||||
const { store, varStore, cleanup } = await createTempVarStore();
|
||||
|
||||
try {
|
||||
// Create schema allowing null
|
||||
const personSchema = await putSchema(store, {
|
||||
type: "object",
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
email: { type: ["string", "null"] },
|
||||
},
|
||||
});
|
||||
|
||||
// Create node with null email
|
||||
const personHash = await store.put(personSchema, {
|
||||
name: "Charlie",
|
||||
email: null,
|
||||
});
|
||||
|
||||
// Register template
|
||||
const templateSchema = await putSchema(store, { type: "string" });
|
||||
const templateHash = await store.put(
|
||||
templateSchema,
|
||||
"Name: {{ payload.name }}, Email: {{ payload.email }}",
|
||||
);
|
||||
varStore.set(`@ucas/template/text/${personSchema}`, templateHash);
|
||||
|
||||
// Render - email should be empty
|
||||
const output = await renderWithTemplate(store, varStore, personHash, {
|
||||
resolution: 1.0,
|
||||
decay: 0.5,
|
||||
epsilon: 0.01,
|
||||
});
|
||||
|
||||
expect(output).toBe("Name: Charlie, Email: ");
|
||||
} finally {
|
||||
varStore.close();
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("9.10 Boolean Property Rendering", async () => {
|
||||
const { store, varStore, cleanup } = await createTempVarStore();
|
||||
|
||||
try {
|
||||
// Create schema with boolean
|
||||
const userSchema = await putSchema(store, {
|
||||
type: "object",
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
active: { type: "boolean" },
|
||||
},
|
||||
});
|
||||
|
||||
// Create node with boolean
|
||||
const userHash = await store.put(userSchema, {
|
||||
name: "Dave",
|
||||
active: true,
|
||||
});
|
||||
|
||||
// Register template with conditional
|
||||
const templateSchema = await putSchema(store, { type: "string" });
|
||||
const templateHash = await store.put(
|
||||
templateSchema,
|
||||
"User {{ payload.name }} is {% if payload.active %}active{% else %}inactive{% endif %}",
|
||||
);
|
||||
varStore.set(`@ucas/template/text/${userSchema}`, templateHash);
|
||||
|
||||
// Render
|
||||
const output = await renderWithTemplate(store, varStore, userHash, {
|
||||
resolution: 1.0,
|
||||
decay: 0.5,
|
||||
epsilon: 0.01,
|
||||
});
|
||||
|
||||
expect(output).toBe("User Dave is active");
|
||||
} finally {
|
||||
varStore.close();
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("9.11 Zero and Empty String Values", async () => {
|
||||
const { store, varStore, cleanup } = await createTempVarStore();
|
||||
|
||||
try {
|
||||
// Create schema
|
||||
const dataSchema = await putSchema(store, {
|
||||
type: "object",
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
count: { type: "number" },
|
||||
},
|
||||
});
|
||||
|
||||
// Create node with empty string and zero
|
||||
const dataHash = await store.put(dataSchema, {
|
||||
name: "",
|
||||
count: 0,
|
||||
});
|
||||
|
||||
// Register template
|
||||
const templateSchema = await putSchema(store, { type: "string" });
|
||||
const templateHash = await store.put(
|
||||
templateSchema,
|
||||
"Name: '{{ payload.name }}', Count: {{ payload.count }}",
|
||||
);
|
||||
varStore.set(`@ucas/template/text/${dataSchema}`, templateHash);
|
||||
|
||||
// Render - zero and empty string should appear
|
||||
const output = await renderWithTemplate(store, varStore, dataHash, {
|
||||
resolution: 1.0,
|
||||
decay: 0.5,
|
||||
epsilon: 0.01,
|
||||
});
|
||||
|
||||
expect(output).toBe("Name: '', Count: 0");
|
||||
} finally {
|
||||
varStore.close();
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("9.12 Special Characters in String Values", async () => {
|
||||
const { store, varStore, cleanup } = await createTempVarStore();
|
||||
|
||||
try {
|
||||
// Create schema
|
||||
const textSchema = await putSchema(store, {
|
||||
type: "object",
|
||||
properties: {
|
||||
text: { type: "string" },
|
||||
},
|
||||
});
|
||||
|
||||
// Create node with special characters
|
||||
const textHash = await store.put(textSchema, {
|
||||
text: 'Hello "World" & <tag>',
|
||||
});
|
||||
|
||||
// Register template
|
||||
const templateSchema = await putSchema(store, { type: "string" });
|
||||
const templateHash = await store.put(
|
||||
templateSchema,
|
||||
"Text: {{ payload.text }}",
|
||||
);
|
||||
varStore.set(`@ucas/template/text/${textSchema}`, templateHash);
|
||||
|
||||
// Render
|
||||
const output = await renderWithTemplate(store, varStore, textHash, {
|
||||
resolution: 1.0,
|
||||
decay: 0.5,
|
||||
epsilon: 0.01,
|
||||
});
|
||||
|
||||
expect(output).toContain('Hello "World" & <tag>');
|
||||
} finally {
|
||||
varStore.close();
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Suite 10: Context Variable Completeness", () => {
|
||||
test("10.1 Context Propagation in Recursive Renders", async () => {
|
||||
const { store, varStore, cleanup } = await createTempVarStore();
|
||||
|
||||
try {
|
||||
// Create child schema and node
|
||||
const childSchema = await putSchema(store, {
|
||||
type: "object",
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
},
|
||||
});
|
||||
const childHash = await store.put(childSchema, { name: "child" });
|
||||
|
||||
// Create parent schema and node
|
||||
const parentSchema = await putSchema(store, {
|
||||
type: "object",
|
||||
properties: {
|
||||
name: { type: "string" },
|
||||
child: { type: "string", format: "cas_ref" },
|
||||
},
|
||||
});
|
||||
const parentHash = await store.put(parentSchema, {
|
||||
name: "parent",
|
||||
child: childHash,
|
||||
});
|
||||
|
||||
// Register parent template
|
||||
const templateSchema = await putSchema(store, { type: "string" });
|
||||
const parentTemplateHash = await store.put(
|
||||
templateSchema,
|
||||
"Parent: {{ payload.name }}\n{% render payload.child %}",
|
||||
);
|
||||
varStore.set(`@ucas/template/text/${parentSchema}`, parentTemplateHash);
|
||||
|
||||
// Register child template that accesses context variables
|
||||
const childTemplateHash = await store.put(
|
||||
templateSchema,
|
||||
"Child: {{ payload.name }}, Hash: {{ hash }}, Resolution: {{ resolution }}",
|
||||
);
|
||||
varStore.set(`@ucas/template/text/${childSchema}`, childTemplateHash);
|
||||
|
||||
// Render
|
||||
const output = await renderWithTemplate(store, varStore, parentHash, {
|
||||
resolution: 1.0,
|
||||
decay: 0.5,
|
||||
epsilon: 0.01,
|
||||
});
|
||||
|
||||
expect(output).toContain("Parent: parent");
|
||||
expect(output).toContain("Child: child");
|
||||
expect(output).toContain(`Hash: ${childHash}`);
|
||||
expect(output).toContain("Resolution: 0.5");
|
||||
} finally {
|
||||
varStore.close();
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("10.2 Context Isolation Between Parent and Child", async () => {
|
||||
const { store, varStore, cleanup } = await createTempVarStore();
|
||||
|
||||
try {
|
||||
// Create child schema and node
|
||||
const childSchema = await putSchema(store, {
|
||||
type: "object",
|
||||
properties: {
|
||||
custom: { type: "string" },
|
||||
},
|
||||
});
|
||||
const childHash = await store.put(childSchema, {
|
||||
custom: "child_value",
|
||||
});
|
||||
|
||||
// Create parent schema and node
|
||||
const parentSchema = await putSchema(store, {
|
||||
type: "object",
|
||||
properties: {
|
||||
custom: { type: "string" },
|
||||
child: { type: "string", format: "cas_ref" },
|
||||
},
|
||||
});
|
||||
const parentHash = await store.put(parentSchema, {
|
||||
custom: "parent_value",
|
||||
child: childHash,
|
||||
});
|
||||
|
||||
// Register parent template
|
||||
const templateSchema = await putSchema(store, { type: "string" });
|
||||
const parentTemplateHash = await store.put(
|
||||
templateSchema,
|
||||
"Parent custom: {{ payload.custom }}\n{% render payload.child %}",
|
||||
);
|
||||
varStore.set(`@ucas/template/text/${parentSchema}`, parentTemplateHash);
|
||||
|
||||
// Register child template
|
||||
const childTemplateHash = await store.put(
|
||||
templateSchema,
|
||||
"Child custom: {{ payload.custom }}",
|
||||
);
|
||||
varStore.set(`@ucas/template/text/${childSchema}`, childTemplateHash);
|
||||
|
||||
// Render
|
||||
const output = await renderWithTemplate(store, varStore, parentHash, {
|
||||
resolution: 1.0,
|
||||
decay: 0.5,
|
||||
epsilon: 0.01,
|
||||
});
|
||||
|
||||
expect(output).toContain("Parent custom: parent_value");
|
||||
expect(output).toContain("Child custom: child_value");
|
||||
expect(output).not.toContain("Child custom: parent_value");
|
||||
} finally {
|
||||
varStore.close();
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { bootstrap } from "./bootstrap.js";
|
||||
import { render, renderDirect } from "./render.js";
|
||||
import { render, renderAsync, renderDirect } from "./render.js";
|
||||
import { putSchema } from "./schema.js";
|
||||
import { createMemoryStore } from "./store.js";
|
||||
import type { Hash } from "./types.js";
|
||||
import { CasNodeNotFoundError } from "./variable-store.js";
|
||||
|
||||
describe("Suite 1: Basic Rendering (No Nesting)", () => {
|
||||
test("1.1 Render Simple Primitives", async () => {
|
||||
@@ -65,13 +66,14 @@ describe("Suite 1: Basic Rendering (No Nesting)", () => {
|
||||
expect(output.trim()).toBe(`cas:${hash}`);
|
||||
});
|
||||
|
||||
test("1.5 Render Non-existent Hash", () => {
|
||||
test("1.5 Render Non-existent Hash Throws Error", () => {
|
||||
const store = createMemoryStore();
|
||||
const fakeHash = "ZZZZZZZZZZZZZ" as Hash;
|
||||
|
||||
// Non-existent node renders as cas: reference
|
||||
const output = render(store, fakeHash);
|
||||
expect(output.trim()).toBe(`cas:${fakeHash}`);
|
||||
// Non-existent root node should throw
|
||||
expect(() => render(store, fakeHash)).toThrow(CasNodeNotFoundError);
|
||||
expect(() => render(store, fakeHash)).toThrow("CAS node not found");
|
||||
expect(() => render(store, fakeHash)).toThrow(fakeHash);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -793,9 +795,10 @@ describe("Suite 6: Schema Integration", () => {
|
||||
|
||||
test("6.5 Schema-less Node (Bootstrap Node)", async () => {
|
||||
const store = createMemoryStore();
|
||||
const metaHash = await bootstrap(store);
|
||||
const types = await bootstrap(store);
|
||||
const schemaHash = types["@schema"];
|
||||
|
||||
const output = render(store, metaHash);
|
||||
const output = render(store, schemaHash);
|
||||
|
||||
// Should render without recursive expansion
|
||||
expect(output).toBeTruthy();
|
||||
@@ -1055,3 +1058,95 @@ describe("Suite 9: renderDirect (in-memory rendering)", () => {
|
||||
expect(output).toContain("key: val");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Suite 10: Missing Root Hash Error Handling (Issue #53)", () => {
|
||||
test("10.1 renderAsync() throws CasNodeNotFoundError for missing root hash", async () => {
|
||||
const store = createMemoryStore();
|
||||
await bootstrap(store);
|
||||
const fakeHash = "AAAAAAAAAAAAA" as Hash;
|
||||
|
||||
await expect(renderAsync(store, fakeHash)).rejects.toThrow(
|
||||
CasNodeNotFoundError,
|
||||
);
|
||||
await expect(renderAsync(store, fakeHash)).rejects.toThrow(
|
||||
"CAS node not found",
|
||||
);
|
||||
await expect(renderAsync(store, fakeHash)).rejects.toThrow(fakeHash);
|
||||
});
|
||||
|
||||
test("10.2 render() throws CasNodeNotFoundError for missing root hash", () => {
|
||||
const store = createMemoryStore();
|
||||
const fakeHash = "ZZZZZZZZZZZZZ" as Hash;
|
||||
|
||||
expect(() => render(store, fakeHash)).toThrow(CasNodeNotFoundError);
|
||||
expect(() => render(store, fakeHash)).toThrow("CAS node not found");
|
||||
expect(() => render(store, fakeHash)).toThrow(fakeHash);
|
||||
});
|
||||
|
||||
test("10.3 renderDirect() does NOT throw for non-existent type hash", () => {
|
||||
const store = createMemoryStore();
|
||||
const fakeTypeHash = "0000000000000" as Hash;
|
||||
const output = renderDirect(fakeTypeHash, { key: "value" }, store, null);
|
||||
|
||||
expect(output).toContain("key: value");
|
||||
});
|
||||
|
||||
test("10.4 Missing nested node renders as cas: reference (no error)", async () => {
|
||||
const store = createMemoryStore();
|
||||
await bootstrap(store);
|
||||
|
||||
const parentSchema = await putSchema(store, {
|
||||
type: "object",
|
||||
properties: {
|
||||
title: { type: "string" },
|
||||
child: { type: "string", format: "cas_ref" },
|
||||
},
|
||||
});
|
||||
|
||||
const fakeChildHash = "ZZZZZZZZZZZZZ" as Hash;
|
||||
const parentHash = await store.put(parentSchema, {
|
||||
title: "root",
|
||||
child: fakeChildHash,
|
||||
});
|
||||
|
||||
const output = render(store, parentHash);
|
||||
|
||||
expect(output).toContain("title: root");
|
||||
expect(output).toContain(`cas:${fakeChildHash}`);
|
||||
});
|
||||
|
||||
test("10.5 Resolution below epsilon renders as cas: reference (no error)", async () => {
|
||||
const store = createMemoryStore();
|
||||
await bootstrap(store);
|
||||
|
||||
const nodeSchema = await putSchema(store, {
|
||||
type: "object",
|
||||
properties: {
|
||||
level: { type: "number" },
|
||||
next: {
|
||||
anyOf: [{ type: "string", format: "cas_ref" }, { type: "null" }],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Create 3-level chain
|
||||
let currentHash: Hash | null = null;
|
||||
for (let i = 2; i >= 0; i--) {
|
||||
currentHash = await store.put(nodeSchema, {
|
||||
level: i,
|
||||
next: currentHash,
|
||||
});
|
||||
}
|
||||
|
||||
const output = render(store, currentHash as Hash, {
|
||||
resolution: 1.0,
|
||||
decay: 0.1,
|
||||
epsilon: 0.5,
|
||||
});
|
||||
|
||||
// Level 0 should be expanded (resolution = 1.0 > 0.5)
|
||||
expect(output).toContain("level: 0");
|
||||
// Level 1+ should be cas: references (0.1, 0.01 < 0.5)
|
||||
expect(output).toContain("cas:");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import { renderWithTemplate } from "./liquid-render.js";
|
||||
import { collectRefs, getSchema, putSchema, refs } from "./schema.js";
|
||||
import type { Hash, Store } from "./types.js";
|
||||
import type { VariableStore } from "./variable-store.js";
|
||||
import { CasNodeNotFoundError } from "./variable-store.js";
|
||||
|
||||
export type RenderOptions = {
|
||||
resolution?: number; // (0, 1], default 1.0
|
||||
@@ -55,6 +56,11 @@ export function render(
|
||||
): string {
|
||||
const { resolution, decay, epsilon } = validateAndExtractOptions(options);
|
||||
|
||||
// Check if root node exists
|
||||
if (store.get(hash) === null) {
|
||||
throw new CasNodeNotFoundError(hash);
|
||||
}
|
||||
|
||||
const visited = new Set<Hash>();
|
||||
return renderNode(store, hash, resolution, decay, epsilon, visited);
|
||||
}
|
||||
@@ -70,6 +76,12 @@ export async function renderAsync(
|
||||
options?: RenderOptions,
|
||||
): Promise<string> {
|
||||
const { resolution, decay, epsilon } = validateAndExtractOptions(options);
|
||||
|
||||
// Check if root node exists
|
||||
if (store.get(hash) === null) {
|
||||
throw new CasNodeNotFoundError(hash);
|
||||
}
|
||||
|
||||
const varStore = options?.varStore;
|
||||
|
||||
// If varStore provided, try template rendering first
|
||||
|
||||
@@ -36,8 +36,11 @@ export class SchemaMismatchError extends Error {
|
||||
}
|
||||
|
||||
export class CasNodeNotFoundError extends Error {
|
||||
constructor(hash: string) {
|
||||
super(`CAS node not found: ${hash}`);
|
||||
constructor(
|
||||
public readonly hash: string,
|
||||
message?: string,
|
||||
) {
|
||||
super(message ?? `CAS node not found: ${hash}`);
|
||||
this.name = "CasNodeNotFoundError";
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user