@gloocan/cat-inspector 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +171 -98
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,166 +1,239 @@
1
- # 🐱 Cat Inspector SDK
1
+ # @gloocan/cat-inspector
2
2
 
3
- <img
4
- src="https://cat-inspector.gloocan.com/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Flogo3.abd05647.png&w=1080&q=75"
5
- alt="logo"
6
- />
3
+ TypeScript SDK for **registering allowlisted backend functions** so QA and inspection tools get a **catalog** (ids, parameters, return metadata, optional JSON Schema), then **invoke** those units over a **versioned** wire protocol—embedded WebSocket, Socket.IO, or remote bridge—not arbitrary code execution from the network.
7
4
 
8
- **Welcome!** This is the official home of the TypeScript SDK that connects your backend to QA and inspection tooling—safely, deliberately, and without handing the internet a remote-code-execution button.
5
+ **Typical host:** Node.js with **Express** (or similar). Types ship with the package (`dist/*.d.ts`).
9
6
 
10
- The published package is `**@gloocan/cat-inspector`**. All source you can build and ship lives under `**[ts/](./ts/)`**.
7
+ ---
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install @gloocan/cat-inspector
13
+ ```
14
+
15
+ Install **peer** packages you actually use in your app (npm does not install peers for you):
16
+
17
+ | Peer | When you need it |
18
+ | --------------- | ----------------------------------------------------- |
19
+ | `express` | Express integration (`registerCatPipeline`, etc.). |
20
+ | `socket.io` | Socket.IO transport (`@gloocan/cat-inspector/socket-io`). Optional. |
21
+ | `minio` | Optional host-side object storage helpers. |
22
+
23
+ Always install **`reflect-metadata`** if you use **`@Cat`** decorators (see TypeScript below).
11
24
 
12
25
  ---
13
26
 
14
- ## 👋 New here? Start calm
27
+ ## Package entry points
15
28
 
16
- **Cat Inspector** is a **host-side library**: you drop it into **your** Node.js app. It does **not** replace your product, your API design, or your database.
29
+ The package is **ESM** (`"type": "module"`).
17
30
 
18
- Think of it as a friendly gatekeeper:
31
+ | Import from | Use for |
32
+ | ----------------------------------- | ------- |
33
+ | `@gloocan/cat-inspector` | Main API: registration, `bootstrap`, Express, RPC, WebSocket server, types, policy, validation, etc. |
34
+ | `@gloocan/cat-inspector/socket-io` | `attachCatRPC`, Socket.IO–oriented helpers. Requires `socket.io` as a dependency. |
19
35
 
20
- - 🎯 You choose **which** functions may be discovered and invoked by QA tools.
21
- - 📋 You attach **metadata** (names, parameters, return hints, optional JSON Schema) so generic UIs can build forms and checks.
22
- - 🔒 Only what you **register** is on the menu—nothing else gets exposed by accident.
36
+ ---
23
37
 
24
- **You do not need the whole map on day one.** Most teams start with three ideas:
38
+ ## TypeScript and decorators
25
39
 
26
- 1. **Registration** how functions join the catalog
27
- 2. **Express** — how those units line up with your HTTP world
28
- 3. **One transport** — how a QA client says hello (WebSocket, Socket.IO, bridge—pick what you use)
40
+ For **`@Cat`** (and related metadata), enable decorator emit and load reflect metadata **before** other app imports:
29
41
 
30
- Everything beyond that is **bonus depth** when you need it. 🌱
42
+ 1. `npm install reflect-metadata`
43
+ 2. At the **top** of your app entry (e.g. `server.ts`): `import 'reflect-metadata'`
44
+ 3. In `tsconfig.json`:
45
+
46
+ ```json
47
+ {
48
+ "compilerOptions": {
49
+ "experimentalDecorators": true,
50
+ "emitDecoratorMetadata": true
51
+ }
52
+ }
53
+ ```
54
+
55
+ If you only use the **functional** API (`cat()`, `catModule()`, …), decorators may be unnecessary; still follow the docs for your chosen registration style.
31
56
 
32
57
  ---
33
58
 
34
- ## 🗂️ How `sdk/` fits this repo
59
+ ## Quick examples: registration
35
60
 
36
- This monorepo is bigger than the SDK (think **frontend**, **backend**, deploy recipes, examples). The `**sdk/`** folder is the **canonical home** for Cat Inspector:
61
+ Each example uses a **stable function id** (`fnKey`) such as `Orders.find`—that id is what the catalog and RPC clients use. Pick ids that stay stable across refactors.
37
62
 
63
+ ### `cat()` — one function
38
64
 
39
- | Path | What you’ll find |
40
- | ------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
41
- | 📄 `[README.md](./README.md)` *(this file)* | Friendly orientation—perfect first stop for humans. |
42
- | 📦 `[ts/](./ts/)` | The real **npm package**: `package.json`, `src/`, tests, `PROTOCOL.md`, and `[ts/docs/](./ts/docs/)`. |
43
- | 🧠 `[ts/src/](./ts/src/)` | Implementation; the **public API** is whatever `[ts/src/index.ts](./ts/src/index.ts)` exports. |
44
- | 🏗️ `[ts/dist/](./ts/dist/)` | Build output from `npm run build` (publishable; often git-ignored). |
65
+ Wrap a plain function and give it a unique key. For HTTP-style handlers you can pass `route` / `method` so the catalog knows the path.
45
66
 
67
+ ```ts
68
+ import { cat, Return, Throw } from '@gloocan/cat-inspector'
46
69
 
47
- > 💡 **Consuming from npm?** You only need the package name + docs—you don’t have to clone the whole repo unless you want examples or contributions.
70
+ export const findUser = cat('Users.findById', function findUser(id: string) {
71
+ if (!id) return Throw('INVALID', new Error('id required'))
72
+ return Return('OK', { id, name: 'Ada' })
73
+ })
74
+ ```
48
75
 
49
- ---
76
+ Call `findUser('42')` as normal; the wrapper records **which labeled branch** ran for inspector UIs.
50
77
 
51
- ## 🎪 What it *is*
78
+ ### `@Cat` class methods
52
79
 
53
- Backend devs **register** hand-picked functions (handlers, services, little modules) as **named, typed, inspectable units**. QA clients get a **catalog**—stable ids, parameters, return metadata, optional tags—and can drive **forms + assertions** instead of shipping bespoke test code for every app.
80
+ Requires `reflect-metadata` and the `tsconfig.json` flags above. Registration runs when the class is **loaded**.
54
81
 
55
- ---
82
+ ```ts
83
+ import 'reflect-metadata'
84
+ import { Cat, Return } from '@gloocan/cat-inspector'
56
85
 
57
- ## 🚀 What it’s *for*
86
+ export class Billing {
87
+ @Cat
88
+ estimate(total: number) {
89
+ return Return('QUOTE', { cents: Math.round(total * 100) })
90
+ }
91
+ }
92
+ ```
58
93
 
94
+ The catalog entry key becomes **`Billing.estimate`** (class name + method name).
59
95
 
60
- | Goal | Why it feels good |
61
- | ------------------------------------ | --------------------------------------------------------------------------------------------------------------- |
62
- | 🛡️ **Controlled surface** | Pick entry points that are safe and meaningful to call from tooling—not “whatever was imported.” |
63
- | 🤖 **Machine-friendly descriptions** | Schemas, labels, type hints keep QA UIs generic across products. |
64
- | 🔌 **Authorized clients** | Embedded WebSocket, optional Socket.IO, remote bridge—listing and invoke stay under **your** process and rules. |
96
+ ### `catModule()` a namespace of functions
65
97
 
98
+ Registers every export under **`${moduleName}.${methodName}`** in one call.
66
99
 
67
- **Typical host:** a **Node.js / Express** (or similar) service where your real business logic already lives. ☕
100
+ ```ts
101
+ import { catModule, Return } from '@gloocan/cat-inspector'
68
102
 
69
- ---
103
+ export const inventory = catModule('Inventory', {
104
+ list() {
105
+ return Return('LIST', [{ sku: 'a1' }])
106
+ },
107
+ reserve(sku: string) {
108
+ return Return('RESERVED', { sku, qty: 1 })
109
+ },
110
+ })
111
+ // Keys: Inventory.list, Inventory.reserve — call inventory.list() as usual.
112
+ ```
70
113
 
71
- ## 🧩 Main areas at a glance
114
+ Optional third argument lets you attach per-method `params`, `declaredReturn`, or `paramsJsonSchema` (see typings).
72
115
 
116
+ ### `registerCatPipeline()` — Express route + middleware chain
73
117
 
74
- | Area | Role |
75
- | --------------------------- | -------------------------------------------------------------------------------------------------------- |
76
- | 🏷️ **Registration** | `@Cat`, `cat`, `catModule`, class/service helpers, instance registration → catalog entries. |
77
- | 📡 **Bootstrap & metadata** | Load/merge catalog + bootstrap data; optional storage-backed bits so tools see one coherent picture. |
78
- | 🚂 **Express** | Pipelines, correlation, optional HTTP bridge—meet your routes where they already are. |
79
- | ⚡ **RPC surface** | Invoke by id with structured results/errors—no ad-hoc “run anything” scripting. |
80
- | 🌐 **Transports** | WebSocket server, remote bridge, Socket.IO subpath export when you need it. |
81
- | ✅ **Validation & policy** | JSON Schema, serialization limits, pre-invoke hooks, rate limits, audits. |
82
- | 🎨 **Returns & labels** | `Return`, `Throw`, `ApiReturn` so tooling can tell labeled outcomes apart from plain values. |
83
- | 🎁 **Optional extras** | Coverage helpers, OpenAPI export, uploads materialization, jobs/broadcasts, sessions—grab what you need. |
118
+ Pass an Express `Router`, HTTP method, route path, and an array of **already wrapped** `cat()` handlers. The **last** handler is the route endpoint; earlier entries are treated as middleware (`req`, `res`, `next`).
84
119
 
120
+ ```ts
121
+ import express from 'express'
122
+ import type { Request, Response, NextFunction } from 'express'
123
+ import { cat, registerCatPipeline, Return } from '@gloocan/cat-inspector'
85
124
 
86
- ---
125
+ const router = express.Router()
87
126
 
88
- ## 📖 Tiny glossary
127
+ const requireAuth = cat('Api.requireAuth', (req: Request, res: Response, next: NextFunction) => {
128
+ // …validate session, then:
129
+ next()
130
+ })
89
131
 
132
+ const getProfile = cat('Api.getProfile', (req: Request, res: Response) => {
133
+ return Return('BODY', { userId: req.params['id'] })
134
+ })
90
135
 
91
- | Term | In plain English |
92
- | ------------------------- | -------------------------------------------------------------------------------------------- |
93
- | **Host** | Your Node process running the SDK and your app code. |
94
- | **Catalog** | The allowlisted set of registered units + metadata tools may see. |
95
- | **Function id** | Stable string clients use when they invoke something specific. |
96
- | **Inspector / QA client** | Another app or UI that talks to your host—not shipped inside this package. |
97
- | **Protocol** | Versioned JSON + message families—see `[ts/PROTOCOL.md](./ts/PROTOCOL.md)` for the contract. |
136
+ registerCatPipeline(router, 'get', '/users/:id', [requireAuth, getProfile])
137
+ // app.use('/v1', router)
138
+ ```
98
139
 
140
+ The SDK aligns all handlers in the array with one **pipeline id** (e.g. `GET /users/:id`) so tools see middleware + endpoint as one HTTP unit.
99
141
 
100
142
  ---
101
143
 
102
- ## Before you integrate (checklist vibes)
144
+ ## `Return()` and `Throw()` labels for tooling
103
145
 
104
- - **Node.js** + **npm** (or pnpm/yarn—your house, your rules).
105
- - **TypeScript** in the host is typical; types ship with the package.
106
- - **Peers:** `express` when you use Express helpers; `**minio`** / `**socket.io`** are optional—peek at `[ts/package.json](./ts/package.json)`.
107
- - `**@Cat` decorators?** Turn on `**reflect-metadata`** + TS `**experimentalDecorators`** / `**emitDecoratorMetadata`** (details live in the docs linked below).
146
+ These helpers are **no-ops for business data**: they return or throw the same values you would use without Cat Inspector. Their job is to attach a **string label** so QA clients and the catalog can distinguish branches (success variants, validation failures, expected errors) without parsing your whole codebase.
108
147
 
109
- ---
148
+ | Helper | What you write | What QA / catalog sees |
149
+ | ------ | -------------- | ---------------------- |
150
+ | `Return(label, value)` | `return Return('CREATED', entity)` | Outcome tied to label **`CREATED`**; payload is `value` (types/shapes can be captured for assertions). |
151
+ | `Throw(label, error)` | `return Throw('NOT_FOUND', new Error('…'))` | Expected error path **`NOT_FOUND`** with message/stack; still throws `error` to callers. |
152
+
153
+ **Labels** are arbitrary string literals you choose (`'OK'`, `'INVALID'`, `'QUOTE'`, …). Use short, stable names: they become part of how teams author **assertions** (“expect `Users.findById` to resolve with label `OK`”).
110
154
 
111
- ## 🗺️ Suggested reading order (snackable path)
155
+ **Data:** the second argument to `Return` is whatever your function would normally return. `Throw` always takes an `Error` (or subclass); use normal `throw new Error()` for unexpected failures you do **not** want labeled.
112
156
 
113
- 1. **This README** you’re almost done with step one. Nice. 🎉
114
- 2. `**[ts/docs/protocol-client.md](./ts/docs/protocol-client.md)`** — if you’ll build or wire a client.
115
- 3. `**[ts/docs/boostrap.md](./ts/docs/boostrap.md)`** — bootstrap-oriented notes (path matches the repository filename).
116
- 4. `**[ts/PROTOCOL.md](./ts/PROTOCOL.md)`** — wire truth; keep clients aligned with `**PROTOCOL_VERSION**`.
117
- 5. **[Nextra docs](../qa-test-doc/src/)** — long-form MDX. Run:
118
- ```bash
119
- cd qa-test-doc/src && npm install && npm run dev
120
- ```
121
- …then open **[http://localhost:3015](http://localhost:3015)** (default dev port).
122
- 6. **Runnable demo:** `[examples/cat-demo/backend](../examples/cat-demo/backend/README.md)` — Express + Socket.IO, real bootstrap, copy-paste energy. 🐾
157
+ Combine with `cat` / `@Cat` / `catModule` so the inspector knows **which function** is active when a label fires (`ActiveContext` is managed by the wrappers).
123
158
 
124
159
  ---
125
160
 
126
- ## 📚 Doc map (who reads what)
161
+ ## Minimal integration shape
127
162
 
163
+ Exact APIs depend on your stack; most setups touch these ideas in order:
128
164
 
129
- | Resource | Best for |
130
- | -------------------------------------- | ---------------------------------- |
131
- | `[ts/PROTOCOL.md](./ts/PROTOCOL.md)` | Wire compatibility detectives 🕵️ |
132
- | `[ts/docs/](./ts/docs/)` | Day-to-day integrators |
133
- | `[qa-test-doc/](../qa-test-doc/)` | Deep dives + searchable reference |
134
- | `[ts/package.json](./ts/package.json)` | Scripts, `exports`, peers, version |
165
+ 1. **Register** testable units (`@Cat`, `cat`, `catModule`, class helpers, `registerInstance`, …).
166
+ 2. **Wire Express** (e.g. `registerCatPipeline`, correlation middleware) so HTTP routes map to catalog entries.
167
+ 3. **Expose a transport** so a QA client can load the catalog and call `invoke`—e.g. `startInspectorWebSocket`, or `attachCatRPC` from the `socket-io` entry after you create your `socket.io` `Server`.
135
168
 
169
+ Example (illustrative only—adapt ports, CORS, and auth to your environment):
136
170
 
137
- ---
171
+ ```ts
172
+ import 'reflect-metadata'
138
173
 
139
- ## 🛠️ Install & build (from a full clone)
174
+ import express from 'express'
175
+ import http from 'node:http'
176
+ import { Server as SocketIOServer } from 'socket.io'
140
177
 
141
- ```bash
142
- cd sdk/ts
143
- npm install
144
- npm run build
145
- npm test
178
+ import {
179
+ createInspectorCorrelationMiddleware,
180
+ attachCatRPC,
181
+ } from '@gloocan/cat-inspector/socket-io'
182
+
183
+ const app = express()
184
+ app.use(express.json())
185
+ app.use('/api', createInspectorCorrelationMiddleware())
186
+
187
+ const server = http.createServer(app)
188
+ const io = new SocketIOServer(server, {
189
+ cors: { origin: 'http://localhost:3013' },
190
+ })
191
+
192
+ attachCatRPC(io, {
193
+ scanRoots: [new URL('.', import.meta.url).pathname],
194
+ serverId: 'my-service',
195
+ isDevelopment: process.env.NODE_ENV !== 'production',
196
+ // bootstrap, upload, auth: see docs and PROTOCOL.md in the source repo
197
+ })
198
+
199
+ server.listen(5050)
146
200
  ```
147
201
 
148
- **Consumers** add `**@gloocan/cat-inspector`** from your registry or workspace. Imports follow `**package.json` → `exports`** (main entry + optional `**@gloocan/cat-inspector/socket-io`** when published).
202
+ For **`executeRPC`**, validation, serialization limits, pre-invoke hooks, and audits, import from `@gloocan/cat-inspector`.
149
203
 
150
204
  ---
151
205
 
152
- ## 🤝 Contributing
206
+ ## Wire protocol and versioning
207
+
208
+ Clients and hosts must agree on JSON message shapes. The SDK exports **`PROTOCOL_VERSION`** from the main entry—bump-aware clients should read it and follow the contract documented alongside the source tree.
153
209
 
154
- - Keep `**index.ts` exports** stable or clearly versioned—downstream clients will thank you. 🙏
155
- - Under `sdk/ts`, run `**npm run typecheck`** and `**npm test`** before opening a PR.
156
- - If behavior crosses the wire, update `**PROTOCOL.md`** plus `**ts/docs/**` or `**qa-test-doc/**` in the same breath when you can.
210
+ **Note:** The **published npm tarball** contains **`dist/`** (compiled JS + declarations) plus standard metadata. Markdown references such as **`PROTOCOL.md`** live in the **source repository** (use the **Repository** link on the [npm package page](https://www.npmjs.com/package/@gloocan/cat-inspector) if your maintainers have set `repository` in `package.json`).
157
211
 
158
212
  ---
159
213
 
160
- ## 🌟 One-sentence summary
214
+ ## Security (read before production)
161
215
 
162
- **Cat Inspector** is the **host-side SDK** that says *which* backend behavior is QA-visible, *how* tools should describe and validate it, and *how* authorized clients connectwhile keeping the whole story explicit in **your** codebase.
216
+ - Only **registered** functions are invokabletreat registration as an **allowlist**.
217
+ - **Authenticate** transports in non-dev environments; do not expose invoke surfaces anonymously on the public internet.
218
+ - Prefer **read-only** or sandbox data for QA; avoid putting production secrets in tool-visible payloads.
219
+ - Configure **serialization limits**, **rate limits**, and **pre-invoke** hooks where appropriate (`setRpcSerializationConfig`, `configureInvokeRateLimit`, `registerPreInvoke`, …—see typings and docs).
163
220
 
164
221
  ---
165
222
 
166
- *Happy inspecting! 🐱✨*
223
+ ## Documentation and examples
224
+
225
+ - **Product / docs site:** [cat-inspector.gloocan.com](https://cat-inspector.gloocan.com) (when available for your deployment).
226
+ - **Deep reference:** your team’s Nextra or internal doc site, if published.
227
+ - **Runnable monorepo example:** an Express + Socket.IO backend under the same repository as this package (search for `examples/cat-demo` in the SDK source tree).
228
+
229
+ ---
230
+
231
+ ## Public API surface
232
+
233
+ The supported public API is whatever **`@gloocan/cat-inspector` re-exports** from its main module (registration, `bootstrap`, Express helpers, `executeRPC`, transports, `PROTOCOL_VERSION`, wire types such as `RegistryEntry` and `RpcResponse`, validation helpers, policy hooks, uploads, coverage/OpenAPI helpers, sessions, etc.). Prefer importing from the package root rather than deep paths into `dist/`, which are not a stable contract.
234
+
235
+ ---
236
+
237
+ ## License
238
+
239
+ MIT — see the `license` field in `package.json`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gloocan/cat-inspector",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "TypeScript @Cat decorator, Return() paths, AST metadata, WebSocket inspector",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",