@divithselvam/jokebook 0.0.0-stage → 1.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,243 @@
1
+ import { Command, Flags } from '@oclif/core';
2
+ import path from 'node:path';
3
+ import { catalogDocument, findProduct, Issue, slug, Workflow } from '../../index.js';
4
+ // Catalog 1.0.0 shipped before the machine-readable block. It is frozen, so its
5
+ // section ownership can only live here; every newer catalog must declare it.
6
+ const legacySections = [
7
+ { header: 'Capability', heading: 'Data, synchronization, search, analytics and AI', workspace: 'services and infrastructure, with client integration as specified' },
8
+ { header: 'Capability', heading: 'Desktop packages and operating-system integration', workspace: 'apps/desktop' },
9
+ { header: 'Capability', heading: 'Mobile packages and operating-system integration', workspace: 'apps/mobile' },
10
+ { header: 'Capability', heading: 'Monorepo, delivery and operations', workspace: 'Workspace root, tooling and infrastructure' },
11
+ { header: 'Capability', heading: 'Rust API and worker packages', workspace: 'services/api and Cargo workspace' },
12
+ { header: 'Capability', heading: 'Smaller packages that matter in specialized products', workspace: 'Depends on capability. See setup.' },
13
+ { header: 'Surface', heading: 'The decision', workspace: 'Root architecture and platform foundations' },
14
+ { header: 'Capability', heading: 'Web package catalog', workspace: 'apps/web' },
15
+ ];
16
+ function isRecord(value) {
17
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
18
+ }
19
+ function requiredString(value, field) {
20
+ if (typeof value !== 'string' || value.trim() === '') {
21
+ throw new Issue(`The catalog metadata field "${field}" must be a non-empty string.`);
22
+ }
23
+ return value.trim();
24
+ }
25
+ function workspacePath(value, field) {
26
+ const workspace = requiredString(value, field);
27
+ const normalized = path.posix.normalize(workspace);
28
+ if (normalized !== workspace || normalized === '.' || normalized === '..' ||
29
+ normalized.startsWith('../') || workspace.includes('\\') || path.posix.isAbsolute(workspace)) {
30
+ throw new Issue(`The catalog metadata field "${field}" must be a relative workspace path.`);
31
+ }
32
+ return workspace;
33
+ }
34
+ function metadataValue(markdown) {
35
+ const match = /<!--\s*jokebook-catalog\s*\r?\n([\s\S]*?)\r?\n-->/v.exec(markdown);
36
+ if (!match)
37
+ return undefined;
38
+ try {
39
+ return JSON.parse(match[1]);
40
+ }
41
+ catch (error) {
42
+ throw new Issue(`The catalog metadata block is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
43
+ }
44
+ }
45
+ export function catalogMetadata(markdown) {
46
+ const value = metadataValue(markdown);
47
+ if (value === undefined)
48
+ return undefined;
49
+ if (!isRecord(value) || !Array.isArray(value.sections) || !Array.isArray(value.recipes)) {
50
+ throw new Issue('The catalog metadata block must contain sections and recipes arrays.');
51
+ }
52
+ const headings = new Set();
53
+ const sections = value.sections.map((entry, index) => {
54
+ if (!isRecord(entry))
55
+ throw new Issue(`Catalog section ${index + 1} must be an object.`);
56
+ const section = {
57
+ header: requiredString(entry.header, `sections[${index}].header`),
58
+ heading: requiredString(entry.heading, `sections[${index}].heading`),
59
+ workspace: requiredString(entry.workspace, `sections[${index}].workspace`),
60
+ };
61
+ if (headings.has(section.heading))
62
+ throw new Issue(`Catalog section "${section.heading}" is declared twice.`);
63
+ headings.add(section.heading);
64
+ return section;
65
+ });
66
+ const names = new Set();
67
+ const recipes = value.recipes.map((entry, index) => {
68
+ if (!isRecord(entry))
69
+ throw new Issue(`Catalog recipe ${index + 1} must be an object.`);
70
+ const id = requiredString(entry.id, `recipes[${index}].id`);
71
+ if (slug(id) !== id)
72
+ throw new Issue(`Catalog recipe id "${id}" must be a slug.`);
73
+ const aliases = Array.isArray(entry.aliases) ? entry.aliases.map((alias, aliasIndex) => {
74
+ const aliasValue = requiredString(alias, `recipes[${index}].aliases[${aliasIndex}]`);
75
+ if (slug(aliasValue) !== aliasValue)
76
+ throw new Issue(`Catalog recipe alias "${aliasValue}" must be a slug.`);
77
+ return aliasValue;
78
+ }) : [];
79
+ for (const name of [id, ...aliases]) {
80
+ if (names.has(name))
81
+ throw new Issue(`Catalog recipe name "${name}" is declared twice.`);
82
+ names.add(name);
83
+ }
84
+ const capability = requiredString(entry.capability, `recipes[${index}].capability`);
85
+ if (slug(capability) !== capability)
86
+ throw new Issue(`Catalog recipe capability "${capability}" must be a slug.`);
87
+ return {
88
+ aliases,
89
+ capability,
90
+ id,
91
+ implementation: requiredString(entry.implementation, `recipes[${index}].implementation`),
92
+ package: requiredString(entry.package, `recipes[${index}].package`),
93
+ summary: requiredString(entry.summary, `recipes[${index}].summary`),
94
+ workspace: workspacePath(entry.workspace, `recipes[${index}].workspace`),
95
+ };
96
+ });
97
+ return { recipes, sections };
98
+ }
99
+ function cells(line) {
100
+ return line.trim().replace(/^\|/v, '').replace(/\|$/v, '').split(/(?<!\\)\|/v)
101
+ .map((cell) => cell.trim().replaceAll(String.raw `\|`, '|'));
102
+ }
103
+ function references(value) {
104
+ return value.matchAll(/\[\d+\]\(<(https?:\/\/[^>]+)>\)/gv).map((match) => match[1]).toArray();
105
+ }
106
+ function withoutReferences(value) {
107
+ return value.replaceAll(/\s*\[\d+\]\(<[^>]+>\)/gv, '').trim();
108
+ }
109
+ function versionList(selection) {
110
+ return new Set(selection.matchAll(/(?:@|\*\*)(\d+(?:\.\d+)*(?:[.\-][\w.]+)?)/gv)
111
+ .map((match) => match[1])).values().toArray();
112
+ }
113
+ function escapePattern(value) {
114
+ const special = new Set(String.raw `\^$.*+?()[]{}|`);
115
+ return [...value].map((character) => special.has(character) ? `\\${character}` : character).join('');
116
+ }
117
+ function packagePin(selection, packageName) {
118
+ const pattern = new RegExp('`' + escapePattern(packageName) +
119
+ '@(\\d+(?:\\.\\d+)+(?:[\\-+][\\w.]+)?)`', 'v');
120
+ const match = pattern.exec(selection);
121
+ if (!match)
122
+ throw new Issue(`STACK.md does not pin ${packageName} for its automated recipe.`);
123
+ return match[1];
124
+ }
125
+ export function compileCatalog(markdown) {
126
+ const metadata = catalogMetadata(markdown);
127
+ const sections = metadata?.sections ?? legacySections;
128
+ const byHeading = new Map(sections.map((section) => [section.heading, section]));
129
+ const recipeByCapability = new Map();
130
+ for (const recipe of metadata?.recipes ?? []) {
131
+ if (recipeByCapability.has(recipe.capability)) {
132
+ throw new Issue(`Catalog capability "${recipe.capability}" has more than one automated recipe.`);
133
+ }
134
+ recipeByCapability.set(recipe.capability, recipe);
135
+ }
136
+ const headings = new Set();
137
+ for (const line of markdown.split(/\r?\n/v)) {
138
+ if (line.startsWith('## '))
139
+ headings.add(line.slice(3).trim());
140
+ }
141
+ for (const section of sections) {
142
+ if (!headings.has(section.heading))
143
+ throw new Issue(`STACK.md is missing the declared section "${section.heading}".`);
144
+ }
145
+ const declaredHeaders = new Set(sections.map(({ header }) => header));
146
+ const seenSections = new Set();
147
+ const rows = [];
148
+ let section = '';
149
+ let isReadingTable = false;
150
+ let isDeclaredTable = false;
151
+ for (const [index, line] of markdown.split(/\r?\n/v).entries()) {
152
+ if (line.startsWith('## ')) {
153
+ section = line.slice(3).trim();
154
+ isReadingTable = false;
155
+ continue;
156
+ }
157
+ if (!line.startsWith('|')) {
158
+ isReadingTable = false;
159
+ continue;
160
+ }
161
+ if (!isReadingTable) {
162
+ isReadingTable = true;
163
+ const header = cells(line)[0];
164
+ isDeclaredTable = byHeading.get(section)?.header === header;
165
+ if (!isDeclaredTable && declaredHeaders.has(header)) {
166
+ throw new Issue(`Catalog table "${header}" on line ${index + 1} is not declared by section "${section || '(none)'}".`);
167
+ }
168
+ continue;
169
+ }
170
+ if (!isDeclaredTable || line.startsWith('|---'))
171
+ continue;
172
+ const [label, selected, notes] = cells(line);
173
+ const id = slug(label);
174
+ if (!id || !selected || !notes)
175
+ throw new Issue(`Invalid catalog row on line ${index + 1}.`);
176
+ if (rows.some((row) => row.id === id))
177
+ throw new Issue(`Catalog capability "${id}" is declared twice.`);
178
+ const recipe = recipeByCapability.get(id);
179
+ rows.push({
180
+ capability: label,
181
+ id,
182
+ recipe: recipe?.id,
183
+ section,
184
+ selection: withoutReferences(selected),
185
+ setup: withoutReferences(notes),
186
+ source: { document: 'STACK.md', line: index + 1, links: references(line) },
187
+ status: recipe ? `Automated recipe: ${recipe.id}` : 'Catalog recommendation; verify before adopting',
188
+ versions: versionList(selected),
189
+ workspace: byHeading.get(section)?.workspace ?? 'See catalog setup',
190
+ });
191
+ seenSections.add(section);
192
+ }
193
+ for (const declaredSection of sections) {
194
+ if (!seenSections.has(declaredSection.heading)) {
195
+ throw new Issue(`STACK.md section "${declaredSection.heading}" has no "${declaredSection.header}" table.`);
196
+ }
197
+ }
198
+ if (rows.length === 0)
199
+ throw new Issue('No capability rows were found in STACK.md.');
200
+ for (const recipe of metadata?.recipes ?? []) {
201
+ const row = rows.find(({ id }) => id === recipe.capability);
202
+ if (!row)
203
+ throw new Issue(`Catalog recipe ${recipe.id} points at unknown capability "${recipe.capability}".`);
204
+ packagePin(row.selection, recipe.package);
205
+ }
206
+ return { metadata, rows };
207
+ }
208
+ export function entries(markdown) {
209
+ return compileCatalog(markdown).rows;
210
+ }
211
+ export function recipeVersion(rows, recipe) {
212
+ const row = rows.find(({ id }) => id === recipe.capability);
213
+ if (!row)
214
+ throw new Issue(`Catalog recipe ${recipe.id} points at unknown capability "${recipe.capability}".`);
215
+ return packagePin(row.selection, recipe.package);
216
+ }
217
+ export function lookup(catalog, capability) {
218
+ const id = slug(capability);
219
+ const exact = catalog.find((row) => row.id === id);
220
+ if (exact)
221
+ return exact;
222
+ const packages = catalog.filter(({ selection }) => selection.matchAll(/`([^`]+)`/gv).some((match) => match[1].toLowerCase().replace(/@\d.*$/v, '') === capability.toLowerCase()));
223
+ if (packages.length > 1) {
224
+ throw new Issue('Package matches multiple capabilities. Use a capability slug.', { matches: packages.map((row) => row.id) });
225
+ }
226
+ return packages[0];
227
+ }
228
+ export default class List extends Command {
229
+ static description = 'List package and platform capabilities from STACK.md';
230
+ static flags = { json: Flags.boolean({ description: 'Emit JSON' }) };
231
+ async run() {
232
+ const workflow = new Workflow('stack list');
233
+ await workflow.report(this.argv.includes('--json'), 'Try: jokebook stack list [--json]', async () => {
234
+ await this.parse(List);
235
+ workflow.stage = 'catalog';
236
+ const product = await findProduct();
237
+ if (product)
238
+ workflow.starterRevision = product.marker.starter;
239
+ const { digest, text } = await catalogDocument(product);
240
+ return { capabilities: entries(text), stackSha256: digest };
241
+ }, (result) => result.capabilities.map(({ capability, id }) => `${id} ${capability}`).join('\n'));
242
+ }
243
+ }
@@ -0,0 +1,11 @@
1
+ import { Command } from '@oclif/core';
2
+ export default class Show extends Command {
3
+ static args: {
4
+ capability: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
5
+ };
6
+ static description: string;
7
+ static flags: {
8
+ json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
9
+ };
10
+ run(): Promise<void>;
11
+ }
@@ -0,0 +1,36 @@
1
+ import { Args, Command, Flags } from '@oclif/core';
2
+ import { catalogDocument, findProduct, Issue, Workflow } from '../../index.js';
3
+ import { entries, lookup } from './list.js';
4
+ export default class Show extends Command {
5
+ static args = { capability: Args.string({ description: 'Capability slug or package name', required: true }) };
6
+ static description = 'Show a capability, its workspace, sources and setup';
7
+ static flags = { json: Flags.boolean({ description: 'Emit JSON' }) };
8
+ async run() {
9
+ const workflow = new Workflow('stack show');
10
+ await workflow.report(this.argv.includes('--json'), 'Try: jokebook stack show runtime-validation [--json]', async () => {
11
+ const { args } = await this.parse(Show);
12
+ workflow.stage = 'catalog';
13
+ const product = await findProduct();
14
+ if (product)
15
+ workflow.starterRevision = product.marker.starter;
16
+ const { digest, text } = await catalogDocument(product);
17
+ const capability = lookup(entries(text), args.capability);
18
+ if (!capability)
19
+ throw new Issue(`Unknown capability "${args.capability}". Run jokebook stack list.`);
20
+ return { capability, stackSha256: digest };
21
+ }, (result) => {
22
+ const row = result.capability;
23
+ return [
24
+ row.capability,
25
+ row.selection,
26
+ `Versions: ${row.versions.join(', ') || 'Not pinned'}`,
27
+ `Workspace: ${row.workspace}`,
28
+ `Status: ${row.status}`,
29
+ `Setup: ${row.setup}`,
30
+ `Source: ${row.source.document}:${row.source.line}`,
31
+ ...row.source.links,
32
+ ...(row.recipe ? [`Recipe: jokebook add ${row.recipe}`] : []),
33
+ ].join('\n');
34
+ });
35
+ }
36
+ }
@@ -0,0 +1,10 @@
1
+ import { Command } from '@oclif/core';
2
+ export default class Upgrade extends Command {
3
+ static description: string;
4
+ static flags: {
5
+ apply: import("@oclif/core/interfaces").BooleanFlag<boolean>;
6
+ check: import("@oclif/core/interfaces").BooleanFlag<boolean>;
7
+ json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
8
+ };
9
+ run(): Promise<void>;
10
+ }
@@ -0,0 +1,55 @@
1
+ import { Command, Flags } from '@oclif/core';
2
+ import { catalogDocument, findProduct, Issue, release, Workflow } from '../index.js';
3
+ import { applyUpgrade, planUpgrade, publicPlan } from '../upgrade.js';
4
+ const usage = 'Try: jokebook upgrade [--check | --apply] [--json] (from a Jokebook product)';
5
+ export default class Upgrade extends Command {
6
+ static description = 'Merge a newer bundled starter into an existing product without discarding local edits';
7
+ static flags = {
8
+ apply: Flags.boolean({ default: false, description: 'Write the reviewed upgrade plan' }),
9
+ check: Flags.boolean({ default: false, description: 'Inspect the upgrade plan without writing anything' }),
10
+ json: Flags.boolean({ description: 'Emit a single JSON result' }),
11
+ };
12
+ async run() {
13
+ const workflow = new Workflow('upgrade');
14
+ await workflow.report(this.argv.includes('--json'), usage, async () => {
15
+ const { flags } = await this.parse(Upgrade);
16
+ if (flags.apply && flags.check)
17
+ throw new Issue('Use either --check or --apply, not both.');
18
+ if (process.versions.node !== release.node) {
19
+ throw new Issue(`Use Node.js ${release.node}. Found ${process.versions.node}.`);
20
+ }
21
+ const product = await findProduct();
22
+ if (!product)
23
+ throw new Issue('Run this command inside a product created by Jokebook.');
24
+ workflow.destination = product.cwd;
25
+ workflow.starterRevision = product.marker.starter;
26
+ workflow.stage = 'catalog';
27
+ const { digest } = await catalogDocument(product);
28
+ workflow.stage = 'upgrade';
29
+ const plan = await planUpgrade(product, digest);
30
+ if (flags.apply && plan.status !== 'up-to-date') {
31
+ const report = await applyUpgrade(product, plan);
32
+ workflow.stage = 'complete';
33
+ const outcome = { ...publicPlan(plan), applied: true, report };
34
+ return outcome;
35
+ }
36
+ workflow.stage = flags.apply ? 'complete' : 'plan';
37
+ const outcome = { ...publicPlan(plan), applied: false };
38
+ return outcome;
39
+ }, (result) => {
40
+ if (result.status === 'up-to-date') {
41
+ return `Starter ${result.to} and catalog ${result.catalog} are up to date.`;
42
+ }
43
+ const changes = result.actions.length;
44
+ const conflicts = result.conflicts.length;
45
+ if (result.status === 'blocked') {
46
+ return `Plan ${result.from} -> ${result.to}: ${changes} files change, ${conflicts} conflicts. ` +
47
+ 'Resolve the conflicts before running jokebook upgrade --apply. No files were changed.';
48
+ }
49
+ if (result.applied) {
50
+ return `Upgraded ${result.from} -> ${result.to}. ${changes} files changed, ${conflicts} need review. Report: ${result.report}`;
51
+ }
52
+ return `Plan ${result.from} -> ${result.to}: ${changes} files change, ${conflicts} need review. Run jokebook upgrade --apply to write it.`;
53
+ });
54
+ }
55
+ }
@@ -0,0 +1,79 @@
1
+ type Skill = {
2
+ name: string;
3
+ repo: string;
4
+ };
5
+ export declare const release: Readonly<{
6
+ catalog: string;
7
+ node: string;
8
+ npm: string;
9
+ pnpm: string;
10
+ revision: string;
11
+ skillsCli: string;
12
+ version: string;
13
+ }>;
14
+ export declare const skills: Skill[];
15
+ export declare const presets: {
16
+ desktop: string;
17
+ full: string;
18
+ mobile: string;
19
+ web: string;
20
+ };
21
+ export type Preset = keyof typeof presets;
22
+ export type Settings = {
23
+ destination: string;
24
+ preset: Preset;
25
+ product: string;
26
+ recipes: string[];
27
+ };
28
+ export type ProductMarker = {
29
+ catalog?: string;
30
+ preset: string;
31
+ stackSha256: string;
32
+ starter: string;
33
+ };
34
+ export type Product = {
35
+ cwd: string;
36
+ marker: ProductMarker;
37
+ };
38
+ export declare class Issue extends Error {
39
+ readonly details: Record<string, unknown>;
40
+ readonly code: number;
41
+ constructor(message: string, details?: Record<string, unknown>, code?: number);
42
+ }
43
+ export declare function isUnattended(): boolean;
44
+ type CommandOptions = {
45
+ cwd: string;
46
+ deliverable: string;
47
+ signal?: AbortSignal;
48
+ };
49
+ export declare class Workflow {
50
+ readonly controller: AbortController;
51
+ destination: string | undefined;
52
+ installedSkills: Array<{
53
+ commit: string;
54
+ name: string;
55
+ path: string;
56
+ repository: string;
57
+ }>;
58
+ readonly operation: string;
59
+ settings: Settings | undefined;
60
+ stage: string;
61
+ starterRevision: string;
62
+ readonly versions: Record<string, string>;
63
+ constructor(operation: string);
64
+ checkCancelled(): void;
65
+ command(binary: string, args: string[], options: CommandOptions): Promise<string>;
66
+ prerequisites(cwd: string, hasSkills?: boolean): Promise<void>;
67
+ report<T extends Record<string, unknown>>(isJson: boolean, usage: string, task: () => Promise<T>, format: (result: T) => string): Promise<void>;
68
+ }
69
+ export declare function assertDestination(destination: string): Promise<void>;
70
+ export declare function resolveDestination(directory: string): Promise<string>;
71
+ export declare function packageFile(relative: string): string;
72
+ export declare function readJson<T>(file: string): Promise<T>;
73
+ export declare function findProduct(start?: string): Promise<Product | undefined>;
74
+ export declare function catalogDocument(product?: Product): Promise<{
75
+ digest: string;
76
+ text: string;
77
+ }>;
78
+ export declare function slug(value: string): string;
79
+ export {};