mnfst-types 0.1.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/README.md ADDED
@@ -0,0 +1,46 @@
1
+ # mnfst-types
2
+
3
+ Generate a `manifest.d.ts` file for a Manifest project so editors and AI coding assistants understand the shape of `$x.<source>`, `$route`, `$modify`, and the other Manifest magic globals.
4
+
5
+ ## Usage
6
+
7
+ From the root of a Manifest project (next to `manifest.json`):
8
+
9
+ ```bash
10
+ npx mnfst-types
11
+ ```
12
+
13
+ This writes `manifest.d.ts` in the current directory. Re-run it whenever you add or change a data source in `manifest.json`.
14
+
15
+ ## Options
16
+
17
+ ```
18
+ --manifest <path> Path to manifest.json (default: ./manifest.json)
19
+ --out <path> Output .d.ts path (default: ./manifest.d.ts)
20
+ --init Also write a baseline jsconfig.json (only if missing)
21
+ -h, --help Show usage
22
+ ```
23
+
24
+ ## How it works
25
+
26
+ 1. Reads `manifest.json` and walks each entry under `data`.
27
+ 2. For local CSV / JSON / YAML sources, samples the first ~50 rows to infer field types.
28
+ 3. For Appwrite-table sources, generates a row interface with `$id` plus an extension point.
29
+ 4. For Appwrite-bucket sources, types the source as `ManifestBucketSource`.
30
+ 5. Combines the inferred row types with the static ambient declarations and writes a single `manifest.d.ts`.
31
+
32
+ The generated file's static portion (magic globals, query operators, source-state flags) is fixed; only the section between `// AUGMENTATION:start` and `// AUGMENTATION:end` is regenerated on subsequent runs.
33
+
34
+ ## Companion: `manifest.json` JSON Schema
35
+
36
+ For autocomplete and validation in `manifest.json` itself, add a `$schema` reference at the top of the file:
37
+
38
+ ```json
39
+ {
40
+ "$schema": "https://manifestjs.org/manifest.schema.json",
41
+ "name": "My Project",
42
+ "data": { ... }
43
+ }
44
+ ```
45
+
46
+ VS Code and most JSON-aware editors will fetch and apply the schema automatically.
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../manifest.types.mjs';
3
+
4
+ main(process.argv.slice(2)).catch((err) => {
5
+ console.error('mnfst-types:', err.message || err);
6
+ process.exit(1);
7
+ });
@@ -0,0 +1,571 @@
1
+ // mnfst-types: generate manifest.d.ts for a Manifest project.
2
+ //
3
+ // Reads ./manifest.json, samples each data source (CSV / JSON / YAML or
4
+ // Appwrite-table config), and writes a single manifest.d.ts that contains
5
+ // the static ambient declarations plus a project-specific augmentation of
6
+ // the ManifestSources interface.
7
+ //
8
+ // Re-running the CLI overwrites the augmentation block (between the
9
+ // AUGMENTATION:start / AUGMENTATION:end markers in the template).
10
+
11
+ import { readFileSync, writeFileSync, existsSync, statSync } from 'node:fs';
12
+ import { dirname, join, resolve, isAbsolute } from 'node:path';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { createRequire } from 'node:module';
15
+
16
+ const require = createRequire(import.meta.url);
17
+
18
+ const PACKAGE_ROOT = dirname(fileURLToPath(import.meta.url));
19
+ const TEMPLATE_PATH = join(PACKAGE_ROOT, 'template', 'manifest.d.ts');
20
+
21
+ // ---------------------------------------------------------------------------
22
+ // CLI entry
23
+ // ---------------------------------------------------------------------------
24
+
25
+ export async function main(argv) {
26
+ const opts = parseArgs(argv);
27
+
28
+ if (opts.help) {
29
+ printHelp();
30
+ return;
31
+ }
32
+
33
+ const cwd = process.cwd();
34
+ const manifestPath = resolve(cwd, opts.manifest);
35
+
36
+ if (!existsSync(manifestPath)) {
37
+ throw new Error(`manifest.json not found at ${manifestPath}`);
38
+ }
39
+
40
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
41
+ const projectRoot = dirname(manifestPath);
42
+
43
+ const augmentation = await buildAugmentation(manifest, projectRoot);
44
+ const template = readFileSync(TEMPLATE_PATH, 'utf8');
45
+ const output = applyAugmentation(template, augmentation);
46
+
47
+ const outPath = resolve(cwd, opts.out);
48
+ writeFileSync(outPath, output);
49
+ console.log(`mnfst-types: wrote ${outPath}`);
50
+
51
+ if (opts.init) {
52
+ const jsconfigPath = resolve(cwd, 'jsconfig.json');
53
+ if (existsSync(jsconfigPath)) {
54
+ console.log(`mnfst-types: jsconfig.json already exists, leaving it alone`);
55
+ } else {
56
+ writeFileSync(jsconfigPath, defaultJsconfig());
57
+ console.log(`mnfst-types: wrote ${jsconfigPath}`);
58
+ }
59
+ }
60
+ }
61
+
62
+ function parseArgs(argv) {
63
+ const opts = {
64
+ manifest: 'manifest.json',
65
+ out: 'manifest.d.ts',
66
+ init: false,
67
+ help: false
68
+ };
69
+ for (let i = 0; i < argv.length; i++) {
70
+ const a = argv[i];
71
+ if (a === '--help' || a === '-h') opts.help = true;
72
+ else if (a === '--init') opts.init = true;
73
+ else if (a === '--manifest') opts.manifest = argv[++i];
74
+ else if (a === '--out') opts.out = argv[++i];
75
+ else if (a.startsWith('--manifest=')) opts.manifest = a.slice('--manifest='.length);
76
+ else if (a.startsWith('--out=')) opts.out = a.slice('--out='.length);
77
+ }
78
+ return opts;
79
+ }
80
+
81
+ function printHelp() {
82
+ console.log(`mnfst-types — generate manifest.d.ts from a Manifest project
83
+
84
+ Usage:
85
+ npx mnfst-types [options]
86
+
87
+ Options:
88
+ --manifest <path> Path to manifest.json (default: ./manifest.json)
89
+ --out <path> Output .d.ts path (default: ./manifest.d.ts)
90
+ --init Also write a baseline jsconfig.json (only if missing)
91
+ -h, --help Show this message
92
+ `);
93
+ }
94
+
95
+ function defaultJsconfig() {
96
+ return JSON.stringify({
97
+ compilerOptions: {
98
+ target: 'es2022',
99
+ module: 'es2022',
100
+ moduleResolution: 'node',
101
+ checkJs: true,
102
+ allowJs: true,
103
+ noEmit: true,
104
+ strict: false,
105
+ lib: ['es2022', 'dom']
106
+ },
107
+ include: ['**/*.js', 'manifest.d.ts'],
108
+ exclude: ['node_modules', 'dist']
109
+ }, null, 2) + '\n';
110
+ }
111
+
112
+ // ---------------------------------------------------------------------------
113
+ // Template augmentation
114
+ // ---------------------------------------------------------------------------
115
+
116
+ const START_MARKER = '// AUGMENTATION:start';
117
+ const END_MARKER = '// AUGMENTATION:end';
118
+
119
+ function applyAugmentation(template, body) {
120
+ const startIdx = template.indexOf(START_MARKER);
121
+ const endIdx = template.indexOf(END_MARKER);
122
+ if (startIdx === -1 || endIdx === -1) {
123
+ throw new Error('Template is missing AUGMENTATION:start / AUGMENTATION:end markers');
124
+ }
125
+ // Find the end of the start-marker line and the start of the end-marker line.
126
+ const startLineEnd = template.indexOf('\n', startIdx) + 1;
127
+ // Walk back from endIdx to the previous newline so we replace whole lines.
128
+ let endLineStart = endIdx;
129
+ while (endLineStart > 0 && template[endLineStart - 1] !== '\n') endLineStart--;
130
+
131
+ const before = template.slice(0, startLineEnd);
132
+ const after = template.slice(endLineStart);
133
+
134
+ const generatedHeader = [
135
+ '// Generated by `npx mnfst-types`. Do not edit by hand —',
136
+ '// hand-edits between AUGMENTATION:start and AUGMENTATION:end are',
137
+ '// overwritten on regeneration.',
138
+ '// ---------------------------------------------------------------------------',
139
+ ''
140
+ ].join('\n');
141
+
142
+ return before + generatedHeader + body + '\n' + after;
143
+ }
144
+
145
+ // ---------------------------------------------------------------------------
146
+ // Augmentation builder
147
+ // ---------------------------------------------------------------------------
148
+
149
+ async function buildAugmentation(manifest, projectRoot) {
150
+ const data = manifest && typeof manifest === 'object' ? manifest.data : null;
151
+ if (!data || typeof data !== 'object' || Object.keys(data).length === 0) {
152
+ return [
153
+ 'declare global {',
154
+ ' // No data sources declared in manifest.json.',
155
+ '}',
156
+ 'export {};'
157
+ ].join('\n');
158
+ }
159
+
160
+ const sourceTypes = [];
161
+ const augmentations = [];
162
+
163
+ for (const [name, config] of Object.entries(data)) {
164
+ const inferred = await inferSourceType(name, config, projectRoot);
165
+ if (!inferred) continue;
166
+ sourceTypes.push(inferred.typeBlock);
167
+ augmentations.push(` ${jsonKey(name)}: ${inferred.augmentationType};`);
168
+ }
169
+
170
+ const lines = [];
171
+ lines.push('// ---------------------------------------------------------------------------');
172
+ lines.push('// Inferred row types for each data source.');
173
+ lines.push('// ---------------------------------------------------------------------------');
174
+ lines.push('');
175
+ for (const block of sourceTypes) {
176
+ lines.push(block);
177
+ lines.push('');
178
+ }
179
+ lines.push('declare global {');
180
+ lines.push(' interface ManifestSources {');
181
+ lines.push.apply(lines, augmentations);
182
+ lines.push(' }');
183
+ lines.push('}');
184
+ lines.push('');
185
+ lines.push('export {};');
186
+ return lines.join('\n');
187
+ }
188
+
189
+ // ---------------------------------------------------------------------------
190
+ // Source-shape inference
191
+ // ---------------------------------------------------------------------------
192
+
193
+ async function inferSourceType(name, config, projectRoot) {
194
+ const safeName = toTypeName(name);
195
+
196
+ // Appwrite bucket (storage).
197
+ if (config && typeof config === 'object' && config.appwriteBucketId) {
198
+ return {
199
+ typeBlock: `// ${name}: Appwrite storage bucket`,
200
+ augmentationType: 'ManifestBucketSource'
201
+ };
202
+ }
203
+
204
+ // Appwrite table.
205
+ if (config && typeof config === 'object' && config.appwriteTableId) {
206
+ const rowType = `Row_${safeName}`;
207
+ const typeBlock = [
208
+ `/** Row shape for $x.${name} (Appwrite table — extend as needed). */`,
209
+ `export interface ${rowType} {`,
210
+ ` $id: string;`,
211
+ ` $createdAt?: string;`,
212
+ ` $updatedAt?: string;`,
213
+ ` [field: string]: unknown;`,
214
+ `}`
215
+ ].join('\n');
216
+ return {
217
+ typeBlock,
218
+ augmentationType: `ManifestArraySource<${rowType}> & ManifestAppwriteTableOps<${rowType}>`
219
+ };
220
+ }
221
+
222
+ // String — direct path/URL to a CSV/JSON/YAML file.
223
+ if (typeof config === 'string') {
224
+ const sample = sampleLocalFile(config, projectRoot);
225
+ return formatLocalSource(name, safeName, sample);
226
+ }
227
+
228
+ // Object — could be a localized source (`locales:` or per-locale keys), an
229
+ // HTTP endpoint with `url`, or an explicit defaultValue.
230
+ if (config && typeof config === 'object') {
231
+ if (typeof config.locales === 'string') {
232
+ const sample = sampleLocalFile(config.locales, projectRoot);
233
+ return formatLocalSource(name, safeName, sample);
234
+ }
235
+
236
+ // Per-locale keys — sample the first one we find.
237
+ const localeKey = Object.keys(config).find((k) => /^[a-zA-Z]{2}(-[a-zA-Z]{2})?$/.test(k));
238
+ if (localeKey && typeof config[localeKey] === 'string') {
239
+ const sample = sampleLocalFile(config[localeKey], projectRoot);
240
+ return formatLocalSource(name, safeName, sample);
241
+ }
242
+
243
+ if (typeof config.url === 'string') {
244
+ return {
245
+ typeBlock: `// ${name}: HTTP source — row type left generic.`,
246
+ augmentationType: 'ManifestArraySource<any>'
247
+ };
248
+ }
249
+ }
250
+
251
+ return {
252
+ typeBlock: `// ${name}: shape could not be inferred — leaving as ManifestArraySource<any>.`,
253
+ augmentationType: 'ManifestArraySource<any>'
254
+ };
255
+ }
256
+
257
+ function formatLocalSource(name, safeName, sample) {
258
+ if (!sample) {
259
+ return {
260
+ typeBlock: `// ${name}: file not found at sample time.`,
261
+ augmentationType: 'ManifestArraySource<any>'
262
+ };
263
+ }
264
+ if (sample.kind === 'array') {
265
+ const rowType = `Row_${safeName}`;
266
+ const fields = formatFields(sample.fields, ' ');
267
+ const typeBlock = [
268
+ `/** Row shape for $x.${name} inferred from ${sample.path}. */`,
269
+ `export interface ${rowType} {`,
270
+ fields,
271
+ `}`
272
+ ].filter(Boolean).join('\n');
273
+ return {
274
+ typeBlock,
275
+ augmentationType: `ManifestArraySource<${rowType}>`
276
+ };
277
+ }
278
+ if (sample.kind === 'object') {
279
+ const objType = `Obj_${safeName}`;
280
+ const typeBlock = [
281
+ `/** Object shape for $x.${name} inferred from ${sample.path}. */`,
282
+ `export interface ${objType} ${formatObjectShape(sample.shape, '')}`
283
+ ].join('\n');
284
+ return {
285
+ typeBlock,
286
+ augmentationType: `ManifestObjectSource<${objType}>`
287
+ };
288
+ }
289
+ return {
290
+ typeBlock: `// ${name}: empty or unrecognized sample.`,
291
+ augmentationType: 'ManifestArraySource<any>'
292
+ };
293
+ }
294
+
295
+ // ---------------------------------------------------------------------------
296
+ // Local file sampling (CSV / JSON / YAML)
297
+ // ---------------------------------------------------------------------------
298
+
299
+ function sampleLocalFile(filePath, projectRoot) {
300
+ if (typeof filePath !== 'string') return null;
301
+ if (filePath.startsWith('http://') || filePath.startsWith('https://')) return null;
302
+ const cleaned = filePath.replace(/^\/+/, '');
303
+ const candidates = [
304
+ isAbsolute(filePath) ? filePath : null,
305
+ join(projectRoot, cleaned),
306
+ join(projectRoot, filePath)
307
+ ].filter(Boolean);
308
+
309
+ let resolved = null;
310
+ for (const c of candidates) {
311
+ try {
312
+ if (existsSync(c) && statSync(c).isFile()) {
313
+ resolved = c;
314
+ break;
315
+ }
316
+ } catch (_) { /* skip */ }
317
+ }
318
+ if (!resolved) return null;
319
+
320
+ const lower = resolved.toLowerCase();
321
+ try {
322
+ if (lower.endsWith('.csv')) return { ...sampleCsv(resolved), path: filePath };
323
+ if (lower.endsWith('.json')) return { ...sampleJson(resolved), path: filePath };
324
+ if (lower.endsWith('.yaml') || lower.endsWith('.yml')) return { ...sampleYaml(resolved), path: filePath };
325
+ } catch (e) {
326
+ return null;
327
+ }
328
+ return null;
329
+ }
330
+
331
+ function sampleCsv(path) {
332
+ const text = readFileSync(path, 'utf8');
333
+ const rows = parseCsv(text);
334
+ if (rows.length === 0) return { kind: 'array', fields: {} };
335
+ const header = rows[0];
336
+ const sampleRows = rows.slice(1, 51);
337
+ const firstHeader = (header[0] || '').toLowerCase();
338
+
339
+ // Key-value mode: first column is `key`, second is `value`.
340
+ if (firstHeader === 'key' && (header[1] || '').toLowerCase() === 'value') {
341
+ const shape = {};
342
+ for (const row of sampleRows) {
343
+ if (!row[0]) continue;
344
+ assignDottedKey(shape, row[0], row[1]);
345
+ }
346
+ return { kind: 'object', shape };
347
+ }
348
+
349
+ // Tabular: array of rows with the header as field names.
350
+ const fields = {};
351
+ for (const col of header) {
352
+ if (!col) continue;
353
+ fields[col] = inferFieldType(sampleRows.map((r) => r[header.indexOf(col)]));
354
+ }
355
+ return { kind: 'array', fields };
356
+ }
357
+
358
+ function sampleJson(path) {
359
+ const data = JSON.parse(readFileSync(path, 'utf8'));
360
+ if (Array.isArray(data)) {
361
+ const sample = data.slice(0, 50);
362
+ const fields = {};
363
+ for (const item of sample) {
364
+ if (item && typeof item === 'object' && !Array.isArray(item)) {
365
+ for (const [k, v] of Object.entries(item)) {
366
+ if (!fields[k]) fields[k] = [];
367
+ fields[k].push(v);
368
+ }
369
+ }
370
+ }
371
+ const out = {};
372
+ for (const [k, vals] of Object.entries(fields)) {
373
+ out[k] = inferFieldTypeFromValues(vals);
374
+ }
375
+ return { kind: 'array', fields: out };
376
+ }
377
+ if (data && typeof data === 'object') {
378
+ return { kind: 'object', shape: shapeFromValue(data, 0) };
379
+ }
380
+ return { kind: 'object', shape: {} };
381
+ }
382
+
383
+ function sampleYaml(path) {
384
+ let yaml;
385
+ try { yaml = require('js-yaml'); } catch {
386
+ return null;
387
+ }
388
+ const data = yaml.load(readFileSync(path, 'utf8'));
389
+ if (Array.isArray(data)) {
390
+ return sampleJsonFromObject(data);
391
+ }
392
+ if (data && typeof data === 'object') {
393
+ return { kind: 'object', shape: shapeFromValue(data, 0) };
394
+ }
395
+ return { kind: 'object', shape: {} };
396
+ }
397
+
398
+ function sampleJsonFromObject(arr) {
399
+ const sample = arr.slice(0, 50);
400
+ const fields = {};
401
+ for (const item of sample) {
402
+ if (item && typeof item === 'object' && !Array.isArray(item)) {
403
+ for (const [k, v] of Object.entries(item)) {
404
+ if (!fields[k]) fields[k] = [];
405
+ fields[k].push(v);
406
+ }
407
+ }
408
+ }
409
+ const out = {};
410
+ for (const [k, vals] of Object.entries(fields)) {
411
+ out[k] = inferFieldTypeFromValues(vals);
412
+ }
413
+ return { kind: 'array', fields: out };
414
+ }
415
+
416
+ // ---------------------------------------------------------------------------
417
+ // CSV parsing (header + rows, RFC-4180-ish: handles quotes and escapes)
418
+ // ---------------------------------------------------------------------------
419
+
420
+ function parseCsv(text) {
421
+ const rows = [];
422
+ let row = [];
423
+ let field = '';
424
+ let inQuotes = false;
425
+
426
+ for (let i = 0; i < text.length; i++) {
427
+ const ch = text[i];
428
+ if (inQuotes) {
429
+ if (ch === '"') {
430
+ if (text[i + 1] === '"') { field += '"'; i++; }
431
+ else { inQuotes = false; }
432
+ } else {
433
+ field += ch;
434
+ }
435
+ continue;
436
+ }
437
+ if (ch === '"') { inQuotes = true; continue; }
438
+ if (ch === ',') { row.push(field); field = ''; continue; }
439
+ if (ch === '\r') continue;
440
+ if (ch === '\n') { row.push(field); rows.push(row); row = []; field = ''; continue; }
441
+ field += ch;
442
+ }
443
+ if (field.length > 0 || row.length > 0) {
444
+ row.push(field);
445
+ rows.push(row);
446
+ }
447
+ return rows.filter((r) => r.length > 1 || (r.length === 1 && r[0] !== ''));
448
+ }
449
+
450
+ function assignDottedKey(target, dottedKey, value) {
451
+ const parts = dottedKey.split('.');
452
+ let cur = target;
453
+ for (let i = 0; i < parts.length - 1; i++) {
454
+ const part = parts[i];
455
+ const isIndex = /^\d+$/.test(part);
456
+ if (isIndex) {
457
+ // Numeric segment indicates an array element; we still model as object for typing.
458
+ if (!cur._array) cur._array = true;
459
+ }
460
+ if (!cur[part] || typeof cur[part] !== 'object') cur[part] = {};
461
+ cur = cur[part];
462
+ }
463
+ const leaf = parts[parts.length - 1];
464
+ cur[leaf] = inferLiteralType(value);
465
+ }
466
+
467
+ // ---------------------------------------------------------------------------
468
+ // Type inference helpers
469
+ // ---------------------------------------------------------------------------
470
+
471
+ function inferFieldType(values) {
472
+ return inferFieldTypeFromValues(values);
473
+ }
474
+
475
+ function inferFieldTypeFromValues(values) {
476
+ let sawNumber = false, sawBool = false, sawString = false, sawNull = false, sawObject = false, sawArray = false;
477
+ for (const v of values) {
478
+ if (v === undefined || v === null || v === '') { sawNull = true; continue; }
479
+ if (typeof v === 'number') { sawNumber = true; continue; }
480
+ if (typeof v === 'boolean') { sawBool = true; continue; }
481
+ if (Array.isArray(v)) { sawArray = true; continue; }
482
+ if (typeof v === 'object') { sawObject = true; continue; }
483
+ if (typeof v === 'string') {
484
+ const t = v.trim();
485
+ if (t === 'true' || t === 'false') { sawBool = true; continue; }
486
+ if (t !== '' && !isNaN(Number(t))) { sawNumber = true; continue; }
487
+ sawString = true;
488
+ }
489
+ }
490
+ const parts = [];
491
+ if (sawString) parts.push('string');
492
+ if (sawNumber) parts.push('number');
493
+ if (sawBool) parts.push('boolean');
494
+ if (sawArray) parts.push('unknown[]');
495
+ if (sawObject) parts.push('Record<string, unknown>');
496
+ if (sawNull) parts.push('null');
497
+ if (parts.length === 0) return 'string';
498
+ return parts.join(' | ');
499
+ }
500
+
501
+ function inferLiteralType(value) {
502
+ if (value === undefined || value === null || value === '') return 'string';
503
+ const s = String(value).trim();
504
+ if (s === 'true' || s === 'false') return 'boolean';
505
+ if (!isNaN(Number(s))) return 'number';
506
+ return 'string';
507
+ }
508
+
509
+ function shapeFromValue(value, depth) {
510
+ if (depth > 5 || value === null || value === undefined) return 'unknown';
511
+ if (Array.isArray(value)) {
512
+ if (value.length === 0) return 'unknown[]';
513
+ const inner = shapeFromValue(value[0], depth + 1);
514
+ if (typeof inner === 'object' && inner !== null) {
515
+ return inlineShape(inner) + '[]';
516
+ }
517
+ return inner + '[]';
518
+ }
519
+ if (typeof value === 'object') {
520
+ const out = {};
521
+ for (const [k, v] of Object.entries(value)) {
522
+ out[k] = shapeFromValue(v, depth + 1);
523
+ }
524
+ return out;
525
+ }
526
+ return typeof value;
527
+ }
528
+
529
+ function inlineShape(tree) {
530
+ if (typeof tree === 'string') return tree;
531
+ if (typeof tree !== 'object' || tree === null) return 'unknown';
532
+ const parts = [];
533
+ for (const [k, v] of Object.entries(tree)) {
534
+ if (k === '_array') continue;
535
+ parts.push(`${jsonKey(k)}: ${inlineShape(v)}`);
536
+ }
537
+ return parts.length === 0 ? 'Record<string, unknown>' : `{ ${parts.join('; ')} }`;
538
+ }
539
+
540
+ // ---------------------------------------------------------------------------
541
+ // Type rendering
542
+ // ---------------------------------------------------------------------------
543
+
544
+ function formatFields(fields, indent) {
545
+ return Object.entries(fields)
546
+ .map(([k, t]) => `${indent}${jsonKey(k)}: ${t};`)
547
+ .join('\n');
548
+ }
549
+
550
+ function formatObjectShape(shape, indent) {
551
+ if (typeof shape === 'string') return shape;
552
+ if (typeof shape !== 'object' || shape === null) return 'unknown';
553
+ const inner = indent + ' ';
554
+ const lines = [];
555
+ for (const [k, v] of Object.entries(shape)) {
556
+ if (k === '_array') continue;
557
+ const formatted = typeof v === 'object' && v !== null && !Array.isArray(v)
558
+ ? formatObjectShape(v, inner)
559
+ : v;
560
+ lines.push(`${inner}${jsonKey(k)}: ${formatted};`);
561
+ }
562
+ return `{\n${lines.join('\n')}\n${indent}}`;
563
+ }
564
+
565
+ function jsonKey(name) {
566
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name);
567
+ }
568
+
569
+ function toTypeName(name) {
570
+ return name.replace(/[^A-Za-z0-9_$]/g, '_');
571
+ }
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "mnfst-types",
3
+ "version": "0.1.1",
4
+ "description": "Generate TypeScript types for a Manifest project from manifest.json and sample data",
5
+ "type": "module",
6
+ "bin": {
7
+ "mnfst-types": "./bin/mnfst-types.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "manifest.types.mjs",
12
+ "template",
13
+ "README.md"
14
+ ],
15
+ "scripts": {
16
+ "prepare:source": "node ./scripts/sync-types.mjs",
17
+ "prepack": "npm run prepare:source"
18
+ },
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "keywords": [
23
+ "manifest",
24
+ "mnfst",
25
+ "typescript",
26
+ "types",
27
+ "codegen",
28
+ "ai",
29
+ "intellisense"
30
+ ],
31
+ "dependencies": {
32
+ "js-yaml": "^4.1.0"
33
+ },
34
+ "author": "Andrew Matlock",
35
+ "license": "MIT",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/Manifest-X/Manifest.git",
39
+ "directory": "packages/types"
40
+ }
41
+ }
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Manifest ambient type declarations.
3
+ * https://manifestjs.org
4
+ *
5
+ * This file gives editors (VS Code, Cursor, JetBrains) and AI coding assistants
6
+ * type information for Manifest's magic globals and data-source state. It is
7
+ * intended to live in the project root and is regenerated by `npx mnfst-types`
8
+ * to add project-specific augmentations to ManifestSources from manifest.json.
9
+ *
10
+ * Hand-edits below the AUGMENTATION marker will be overwritten on regeneration.
11
+ */
12
+
13
+ // ---------------------------------------------------------------------------
14
+ // Data-source state and operators (attached to every $x.<source>)
15
+ // ---------------------------------------------------------------------------
16
+
17
+ /** Appwrite-style query expression returned by helper builders. */
18
+ export type ManifestQueryExpr = string;
19
+
20
+ /** Appwrite-style query helpers used with `$query([...])`. */
21
+ export interface ManifestQuery {
22
+ equal(field: string, value: unknown): ManifestQueryExpr;
23
+ notEqual(field: string, value: unknown): ManifestQueryExpr;
24
+ lessThan(field: string, value: number | string): ManifestQueryExpr;
25
+ lessThanEqual(field: string, value: number | string): ManifestQueryExpr;
26
+ greaterThan(field: string, value: number | string): ManifestQueryExpr;
27
+ greaterThanEqual(field: string, value: number | string): ManifestQueryExpr;
28
+ between(field: string, start: number | string, end: number | string): ManifestQueryExpr;
29
+ contains(field: string, value: string | string[]): ManifestQueryExpr;
30
+ startsWith(field: string, value: string): ManifestQueryExpr;
31
+ endsWith(field: string, value: string): ManifestQueryExpr;
32
+ search(field: string, value: string): ManifestQueryExpr;
33
+ isNull(field: string): ManifestQueryExpr;
34
+ isNotNull(field: string): ManifestQueryExpr;
35
+ select(fields: string[]): ManifestQueryExpr;
36
+ orderAsc(field: string): ManifestQueryExpr;
37
+ orderDesc(field: string): ManifestQueryExpr;
38
+ limit(value: number): ManifestQueryExpr;
39
+ offset(value: number): ManifestQueryExpr;
40
+ cursorAfter(id: string): ManifestQueryExpr;
41
+ cursorBefore(id: string): ManifestQueryExpr;
42
+ }
43
+
44
+ /** State flags exposed on every data source (array or object). */
45
+ export interface ManifestSourceState {
46
+ /** True while the source is fetching for the first time or after a mutation. */
47
+ readonly $loading: boolean;
48
+ /** Last error from a load or mutation, or null. */
49
+ readonly $error: Error | string | null;
50
+ /** True once initial load has completed (success or failure). */
51
+ readonly $ready: boolean;
52
+ }
53
+
54
+ /** Operators available on array-shaped sources (CSV tabular, JSON arrays, Appwrite tables). */
55
+ export interface ManifestArrayOps<T> {
56
+ /** Substring match across the given fields. Returns matching items. */
57
+ $search(term: string, ...fields: (keyof T & string)[]): T[];
58
+ /**
59
+ * Local sources: filter by an array of `Manifest.query.*` expressions and array methods.
60
+ * Appwrite sources: server-side query, returns a Promise.
61
+ */
62
+ $query(expressions: ManifestQueryExpr[]): T[] | Promise<T[]>;
63
+ /** Look up a single row whose `id` matches the current route param, if any. */
64
+ $route(path?: string): T | undefined;
65
+ }
66
+
67
+ /** Mutations available on Appwrite-table sources. */
68
+ export interface ManifestAppwriteTableOps<T> {
69
+ $create(values: Partial<T>): Promise<T>;
70
+ $update(id: string, values: Partial<T>): Promise<T>;
71
+ $delete(id: string): Promise<void>;
72
+ $duplicate(id: string, overrides?: Partial<T>): Promise<T>;
73
+ }
74
+
75
+ /** Operations available on Appwrite-bucket (storage) sources. */
76
+ export interface ManifestAppwriteBucketOps {
77
+ $url(fileId: string): string;
78
+ $preview(fileId: string, opts?: Record<string, unknown>): string;
79
+ $download(fileId: string): string;
80
+ $openUrl(fileId: string): void;
81
+ $openPreview(fileId: string): void;
82
+ $openDownload(fileId: string): void;
83
+ $upload(file: File | Blob, opts?: Record<string, unknown>): Promise<{ $id: string }>;
84
+ $remove(fileId: string): Promise<void>;
85
+ $filesFor(parentId: string, fieldName?: string): unknown[];
86
+ $unlinkFrom(parentId: string, fileId: string): Promise<void>;
87
+ $removeFrom(parentId: string, fileId: string): Promise<void>;
88
+ }
89
+
90
+ /**
91
+ * The shape returned by `$x.<source>` for an array-of-rows source.
92
+ * Behaves as a regular `T[]` (supports `map`, `filter`, `find`, etc.) plus
93
+ * Manifest operators and state flags.
94
+ */
95
+ export type ManifestArraySource<T> =
96
+ & ReadonlyArray<T>
97
+ & ManifestSourceState
98
+ & ManifestArrayOps<T>
99
+ & Partial<ManifestAppwriteTableOps<T>>;
100
+
101
+ /** The shape returned by `$x.<source>` for an object-shaped source (CSV key-value, JSON object, YAML map). */
102
+ export type ManifestObjectSource<T> = T & ManifestSourceState;
103
+
104
+ /** The shape returned by `$x.<source>` for an Appwrite storage bucket. */
105
+ export type ManifestBucketSource = ManifestSourceState & ManifestAppwriteBucketOps;
106
+
107
+ // ---------------------------------------------------------------------------
108
+ // Magic globals registered by Manifest plugins
109
+ // ---------------------------------------------------------------------------
110
+
111
+ /**
112
+ * Project-specific data sources, keyed by the names declared in `manifest.json`'s
113
+ * `data` property. Augmented by `npx mnfst-types` from manifest.json + sample
114
+ * data (declarations appended below the AUGMENTATION marker).
115
+ */
116
+ export interface ManifestSources {
117
+ [sourceName: string]: ManifestArraySource<any> | ManifestObjectSource<any> | ManifestBucketSource;
118
+ }
119
+
120
+ /** `$auth` from the Appwrite auth plugin. Loose by design — auth API is broad. */
121
+ export interface ManifestAuth {
122
+ readonly current: { $id: string; email?: string; name?: string; [k: string]: unknown } | null;
123
+ readonly isAuthenticated: boolean;
124
+ readonly isLoading: boolean;
125
+ readonly currentTeam: { $id: string; name: string; [k: string]: unknown } | null;
126
+ readonly teams: Array<{ $id: string; name: string; [k: string]: unknown }>;
127
+ login(email: string, password?: string): Promise<unknown>;
128
+ loginWithMagic(email: string): Promise<unknown>;
129
+ loginWithOAuth(provider: string, opts?: Record<string, unknown>): Promise<unknown>;
130
+ loginAsGuest(): Promise<unknown>;
131
+ logout(): Promise<unknown>;
132
+ [extra: string]: unknown;
133
+ }
134
+
135
+ /** `$locale` from the localization plugin. */
136
+ export interface ManifestLocale {
137
+ readonly current: string;
138
+ readonly available: string[];
139
+ set(locale: string): void;
140
+ }
141
+
142
+ /** `$toast` from the toasts plugin. */
143
+ export interface ManifestToast {
144
+ (message: string, opts?: { type?: 'info' | 'success' | 'warning' | 'error'; duration?: number }): void;
145
+ info(message: string, opts?: Record<string, unknown>): void;
146
+ success(message: string, opts?: Record<string, unknown>): void;
147
+ warning(message: string, opts?: Record<string, unknown>): void;
148
+ error(message: string, opts?: Record<string, unknown>): void;
149
+ dismiss(id?: string): void;
150
+ }
151
+
152
+ /** `$theme` from the themes plugin. */
153
+ export interface ManifestTheme {
154
+ readonly current: 'light' | 'dark' | 'system';
155
+ set(theme: 'light' | 'dark' | 'system'): void;
156
+ toggle(): void;
157
+ }
158
+
159
+ /** `$colors` from the colors plugin. */
160
+ export interface ManifestColors {
161
+ [name: string]: string | ManifestColors;
162
+ }
163
+
164
+ /** `$colorpicker` from the colorpicker plugin. */
165
+ export interface ManifestColorpicker {
166
+ open(opts?: Record<string, unknown>): void;
167
+ close(): void;
168
+ [extra: string]: unknown;
169
+ }
170
+
171
+ /** `$url` from the url-parameters plugin: read/write URL query params reactively. */
172
+ export interface ManifestUrl {
173
+ get(name: string): string | null;
174
+ set(name: string, value: string | null): void;
175
+ has(name: string): boolean;
176
+ [name: string]: unknown;
177
+ }
178
+
179
+ /** `$route` magic — true if the current route matches the given pattern. */
180
+ export type ManifestRoute = (pattern: string) => boolean;
181
+
182
+ /**
183
+ * `$modify('attr')` — exposed in component HTML. Returns the value of an
184
+ * attribute set on the parent component instance (Manifest's prop mechanism).
185
+ */
186
+ export type ManifestModify = (attr: string) => string | undefined;
187
+
188
+ /** `$try(fn)` — run a callback and swallow any thrown error, returning undefined on failure. */
189
+ export type ManifestTry = <T>(fn: () => T) => T | undefined;
190
+
191
+ // ---------------------------------------------------------------------------
192
+ // Global declarations (what Alpine exposes inside `x-data`, `x-show`, etc.)
193
+ // ---------------------------------------------------------------------------
194
+
195
+ declare global {
196
+ /** Project data sources registered in manifest.json. */
197
+ const $x: ManifestSources;
198
+ /** Match the current route against a pattern (e.g. `$route('/about')`). */
199
+ const $route: ManifestRoute;
200
+ /** Read a parent component attribute (Manifest's prop mechanism). */
201
+ const $modify: ManifestModify;
202
+ /** Run a callback safely, returning undefined on error. */
203
+ const $try: ManifestTry;
204
+ /** Appwrite auth plugin (only present when the plugin is loaded). */
205
+ const $auth: ManifestAuth;
206
+ /** Localization plugin. */
207
+ const $locale: ManifestLocale;
208
+ /** Toasts plugin. */
209
+ const $toast: ManifestToast;
210
+ /** Themes plugin. */
211
+ const $theme: ManifestTheme;
212
+ /** Colors plugin. */
213
+ const $colors: ManifestColors;
214
+ /** Colorpicker plugin. */
215
+ const $colorpicker: ManifestColorpicker;
216
+ /** URL parameters plugin. */
217
+ const $url: ManifestUrl;
218
+
219
+ /** Window-level Manifest namespace exposed by the loader. */
220
+ interface Window {
221
+ Manifest?: {
222
+ loadPlugin(name: string, version?: string): Promise<unknown>;
223
+ loadTailwind(version?: string): Promise<unknown>;
224
+ getPluginUrl(name: string, version?: string): string;
225
+ };
226
+ Alpine?: unknown;
227
+ __manifestLoaded?: unknown;
228
+ }
229
+ }
230
+
231
+ // ---------------------------------------------------------------------------
232
+ // AUGMENTATION:start
233
+ // Project-specific declarations are appended below by `npx mnfst-types`.
234
+ // Do not hand-edit between the start/end markers — re-running the CLI
235
+ // regenerates this section from manifest.json + sample data.
236
+ // ---------------------------------------------------------------------------
237
+
238
+ // (No project augmentations yet — run `npx mnfst-types` to generate.)
239
+
240
+ // ---------------------------------------------------------------------------
241
+ // AUGMENTATION:end
242
+ // ---------------------------------------------------------------------------
243
+
244
+ export {};