@shoplifter/cli 0.0.0-stage → 0.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ Shoplifter presentation tooling
2
+
3
+ Shoplifter-owned code in this package is licensed under Apache License 2.0.
4
+ This license does not apply to the Shoplifter backend, private repository, customer
5
+ content, or third-party components. Third-party components retain their own
6
+ copyrights and licenses; see THIRD_PARTY_NOTICES and the bundled notice inventory.
7
+
8
+ Shared first-party rendering code is adapted from the Shoplifter storefront.
9
+ Generated release manifests record the repository-relative source provenance.
package/README.md CHANGED
@@ -1,3 +1,52 @@
1
- # Temporary Holding Version
1
+ # Shoplifter CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Requires Node 24. Install with `npm install --global @shoplifter/cli@0.1.0`.
4
+ The public SDK, contract and CLI release versions match.
5
+
6
+ ## Authoring
7
+
8
+ `shoplifter init ./site site` downloads the matching public SDK and contract with
9
+ integrity verification, without a dashboard session. For existing local archives:
10
+
11
+ ```sh
12
+ shoplifter init ./site site /absolute/sdk.tgz /absolute/contract.tgz
13
+ cd site
14
+ npm install
15
+ shoplifter fixtures generate
16
+ shoplifter types
17
+ shoplifter validate
18
+ npm run dev
19
+ npm run build
20
+ ```
21
+
22
+ Commands include `fields`, `editor`, `assets`, `data`, `design`, `migrations`,
23
+ `fixtures`, `types`, `validate`, `scaffold`, `files`, `dependencies`, `login`,
24
+ `logout` and `publication`. Authoring commands and manual edits share validation.
25
+ Use explicit `scaffold` or `fixtures reset` to create components or reset fixtures;
26
+ ordinary generation preserves valid edits and authored markup/styles.
27
+
28
+ ## Upload safety and publishing
29
+
30
+ `shoplifter files` prints only included file paths, byte sizes and the total size.
31
+ Uploads use that same file selection. Root and nested `.gitignore` and
32
+ `.shoplifterignore` rules are supported; missing required files are errors.
33
+ Mandatory credential/key/environment exclusions always win, including over negation.
34
+ Do not store private records or hardcoded credentials in project source.
35
+
36
+ Set `SHOPLIFTER_API_URL=https://<platform-api-host>` before production operations.
37
+ `shoplifter dependencies sync` anonymously downloads the platform-approved public
38
+ runtime, verifies hashes and explicitly updates local archives and the lockfile.
39
+ It preserves authored files. Run `npm ci --ignore-scripts` after synchronization.
40
+
41
+ `shoplifter login` opens dashboard approval for a specific channel. One-hour credentials
42
+ are stored with private permissions outside the project. Use `shoplifter logout` to revoke.
43
+ `shoplifter publication upload <channel-id>` uploads source; `stage`, `preview`,
44
+ `build`, `activate`, `publish`, `status`, `logs`, `retry`, `retry-deployment` and
45
+ `rollback` operate on channel-scoped revisions. `preview-link` requests protected
46
+ preview access. Source changes require exact-input preview and explicit activation.
47
+ Downloading the SDK never grants publication permission. The loopback bypass is
48
+ development-only and cannot be used remotely or in production.
49
+
50
+ Shoplifter-owned code is Apache-2.0; separately installed dependencies retain their
51
+ licenses. See `LICENSE`, `NOTICE` and `THIRD_PARTY_NOTICES`. This does not license
52
+ the private backend, repository or customer content.
@@ -0,0 +1,8 @@
1
+ Third-party components retain their original licenses.
2
+
3
+ Complete notices for code actually bundled into this package are generated from
4
+ the build inputs and included in dist/THIRD_PARTY_NOTICES. The matching
5
+ dist/release-manifest.json records dependency versions and file digests.
6
+
7
+ Dependencies installed separately by npm retain their own package licenses and
8
+ notices. This package's Apache-2.0 license does not replace those licenses.
@@ -0,0 +1,2 @@
1
+ Bundled dependencies retain their original licenses.
2
+
package/dist/auth.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ export declare function apiOrigin(): URL;
2
+ export declare function credentials(required?: boolean): Promise<{
3
+ token: string;
4
+ channelId: string;
5
+ expiresAt: string;
6
+ } | undefined>;
7
+ export declare function login(): Promise<void>;
8
+ export declare function logout(): Promise<void>;
9
+ export declare function syncDependencies(): Promise<void>;
package/dist/auth.js ADDED
@@ -0,0 +1,106 @@
1
+ import { mkdir, readFile, writeFile, rename, chmod, stat, rm } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { resolve } from 'node:path';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+ import { spawn } from 'node:child_process';
6
+ import { setTimeout as pause } from 'node:timers/promises';
7
+ import { downloadRuntime } from './runtime.js';
8
+ export function apiOrigin() {
9
+ const url = new URL(process.env.SHOPLIFTER_API_URL ?? 'http://localhost:3000');
10
+ if (url.username || url.password || url.pathname !== '/' || url.search || url.hash
11
+ || url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)))
12
+ throw new Error('Use an HTTPS API origin (HTTP is allowed only on loopback)');
13
+ return url;
14
+ }
15
+ const directory = () => resolve(process.env.SHOPLIFTER_CONFIG_DIRECTORY ?? resolve(homedir(), '.config/shoplifter'));
16
+ const filename = () => resolve(directory(), createHash('sha256').update(apiOrigin().origin).digest('hex') + '.json');
17
+ export async function credentials(required = true) {
18
+ try {
19
+ if (process.platform !== 'win32' && (await stat(filename())).mode & 0o077)
20
+ throw new Error('CLI credential file must be private (mode 0600)');
21
+ const value = JSON.parse(await readFile(filename(), 'utf8'));
22
+ if (!/^slw_[A-Za-z0-9_-]{43}$/.test(value.token) || !/^\d+$/.test(value.channelId) || !Number.isFinite(Date.parse(value.expiresAt)) || Date.parse(value.expiresAt) <= Date.now())
23
+ throw new Error('CLI session expired; run shoplifter login');
24
+ return value;
25
+ }
26
+ catch (error) {
27
+ if (error.code !== 'ENOENT')
28
+ throw error;
29
+ if (required)
30
+ throw new Error('Run shoplifter login first');
31
+ return undefined;
32
+ }
33
+ }
34
+ async function response(value) { if (!value.ok)
35
+ throw new Error(`CLI request failed (${value.status})`); return value.json(); }
36
+ export async function login() {
37
+ const origin = apiOrigin();
38
+ const grant = await response(await fetch(new URL('/shoplifter-cli/device', origin), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ scopes: ['read', 'content', 'source'] }), signal: AbortSignal.timeout(15000) }));
39
+ const url = new URL(grant.verificationUri);
40
+ if (url.origin !== origin.origin || !/^[A-F0-9]{10}$/.test(grant.userCode))
41
+ throw new Error('Invalid CLI approval response');
42
+ url.searchParams.set('code', grant.userCode);
43
+ console.log(`Approve code ${grant.userCode} in your dashboard: ${url}`);
44
+ if (['darwin', 'linux'].includes(process.platform)) {
45
+ const child = spawn(process.platform === 'darwin' ? 'open' : 'xdg-open', [url.href], { stdio: 'ignore', detached: true });
46
+ child.on('error', () => undefined);
47
+ child.unref();
48
+ }
49
+ for (let attempt = 0; attempt < 120; attempt++) {
50
+ await pause(5000);
51
+ const result = await response(await fetch(new URL('/shoplifter-cli/poll', origin), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ deviceCode: grant.deviceCode }), signal: AbortSignal.timeout(15000) }));
52
+ if (['pending', 'slow_down'].includes(result.status))
53
+ continue;
54
+ if (result.status !== 'approved')
55
+ throw new Error('CLI authorization denied or expired');
56
+ if (!/^slw_[A-Za-z0-9_-]{43}$/.test(result.token) || !/^\d+$/.test(result.channelId)
57
+ || !Number.isFinite(Date.parse(result.expiresAt)) || Date.parse(result.expiresAt) <= Date.now()
58
+ || Date.parse(result.expiresAt) > Date.now() + 3600000)
59
+ throw new Error('Invalid CLI credential response');
60
+ await mkdir(directory(), { recursive: true, mode: 0o700 });
61
+ await chmod(directory(), 0o700);
62
+ const temporary = filename() + '.' + randomUUID();
63
+ await writeFile(temporary, JSON.stringify({ token: result.token, channelId: result.channelId, expiresAt: result.expiresAt }), { mode: 0o600, flag: 'wx' });
64
+ await rename(temporary, filename());
65
+ console.log(`Authorized channel ${result.channelId} until ${result.expiresAt}`);
66
+ return;
67
+ }
68
+ throw new Error('CLI approval timed out');
69
+ }
70
+ export async function logout() {
71
+ try {
72
+ const session = await credentials(false);
73
+ if (session)
74
+ await response(await fetch(new URL('/shoplifter-cli/logout', apiOrigin()), { method: 'POST', headers: { authorization: 'Bearer ' + session.token }, signal: AbortSignal.timeout(15000) }));
75
+ }
76
+ finally {
77
+ await rm(filename(), { force: true });
78
+ }
79
+ console.log('CLI session removed');
80
+ }
81
+ export async function syncDependencies() {
82
+ await readFile(resolve('shoplifter.json'));
83
+ const { sdk, contract } = await downloadRuntime(process.env.SHOPLIFTER_API_URL ? apiOrigin() : undefined);
84
+ const pkg = JSON.parse(await readFile(resolve('package.json'), 'utf8'));
85
+ await mkdir(resolve('vendor'), { recursive: true });
86
+ await writeFile(resolve('vendor/sdk.tgz'), sdk);
87
+ await writeFile(resolve('vendor/contract.tgz'), contract);
88
+ pkg.dependencies = { ...pkg.dependencies, '@shoplifter/presentation-sdk': 'file:vendor/sdk.tgz', '@shoplifter/presentation-contract': 'file:vendor/contract.tgz' };
89
+ await writeFile(resolve('package.json'), JSON.stringify(pkg, null, 2) + '\n');
90
+ // Local archives can change while their package version and filename stay stable. Explicit sync must re-resolve their integrity.
91
+ try {
92
+ const lock = JSON.parse(await readFile(resolve('package-lock.json'), 'utf8'));
93
+ if (lock.packages)
94
+ for (const key of Object.keys(lock.packages))
95
+ if (/(?:^|\/)node_modules\/@shoplifter\/presentation-(?:sdk|contract)$/.test(key))
96
+ delete lock.packages[key];
97
+ await writeFile(resolve('package-lock.json'), JSON.stringify(lock, null, 2) + '\n');
98
+ }
99
+ catch (error) {
100
+ if (error.code !== 'ENOENT')
101
+ throw error;
102
+ }
103
+ const child = spawn('npm', ['install', '--package-lock-only', '--ignore-scripts', '--no-audit', '--no-fund'], { cwd: process.cwd(), stdio: 'inherit' });
104
+ await new Promise((done, reject) => { child.once('error', reject); child.once('exit', code => code === 0 ? done() : reject(new Error('Dependency lock synchronization failed'))); });
105
+ console.log('Platform archives and package-lock.json synchronized; authored components preserved');
106
+ }
@@ -0,0 +1,4 @@
1
+ export declare function editProject(group: string, action: string, path: string, raw?: string): Promise<void>;
2
+ /** Explicit scaffolding never replaces an authored component. */
3
+ export declare function scaffold(component: string): Promise<void>;
4
+ export declare function initialize(directory: string, id: string, sdkArchive?: string, contractArchive?: string): Promise<void>;
package/dist/author.js ADDED
@@ -0,0 +1,139 @@
1
+ import { mkdir, writeFile, access, readFile, lstat } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ import { json, readProject, writeJson, generate, projectFiles } from './files.js';
4
+ import { validateProject, validateMigrations, presentationAstroConfig } from '@shoplifter/presentation-contract';
5
+ import { downloadRuntime } from './runtime.js';
6
+ import { apiOrigin } from './auth.js';
7
+ function safeParts(path) {
8
+ const parts = path.split('.');
9
+ if (parts.some(part => !/^[a-zA-Z0-9_-]+$/.test(part) || ['constructor', 'prototype', '__proto__'].includes(part)))
10
+ throw new Error('Invalid path');
11
+ return parts;
12
+ }
13
+ function edit(value, action, path, next) {
14
+ const parts = safeParts(path), key = parts.pop();
15
+ let parent = value;
16
+ for (const part of parts) {
17
+ if (!parent || typeof parent !== 'object' || !Object.hasOwn(parent, part))
18
+ throw new Error('Unknown parent path');
19
+ parent = parent[part];
20
+ }
21
+ if (!parent || typeof parent !== 'object')
22
+ throw new Error('Invalid parent');
23
+ if (action === 'remove') {
24
+ if (!Object.hasOwn(parent, key))
25
+ throw new Error('Unknown path');
26
+ if (Array.isArray(parent))
27
+ parent.splice(Number(key), 1);
28
+ else
29
+ delete parent[key];
30
+ }
31
+ else if (action === 'set')
32
+ parent[key] = next;
33
+ else if (action === 'append') {
34
+ if (!Array.isArray(parent[key]))
35
+ throw new Error('Append requires a list');
36
+ parent[key].push(next);
37
+ }
38
+ else
39
+ throw new Error('Choose set, append or remove');
40
+ }
41
+ export async function editProject(group, action, path, raw) {
42
+ const directory = process.cwd(), project = await readProject(directory);
43
+ const next = raw === undefined ? undefined : raw.startsWith('@') ? await json(resolve(raw.slice(1))) : JSON.parse(raw);
44
+ if (group === 'migrations') {
45
+ const migrations = await json(resolve(directory, 'migrations.json'));
46
+ if (action === 'append' && path === 'operations')
47
+ throw new Error('Append a versioned migration, not a top-level operation');
48
+ if (action === 'append' && path === 'migrations')
49
+ migrations.push(next);
50
+ else
51
+ edit(migrations, action, path, next);
52
+ validateMigrations(migrations);
53
+ await writeJson(resolve(directory, 'migrations.json'), migrations);
54
+ return;
55
+ }
56
+ const key = group === 'fields' ? 'definition' : group;
57
+ if (!(key in projectFiles))
58
+ throw new Error('Unknown authoring group');
59
+ const file = key;
60
+ if (path === '$' && action === 'set')
61
+ project[file] = next;
62
+ else
63
+ edit(project[file], action, path, next);
64
+ validateProject(project);
65
+ // Files remain authoritative. Fixture errors are reported by validate/generate.
66
+ await writeJson(resolve(directory, projectFiles[file]), project[file]);
67
+ }
68
+ /** Explicit scaffolding never replaces an authored component. */
69
+ export async function scaffold(component) {
70
+ if (!['homepage', 'header', 'footer'].includes(component))
71
+ throw new Error('Choose homepage, header or footer');
72
+ const root = process.cwd();
73
+ const project = validateProject(Object.fromEntries(await Promise.all(Object.entries(projectFiles).map(async ([key, file]) => [key, await json(resolve(root, file))]))));
74
+ const path = project.manifest.components[component];
75
+ let directory = root;
76
+ for (const part of path.split('/').slice(0, -1)) {
77
+ directory = resolve(directory, part);
78
+ try {
79
+ await mkdir(directory);
80
+ }
81
+ catch (error) {
82
+ if (error.code !== 'EEXIST')
83
+ throw error;
84
+ }
85
+ if ((await lstat(directory)).isSymbolicLink())
86
+ throw new Error('Component directories cannot be symlinks');
87
+ }
88
+ const templates = {
89
+ homepage: '---\nconst { content } = Astro.props;\n---\n<main><h1>{content.title}</h1></main>\n',
90
+ header: '<header><a href="/">Home</a></header>\n', footer: '<footer>Built with Shoplifter</footer>\n',
91
+ };
92
+ await writeFile(resolve(root, path), templates[component], { flag: 'wx' });
93
+ }
94
+ export async function initialize(directory, id, sdkArchive, contractArchive) {
95
+ if (!/^[a-z][a-z0-9-]{0,63}$/.test(id))
96
+ throw new Error('Invalid presentation ID');
97
+ const root = resolve(directory);
98
+ try {
99
+ await access(root);
100
+ throw new Error('Initialization requires a new directory');
101
+ }
102
+ catch (error) {
103
+ if (error.code !== 'ENOENT')
104
+ throw error;
105
+ }
106
+ if (Boolean(sdkArchive) !== Boolean(contractArchive))
107
+ throw new Error('Provide both SDK and contract archives, or neither');
108
+ for (const archive of [sdkArchive, contractArchive].filter((value) => Boolean(value)))
109
+ if (!archive.endsWith('.tgz'))
110
+ throw new Error('Provide SDK and contract tarballs');
111
+ const runtime = sdkArchive && contractArchive ? { sdk: await readFile(resolve(sdkArchive)), contract: await readFile(resolve(contractArchive)) }
112
+ : await downloadRuntime(process.env.SHOPLIFTER_API_URL ? apiOrigin() : undefined);
113
+ await mkdir(resolve(root, 'src/components'), { recursive: true });
114
+ await mkdir(resolve(root, 'assets'), { recursive: true });
115
+ const project = {
116
+ manifest: { contractVersion: 1, components: { homepage: 'src/components/HomePage.astro', header: 'src/components/Header.astro', footer: 'src/components/Footer.astro' } },
117
+ definition: { contractVersion: 1, presentationId: id, version: 1, name: id, routes: ['/', '/pages/:slug', '/blogs/:blogSlug', '/blogs/:blogSlug/:slug', '/contact-us'], fields: [{ id: 'title', label: 'Title', type: 'text', required: true }], defaults: { title: id } },
118
+ editor: null, data: { content: { source: 'content' } }, assets: {}, design: {},
119
+ };
120
+ validateProject(project);
121
+ for (const [key, file] of Object.entries(projectFiles))
122
+ await writeJson(resolve(root, file), project[key]);
123
+ await writeJson(resolve(root, 'migrations.json'), []);
124
+ await mkdir(resolve(root, 'vendor'));
125
+ await writeFile(resolve(root, 'vendor/sdk.tgz'), runtime.sdk);
126
+ await writeFile(resolve(root, 'vendor/contract.tgz'), runtime.contract);
127
+ await writeJson(resolve(root, 'package.json'), {
128
+ name: id, private: true, type: 'module',
129
+ scripts: { dev: 'astro dev', build: 'astro build', preview: 'astro preview' },
130
+ engines: { node: '>=24 <25' },
131
+ dependencies: { astro: '^7.4.3', '@shoplifter/presentation-sdk': 'file:vendor/sdk.tgz', '@shoplifter/presentation-contract': 'file:vendor/contract.tgz' },
132
+ });
133
+ await writeFile(resolve(root, 'astro.config.mjs'), presentationAstroConfig);
134
+ await writeFile(resolve(root, 'src/components/HomePage.astro'), '---\nconst { content } = Astro.props;\n---\n<main><h1>{content.title}</h1></main>\n');
135
+ await writeFile(resolve(root, 'src/components/Header.astro'), '<header><a href="/">Home</a></header>\n');
136
+ await writeFile(resolve(root, 'src/components/Footer.astro'), '<footer>Built with Shoplifter</footer>\n');
137
+ await generate(root);
138
+ console.log(`Created ${root}. Run npm install, then npm run dev.`);
139
+ }
@@ -0,0 +1,15 @@
1
+ import { type PresentationProject, type Fixture } from '@shoplifter/presentation-contract';
2
+ export declare const projectFiles: {
3
+ readonly manifest: "shoplifter.json";
4
+ readonly definition: "definition.json";
5
+ readonly editor: "editor.json";
6
+ readonly data: "data.json";
7
+ readonly assets: "assets.json";
8
+ readonly design: "design.json";
9
+ };
10
+ export declare function json(path: string): Promise<any>;
11
+ export declare function writeJson(path: string, value: unknown): Promise<void>;
12
+ export declare function readProject(directory?: string): Promise<PresentationProject>;
13
+ export declare function generate(directory?: string, reset?: boolean): Promise<Fixture>;
14
+ /** Check author source and built HTML. Raster rendering belongs to SDK Picture. */
15
+ export declare function validateImages(directory: string, output?: boolean): Promise<void>;
package/dist/files.js ADDED
@@ -0,0 +1,76 @@
1
+ import { readFile, writeFile, rename, mkdir, realpath, readdir } from 'node:fs/promises';
2
+ import { resolve, relative, sep } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { validateProject, validateMigrations, generateFixtures, generateContentType, generateDataType, projectPath, validateImageMarkup, validateAstroConfig, } from '@shoplifter/presentation-contract';
5
+ export const projectFiles = {
6
+ manifest: 'shoplifter.json', definition: 'definition.json', editor: 'editor.json',
7
+ data: 'data.json', assets: 'assets.json', design: 'design.json',
8
+ };
9
+ export async function json(path) { return JSON.parse(await readFile(path, 'utf8')); }
10
+ export async function writeJson(path, value) {
11
+ const temporary = path + '.' + randomUUID() + '.tmp';
12
+ await writeFile(temporary, JSON.stringify(value, null, 2) + '\n', { flag: 'wx' });
13
+ await rename(temporary, path);
14
+ }
15
+ export async function readProject(directory = process.cwd()) {
16
+ const entries = await Promise.all(Object.entries(projectFiles).map(async ([key, file]) => [key, await json(resolve(directory, file))]));
17
+ const project = validateProject(Object.fromEntries(entries));
18
+ validateMigrations(await json(resolve(directory, 'migrations.json')));
19
+ validateAstroConfig(await readFile(resolve(directory, 'astro.config.mjs'), 'utf8'));
20
+ const root = await realpath(directory);
21
+ for (const path of [...Object.values(project.manifest.components), ...Object.values(project.assets).map(asset => asset.file)]) {
22
+ const actual = await realpath(resolve(root, path));
23
+ const local = relative(root, actual);
24
+ if (local.startsWith('..' + sep) || local === '..' || !projectPath(local.split(sep).join('/')))
25
+ throw new Error('Project files must stay inside the project');
26
+ }
27
+ await validateImages(directory);
28
+ return project;
29
+ }
30
+ export async function generate(directory = process.cwd(), reset = false) {
31
+ const project = await readProject(directory), fixturePath = resolve(directory, 'fixtures.json');
32
+ let previous;
33
+ if (!reset) {
34
+ try {
35
+ previous = await json(fixturePath);
36
+ }
37
+ catch (error) {
38
+ if (error.code !== 'ENOENT')
39
+ throw error;
40
+ }
41
+ }
42
+ const fixture = generateFixtures(project, previous);
43
+ await writeJson(fixturePath, fixture);
44
+ await mkdir(resolve(directory, 'src/generated'), { recursive: true });
45
+ await writeFile(resolve(directory, 'src/generated/content.d.ts'), generateContentType(project.definition.fields));
46
+ await writeFile(resolve(directory, 'src/generated/project.d.ts'), generateDataType(project));
47
+ return fixture;
48
+ }
49
+ async function sourceFiles(directory) {
50
+ const entries = await readdir(directory, { withFileTypes: true });
51
+ return (await Promise.all(entries.map(async (entry) => {
52
+ const path = resolve(directory, entry.name);
53
+ if (entry.isSymbolicLink())
54
+ throw new Error('Source symlinks are unsupported');
55
+ return entry.isDirectory() ? sourceFiles(path) : [path];
56
+ }))).flat();
57
+ }
58
+ /** Check author source and built HTML. Raster rendering belongs to SDK Picture. */
59
+ export async function validateImages(directory, output = false) {
60
+ const files = await sourceFiles(resolve(directory, output ? 'dist' : 'src'));
61
+ if (!output) {
62
+ try {
63
+ files.push(...await sourceFiles(resolve(directory, 'assets')));
64
+ }
65
+ catch (error) {
66
+ if (error.code !== 'ENOENT')
67
+ throw error;
68
+ }
69
+ }
70
+ if (!output && files.some(path => relative(directory, path).split(sep).join('/').startsWith('src/pages/')))
71
+ throw new Error('Additional routes are unsupported; SDK owns all page routes');
72
+ for (const path of files.filter(path => /\.(astro|[cm]?[jt]sx?|css|html|svg)$/.test(path))) {
73
+ const source = await readFile(path, 'utf8');
74
+ validateImageMarkup(source, path, output);
75
+ }
76
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,204 @@
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, requiredArg, optionalArg, description, version } from 'commander-ts';
15
+ import { spawn } from 'node:child_process';
16
+ import { initialize, editProject, scaffold } from './author.js';
17
+ import { generate, validateImages } from './files.js';
18
+ import { publication, previewUpload } from './publication.js';
19
+ import { login, logout, syncDependencies } from './auth.js';
20
+ let Shoplifter = class Shoplifter {
21
+ async files() { await previewUpload(); }
22
+ async login() { await login(); }
23
+ async logout() { await logout(); }
24
+ async dependencies(action) { if (action !== 'sync')
25
+ throw new Error('Choose dependencies sync'); await syncDependencies(); }
26
+ run() {
27
+ if (process.argv.length === 2)
28
+ console.log('Commands: login, logout, dependencies, init, scaffold, fields, editor, assets, data, design, migrations, fixtures, dev, validate, types, files, publication');
29
+ }
30
+ async scaffold(component) { await scaffold(component); }
31
+ async init(directory, id, sdk, contract) {
32
+ await initialize(directory, id, sdk, contract);
33
+ }
34
+ async fields(action, path, json) { await editProject('fields', action, path, json); }
35
+ async editor(action, path, json) { await editProject('editor', action, path, json); }
36
+ async assets(action, path, json) { await editProject('assets', action, path, json); }
37
+ async data(action, path, json) { await editProject('data', action, path, json); }
38
+ async design(action, path, json) { await editProject('design', action, path, json); }
39
+ async migrations(action, path, json) { await editProject('migrations', action, path, json); }
40
+ async fixtures(action = 'generate') {
41
+ if (!['generate', 'reset'].includes(action))
42
+ throw new Error('Choose generate or reset');
43
+ await generate(process.cwd(), action === 'reset');
44
+ }
45
+ async types() { await generate(); }
46
+ async validate(mode) {
47
+ if (mode && mode !== 'output')
48
+ throw new Error('Unknown validation mode');
49
+ await generate();
50
+ if (mode === 'output')
51
+ await validateImages(process.cwd(), true);
52
+ console.log('Presentation is valid');
53
+ }
54
+ async dev() {
55
+ await generate();
56
+ const child = spawn('npm', ['run', 'dev'], { stdio: 'inherit', cwd: process.cwd() });
57
+ const code = await new Promise((resolve, reject) => { child.once('error', reject); child.once('exit', code => resolve(code ?? 1)); });
58
+ if (code)
59
+ throw new Error(`Astro exited with status ${code}`);
60
+ }
61
+ async publication(action, channel, revision, language) {
62
+ await publication(action, channel, revision, language);
63
+ }
64
+ };
65
+ __decorate([
66
+ command(),
67
+ __metadata("design:type", Function),
68
+ __metadata("design:paramtypes", []),
69
+ __metadata("design:returntype", Promise)
70
+ ], Shoplifter.prototype, "files", null);
71
+ __decorate([
72
+ command(),
73
+ __metadata("design:type", Function),
74
+ __metadata("design:paramtypes", []),
75
+ __metadata("design:returntype", Promise)
76
+ ], Shoplifter.prototype, "login", null);
77
+ __decorate([
78
+ command(),
79
+ __metadata("design:type", Function),
80
+ __metadata("design:paramtypes", []),
81
+ __metadata("design:returntype", Promise)
82
+ ], Shoplifter.prototype, "logout", null);
83
+ __decorate([
84
+ command(),
85
+ __param(0, requiredArg('action')),
86
+ __metadata("design:type", Function),
87
+ __metadata("design:paramtypes", [String]),
88
+ __metadata("design:returntype", Promise)
89
+ ], Shoplifter.prototype, "dependencies", null);
90
+ __decorate([
91
+ command(),
92
+ __param(0, requiredArg('component')),
93
+ __metadata("design:type", Function),
94
+ __metadata("design:paramtypes", [String]),
95
+ __metadata("design:returntype", Promise)
96
+ ], Shoplifter.prototype, "scaffold", null);
97
+ __decorate([
98
+ command(),
99
+ __param(0, requiredArg('directory')),
100
+ __param(1, requiredArg('id')),
101
+ __param(2, optionalArg('sdk-tarball')),
102
+ __param(3, optionalArg('contract-tarball')),
103
+ __metadata("design:type", Function),
104
+ __metadata("design:paramtypes", [String, String, String, String]),
105
+ __metadata("design:returntype", Promise)
106
+ ], Shoplifter.prototype, "init", null);
107
+ __decorate([
108
+ command(),
109
+ __param(0, requiredArg('action')),
110
+ __param(1, requiredArg('path')),
111
+ __param(2, optionalArg('json')),
112
+ __metadata("design:type", Function),
113
+ __metadata("design:paramtypes", [String, String, String]),
114
+ __metadata("design:returntype", Promise)
115
+ ], Shoplifter.prototype, "fields", null);
116
+ __decorate([
117
+ command(),
118
+ __param(0, requiredArg('action')),
119
+ __param(1, requiredArg('path')),
120
+ __param(2, optionalArg('json')),
121
+ __metadata("design:type", Function),
122
+ __metadata("design:paramtypes", [String, String, String]),
123
+ __metadata("design:returntype", Promise)
124
+ ], Shoplifter.prototype, "editor", null);
125
+ __decorate([
126
+ command(),
127
+ __param(0, requiredArg('action')),
128
+ __param(1, requiredArg('path')),
129
+ __param(2, optionalArg('json')),
130
+ __metadata("design:type", Function),
131
+ __metadata("design:paramtypes", [String, String, String]),
132
+ __metadata("design:returntype", Promise)
133
+ ], Shoplifter.prototype, "assets", null);
134
+ __decorate([
135
+ command(),
136
+ __param(0, requiredArg('action')),
137
+ __param(1, requiredArg('path')),
138
+ __param(2, optionalArg('json')),
139
+ __metadata("design:type", Function),
140
+ __metadata("design:paramtypes", [String, String, String]),
141
+ __metadata("design:returntype", Promise)
142
+ ], Shoplifter.prototype, "data", null);
143
+ __decorate([
144
+ command(),
145
+ __param(0, requiredArg('action')),
146
+ __param(1, requiredArg('path')),
147
+ __param(2, optionalArg('json')),
148
+ __metadata("design:type", Function),
149
+ __metadata("design:paramtypes", [String, String, String]),
150
+ __metadata("design:returntype", Promise)
151
+ ], Shoplifter.prototype, "design", null);
152
+ __decorate([
153
+ command(),
154
+ __param(0, requiredArg('action')),
155
+ __param(1, requiredArg('path')),
156
+ __param(2, optionalArg('json')),
157
+ __metadata("design:type", Function),
158
+ __metadata("design:paramtypes", [String, String, String]),
159
+ __metadata("design:returntype", Promise)
160
+ ], Shoplifter.prototype, "migrations", null);
161
+ __decorate([
162
+ command(),
163
+ __param(0, optionalArg('action')),
164
+ __metadata("design:type", Function),
165
+ __metadata("design:paramtypes", [Object]),
166
+ __metadata("design:returntype", Promise)
167
+ ], Shoplifter.prototype, "fixtures", null);
168
+ __decorate([
169
+ command(),
170
+ __metadata("design:type", Function),
171
+ __metadata("design:paramtypes", []),
172
+ __metadata("design:returntype", Promise)
173
+ ], Shoplifter.prototype, "types", null);
174
+ __decorate([
175
+ command(),
176
+ __param(0, optionalArg('mode')),
177
+ __metadata("design:type", Function),
178
+ __metadata("design:paramtypes", [String]),
179
+ __metadata("design:returntype", Promise)
180
+ ], Shoplifter.prototype, "validate", null);
181
+ __decorate([
182
+ command(),
183
+ __metadata("design:type", Function),
184
+ __metadata("design:paramtypes", []),
185
+ __metadata("design:returntype", Promise)
186
+ ], Shoplifter.prototype, "dev", null);
187
+ __decorate([
188
+ command(),
189
+ __param(0, requiredArg('action')),
190
+ __param(1, requiredArg('channel')),
191
+ __param(2, optionalArg('revision')),
192
+ __param(3, optionalArg('language')),
193
+ __metadata("design:type", Function),
194
+ __metadata("design:paramtypes", [String, String, String, String]),
195
+ __metadata("design:returntype", Promise)
196
+ ], Shoplifter.prototype, "publication", null);
197
+ Shoplifter = __decorate([
198
+ program(),
199
+ version('0.1.0'),
200
+ description('Author and publish independent Shoplifter presentations')
201
+ ], Shoplifter);
202
+ if (Number(process.versions.node.split('.')[0]) !== 24)
203
+ throw new Error('Shoplifter requires Node 24');
204
+ new Shoplifter();
@@ -0,0 +1,8 @@
1
+ export declare function previewUpload(directory?: string): Promise<{
2
+ files: {
3
+ path: string;
4
+ size: number;
5
+ }[];
6
+ totalBytes: number;
7
+ }>;
8
+ export declare function publication(action: string, channel: string, revision?: string, languageCode?: string): Promise<void>;
@@ -0,0 +1,40 @@
1
+ import { apiOrigin, credentials } from './auth.js';
2
+ import { readProject } from './files.js';
3
+ import { collectUploadFiles } from './upload-files.js';
4
+ export async function previewUpload(directory = process.cwd()) {
5
+ const files = await collectUploadFiles(directory, await readProject(directory));
6
+ const preview = { files: files.map(file => ({ path: file.path, size: file.bytes.length })), totalBytes: files.reduce((sum, file) => sum + file.bytes.length, 0) };
7
+ console.log(JSON.stringify(preview, null, 2));
8
+ return preview;
9
+ }
10
+ export async function publication(action, channel, revision, languageCode) {
11
+ if (!['upload', 'stage', 'preview', 'preview-link', 'build', 'publish', 'status', 'logs', 'retry', 'retry-deployment', 'activate', 'rollback'].includes(action))
12
+ throw new Error('Unknown publication operation');
13
+ const base = apiOrigin(), session = await credentials(false);
14
+ if (session && session.channelId !== channel)
15
+ throw new Error('CLI session belongs to another channel; run shoplifter login');
16
+ if (!session && !['localhost', '127.0.0.1', '[::1]'].includes(base.hostname))
17
+ throw new Error('Run shoplifter login before publishing remotely');
18
+ if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password)
19
+ throw new Error('Invalid API origin');
20
+ const body = { channelId: channel, revisionId: revision, ...(languageCode ? { languageCode } : {}) };
21
+ if (action === 'upload') {
22
+ body.project = await readProject();
23
+ body.files = (await collectUploadFiles(process.cwd(), body.project)).map(file => ({ path: file.path, bytes: file.bytes.toString('base64') }));
24
+ }
25
+ if (['stage', 'preview', 'preview-link', 'build', 'retry', 'retry-deployment', 'activate', 'rollback'].includes(action) && !revision)
26
+ throw new Error('Revision ID is required');
27
+ if (action === 'preview-link' && !session)
28
+ throw new Error('Protected preview access requires shoplifter login');
29
+ const operation = action === 'preview' ? 'preview-candidate' : action === 'build' ? 'build-candidate' : action === 'preview-link' ? 'preview-access' : action;
30
+ const response = await fetch(new URL(session ? '/shoplifter-cli/operation' : '/shoplifter-development/' + operation, base), {
31
+ method: 'POST',
32
+ headers: { 'content-type': 'application/json', ...(session ? { authorization: 'Bearer ' + session.token } : {}) },
33
+ body: JSON.stringify(session ? { channelId: channel, languageCode, action: operation, input: body } : body),
34
+ signal: AbortSignal.timeout(120000),
35
+ });
36
+ const result = await response.text();
37
+ if (!response.ok)
38
+ throw new Error(`Publication failed (${response.status}): ${result}`);
39
+ console.log(result);
40
+ }
@@ -0,0 +1,67 @@
1
+ {
2
+ "version": 1,
3
+ "files": [
4
+ {
5
+ "path": "THIRD_PARTY_NOTICES",
6
+ "sha256": "f62b711e14475f3192779513371ef989b1eadd2737843f2dedcb7227b55fecd2"
7
+ },
8
+ {
9
+ "path": "auth.d.ts",
10
+ "sha256": "796dd7dad86e0c8865d78e10cdad471948121fa5d838f9f7f88c162d8e3f6734"
11
+ },
12
+ {
13
+ "path": "auth.js",
14
+ "sha256": "0f91582d678556c8d16f9f6be10993d5a47989914c06358c20ed25c213d90f6a"
15
+ },
16
+ {
17
+ "path": "author.d.ts",
18
+ "sha256": "6e545588915a50c89278b10c12e1870fd9331311b97d1971f2d86effa41fa120"
19
+ },
20
+ {
21
+ "path": "author.js",
22
+ "sha256": "fd7769a92839f79f625dee80357b7cae5ad26ee21b0fc142c1f544a7ee991cbe"
23
+ },
24
+ {
25
+ "path": "files.d.ts",
26
+ "sha256": "9394acb0d3434a82ef7589a4ec7bd2399837d0c1ef45f20b53a83f26a839a6cc"
27
+ },
28
+ {
29
+ "path": "files.js",
30
+ "sha256": "47947b274a0d4adb0c09224ddcb6b1ae91be662a2f65567875ffc38966d7ddec"
31
+ },
32
+ {
33
+ "path": "index.d.ts",
34
+ "sha256": "43e818adf60173644896298637f47b01d5819b17eda46eaa32d0c7d64724d012"
35
+ },
36
+ {
37
+ "path": "index.js",
38
+ "sha256": "69c7e98bf5dbcd110c84e975ae90837cd05d8364fbdbdb13bc8ca97f492ee867"
39
+ },
40
+ {
41
+ "path": "publication.d.ts",
42
+ "sha256": "d867e9cb1291895fbbc99fa0eae91f51c2dd0958cb8ab3128ae47b30051f5afb"
43
+ },
44
+ {
45
+ "path": "publication.js",
46
+ "sha256": "cfba2d5a39d1e1c3f713493f4fd58b886adc26573ee3691a660b23d827ca9d98"
47
+ },
48
+ {
49
+ "path": "runtime.d.ts",
50
+ "sha256": "1c64241a526c3d82e04df81089f4f9e0d4fd49b5aeb11929d857e20b9d752bca"
51
+ },
52
+ {
53
+ "path": "runtime.js",
54
+ "sha256": "134ba8b055ace5ee9ca375915a24848ba1cf677685da051462b6319cc1d637f7"
55
+ },
56
+ {
57
+ "path": "upload-files.d.ts",
58
+ "sha256": "72da98e62d7f85a523accb4f1148e2939ab2a5b9fb238b8e849168b98edcdb7c"
59
+ },
60
+ {
61
+ "path": "upload-files.js",
62
+ "sha256": "7c3c0a489e2ae2d4d8313660ffe645e92d69aaa59be6fc2a0c9a0f0520167ae5"
63
+ }
64
+ ],
65
+ "firstPartySources": [],
66
+ "bundledDependencies": []
67
+ }
@@ -0,0 +1,5 @@
1
+ /** Public code needs no publishing session. Production admission still pins the platform's exact runtime bytes. */
2
+ export declare function downloadRuntime(origin?: URL): Promise<{
3
+ sdk: Buffer;
4
+ contract: Buffer;
5
+ }>;
@@ -0,0 +1,53 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { readFile } from 'node:fs/promises';
3
+ import { createHash } from 'node:crypto';
4
+ const maximumArchive = 12 * 1024 * 1024;
5
+ async function bytes(response, maximum) {
6
+ if (!response.ok || !response.body)
7
+ throw new Error(`Public SDK download failed (${response.status}); use explicit local archives for an unpublished release`);
8
+ const chunks = [];
9
+ let size = 0;
10
+ try {
11
+ for await (const chunk of response.body) {
12
+ size += chunk.length;
13
+ if (size > maximum)
14
+ throw new Error('SDK download exceeds limit');
15
+ chunks.push(Buffer.from(chunk));
16
+ }
17
+ }
18
+ catch (error) {
19
+ await response.body.cancel().catch(() => undefined);
20
+ throw error;
21
+ }
22
+ return Buffer.concat(chunks);
23
+ }
24
+ const get = (url) => fetch(url, { redirect: 'error', signal: AbortSignal.timeout(30000) });
25
+ /** Public code needs no publishing session. Production admission still pins the platform's exact runtime bytes. */
26
+ export async function downloadRuntime(origin) {
27
+ if (origin) {
28
+ const result = JSON.parse((await bytes(await get(new URL('/shoplifter-cli/runtime', origin)), maximumArchive * 3)).toString());
29
+ const runtime = { sdk: Buffer.from(result.sdk ?? '', 'base64'), contract: Buffer.from(result.contract ?? '', 'base64') };
30
+ for (const kind of ['sdk', 'contract'])
31
+ if (!runtime[kind].length || runtime[kind].length > maximumArchive
32
+ || createHash('sha256').update(runtime[kind]).digest('hex') !== result[kind + 'Sha256'])
33
+ throw new Error('Invalid platform runtime archive');
34
+ return runtime;
35
+ }
36
+ const { version } = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
37
+ const archive = async (kind) => {
38
+ const name = '@shoplifter/presentation-' + kind;
39
+ const metadata = JSON.parse((await bytes(await get(`https://registry.npmjs.org/${encodeURIComponent(name)}/${version}`), 512 * 1024)).toString());
40
+ if (metadata.name !== name || metadata.version !== version || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(metadata.dist?.integrity ?? ''))
41
+ throw new Error('Invalid SDK release metadata');
42
+ const url = new URL(metadata.dist.tarball);
43
+ if (url.origin !== 'https://registry.npmjs.org' || url.username || url.password || url.search || url.hash
44
+ || !url.pathname.startsWith('/' + name + '/-/'))
45
+ throw new Error('Invalid SDK registry archive URL');
46
+ const buffer = await bytes(await get(url), maximumArchive);
47
+ if ('sha512-' + createHash('sha512').update(buffer).digest('base64') !== metadata.dist.integrity)
48
+ throw new Error('SDK release integrity mismatch');
49
+ return buffer;
50
+ };
51
+ const [sdk, contract] = await Promise.all([archive('sdk'), archive('contract')]);
52
+ return { sdk, contract };
53
+ }
@@ -0,0 +1,5 @@
1
+ import { type PresentationProject } from '@shoplifter/presentation-contract';
2
+ export declare function collectUploadFiles(directory: string, project: PresentationProject): Promise<{
3
+ path: string;
4
+ bytes: Buffer;
5
+ }[]>;
@@ -0,0 +1,70 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { readFile, readdir, lstat } from 'node:fs/promises';
3
+ import { resolve } from 'node:path';
4
+ import ignore from 'ignore';
5
+ import { assertPresentationSource, isPresentationSourceDirectory, isPresentationSourcePath } from '@shoplifter/presentation-contract';
6
+ export async function collectUploadFiles(directory, project) {
7
+ const files = [];
8
+ let totalBytes = 0;
9
+ async function walk(path = '', inherited = []) {
10
+ const rules = [...inherited];
11
+ for (const name of ['.gitignore', '.shoplifterignore']) {
12
+ try {
13
+ const file = resolve(directory, path, name), stat = await lstat(file);
14
+ if (!stat.isFile() || stat.size > 64 * 1024)
15
+ throw new Error('Ignore rules must be regular files smaller than 64 KiB');
16
+ rules.push({ base: path, matcher: ignore().add(await readFile(file, 'utf8')) });
17
+ }
18
+ catch (error) {
19
+ if (error.code !== 'ENOENT')
20
+ throw error;
21
+ }
22
+ }
23
+ for (const entry of (await readdir(resolve(directory, path), { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
24
+ const local = path ? path + '/' + entry.name : entry.name;
25
+ if (entry.isDirectory() ? !isPresentationSourceDirectory(local) : !isPresentationSourcePath(local, project))
26
+ continue;
27
+ let excluded = false;
28
+ for (const rule of rules) {
29
+ const relative = rule.base ? local.slice(rule.base.length + 1) : local;
30
+ const result = rule.matcher.test(relative + (entry.isDirectory() ? '/' : ''));
31
+ if (result.ignored)
32
+ excluded = true;
33
+ else if (result.unignored)
34
+ excluded = false;
35
+ }
36
+ if (excluded)
37
+ continue;
38
+ if (entry.isSymbolicLink() || !entry.isFile() && !entry.isDirectory())
39
+ throw new Error('Source files must be regular files, without symlinks');
40
+ if (entry.isDirectory()) {
41
+ await walk(local, rules);
42
+ continue;
43
+ }
44
+ const stat = await lstat(resolve(directory, local));
45
+ if (!stat.isFile())
46
+ throw new Error('Source files must be regular files, without symlinks');
47
+ if (stat.size > 12 * 1024 * 1024)
48
+ throw new Error(`Source file too large: ${JSON.stringify(local)}`);
49
+ if (files.length >= 2000 || totalBytes + stat.size > 96 * 1024 * 1024)
50
+ throw new Error('Source bundle exceeds limits');
51
+ const bytes = await readFile(resolve(directory, local));
52
+ assertPresentationSource(local, bytes, project);
53
+ if (bytes.length > 12 * 1024 * 1024)
54
+ throw new Error(`Source file too large: ${JSON.stringify(local)}`);
55
+ files.push({ path: local, bytes });
56
+ totalBytes += bytes.length;
57
+ if (totalBytes > 96 * 1024 * 1024)
58
+ throw new Error('Source bundle exceeds limits');
59
+ }
60
+ }
61
+ await walk();
62
+ if (files.length > 2000 || files.reduce((sum, file) => sum + file.bytes.length, 0) > 96 * 1024 * 1024)
63
+ throw new Error('Source bundle exceeds limits');
64
+ const required = ['shoplifter.json', 'definition.json', 'editor.json', 'data.json', 'assets.json', 'design.json', 'migrations.json', 'package.json', 'astro.config.mjs',
65
+ ...Object.values(project.manifest.components), ...Object.values(project.assets).map(asset => asset.file)];
66
+ for (const path of required)
67
+ if (!files.some(file => file.path === path))
68
+ throw new Error(`Required project file is missing or ignored: ${JSON.stringify(path)}`);
69
+ return files;
70
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@shoplifter/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "license": "Apache-2.0",
6
+ "description": "Author, validate and publish independent Shoplifter Astro presentations",
7
+ "engines": {
8
+ "node": ">=24 <25"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public",
12
+ "registry": "https://registry.npmjs.org/"
13
+ },
14
+ "type": "module",
15
+ "bin": {
16
+ "shoplifter": "./dist/index.js"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "LICENSE",
21
+ "NOTICE",
22
+ "THIRD_PARTY_NOTICES",
23
+ "README.md"
24
+ ],
25
+ "dependencies": {
26
+ "commander-ts": "0.2.0",
27
+ "ignore": "^7.0.14",
28
+ "reflect-metadata": "^0.1.14",
29
+ "@shoplifter/presentation-contract": "0.1.0"
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "^24.19.2",
33
+ "typescript": "5.8.2"
34
+ },
35
+ "scripts": {
36
+ "build": "node scripts/build.mjs",
37
+ "test": "node --test test/*.test.mjs"
38
+ }
6
39
  }