All files / lib/metadata imports.ts

100% Statements 24/24
100% Branches 11/11
100% Functions 7/7
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283          1x                       11x 4x     7x 6x     6x 6x     8x   7x 7x 1x     6x   1x     5x   7x 1x     4x 4x 4x       4x   4x               6x                                                                                                                                                                                                                                                                                                                                                                                                                                                      
import type { DatabaseHandle } from '$lib/idb.svelte.js';
import type { NamespacedMetadataID } from '$lib/schemas/common.js';
import { namespaceOfMetadataId } from '$lib/schemas/metadata.js';
import { ExportedProtocol, ProtocolRegistry } from '$lib/schemas/protocols.js';
 
let PROTOCOLS_REGISTRY: typeof ProtocolRegistry.infer | null = null;
 
/**
 * Downloads (recursively) all the protocols needed to import the given protocol
 */
export async function resolveProtocolImports(
	db: DatabaseHandle,
	protocolId: string,
	imports: (typeof ExportedProtocol.inferOut)['importedMetadata'],
	/** Resolved imports  */
	resolved = new Map<string, typeof ExportedProtocol.infer>()
): Promise<(typeof ExportedProtocol.infer)[]> {
	if (imports.length === 0) {
		return [];
	}
 
	if (!PROTOCOLS_REGISTRY) {
		PROTOCOLS_REGISTRY = await fetch(
			'https://raw.githubusercontent.com/cigaleapp/cigale/main/protocols/registry.json'
		)
			.then((res) => res.json())
			.then((data) => ProtocolRegistry.assert(data));
	}
 
	const importedProtocolIds = new Set(imports.map((imp) => namespaceOfMetadataId(imp.source)));
 
	for (const from of importedProtocolIds) {
		if (resolved.has(from)) {
			continue;
		}
 
		if (await db.get('Protocol', from)) {
			// Protocol already in the database, we can skip it
			continue;
		}
 
		const registryEntry = PROTOCOLS_REGISTRY?.protocols.find((entry) => entry.id === from);
 
		if (!registryEntry) {
			throw new Error(`Protocol ${protocolId} inherits from unknown protocol ${from}`);
		}
 
		const parentProtocol = await fetch(registryEntry.url)
			.then((res) => res.json())
			.then((data) => ExportedProtocol.assert(data));
 
		// TODO resolve parentProtocol.importedMetadata in case there's a >2-depth import. We can also detect import cycles there
 
		resolved.set(from, parentProtocol);
 
		await resolveProtocolImports(
			db,
			parentProtocol.id,
			parentProtocol.importedMetadata,
			resolved
		);
	}
 
	return [...resolved.values()];
}
 
if (import.meta.vitest) {
	const { test, expect, describe, beforeEach, vi } = import.meta.vitest;
 
	/** Helper to create a mock DatabaseHandle with a configurable `get` */
	function mockDb(existing: Record<string, Record<string, unknown>> = {}) {
		return {
			get: vi.fn(async (store: string, key: string) => existing[store]?.[key] ?? undefined)
		} as unknown as DatabaseHandle;
	}
 
	/** Helper to build an importedMetadata entry */
	function imp(source: NamespacedMetadataID, target: NamespacedMetadataID, sessionwide = false) {
		return { source, target, sessionwide };
	}
 
	/**
	 * Minimal fake exported protocol input (shape that passes ExportedProtocol.assert).
	 * `imports` uses the ExportedProtocol input format: `{ from, metadata, sessionMetadata }`.
	 */
	function fakeExportedProtocol(
		id: string,
		imports: { from: string; metadata: string[]; sessionMetadata?: string[] }[] = []
	) {
		return {
			id,
			name: `Protocol ${id}`,
			description: `Description of ${id}`,
			authors: [{ name: 'Test Author' }],
			metadata: {},
			imports: imports.map(({ from, metadata, sessionMetadata }) => ({
				from,
				metadata: metadata,
				sessionMetadata: sessionMetadata ?? []
			}))
		};
	}
 
	describe('resolveProtocolImports', () => {
		beforeEach(() => {
			// Reset module-level cache
			PROTOCOLS_REGISTRY = null;
			vi.restoreAllMocks();
		});
 
		test('returns empty array when imports is empty', async () => {
			const result = await resolveProtocolImports(mockDb(), 'my-protocol', []);
			expect(result).toEqual([]);
		});
 
		test('fetches registry and resolves a single import', async () => {
			const parentInput = fakeExportedProtocol('parent-protocol');
 
			vi.stubGlobal(
				'fetch',
				vi.fn(async (url: string) => ({
					json: async () => {
						if (url.includes('registry.json')) {
							return {
								protocols: [
									{
										id: 'parent-protocol',
										url: 'https://example.com/parent.json'
									}
								]
							};
						}
						return parentInput;
					}
				}))
			);
 
			const result = await resolveProtocolImports(mockDb(), 'my-protocol', [
				imp('parent-protocol__field1', 'my-protocol__field1')
			]);
 
			expect(result).toHaveLength(1);
			expect(result[0].id).toBe('parent-protocol');
		});
 
		test('skips protocols already resolved', async () => {
			const alreadyResolved = new Map([
				['parent-protocol', { id: 'parent-protocol' } as typeof ExportedProtocol.infer]
			]);
 
			vi.stubGlobal(
				'fetch',
				vi.fn(async () => ({
					json: async () => ({
						protocols: [
							{ id: 'parent-protocol', url: 'https://example.com/parent.json' }
						]
					})
				}))
			);
 
			const result = await resolveProtocolImports(
				mockDb(),
				'my-protocol',
				[imp('parent-protocol__field1', 'my-protocol__field1')],
				alreadyResolved
			);
 
			expect(result).toHaveLength(1);
			expect(result[0].id).toBe('parent-protocol');
			// fetch should only have been called once (for the registry), not for the protocol itself
			expect(vi.mocked(fetch)).toHaveBeenCalledTimes(1);
		});
 
		test('skips protocols already in the database', async () => {
			vi.stubGlobal(
				'fetch',
				vi.fn(async () => ({
					json: async () => ({
						protocols: [
							{ id: 'parent-protocol', url: 'https://example.com/parent.json' }
						]
					})
				}))
			);
 
			const db = mockDb({ Protocol: { 'parent-protocol': { id: 'parent-protocol' } } });
 
			const result = await resolveProtocolImports(db, 'my-protocol', [
				imp('parent-protocol__field1', 'my-protocol__field1')
			]);
 
			expect(result).toEqual([]);
			expect(db.get).toHaveBeenCalledWith('Protocol', 'parent-protocol');
		});
 
		test('throws for unknown protocol in registry', async () => {
			vi.stubGlobal(
				'fetch',
				vi.fn(async () => ({
					json: async () => ({ protocols: [] }) // empty registry
				}))
			);
 
			await expect(
				resolveProtocolImports(mockDb(), 'my-protocol', [
					imp('unknown-protocol__field1', 'my-protocol__field1')
				])
			).rejects.toThrow('inherits from unknown protocol unknown-protocol');
		});
 
		test('deduplicates imports from the same protocol', async () => {
			const parentInput = fakeExportedProtocol('parent-protocol');
 
			vi.stubGlobal(
				'fetch',
				vi.fn(async (url: string) => ({
					json: async () => {
						if (url.includes('registry.json')) {
							return {
								protocols: [
									{
										id: 'parent-protocol',
										url: 'https://example.com/parent.json'
									}
								]
							};
						}
						return parentInput;
					}
				}))
			);
 
			const result = await resolveProtocolImports(mockDb(), 'my-protocol', [
				imp('parent-protocol__field1', 'my-protocol__field1'),
				imp('parent-protocol__field2', 'my-protocol__field2')
			]);
 
			expect(result).toHaveLength(1);
			// registry fetch + one protocol fetch = 2 calls total
			expect(vi.mocked(fetch)).toHaveBeenCalledTimes(2);
		});
 
		test('resolves recursive imports', async () => {
			const grandparentInput = fakeExportedProtocol('grandparent');
			const parentInput = fakeExportedProtocol('parent', [
				{ from: 'grandparent', metadata: ['field'] }
			]);
 
			vi.stubGlobal(
				'fetch',
				vi.fn(async (url: string) => ({
					json: async () => {
						if (url.includes('registry.json')) {
							return {
								protocols: [
									{ id: 'parent', url: 'https://example.com/proto-parent.json' },
									{
										id: 'grandparent',
										url: 'https://example.com/proto-grandparent.json'
									}
								]
							};
						}
						if (url.includes('proto-grandparent.json')) return grandparentInput;
						if (url.includes('proto-parent.json')) return parentInput;
						throw new Error(`Unexpected fetch: ${url}`);
					}
				}))
			);
 
			const result = await resolveProtocolImports(mockDb(), 'child', [
				imp('parent__field', 'child__field')
			]);
 
			expect(result).toHaveLength(2);
			const ids = result.map((p) => p.id);
			expect(ids).toContain('parent');
			expect(ids).toContain('grandparent');
		});
	});
}