@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,4 @@
1
+ {
2
+ "catalog": "1.1.0",
3
+ "sha256": "14f8bf06942076bf593e89e20f6413677fbf8f0cf4aee9151fbe87e604150e17"
4
+ }
@@ -0,0 +1,33 @@
1
+ import { Command } from '@oclif/core';
2
+ import { findProduct, Workflow } from '../index.js';
3
+ import { type CatalogRecipe, type CatalogRow } from './stack/list.js';
4
+ export type RecipeSpec = CatalogRecipe & {
5
+ version: string;
6
+ };
7
+ type Catalog = {
8
+ recipes: CatalogRecipe[];
9
+ rows: CatalogRow[];
10
+ };
11
+ export declare function catalogRecipes(markdown: string): Catalog;
12
+ export declare function resolveRecipe(name: string, product?: Awaited<ReturnType<typeof findProduct>>): Promise<RecipeSpec>;
13
+ export declare function applyRecipe(workflow: Workflow, cwd: string, recipe: RecipeSpec, isDryRun: boolean): Promise<{
14
+ alreadyApplied: boolean;
15
+ changed: boolean;
16
+ dryRun: boolean;
17
+ package: string;
18
+ recipe: string;
19
+ workspace: string;
20
+ }>;
21
+ export default class Add extends Command {
22
+ static args: {
23
+ recipe: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
24
+ };
25
+ static description: string;
26
+ static flags: {
27
+ 'dry-run': import("@oclif/core/interfaces").BooleanFlag<boolean>;
28
+ json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
29
+ 'no-interactive': import("@oclif/core/interfaces").BooleanFlag<boolean>;
30
+ };
31
+ run(): Promise<void>;
32
+ }
33
+ export {};
@@ -0,0 +1,149 @@
1
+ import { Args, Command, Flags } from '@oclif/core';
2
+ import { lstat, mkdir, readFile, rmdir, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { catalogDocument, findProduct, Issue, readJson, release, slug, Workflow } from '../index.js';
5
+ import { compileCatalog, lookup, recipeVersion } from './stack/list.js';
6
+ const usage = 'Try: jokebook add runtime-validation --no-interactive (from a Jokebook product)';
7
+ export function catalogRecipes(markdown) {
8
+ const catalog = compileCatalog(markdown);
9
+ return { recipes: catalog.metadata?.recipes ?? [], rows: catalog.rows };
10
+ }
11
+ export async function resolveRecipe(name, product) {
12
+ const { text } = await catalogDocument(product);
13
+ const catalog = catalogRecipes(text);
14
+ const id = slug(name);
15
+ const recipe = catalog.recipes.find(({ aliases, id: recipeId }) => recipeId === id || aliases.includes(id));
16
+ if (recipe) {
17
+ return { ...recipe, version: recipeVersion(catalog.rows, recipe) };
18
+ }
19
+ const capability = lookup(catalog.rows, name);
20
+ if (capability) {
21
+ throw new Issue('This capability requires manual integration. Follow the catalog setup instructions.', { capability });
22
+ }
23
+ throw new Issue(`Unknown recipe "${name}". Run jokebook stack list to find a capability.`);
24
+ }
25
+ async function inspect(cwd, recipe) {
26
+ const workspace = path.join(cwd, recipe.workspace);
27
+ const manifest = path.join(workspace, 'package.json');
28
+ const lockfile = path.join(cwd, 'pnpm-lock.yaml');
29
+ const root = path.join(cwd, 'package.json');
30
+ const expected = [root, manifest, lockfile, path.join(cwd, 'pnpm-workspace.yaml')];
31
+ await Promise.all(expected.map(async (file) => {
32
+ if (!(await lstat(file)).isFile())
33
+ throw new Issue(`Expected a regular project file at ${file}.`);
34
+ }));
35
+ const { packageManager } = await readJson(root);
36
+ if (packageManager !== `pnpm@${release.pnpm}`)
37
+ throw new Issue('Restore the starter pnpm pin before applying recipes.');
38
+ const contents = await readFile(manifest, 'utf8');
39
+ const data = JSON.parse(contents);
40
+ const declarations = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']
41
+ .filter((group) => data[group]?.[recipe.package] !== undefined);
42
+ const isApplied = declarations.length === 1 && declarations[0] === 'dependencies' &&
43
+ data.dependencies?.[recipe.package] === recipe.version;
44
+ if (!isApplied && declarations.length > 0) {
45
+ throw new Issue(`${recipe.workspace} already declares ${recipe.package} in a conflicting form. Review that declaration before applying this recipe.`);
46
+ }
47
+ return { contents, isApplied, lockfile, manifest };
48
+ }
49
+ export async function applyRecipe(workflow, cwd, recipe, isDryRun) {
50
+ workflow.stage = 'recipe-inspection';
51
+ if (recipe.implementation !== 'valibot')
52
+ throw new Issue(`Unknown recipe implementation "${recipe.implementation}".`);
53
+ const current = await inspect(cwd, recipe);
54
+ const spec = `${recipe.package}@${recipe.version}`;
55
+ const result = {
56
+ alreadyApplied: current.isApplied,
57
+ changed: !current.isApplied && !isDryRun,
58
+ dryRun: isDryRun,
59
+ package: spec,
60
+ recipe: recipe.id,
61
+ workspace: recipe.workspace,
62
+ };
63
+ if (isDryRun)
64
+ return result;
65
+ const lock = path.join(cwd, '.jokebook-recipe-lock');
66
+ try {
67
+ await mkdir(lock);
68
+ }
69
+ catch (error) {
70
+ if (error.code === 'EEXIST') {
71
+ throw new Issue('Another Jokebook recipe is running. If it exited unexpectedly, remove the empty .jokebook-recipe-lock directory and retry.');
72
+ }
73
+ throw error;
74
+ }
75
+ try {
76
+ const { contents, isApplied, lockfile, manifest } = await inspect(cwd, recipe);
77
+ const previousLock = await readFile(lockfile);
78
+ workflow.stage = 'recipe-installation';
79
+ try {
80
+ if (!isApplied) {
81
+ await workflow.command('pnpm', ['--filter', `./${recipe.workspace}`, 'add', '--save-exact', '--lockfile-only', spec], {
82
+ cwd,
83
+ deliverable: `resolve ${spec} for ${recipe.workspace}`,
84
+ });
85
+ }
86
+ await workflow.command('pnpm', ['install', '--frozen-lockfile'], { cwd, deliverable: 'install recipe dependencies' });
87
+ workflow.stage = 'recipe-verification';
88
+ await workflow.command('pnpm', ['--filter', `./${recipe.workspace}`, 'exec', 'node', '--input-type=module',
89
+ '-e', `import {parse, string} from '${recipe.package}'; if (parse(string(), 'ready') !== 'ready') process.exit(1)`], {
90
+ cwd,
91
+ deliverable: `verify ${spec} from ${recipe.workspace}`,
92
+ });
93
+ return { ...result, alreadyApplied: isApplied, changed: !isApplied };
94
+ }
95
+ catch (error) {
96
+ if (!isApplied) {
97
+ await writeFile(manifest, contents);
98
+ await writeFile(lockfile, previousLock);
99
+ try {
100
+ await workflow.command('pnpm', ['install', '--frozen-lockfile'], {
101
+ cwd,
102
+ deliverable: 'restore original dependency installation',
103
+ signal: new AbortController().signal,
104
+ });
105
+ }
106
+ catch (error_) {
107
+ throw new Issue('Recipe failed and dependency recovery also failed. The pre-recipe manifest and lockfile were restored.', { original: error instanceof Issue ? { message: error.message, ...error.details } : String(error),
108
+ recovery: error_ instanceof Issue ? { message: error_.message, ...error_.details } : String(error_) });
109
+ }
110
+ }
111
+ throw error;
112
+ }
113
+ }
114
+ finally {
115
+ await rmdir(lock);
116
+ }
117
+ }
118
+ export default class Add extends Command {
119
+ static args = { recipe: Args.string({ description: 'Recipe or catalog capability slug', required: true }) };
120
+ static description = 'Apply a verified recipe to an existing product';
121
+ static flags = {
122
+ 'dry-run': Flags.boolean({ description: 'Inspect and show planned changes' }),
123
+ json: Flags.boolean({ description: 'Emit a single JSON result' }),
124
+ 'no-interactive': Flags.boolean({ description: 'Use unattended mode (the default)' }),
125
+ };
126
+ async run() {
127
+ const workflow = new Workflow('add');
128
+ await workflow.report(this.argv.includes('--json'), usage, async () => {
129
+ const { args, flags } = await this.parse(Add);
130
+ workflow.stage = 'recipe-inspection';
131
+ const product = await findProduct();
132
+ if (product) {
133
+ workflow.destination = product.cwd;
134
+ workflow.starterRevision = product.marker.starter;
135
+ await catalogDocument(product);
136
+ }
137
+ const recipe = await resolveRecipe(args.recipe, product);
138
+ if (!product)
139
+ throw new Issue('Run this command inside a product created by Jokebook.');
140
+ if (product.marker.starter !== release.revision)
141
+ throw new Issue('Use the Jokebook version that created this starter.');
142
+ if (!flags['dry-run'])
143
+ await workflow.prerequisites(product.cwd);
144
+ const result = await applyRecipe(workflow, product.cwd, recipe, flags['dry-run']);
145
+ workflow.stage = flags['dry-run'] ? 'plan' : 'complete';
146
+ return result;
147
+ }, (result) => `${result.dryRun ? 'Plan:' : 'Verified'} ${result.package} in ${result.workspace}${result.alreadyApplied ? ' (already applied)' : ''}`);
148
+ }
149
+ }
@@ -0,0 +1,18 @@
1
+ import { Command } from '@oclif/core';
2
+ export default class Init extends Command {
3
+ static args: {
4
+ product: import("@oclif/core/interfaces").Arg<string | undefined, Record<string, unknown>>;
5
+ };
6
+ static description: string;
7
+ static examples: string[];
8
+ static flags: {
9
+ dir: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
10
+ 'dry-run': import("@oclif/core/interfaces").BooleanFlag<boolean>;
11
+ interactive: import("@oclif/core/interfaces").BooleanFlag<boolean>;
12
+ json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
13
+ 'no-interactive': import("@oclif/core/interfaces").BooleanFlag<boolean>;
14
+ preset: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
15
+ with: import("@oclif/core/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/interfaces").CustomOptions>;
16
+ };
17
+ run(): Promise<void>;
18
+ }
@@ -0,0 +1,208 @@
1
+ import * as prompts from '@clack/prompts';
2
+ import { Args, Command, Flags } from '@oclif/core';
3
+ import { lstat, mkdtemp, readFile, rename, rm, rmdir, writeFile } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { assertDestination, catalogDocument, Issue, isUnattended, presets, readJson, release, resolveDestination, skills, Workflow, } from '../index.js';
6
+ import { extractStarter } from '../starter.js';
7
+ import { applyRecipe, catalogRecipes, resolveRecipe } from './add.js';
8
+ const usage = 'Try: jokebook init my-product --preset web --dir ./my-product --no-interactive';
9
+ const presetNames = Object.keys(presets);
10
+ function productError(value = '') {
11
+ if (value.length > 63 || !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/v.test(value)) {
12
+ return 'Use 1–63 lowercase letters, digits and single hyphens, starting with a letter.';
13
+ }
14
+ if (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9]|node-modules)$/v.test(value)) {
15
+ return 'Choose a name that is portable across filesystems.';
16
+ }
17
+ }
18
+ function answered(value) {
19
+ if (prompts.isCancel(value))
20
+ throw new Issue('Cancelled.', {}, 130);
21
+ return value;
22
+ }
23
+ async function promptProduct() {
24
+ return answered(await prompts.text({
25
+ message: 'Product name',
26
+ placeholder: 'my-product',
27
+ validate: productError,
28
+ }));
29
+ }
30
+ async function promptDestination(product) {
31
+ return answered(await prompts.text({
32
+ defaultValue: product,
33
+ message: 'Destination',
34
+ placeholder: './' + product,
35
+ }));
36
+ }
37
+ async function promptPreset() {
38
+ return answered(await prompts.select({
39
+ initialValue: 'web',
40
+ message: 'Preset',
41
+ options: presetNames.map((value) => ({
42
+ hint: presets[value], label: value === 'web' ? 'web (recommended)' : value, value,
43
+ })),
44
+ }));
45
+ }
46
+ async function promptRecipes(recipes) {
47
+ return answered(await prompts.multiselect({
48
+ message: 'Optional recipes',
49
+ options: recipes.map(({ id, package: packageName, summary }) => ({ hint: summary, label: packageName, value: id })),
50
+ required: false,
51
+ }));
52
+ }
53
+ function plan(settings) {
54
+ return [
55
+ settings.product + ' · ' + settings.preset,
56
+ settings.destination,
57
+ 'Starter ' + release.revision,
58
+ 'Recipes: ' + (settings.recipes.join(', ') || 'none'),
59
+ 'Skills: ' + skills.map(({ name }) => name).join(', '),
60
+ ].join('\n');
61
+ }
62
+ async function installSkill(workflow, stage, index) {
63
+ const skill = skills[index];
64
+ if (!skill)
65
+ return;
66
+ const { name, repo } = skill;
67
+ const repository = 'https://github.com/' + repo;
68
+ const args = ['--yes', 'skills@' + release.skillsCli, 'add', repository,
69
+ '--skill', name, '--agent', 'universal', '--copy', '--yes'];
70
+ const output = await workflow.command('npx', args, { cwd: stage, deliverable: `project skill ${name}` });
71
+ const relativePath = `.agents/skills/${name}/SKILL.md`;
72
+ const registration = await readJson(path.join(stage, 'skills-lock.json'));
73
+ const provenance = registration.skills[name];
74
+ const file = path.join(stage, relativePath);
75
+ const identity = /^---\r?\n([\s\S]*?)\r?\n---/v.exec(await readFile(file, 'utf8'))?.[1];
76
+ if (!(await lstat(file)).isFile() || !identity?.split(/\r?\n/v).includes('name: ' + name) ||
77
+ provenance?.source.toLowerCase() !== repo.toLowerCase() ||
78
+ provenance.installMode !== 'copy' || provenance.sourceType !== 'github' ||
79
+ !/^[a-f0-9]{40}$/v.test(provenance.commit)) {
80
+ throw new Issue(`Skills CLI did not verify ${name} from ${repository}.`, {
81
+ command: ['npx', ...args].join(' '),
82
+ cwd: stage,
83
+ deliverable: relativePath,
84
+ exitCode: 0,
85
+ stdout: output,
86
+ versions: workflow.versions,
87
+ });
88
+ }
89
+ workflow.installedSkills.push({ commit: provenance.commit, name, path: relativePath, repository });
90
+ await installSkill(workflow, stage, index + 1);
91
+ }
92
+ async function installSkills(workflow, stage) {
93
+ workflow.stage = 'skills';
94
+ await installSkill(workflow, stage, 0);
95
+ }
96
+ async function applyRecipes(workflow, stage, recipes, index = 0) {
97
+ const recipe = recipes[index];
98
+ if (!recipe)
99
+ return;
100
+ await applyRecipe(workflow, stage, await resolveRecipe(recipe), false);
101
+ await applyRecipes(workflow, stage, recipes, index + 1);
102
+ }
103
+ async function materialize(workflow, settings) {
104
+ const { destination, preset, product, recipes } = settings;
105
+ const isDesktop = ['desktop', 'full'].includes(preset);
106
+ workflow.stage = 'generation';
107
+ const stage = await mkdtemp(path.join(path.dirname(destination), '.jokebook-'));
108
+ try {
109
+ await extractStarter(release.revision, preset, stage);
110
+ const { digest, text } = await catalogDocument();
111
+ await writeFile(path.join(stage, 'STACK.md'), text);
112
+ const manifest = path.join(stage, 'package.json');
113
+ const starterManifest = await readJson(manifest);
114
+ const marker = { catalog: release.catalog, preset, stackSha256: digest, starter: release.revision };
115
+ await writeFile(manifest, JSON.stringify({ ...starterManifest, jokebook: marker, name: product }, null, 2) + '\n');
116
+ if (isDesktop) {
117
+ const configFile = path.join(stage, 'apps/desktop/src-tauri/tauri.conf.json');
118
+ const config = await readJson(configFile);
119
+ config.productName = product;
120
+ config.identifier = `com.example.${product}`;
121
+ config.app.windows[0].title = product;
122
+ await writeFile(configFile, JSON.stringify(config, null, 2) + '\n');
123
+ }
124
+ workflow.stage = 'dependencies';
125
+ await workflow.command('pnpm', ['install', '--frozen-lockfile'], { cwd: stage, deliverable: 'product dependencies' });
126
+ await applyRecipes(workflow, stage, recipes);
127
+ await installSkills(workflow, stage);
128
+ workflow.stage = 'finalize';
129
+ workflow.checkCancelled();
130
+ await assertDestination(destination);
131
+ // Windows rename cannot replace an existing directory, even when empty.
132
+ if (process.platform === 'win32') {
133
+ try {
134
+ await rmdir(destination);
135
+ }
136
+ catch (error) {
137
+ if (error.code !== 'ENOENT')
138
+ throw error;
139
+ }
140
+ }
141
+ await rename(stage, destination);
142
+ }
143
+ finally {
144
+ await rm(stage, { force: true, recursive: true });
145
+ }
146
+ }
147
+ export default class Init extends Command {
148
+ static args = { product: Args.string({ description: 'Product name in kebab case' }) };
149
+ static description = 'Create a product from the bundled starter release';
150
+ static examples = ['<%= config.bin %> init my-product --preset web --no-interactive --json'];
151
+ static flags = {
152
+ dir: Flags.string({ description: 'Exact destination (default: ./<product>)' }),
153
+ 'dry-run': Flags.boolean({ description: 'Resolve the plan without writing anything' }),
154
+ interactive: Flags.boolean({ description: 'Prompt in a usable terminal outside CI' }),
155
+ json: Flags.boolean({ description: 'Emit a single JSON result without prompts' }),
156
+ 'no-interactive': Flags.boolean({ description: 'Resolve input without prompts' }),
157
+ preset: Flags.string({ description: 'Surface preset (default: web)', options: presetNames }),
158
+ with: Flags.string({ description: 'Apply an automated catalog recipe (repeat for each recipe)', multiple: true }),
159
+ };
160
+ async run() {
161
+ const workflow = new Workflow('init');
162
+ await workflow.report(this.argv.includes('--json'), usage, async () => {
163
+ const { args, flags } = await this.parse(Init);
164
+ const canPrompt = !isUnattended() && !flags.json && !flags['no-interactive'];
165
+ if (!canPrompt && flags.interactive) {
166
+ throw new Issue('--interactive requires a usable terminal outside CI and conflicts with --no-interactive and --json.');
167
+ }
168
+ await Promise.all((flags.with ?? []).map(async (recipe) => resolveRecipe(recipe)));
169
+ const catalog = catalogRecipes((await catalogDocument()).text);
170
+ const product = args.product ?? (canPrompt ? await promptProduct() : undefined);
171
+ if (!product)
172
+ throw new Issue('Supply a product name in non-interactive mode.');
173
+ const invalid = productError(product);
174
+ if (invalid)
175
+ throw new Issue(invalid);
176
+ const dir = flags.dir ?? (canPrompt ? await promptDestination(product) : product);
177
+ const preset = flags.preset ?? (canPrompt ? await promptPreset() : 'web');
178
+ const recipes = flags.with ?? (canPrompt ? await promptRecipes(catalog.recipes) : []);
179
+ workflow.stage = 'destination';
180
+ const settings = {
181
+ destination: await resolveDestination(dir),
182
+ preset,
183
+ product,
184
+ recipes: [...new Set(recipes)],
185
+ };
186
+ workflow.destination = settings.destination;
187
+ workflow.settings = settings;
188
+ if (flags['dry-run']) {
189
+ workflow.stage = 'plan';
190
+ return { dryRun: true, plan: plan(settings), skills: skills.map(({ name }) => name) };
191
+ }
192
+ if (canPrompt) {
193
+ prompts.note(plan(settings), 'Create product');
194
+ if (!answered(await prompts.confirm({ initialValue: true, message: 'Create this project?' }))) {
195
+ throw new Issue('Cancelled.', {}, 130);
196
+ }
197
+ }
198
+ await workflow.prerequisites(path.dirname(settings.destination), true);
199
+ if (canPrompt)
200
+ prompts.log.info('Installing the workspace and both project skills…');
201
+ await materialize(workflow, settings);
202
+ workflow.stage = 'complete';
203
+ return { created: settings.destination, dryRun: false, skills: skills.map(({ name }) => name) };
204
+ }, (result) => result.dryRun
205
+ ? result.plan
206
+ : `Created ${result.created}\nRun pnpm dev from the project root. See README.md for the API and native targets.`);
207
+ }
208
+ }
@@ -0,0 +1,51 @@
1
+ import { Command } from '@oclif/core';
2
+ export type CatalogRecipe = {
3
+ aliases: string[];
4
+ capability: string;
5
+ id: string;
6
+ implementation: string;
7
+ package: string;
8
+ summary: string;
9
+ workspace: string;
10
+ };
11
+ type CatalogSection = {
12
+ header: string;
13
+ heading: string;
14
+ workspace: string;
15
+ };
16
+ export type CatalogMetadata = {
17
+ recipes: CatalogRecipe[];
18
+ sections: CatalogSection[];
19
+ };
20
+ export type CatalogRow = {
21
+ capability: string;
22
+ id: string;
23
+ recipe: string | undefined;
24
+ section: string;
25
+ selection: string;
26
+ setup: string;
27
+ source: {
28
+ document: string;
29
+ line: number;
30
+ links: string[];
31
+ };
32
+ status: string;
33
+ versions: string[];
34
+ workspace: string;
35
+ };
36
+ export declare function catalogMetadata(markdown: string): CatalogMetadata | undefined;
37
+ export declare function compileCatalog(markdown: string): {
38
+ metadata: CatalogMetadata | undefined;
39
+ rows: CatalogRow[];
40
+ };
41
+ export declare function entries(markdown: string): CatalogRow[];
42
+ export declare function recipeVersion(rows: CatalogRow[], recipe: CatalogRecipe): string;
43
+ export declare function lookup(catalog: ReturnType<typeof entries>, capability: string): CatalogRow;
44
+ export default class List extends Command {
45
+ static description: string;
46
+ static flags: {
47
+ json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
48
+ };
49
+ run(): Promise<void>;
50
+ }
51
+ export {};