gell-dispatch 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,45 @@
1
+ name: publish
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - 'v*'
7
+
8
+ permissions:
9
+ contents: read
10
+ id-token: write
11
+
12
+ jobs:
13
+ publish:
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - uses: actions/checkout@v5
17
+
18
+ - uses: actions/setup-node@v5
19
+ with:
20
+ node-version: 24
21
+ registry-url: https://registry.npmjs.org
22
+
23
+ - run: npm install -g npm@latest
24
+
25
+ - name: Check tag matches package version
26
+ run: |
27
+ VERSION=$(node -p "require('./package.json').version")
28
+ if [ "v$VERSION" != "$GITHUB_REF_NAME" ]; then
29
+ echo "tag $GITHUB_REF_NAME does not match package.json version $VERSION"
30
+ exit 1
31
+ fi
32
+
33
+ - run: npm ci
34
+
35
+ - run: npm test
36
+
37
+ - name: Publish
38
+ run: |
39
+ NAME=$(node -p "require('./package.json').name")
40
+ VERSION=$(node -p "require('./package.json').version")
41
+ if npm view "$NAME@$VERSION" version > /dev/null 2>&1; then
42
+ echo "$NAME@$VERSION is already published"
43
+ exit 0
44
+ fi
45
+ npm publish
@@ -0,0 +1,215 @@
1
+ # Registry Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** A generic `Registry` in gell-dispatch, instantiated once per kind of named declaration, plus kinds for actions, snapshots and types.
6
+
7
+ **Architecture:** `Registry` is a plain class backed by a `Map`, configured with a *kind* object (`{ kind, nameOf, validate?, describe? }`) that supplies everything kind specific. Kinds are small modules under `kind/`. A shared `normalizeParameters` helper turns parameter specs into a uniform description.
8
+
9
+ **Tech Stack:** Node (CommonJS, `^20.19.0 || >=22.12.0`), lodash, mocha 8 with `assert`.
10
+
11
+ **Spec:** `docs/superpowers/specs/2026-11-25-registry-design.md`
12
+
13
+ ## Global Constraints
14
+
15
+ - CommonJS modules, 4-space indentation, `assert` + lodash like the existing gell-dispatch code
16
+ - no new dependencies; gell-dispatch must not depend on gell-domain or gell-aws-dynamodb (or `gell`)
17
+ - invalid registrations fail with `assert` (AssertionError)
18
+ - run tests with Node 24: `export PATH=~/.nvm/versions/node/v24.22.3/bin:$PATH; npx mocha` (from the gell-dispatch root)
19
+ - do not commit; the user commits when they ask
20
+
21
+ ## Review Focus
22
+
23
+ - `registerAll` where a later entry is invalid or a duplicate (of the registry or of an earlier entry in the same batch): nothing from that batch is registered
24
+ - a declaration missing the structure a kind reads (action module without `__metadata`, type without `model`): AssertionError naming the kind, never a TypeError
25
+ - mutating a `describe` result (e.g. its `params` array) must not change the registered declaration
26
+ - mutating the array returned by `names()` must not change the registry
27
+ - `registerAll` given `null`, `undefined` or a string: AssertionError
28
+
29
+ ---
30
+
31
+ ### Task 1: Parameters helper
32
+
33
+ **Files:**
34
+ - Create: `util/parameters.js`
35
+ - Test: `test/util/test-parameters.js`
36
+
37
+ **Interfaces:**
38
+ - Produces: `normalizeParameters(params) -> Array<{ name, type, optional }>` exported as `module.exports = { normalizeParameters }`
39
+
40
+ - [ ] **Step 1: Write the failing tests**
41
+
42
+ ```js
43
+ const { normalizeParameters } = require('../../util/parameters');
44
+
45
+ it('normalizes a type name', () =>
46
+ assert.deepStrictEqual(normalizeParameters({ parentId: 'uuid' }), [{ name: 'parentId', type: 'uuid', optional: false }]));
47
+ it('normalizes a spec object', () =>
48
+ assert.deepStrictEqual(normalizeParameters({ type: { type: 'string', optional: true } }), [{ name: 'type', type: 'string', optional: true }]));
49
+ it('defaults optional to false', () =>
50
+ assert.deepStrictEqual(normalizeParameters({ count: { type: 'number' } }), [{ name: 'count', type: 'number', optional: false }]));
51
+ it('keeps declaration order', () =>
52
+ assert.deepStrictEqual(normalizeParameters({ b: 'string', a: 'string' }).map(p => p.name), ['b', 'a']));
53
+ it('returns an empty array for missing parameters', () => {
54
+ assert.deepStrictEqual(normalizeParameters(), []);
55
+ assert.deepStrictEqual(normalizeParameters(null), []);
56
+ });
57
+ it('does not copy other spec attributes', () =>
58
+ assert.deepStrictEqual(normalizeParameters({ m: { type: 'string', maxLength: 10 } }), [{ name: 'm', type: 'string', optional: false }]));
59
+ ```
60
+
61
+ - [ ] **Step 2: Run, expect FAIL** with `Cannot find module '../../util/parameters'`
62
+
63
+ - [ ] **Step 3: Implement `normalizeParameters(params={})`** in `util/parameters.js`; `optional` is coerced to a boolean
64
+
65
+ - [ ] **Step 4: Run, expect all tests PASS**
66
+
67
+ ---
68
+
69
+ ### Task 2: Registry
70
+
71
+ **Files:**
72
+ - Create: `registry.js`
73
+ - Test: `test/test-registry.js`
74
+
75
+ **Interfaces:**
76
+ - Consumes: nothing
77
+ - Produces: `module.exports = Registry` (class)
78
+ - `new Registry(kind)`; `kind = { kind: string, nameOf(decl) -> string, validate?(decl), describe?(decl) -> object }`
79
+ - `register(decl) -> decl`
80
+ - `registerAll(decls) -> Array<decl>` (object: its values; iterable: its items)
81
+ - `get(name) -> decl | undefined`, `has(name) -> boolean`, `names() -> Array<string>` (new array, registration order)
82
+ - `describe(name) -> object | undefined` = `{ ...kind.describe(decl), name }` (`{ name }` without `kind.describe`)
83
+ - `describeAll() -> Array<object>` in registration order
84
+
85
+ - [ ] **Step 1: Write the failing tests**, using a test kind `{ kind: 'query', nameOf: d => d && d.name, describe: d => ({ description: d.description }) }`:
86
+
87
+ ```js
88
+ it('requires a kind with nameOf', () => {
89
+ assert.throws(() => new Registry(), { name: 'AssertionError' });
90
+ assert.throws(() => new Registry({ kind: 'query' }), { name: 'AssertionError' });
91
+ });
92
+ it('registers and returns the original declaration', ...) // register(d) === d; get('q.one') === d; has true
93
+ it('returns undefined / false for unknown names', ...)
94
+ it('rejects a declaration that is not an object', ...) // register(null), register('q') -> AssertionError
95
+ it('rejects a declaration without a name', ...) // message: 'query must define a name to be registered'
96
+ it('rejects a duplicate name', ...) // message: 'query (name=q.one) is already registered'; also for the same object
97
+ it('validates with the kind', ...) // validate throws -> register throws, has() false
98
+ it('lists names in registration order', ...)
99
+ it('returns a copy of names', ...) // names().push('x') doesn't change names()
100
+ it('registers every value of an object', ...) // registerAll({ a: d1, b: d2 }) -> names ['q.one', 'q.two']; returns [d1, d2]
101
+ it('registers every item of an iterable', ...) // array and a Set
102
+ it('registers nothing if a later declaration is invalid', ...) // registerAll([d1, {}]) throws; has('q.one') false
103
+ it('registers nothing if a batch repeats a name', ...) // registerAll([d1, d1copy]) throws; names() []
104
+ it('registers nothing if a batch repeats a registered name', ...)
105
+ it('rejects null, undefined or a string for registerAll', ...)
106
+ it('describes a declaration with its name', ...) // describe('q.one') deepEquals { description: 'one', name: 'q.one' }
107
+ it('describes with only the name if the kind has no describe', ...)
108
+ it('describe returns undefined for unknown names', ...)
109
+ it('describes all declarations in order', ...)
110
+ ```
111
+
112
+ - [ ] **Step 2: Run, expect FAIL** with `Cannot find module '../registry'`
113
+
114
+ - [ ] **Step 3: Implement `Registry`** in `registry.js`. `registerAll` checks every declaration (object, name, validate, no duplicates against the registry *and* within the batch) before adding any.
115
+
116
+ - [ ] **Step 4: Run, expect all tests PASS**
117
+
118
+ ---
119
+
120
+ ### Task 3: Action and snapshot kinds
121
+
122
+ **Files:**
123
+ - Create: `kind/event.js`, `kind/action.js`, `kind/snapshot.js`
124
+ - Test: `test/kind/test-action.js`, `test/kind/test-snapshot.js`
125
+
126
+ **Interfaces:**
127
+ - Consumes: `normalizeParameters` (Task 1), `Registry` (Task 2, tests only)
128
+ - Produces:
129
+ - `kind/event.js`: `module.exports = { eventKind(kindName, triggerName) -> kind, describeEvent(__metadata) -> object }`
130
+ - `kind/action.js`: `module.exports = eventKind('action', 'action')`
131
+ - `kind/snapshot.js`: `module.exports = eventKind('snapshot', 'api')`
132
+ - `nameOf: m => m.__metadata.name` guarded so a missing `__metadata` yields `undefined` (Registry then rejects the missing name)
133
+ - `validate`: asserts `m[triggerName]` is a function, message `action (name=<name>) must define an action function` / `snapshot (name=<name>) must define an api function`
134
+ - `describeEvent` returns `{ name, description, triggers }`; each trigger spec is deep-copied with `params` and `context` replaced by `normalizeParameters(...)`, other trigger attributes (`roles`, `public`, `transaction`, ...) copied as is; missing `triggers` -> `{}`
135
+
136
+ - [ ] **Step 1: Write the failing tests** (action shown; snapshot mirrors it with `api`):
137
+
138
+ ```js
139
+ const registry = new Registry(require('../../kind/action'));
140
+ const MODULE = {
141
+ __metadata: {
142
+ name: 'session.update', description: 'updates a session',
143
+ triggers: { action: { params: { attr: 'string', count: { type: 'number', optional: true } }, context: { session$: 'complex' }, roles: ['admin'] }, effect: {} }
144
+ },
145
+ action: () => {}, effect: () => {}
146
+ };
147
+
148
+ it('registers by __metadata.name', ...) // registry.get('session.update') === MODULE
149
+ it('rejects a module without an action function', ...) // message 'action (name=session.update) must define an action function'
150
+ it('rejects a module without __metadata', ...) // { action() {} } -> AssertionError (not TypeError)
151
+ it('describes name, description and triggers', () =>
152
+ assert.deepStrictEqual(registry.describe('session.update'), {
153
+ name: 'session.update', description: 'updates a session',
154
+ triggers: {
155
+ action: {
156
+ params: [{ name: 'attr', type: 'string', optional: false }, { name: 'count', type: 'number', optional: true }],
157
+ context: [{ name: 'session$', type: 'complex', optional: false }],
158
+ roles: ['admin']
159
+ },
160
+ effect: { params: [], context: [] }
161
+ }
162
+ }));
163
+ it('describes a module without triggers', ...) // triggers: {}
164
+ it('does not share data with the declaration', ...) // mutate describe(...).triggers.action.roles -> MODULE roles unchanged
165
+ ```
166
+
167
+ - [ ] **Step 2: Run, expect FAIL** with `Cannot find module '../../kind/action'`
168
+
169
+ - [ ] **Step 3: Implement `kind/event.js`, `kind/action.js`, `kind/snapshot.js`** per the Interfaces block (lodash `cloneDeep` for the copy)
170
+
171
+ - [ ] **Step 4: Run, expect all tests PASS**
172
+
173
+ ---
174
+
175
+ ### Task 4: Type kind
176
+
177
+ **Files:**
178
+ - Create: `kind/type.js`
179
+ - Test: `test/kind/test-type.js`
180
+
181
+ **Interfaces:**
182
+ - Consumes: `Registry` (tests only)
183
+ - Produces: `module.exports = { kind: 'type', nameOf, validate, describe }`
184
+ - `nameOf: m => m.model.name`, guarded like Task 3
185
+ - `validate`: asserts `TYPE` is a string, message `type (name=<name>) must define TYPE`
186
+ - `describe: m -> { name, type: m.TYPE, attributes: [attribute names] }`; `model.attributes` may be a map (keys) or an array of specs (`a.name`); missing -> `[]`
187
+
188
+ - [ ] **Step 1: Write the failing tests**
189
+
190
+ ```js
191
+ const registry = new Registry(require('../../kind/type'));
192
+ const SESSION = { TYPE: 'GELL#SESSION', model: { name: 'gell.session', attributes: { type: 'string', parentId: 'uuid' } } };
193
+
194
+ it('registers by model.name', ...) // get('gell.session') === SESSION
195
+ it('rejects a module without TYPE', ...) // message 'type (name=gell.session) must define TYPE'
196
+ it('rejects a module without a model', ...) // AssertionError, not TypeError
197
+ it('describes map attributes', () =>
198
+ assert.deepStrictEqual(registry.describe('gell.session'), { name: 'gell.session', type: 'GELL#SESSION', attributes: ['type', 'parentId'] }));
199
+ it('describes array attributes', ...) // attributes: [{ name: 'type' }, { name: 'parentId' }] -> ['type', 'parentId']
200
+ it('describes a model without attributes', ...) // attributes: []
201
+ ```
202
+
203
+ - [ ] **Step 2: Run, expect FAIL** with `Cannot find module '../../kind/type'`
204
+
205
+ - [ ] **Step 3: Implement `kind/type.js`**
206
+
207
+ - [ ] **Step 4: Run, expect all tests PASS**
208
+
209
+ ---
210
+
211
+ ### Task 5: Full verification
212
+
213
+ - [ ] **Step 1:** `npx mocha` from the gell-dispatch root: all tests pass (82 existing + new)
214
+ - [ ] **Step 2:** no-gell guard: `npx mocha -r <guard>` where the guard throws for requires of `gell`, `gell/*` or `when`; all pass
215
+ - [ ] **Step 3:** `git status`: only the files listed in Tasks 1-4 plus `docs/superpowers/` are new; nothing committed
@@ -0,0 +1,87 @@
1
+ # Registry design
2
+
3
+ ## Intent
4
+
5
+ Applications declare many kinds of named things: actions, snapshots, types, DynamoDB named queries and named
6
+ operations. Each kind is collected, looked up by name, and described (listed with metadata) by discovery snapshots.
7
+ Today this is done ad hoc: gell-aws-dynamodb wraps query/operation maps (losing the definitions), and
8
+ gell-promote/gell-discover has near-identical `Queries`/`Operations` registries plus a catch-all `Registry`.
9
+
10
+ Goal: one registry implementation in gell-dispatch, instantiated once per kind of declaration.
11
+
12
+ ## Goals
13
+
14
+ - a generic `Registry` that holds declarations of a single kind
15
+ - kind specific behavior (where the name lives, validation, description) supplied by a *kind* object
16
+ - kinds for the declarations gell-dispatch owns: actions, snapshots
17
+ - a kind for types (gell-domain models), without depending on gell-domain
18
+ - a shared helper normalizing parameter specs (`'string'` or `{ type, optional }`), usable by any kind
19
+
20
+ ## Non-goals
21
+
22
+ - a single registry holding every kind (each application has many registries, one per kind)
23
+ - query/operation kinds and gell-aws-dynamodb store integration (follow-up, in gell-aws-dynamodb)
24
+ - discovery snapshots (`gell.queries`, `gell.inspect`, ...) (follow-up)
25
+ - the compile/normalization step (later; the kind gets a hook for it then)
26
+ - replacing the bus resolver with an action registry (later)
27
+
28
+ ## Approaches
29
+
30
+ - **A. One class configured with a kind object** (chosen): `new Registry(kind)`; kinds are small objects defined
31
+ where the kind belongs. Keeps the registry generic and gives the future compile step an obvious home.
32
+ - B. Base class with a subclass per kind: a class per kind, re-subclassing to change behavior.
33
+ - C. Plain name -> declaration map with normalization outside: nothing validates declarations, and callers must know
34
+ which describe/compile function goes with which registry.
35
+
36
+ ## Design
37
+
38
+ ### Kind
39
+
40
+ ```js
41
+ {
42
+ kind: 'query', // used in error messages
43
+ nameOf: decl => decl.name, // required
44
+ validate: decl => {}, // optional; throws for an invalid declaration
45
+ describe: decl => ({}), // optional; plain object metadata (no functions); default { name }
46
+ }
47
+ ```
48
+
49
+ ### Registry
50
+
51
+ ```js
52
+ const registry = new Registry(kind);
53
+
54
+ registry.register(decl) // validates, rejects missing name and duplicates; returns decl
55
+ registry.registerAll(decls) // every value of an object (e.g. a module's exports) or an iterable
56
+ registry.get(name) // the original declaration (undefined if not registered)
57
+ registry.has(name)
58
+ registry.names() // array, in registration order
59
+ registry.describe(name) // kind.describe(decl), with name; undefined if not registered
60
+ registry.describeAll() // describe() for every declaration
61
+ ```
62
+
63
+ - stores the original declaration; callers need it to execute (`query()`, `filter()`, `action()`, ...)
64
+ - registering a name twice throws, even for the same declaration
65
+
66
+ ### Kinds in gell-dispatch
67
+
68
+ - **action**: event module with `__metadata.name` and an `action` function;
69
+ describes `{ name, description, triggers }`, trigger params normalized
70
+ - **snapshot**: same, with an `api` function
71
+ - **type**: module with `model.name` (and `TYPE`); describes `{ name, type: TYPE, attributes: [names] }`
72
+
73
+ ### Parameters helper
74
+
75
+ `normalizeParameters(params)` -> `[{ name, type, optional }]`; `'uuid'` becomes `{ type: 'uuid', optional: false }`.
76
+
77
+ ## Calls made by Claude (check these)
78
+
79
+ - the registry is a plain class backed by a `Map`, not a gell-state `State` (gell-discover used `State`; nothing
80
+ here needs snapshots or projections)
81
+ - invalid registrations fail with `assert` (programming errors), like gell-discover
82
+ - module paths: `registry.js`, `kind/action.js`, `kind/snapshot.js`, `kind/type.js`, `util/parameters.js`
83
+
84
+ ## Left to the builder
85
+
86
+ - exact describe output for triggers (which trigger attributes beyond params to include)
87
+ - test layout, following the existing `test/` structure
package/kind/action.js ADDED
@@ -0,0 +1,6 @@
1
+ const { eventKind } = require('./event');
2
+
3
+ /**
4
+ * Registry kind for action event modules (see registry)
5
+ */
6
+ module.exports = eventKind('action', 'action');
package/kind/event.js ADDED
@@ -0,0 +1,38 @@
1
+ const assert = require('assert');
2
+ const _ = require('lodash');
3
+
4
+ const { normalizeParameters } = require('../util/parameters');
5
+
6
+ /**
7
+ * Describes an event module's metadata as plain data
8
+ * - trigger params and context are normalized (see util/parameters)
9
+ * - other trigger attributes (e.g. roles, public, transaction) are copied as is
10
+ *
11
+ * @param {*} __metadata
12
+ */
13
+ function describeEvent({ name, description, triggers={} }) {
14
+ const described = _.mapValues(_.cloneDeep(triggers), spec => ({
15
+ ...spec,
16
+ params: normalizeParameters(spec.params),
17
+ context: normalizeParameters(spec.context),
18
+ }));
19
+
20
+ return { name, description, triggers: described };
21
+ }
22
+
23
+ /**
24
+ * Creates a registry kind for event modules (__metadata with a name) that define a specific trigger function
25
+ *
26
+ * @param {*} kindName name of the kind (e.g. action)
27
+ * @param {*} triggerName trigger function the module must define (e.g. action)
28
+ */
29
+ function eventKind(kindName, triggerName) {
30
+ return {
31
+ kind: kindName,
32
+ nameOf: m => m.__metadata && m.__metadata.name,
33
+ validate: m => assert(_.isFunction(m[triggerName]), `${kindName} (name=${m.__metadata.name}) must define an ${triggerName} function`),
34
+ describe: m => describeEvent(m.__metadata),
35
+ };
36
+ }
37
+
38
+ module.exports = { eventKind, describeEvent };
@@ -0,0 +1,6 @@
1
+ const { eventKind } = require('./event');
2
+
3
+ /**
4
+ * Registry kind for snapshot event modules (see registry)
5
+ */
6
+ module.exports = eventKind('snapshot', 'api');
package/kind/type.js ADDED
@@ -0,0 +1,21 @@
1
+ const assert = require('assert');
2
+ const _ = require('lodash');
3
+
4
+ /**
5
+ * Names of a model's attributes; attributes may be a map or an array of specs ({ name, ... })
6
+ */
7
+ function attributeNames({ attributes }) {
8
+ if (_.isArray(attributes)) return attributes.map(a => a.name);
9
+
10
+ return Object.keys(attributes || {});
11
+ }
12
+
13
+ /**
14
+ * Registry kind for type modules ({ TYPE, model }, see gell-domain) (see registry)
15
+ */
16
+ module.exports = {
17
+ kind: 'type',
18
+ nameOf: m => m.model && m.model.name,
19
+ validate: m => assert(_.isString(m.TYPE), `type (name=${m.model.name}) must define TYPE`),
20
+ describe: m => ({ name: m.model.name, type: m.TYPE, attributes: attributeNames(m.model) }),
21
+ };
@@ -1,50 +1,50 @@
1
- const _ = require('lodash');
1
+ const assert = require('assert');
2
+
3
+ const { compileParams } = require('gell-domain/event/compiler');
4
+ const { validate } = require('gell-domain/type/javascript');
2
5
 
3
6
  const { error } = require('../util/error');
4
7
 
5
- const MESSAGE_REQUIRED_PARAMETER = 'call to event trigger (route="%s") does not provide required argument (name="%s")';
6
- const MESSAGE_PARAMETER_MAXLENGTH = 'call to event trigger (route="%s") has argument (name="%s") that exceeds maximum allowed length';
7
- const MESSAGE_PARAMETER_TYPE = 'call to event trigger (route="%s") has argument (name="%s") that is not of type (type="%s")';
8
+ // NOTE: validation failures are the caller's fault, so the API answers them with 400 (gell-http/next/api uses e.status)
9
+ const STATUS = 400;
10
+
11
+ function doValidate(event, resume, TYPES) {
12
+ const { params: values, __invocationSpec, deps } = event;
8
13
 
9
- /**
10
- * gell-dispatch middleware that validates event invocation parameters against the event metadata
11
- *
12
- * WIP: use gell-domain here to validate this correctly
13
- *
14
- * WIP: this isn't yet re-usable because of the error message
15
- * - one approach would be to collect validation failures and throw at the end
16
- * - short circuit
17
- */
18
- module.exports = function(event, resume) {
19
- const { params: values, __invocationSpec } = event;
20
-
21
14
  if (!__invocationSpec) return resume(event);
22
-
23
- const metadata = __invocationSpec.triggerSpec.params || {};
24
- const route = __invocationSpec.route;
25
15
 
26
- const keys = Object.keys(metadata || {});
27
- keys.forEach(n => {
28
- const param = metadata[n];
29
- const val = values[n];
16
+ const { route, triggerSpec } = __invocationSpec;
17
+ const params = compileParams(triggerSpec.params);
30
18
 
31
- if (val === undefined && !param.optional) {
32
- throw error('RequiredParameterError', MESSAGE_REQUIRED_PARAMETER, { route, parameter: n }, route, n);
33
- }
19
+ // NOTE: gell-domain names a failure's property; the middleware reports it as the parameter
20
+ const errors = validate(values || {}, params, TYPES, true).map(({ property, ...failure }) => ({ parameter: property, ...failure }));
34
21
 
35
- // NOTE: omitted optional parameters are not type checked
36
- if (val === undefined) return;
22
+ if (errors.length) {
23
+ const logger = deps.resolveSingle('logger');
37
24
 
38
- if (param.type === 'string') {
39
- if (!_.isString(val)) {
40
- throw error('ParameterValidationError', MESSAGE_PARAMETER_TYPE, { route, parameter: n, type: param.type }, route, n, param.type);
41
- }
25
+ errors.forEach(({ parameter, rule }) => logger.info(`parameter validation failed (route="${route}"; parameter="${parameter}"; rule="${rule}")`));
42
26
 
43
- if (param.maxLength && val.length > param.maxLength) {
44
- throw error('ParameterValidationError', MESSAGE_PARAMETER_MAXLENGTH, { route, parameter: n }, route, n);
45
- }
46
- }
47
- })
27
+ throw error('ParameterValidationError', '%s', { status: STATUS, route, errors }, errors.map(({ message }) => message).join('; '));
28
+ }
48
29
 
49
30
  return resume(event);
50
31
  }
32
+
33
+ /**
34
+ * gell-dispatch middleware that validates event invocation parameters against the event metadata
35
+ * - the params are validated with gell-domain/type/javascript validate (it defines what a param spec can declare:
36
+ * rules, messages, items, a validate function), against the types it is given (the application's compiled
37
+ * types, e.g. gell-domain/type/compiler compile([...appTypes]))
38
+ * - collects every failure of the call, then throws one ParameterValidationError (status 400) whose message joins
39
+ * the readable messages with '; ', and whose errors lists the failures ({ parameter, rule, message })
40
+ * - a mistake in the metadata (e.g. a rule the type does not define) is a bug, not a validation failure: its
41
+ * AssertionError propagates (500)
42
+ *
43
+ * WIP: errors stays server-side (logs, tests, direct callers); per-field form errors need gell-http (or a wrapper)
44
+ * and bh-react useAction to pass errors through to the browser
45
+ */
46
+ module.exports = function(types) {
47
+ assert(types, 'compiled types is required');
48
+
49
+ return (event, resume) => doValidate(event, resume, types);
50
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gell-dispatch",
3
- "version": "0.0.1",
3
+ "version": "0.1.0",
4
4
  "description": "Event dispatch bus and middleware for gell",
5
5
  "scripts": {
6
6
  "test": "mocha"
@@ -10,6 +10,11 @@
10
10
  ],
11
11
  "author": "Daniel Gay",
12
12
  "license": "ISC",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/djghokie/gell-dispatch.git"
16
+ },
17
+ "homepage": "https://github.com/djghokie/gell-dispatch#readme",
13
18
  "engines": {
14
19
  "node": "^20.19.0 || >=22.12.0"
15
20
  },
@@ -19,6 +24,7 @@
19
24
  "mocha": "^8.4.0"
20
25
  },
21
26
  "dependencies": {
27
+ "gell-domain": "^1.1.2",
22
28
  "gell-state": "^1.0.0",
23
29
  "lodash": "^4.18.1"
24
30
  }
package/registry.js ADDED
@@ -0,0 +1,97 @@
1
+ const assert = require('assert');
2
+ const _ = require('lodash');
3
+
4
+ /**
5
+ * Registry of named declarations of a single kind (e.g. actions, snapshots, types, named queries)
6
+ * - an application has many registries, one per kind of declaration
7
+ * - kind specific behavior is supplied by a kind object
8
+ * - kind: name of the kind, used in error messages
9
+ * - nameOf(decl): returns the declaration's name
10
+ * - validate(decl): optional; throws if the declaration is invalid
11
+ * - describe(decl): optional; returns plain object metadata (no functions) for the declaration
12
+ * - stores the original declaration; callers need it to execute (e.g. query, action)
13
+ *
14
+ * WIP: compile step normalizing declarations (future kind hook)
15
+ */
16
+ class Registry {
17
+
18
+ #kind;
19
+
20
+ #declarations = new Map();
21
+
22
+ constructor(kind) {
23
+ assert(kind && _.isFunction(kind.nameOf), 'kind with nameOf function is required');
24
+
25
+ this.#kind = { kind: 'declaration', ...kind };
26
+ }
27
+
28
+ /**
29
+ * Returns the name of a valid declaration; throws if the declaration can't be registered
30
+ */
31
+ #check(decl, names=this.#declarations) {
32
+ const { kind, nameOf, validate } = this.#kind;
33
+
34
+ assert(_.isObjectLike(decl), `${kind} declaration must be an object`);
35
+
36
+ const name = nameOf(decl);
37
+
38
+ assert(_.isString(name) && name.length > 0, `${kind} must define a name to be registered`);
39
+ assert(!names.has(name), `${kind} (name=${name}) is already registered`);
40
+
41
+ if (validate) validate(decl);
42
+
43
+ return name;
44
+ }
45
+
46
+ register(decl) {
47
+ this.#declarations.set(this.#check(decl), decl);
48
+
49
+ return decl;
50
+ }
51
+
52
+ /**
53
+ * Registers every value of an object (e.g. a module's exports) or every item of an iterable
54
+ * - nothing is registered if any declaration can't be registered
55
+ */
56
+ registerAll(decls) {
57
+ assert(_.isObjectLike(decls), `${this.#kind.kind} declarations must be an object or iterable`);
58
+
59
+ const list = _.isFunction(decls[Symbol.iterator]) ? [...decls] : Object.values(decls);
60
+
61
+ const pending = new Map(this.#declarations);
62
+ list.forEach(decl => pending.set(this.#check(decl, pending), decl));
63
+
64
+ this.#declarations = pending;
65
+
66
+ return list;
67
+ }
68
+
69
+ get(name) {
70
+ return this.#declarations.get(name);
71
+ }
72
+
73
+ has(name) {
74
+ return this.#declarations.has(name);
75
+ }
76
+
77
+ names() {
78
+ return [...this.#declarations.keys()];
79
+ }
80
+
81
+ describe(name) {
82
+ const decl = this.get(name);
83
+
84
+ if (!decl) return;
85
+
86
+ const { describe } = this.#kind;
87
+
88
+ return { ...(describe ? describe(decl) : {}), name };
89
+ }
90
+
91
+ describeAll() {
92
+ return this.names().map(name => this.describe(name));
93
+ }
94
+
95
+ }
96
+
97
+ module.exports = Registry;