@larkup/marketplace 0.1.25 → 0.2.1
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/.env +6 -0
- package/.env.example +3 -0
- package/.turbo/turbo-test.log +17 -0
- package/.turbo/turbo-type-check.log +4 -0
- package/CHANGELOG.md +183 -0
- package/README.md +34 -0
- package/db/dist/builtin-tools.d.ts +2 -0
- package/db/dist/builtin-tools.js +116 -0
- package/db/dist/client.d.ts +7 -0
- package/db/dist/client.js +20 -0
- package/db/dist/repo.d.ts +67 -0
- package/db/dist/repo.js +236 -0
- package/db/dist/schema/audit.d.ts +128 -0
- package/db/dist/schema/audit.js +18 -0
- package/db/dist/schema/extensions.d.ts +326 -0
- package/db/dist/schema/extensions.js +36 -0
- package/db/dist/schema/index.d.ts +5 -0
- package/db/dist/schema/index.js +5 -0
- package/db/dist/schema/installations.d.ts +93 -0
- package/db/dist/schema/installations.js +15 -0
- package/db/dist/schema/publishers.d.ts +110 -0
- package/db/dist/schema/publishers.js +12 -0
- package/db/dist/schema/versions.d.ts +127 -0
- package/db/dist/schema/versions.js +17 -0
- package/db/dist/seed.d.ts +2 -0
- package/db/dist/seed.js +31 -0
- package/db/dist/validate.d.ts +6 -0
- package/db/dist/validate.js +51 -0
- package/db/drizzle/0000_hesitant_joseph.sql +69 -0
- package/db/drizzle/0001_deep_phil_sheldon.sql +1 -0
- package/db/drizzle/0002_jittery_living_mummy.sql +18 -0
- package/db/drizzle/meta/0000_snapshot.json +483 -0
- package/db/drizzle/meta/0001_snapshot.json +490 -0
- package/db/drizzle/meta/0002_snapshot.json +615 -0
- package/db/drizzle/meta/_journal.json +27 -0
- package/db/drizzle.config.ts +19 -0
- package/db/tsconfig.build.json +11 -0
- package/db/tsconfig.json +17 -0
- package/db/vitest.config.ts +11 -0
- package/package.json +31 -4
- package/src/db/builtin-tools.ts +613 -0
- package/src/db/client.ts +26 -0
- package/src/db/repo.test.ts +309 -0
- package/src/db/repo.ts +558 -0
- package/src/db/schema/audit.ts +27 -0
- package/src/db/schema/extensions.ts +73 -0
- package/src/db/schema/index.ts +5 -0
- package/src/db/schema/installations.ts +23 -0
- package/src/db/schema/publishers.ts +13 -0
- package/src/db/schema/versions.ts +22 -0
- package/src/db/seed.ts +33 -0
- package/src/db/validate.test.ts +79 -0
- package/src/db/validate.ts +84 -0
- package/src/output-sanitizer.test.ts +17 -0
- package/src/output-sanitizer.ts +8 -0
- package/src/storage-provider-s3.test.ts +110 -0
- package/src/storage-provider.ts +164 -13
- package/src/tool-extension.ts +247 -0
- package/src/tool-installer.ts +80 -109
- package/src/tool-loader.test.ts +120 -0
- package/src/tool-loader.ts +99 -37
- package/src/tool-manifest.schema.ts +89 -32
- package/src/tool-registry.ts +34 -111
- package/src/types.ts +217 -87
- package/vitest.config.ts +13 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { index, jsonb, pgTable, text, timestamp, unique } from 'drizzle-orm/pg-core';
|
|
2
|
+
import { extensions } from './extensions.js';
|
|
3
|
+
|
|
4
|
+
/** Immutable published extension versions. */
|
|
5
|
+
export const extensionVersions = pgTable(
|
|
6
|
+
'extension_versions',
|
|
7
|
+
{
|
|
8
|
+
id: text('id').primaryKey(),
|
|
9
|
+
extensionId: text('extension_id')
|
|
10
|
+
.notNull()
|
|
11
|
+
.references(() => extensions.id),
|
|
12
|
+
version: text('version').notNull(),
|
|
13
|
+
manifest: jsonb('manifest').notNull(),
|
|
14
|
+
integrity: text('integrity').notNull(),
|
|
15
|
+
publishedBy: text('published_by').notNull(),
|
|
16
|
+
publishedAt: timestamp('published_at', { withTimezone: true }).notNull().defaultNow(),
|
|
17
|
+
},
|
|
18
|
+
(table) => [
|
|
19
|
+
unique('extension_versions_extension_version_unique').on(table.extensionId, table.version),
|
|
20
|
+
index('extension_versions_extension_id_idx').on(table.extensionId),
|
|
21
|
+
],
|
|
22
|
+
);
|
package/src/db/seed.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Seeds built-in Marketplace tools. */
|
|
2
|
+
|
|
3
|
+
import 'dotenv/config';
|
|
4
|
+
import { BUILTIN_TOOLS } from './builtin-tools.js';
|
|
5
|
+
import { getMarketplaceDb } from './client.js';
|
|
6
|
+
import { publishExtension, VersionExistsError } from './repo.js';
|
|
7
|
+
|
|
8
|
+
async function main() {
|
|
9
|
+
const db = getMarketplaceDb();
|
|
10
|
+
for (const manifest of BUILTIN_TOOLS) {
|
|
11
|
+
try {
|
|
12
|
+
await publishExtension(db, {
|
|
13
|
+
manifest,
|
|
14
|
+
publisherId: 'larkup',
|
|
15
|
+
publisherName: 'Larkup',
|
|
16
|
+
});
|
|
17
|
+
console.log(`seeded ${manifest.id}@${manifest.version}`);
|
|
18
|
+
} catch (err) {
|
|
19
|
+
if (err instanceof VersionExistsError) {
|
|
20
|
+
console.log(`already seeded: ${manifest.id}@${manifest.version}`);
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
throw err;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
main()
|
|
29
|
+
.then(() => process.exit(0))
|
|
30
|
+
.catch((err) => {
|
|
31
|
+
console.error(err);
|
|
32
|
+
process.exit(1);
|
|
33
|
+
});
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { validateToolManifest } from './validate';
|
|
3
|
+
|
|
4
|
+
const VALID = {
|
|
5
|
+
id: 'my-tool',
|
|
6
|
+
name: 'My Tool',
|
|
7
|
+
description: 'Does a thing.',
|
|
8
|
+
category: 'utility',
|
|
9
|
+
version: '1.0.0',
|
|
10
|
+
pricing: 'free',
|
|
11
|
+
icon: 'Wrench',
|
|
12
|
+
packageName: '@acme/my-tool',
|
|
13
|
+
installSize: '~1 MB',
|
|
14
|
+
author: 'Acme',
|
|
15
|
+
capabilities: ['does-a-thing'],
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
describe('validateToolManifest', () => {
|
|
19
|
+
it('accepts a complete, well-formed manifest', () => {
|
|
20
|
+
expect(validateToolManifest(VALID)).toEqual({ valid: true, errors: [] });
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('rejects a non-object', () => {
|
|
24
|
+
expect(validateToolManifest(null).valid).toBe(false);
|
|
25
|
+
expect(validateToolManifest('nope').valid).toBe(false);
|
|
26
|
+
expect(validateToolManifest(undefined).valid).toBe(false);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('rejects a missing required string field', () => {
|
|
30
|
+
const { valid, errors } = validateToolManifest({ ...VALID, name: undefined });
|
|
31
|
+
expect(valid).toBe(false);
|
|
32
|
+
expect(errors).toContain('"name" is required');
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('rejects an id with uppercase or invalid characters', () => {
|
|
36
|
+
expect(validateToolManifest({ ...VALID, id: 'My_Tool' }).valid).toBe(false);
|
|
37
|
+
expect(validateToolManifest({ ...VALID, id: '-leading-hyphen' }).valid).toBe(false);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it('rejects an unknown category', () => {
|
|
41
|
+
const { valid, errors } = validateToolManifest({ ...VALID, category: 'not-a-category' });
|
|
42
|
+
expect(valid).toBe(false);
|
|
43
|
+
expect(errors.some((e) => e.includes('category'))).toBe(true);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('rejects an unknown pricing tier', () => {
|
|
47
|
+
expect(validateToolManifest({ ...VALID, pricing: 'gold' }).valid).toBe(false);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('rejects a non-semver version', () => {
|
|
51
|
+
expect(validateToolManifest({ ...VALID, version: 'v1' }).valid).toBe(false);
|
|
52
|
+
expect(validateToolManifest({ ...VALID, version: '1.0' }).valid).toBe(false);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('accepts a semver version with a prerelease/build suffix', () => {
|
|
56
|
+
expect(validateToolManifest({ ...VALID, version: '1.0.0-beta.1' }).valid).toBe(true);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it('rejects an empty capabilities array', () => {
|
|
60
|
+
const { valid, errors } = validateToolManifest({ ...VALID, capabilities: [] });
|
|
61
|
+
expect(valid).toBe(false);
|
|
62
|
+
expect(errors.some((e) => e.includes('capabilities'))).toBe(true);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('allows an explicit sandbox opt-out but rejects a malformed value', () => {
|
|
66
|
+
expect(validateToolManifest({ ...VALID, requiresSandbox: false }).valid).toBe(true);
|
|
67
|
+
expect(validateToolManifest({ ...VALID, requiresSandbox: 'no' }).valid).toBe(false);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it('accepts public/private distribution and rejects another value', () => {
|
|
71
|
+
expect(validateToolManifest({ ...VALID, distribution: 'private' }).valid).toBe(true);
|
|
72
|
+
expect(validateToolManifest({ ...VALID, distribution: 'unlisted' }).valid).toBe(false);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('collects every violation in one pass rather than stopping at the first', () => {
|
|
76
|
+
const { errors } = validateToolManifest({});
|
|
77
|
+
expect(errors.length).toBeGreaterThan(3);
|
|
78
|
+
});
|
|
79
|
+
});
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/** Validates Marketplace tool manifests. */
|
|
2
|
+
|
|
3
|
+
export interface ManifestValidationResult {
|
|
4
|
+
valid: boolean;
|
|
5
|
+
errors: string[];
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
const ID_PATTERN = /^[a-z0-9][a-z0-9-]*[a-z0-9]$/;
|
|
9
|
+
const VERSION_PATTERN = /^\d+\.\d+\.\d+/;
|
|
10
|
+
const CATEGORIES = [
|
|
11
|
+
'media',
|
|
12
|
+
'search',
|
|
13
|
+
'analytics',
|
|
14
|
+
'integration',
|
|
15
|
+
'embedding',
|
|
16
|
+
'ai',
|
|
17
|
+
'automation',
|
|
18
|
+
'utility',
|
|
19
|
+
] as const;
|
|
20
|
+
const PRICING = ['free', 'pro', 'enterprise'] as const;
|
|
21
|
+
const DISTRIBUTIONS = ['public', 'private'] as const;
|
|
22
|
+
|
|
23
|
+
export function validateToolManifest(manifest: unknown): ManifestValidationResult {
|
|
24
|
+
const errors: string[] = [];
|
|
25
|
+
if (!manifest || typeof manifest !== 'object') {
|
|
26
|
+
return { valid: false, errors: ['manifest must be an object'] };
|
|
27
|
+
}
|
|
28
|
+
const m = manifest as Record<string, unknown>;
|
|
29
|
+
|
|
30
|
+
const requireString = (key: string) => {
|
|
31
|
+
if (typeof m[key] !== 'string' || !m[key]) errors.push(`"${key}" is required`);
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
requireString('id');
|
|
35
|
+
if (typeof m.id === 'string' && !ID_PATTERN.test(m.id)) {
|
|
36
|
+
errors.push('"id" must be lowercase alphanumeric with hyphens, e.g. "video-audio"');
|
|
37
|
+
}
|
|
38
|
+
requireString('name');
|
|
39
|
+
requireString('description');
|
|
40
|
+
requireString('icon');
|
|
41
|
+
requireString('packageName');
|
|
42
|
+
requireString('installSize');
|
|
43
|
+
requireString('author');
|
|
44
|
+
|
|
45
|
+
if (typeof m.category !== 'string' || !CATEGORIES.includes(m.category as any)) {
|
|
46
|
+
errors.push(`"category" must be one of: ${CATEGORIES.join(', ')}`);
|
|
47
|
+
}
|
|
48
|
+
if (typeof m.pricing !== 'string' || !PRICING.includes(m.pricing as any)) {
|
|
49
|
+
errors.push(`"pricing" must be one of: ${PRICING.join(', ')}`);
|
|
50
|
+
}
|
|
51
|
+
if (m.distribution !== undefined && !DISTRIBUTIONS.includes(m.distribution as any)) {
|
|
52
|
+
errors.push('"distribution" must be "public" or "private" when provided');
|
|
53
|
+
}
|
|
54
|
+
if (typeof m.version !== 'string' || !VERSION_PATTERN.test(m.version)) {
|
|
55
|
+
errors.push('"version" must be semver, e.g. "1.0.0"');
|
|
56
|
+
}
|
|
57
|
+
if (!Array.isArray(m.capabilities) || m.capabilities.length === 0) {
|
|
58
|
+
errors.push('"capabilities" must be a non-empty array');
|
|
59
|
+
}
|
|
60
|
+
if (m.requiresSandbox !== undefined && typeof m.requiresSandbox !== 'boolean') {
|
|
61
|
+
errors.push('"requiresSandbox" must be a boolean when provided');
|
|
62
|
+
}
|
|
63
|
+
if (m.manifestVersion === '3.0') {
|
|
64
|
+
const entrypoints = m.entrypoints as Record<string, unknown> | undefined;
|
|
65
|
+
const runtime = m.runtime as Record<string, unknown> | undefined;
|
|
66
|
+
if (m.kind !== 'tool') errors.push('v3 manifests must set "kind" to "tool"');
|
|
67
|
+
if (!entrypoints || typeof entrypoints.server !== 'string') {
|
|
68
|
+
errors.push('v3 manifests must declare "entrypoints.server"');
|
|
69
|
+
}
|
|
70
|
+
if (
|
|
71
|
+
!runtime ||
|
|
72
|
+
typeof runtime.protocolVersion !== 'string' ||
|
|
73
|
+
typeof runtime.defaultMode !== 'string' ||
|
|
74
|
+
!Array.isArray(runtime.modes) ||
|
|
75
|
+
runtime.modes.length === 0
|
|
76
|
+
) {
|
|
77
|
+
errors.push(
|
|
78
|
+
'v3 manifests must declare runtime.protocolVersion, runtime.defaultMode, and runtime.modes',
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return { valid: errors.length === 0, errors };
|
|
84
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { sanitizeGeneratedOutput } from './output-sanitizer';
|
|
3
|
+
|
|
4
|
+
describe('sanitizeGeneratedOutput', () => {
|
|
5
|
+
it('removes hidden reasoning blocks and keeps final tool output', () => {
|
|
6
|
+
expect(
|
|
7
|
+
sanitizeGeneratedOutput(
|
|
8
|
+
'<think>private chain of thought</think>\n## Overview\n[0:00–0:03] LARKUP VIDEO 2026.',
|
|
9
|
+
),
|
|
10
|
+
).toBe('## Overview\n[0:00–0:03] LARKUP VIDEO 2026.');
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
it('removes stray provider reasoning tags', () => {
|
|
14
|
+
expect(sanitizeGeneratedOutput('<analysis>Visible evidence only</analysis>')).toBe('');
|
|
15
|
+
expect(sanitizeGeneratedOutput('<reasoning>\nFinal notes')).toBe('Final notes');
|
|
16
|
+
});
|
|
17
|
+
});
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Removes provider-specific hidden reasoning before tool output reaches storage or retrieval. */
|
|
2
|
+
export function sanitizeGeneratedOutput(text: string): string {
|
|
3
|
+
let sanitized = text;
|
|
4
|
+
for (const tag of ['think', 'analysis', 'reasoning']) {
|
|
5
|
+
sanitized = sanitized.replace(new RegExp(`<${tag}\\b[^>]*>[\\s\\S]*?<\\/${tag}>`, 'gi'), '');
|
|
6
|
+
}
|
|
7
|
+
return sanitized.replace(/<\/?(?:think|analysis|reasoning)\b[^>]*>/gi, '').trim();
|
|
8
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
const sendMock = vi.fn();
|
|
4
|
+
const getSignedUrlMock = vi.fn();
|
|
5
|
+
|
|
6
|
+
vi.mock('@aws-sdk/client-s3', () => {
|
|
7
|
+
class S3Client {
|
|
8
|
+
send = sendMock;
|
|
9
|
+
}
|
|
10
|
+
class PutObjectCommand {
|
|
11
|
+
input: any;
|
|
12
|
+
constructor(input: any) {
|
|
13
|
+
this.input = input;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
class GetObjectCommand {
|
|
17
|
+
input: any;
|
|
18
|
+
constructor(input: any) {
|
|
19
|
+
this.input = input;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
class DeleteObjectCommand {
|
|
23
|
+
input: any;
|
|
24
|
+
constructor(input: any) {
|
|
25
|
+
this.input = input;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return { S3Client, PutObjectCommand, GetObjectCommand, DeleteObjectCommand };
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
vi.mock('@aws-sdk/s3-request-presigner', () => ({
|
|
32
|
+
getSignedUrl: getSignedUrlMock,
|
|
33
|
+
}));
|
|
34
|
+
|
|
35
|
+
import { S3StorageProvider } from './storage-provider';
|
|
36
|
+
|
|
37
|
+
describe('S3StorageProvider', () => {
|
|
38
|
+
beforeEach(() => {
|
|
39
|
+
sendMock.mockReset();
|
|
40
|
+
getSignedUrlMock.mockReset();
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('stores an object under the canonical prefix, KMS-encrypted, and returns an s3:// uri', async () => {
|
|
44
|
+
sendMock.mockResolvedValueOnce({});
|
|
45
|
+
const provider = new S3StorageProvider({ bucket: 'my-bucket', kmsKeyId: 'arn:aws:kms:1' });
|
|
46
|
+
const uri = await provider.store('videos/a.mp4', Buffer.from('data'), 'video/mp4');
|
|
47
|
+
expect(uri).toBe('s3://my-bucket/canonical/videos/a.mp4');
|
|
48
|
+
const sentCommand = sendMock.mock.calls[0][0];
|
|
49
|
+
expect(sentCommand.input).toMatchObject({
|
|
50
|
+
Bucket: 'my-bucket',
|
|
51
|
+
Key: 'canonical/videos/a.mp4',
|
|
52
|
+
ContentType: 'video/mp4',
|
|
53
|
+
ServerSideEncryption: 'aws:kms',
|
|
54
|
+
SSEKMSKeyId: 'arn:aws:kms:1',
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('uses a custom prefix when configured', async () => {
|
|
59
|
+
sendMock.mockResolvedValueOnce({});
|
|
60
|
+
const provider = new S3StorageProvider({ bucket: 'b', prefix: 'tmp' });
|
|
61
|
+
const uri = await provider.store('x.mp4', Buffer.from('d'), 'video/mp4');
|
|
62
|
+
expect(uri).toBe('s3://b/tmp/x.mp4');
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('retrieve() streams and concatenates the object body', async () => {
|
|
66
|
+
const chunks = [Buffer.from('hel'), Buffer.from('lo')];
|
|
67
|
+
sendMock.mockResolvedValueOnce({
|
|
68
|
+
Body: (async function* () {
|
|
69
|
+
for (const chunk of chunks) yield chunk;
|
|
70
|
+
})(),
|
|
71
|
+
});
|
|
72
|
+
const provider = new S3StorageProvider({ bucket: 'my-bucket' });
|
|
73
|
+
const data = await provider.retrieve('s3://my-bucket/canonical/videos/a.mp4');
|
|
74
|
+
expect(data.toString('utf-8')).toBe('hello');
|
|
75
|
+
expect(sendMock.mock.calls[0][0].input).toMatchObject({
|
|
76
|
+
Bucket: 'my-bucket',
|
|
77
|
+
Key: 'canonical/videos/a.mp4',
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('retrieve() rejects a non-s3 uri', async () => {
|
|
82
|
+
const provider = new S3StorageProvider({ bucket: 'b' });
|
|
83
|
+
await expect(provider.retrieve('local://x.mp4')).rejects.toThrow(/Unsupported S3 storage URI/);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('resolvePath always returns undefined, forcing callers to a remote path', async () => {
|
|
87
|
+
const provider = new S3StorageProvider({ bucket: 'b' });
|
|
88
|
+
await expect(provider.resolvePath('s3://b/canonical/x.mp4')).resolves.toBeUndefined();
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it('getReadUrl produces a presigned GET url scoped to the parsed bucket/key', async () => {
|
|
92
|
+
getSignedUrlMock.mockResolvedValueOnce('https://signed.example/x.mp4?sig=1');
|
|
93
|
+
const provider = new S3StorageProvider({ bucket: 'my-bucket' });
|
|
94
|
+
const url = await provider.getReadUrl('s3://my-bucket/canonical/videos/a.mp4', 3600);
|
|
95
|
+
expect(url).toBe('https://signed.example/x.mp4?sig=1');
|
|
96
|
+
const [, command, options] = getSignedUrlMock.mock.calls[0];
|
|
97
|
+
expect(command.input).toMatchObject({ Bucket: 'my-bucket', Key: 'canonical/videos/a.mp4' });
|
|
98
|
+
expect(options).toEqual({ expiresIn: 3600 });
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('delete() swallows a failure instead of throwing (object may already be gone)', async () => {
|
|
102
|
+
sendMock.mockRejectedValueOnce(new Error('NoSuchKey'));
|
|
103
|
+
const provider = new S3StorageProvider({ bucket: 'b' });
|
|
104
|
+
await expect(provider.delete('s3://b/canonical/gone.mp4')).resolves.toBeUndefined();
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it('constructor requires a bucket name', () => {
|
|
108
|
+
expect(() => new S3StorageProvider({ bucket: '' })).toThrow(/requires a bucket name/);
|
|
109
|
+
});
|
|
110
|
+
});
|
package/src/storage-provider.ts
CHANGED
|
@@ -2,12 +2,12 @@ import { promises as fs } from 'node:fs';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import type { StorageProvider, StorageStats } from './types';
|
|
4
4
|
import { STORAGE_WARNING_THRESHOLDS } from './types';
|
|
5
|
-
import {
|
|
5
|
+
import { requireProjectDataDir } from '@larkup/core/project-store';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* Local file-based storage provider for media assets.
|
|
9
9
|
*
|
|
10
|
-
* Stores files under `.larkup/
|
|
10
|
+
* Stores files under `.larkup/projects/<activeProject>/media/`.
|
|
11
11
|
* Designed to be swappable with cloud providers (S3, UploadThing, GCS)
|
|
12
12
|
* in the future via the StorageProvider interface.
|
|
13
13
|
*/
|
|
@@ -17,7 +17,7 @@ export class LocalStorageProvider implements StorageProvider {
|
|
|
17
17
|
readonly name = 'Local Storage';
|
|
18
18
|
|
|
19
19
|
private async mediaDir(): Promise<string> {
|
|
20
|
-
const dataDir = await
|
|
20
|
+
const dataDir = await requireProjectDataDir();
|
|
21
21
|
const dir = path.join(dataDir, 'media');
|
|
22
22
|
await fs.mkdir(dir, { recursive: true });
|
|
23
23
|
return dir;
|
|
@@ -78,10 +78,6 @@ export class LocalStorageProvider implements StorageProvider {
|
|
|
78
78
|
}
|
|
79
79
|
}
|
|
80
80
|
|
|
81
|
-
/* ------------------------------------------------------------------ */
|
|
82
|
-
/* Helpers */
|
|
83
|
-
/* ------------------------------------------------------------------ */
|
|
84
|
-
|
|
85
81
|
async function computeDirStats(dir: string): Promise<StorageStats> {
|
|
86
82
|
let usedBytes = 0;
|
|
87
83
|
let fileCount = 0;
|
|
@@ -102,9 +98,7 @@ async function computeDirStats(dir: string): Promise<StorageStats> {
|
|
|
102
98
|
const stat = await fs.stat(full);
|
|
103
99
|
usedBytes += stat.size;
|
|
104
100
|
fileCount++;
|
|
105
|
-
} catch {
|
|
106
|
-
// skip
|
|
107
|
-
}
|
|
101
|
+
} catch {}
|
|
108
102
|
}
|
|
109
103
|
}
|
|
110
104
|
}
|
|
@@ -136,12 +130,169 @@ export function getStorageWarningLevel(usedBytes: number): number | null {
|
|
|
136
130
|
return null;
|
|
137
131
|
}
|
|
138
132
|
|
|
133
|
+
/**
|
|
134
|
+
* S3-backed storage provider for durable canonical media (video sources that
|
|
135
|
+
* watch_original must be able to re-inspect at any point, not just at
|
|
136
|
+
* indexing time).
|
|
137
|
+
*
|
|
138
|
+
* Every object is written under a `canonical/` key prefix and encrypted with
|
|
139
|
+
* the configured KMS key. `canonical/` is deliberately kept out of the
|
|
140
|
+
* short-lived processing bucket's `sources/`/`results/` lifecycle rules (see
|
|
141
|
+
* deploy/aws/template.yaml) so a canonical source's retention is governed
|
|
142
|
+
* only by retainSourceHours-driven explicit deletion, never a bucket-wide
|
|
143
|
+
* expiration policy.
|
|
144
|
+
*/
|
|
145
|
+
export class S3StorageProvider implements StorageProvider {
|
|
146
|
+
readonly id = 's3';
|
|
147
|
+
readonly name = 'Amazon S3';
|
|
148
|
+
|
|
149
|
+
private readonly bucket: string;
|
|
150
|
+
private readonly region: string;
|
|
151
|
+
private readonly kmsKeyId?: string;
|
|
152
|
+
private readonly prefix: string;
|
|
153
|
+
private _client: any;
|
|
154
|
+
private _credentials: { accessKeyId: string; secretAccessKey: string } | undefined;
|
|
155
|
+
|
|
156
|
+
constructor(config: {
|
|
157
|
+
bucket: string;
|
|
158
|
+
region?: string;
|
|
159
|
+
kmsKeyId?: string;
|
|
160
|
+
prefix?: string;
|
|
161
|
+
accessKeyId?: string;
|
|
162
|
+
secretAccessKey?: string;
|
|
163
|
+
}) {
|
|
164
|
+
if (!config.bucket) throw new Error('S3StorageProvider requires a bucket name.');
|
|
165
|
+
this.bucket = config.bucket;
|
|
166
|
+
this.region = config.region || process.env.AWS_REGION || 'us-east-1';
|
|
167
|
+
this.kmsKeyId = config.kmsKeyId;
|
|
168
|
+
this.prefix = (config.prefix ?? 'canonical').replace(/^\/+|\/+$/g, '');
|
|
169
|
+
this._credentials =
|
|
170
|
+
config.accessKeyId && config.secretAccessKey
|
|
171
|
+
? { accessKeyId: config.accessKeyId, secretAccessKey: config.secretAccessKey }
|
|
172
|
+
: undefined;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
private async client(): Promise<any> {
|
|
176
|
+
if (!this._client) {
|
|
177
|
+
const { S3Client } = await import('@aws-sdk/client-s3');
|
|
178
|
+
this._client = new S3Client({
|
|
179
|
+
region: this.region,
|
|
180
|
+
...(this._credentials ? { credentials: this._credentials } : {}),
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
return this._client;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
private objectKey(key: string): string {
|
|
187
|
+
return `${this.prefix}/${key}`;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
private parseUri(uri: string): { bucket: string; key: string } {
|
|
191
|
+
if (!uri.startsWith('s3://')) throw new Error(`Unsupported S3 storage URI: ${uri}`);
|
|
192
|
+
const withoutScheme = uri.slice('s3://'.length);
|
|
193
|
+
const slashIndex = withoutScheme.indexOf('/');
|
|
194
|
+
if (slashIndex < 0) throw new Error(`Malformed S3 storage URI: ${uri}`);
|
|
195
|
+
return { bucket: withoutScheme.slice(0, slashIndex), key: withoutScheme.slice(slashIndex + 1) };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async store(key: string, data: Buffer, mimeType: string): Promise<string> {
|
|
199
|
+
const { PutObjectCommand } = await import('@aws-sdk/client-s3');
|
|
200
|
+
const client = await this.client();
|
|
201
|
+
const objectKey = this.objectKey(key);
|
|
202
|
+
await client.send(
|
|
203
|
+
new PutObjectCommand({
|
|
204
|
+
Bucket: this.bucket,
|
|
205
|
+
Key: objectKey,
|
|
206
|
+
Body: data,
|
|
207
|
+
ContentType: mimeType,
|
|
208
|
+
...(this.kmsKeyId
|
|
209
|
+
? { ServerSideEncryption: 'aws:kms', SSEKMSKeyId: this.kmsKeyId }
|
|
210
|
+
: { ServerSideEncryption: 'aws:kms' }),
|
|
211
|
+
}),
|
|
212
|
+
);
|
|
213
|
+
return `s3://${this.bucket}/${objectKey}`;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async storeFile(key: string, sourcePath: string, mimeType: string): Promise<string> {
|
|
217
|
+
return this.store(key, await fs.readFile(sourcePath), mimeType);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async retrieve(uri: string): Promise<Buffer> {
|
|
221
|
+
const { GetObjectCommand } = await import('@aws-sdk/client-s3');
|
|
222
|
+
const { bucket, key } = this.parseUri(uri);
|
|
223
|
+
const client = await this.client();
|
|
224
|
+
const response = await client.send(new GetObjectCommand({ Bucket: bucket, Key: key }));
|
|
225
|
+
const chunks: Uint8Array[] = [];
|
|
226
|
+
for await (const chunk of response.Body as AsyncIterable<Uint8Array>) {
|
|
227
|
+
chunks.push(chunk);
|
|
228
|
+
}
|
|
229
|
+
return Buffer.concat(chunks);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Never local: every call site that checks resolvePath?.() already falls
|
|
233
|
+
// back to retrieve()/getReadUrl() for a non-local provider.
|
|
234
|
+
async resolvePath(_uri: string): Promise<string | undefined> {
|
|
235
|
+
return undefined;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async getReadUrl(uri: string, expiresInSecs: number): Promise<string | undefined> {
|
|
239
|
+
const { GetObjectCommand } = await import('@aws-sdk/client-s3');
|
|
240
|
+
const { getSignedUrl } = await import('@aws-sdk/s3-request-presigner');
|
|
241
|
+
const { bucket, key } = this.parseUri(uri);
|
|
242
|
+
const client = await this.client();
|
|
243
|
+
return getSignedUrl(client, new GetObjectCommand({ Bucket: bucket, Key: key }), {
|
|
244
|
+
expiresIn: expiresInSecs,
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async delete(uri: string): Promise<void> {
|
|
249
|
+
const { DeleteObjectCommand } = await import('@aws-sdk/client-s3');
|
|
250
|
+
const { bucket, key } = this.parseUri(uri);
|
|
251
|
+
const client = await this.client();
|
|
252
|
+
try {
|
|
253
|
+
await client.send(new DeleteObjectCommand({ Bucket: bucket, Key: key }));
|
|
254
|
+
} catch {
|
|
255
|
+
// Object may already be deleted.
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async stats(): Promise<StorageStats> {
|
|
260
|
+
// S3 has no cheap aggregate byte count without a full ListObjects scan
|
|
261
|
+
// or S3 Storage Lens; the storage-usage UI is a local-disk concept only.
|
|
262
|
+
return { usedBytes: 0, fileCount: 0 };
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
139
266
|
/**
|
|
140
267
|
* Factory: create the appropriate storage provider from config.
|
|
141
|
-
*
|
|
142
|
-
*
|
|
268
|
+
*
|
|
269
|
+
* Env-driven so it can change without a code change: set
|
|
270
|
+
* LARKUP_MEDIA_STORAGE=s3 with LARKUP_MEDIA_S3_BUCKET (and optionally
|
|
271
|
+
* LARKUP_MEDIA_S3_REGION / LARKUP_MEDIA_S3_KMS_KEY_ID / a scoped
|
|
272
|
+
* LARKUP_MEDIA_S3_ACCESS_KEY_ID+SECRET) to store canonical media in S3
|
|
273
|
+
* instead of local disk. Falls back to LocalStorageProvider otherwise.
|
|
143
274
|
*/
|
|
144
275
|
export function createStorageProvider(_config?: Record<string, any>): StorageProvider {
|
|
145
|
-
|
|
276
|
+
const provider = (_config?.provider ?? process.env.LARKUP_MEDIA_STORAGE ?? 'local').toLowerCase();
|
|
277
|
+
if (provider === 's3') {
|
|
278
|
+
const bucket = _config?.bucket ?? process.env.LARKUP_MEDIA_S3_BUCKET;
|
|
279
|
+
if (!bucket) {
|
|
280
|
+
throw new Error('LARKUP_MEDIA_STORAGE=s3 requires LARKUP_MEDIA_S3_BUCKET to be set.');
|
|
281
|
+
}
|
|
282
|
+
return new S3StorageProvider({
|
|
283
|
+
bucket,
|
|
284
|
+
region: _config?.region ?? process.env.LARKUP_MEDIA_S3_REGION,
|
|
285
|
+
kmsKeyId: _config?.kmsKeyId ?? process.env.LARKUP_MEDIA_S3_KMS_KEY_ID,
|
|
286
|
+
prefix: _config?.prefix ?? process.env.LARKUP_MEDIA_S3_PREFIX,
|
|
287
|
+
accessKeyId:
|
|
288
|
+
_config?.accessKeyId ??
|
|
289
|
+
process.env.LARKUP_MEDIA_S3_ACCESS_KEY_ID ??
|
|
290
|
+
process.env.AWS_ACCESS_KEY_ID,
|
|
291
|
+
secretAccessKey:
|
|
292
|
+
_config?.secretAccessKey ??
|
|
293
|
+
process.env.LARKUP_MEDIA_S3_SECRET_ACCESS_KEY ??
|
|
294
|
+
process.env.AWS_SECRET_ACCESS_KEY,
|
|
295
|
+
});
|
|
296
|
+
}
|
|
146
297
|
return new LocalStorageProvider();
|
|
147
298
|
}
|