@shoplifter/cli 0.1.7 → 0.1.10

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 CHANGED
@@ -1,9 +1,28 @@
1
1
  # Shoplifter CLI
2
2
 
3
- Requires Node 24. This source prepares CLI `0.1.5` with SDK and contract `0.1.2`.
4
- After publication, install with `npm install --global @shoplifter/cli@0.1.5`.
3
+ Requires Node 24. This source prepares CLI `0.1.9` with SDK and contract `0.2.0`.
4
+ After publication, install with `npm install --global @shoplifter/cli@0.1.9`.
5
5
  Existing projects upgrade runtime inputs only through explicit dependency synchronization.
6
6
 
7
+ ## Agent skills
8
+
9
+ After the public docs catalog and CLI 0.1.9 are released:
10
+
11
+ ```sh
12
+ shoplifter skills install --agent codex
13
+ shoplifter skills install --agent claude
14
+ shoplifter skills install --agent all --version 0.1.0
15
+ shoplifter skills install --agent codex --global
16
+ ```
17
+
18
+ Installs both official Shoplifter skills in the current directory by default:
19
+ `.agents/skills` for Codex, `.claude/skills` for Claude Code. `--global` uses the
20
+ corresponding directories under your home. No login is needed. Bundles are selected
21
+ against this CLI version and its pinned SDK runtime, then checksum/path validated
22
+ before installation. Identical installs stay unchanged. Use `--force` only to
23
+ replace differing Shoplifter skill folders; unrelated skills/settings are preserved.
24
+ Manual ZIPs and installation guidance are at https://docs.shoplifter.co.il/en/skills/.
25
+
7
26
  ## Authoring
8
27
 
9
28
  `shoplifter init ./site site` downloads the matching public SDK and contract with
@@ -57,6 +76,8 @@ Set `SHOPLIFTER_API_URL=https://<platform-api-host>` before production operation
57
76
  `shoplifter dependencies sync` anonymously downloads the platform-approved public
58
77
  runtime, verifies hashes and explicitly updates local archives and the lockfile.
59
78
  It preserves authored files. Run `npm ci --ignore-scripts` after synchronization.
79
+ For an unpublished local runtime pair, use `shoplifter dependencies sync
80
+ /absolute/path/sdk.tgz /absolute/path/contract.tgz`; both archives are required.
60
81
 
61
82
  `shoplifter login combo-media` opens dashboard approval for that channel code.
62
83
  With `shoplifter login` alone, explicitly choose a channel on the approval page.
package/dist/auth.d.ts CHANGED
@@ -8,4 +8,4 @@ export declare function credentials(required?: boolean): Promise<{
8
8
  export declare function sessionChannel(token: string): Promise<string>;
9
9
  export declare function login(channelCode?: string): Promise<void>;
10
10
  export declare function logout(): Promise<void>;
11
- export declare function syncDependencies(): Promise<void>;
11
+ export declare function syncDependencies(sdkArchive?: string, contractArchive?: string): Promise<void>;
package/dist/auth.js CHANGED
@@ -98,9 +98,13 @@ export async function logout() {
98
98
  }
99
99
  console.log('CLI session removed');
100
100
  }
101
- export async function syncDependencies() {
101
+ export async function syncDependencies(sdkArchive, contractArchive) {
102
102
  await readFile(resolve('shoplifter.json'));
103
- const { sdk, contract } = await downloadRuntime(process.env.SHOPLIFTER_API_URL ? apiOrigin() : undefined);
103
+ if (Boolean(sdkArchive) !== Boolean(contractArchive))
104
+ throw new Error('Provide both local SDK and contract archives');
105
+ const { sdk, contract } = sdkArchive && contractArchive
106
+ ? { sdk: await readFile(resolve(sdkArchive)), contract: await readFile(resolve(contractArchive)) }
107
+ : await downloadRuntime(process.env.SHOPLIFTER_API_URL ? apiOrigin() : undefined);
104
108
  const pkg = JSON.parse(await readFile(resolve('package.json'), 'utf8'));
105
109
  await mkdir(resolve('vendor'), { recursive: true });
106
110
  await writeFile(resolve('vendor/sdk.tgz'), sdk);
package/dist/files.d.ts CHANGED
@@ -10,7 +10,7 @@ export declare const projectFiles: {
10
10
  export declare function json(path: string): Promise<any>;
11
11
  export declare function writeJson(path: string, value: unknown): Promise<void>;
12
12
  export declare function readSourceBytes(path: string, maximum?: number): Promise<Buffer<ArrayBuffer>>;
13
- export declare function readProject(directory?: string, sourceImages?: boolean): Promise<PresentationProject>;
14
- export declare function generate(directory?: string, reset?: boolean): Promise<Fixture>;
13
+ export declare function readProject(directory?: string, sourceImages?: boolean, warn?: (message: string) => void): Promise<PresentationProject>;
14
+ export declare function generate(directory?: string, reset?: boolean, warn?: (message: string) => void): Promise<Fixture>;
15
15
  /** Check author source and built HTML. Raster rendering belongs to SDK Picture. */
16
- export declare function validateImages(directory: string, output?: boolean): Promise<void>;
16
+ export declare function validateImages(directory: string, output?: boolean, warn?: (message: string) => void): Promise<void>;
package/dist/files.js CHANGED
@@ -2,7 +2,10 @@ import { readFile, writeFile, rename, mkdir, realpath, readdir, lstat } from 'no
2
2
  import { createReadStream } from 'node:fs';
3
3
  import { resolve, relative, sep } from 'node:path';
4
4
  import { randomUUID } from 'node:crypto';
5
- import { validateProject, validateMigrations, generateFixtures, generateContentType, generateDataType, projectPath, validateImageMarkup, validateAstroConfig, } from '@shoplifter/presentation-contract';
5
+ import { execFile } from 'node:child_process';
6
+ import { promisify } from 'node:util';
7
+ import { pathToFileURL } from 'node:url';
8
+ import { validateProject, validateMigrations, generateFixtures, generateContentType, generateDataType, projectPath, validateImageMarkup, validateAstroConfig, imageMarkupWarnings, } from '@shoplifter/presentation-contract';
6
9
  export const projectFiles = {
7
10
  manifest: 'shoplifter.json', definition: 'definition.json', editor: 'editor.json',
8
11
  data: 'data.json', assets: 'assets.json', design: 'design.json',
@@ -27,24 +30,40 @@ export async function readSourceBytes(path, maximum = 12 * 1024 * 1024) {
27
30
  }
28
31
  return Buffer.concat(chunks);
29
32
  }
30
- export async function readProject(directory = process.cwd(), sourceImages = true) {
33
+ export async function readProject(directory = process.cwd(), sourceImages = true, warn = console.warn) {
31
34
  const entries = await Promise.all(Object.entries(projectFiles).map(async ([key, file]) => [key, JSON.parse((await readSourceBytes(resolve(directory, file))).toString())]));
35
+ const manifest = entries.find(([key]) => key === 'manifest')[1];
36
+ if (manifest.leads?.source) {
37
+ if (!projectPath(manifest.leads.source) || !manifest.leads.source.startsWith('src/') || !manifest.leads.source.endsWith('.ts'))
38
+ throw new Error('Invalid lead source');
39
+ const root = await realpath(directory), source = await realpath(resolve(directory, manifest.leads.source));
40
+ if (!source.startsWith(root + sep))
41
+ throw new Error('Lead source must stay inside the project');
42
+ const script = 'const m = await import(process.argv[1]); console.log(JSON.stringify({defaultFormId:m.defaultFormId,forms:m.leadForms.map(({form,component})=>({component,definition:JSON.parse(JSON.stringify(form))}))}));';
43
+ const { stdout } = await promisify(execFile)(process.execPath, ['--input-type=module', '-e', script, pathToFileURL(source).href], { cwd: root, timeout: 30000, maxBuffer: 256 * 1024 });
44
+ const generated = JSON.parse(stdout);
45
+ const next = { ...manifest, leads: { source: manifest.leads.source, ...generated } };
46
+ validateProject({ ...Object.fromEntries(entries), manifest: next });
47
+ if (JSON.stringify(manifest) !== JSON.stringify(next))
48
+ await writeJson(resolve(directory, 'shoplifter.json'), next);
49
+ entries.find(([key]) => key === 'manifest')[1] = next;
50
+ }
32
51
  const project = validateProject(Object.fromEntries(entries));
33
52
  validateMigrations(JSON.parse((await readSourceBytes(resolve(directory, 'migrations.json'))).toString()));
34
53
  validateAstroConfig((await readSourceBytes(resolve(directory, 'astro.config.mjs'))).toString());
35
54
  const root = await realpath(directory);
36
- for (const path of [...Object.values(project.manifest.components), ...Object.values(project.assets).map(asset => asset.file)]) {
55
+ for (const path of [...Object.values(project.manifest.components), ...(project.manifest.leads ? [project.manifest.leads.source, ...project.manifest.leads.forms.map(form => form.component)] : []), ...Object.values(project.assets).map(asset => asset.file)]) {
37
56
  const actual = await realpath(resolve(root, path));
38
57
  const local = relative(root, actual);
39
58
  if (local.startsWith('..' + sep) || local === '..' || !projectPath(local.split(sep).join('/')))
40
59
  throw new Error('Project files must stay inside the project');
41
60
  }
42
61
  if (sourceImages)
43
- await validateImages(directory);
62
+ await validateImages(directory, false, warn);
44
63
  return project;
45
64
  }
46
- export async function generate(directory = process.cwd(), reset = false) {
47
- const project = await readProject(directory), fixturePath = resolve(directory, 'fixtures.json');
65
+ export async function generate(directory = process.cwd(), reset = false, warn = console.warn) {
66
+ const project = await readProject(directory, true, warn), fixturePath = resolve(directory, 'fixtures.json');
48
67
  let previous;
49
68
  if (!reset) {
50
69
  try {
@@ -72,7 +91,8 @@ async function sourceFiles(directory) {
72
91
  }))).flat();
73
92
  }
74
93
  /** Check author source and built HTML. Raster rendering belongs to SDK Picture. */
75
- export async function validateImages(directory, output = false) {
94
+ export async function validateImages(directory, output = false, warn = console.warn) {
95
+ const warnings = new Set();
76
96
  const files = await sourceFiles(resolve(directory, output ? 'dist' : 'src'));
77
97
  if (!output) {
78
98
  try {
@@ -88,5 +108,9 @@ export async function validateImages(directory, output = false) {
88
108
  for (const path of files.filter(path => /\.(astro|[cm]?[jt]sx?|css|html|svg)$/.test(path))) {
89
109
  const source = await readFile(path, 'utf8');
90
110
  validateImageMarkup(source, path, output);
111
+ for (const warning of imageMarkupWarnings(source, output))
112
+ warnings.add(warning);
91
113
  }
114
+ for (const warning of warnings)
115
+ warn(warning);
92
116
  }
package/dist/index.js CHANGED
@@ -1,217 +1,84 @@
1
1
  #!/usr/bin/env node
2
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
- return c > 3 && r && Object.defineProperty(target, key, r), r;
7
- };
8
- var __metadata = (this && this.__metadata) || function (k, v) {
9
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
- };
11
- var __param = (this && this.__param) || function (paramIndex, decorator) {
12
- return function (target, key) { decorator(target, key, paramIndex); }
13
- };
14
- import { program, command, commandOption, requiredArg, optionalArg, description, version } from 'commander-ts';
2
+ import { Command } from 'commander-ts';
15
3
  import { spawn } from 'node:child_process';
16
4
  import { readFileSync } from 'node:fs';
17
5
  import { initialize, editProject, scaffold } from './author.js';
18
6
  import { generate, validateImages } from './files.js';
19
7
  import { publication, previewUpload } from './publication.js';
20
8
  import { login, logout, syncDependencies } from './auth.js';
21
- // commander-ts exits on async command failures without reporting the error.
22
- async function reportFailure(work) {
23
- try {
24
- await work();
25
- }
26
- catch (error) {
27
- console.error(error instanceof Error ? error.message : String(error));
28
- throw error;
29
- }
30
- }
31
- let Shoplifter = class Shoplifter {
32
- async files() { await previewUpload(); }
33
- async login(channelCode) { await reportFailure(() => login(channelCode)); }
34
- async logout() { await logout(); }
35
- async dependencies(action) { if (action !== 'sync')
36
- throw new Error('Choose dependencies sync'); await syncDependencies(); }
37
- run() {
38
- if (process.argv.length === 2)
39
- console.log('Commands: login, logout, dependencies, init, scaffold, fields, editor, assets, data, design, migrations, fixtures, dev, validate, types, files, publication');
40
- }
41
- async scaffold(component) { await scaffold(component); }
42
- async init(directory, id, sdk, contract) {
43
- await initialize(directory, id, sdk, contract);
44
- }
45
- async fields(action, path, json) { await editProject('fields', action, path, json); }
46
- async editor(action, path, json) { await editProject('editor', action, path, json); }
47
- async assets(action, path, json) { await editProject('assets', action, path, json); }
48
- async data(action, path, json) { await editProject('data', action, path, json); }
49
- async design(action, path, json) { await editProject('design', action, path, json); }
50
- async migrations(action, path, json) { await editProject('migrations', action, path, json); }
51
- async fixtures(action = 'generate') {
52
- if (!['generate', 'reset'].includes(action))
53
- throw new Error('Choose generate or reset');
54
- await generate(process.cwd(), action === 'reset');
55
- }
56
- async types() { await generate(); }
57
- async validate(mode) {
58
- if (mode && mode !== 'output')
59
- throw new Error('Unknown validation mode');
60
- await generate();
61
- if (mode === 'output')
62
- await validateImages(process.cwd(), true);
63
- console.log('Presentation is valid');
64
- }
65
- async dev() {
66
- await generate();
67
- const child = spawn('npm', ['run', 'dev'], { stdio: 'inherit', cwd: process.cwd() });
68
- const code = await new Promise((resolve, reject) => { child.once('error', reject); child.once('exit', code => resolve(code ?? 1)); });
69
- if (code)
70
- throw new Error(`Astro exited with status ${code}`);
71
- }
72
- async publication(action, channel, revision, language) {
73
- await reportFailure(() => publication(action, channel, revision, language, Boolean(this.opts().reset)));
74
- }
75
- };
76
- __decorate([
77
- command(),
78
- __metadata("design:type", Function),
79
- __metadata("design:paramtypes", []),
80
- __metadata("design:returntype", Promise)
81
- ], Shoplifter.prototype, "files", null);
82
- __decorate([
83
- command(),
84
- __param(0, optionalArg('channel-code')),
85
- __metadata("design:type", Function),
86
- __metadata("design:paramtypes", [String]),
87
- __metadata("design:returntype", Promise)
88
- ], Shoplifter.prototype, "login", null);
89
- __decorate([
90
- command(),
91
- __metadata("design:type", Function),
92
- __metadata("design:paramtypes", []),
93
- __metadata("design:returntype", Promise)
94
- ], Shoplifter.prototype, "logout", null);
95
- __decorate([
96
- command(),
97
- __param(0, requiredArg('action')),
98
- __metadata("design:type", Function),
99
- __metadata("design:paramtypes", [String]),
100
- __metadata("design:returntype", Promise)
101
- ], Shoplifter.prototype, "dependencies", null);
102
- __decorate([
103
- command(),
104
- __param(0, requiredArg('component')),
105
- __metadata("design:type", Function),
106
- __metadata("design:paramtypes", [String]),
107
- __metadata("design:returntype", Promise)
108
- ], Shoplifter.prototype, "scaffold", null);
109
- __decorate([
110
- command(),
111
- __param(0, requiredArg('directory')),
112
- __param(1, requiredArg('id')),
113
- __param(2, optionalArg('sdk-tarball')),
114
- __param(3, optionalArg('contract-tarball')),
115
- __metadata("design:type", Function),
116
- __metadata("design:paramtypes", [String, String, String, String]),
117
- __metadata("design:returntype", Promise)
118
- ], Shoplifter.prototype, "init", null);
119
- __decorate([
120
- command(),
121
- __param(0, requiredArg('action')),
122
- __param(1, requiredArg('path')),
123
- __param(2, optionalArg('json')),
124
- __metadata("design:type", Function),
125
- __metadata("design:paramtypes", [String, String, String]),
126
- __metadata("design:returntype", Promise)
127
- ], Shoplifter.prototype, "fields", null);
128
- __decorate([
129
- command(),
130
- __param(0, requiredArg('action')),
131
- __param(1, requiredArg('path')),
132
- __param(2, optionalArg('json')),
133
- __metadata("design:type", Function),
134
- __metadata("design:paramtypes", [String, String, String]),
135
- __metadata("design:returntype", Promise)
136
- ], Shoplifter.prototype, "editor", null);
137
- __decorate([
138
- command(),
139
- __param(0, requiredArg('action')),
140
- __param(1, requiredArg('path')),
141
- __param(2, optionalArg('json')),
142
- __metadata("design:type", Function),
143
- __metadata("design:paramtypes", [String, String, String]),
144
- __metadata("design:returntype", Promise)
145
- ], Shoplifter.prototype, "assets", null);
146
- __decorate([
147
- command(),
148
- __param(0, requiredArg('action')),
149
- __param(1, requiredArg('path')),
150
- __param(2, optionalArg('json')),
151
- __metadata("design:type", Function),
152
- __metadata("design:paramtypes", [String, String, String]),
153
- __metadata("design:returntype", Promise)
154
- ], Shoplifter.prototype, "data", null);
155
- __decorate([
156
- command(),
157
- __param(0, requiredArg('action')),
158
- __param(1, requiredArg('path')),
159
- __param(2, optionalArg('json')),
160
- __metadata("design:type", Function),
161
- __metadata("design:paramtypes", [String, String, String]),
162
- __metadata("design:returntype", Promise)
163
- ], Shoplifter.prototype, "design", null);
164
- __decorate([
165
- command(),
166
- __param(0, requiredArg('action')),
167
- __param(1, requiredArg('path')),
168
- __param(2, optionalArg('json')),
169
- __metadata("design:type", Function),
170
- __metadata("design:paramtypes", [String, String, String]),
171
- __metadata("design:returntype", Promise)
172
- ], Shoplifter.prototype, "migrations", null);
173
- __decorate([
174
- command(),
175
- __param(0, optionalArg('action')),
176
- __metadata("design:type", Function),
177
- __metadata("design:paramtypes", [Object]),
178
- __metadata("design:returntype", Promise)
179
- ], Shoplifter.prototype, "fixtures", null);
180
- __decorate([
181
- command(),
182
- __metadata("design:type", Function),
183
- __metadata("design:paramtypes", []),
184
- __metadata("design:returntype", Promise)
185
- ], Shoplifter.prototype, "types", null);
186
- __decorate([
187
- command(),
188
- __param(0, optionalArg('mode')),
189
- __metadata("design:type", Function),
190
- __metadata("design:paramtypes", [String]),
191
- __metadata("design:returntype", Promise)
192
- ], Shoplifter.prototype, "validate", null);
193
- __decorate([
194
- command(),
195
- __metadata("design:type", Function),
196
- __metadata("design:paramtypes", []),
197
- __metadata("design:returntype", Promise)
198
- ], Shoplifter.prototype, "dev", null);
199
- __decorate([
200
- command(),
201
- commandOption('--reset', 'Reset the channel preview link and revoke existing preview browsers'),
202
- __param(0, requiredArg('action')),
203
- __param(1, requiredArg('channel')),
204
- __param(2, optionalArg('revision')),
205
- __param(3, optionalArg('language')),
206
- __metadata("design:type", Function),
207
- __metadata("design:paramtypes", [String, String, String, String]),
208
- __metadata("design:returntype", Promise)
209
- ], Shoplifter.prototype, "publication", null);
210
- Shoplifter = __decorate([
211
- program(),
212
- version(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version),
213
- description('Author and publish independent Shoplifter presentations')
214
- ], Shoplifter);
9
+ import { installSkills } from './skills.js';
215
10
  if (Number(process.versions.node.split('.')[0]) !== 24)
216
11
  throw new Error('Shoplifter requires Node 24');
217
- new Shoplifter();
12
+ // Positional options keep root --version from swallowing skills --version.
13
+ // Command is already exported by commander-ts; no dependency changes are needed.
14
+ const program = new Command()
15
+ .name('shoplifter')
16
+ .description('Author and publish independent Shoplifter presentations')
17
+ .version(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version)
18
+ .enablePositionalOptions();
19
+ program.command('skills <action>')
20
+ .description('Install official Shoplifter agent skills')
21
+ .requiredOption('--agent <agent>', 'Install for codex, claude or all')
22
+ .option('--global', 'Install in the user home rather than the current project')
23
+ .option('--version <version>', 'Install an exact skill bundle version')
24
+ .option('--force', 'Replace differing Shoplifter skill folders')
25
+ .action(async (action, options) => {
26
+ if (action !== 'install')
27
+ throw new Error('Choose skills install');
28
+ await installSkills(options);
29
+ });
30
+ program.command('files').action(async () => { await previewUpload(); });
31
+ program.command('login [channel-code]').action((channel) => login(channel));
32
+ program.command('logout').action(() => logout());
33
+ program.command('dependencies <action> [sdk-archive] [contract-archive]')
34
+ .action(async (action, sdk, contract) => {
35
+ if (action !== 'sync')
36
+ throw new Error('Choose dependencies sync');
37
+ await syncDependencies(sdk, contract);
38
+ });
39
+ program.command('scaffold <component>').action((component) => scaffold(component));
40
+ program.command('init <directory> <id> [sdk-tarball] [contract-tarball]')
41
+ .action((directory, id, sdk, contract) => initialize(directory, id, sdk, contract));
42
+ for (const group of ['fields', 'editor', 'assets', 'data', 'design', 'migrations']) {
43
+ program.command(group + ' <action> <path> [json]')
44
+ .action((action, path, json) => editProject(group, action, path, json));
45
+ }
46
+ program.command('fixtures [action]').action(async (action = 'generate') => {
47
+ if (!['generate', 'reset'].includes(action))
48
+ throw new Error('Choose generate or reset');
49
+ await generate(process.cwd(), action === 'reset');
50
+ });
51
+ program.command('types').action(async () => { await generate(); });
52
+ program.command('validate [mode]').action(async (mode) => {
53
+ if (mode && mode !== 'output')
54
+ throw new Error('Unknown validation mode');
55
+ const warnings = new Set();
56
+ const warn = (message) => { if (!warnings.has(message)) {
57
+ warnings.add(message);
58
+ console.warn(message);
59
+ } };
60
+ await generate(process.cwd(), false, warn);
61
+ if (mode === 'output')
62
+ await validateImages(process.cwd(), true, warn);
63
+ console.log('Presentation is valid');
64
+ });
65
+ program.command('dev').action(async () => {
66
+ await generate();
67
+ const child = spawn('npm', ['run', 'dev'], { stdio: 'inherit', cwd: process.cwd() });
68
+ const code = await new Promise((resolve, reject) => { child.once('error', reject); child.once('exit', code => resolve(code ?? 1)); });
69
+ if (code)
70
+ throw new Error('Astro exited with status ' + code);
71
+ });
72
+ program.command('publication <action> <channel> [revision] [language]')
73
+ .option('--reset', 'Reset the channel preview link and revoke existing preview browsers')
74
+ .action((action, channel, revision, language, options) => publication(action, channel, revision, language, Boolean(options.reset)));
75
+ try {
76
+ if (process.argv.length === 2)
77
+ program.outputHelp();
78
+ else
79
+ await program.parseAsync(process.argv);
80
+ }
81
+ catch (error) {
82
+ console.error(error instanceof Error ? error.message : String(error));
83
+ process.exitCode = 1;
84
+ }
@@ -7,11 +7,11 @@
7
7
  },
8
8
  {
9
9
  "path": "auth.d.ts",
10
- "sha256": "ff98d7cbeca5a9fc2985acf804d18fcfe18e54cdac63a4484367b3e1638d349a"
10
+ "sha256": "19ccc11fadb17406cfa61d830338a58f0da2e51ab050a820ca4c02192bd6e8f9"
11
11
  },
12
12
  {
13
13
  "path": "auth.js",
14
- "sha256": "848d11a0471e0e82cfd759b82b5a927517bcb6ff89b47e12f4b588995bd32077"
14
+ "sha256": "686a9b0e3b7af947422eab83641d6e9cb5ea028b38c8f739b647fd5146769a86"
15
15
  },
16
16
  {
17
17
  "path": "author.d.ts",
@@ -23,11 +23,11 @@
23
23
  },
24
24
  {
25
25
  "path": "files.d.ts",
26
- "sha256": "2463402ebe9011eac96ee3275de96188513076ef279ad4c27ce2c02ba08df4ef"
26
+ "sha256": "26d33d1d21e3a20ea47db647f3823dc1d75b58183d42bba301364b8aaf2fb9f1"
27
27
  },
28
28
  {
29
29
  "path": "files.js",
30
- "sha256": "7deb659f0cdcbbc82b4e225d930c12627ab5f871c1cf2b24c119d08bc1282d79"
30
+ "sha256": "f65b46e16df3286bacdaeca4f5e598f4ab6b7c39a2d77dc01f9b9d9ff88a33f4"
31
31
  },
32
32
  {
33
33
  "path": "index.d.ts",
@@ -35,7 +35,7 @@
35
35
  },
36
36
  {
37
37
  "path": "index.js",
38
- "sha256": "a8527790a792a857f9e87d02753af4ca1c4e8bf70c93a33b22f28c35c600839c"
38
+ "sha256": "445a9124b79949d791133123c2297a3e2c7a763949a831be45313466ee195f57"
39
39
  },
40
40
  {
41
41
  "path": "publication.d.ts",
@@ -53,6 +53,22 @@
53
53
  "path": "runtime.js",
54
54
  "sha256": "c5ba204f6e98599e7dd376c9358e75e23ca266ff4c0c25762eea6af3cd10ca54"
55
55
  },
56
+ {
57
+ "path": "skill-archive.d.ts",
58
+ "sha256": "7cd7632e77ae06f80be41d411d1e8372a6fc699f0b1e8e7a0c30501c25bb85e1"
59
+ },
60
+ {
61
+ "path": "skill-archive.js",
62
+ "sha256": "3a795a8645934fcaa7c1c82131fa26951b49faa5acc65814ffef824e76383b1f"
63
+ },
64
+ {
65
+ "path": "skills.d.ts",
66
+ "sha256": "e7881284be051f8bd891b43ddd4b982b407e0dbe8da838b5954b05aafc6a8e13"
67
+ },
68
+ {
69
+ "path": "skills.js",
70
+ "sha256": "d464f87c26eea528018df16e347d1041b9c2e4f5f801ec397ded5c995ea33de1"
71
+ },
56
72
  {
57
73
  "path": "upload-archive.d.ts",
58
74
  "sha256": "7b73a3095ca90a2504658db0392dba26bbdecb4472435953487a5e1f6e51419d"
@@ -0,0 +1,6 @@
1
+ export declare const skillNames: readonly ["shoplifter-presentation-authoring", "shoplifter-presentation-publishing"];
2
+ export declare const archiveLimit: number;
3
+ /** A deterministic, uncompressed ZIP also usable by ordinary ZIP clients. */
4
+ export declare function createSkillZip(files: ReadonlyMap<string, Buffer>): Buffer;
5
+ /** Parse a deliberately small ZIP subset; never extract paths supplied by an archive. */
6
+ export declare function readSkillZip(zip: Buffer, expectedSkills?: readonly string[]): Map<string, Buffer>;
@@ -0,0 +1,102 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { crc32, inflateRawSync } from 'node:zlib';
3
+ export const skillNames = ['shoplifter-presentation-authoring', 'shoplifter-presentation-publishing'];
4
+ export const archiveLimit = 4 * 1024 * 1024;
5
+ const expandedLimit = 8 * 1024 * 1024;
6
+ /** A deterministic, uncompressed ZIP also usable by ordinary ZIP clients. */
7
+ export function createSkillZip(files) {
8
+ const local = [], central = [];
9
+ let offset = 0;
10
+ for (const [path, data] of [...files].sort(([a], [b]) => a.localeCompare(b))) {
11
+ const name = Buffer.from(path), crc = crc32(data);
12
+ const header = Buffer.alloc(30);
13
+ header.writeUInt32LE(0x04034b50);
14
+ header.writeUInt16LE(20, 4);
15
+ header.writeUInt16LE(0x800, 6);
16
+ header.writeUInt16LE(33, 12);
17
+ header.writeUInt32LE(crc, 14);
18
+ header.writeUInt32LE(data.length, 18);
19
+ header.writeUInt32LE(data.length, 22);
20
+ header.writeUInt16LE(name.length, 26);
21
+ local.push(header, name, data);
22
+ const entry = Buffer.alloc(46);
23
+ entry.writeUInt32LE(0x02014b50);
24
+ entry.writeUInt16LE(0x314, 4);
25
+ entry.writeUInt16LE(20, 6);
26
+ entry.writeUInt16LE(0x800, 8);
27
+ entry.writeUInt16LE(33, 14);
28
+ entry.writeUInt32LE(crc, 16);
29
+ entry.writeUInt32LE(data.length, 20);
30
+ entry.writeUInt32LE(data.length, 24);
31
+ entry.writeUInt16LE(name.length, 28);
32
+ entry.writeUInt32LE(0x81a40000, 38);
33
+ entry.writeUInt32LE(offset, 42);
34
+ central.push(entry, name);
35
+ offset += header.length + name.length + data.length;
36
+ }
37
+ const directory = Buffer.concat(central), end = Buffer.alloc(22);
38
+ end.writeUInt32LE(0x06054b50);
39
+ end.writeUInt16LE(files.size, 8);
40
+ end.writeUInt16LE(files.size, 10);
41
+ end.writeUInt32LE(directory.length, 12);
42
+ end.writeUInt32LE(offset, 16);
43
+ return Buffer.concat([...local, directory, end]);
44
+ }
45
+ /** Parse a deliberately small ZIP subset; never extract paths supplied by an archive. */
46
+ export function readSkillZip(zip, expectedSkills = skillNames) {
47
+ const fail = () => { throw new Error('Unsafe or malformed skill archive'); };
48
+ if (zip.length < 22 || zip.length > archiveLimit)
49
+ fail();
50
+ const end = zip.length - 22;
51
+ if (zip.readUInt32LE(end) !== 0x06054b50 || zip.readUInt16LE(end + 4) || zip.readUInt16LE(end + 6)
52
+ || zip.readUInt16LE(end + 20))
53
+ fail();
54
+ const count = zip.readUInt16LE(end + 10), start = zip.readUInt32LE(end + 16);
55
+ if (!count || count > 512 || count !== zip.readUInt16LE(end + 8) || start + zip.readUInt32LE(end + 12) !== end)
56
+ fail();
57
+ const files = new Map();
58
+ let position = start, expanded = 0, localEnd = 0;
59
+ for (let i = 0; i < count; i++) {
60
+ if (position + 46 > end || zip.readUInt32LE(position) !== 0x02014b50)
61
+ fail();
62
+ const flags = zip.readUInt16LE(position + 8), method = zip.readUInt16LE(position + 10);
63
+ const compressed = zip.readUInt32LE(position + 20), size = zip.readUInt32LE(position + 24);
64
+ const nameLength = zip.readUInt16LE(position + 28), extra = zip.readUInt16LE(position + 30), comment = zip.readUInt16LE(position + 32);
65
+ const offset = zip.readUInt32LE(position + 42), mode = zip.readUInt32LE(position + 38) >>> 16;
66
+ if ((flags & ~0x800) || ![0, 8].includes(method) || size > 1024 * 1024 || (expanded += size) > expandedLimit
67
+ || extra || comment || zip.readUInt16LE(position + 34) || (mode & 0xf000) !== 0x8000
68
+ || position + 46 + nameLength > end || offset !== localEnd || offset + 30 > start)
69
+ fail();
70
+ const name = zip.subarray(position + 46, position + 46 + nameLength).toString('utf8');
71
+ const parts = name.split('/');
72
+ if (!expectedSkills.includes(parts[0]) || parts.length < 2 || parts.some(part => !/^[a-zA-Z0-9_.-]+$/.test(part) || part === '.' || part === '..')
73
+ || !/\.(md|yaml|yml|json|txt)$/.test(name) || files.has(name))
74
+ fail();
75
+ if (zip.readUInt32LE(offset) !== 0x04034b50 || zip.readUInt16LE(offset + 6) !== flags
76
+ || zip.readUInt16LE(offset + 8) !== method || zip.readUInt32LE(offset + 14) !== zip.readUInt32LE(position + 16)
77
+ || zip.readUInt32LE(offset + 18) !== compressed || zip.readUInt32LE(offset + 22) !== size
78
+ || zip.readUInt16LE(offset + 26) !== nameLength || zip.readUInt16LE(offset + 28)
79
+ || !zip.subarray(offset + 30, offset + 30 + nameLength).equals(Buffer.from(name)))
80
+ fail();
81
+ const dataStart = offset + 30 + nameLength;
82
+ if (dataStart + compressed > start)
83
+ fail();
84
+ const compressedData = zip.subarray(dataStart, dataStart + compressed);
85
+ const data = method === 0 ? compressedData : inflateRawSync(compressedData, { maxOutputLength: 1024 * 1024 });
86
+ if (data.length !== size || crc32(data) !== zip.readUInt32LE(position + 16))
87
+ fail();
88
+ files.set(name, data);
89
+ localEnd = dataStart + compressed;
90
+ position += 46 + nameLength;
91
+ }
92
+ if (position !== end || localEnd !== start)
93
+ fail();
94
+ for (const name of expectedSkills) {
95
+ const source = files.get(name + '/SKILL.md')?.toString('utf8');
96
+ if (!source || !source.startsWith('---\n') || !source.includes('\n---\n')
97
+ || !source.split('\n---\n')[0].split('\n').includes('name: ' + name)
98
+ || !/^description: .+$/m.test(source.split('\n---\n')[0]))
99
+ fail();
100
+ }
101
+ return files;
102
+ }
@@ -0,0 +1,16 @@
1
+ export interface SkillInstallOptions {
2
+ agent: string;
3
+ global?: boolean;
4
+ version?: string;
5
+ force?: boolean;
6
+ }
7
+ interface Environment {
8
+ fetch?: typeof fetch;
9
+ directory?: string;
10
+ home?: string;
11
+ cliVersion?: string;
12
+ sdkVersion?: string;
13
+ log?: (text: string) => void;
14
+ }
15
+ export declare function installSkills(options: SkillInstallOptions, environment?: Environment): Promise<void>;
16
+ export {};
package/dist/skills.js ADDED
@@ -0,0 +1,188 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { createHash } from 'node:crypto';
3
+ import { homedir } from 'node:os';
4
+ import { join, dirname, resolve } from 'node:path';
5
+ import { lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises';
6
+ import { archiveLimit, readSkillZip, skillNames } from './skill-archive.js';
7
+ const origin = 'https://docs.shoplifter.co.il';
8
+ const catalogPath = '/downloads/skills/catalog-v1.json';
9
+ function versionParts(value) {
10
+ if (typeof value !== 'string' || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value))
11
+ throw new Error('Invalid skill catalog version');
12
+ const parts = value.split('.').map(Number);
13
+ if (parts.some(part => !Number.isSafeInteger(part)))
14
+ throw new Error('Invalid skill catalog version');
15
+ return parts;
16
+ }
17
+ function compare(a, b) {
18
+ const left = versionParts(a), right = versionParts(b);
19
+ return left[0] - right[0] || left[1] - right[1] || left[2] - right[2];
20
+ }
21
+ function accepts(version, range) {
22
+ if (!range || compare(range.min, range.maxExclusive) >= 0)
23
+ throw new Error('Invalid skill compatibility range');
24
+ return compare(version, range.min) >= 0 && compare(version, range.maxExclusive) < 0;
25
+ }
26
+ async function download(url, maximum, get) {
27
+ const response = await get(url, { redirect: 'error', signal: AbortSignal.timeout(30000) });
28
+ if (!response.ok || !response.body)
29
+ throw new Error(`Skill download failed (${response.status})`);
30
+ const chunks = [];
31
+ let size = 0;
32
+ for await (const chunk of response.body) {
33
+ size += chunk.length;
34
+ if (size > maximum)
35
+ throw new Error('Skill download exceeds size limit');
36
+ chunks.push(Buffer.from(chunk));
37
+ }
38
+ return Buffer.concat(chunks);
39
+ }
40
+ async function exists(path) {
41
+ try {
42
+ await lstat(path);
43
+ return true;
44
+ }
45
+ catch (error) {
46
+ if (error.code === 'ENOENT')
47
+ return false;
48
+ throw error;
49
+ }
50
+ }
51
+ async function safeDirectory(root, parts, create) {
52
+ let path = root;
53
+ for (const part of parts) {
54
+ path = join(path, part);
55
+ if (create && !await exists(path))
56
+ await mkdir(path);
57
+ if (await exists(path)) {
58
+ const entry = await lstat(path);
59
+ if (!entry.isDirectory() || entry.isSymbolicLink())
60
+ throw new Error('Skill destination must contain real directories: ' + path);
61
+ }
62
+ }
63
+ return path;
64
+ }
65
+ async function existingFiles(root, prefix = '') {
66
+ const files = new Map();
67
+ for (const entry of await readdir(join(root, prefix), { withFileTypes: true })) {
68
+ const path = prefix ? prefix + '/' + entry.name : entry.name;
69
+ if (entry.isSymbolicLink())
70
+ throw new Error('Skill destination contains a symlink: ' + path);
71
+ if (entry.isDirectory())
72
+ for (const [key, value] of await existingFiles(root, path))
73
+ files.set(key, value);
74
+ else if (entry.isFile())
75
+ files.set(path, await readFile(join(root, path)));
76
+ else
77
+ throw new Error('Unsupported skill destination file');
78
+ }
79
+ return files;
80
+ }
81
+ export async function installSkills(options, environment = {}) {
82
+ if (!['codex', 'claude', 'all'].includes(options.agent))
83
+ throw new Error('Choose --agent codex, claude or all');
84
+ if (options.version)
85
+ versionParts(options.version);
86
+ const metadata = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
87
+ const cliVersion = environment.cliVersion ?? metadata.version, sdkVersion = environment.sdkVersion ?? metadata.shoplifterRuntimeVersion;
88
+ const get = environment.fetch ?? fetch, log = environment.log ?? console.log;
89
+ const catalog = JSON.parse((await download(new URL(catalogPath, origin), 512 * 1024, get)).toString('utf8'));
90
+ if (catalog.schemaVersion !== 1 || !Array.isArray(catalog.releases) || catalog.releases.length > 200)
91
+ throw new Error('Unsupported skill catalog');
92
+ const versions = new Set();
93
+ const releases = catalog.releases.map((release) => {
94
+ versionParts(release.version);
95
+ if (versions.has(release.version))
96
+ throw new Error('Duplicate skill release');
97
+ versions.add(release.version);
98
+ accepts(cliVersion, release.compatibility?.cli);
99
+ accepts(sdkVersion, release.compatibility?.sdk);
100
+ const url = new URL(release.bundle?.url, origin);
101
+ if (url.origin !== origin || url.username || url.password || url.search || url.hash
102
+ || url.pathname !== `/downloads/skills/${release.version}/shoplifter-skills.zip`
103
+ || !/^[a-f0-9]{64}$/.test(release.bundle?.sha256))
104
+ throw new Error('Invalid skill bundle metadata');
105
+ return release;
106
+ });
107
+ const selected = releases.filter(release => (!options.version || release.version === options.version)
108
+ && accepts(cliVersion, release.compatibility.cli) && accepts(sdkVersion, release.compatibility.sdk))
109
+ .sort((a, b) => compare(b.version, a.version))[0];
110
+ if (!selected)
111
+ throw new Error(`No compatible skill bundle for CLI ${cliVersion} / SDK ${sdkVersion}${options.version ? ' at version ' + options.version : ''}`);
112
+ const zip = await download(new URL(selected.bundle.url, origin), archiveLimit, get);
113
+ if (createHash('sha256').update(zip).digest('hex') !== selected.bundle.sha256)
114
+ throw new Error('Skill bundle checksum mismatch');
115
+ const files = readSkillZip(zip);
116
+ const root = await realpath(resolve(options.global ? environment.home ?? homedir() : environment.directory ?? process.cwd()));
117
+ const agents = options.agent === 'all' ? ['codex', 'claude'] : [options.agent];
118
+ const targets = [];
119
+ for (const agent of agents)
120
+ for (const name of skillNames) {
121
+ const parts = [agent === 'codex' ? '.agents' : '.claude', 'skills'];
122
+ await safeDirectory(root, parts, false);
123
+ const path = join(root, ...parts, name), present = await exists(path);
124
+ if (present) {
125
+ await safeDirectory(root, [...parts, name], false);
126
+ const current = await existingFiles(path);
127
+ const expected = [...files].filter(([key]) => key.startsWith(name + '/')).map(([key, value]) => [key.slice(name.length + 1), value]);
128
+ if (current.size === expected.length && expected.every(([key, value]) => current.get(key)?.equals(value))) {
129
+ log(`Unchanged ${selected.version}: ${path}`);
130
+ continue;
131
+ }
132
+ if (!options.force)
133
+ throw new Error(`Skill already exists with different content: ${path}; use --force to replace it`);
134
+ }
135
+ targets.push({ path, name, parts, present });
136
+ }
137
+ if (!targets.length)
138
+ return;
139
+ const stage = await mkdtemp(join(root, '.shoplifter-skills-'));
140
+ const changed = [];
141
+ let cleanup = true;
142
+ try {
143
+ for (const [index, target] of targets.entries()) {
144
+ const incoming = join(stage, String(index));
145
+ await mkdir(incoming);
146
+ for (const [name, bytes] of files)
147
+ if (name.startsWith(target.name + '/')) {
148
+ const path = join(incoming, name.slice(target.name.length + 1));
149
+ await mkdir(dirname(path), { recursive: true });
150
+ await writeFile(path, bytes, { flag: 'wx' });
151
+ }
152
+ }
153
+ for (const [index, target] of targets.entries()) {
154
+ await safeDirectory(root, target.parts, true);
155
+ if (await exists(target.path) !== target.present)
156
+ throw new Error('Skill destination changed during installation');
157
+ if (target.present)
158
+ await safeDirectory(root, [...target.parts, target.name], false);
159
+ const record = { path: target.path, backup: target.present ? join(stage, 'backup-' + index) : undefined, installed: false };
160
+ if (record.backup)
161
+ await rename(target.path, record.backup);
162
+ changed.push(record);
163
+ await rename(join(stage, String(index)), target.path);
164
+ record.installed = true;
165
+ }
166
+ for (const target of targets)
167
+ log(`Installed ${selected.version}: ${target.path}`);
168
+ }
169
+ catch (error) {
170
+ try {
171
+ for (const record of changed.reverse()) {
172
+ if (record.installed)
173
+ await rm(record.path, { recursive: true });
174
+ if (record.backup)
175
+ await rename(record.backup, record.path);
176
+ }
177
+ }
178
+ catch (rollbackError) {
179
+ cleanup = false;
180
+ throw new AggregateError([error, rollbackError], 'Skill rollback incomplete; recoverable backups retained at ' + stage);
181
+ }
182
+ throw error;
183
+ }
184
+ finally {
185
+ if (cleanup)
186
+ await rm(stage, { recursive: true, force: true });
187
+ }
188
+ }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@shoplifter/cli",
3
- "version": "0.1.7",
4
- "shoplifterRuntimeVersion": "0.1.3",
5
- "shoplifterContractVersion": "0.1.2",
3
+ "version": "0.1.10",
4
+ "shoplifterRuntimeVersion": "0.3.1",
5
+ "shoplifterContractVersion": "0.3.0",
6
6
  "private": false,
7
7
  "license": "Apache-2.0",
8
8
  "description": "Author, validate and publish independent Shoplifter Astro presentations",
@@ -29,7 +29,7 @@
29
29
  "ignore": "^7.0.14",
30
30
  "tar-stream": "3.2.2",
31
31
  "reflect-metadata": "^0.1.14",
32
- "@shoplifter/presentation-contract": "0.1.2"
32
+ "@shoplifter/presentation-contract": "0.3.0"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@types/node": "^24.19.2",