All files / lib/accounts kobotoolbox.ts

50.71% Statements 106/209
33.09% Branches 46/139
52.94% Functions 27/51
53.8% Lines 99/184

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 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819                                      1x 1x       1x 1x 1x 1x                       15x                         1x           7x   6x   1x           12x                                       12x 12x 24x 12x 12x 12x 12x       1x                           3x   3x       2x   1x                   7x   6x                           3x   3x               1x   1x                               2x 2x   2x 3x 3x   1x   1x             1x                               1x 1x   1x 5x 5x   5x   5x         5x   15x         5x   5x   5x 5x                     5x   5x 5x                                                 3x 1x   2x 2x   1x             1x 1x   1x         1x 1x                     1x                                                                                                                                                                                 6x   6x                                                                                                                                                           6x         2x                   2x   1x   1x                                                                                                                 5x 130x                                                                                                                                         5x       2x 2x       1x 1x     1x   1x     1x                   10x                     10x 3x   7x       12x         12x     1x           1x                                                 1x                                                                                                                       1x                                                                           130x 130x 130x             130x   115x 115x   115x    
import type { DatabaseHandle } from '../idb.svelte.js';
import type { Account, AuthenticationMethod, LoginData } from '$lib/accounts/types.js';
import type * as DB from '$lib/database.js';
import type { MetadataRecordValue, RuntimeValue } from '$lib/schemas/metadata.js';
 
import { Type, type } from 'arktype';
import * as date from 'date-fns';
 
import { Schemas } from '$lib/database.js';
import { resolveMetadataImport } from '$lib/metadata/imports.js';
import { protocolMetadataValues } from '$lib/metadata/namespacing.js';
import { serializeMetadataValue } from '$lib/metadata/serializing.js';
import { metadataOptionsKeyRange } from '$lib/metadata/storage.js';
import { MIMEType, NamespacedMetadataID } from '$lib/schemas/common.js';
import { removeNamespaceFromMetadataId, splitMetadataId } from '$lib/schemas/metadata.js';
import { SessionRemoteID } from '$lib/schemas/sessions.js';
import { corsfix, ensureArray, mapValues } from '$lib/utils.js';
 
export default class Provider implements Account {
	static id = 'kobotoolbox' as const;
	static servers = [
		{ domain: 'kf.kobotoolbox.org', name: 'Global' },
		{ domain: 'eu.kobotoolbox.org', name: 'Europe' },
	] as const;
	static auth = 'token' as const satisfies AuthenticationMethod;
	static capabilities = ['sessions'] as const;
	static displayName = 'KoboToolbox';
	static logoURL = new URL('https://avatars.githubusercontent.com/u/5543677?s=280&v=4');
 
	#token: string;
	username: string;
	displayName: string;
	avatarURL: URL | undefined;
	domain: (typeof Provider.servers)[number]['domain'];
	db: DatabaseHandle;
	/** Database ID of the account */
	id: string | undefined;
 
	get v2domain(): string {
		return this.domain;
	}
 
	get v1domain(): string {
		switch (this.domain) {
			case 'eu.kobotoolbox.org':
				return 'kc-eu.kobotoolbox.org';
			case 'kf.kobotoolbox.org':
				return 'kc.kobotoolbox.org';
		}
	}
 
	static tokenPageURL(server: string): URL {
		return new URL('/token/', 'https://' + server);
	}
 
	static domainOfProfileURL(
		profileURL: string | URL
	): (typeof Provider.servers)[number]['domain'] {
		switch (new URL(profileURL).hostname) {
			case 'kc.kobotoolbox.org':
				return 'kf.kobotoolbox.org';
			case 'kc-eu.kobotoolbox.org':
				return 'eu.kobotoolbox.org';
			default:
				throw new Error(`Profile is on a unknown KoboToolbox server: ${profileURL}`);
		}
	}
 
	#cache: Map<SessionRemoteID, (typeof Provider.ProjectDataResponse)['infer']> = new Map();
 
	constructor(
		db: DatabaseHandle,
		{
			token,
			username,
			displayName,
			avatarURL,
			domain,
			id,
		}: {
			token: string;
			domain: (typeof Provider.servers)[number]['domain'];
			username?: string;
			displayName?: string;
			avatarURL?: URL | undefined;
			id?: string | undefined;
		}
	) {
		this.#token = token;
		this.username = username ?? '';
		this.domain = type.enumerated(...Provider.servers.map((s) => s.domain)).assert(domain);
		this.displayName = displayName ?? '';
		this.avatarURL = avatarURL;
		this.db = db;
		this.id = id;
	}
 
	toJSON() {
		return {
			token: this.#token,
			username: this.username,
			domain: this.domain,
			displayName: this.displayName,
			db: this.db,
			id: this.id,
		};
	}
 
	static async checkAuth({
		server,
		token,
	}: LoginData<(typeof Provider.servers)[number]['domain']>) {
		Iif (!token) return 'Token vide';
 
		const response = await new Provider(undefined!, { token, domain: server }).fetch(
			`https://${server}/me/`
		);
 
		if (response.ok) return undefined;
 
		return response.text();
	}
 
	static fromDatabase(
		db: DatabaseHandle,
		account: Pick<
			DB.Account,
			'token' | 'profileURL' | 'username' | 'type' | 'displayName' | 'avatarURL' | 'id'
		>
	) {
		if (account.type !== 'kobotoolbox') throw new Error('Invalid account type');
 
		return new Provider(db, {
			token: account.token,
			domain: Provider.domainOfProfileURL(account.profileURL),
			username: account.username,
			displayName: account.displayName,
			avatarURL: account.avatarURL,
			id: account.id,
		});
	}
 
	static async login(
		db: DatabaseHandle,
		{ token, server }: LoginData<(typeof Provider.servers)[number]['domain']>
	) {
		Iif (!token) throw new Error('No login data provided');
 
		const me = await new Provider(db, { domain: server, token }).json(
			'GET',
			'v2',
			'/me/',
			Provider.MeResponse
		);
 
		// Enforce a 200px thumbnail
		me.gravatar.searchParams.set('s', '200');
 
		return {
			type: 'kobotoolbox' as const,
			token,
			username: me.username,
			displayName:
				(me.first_name || me.last_name
					? `${me.first_name} ${me.last_name}`
					: me.extra_details.name) || me.username,
			avatarURL: me.gravatar.href,
			profileURL: me.projects_url.href,
		};
	}
 
	async logout() {}
 
	async *sessions({ cursor = undefined, limit = 40, mine = false } = {}) {
		const yielded = new Set<string>();
		let total = 0;
 
		for (const p of await this.db.getAll('Protocol')) {
			const protocol = Schemas.Protocol.assert(p);
			if (!protocol.remote?.kobocollect) continue;
 
			const assetUid = this.#projectAssetUid(protocol.remote.kobocollect.form);
 
			const project = await this.json(
				'GET',
				'v2',
				`/api/v2/assets/${assetUid}`,
				Provider.ProjectResponse
			);
 
			const response = await this.json(
				'GET',
				'v2',
				`/api/v2/assets/${assetUid}/data?${new URLSearchParams({
					limit: limit.toString(),
					offset: cursor ? (new URL(cursor).searchParams.get('offset') ?? '0') : '0',
					query: JSON.stringify({
						_submitted_by: mine ? this.username : undefined,
					}),
					sort: JSON.stringify({
						_submission_time: -1,
					}),
				})}`,
				Provider.PaginatedResponse(Provider.ProjectDataResponse)
			);
 
			total += response.results.length;
			yield { total };
 
			for (const result of response.results) {
				const gid = this.#SessionRemoteID(assetUid, result._id);
				this.#cache.set(gid, result);
 
				const thumbFields = ensureArray(protocol.remote?.kobocollect?.thumbnails ?? []).map(
					(field) =>
						this.#columnByNameOrLabel(project, result, {
							both: field,
						})
				);
 
				const thumbs = result._attachments.filter(
					(a) =>
						a.mimetype.startsWith('image/') &&
						thumbFields.some((field) => field?.$xpath === a.question_xpath) &&
						!a.is_deleted
				);
 
				const metadata = await this.#rowToMetadata(protocol, project, result);
 
				let name = 'Sans nom';
 
				try {
					name = protocol.remote.kobocollect.title.render({
						survey: result,
						session: {
							metadata,
							protocolMetadata: protocolMetadataValues('session', protocol, metadata),
						},
					});
				} catch (error) {
					console.error(error);
				}
 
				Iif (yielded.has(gid)) continue;
 
				yielded.add(gid);
				yield {
					id: gid,
					name,
					page: new URL(
						`https://${this.v2domain}/api/v2/assets/${assetUid}/data/${result._id}/enketo/redirect/view`
					),
					protocol: protocol.id,
					submittedAt: result._submission_time,
					submittedBy: result._submitted_by,
					nextCursor: response.next ?? undefined,
					filesCount: result._attachments.length,
					imagesCount: 0,
					thumbnails: thumbs.map((thumb) => thumb.download_small_url),
				};
			}
		}
	}
 
	async thumbnail(url: URL) {
		return this.fetch(url)
			.then((response) => response.blob())
			.then((blob) => new URL(URL.createObjectURL(blob)));
	}
 
	async session(protocol: DB.Protocol, id: SessionRemoteID) {
		if (!protocol.remote?.kobocollect)
			throw new Error("This protocol doesn't support KoboToolbox remote sessions");
 
		const project = await this.#fetchProject(id);
		const row = await this.#fetchData(id);
 
		const { url: submissionUrl } = await this.json(
			'GET',
			'v2',
			`${id.replace(/\/$/, '')}/enketo/view`,
			type({ url: 'string.url' })
		);
 
		const metadata = await this.#rowToMetadata(protocol, project, row);
		let name = 'Sans nom';
 
		console.info(
			'Metadata computed from KoboToolbox fields:',
			mapValues(metadata, ({ value }) => value)
		);
 
		try {
			name = protocol.remote.kobocollect.title.render({
				survey: row,
				session: {
					metadata,
					protocolMetadata: protocolMetadataValues('session', protocol, metadata),
				},
			});
		} catch (error) {
			console.error(error);
		}
 
		return {
			remoteId: id,
			protocol: protocol.id,
			name,
			createdAt: row._submission_time.toISOString(),
			description: `Créée sur KoboToolbox. Voir ${submissionUrl}`,
			openedAt: new Date().toISOString(),
			metadata: mapValues(metadata, ({ value, ...rest }) => ({
				...rest,
				value: serializeMetadataValue(value),
			})),
			inferenceModels: {},
			group: {
				global: { field: 'none', tolerances: { dates: 'day', decimal: 'unit' } } as const,
			},
			sort: {
				global: { field: 'name', direction: 'asc' } as const,
			},
			fullscreenClassifier: {
				layout: 'top-bottom' as const,
			},
		};
	}
 
	async items() {
		return {
			observations: [],
			images: [],
			files: [],
		};
	}
 
	async *files(protocol: DB.Protocol, id: SessionRemoteID) {
		const project = await this.#fetchProject(id);
		const row = await this.#fetchData(id);
 
		for (const metadataId of protocol.sessionMetadata) {
			const def = await this.db
				.get('Metadata', resolveMetadataImport(protocol, metadataId))
				.then((raw) => (raw ? Schemas.Metadata.assert(raw) : undefined));
 
			if (!def) continue;
			if (def.type !== 'file') continue;
 
			const column = this.#columnOfMetadata(project, row, def);
			if (!column) continue;
 
			const attachment = this.#findAttachment({
				xpath: column.$xpath,
				attachments: row._attachments,
			});
			if (!attachment) continue;
 
			const file = await this.fetch(attachment.download_url);
			const bytes = await file.arrayBuffer();
 
			yield {
				// TODO: support attaching download_url here
				id: this.#compositeFileId(project, row, attachment),
				bytes,
				contentType: attachment.mimetype,
				filename: attachment.media_file_basename,
				size: bytes.byteLength,
				// kobocollect doesn't store it...
				lastModifiedAt: row._submission_time.toISOString(),
			};
		}
	}
 
	async upload(): Promise<{ remoteID?: SessionRemoteID; page?: URL }> {
		throw new Error('Not implemented');
	}
 
	#compositeFileId(
		project: (typeof Provider.ProjectResponse)['infer'],
		row: (typeof Provider.ProjectDataResponse)['infer'],
		attachment: (typeof Provider.ProjectDataResponse)['infer']['_attachments'][number]
	) {
		return `${this.domain}__${project.uid}__${row._id}__${attachment.uid}`;
	}
 
	async #rowToMetadata(
		protocol: DB.Protocol,
		project: (typeof Provider.ProjectResponse)['infer'],
		row: (typeof Provider.ProjectDataResponse)['infer']
	) {
		const metadataValues: Record<
			NamespacedMetadataID,
			(typeof MetadataRecordValue)['inferIn']
		> = {};
 
		for (const id of protocol.sessionMetadata) {
			const def = await this.db
				.get('Metadata', resolveMetadataImport(protocol, id))
				.then((raw) => (raw ? Schemas.Metadata.assert(raw) : undefined));
 
			if (!def) continue;
 
			const column = this.#columnOfMetadata(project, row, def);
 
			let xpath: string | undefined;
			if (column) {
				xpath = column.$xpath;
			} else {
				xpath = ensureArray(def.kobocollect)
					.flatMap((field) =>
						ensureArray(
							typeof field === 'string'
								? field
								: field && 'list' in field
									? field.list
									: []
						)
					)
					.find((field) => field in row);
			}
 
			const value = xpath && xpath in row ? row[xpath]?.toString() : undefined;
			if (!value) {
				console.debug(
					`No value found in KoboToolbox submission for metadata '${def.id}' (column xpath ${xpath})`,
					{ metadata: def, column, row, xpath }
				);
				continue;
			}
 
			switch (def.type) {
				case 'enum': {
					const option = await this.#parseEnumCell(def, value);
					if (!option) continue;
 
					metadataValues[def.id] = {
						value: option.key,
						confidences: {},
						alternatives: [],
					};
					break;
				}
				case 'file': {
					if (!xpath) continue;
 
					const file = this.#findAttachment({
						xpath,
						attachments: row._attachments,
					});
 
					if (!file) continue;
 
					metadataValues[def.id] = {
						value: this.#compositeFileId(project, row, file),
						alternatives: [],
						confidences: {},
					};
					break;
				}
				default: {
					const parsed = this.#parseKobocollectCell(def, value);
					if (parsed === undefined) continue;
 
					metadataValues[def.id] = {
						value: parsed instanceof Date ? parsed.toISOString() : parsed,
						alternatives: [],
						confidences: {},
					};
					break;
				}
			}
		}
 
		return metadataValues;
	}
 
	async #fetchProject(id: SessionRemoteID) {
		// TODO cache this too
		return this.json(
			'GET',
			'v2',
			`/api/v2/assets/${this.#parseSessionRemoteID(id).assetUid}`,
			Provider.ProjectResponse
		);
	}
 
	async #fetchData(id: SessionRemoteID) {
		const response =
			this.#cache.get(id) ?? (await this.json('GET', 'v2', id, Provider.ProjectDataResponse));
 
		this.#cache.set(id, response);
 
		return response;
	}
 
	#findAttachment({
		xpath,
		attachments,
	}: {
		attachments: (typeof Provider.ProjectDataResponse)['infer']['_attachments'];
		xpath: string;
	}) {
		return attachments.find((a) => a.question_xpath === xpath && !a.is_deleted);
	}
 
	async #parseEnumCell(metadata: DB.Metadata & { type: 'enum' }, serializedValue: string) {
		const { namespace, id } = splitMetadataId(metadata.id);
		const options = await this.db.getAll(
			'MetadataOption',
			metadataOptionsKeyRange(namespace, id)
		);
 
		return options.find((option) => serializedValue === (option.kobocollect ?? option.key));
	}
 
	#columnOfMetadata(
		project: (typeof Provider.ProjectResponse)['infer'],
		row: (typeof Provider.ProjectDataResponse)['infer'],
		metadata: DB.Metadata
	) {
		return this.#columnByNameOrLabel(project, row, {
			name: removeNamespaceFromMetadataId(metadata.id),
			label: metadata.label,
			both: metadata.kobocollect
				? Array.isArray(metadata.kobocollect)
					? metadata.kobocollect
					: typeof metadata.kobocollect === 'string'
						? [metadata.kobocollect]
						: Array.isArray(metadata.kobocollect.list)
							? metadata.kobocollect.list
							: [metadata.kobocollect.list]
				: undefined,
		});
	}
 
	#columnByNameOrLabel(
		project: (typeof Provider.ProjectResponse)['infer'],
		/** Also filter for columns that have a matching $xpath in row's keys */
		row: (typeof Provider.ProjectDataResponse)['infer'] | undefined,
		{
			name,
			label,
			both,
		}: {
			name?: undefined | string | Array<string | undefined>;
			label?: undefined | string | Array<string | undefined>;
			both?: undefined | string | Array<string | undefined>;
		}
	) {
		return project.content.survey.find(
			(field) =>
				(matchesName(field, both ?? name ?? []) ||
					matchesLabel(field, both ?? label ?? [])) &&
				(!row || field.$xpath in row)
		);
	}
 
	#parseKobocollectCell<T extends DB.MetadataType>(
		metadata: DB.Metadata & { type: T },
		serializedValue: string
	): RuntimeValue<T> {
		switch (metadata.type) {
			case 'string':
				return serializedValue;
			case 'integer':
				return Number.parseInt(serializedValue);
			case 'float':
				return Number.parseFloat(serializedValue);
			case 'enum': {
				throw new Error('enum-type metadata should not be handled by parseKobocollectCell');
			}
 
			case 'boolean': {
				const isOK = serializedValue === 'OK';
 
				if (!metadata.kobocollect) return isOK;
				if (typeof metadata.kobocollect === 'string') return isOK;
				if (Array.isArray(metadata.kobocollect)) return isOK;
 
				if ('choice' in metadata.kobocollect) {
					const choices = ensureArray(metadata.kobocollect.choice);
					return serializedValue.split(' ').some((value) => choices.includes(value));
				}
 
				return ensureArray(metadata.kobocollect.true).includes(serializedValue);
			}
 
			case 'location': {
				const components = serializedValue
					.split(' ')
					.map(Number.parseFloat)
					.filter((x) => !Number.isNaN(x));
 
				if (components.length !== 4)
					throw new Error(
						`Invalid GPS point serialization: '${serializedValue}' doesn't have four space-separated numbers`
					);
 
				const [latitude, longitude, _, __] = components;
 
				return { latitude, longitude };
			}
 
			case 'boundingbox': {
				// TODO validate
				return JSON.parse(serializedValue) as RuntimeValue<'boundingbox'>;
			}
 
			case 'date': {
				return date.parseISO(serializedValue);
			}
 
			case 'file': {
				throw new Error('file metadata should not be handled by parseKobocollectCell');
			}
		}
	}
 
	#SessionRemoteID(assetUid: string, dataId: string | number) {
		return SessionRemoteID.assert(`/api/v2/assets/${assetUid}/data/${dataId}`);
	}
 
	#parseSessionRemoteID(id: SessionRemoteID): { assetUid: string; dataId: string } {
		const [_, _api, _v2, _assets, assetUid, _data, dataId] = id.split('/');
		return { assetUid, dataId };
	}
 
	#projectAssetUid(href: string): string {
		const url = new URL(href);
		Iif (!url.hash.startsWith('#/forms/'))
			throw new Error(`Invalid form URL '${url}': must contain #/forms/...`);
 
		const id = url.hash.split('/').at(2);
 
		Iif (!id)
			throw new Error(`Invalid form URL '${url}': must be of the form #/forms/ID HERE/(...)`);
 
		return id;
	}
 
	async json<Response extends Type>(
		method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
		version: 'v1' | 'v2',
		path: string,
		responseSchema: Response,
		init?: RequestInit
	) {
		const response = await this.fetch(
			new URL(path, `https://${version === 'v1' ? this.v1domain : this.v2domain}`),
			{
				method,
				headers: {
					Accept: 'application/json',
				},
				...init,
			}
		);
 
		if (!response.ok)
			throw new Error('Impossible de se connecter à KoboToolbox: ' + (await response.text()));
 
		return responseSchema.assert(await response.json());
	}
 
	async fetch(url: URL | string, init: RequestInit = {}) {
		init.headers = {
			Authorization: `Token ${this.#token}`,
			...init.headers,
		};
 
		return fetch(corsfix(url), init);
	}
 
	static PaginatedResponse = type('<T>', {
		count: 'number.integer',
		next: 'string.url | null',
		results: 'T[]',
	});
 
	static ProjectDataResponse = type({
		'[string]': 'unknown',
		_id: 'number.integer',
		__version__: 'string',
		_xform_id_string: 'string',
		_uuid: 'string',
		_status: type('string').as<'submitted_via_web' | (string & {})>(),
		_geolocation: ['number|null', 'number|null'],
		_submission_time: 'string.date.iso.parse',
		_submitted_by: 'string|null',
		'meta/instanceID': 'string',
		_attachments: type({
			download_url: 'string.url.parse',
			download_large_url: 'string.url.parse',
			download_medium_url: 'string.url.parse',
			download_small_url: 'string.url.parse',
			mimetype: MIMEType,
			filename: 'string',
			media_file_basename: 'string',
			question_xpath: 'string',
			uid: 'string',
			'is_deleted?': 'boolean',
		}).array(),
	});
 
	static ProjectResponse = type({
		name: 'string',
		uid: 'string',
		version_id: 'string',
		deployment__uuid: 'string',
		deployment__links: {
			url: 'string.url.parse',
		},
		deployment__active: 'boolean',
		settings: {
			description: 'string',
		},
		content: {
			schema: type.enumerated('1'),
			survey: type({
				'name?': 'string',
				type: type('string').as<
					| 'datetime'
					| 'decimal'
					| 'end'
					| 'geopoint'
					| 'image'
					| 'integer'
					| 'select_multiple'
					| 'select_one'
					| 'start'
					| 'text'
					| 'username'
					| (string & {})
				>(),
				'required?': 'boolean',
				$xpath: 'string',
				$kuid: 'string',
				'label?': 'string[]',
				$autoname: 'string',
				'select_from_list_name?': 'string',
			}).array(),
			choices: type({
				name: 'string',
				$kuid: 'string',
				label: 'string[]',
				list_name: 'string',
				$autovalue: 'string',
			}).array(),
		},
		effective_permissions: type({
			codename: type.enumerated(
				'change_asset',
				'delete_asset',
				'change_submissions',
				'validate_submissions',
				'add_submissions',
				'view_submissions',
				'manage_asset',
				'view_asset',
				'delete_submissions'
			),
		}).array(),
	});
 
	static MeResponse = type({
		username: 'string',
		first_name: 'string',
		last_name: 'string',
		email: 'string',
		server_time: 'string.date.iso.parse',
		date_joined: 'string.date.iso.parse',
		projects_url: 'string.url.parse',
		gravatar: 'string.url.parse',
		last_login: 'string.date.iso.parse',
		extra_details: {
			name: 'string',
			sector: 'string',
			country: 'string',
			organization: 'string',
			last_ui_language: 'string',
			organization_type: 'string',
			organization_website: 'string',
			newsletter_subscription: 'boolean',
			require_auth: 'boolean',
		},
		git_rev: 'boolean',
		social_accounts: 'Array',
		validated_password: 'boolean',
		accepted_tos: 'boolean',
		organization: {
			url: 'string.url.parse',
			name: 'string',
			uid: 'string',
		},
		extra_details__uid: 'string',
	});
}
 
function matchesName(
	subject: { $autovalue: string; name?: string } | { $autoname: string; name?: string },
	name: string | Array<string | undefined>
) {
	const subj = subject.name || ('$autovalue' in subject ? subject.$autovalue : subject.$autoname);
	const candidates = ensureArray(name).map((c) => c?.trim().toLowerCase());
	return candidates.includes(subj.trim().toLowerCase());
}
 
function matchesLabel(
	subject: { label?: string | string[] },
	label: string | Array<string | undefined>
) {
	if (!subject.label) return false;
 
	const subj = ensureArray(subject.label)[0];
	const candidates = ensureArray(label).map((c) => c?.trim().toLowerCase());
 
	return candidates.includes(subj.trim().toLowerCase());
}