@pithyjs/mcp 0.0.0-stage → 0.1.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +123 -2
- package/dist/cli.d.ts +3 -0
- package/dist/cli.js +74 -0
- package/dist/errors/catalog.d.ts +48 -0
- package/dist/errors/catalog.js +252 -0
- package/dist/guard.d.ts +41 -0
- package/dist/guard.js +140 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/knowledge.d.ts +157 -0
- package/dist/knowledge.js +163 -0
- package/dist/lookup.d.ts +47 -0
- package/dist/lookup.js +69 -0
- package/dist/pidl.d.ts +27 -0
- package/dist/pidl.js +251 -0
- package/dist/scaffold.d.ts +54 -0
- package/dist/scaffold.js +280 -0
- package/dist/search.d.ts +37 -0
- package/dist/search.js +129 -0
- package/dist/server.d.ts +25 -0
- package/dist/server.js +126 -0
- package/dist/snapshot.json +1 -0
- package/dist/template.d.ts +26 -0
- package/dist/template.js +66 -0
- package/dist/tokens.d.ts +71 -0
- package/dist/tokens.js +420 -0
- package/package.json +56 -3
package/dist/pidl.js
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
/** @codex { "id": "pithy.mcp.pidl", "title": "MCP PIDL Validator", "category": "feature", "risk": "medium" } */
|
|
2
|
+
import { extractDocs, extractPublic, } from '@pithyjs/ui-kit/registry/pidl-extract';
|
|
3
|
+
import { guardInput } from './guard.js';
|
|
4
|
+
const CITATIONS = [
|
|
5
|
+
{ file: 'docs/site-builder/features/pidl.md' },
|
|
6
|
+
{ file: 'packages/pidl-catalog/specs' },
|
|
7
|
+
{ file: 'packages/ui-kit/src/registry/pidl-extract.ts' },
|
|
8
|
+
];
|
|
9
|
+
// extractPublic prefixes `PIDL <file>: `; the rest names the field.
|
|
10
|
+
const CONSUMER_PATH = [
|
|
11
|
+
[/^slots\[(\d+)\](\.\w+)?/, m => m[0]],
|
|
12
|
+
[/^prop\[(\d+)\]/, m => `props[${m[1]}]`],
|
|
13
|
+
[/required string field "(\w+)"/, m => m[1]],
|
|
14
|
+
[/^invalid (level|domain)\b/, m => m[1]],
|
|
15
|
+
[/^icon\b/, () => 'icon'],
|
|
16
|
+
[/^examples\[(\d+)\](\.\w+)?/, m => m[0]],
|
|
17
|
+
[/^a11y(?: at "([^"]+)")?/, m => (m[1] ? `a11y.${m[1]}` : 'a11y')],
|
|
18
|
+
[/^missing non-empty string "(\w+)"/, m => m[1]],
|
|
19
|
+
];
|
|
20
|
+
function consumerPath(spec, message) {
|
|
21
|
+
for (const [re, to] of CONSUMER_PATH) {
|
|
22
|
+
const m = re.exec(message);
|
|
23
|
+
if (m)
|
|
24
|
+
return to(m);
|
|
25
|
+
}
|
|
26
|
+
const prop = /^prop "([^"]+)"/.exec(message);
|
|
27
|
+
if (prop && Array.isArray(spec.props)) {
|
|
28
|
+
const i = spec.props.findIndex(p => isObj(p) && p.name === prop[1]);
|
|
29
|
+
if (i >= 0) {
|
|
30
|
+
const field = / (editor\.\w+|kind|visibleWhen|enum|valueKinds)\b/.exec(message);
|
|
31
|
+
return `props[${i}]${field ? `.${field[1]}` : ''}`;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return '';
|
|
35
|
+
}
|
|
36
|
+
const short = (key) => key.length > 80 ? `${key.slice(0, 80)}… (${key.length} characters)` : key;
|
|
37
|
+
const ENTITY_KINDS = [
|
|
38
|
+
'design-token',
|
|
39
|
+
'utility',
|
|
40
|
+
'directive',
|
|
41
|
+
'component',
|
|
42
|
+
'pattern',
|
|
43
|
+
'layout',
|
|
44
|
+
];
|
|
45
|
+
const LEVELS = ['atom', 'molecule', 'organism', 'section'];
|
|
46
|
+
const KNOWN_FIELDS = new Set([
|
|
47
|
+
'kind',
|
|
48
|
+
'id',
|
|
49
|
+
'name',
|
|
50
|
+
'displayName',
|
|
51
|
+
'version',
|
|
52
|
+
'level',
|
|
53
|
+
'domain',
|
|
54
|
+
'icon',
|
|
55
|
+
'bidi',
|
|
56
|
+
'description',
|
|
57
|
+
'props',
|
|
58
|
+
'events',
|
|
59
|
+
'slots',
|
|
60
|
+
'tokens',
|
|
61
|
+
'spacing',
|
|
62
|
+
'constraints',
|
|
63
|
+
'a11y',
|
|
64
|
+
'ai',
|
|
65
|
+
'examples',
|
|
66
|
+
'designGuidance',
|
|
67
|
+
'studioReady',
|
|
68
|
+
'itemSchema',
|
|
69
|
+
'requiredProps',
|
|
70
|
+
]);
|
|
71
|
+
const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
72
|
+
const isStr = (v) => typeof v === 'string';
|
|
73
|
+
const isStrArr = (v) => Array.isArray(v) && v.every(isStr);
|
|
74
|
+
/**
|
|
75
|
+
* Validates a PIDL component spec against the format in
|
|
76
|
+
* `docs/site-builder/features/pidl.md`, the conventions every spec in
|
|
77
|
+
* `@pithyjs/pidl-catalog` follows, and then the registry's own
|
|
78
|
+
* `extractPublic`, so a valid spec is one the registry accepts.
|
|
79
|
+
*
|
|
80
|
+
* @param input - The spec, as an object or as JSON text.
|
|
81
|
+
* @returns Errors and warnings by JSON path.
|
|
82
|
+
*/
|
|
83
|
+
/** @codexApi {"parent":"pithy.mcp.pidl","name":"validatePidl","stability":"experimental","signature":"(input: unknown) => PidlResult"} */
|
|
84
|
+
export function validatePidl(input) {
|
|
85
|
+
const errors = [];
|
|
86
|
+
const warnings = [];
|
|
87
|
+
const err = (path, message) => errors.push({ path, message });
|
|
88
|
+
const done = () => ({
|
|
89
|
+
valid: errors.length === 0,
|
|
90
|
+
errors,
|
|
91
|
+
warnings,
|
|
92
|
+
citations: CITATIONS,
|
|
93
|
+
});
|
|
94
|
+
let spec = input;
|
|
95
|
+
if (isStr(input)) {
|
|
96
|
+
try {
|
|
97
|
+
spec = JSON.parse(input);
|
|
98
|
+
}
|
|
99
|
+
catch (e) {
|
|
100
|
+
err('', `Not valid JSON: ${e.message}`);
|
|
101
|
+
return done();
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
guardInput(spec);
|
|
105
|
+
}
|
|
106
|
+
catch (e) {
|
|
107
|
+
err('', e.message);
|
|
108
|
+
return done();
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
if (!isObj(spec)) {
|
|
112
|
+
err('', 'A spec is a JSON object.');
|
|
113
|
+
return done();
|
|
114
|
+
}
|
|
115
|
+
if (spec.kind !== 'component') {
|
|
116
|
+
err('kind', ENTITY_KINDS.includes(String(spec.kind))
|
|
117
|
+
? `Only "component" specs can be validated, not "${String(spec.kind)}".`
|
|
118
|
+
: `Must be "component".`);
|
|
119
|
+
}
|
|
120
|
+
const requireStr = (key, re, hint) => {
|
|
121
|
+
const v = spec[key];
|
|
122
|
+
if (!isStr(v) || v.trim() === '')
|
|
123
|
+
err(key, 'Required non-empty string.');
|
|
124
|
+
else if (re && !re.test(v))
|
|
125
|
+
err(key, hint ?? `Must match ${re}.`);
|
|
126
|
+
};
|
|
127
|
+
requireStr('id', /^ui\.[a-z0-9]+(?:-[a-z0-9]+)*$/, 'Must be "ui." plus a kebab-case name, e.g. "ui.page-section".');
|
|
128
|
+
requireStr('name', /^[A-Z][A-Za-z0-9]*$/, 'Must be the PascalCase component name.');
|
|
129
|
+
requireStr('displayName');
|
|
130
|
+
requireStr('version', /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/, 'Must be a semver version.');
|
|
131
|
+
if (!LEVELS.includes(String(spec.level)))
|
|
132
|
+
err('level', `Must be one of ${LEVELS.join(', ')}.`);
|
|
133
|
+
requireStr('domain');
|
|
134
|
+
requireStr('icon');
|
|
135
|
+
if (typeof spec.bidi !== 'boolean')
|
|
136
|
+
err('bidi', 'Required boolean.');
|
|
137
|
+
requireStr('description');
|
|
138
|
+
const names = new Set();
|
|
139
|
+
if (!Array.isArray(spec.props))
|
|
140
|
+
err('props', 'Required array.');
|
|
141
|
+
else
|
|
142
|
+
spec.props.forEach((p, i) => {
|
|
143
|
+
const at = `props[${i}]`;
|
|
144
|
+
if (!isObj(p))
|
|
145
|
+
return err(at, 'A prop is an object.');
|
|
146
|
+
if (!isStr(p.name) || !/^[A-Za-z_$][\w$-]*$/.test(p.name))
|
|
147
|
+
err(`${at}.name`, 'Required identifier.');
|
|
148
|
+
else if (names.has(p.name))
|
|
149
|
+
err(`${at}.name`, `Duplicate prop "${p.name}".`);
|
|
150
|
+
else
|
|
151
|
+
names.add(p.name);
|
|
152
|
+
if (!isStr(p.type) || p.type.trim() === '')
|
|
153
|
+
err(`${at}.type`, 'Required non-empty string.');
|
|
154
|
+
if (!isStr(p.description))
|
|
155
|
+
err(`${at}.description`, 'Required string.');
|
|
156
|
+
// `placeholder` is sample data, of the prop's own type.
|
|
157
|
+
if (p.label !== undefined && !isStr(p.label))
|
|
158
|
+
err(`${at}.label`, 'Must be a string.');
|
|
159
|
+
for (const key of ['required', 'reactive'])
|
|
160
|
+
if (p[key] !== undefined && typeof p[key] !== 'boolean')
|
|
161
|
+
err(`${at}.${key}`, 'Must be a boolean.');
|
|
162
|
+
if (p.enum !== undefined) {
|
|
163
|
+
const ok = Array.isArray(p.enum) &&
|
|
164
|
+
p.enum.length > 0 &&
|
|
165
|
+
p.enum.every(v => isStr(v) || typeof v === 'number');
|
|
166
|
+
if (!ok)
|
|
167
|
+
err(`${at}.enum`, 'Must be a non-empty array of strings or numbers.');
|
|
168
|
+
else if (p.default !== undefined &&
|
|
169
|
+
!p.enum.includes(p.default))
|
|
170
|
+
err(`${at}.default`, `Default ${JSON.stringify(p.default)} is not one of the enum values.`);
|
|
171
|
+
}
|
|
172
|
+
else if (p.type === 'enum')
|
|
173
|
+
err(`${at}.enum`, 'An enum prop lists its values in "enum".');
|
|
174
|
+
if (p.editor !== undefined && !isObj(p.editor))
|
|
175
|
+
err(`${at}.editor`, 'Must be an object.');
|
|
176
|
+
});
|
|
177
|
+
if (spec.requiredProps !== undefined) {
|
|
178
|
+
if (!isStrArr(spec.requiredProps))
|
|
179
|
+
err('requiredProps', 'Must be an array of prop names.');
|
|
180
|
+
else
|
|
181
|
+
spec.requiredProps.forEach((n, i) => {
|
|
182
|
+
if (!names.has(n))
|
|
183
|
+
err(`requiredProps[${i}]`, `No prop named "${n}".`);
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
if (spec.events !== undefined) {
|
|
187
|
+
if (!Array.isArray(spec.events))
|
|
188
|
+
err('events', 'Must be an array.');
|
|
189
|
+
else
|
|
190
|
+
spec.events.forEach((e, i) => {
|
|
191
|
+
if (!isStr(e) && !(isObj(e) && isStr(e.name)))
|
|
192
|
+
err(`events[${i}]`, 'An event is a name, or an object with a "name".');
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
if (spec.slots !== undefined && !Array.isArray(spec.slots))
|
|
196
|
+
err('slots', 'Must be an array.');
|
|
197
|
+
for (const key of ['tokens', 'spacing']) {
|
|
198
|
+
if (!isObj(spec[key]))
|
|
199
|
+
err(key, 'Required object.');
|
|
200
|
+
}
|
|
201
|
+
if (!isStrArr(spec.constraints))
|
|
202
|
+
err('constraints', 'Required array of strings.');
|
|
203
|
+
if (!isStrArr(spec.a11y) && !isObj(spec.a11y))
|
|
204
|
+
err('a11y', 'Required array of strings, or an object of rules.');
|
|
205
|
+
if (!isObj(spec.ai))
|
|
206
|
+
err('ai', 'Required object.');
|
|
207
|
+
else
|
|
208
|
+
for (const key of ['synonyms', 'avoid', 'patterns']) {
|
|
209
|
+
if (!isStrArr(spec.ai[key]))
|
|
210
|
+
err(`ai.${key}`, 'Required array of strings.');
|
|
211
|
+
}
|
|
212
|
+
if (!Array.isArray(spec.examples) || spec.examples.length === 0) {
|
|
213
|
+
err('examples', 'Required non-empty array.');
|
|
214
|
+
}
|
|
215
|
+
else {
|
|
216
|
+
const ids = new Set();
|
|
217
|
+
spec.examples.forEach((x, i) => {
|
|
218
|
+
const at = `examples[${i}]`;
|
|
219
|
+
if (!isObj(x) || !isStr(x.id) || !isStr(x.title))
|
|
220
|
+
return err(at, 'An example has a string "id" and "title".');
|
|
221
|
+
if (!isStr(x.pithy) && !isStr(x.code))
|
|
222
|
+
return err(at, 'An example carries "pithy" markup or "code".');
|
|
223
|
+
if (!isStrArr(x.assertions))
|
|
224
|
+
return err(`${at}.assertions`, 'Required array of strings.');
|
|
225
|
+
if (ids.has(x.id))
|
|
226
|
+
err(`${at}.id`, `Duplicate example id "${x.id}".`);
|
|
227
|
+
ids.add(x.id);
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
for (const key of ['designGuidance', 'itemSchema'])
|
|
231
|
+
if (spec[key] !== undefined && !isObj(spec[key]))
|
|
232
|
+
err(key, 'Must be an object.');
|
|
233
|
+
if (spec.studioReady !== undefined && typeof spec.studioReady !== 'boolean')
|
|
234
|
+
err('studioReady', 'Must be a boolean.');
|
|
235
|
+
for (const key of Object.keys(spec))
|
|
236
|
+
if (!KNOWN_FIELDS.has(key))
|
|
237
|
+
warnings.push({ path: short(key), message: 'Not a PIDL field.' });
|
|
238
|
+
// The registry's own two stages, as sync-registry runs them: metadata
|
|
239
|
+
// (domains, editor, slots, visibleWhen, icons), then docs (a11y, examples).
|
|
240
|
+
if (errors.length === 0) {
|
|
241
|
+
try {
|
|
242
|
+
extractPublic(spec, 'spec');
|
|
243
|
+
extractDocs(spec, 'spec');
|
|
244
|
+
}
|
|
245
|
+
catch (e) {
|
|
246
|
+
const message = e.message.replace(/^PIDL spec: /, '');
|
|
247
|
+
err(consumerPath(spec, message), message);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return done();
|
|
251
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/** @codex { "id": "pithy.mcp.scaffold", "title": "MCP Scaffolds", "category": "feature", "risk": "low" } */
|
|
2
|
+
import type { Knowledge } from './knowledge.js';
|
|
3
|
+
/** @codexApi {"parent":"pithy.mcp.scaffold","name":"ScaffoldFile","stability":"experimental","signature":"interface ScaffoldFile { path: string; contents: string }"} */
|
|
4
|
+
/** A file to create, at a path relative to the app root. */
|
|
5
|
+
export interface ScaffoldFile {
|
|
6
|
+
path: string;
|
|
7
|
+
contents: string;
|
|
8
|
+
}
|
|
9
|
+
/** @codexApi {"parent":"pithy.mcp.scaffold","name":"Scaffold","stability":"experimental","signature":"interface Scaffold { files: ScaffoldFile[] }"} */
|
|
10
|
+
/** Files for the caller to write; nothing is written here. */
|
|
11
|
+
export interface Scaffold {
|
|
12
|
+
files: ScaffoldFile[];
|
|
13
|
+
}
|
|
14
|
+
/** @codexApi {"parent":"pithy.mcp.scaffold","name":"ComponentKind","stability":"experimental","signature":"type ComponentKind = 'atom' | 'molecule' | 'organism' | 'section'"} */
|
|
15
|
+
/** The PIDL level of a scaffolded component. */
|
|
16
|
+
export type ComponentKind = 'atom' | 'molecule' | 'organism' | 'section';
|
|
17
|
+
/**
|
|
18
|
+
* Files for one route under `src/routes`: `page.ts`, plus `loader.ts` and
|
|
19
|
+
* `layout.ts` on request. Route files never take a `+` prefix and are never
|
|
20
|
+
* `.pithy`. Pages compose `@pithyjs/ui-kit` primitives.
|
|
21
|
+
*
|
|
22
|
+
* @param path - The route directory, such as `/blog/[slug]` or `(mkt)/about`.
|
|
23
|
+
* @param options - `loader` adds a typed loader the page reads; `layout` adds a layout with the router outlet.
|
|
24
|
+
* @returns The files to create.
|
|
25
|
+
* @throws When a segment is not one the router scanner reads.
|
|
26
|
+
*/
|
|
27
|
+
/** @codexApi {"parent":"pithy.mcp.scaffold","name":"scaffoldRoute","stability":"experimental","signature":"(path: string, options?: { loader?: boolean; layout?: boolean }) => Scaffold"} */
|
|
28
|
+
export declare function scaffoldRoute(path: string, options?: {
|
|
29
|
+
loader?: boolean;
|
|
30
|
+
layout?: boolean;
|
|
31
|
+
}): Scaffold;
|
|
32
|
+
/**
|
|
33
|
+
* Names a new component must not take: every PIDL component, and every
|
|
34
|
+
* PascalCase function or const `@pithyjs/ui-kit` exports (`Show`, `For`…).
|
|
35
|
+
*
|
|
36
|
+
* @param k - The knowledge to read.
|
|
37
|
+
* @returns The names, sorted.
|
|
38
|
+
*/
|
|
39
|
+
/** @codexApi {"parent":"pithy.mcp.scaffold","name":"takenComponentNames","stability":"experimental","signature":"(k: Knowledge) => string[]"} */
|
|
40
|
+
export declare function takenComponentNames(k: Knowledge): string[];
|
|
41
|
+
/**
|
|
42
|
+
* A component for an app: a `.ts` module that composes `@pithyjs/ui-kit`
|
|
43
|
+
* primitives and returns the `html` handle (`{ el, destroy }`; register
|
|
44
|
+
* cleanup with `onDestroy` before it), a token-only SCSS file with
|
|
45
|
+
* logical properties, and a co-located `.pidl.json` spec.
|
|
46
|
+
*
|
|
47
|
+
* @param name - PascalCase, such as `ProfileCard`.
|
|
48
|
+
* @param kind - The PIDL level; a `section` gets a level-2 heading. Default `molecule`.
|
|
49
|
+
* @returns The files to create, under `src/components/<name>/`.
|
|
50
|
+
* @param existing - Names already taken, such as the ui-kit components.
|
|
51
|
+
* @throws When `name` is not PascalCase, or is in `existing`.
|
|
52
|
+
*/
|
|
53
|
+
/** @codexApi {"parent":"pithy.mcp.scaffold","name":"scaffoldComponent","stability":"experimental","signature":"(name: string, kind?: ComponentKind, existing?: readonly string[]) => Scaffold"} */
|
|
54
|
+
export declare function scaffoldComponent(name: string, kind?: ComponentKind, existing?: readonly string[]): Scaffold;
|
package/dist/scaffold.js
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
/** @codex { "id": "pithy.mcp.scaffold", "title": "MCP Scaffolds", "category": "feature", "risk": "low" } */
|
|
2
|
+
// What the router scanner reads: static, (group), [param] and [...rest].
|
|
3
|
+
const SEGMENT = /^(?:[a-z0-9]+(?:-[a-z0-9]+)*|\([a-z0-9]+(?:-[a-z0-9]+)*\)|\[(?:\.\.\.)?[A-Za-z_][A-Za-z0-9_]*\])$/;
|
|
4
|
+
const pascal = (s) => s
|
|
5
|
+
.replace(/[[\]().]/g, ' ')
|
|
6
|
+
.split(/[^A-Za-z0-9]+/)
|
|
7
|
+
.filter(Boolean)
|
|
8
|
+
.map(w => w[0].toUpperCase() + w.slice(1))
|
|
9
|
+
.join('');
|
|
10
|
+
const kebab = (name) => name
|
|
11
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
|
|
12
|
+
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
|
|
13
|
+
.toLowerCase();
|
|
14
|
+
const words = (name) => kebab(name).replace(/-/g, ' ');
|
|
15
|
+
const sentence = (name) => {
|
|
16
|
+
const w = words(name);
|
|
17
|
+
return w[0].toUpperCase() + w.slice(1);
|
|
18
|
+
};
|
|
19
|
+
const RETURN_TYPE = '{ el: HTMLElement | DocumentFragment; destroy: () => void }';
|
|
20
|
+
/**
|
|
21
|
+
* Files for one route under `src/routes`: `page.ts`, plus `loader.ts` and
|
|
22
|
+
* `layout.ts` on request. Route files never take a `+` prefix and are never
|
|
23
|
+
* `.pithy`. Pages compose `@pithyjs/ui-kit` primitives.
|
|
24
|
+
*
|
|
25
|
+
* @param path - The route directory, such as `/blog/[slug]` or `(mkt)/about`.
|
|
26
|
+
* @param options - `loader` adds a typed loader the page reads; `layout` adds a layout with the router outlet.
|
|
27
|
+
* @returns The files to create.
|
|
28
|
+
* @throws When a segment is not one the router scanner reads.
|
|
29
|
+
*/
|
|
30
|
+
/** @codexApi {"parent":"pithy.mcp.scaffold","name":"scaffoldRoute","stability":"experimental","signature":"(path: string, options?: { loader?: boolean; layout?: boolean }) => Scaffold"} */
|
|
31
|
+
export function scaffoldRoute(path, options = {}) {
|
|
32
|
+
const trimmed = path.trim().replace(/^\/+|\/+$/g, '');
|
|
33
|
+
const segments = trimmed === '' ? [] : trimmed.split('/');
|
|
34
|
+
for (const s of segments) {
|
|
35
|
+
if (!SEGMENT.test(s)) {
|
|
36
|
+
throw new Error(`Route segment "${s}" is not one the router reads: use lowercase kebab-case, (group), [param] or [...rest].`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
// The matcher stops at a catch-all, so a later segment would never be matched.
|
|
40
|
+
const urlSegments = segments.filter(s => !s.startsWith('('));
|
|
41
|
+
const rest = urlSegments.findIndex(s => s.startsWith('[...'));
|
|
42
|
+
if (rest >= 0 && rest < urlSegments.length - 1) {
|
|
43
|
+
throw new Error(`The catch-all "${urlSegments[rest]}" must be the last URL segment; the router matches everything after it.`);
|
|
44
|
+
}
|
|
45
|
+
const params = urlSegments
|
|
46
|
+
.filter(s => s.startsWith('['))
|
|
47
|
+
.map(s => s.replace(/^\[(?:\.\.\.)?|\]$/g, ''));
|
|
48
|
+
const twice = params.find((p, i) => params.indexOf(p) !== i);
|
|
49
|
+
if (twice) {
|
|
50
|
+
throw new Error(`The param "${twice}" is used twice; the second would overwrite the first in params.`);
|
|
51
|
+
}
|
|
52
|
+
const dir = ['src/routes', ...segments].join('/');
|
|
53
|
+
// `[_]` has no letters, so it falls back to `Param` rather than `Home`.
|
|
54
|
+
const named = urlSegments
|
|
55
|
+
.map(s => pascal(s) || (s.startsWith('[') ? 'Param' : ''))
|
|
56
|
+
.join('');
|
|
57
|
+
const title = named ? sentence(named) : 'Home';
|
|
58
|
+
// An identifier cannot start with a digit: `/404` → `Route404Page`.
|
|
59
|
+
const base = !named ? 'Home' : /^\d/.test(named) ? `Route${named}` : named;
|
|
60
|
+
const url = `/${urlSegments.join('/')}`;
|
|
61
|
+
const dataType = `${base}Data`;
|
|
62
|
+
const files = [];
|
|
63
|
+
const page = options.loader
|
|
64
|
+
? `import { html } from '@pithyjs/core';
|
|
65
|
+
import { getGlobalRouter } from '@pithyjs/router';
|
|
66
|
+
import { Heading, Text } from '@pithyjs/ui-kit';
|
|
67
|
+
import type { ${dataType} } from './loader';
|
|
68
|
+
|
|
69
|
+
/** The \`${url}\` route. */
|
|
70
|
+
export default function ${base}Page(): ${RETURN_TYPE} {
|
|
71
|
+
const state = getGlobalRouter()?.loaderData();
|
|
72
|
+
const message = (): string =>
|
|
73
|
+
(state?.()?.data as ${dataType} | undefined)?.message ?? '';
|
|
74
|
+
|
|
75
|
+
return html\`
|
|
76
|
+
<Heading level="1" text="'${title}'" />
|
|
77
|
+
<Text text="message()" />
|
|
78
|
+
\`;
|
|
79
|
+
}
|
|
80
|
+
`
|
|
81
|
+
: `import { html } from '@pithyjs/core';
|
|
82
|
+
import { Heading, Text } from '@pithyjs/ui-kit';
|
|
83
|
+
|
|
84
|
+
/** The \`${url}\` route. */
|
|
85
|
+
export default function ${base}Page(): ${RETURN_TYPE} {
|
|
86
|
+
return html\`
|
|
87
|
+
<Heading level="1" text="'${title}'" />
|
|
88
|
+
<Text text="'${title} content goes here.'" />
|
|
89
|
+
\`;
|
|
90
|
+
}
|
|
91
|
+
`;
|
|
92
|
+
files.push({ path: `${dir}/page.ts`, contents: page });
|
|
93
|
+
if (options.loader) {
|
|
94
|
+
files.push({
|
|
95
|
+
path: `${dir}/loader.ts`,
|
|
96
|
+
contents: `import type { LoaderFunction } from '@pithyjs/router';
|
|
97
|
+
|
|
98
|
+
export interface ${dataType} {
|
|
99
|
+
message: string;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Runs before \`page.ts\` mounts. Return the page's data; pass \`signal\` to
|
|
104
|
+
* \`fetch\` so navigating away aborts the request.
|
|
105
|
+
*/
|
|
106
|
+
export const loader: LoaderFunction<${dataType}> = async ({ signal }) => {
|
|
107
|
+
signal.throwIfAborted();
|
|
108
|
+
return { message: '${title} loaded.' };
|
|
109
|
+
};
|
|
110
|
+
`,
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
if (options.layout) {
|
|
114
|
+
files.push({
|
|
115
|
+
path: `${dir}/layout.ts`,
|
|
116
|
+
contents: `import { html } from '@pithyjs/core';
|
|
117
|
+
import { PageSection } from '@pithyjs/ui-kit';
|
|
118
|
+
|
|
119
|
+
/** Wraps every route under \`${url}\`; child routes render in the outlet. */
|
|
120
|
+
export default function ${base}Layout(): ${RETURN_TYPE} {
|
|
121
|
+
return html\`
|
|
122
|
+
<PageSection as="'main'" contained="true" spacing="'md'">
|
|
123
|
+
<div @routerOutlet></div>
|
|
124
|
+
</PageSection>
|
|
125
|
+
\`;
|
|
126
|
+
}
|
|
127
|
+
`,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
return { files };
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Names a new component must not take: every PIDL component, and every
|
|
134
|
+
* PascalCase function or const `@pithyjs/ui-kit` exports (`Show`, `For`…).
|
|
135
|
+
*
|
|
136
|
+
* @param k - The knowledge to read.
|
|
137
|
+
* @returns The names, sorted.
|
|
138
|
+
*/
|
|
139
|
+
/** @codexApi {"parent":"pithy.mcp.scaffold","name":"takenComponentNames","stability":"experimental","signature":"(k: Knowledge) => string[]"} */
|
|
140
|
+
export function takenComponentNames(k) {
|
|
141
|
+
const names = new Set(k.components.map(c => c.name));
|
|
142
|
+
for (const a of k.entries.flatMap(e => e.apis)) {
|
|
143
|
+
if (a.place?.pkg === '@pithyjs/ui-kit' &&
|
|
144
|
+
(a.kind === 'function' || a.kind === 'const') &&
|
|
145
|
+
/^[A-Z][A-Za-z0-9]*$/.test(a.name))
|
|
146
|
+
names.add(a.name);
|
|
147
|
+
}
|
|
148
|
+
return [...names].sort();
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* A component for an app: a `.ts` module that composes `@pithyjs/ui-kit`
|
|
152
|
+
* primitives and returns the `html` handle (`{ el, destroy }`; register
|
|
153
|
+
* cleanup with `onDestroy` before it), a token-only SCSS file with
|
|
154
|
+
* logical properties, and a co-located `.pidl.json` spec.
|
|
155
|
+
*
|
|
156
|
+
* @param name - PascalCase, such as `ProfileCard`.
|
|
157
|
+
* @param kind - The PIDL level; a `section` gets a level-2 heading. Default `molecule`.
|
|
158
|
+
* @returns The files to create, under `src/components/<name>/`.
|
|
159
|
+
* @param existing - Names already taken, such as the ui-kit components.
|
|
160
|
+
* @throws When `name` is not PascalCase, or is in `existing`.
|
|
161
|
+
*/
|
|
162
|
+
/** @codexApi {"parent":"pithy.mcp.scaffold","name":"scaffoldComponent","stability":"experimental","signature":"(name: string, kind?: ComponentKind, existing?: readonly string[]) => Scaffold"} */
|
|
163
|
+
export function scaffoldComponent(name, kind = 'molecule', existing = []) {
|
|
164
|
+
if (!/^[A-Z][a-z0-9]*(?:[A-Z][a-z0-9]*)*$/.test(name) || name.length > 64) {
|
|
165
|
+
throw new Error(`Component name "${name}" must be PascalCase, such as ProfileCard.`);
|
|
166
|
+
}
|
|
167
|
+
if (existing.some(e => e.toLowerCase() === name.toLowerCase())) {
|
|
168
|
+
throw new Error(`"${name}" is already a @pithyjs/ui-kit export; import it, or pick another name.`);
|
|
169
|
+
}
|
|
170
|
+
const cls = kebab(name);
|
|
171
|
+
const label = sentence(name);
|
|
172
|
+
const dir = `src/components/${name}`;
|
|
173
|
+
const isSection = kind === 'section';
|
|
174
|
+
const root = isSection ? 'section' : 'div';
|
|
175
|
+
const title = isSection
|
|
176
|
+
? '<Heading level="2" text="title" />'
|
|
177
|
+
: `<Text as="'strong'" weight="'semibold'" text="title" />`;
|
|
178
|
+
const ts = `import { html } from '@pithyjs/core';
|
|
179
|
+
import { ${isSection ? 'Heading, ' : ''}Text } from '@pithyjs/ui-kit';
|
|
180
|
+
import './${cls}.scss';
|
|
181
|
+
|
|
182
|
+
export interface ${name}Props {
|
|
183
|
+
/** Shown as the ${isSection ? 'section heading' : 'title'}. */
|
|
184
|
+
title?: string;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** ${label}. */
|
|
188
|
+
export default function ${name}(props: ${name}Props = {}): ${RETURN_TYPE} {
|
|
189
|
+
const title = props.title ?? '${label}';
|
|
190
|
+
return html\`
|
|
191
|
+
<${root} class="${cls}">
|
|
192
|
+
${title}
|
|
193
|
+
<Text text="'${label} content goes here.'" />
|
|
194
|
+
</${root}>
|
|
195
|
+
\`;
|
|
196
|
+
}
|
|
197
|
+
`;
|
|
198
|
+
const scss = `@use "@pithyjs/design-system/a11y/styles/mixins" as a11y;
|
|
199
|
+
|
|
200
|
+
.${cls} {
|
|
201
|
+
--_${cls}-bg: var(--color-surface);
|
|
202
|
+
--_${cls}-color: var(--color-on-surface);
|
|
203
|
+
|
|
204
|
+
display: flex;
|
|
205
|
+
flex-direction: column;
|
|
206
|
+
gap: var(--space-sm);
|
|
207
|
+
padding-block: var(--space-md);
|
|
208
|
+
padding-inline: var(--space-md);
|
|
209
|
+
border: var(--border-width-thin) var(--border-style-solid) var(--color-border);
|
|
210
|
+
border-radius: var(--radius-md);
|
|
211
|
+
background: var(--_${cls}-bg);
|
|
212
|
+
color: var(--_${cls}-color);
|
|
213
|
+
|
|
214
|
+
@include a11y.forced-colors {
|
|
215
|
+
border-color: CanvasText;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
`;
|
|
219
|
+
const pidl = {
|
|
220
|
+
kind: 'component',
|
|
221
|
+
id: `ui.${cls}`,
|
|
222
|
+
name,
|
|
223
|
+
displayName: label,
|
|
224
|
+
version: '0.1.0',
|
|
225
|
+
level: kind,
|
|
226
|
+
domain: isSection ? 'sections' : 'content',
|
|
227
|
+
icon: 'square',
|
|
228
|
+
bidi: true,
|
|
229
|
+
description: `${label}.`,
|
|
230
|
+
props: [
|
|
231
|
+
{
|
|
232
|
+
name: 'title',
|
|
233
|
+
label: 'Title',
|
|
234
|
+
type: 'string',
|
|
235
|
+
default: label,
|
|
236
|
+
description: `Shown as the ${isSection ? 'section heading' : 'title'}.`,
|
|
237
|
+
},
|
|
238
|
+
],
|
|
239
|
+
tokens: {
|
|
240
|
+
bg: '--color-surface',
|
|
241
|
+
text: '--color-on-surface',
|
|
242
|
+
border: '--color-border',
|
|
243
|
+
radius: '--radius-md',
|
|
244
|
+
},
|
|
245
|
+
spacing: {
|
|
246
|
+
internal: '--space-md',
|
|
247
|
+
'title-to-content': '--space-sm (close friends)',
|
|
248
|
+
},
|
|
249
|
+
constraints: [
|
|
250
|
+
'Design tokens only; no raw colors or sizes.',
|
|
251
|
+
'Logical properties only.',
|
|
252
|
+
],
|
|
253
|
+
a11y: isSection
|
|
254
|
+
? ['Renders a <section> whose heading is a level-2 Heading.']
|
|
255
|
+
: ['The title is text, not a heading, so the page outline is unchanged.'],
|
|
256
|
+
ai: {
|
|
257
|
+
synonyms: [words(name)],
|
|
258
|
+
avoid: [],
|
|
259
|
+
patterns: [`<${name} title="'${label}'" />`],
|
|
260
|
+
},
|
|
261
|
+
examples: [
|
|
262
|
+
{
|
|
263
|
+
id: 'basic',
|
|
264
|
+
title: `Basic ${words(name)}`,
|
|
265
|
+
pithy: `<${name} title="'${label}'" />`,
|
|
266
|
+
assertions: [`shows "${label}"`, 'no violations in axe-core'],
|
|
267
|
+
},
|
|
268
|
+
],
|
|
269
|
+
};
|
|
270
|
+
return {
|
|
271
|
+
files: [
|
|
272
|
+
{ path: `${dir}/${name}.ts`, contents: ts },
|
|
273
|
+
{ path: `${dir}/${cls}.scss`, contents: scss },
|
|
274
|
+
{
|
|
275
|
+
path: `${dir}/${cls}.pidl.json`,
|
|
276
|
+
contents: `${JSON.stringify(pidl, null, 2)}\n`,
|
|
277
|
+
},
|
|
278
|
+
],
|
|
279
|
+
};
|
|
280
|
+
}
|
package/dist/search.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** @codex { "id": "pithy.mcp.search", "title": "MCP Search", "category": "feature", "risk": "low" } */
|
|
2
|
+
import { type Citation, type Knowledge } from './knowledge.js';
|
|
3
|
+
/** @codexApi {"parent":"pithy.mcp.search","name":"SearchHit","stability":"experimental","signature":"interface SearchHit"} */
|
|
4
|
+
/** One ranked result. `id` is an entry id, `"<entry id> <api>"`, or a component name. */
|
|
5
|
+
export interface SearchHit {
|
|
6
|
+
kind: 'entry' | 'api' | 'component';
|
|
7
|
+
id: string;
|
|
8
|
+
title: string;
|
|
9
|
+
entryId?: string;
|
|
10
|
+
summary: string | null;
|
|
11
|
+
score: number;
|
|
12
|
+
citations: Citation[];
|
|
13
|
+
}
|
|
14
|
+
/** @codexApi {"parent":"pithy.mcp.search","name":"MAX_SEARCH_LIMIT","stability":"experimental","signature":"50"} */
|
|
15
|
+
/** The most hits one search returns. */
|
|
16
|
+
export declare const MAX_SEARCH_LIMIT = 50;
|
|
17
|
+
/**
|
|
18
|
+
* Lowercased words of `text`, split on camelCase, punctuation and spaces.
|
|
19
|
+
*
|
|
20
|
+
* @param text - Any text.
|
|
21
|
+
* @returns Its words, in order.
|
|
22
|
+
*/
|
|
23
|
+
/** @codexApi {"parent":"pithy.mcp.search","name":"tokenize","stability":"experimental","signature":"(text: string) => string[]"} */
|
|
24
|
+
export declare function tokenize(text: string): string[];
|
|
25
|
+
/**
|
|
26
|
+
* Ranks entries, APIs and components against `query`. Each query word scores
|
|
27
|
+
* the best-weighted field holding it (half for a prefix match), and a whole
|
|
28
|
+
* name equal to the query scores 10 more. Ties sort by id, so results are
|
|
29
|
+
* deterministic.
|
|
30
|
+
*
|
|
31
|
+
* @param k - The knowledge to search.
|
|
32
|
+
* @param query - Free text.
|
|
33
|
+
* @param limit - At most this many hits, capped at {@link MAX_SEARCH_LIMIT}.
|
|
34
|
+
* @returns Hits with a score above zero, best first.
|
|
35
|
+
*/
|
|
36
|
+
/** @codexApi {"parent":"pithy.mcp.search","name":"search","stability":"experimental","signature":"(k: Knowledge, query: string, limit?: number) => SearchHit[]"} */
|
|
37
|
+
export declare function search(k: Knowledge, query: string, limit?: number): SearchHit[];
|