@shoplifter/cli 0.1.3 → 0.1.5
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 +22 -2
- package/THIRD_PARTY_NOTICES +23 -0
- package/dist/author.js +1 -1
- package/dist/files.d.ts +2 -1
- package/dist/files.js +22 -6
- package/dist/publication.js +5 -4
- package/dist/release-manifest.json +22 -6
- package/dist/upload-archive.d.ts +12 -0
- package/dist/upload-archive.js +59 -0
- package/dist/upload-files.d.ts +2 -1
- package/dist/upload-files.js +13 -6
- package/dist/upload.d.ts +9 -0
- package/dist/upload.js +170 -0
- package/package.json +5 -3
package/README.md
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
# Shoplifter CLI
|
|
2
2
|
|
|
3
|
-
Requires Node 24.
|
|
4
|
-
|
|
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`.
|
|
5
|
+
Existing projects upgrade runtime inputs only through explicit dependency synchronization.
|
|
5
6
|
|
|
6
7
|
## Authoring
|
|
7
8
|
|
|
@@ -33,6 +34,25 @@ Uploads use that same file selection. Root and nested `.gitignore` and
|
|
|
33
34
|
Mandatory credential/key/environment exclusions always win, including over negation.
|
|
34
35
|
Do not store private records or hardcoded credentials in project source.
|
|
35
36
|
|
|
37
|
+
`shoplifter publication upload combo-media` prepares a deterministic binary
|
|
38
|
+
archive and streams it directly to private S3. The platform authorizes the transfer
|
|
39
|
+
and validates the source asynchronously. Older CLIs must upgrade for uploads;
|
|
40
|
+
their other publication commands remain supported. No SDK upgrade is needed.
|
|
41
|
+
|
|
42
|
+
Rerun the same command after an interruption or after renewing an expired login.
|
|
43
|
+
The CLI resumes matching uploads and transfers only missing multipart parts. If
|
|
44
|
+
source contents changed, it cancels the previous incomplete session and starts a
|
|
45
|
+
new one. Checkpoints contain metadata only, without tokens or signed URLs. They
|
|
46
|
+
live outside the project under the private Shoplifter configuration directory
|
|
47
|
+
(`SHOPLIFTER_CONFIG_DIRECTORY`, or `~/.config/shoplifter`). Archive and checkpoint
|
|
48
|
+
files are removed after successful validation. A failed validation can be retried
|
|
49
|
+
by correcting the reported project/session issue and rerunning upload.
|
|
50
|
+
|
|
51
|
+
Limits: 2,000 files, 12 MiB per file, 96 MiB expanded and 112 MiB compressed.
|
|
52
|
+
Archives below 32 MiB use one PUT; larger archives use 8 MiB parts with at most
|
|
53
|
+
three concurrent transfers. Sessions expire after 24 hours, transfer grants after
|
|
54
|
+
at most 15 minutes. Two unfinished upload sessions may exist per channel.
|
|
55
|
+
|
|
36
56
|
Set `SHOPLIFTER_API_URL=https://<platform-api-host>` before production operations.
|
|
37
57
|
`shoplifter dependencies sync` anonymously downloads the platform-approved public
|
|
38
58
|
runtime, verifies hashes and explicitly updates local archives and the lockfile.
|
package/THIRD_PARTY_NOTICES
CHANGED
|
@@ -6,3 +6,26 @@ dist/release-manifest.json records dependency versions and file digests.
|
|
|
6
6
|
|
|
7
7
|
Dependencies installed separately by npm retain their own package licenses and
|
|
8
8
|
notices. This package's Apache-2.0 license does not replace those licenses.
|
|
9
|
+
|
|
10
|
+
tar-stream 3.2.2 is an independently installed runtime dependency.
|
|
11
|
+
The MIT License (MIT)
|
|
12
|
+
|
|
13
|
+
Copyright (c) 2014 Mathias Buus
|
|
14
|
+
|
|
15
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
16
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
17
|
+
in the Software without restriction, including without limitation the rights
|
|
18
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
19
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
20
|
+
furnished to do so, subject to the following conditions:
|
|
21
|
+
|
|
22
|
+
The above copyright notice and this permission notice shall be included in
|
|
23
|
+
all copies or substantial portions of the Software.
|
|
24
|
+
|
|
25
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
26
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
27
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
28
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
29
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
30
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
31
|
+
THE SOFTWARE.
|
package/dist/author.js
CHANGED
|
@@ -128,7 +128,7 @@ export async function initialize(directory, id, sdkArchive, contractArchive) {
|
|
|
128
128
|
name: id, private: true, type: 'module',
|
|
129
129
|
scripts: { dev: 'astro dev', build: 'astro build', preview: 'astro preview' },
|
|
130
130
|
engines: { node: '>=24 <25' },
|
|
131
|
-
dependencies: { astro: '^7.4.
|
|
131
|
+
dependencies: { astro: '^7.4.4', '@shoplifter/presentation-sdk': 'file:vendor/sdk.tgz', '@shoplifter/presentation-contract': 'file:vendor/contract.tgz' },
|
|
132
132
|
});
|
|
133
133
|
await writeFile(resolve(root, 'astro.config.mjs'), presentationAstroConfig);
|
|
134
134
|
await writeFile(resolve(root, 'src/components/HomePage.astro'), '---\nconst { content } = Astro.props;\n---\n<main><h1>{content.title}</h1></main>\n');
|
package/dist/files.d.ts
CHANGED
|
@@ -9,7 +9,8 @@ export declare const projectFiles: {
|
|
|
9
9
|
};
|
|
10
10
|
export declare function json(path: string): Promise<any>;
|
|
11
11
|
export declare function writeJson(path: string, value: unknown): Promise<void>;
|
|
12
|
-
export declare function
|
|
12
|
+
export declare function readSourceBytes(path: string, maximum?: number): Promise<Buffer<ArrayBuffer>>;
|
|
13
|
+
export declare function readProject(directory?: string, sourceImages?: boolean): Promise<PresentationProject>;
|
|
13
14
|
export declare function generate(directory?: string, reset?: boolean): Promise<Fixture>;
|
|
14
15
|
/** Check author source and built HTML. Raster rendering belongs to SDK Picture. */
|
|
15
16
|
export declare function validateImages(directory: string, output?: boolean): Promise<void>;
|
package/dist/files.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { readFile, writeFile, rename, mkdir, realpath, readdir } from 'node:fs/promises';
|
|
1
|
+
import { readFile, writeFile, rename, mkdir, realpath, readdir, lstat } from 'node:fs/promises';
|
|
2
|
+
import { createReadStream } from 'node:fs';
|
|
2
3
|
import { resolve, relative, sep } from 'node:path';
|
|
3
4
|
import { randomUUID } from 'node:crypto';
|
|
4
5
|
import { validateProject, validateMigrations, generateFixtures, generateContentType, generateDataType, projectPath, validateImageMarkup, validateAstroConfig, } from '@shoplifter/presentation-contract';
|
|
@@ -12,11 +13,25 @@ export async function writeJson(path, value) {
|
|
|
12
13
|
await writeFile(temporary, JSON.stringify(value, null, 2) + '\n', { flag: 'wx' });
|
|
13
14
|
await rename(temporary, path);
|
|
14
15
|
}
|
|
15
|
-
export async function
|
|
16
|
-
const
|
|
16
|
+
export async function readSourceBytes(path, maximum = 12 * 1024 * 1024) {
|
|
17
|
+
const information = await lstat(path);
|
|
18
|
+
if (!information.isFile() || information.size > maximum)
|
|
19
|
+
throw new Error('Source files must be regular files within the size limit');
|
|
20
|
+
const chunks = [];
|
|
21
|
+
let size = 0;
|
|
22
|
+
for await (const chunk of createReadStream(path)) {
|
|
23
|
+
size += chunk.length;
|
|
24
|
+
if (size > maximum)
|
|
25
|
+
throw new Error('Source file grew beyond its size limit');
|
|
26
|
+
chunks.push(Buffer.from(chunk));
|
|
27
|
+
}
|
|
28
|
+
return Buffer.concat(chunks);
|
|
29
|
+
}
|
|
30
|
+
export async function readProject(directory = process.cwd(), sourceImages = true) {
|
|
31
|
+
const entries = await Promise.all(Object.entries(projectFiles).map(async ([key, file]) => [key, JSON.parse((await readSourceBytes(resolve(directory, file))).toString())]));
|
|
17
32
|
const project = validateProject(Object.fromEntries(entries));
|
|
18
|
-
validateMigrations(await
|
|
19
|
-
validateAstroConfig(await
|
|
33
|
+
validateMigrations(JSON.parse((await readSourceBytes(resolve(directory, 'migrations.json'))).toString()));
|
|
34
|
+
validateAstroConfig((await readSourceBytes(resolve(directory, 'astro.config.mjs'))).toString());
|
|
20
35
|
const root = await realpath(directory);
|
|
21
36
|
for (const path of [...Object.values(project.manifest.components), ...Object.values(project.assets).map(asset => asset.file)]) {
|
|
22
37
|
const actual = await realpath(resolve(root, path));
|
|
@@ -24,7 +39,8 @@ export async function readProject(directory = process.cwd()) {
|
|
|
24
39
|
if (local.startsWith('..' + sep) || local === '..' || !projectPath(local.split(sep).join('/')))
|
|
25
40
|
throw new Error('Project files must stay inside the project');
|
|
26
41
|
}
|
|
27
|
-
|
|
42
|
+
if (sourceImages)
|
|
43
|
+
await validateImages(directory);
|
|
28
44
|
return project;
|
|
29
45
|
}
|
|
30
46
|
export async function generate(directory = process.cwd(), reset = false) {
|
package/dist/publication.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { apiOrigin, credentials, sessionChannel } from './auth.js';
|
|
2
2
|
import { readProject } from './files.js';
|
|
3
3
|
import { collectUploadFiles } from './upload-files.js';
|
|
4
|
+
import { uploadSource } from './upload.js';
|
|
4
5
|
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.
|
|
6
|
+
const files = await collectUploadFiles(directory, await readProject(directory, false));
|
|
7
|
+
const preview = { files: files.map(file => ({ path: file.path, size: file.size })), totalBytes: files.reduce((sum, file) => sum + file.size, 0) };
|
|
7
8
|
console.log(JSON.stringify(preview, null, 2));
|
|
8
9
|
return preview;
|
|
9
10
|
}
|
|
@@ -21,8 +22,8 @@ export async function publication(action, channel, revision, languageCode) {
|
|
|
21
22
|
const selector = !session && /^\d+$/.test(channel) ? { channelId: channel } : { channelCode };
|
|
22
23
|
const body = { ...selector, revisionId: revision, ...(languageCode ? { languageCode } : {}) };
|
|
23
24
|
if (action === 'upload') {
|
|
24
|
-
|
|
25
|
-
|
|
25
|
+
await uploadSource(base, session, channelCode);
|
|
26
|
+
return;
|
|
26
27
|
}
|
|
27
28
|
if (['stage', 'preview', 'preview-link', 'build', 'retry', 'retry-deployment', 'activate', 'rollback'].includes(action) && !revision)
|
|
28
29
|
throw new Error('Revision ID is required');
|
|
@@ -19,15 +19,15 @@
|
|
|
19
19
|
},
|
|
20
20
|
{
|
|
21
21
|
"path": "author.js",
|
|
22
|
-
"sha256": "
|
|
22
|
+
"sha256": "ef727e0db13478d93afa50a14c5f60b2862a59672a44d76a2a213ef1ac565fc4"
|
|
23
23
|
},
|
|
24
24
|
{
|
|
25
25
|
"path": "files.d.ts",
|
|
26
|
-
"sha256": "
|
|
26
|
+
"sha256": "2463402ebe9011eac96ee3275de96188513076ef279ad4c27ce2c02ba08df4ef"
|
|
27
27
|
},
|
|
28
28
|
{
|
|
29
29
|
"path": "files.js",
|
|
30
|
-
"sha256": "
|
|
30
|
+
"sha256": "7deb659f0cdcbbc82b4e225d930c12627ab5f871c1cf2b24c119d08bc1282d79"
|
|
31
31
|
},
|
|
32
32
|
{
|
|
33
33
|
"path": "index.d.ts",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
},
|
|
44
44
|
{
|
|
45
45
|
"path": "publication.js",
|
|
46
|
-
"sha256": "
|
|
46
|
+
"sha256": "2e72ea137f39db74b0f6b651d33464b7ceb76981ec65a40049d6849f17b5068a"
|
|
47
47
|
},
|
|
48
48
|
{
|
|
49
49
|
"path": "runtime.d.ts",
|
|
@@ -53,13 +53,29 @@
|
|
|
53
53
|
"path": "runtime.js",
|
|
54
54
|
"sha256": "f278ffc0d417812adbba6ac0dd742b0c5a3fc91c5089c310c9914dbb8a98f1d2"
|
|
55
55
|
},
|
|
56
|
+
{
|
|
57
|
+
"path": "upload-archive.d.ts",
|
|
58
|
+
"sha256": "7b73a3095ca90a2504658db0392dba26bbdecb4472435953487a5e1f6e51419d"
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
"path": "upload-archive.js",
|
|
62
|
+
"sha256": "46bd6403e4a03fc023f9c4a632597b717d2d3917610de4e678a6c72252a6c7fc"
|
|
63
|
+
},
|
|
56
64
|
{
|
|
57
65
|
"path": "upload-files.d.ts",
|
|
58
|
-
"sha256": "
|
|
66
|
+
"sha256": "80fb18b43cc8a580b6244f84019ddc5a7a5d92926eac93628cc719c78a07ee4a"
|
|
59
67
|
},
|
|
60
68
|
{
|
|
61
69
|
"path": "upload-files.js",
|
|
62
|
-
"sha256": "
|
|
70
|
+
"sha256": "51c102f2d15498059e930de28797e459d9b39354741976028bca194815dd6616"
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
"path": "upload.d.ts",
|
|
74
|
+
"sha256": "bc4291e91aed8bd37e72403f3d5059ef9a099dd88fd394ff1b0e96d2975ebb31"
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
"path": "upload.js",
|
|
78
|
+
"sha256": "86c545693218f34403bd942ac9de565926aa708ece9a64d06c5dff14e367803b"
|
|
63
79
|
}
|
|
64
80
|
],
|
|
65
81
|
"firstPartySources": [],
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { collectUploadFiles } from './upload-files.js';
|
|
2
|
+
export declare const uploadArchiveMaximum: number;
|
|
3
|
+
export declare const uploadManifestPath = ".shoplifter-upload.json";
|
|
4
|
+
export type UploadInventory = Awaited<ReturnType<typeof collectUploadFiles>>;
|
|
5
|
+
export declare const inventoryDigest: (files: UploadInventory) => string;
|
|
6
|
+
export declare function fileDigest(path: string, start?: number, end?: number): Promise<string>;
|
|
7
|
+
/** Bounded-memory packaging of a previously validated inventory. */
|
|
8
|
+
export declare function packUpload(directory: string, destination: string, files: UploadInventory): Promise<{
|
|
9
|
+
size: number;
|
|
10
|
+
sha256: string;
|
|
11
|
+
sourceDigest: string;
|
|
12
|
+
}>;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import { pack } from 'tar-stream';
|
|
3
|
+
import { createGzip } from 'node:zlib';
|
|
4
|
+
import { createReadStream, createWriteStream } from 'node:fs';
|
|
5
|
+
import { stat, rm } from 'node:fs/promises';
|
|
6
|
+
import { pipeline } from 'node:stream/promises';
|
|
7
|
+
import { Transform } from 'node:stream';
|
|
8
|
+
import { createHash } from 'node:crypto';
|
|
9
|
+
import { resolve } from 'node:path';
|
|
10
|
+
import { stableJson } from '@shoplifter/presentation-contract';
|
|
11
|
+
export const uploadArchiveMaximum = 112 * 1024 * 1024;
|
|
12
|
+
export const uploadManifestPath = '.shoplifter-upload.json';
|
|
13
|
+
export const inventoryDigest = (files) => createHash('sha256').update(stableJson(files.map(file => [file.path, file.sha256]))).digest('hex');
|
|
14
|
+
export async function fileDigest(path, start, end) {
|
|
15
|
+
const hash = createHash('sha256');
|
|
16
|
+
for await (const bytes of createReadStream(path, { start, end }))
|
|
17
|
+
hash.update(bytes);
|
|
18
|
+
return hash.digest('hex');
|
|
19
|
+
}
|
|
20
|
+
/** Bounded-memory packaging of a previously validated inventory. */
|
|
21
|
+
export async function packUpload(directory, destination, files) {
|
|
22
|
+
const archive = pack(), manifest = Buffer.from(JSON.stringify({ version: 1, files }));
|
|
23
|
+
if (manifest.length > 4 * 1024 * 1024)
|
|
24
|
+
throw new Error('Upload manifest exceeds limit');
|
|
25
|
+
let packedBytes = 0;
|
|
26
|
+
const writing = pipeline(archive, createGzip(), new Transform({ transform(chunk, _encoding, callback) {
|
|
27
|
+
packedBytes += chunk.length;
|
|
28
|
+
callback(packedBytes > uploadArchiveMaximum ? new Error('Compressed source exceeds limit') : null, chunk);
|
|
29
|
+
} }), createWriteStream(destination, { flags: 'wx', mode: 0o600 }));
|
|
30
|
+
// Observe failure immediately while entries are still being produced.
|
|
31
|
+
writing.catch(error => archive.destroy(error));
|
|
32
|
+
const header = (name, size) => ({ name, size, type: 'file', mode: 0o644, uid: 0, gid: 0, mtime: new Date(0) });
|
|
33
|
+
try {
|
|
34
|
+
await new Promise((done, reject) => archive.entry(header(uploadManifestPath, manifest.length), manifest, error => error ? reject(error) : done()));
|
|
35
|
+
for (const file of files) {
|
|
36
|
+
const path = resolve(directory, file.path), information = await stat(path);
|
|
37
|
+
if (!information.isFile() || information.size !== file.size)
|
|
38
|
+
throw new Error('Project changed during packaging; retry upload');
|
|
39
|
+
const hash = createHash('sha256');
|
|
40
|
+
let size = 0;
|
|
41
|
+
await pipeline(createReadStream(path), new Transform({ transform(chunk, _encoding, callback) {
|
|
42
|
+
size += chunk.length;
|
|
43
|
+
hash.update(chunk);
|
|
44
|
+
callback(size > file.size ? new Error('Project changed during packaging; retry upload') : null, chunk);
|
|
45
|
+
} }), archive.entry(header(file.path, file.size)));
|
|
46
|
+
if (size !== file.size || hash.digest('hex') !== file.sha256)
|
|
47
|
+
throw new Error('Project changed during packaging; retry upload');
|
|
48
|
+
}
|
|
49
|
+
archive.finalize();
|
|
50
|
+
await writing;
|
|
51
|
+
return { size: (await stat(destination)).size, sha256: await fileDigest(destination), sourceDigest: inventoryDigest(files) };
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
archive.destroy(error);
|
|
55
|
+
await writing.catch(() => undefined);
|
|
56
|
+
await rm(destination, { force: true });
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
}
|
package/dist/upload-files.d.ts
CHANGED
package/dist/upload-files.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
-
import {
|
|
2
|
+
import { readdir, lstat } from 'node:fs/promises';
|
|
3
3
|
import { resolve } from 'node:path';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
4
5
|
import ignore from 'ignore';
|
|
5
6
|
import { assertPresentationSource, isPresentationSourceDirectory, isPresentationSourcePath } from '@shoplifter/presentation-contract';
|
|
7
|
+
import { validateImageMarkup } from '@shoplifter/presentation-contract';
|
|
8
|
+
import { readSourceBytes } from './files.js';
|
|
6
9
|
export async function collectUploadFiles(directory, project) {
|
|
7
10
|
const files = [];
|
|
8
11
|
let totalBytes = 0;
|
|
@@ -13,7 +16,7 @@ export async function collectUploadFiles(directory, project) {
|
|
|
13
16
|
const file = resolve(directory, path, name), stat = await lstat(file);
|
|
14
17
|
if (!stat.isFile() || stat.size > 64 * 1024)
|
|
15
18
|
throw new Error('Ignore rules must be regular files smaller than 64 KiB');
|
|
16
|
-
rules.push({ base: path, matcher: ignore().add(await
|
|
19
|
+
rules.push({ base: path, matcher: ignore().add((await readSourceBytes(file, 64 * 1024)).toString()) });
|
|
17
20
|
}
|
|
18
21
|
catch (error) {
|
|
19
22
|
if (error.code !== 'ENOENT')
|
|
@@ -48,23 +51,27 @@ export async function collectUploadFiles(directory, project) {
|
|
|
48
51
|
throw new Error(`Source file too large: ${JSON.stringify(local)}`);
|
|
49
52
|
if (files.length >= 2000 || totalBytes + stat.size > 96 * 1024 * 1024)
|
|
50
53
|
throw new Error('Source bundle exceeds limits');
|
|
51
|
-
const bytes = await
|
|
54
|
+
const bytes = await readSourceBytes(resolve(directory, local));
|
|
52
55
|
assertPresentationSource(local, bytes, project);
|
|
56
|
+
if (local.startsWith('src/pages/'))
|
|
57
|
+
throw new Error('Additional routes are unsupported; SDK owns all page routes');
|
|
58
|
+
if (/\.(astro|[cm]?[jt]sx?|css|html|svg)$/.test(local))
|
|
59
|
+
validateImageMarkup(bytes.toString(), local);
|
|
53
60
|
if (bytes.length > 12 * 1024 * 1024)
|
|
54
61
|
throw new Error(`Source file too large: ${JSON.stringify(local)}`);
|
|
55
|
-
files.push({ path: local, bytes });
|
|
62
|
+
files.push({ path: local, size: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') });
|
|
56
63
|
totalBytes += bytes.length;
|
|
57
64
|
if (totalBytes > 96 * 1024 * 1024)
|
|
58
65
|
throw new Error('Source bundle exceeds limits');
|
|
59
66
|
}
|
|
60
67
|
}
|
|
61
68
|
await walk();
|
|
62
|
-
if (files.length > 2000 || files.reduce((sum, file) => sum + file.
|
|
69
|
+
if (files.length > 2000 || files.reduce((sum, file) => sum + file.size, 0) > 96 * 1024 * 1024)
|
|
63
70
|
throw new Error('Source bundle exceeds limits');
|
|
64
71
|
const required = ['shoplifter.json', 'definition.json', 'editor.json', 'data.json', 'assets.json', 'design.json', 'migrations.json', 'package.json', 'astro.config.mjs',
|
|
65
72
|
...Object.values(project.manifest.components), ...Object.values(project.assets).map(asset => asset.file)];
|
|
66
73
|
for (const path of required)
|
|
67
74
|
if (!files.some(file => file.path === path))
|
|
68
75
|
throw new Error(`Required project file is missing or ignored: ${JSON.stringify(path)}`);
|
|
69
|
-
return files;
|
|
76
|
+
return files.sort((a, b) => a.path.localeCompare(b.path));
|
|
70
77
|
}
|
package/dist/upload.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
type Session = {
|
|
2
|
+
token: string;
|
|
3
|
+
channelId: string;
|
|
4
|
+
channelCode?: string;
|
|
5
|
+
expiresAt: string;
|
|
6
|
+
};
|
|
7
|
+
/** Only metadata and immutable archive bytes are checkpointed; capabilities and credentials are never persisted. */
|
|
8
|
+
export declare function uploadSource(base: URL, session: Session | undefined, channelCode: string): Promise<void>;
|
|
9
|
+
export {};
|
package/dist/upload.js
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
import { mkdir, readFile, writeFile, rename, rm, lstat, realpath } from 'node:fs/promises';
|
|
3
|
+
import { createReadStream } from 'node:fs';
|
|
4
|
+
import { resolve } from 'node:path';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
7
|
+
import { setTimeout as pause } from 'node:timers/promises';
|
|
8
|
+
import { readProject } from './files.js';
|
|
9
|
+
import { collectUploadFiles } from './upload-files.js';
|
|
10
|
+
import { packUpload, fileDigest, inventoryDigest } from './upload-archive.js';
|
|
11
|
+
const hash = (value) => createHash('sha256').update(value).digest('hex');
|
|
12
|
+
/** Only metadata and immutable archive bytes are checkpointed; capabilities and credentials are never persisted. */
|
|
13
|
+
export async function uploadSource(base, session, channelCode) {
|
|
14
|
+
const directory = await realpath(process.cwd()), files = await collectUploadFiles(directory, await readProject(directory, false));
|
|
15
|
+
const sourceDigest = inventoryDigest(files), config = resolve(process.env.SHOPLIFTER_CONFIG_DIRECTORY ?? resolve(homedir(), '.config/shoplifter'));
|
|
16
|
+
const root = resolve(config, 'uploads', hash(base.origin), hash(channelCode + '\n' + directory));
|
|
17
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
18
|
+
if ((await lstat(root)).isSymbolicLink() || process.platform !== 'win32' && (await lstat(root)).mode & 0o077)
|
|
19
|
+
throw new Error('Upload checkpoint directory must be private');
|
|
20
|
+
const filename = resolve(root, 'checkpoint.json'), archivePath = resolve(root, 'source.tar.gz');
|
|
21
|
+
const headers = { 'content-type': 'application/json', 'x-shoplifter-channel-code': channelCode, ...(session ? { authorization: 'Bearer ' + session.token } : {}) };
|
|
22
|
+
async function control(method, path = '', input) {
|
|
23
|
+
const url = new URL('/shoplifter-cli/uploads' + path, base);
|
|
24
|
+
url.searchParams.set('channelCode', channelCode);
|
|
25
|
+
let response;
|
|
26
|
+
try {
|
|
27
|
+
response = await fetch(url, { method, headers, body: method === 'GET' ? undefined : JSON.stringify({ channelCode, ...input }),
|
|
28
|
+
redirect: 'error', signal: AbortSignal.timeout(30000) });
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
throw new Error('Upload control request failed; rerun upload to resume');
|
|
32
|
+
}
|
|
33
|
+
const text = await response.text();
|
|
34
|
+
if (!response.ok)
|
|
35
|
+
throw new Error(`Upload control failed (${response.status}): ${text.slice(0, 2048)}`);
|
|
36
|
+
return JSON.parse(text);
|
|
37
|
+
}
|
|
38
|
+
async function checkpoint(value) {
|
|
39
|
+
const temporary = filename + '.' + randomUUID();
|
|
40
|
+
try {
|
|
41
|
+
await writeFile(temporary, JSON.stringify(value), { flag: 'wx', mode: 0o600 });
|
|
42
|
+
await rename(temporary, filename);
|
|
43
|
+
}
|
|
44
|
+
finally {
|
|
45
|
+
await rm(temporary, { force: true });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
let saved;
|
|
49
|
+
try {
|
|
50
|
+
const information = await lstat(filename);
|
|
51
|
+
if (!information.isFile() || process.platform !== 'win32' && information.mode & 0o077)
|
|
52
|
+
throw new Error('Upload checkpoint must be private');
|
|
53
|
+
saved = JSON.parse(await readFile(filename, 'utf8'));
|
|
54
|
+
if (saved.version !== 1 || !/^[a-f0-9-]{36}$/.test(saved.requestId) || saved.uploadId !== undefined && !/^[a-f0-9-]{36}$/.test(saved.uploadId)
|
|
55
|
+
|| saved.channelCode !== channelCode || saved.directory !== directory)
|
|
56
|
+
throw new Error('Invalid upload checkpoint');
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
if (error.code !== 'ENOENT')
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
if (saved && !saved.uploadId) {
|
|
63
|
+
const recovered = await control('POST', '', { archive: saved.archive, requestId: saved.requestId });
|
|
64
|
+
saved.uploadId = recovered.uploadId;
|
|
65
|
+
await checkpoint(saved);
|
|
66
|
+
}
|
|
67
|
+
if (saved?.sourceDigest !== sourceDigest && saved) {
|
|
68
|
+
await control('DELETE', '/' + saved.uploadId);
|
|
69
|
+
await rm(filename, { force: true });
|
|
70
|
+
await rm(archivePath, { force: true });
|
|
71
|
+
saved = undefined;
|
|
72
|
+
}
|
|
73
|
+
let state;
|
|
74
|
+
if (saved) {
|
|
75
|
+
try {
|
|
76
|
+
state = await control('GET', '/' + saved.uploadId);
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
if (['cancelled', 'expired'].includes(state.status)) {
|
|
82
|
+
await rm(filename, { force: true });
|
|
83
|
+
await rm(archivePath, { force: true });
|
|
84
|
+
saved = undefined;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (!saved) {
|
|
88
|
+
await rm(archivePath, { force: true });
|
|
89
|
+
console.error(`Preparing ${files.length} source files (${files.reduce((sum, file) => sum + file.size, 0)} bytes)`);
|
|
90
|
+
const archive = { ...await packUpload(directory, archivePath, files), fileCount: files.length, expandedBytes: files.reduce((sum, file) => sum + file.size, 0) };
|
|
91
|
+
// Catch additions, removals and edits to already-read files before any upload session exists.
|
|
92
|
+
if (inventoryDigest(await collectUploadFiles(directory, await readProject(directory, false))) !== sourceDigest) {
|
|
93
|
+
await rm(archivePath, { force: true });
|
|
94
|
+
throw new Error('Project changed during packaging; retry upload');
|
|
95
|
+
}
|
|
96
|
+
saved = { version: 1, requestId: randomUUID(), channelCode, directory, sourceDigest, archive };
|
|
97
|
+
await checkpoint(saved);
|
|
98
|
+
state = await control('POST', '', { archive, requestId: saved.requestId });
|
|
99
|
+
saved.uploadId = state.uploadId;
|
|
100
|
+
await checkpoint(saved);
|
|
101
|
+
}
|
|
102
|
+
else if (state.status !== 'ready') {
|
|
103
|
+
const information = await lstat(archivePath);
|
|
104
|
+
if (!information.isFile() || information.isSymbolicLink() || process.platform !== 'win32' && information.mode & 0o077
|
|
105
|
+
|| information.size !== saved.archive.size || await fileDigest(archivePath) !== saved.archive.sha256)
|
|
106
|
+
throw new Error('Upload checkpoint archive is missing or changed; cancel it before starting again');
|
|
107
|
+
console.error('Resuming source upload');
|
|
108
|
+
}
|
|
109
|
+
if (['creating', 'uploading'].includes(state.status)) {
|
|
110
|
+
const size = saved.archive.size, partSize = state.partSize, count = Math.ceil(size / partSize), present = new Map((state.parts ?? []).map((part) => [part.number, part]));
|
|
111
|
+
if (!Number.isSafeInteger(partSize) || partSize < 1 || count > 14)
|
|
112
|
+
throw new Error('Invalid upload transfer configuration');
|
|
113
|
+
const pending = [];
|
|
114
|
+
for (let number = 1; number <= count; number++) {
|
|
115
|
+
const start = (number - 1) * partSize, length = Math.min(partSize, size - start), sha256 = await fileDigest(archivePath, start, start + length - 1);
|
|
116
|
+
const existing = present.get(number);
|
|
117
|
+
if (existing?.size !== length || existing?.sha256 !== sha256)
|
|
118
|
+
pending.push({ number, size: length, sha256 });
|
|
119
|
+
}
|
|
120
|
+
let cursor = 0, complete = count - pending.length;
|
|
121
|
+
const transfers = await Promise.allSettled(Array.from({ length: Math.min(3, pending.length) }, async () => {
|
|
122
|
+
while (cursor < pending.length) {
|
|
123
|
+
const part = pending[cursor++];
|
|
124
|
+
let succeeded = false;
|
|
125
|
+
for (let attempt = 0; attempt < 3 && !succeeded; attempt++) {
|
|
126
|
+
const { parts } = await control('POST', '/' + saved.uploadId + '/parts', { parts: [part] });
|
|
127
|
+
const grant = parts?.[0], url = new URL(grant?.url, base), local = state.transport === 'local';
|
|
128
|
+
if (url.protocol !== 'https:' && !(local && url.origin === base.origin) || url.username || url.password
|
|
129
|
+
|| local && url.origin !== base.origin || !local && !url.hostname.endsWith('.amazonaws.com'))
|
|
130
|
+
throw new Error('Invalid source upload destination');
|
|
131
|
+
const stream = createReadStream(archivePath, { start: (part.number - 1) * partSize, end: (part.number - 1) * partSize + part.size - 1 });
|
|
132
|
+
try {
|
|
133
|
+
const result = await fetch(url, { method: 'PUT', headers: { ...grant.headers, ...(local && session ? { authorization: 'Bearer ' + session.token } : {}) },
|
|
134
|
+
body: stream, duplex: 'half', redirect: 'error', signal: AbortSignal.timeout(10 * 60000) });
|
|
135
|
+
await result.body?.cancel();
|
|
136
|
+
succeeded = result.ok;
|
|
137
|
+
}
|
|
138
|
+
catch { /* Only the failed part is retried; capabilities never appear in errors. */ }
|
|
139
|
+
finally {
|
|
140
|
+
stream.destroy();
|
|
141
|
+
}
|
|
142
|
+
if (!succeeded && attempt < 2) {
|
|
143
|
+
console.error(`Retrying upload part ${part.number} (${attempt + 2}/3)`);
|
|
144
|
+
await pause(500 * 2 ** attempt);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (!succeeded)
|
|
148
|
+
throw new Error('Source transfer interrupted; rerun upload to resume');
|
|
149
|
+
console.error(`Uploaded ${++complete}/${count} parts`);
|
|
150
|
+
}
|
|
151
|
+
}));
|
|
152
|
+
const failure = transfers.find((result) => result.status === 'rejected');
|
|
153
|
+
if (failure)
|
|
154
|
+
throw failure.reason;
|
|
155
|
+
}
|
|
156
|
+
if (state.status !== 'ready') {
|
|
157
|
+
state = await control('POST', '/' + saved.uploadId + '/complete');
|
|
158
|
+
console.error('Source uploaded; validating');
|
|
159
|
+
const deadline = Date.now() + 15 * 60000;
|
|
160
|
+
while (!['ready', 'failed', 'cancelled', 'expired'].includes(state.status) && Date.now() < deadline) {
|
|
161
|
+
await pause(2000);
|
|
162
|
+
state = await control('GET', '/' + saved.uploadId);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (state.status !== 'ready')
|
|
166
|
+
throw new Error(state.error || 'Source validation is still pending; rerun upload to resume');
|
|
167
|
+
console.log(JSON.stringify(state.source));
|
|
168
|
+
await rm(filename, { force: true });
|
|
169
|
+
await rm(archivePath, { force: true });
|
|
170
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shoplifter/cli",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"shoplifterRuntimeVersion": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
|
+
"shoplifterRuntimeVersion": "0.1.2",
|
|
5
5
|
"private": false,
|
|
6
6
|
"license": "Apache-2.0",
|
|
7
7
|
"description": "Author, validate and publish independent Shoplifter Astro presentations",
|
|
@@ -26,11 +26,13 @@
|
|
|
26
26
|
"dependencies": {
|
|
27
27
|
"commander-ts": "0.2.0",
|
|
28
28
|
"ignore": "^7.0.14",
|
|
29
|
+
"tar-stream": "3.2.2",
|
|
29
30
|
"reflect-metadata": "^0.1.14",
|
|
30
|
-
"@shoplifter/presentation-contract": "0.1.
|
|
31
|
+
"@shoplifter/presentation-contract": "0.1.2"
|
|
31
32
|
},
|
|
32
33
|
"devDependencies": {
|
|
33
34
|
"@types/node": "^24.19.2",
|
|
35
|
+
"@types/tar-stream": "3.1.5",
|
|
34
36
|
"typescript": "5.8.2"
|
|
35
37
|
},
|
|
36
38
|
"scripts": {
|