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 | 3x 3x 3x 3x 6x 5x 15x 6x 3x 5x 7x 6x 5x 4x 4x 4x 3x 2x 1x 1x 3x 3x 3x 2x 2x 2x 2x 2x 2x 3x 3x 3x 2x 3x 4x 3x 2x 2x 2x 11x 11x 2x 2x 2x 3x 3x 2x 3x 3x 3x 3x 4x 3x 8x 7x 5x 5x 5x 2x 2x 2x 2x 2x 2x 296x 2x 24x 24x 24x 3x 2x 33x 2x 48x 12x 10x 1x 1x 24x 1x 24x 6x 5x 2x 2x | import { ArkErrors, type } from 'arktype';
import microdiff from 'microdiff';
import { downloadAsFile, stringifyWithToplevelOrdering } from './download.js';
import { promptForFiles } from './files.js';
import { errorMessage } from './i18n.js';
import { metadataOptionsKeyRange } from './metadata.js';
import { ExportedProtocol, Protocol } from './schemas/protocols.js';
import { cachebust, fetchHttpRequest, fromEntries, keys, omit, pick, range, sum } from './utils.js';
/**
* @import { Schemas, Tables } from './database.js';
*/
/**
*
* @param {string} base base path of the app - import `base` from `$app/paths`
*/
export function jsonSchemaURL(base) {
return `${window.location.origin}${base}/protocol.schema.json`;
}
/**
* Turn a database-stored protocol into an object suitable for export.
* @param {import('./idb.svelte.js').DatabaseHandle} db
* @param {typeof Tables.Protocol.infer} protocol
*/
export async function toExportedProtocol(db, protocol) {
const allMetadataOptions = await db.getAll(
'MetadataOption',
metadataOptionsKeyRange(protocol.id, null)
);
const allMetadataDefs = Object.fromEntries(
await db.getAll('Metadata').then((defs) =>
defs
.filter(
(def) =>
protocol.metadata.includes(def.id) ||
protocol.sessionMetadata.includes(def.id)
)
.map((metadata) => [
metadata.id,
{
...omit(metadata, 'id'),
options: allMetadataOptions
.filter(({ id }) =>
metadataOptionsKeyRange(protocol.id, metadata.id).includes(id)
)
.map((option) => omit(option, 'id', 'metadataId'))
}
])
)
);
return ExportedProtocol.assert({
...omit(protocol, 'dirty'),
exports: {
...protocol.exports,
...(protocol.exports
? {
images: {
cropped: protocol.exports.images.cropped.toJSON(),
original: protocol.exports.images.original.toJSON()
}
}
: {})
},
metadata: pick(
allMetadataDefs,
...protocol.metadata.filter((id) => !protocol.sessionMetadata.includes(id))
),
sessionMetadata: pick(allMetadataDefs, ...protocol.sessionMetadata)
});
}
/**
* Exports a protocol by ID into a JSON file, and triggers a download of that file.
* @param {import('./idb.svelte.js').DatabaseHandle} db
* @param {string} base base path of the app - import `base` from `$app/paths`
* @param {import("./database").ID} id
* @param {'json' | 'yaml'} [format='json']
*/
export async function exportProtocol(db, base, id, format = 'json') {
downloadProtocol(
base,
format,
await db
.get('Protocol', id)
.then(Protocol.assert)
.then((p) => toExportedProtocol(db, p))
);
}
/**
* Downloads a protocol as a JSON file
* @param {string} base base path of the app - import `base` from `$app/paths`
* @param {'yaml'|'json'} format
* @param {typeof import('./schemas/protocols.js').ExportedProtocol.infer} exportedProtocol
*/
function downloadProtocol(base, format, exportedProtocol) {
let jsoned = stringifyWithToplevelOrdering(format, jsonSchemaURL(base), exportedProtocol, [
'id',
'name',
'source',
'authors',
'exports',
'metadata',
'inference'
]);
// application/yaml is finally a thing, see https://www.rfc-editor.org/rfc/rfc9512.html
downloadAsFile(jsoned, `${exportedProtocol.id}.${format}`, `application/${format}`);
}
/**
* Imports protocol(s) from JSON file(s).
* Asks the user to select files, then imports the protocols from those files.
* @template {{id: string, name: string, version: number|undefined}} Out
* @template {boolean|undefined} Multiple
* @param {object} param0
* @param {Multiple} param0.allowMultiple allow the user to select multiple files
* @param {() => void} [param0.onInput] callback to call when the user selected files
* @param {((input: {contents: string, isJSON: boolean}) => Promise<{id: string, name: string, version: number|undefined}>)} param0.importProtocol
* @returns {Promise<Multiple extends true ? NoInfer<Out>[] : NoInfer<Out>>}
*/
export async function promptAndImportProtocol({
allowMultiple,
onInput = () => {},
importProtocol
}) {
const files = await promptForFiles({
multiple: allowMultiple,
accept: '.json,.yaml,application/json'
});
onInput();
/** @type {Array<{id: string, name: string, version: number | undefined}>} */
const output = await Promise.all(
[...files].map(async (file) => {
console.time(`Reading file ${file.name}`);
const reader = new FileReader();
return new Promise((resolve) => {
reader.onload = async () => {
if (!reader.result) throw new Error('Fichier vide');
if (reader.result instanceof ArrayBuffer) throw new Error('Fichier binaire');
console.timeEnd(`Reading file ${file.name}`);
const result = await importProtocol({
contents: reader.result,
isJSON: file.name.endsWith('.json')
}).catch((err) => Promise.reject(new Error(errorMessage(err))));
const { tables } = await import('./idb.svelte.js');
await tables.Protocol.refresh(null);
await tables.Metadata.refresh(null);
resolve(result);
};
reader.readAsText(file);
});
})
);
return allowMultiple ? output : output[0];
}
/**
*
* @param {Pick<typeof Schemas.Protocol.infer, 'version'|'source'|'id'>} protocol
* @returns {Promise< { upToDate: boolean; newVersion: number }>}
*/
export async function hasUpgradeAvailable({ version, source, id }) {
if (!source) throw new Error("Le protocole n'a pas de source");
if (!version) throw new Error("Le protocole n'a pas de version");
if (!id) throw new Error("Le protocole n'a pas d'identifiant");
const response = await fetch(
cachebust(typeof source === 'string' ? source : source.url),
typeof source !== 'string'
? source
: {
headers: {
Accept: 'application/json'
}
}
)
.then((r) => r.json())
.then(
type({
'version?': 'number',
id: 'string'
}).assert
);
if (!response.version) throw new Error("Le protocole n'a plus de version");
if (response.id !== id) throw new Error("Le protocole a changé d'identifiant");
if (response.version > version) {
return {
upToDate: false,
newVersion: response.version
};
}
return {
upToDate: true,
newVersion: response.version
};
}
/**
* @param {object} param0
* @param {number} [param0.version]
* @param {import('$lib/database.js').HTTPRequest} param0.source
* @param {string} param0.id
* @param {import('swarpc').SwarpcClient<typeof import('$worker/procedures.js').PROCEDURES>} param0.swarpc
*/
export async function upgradeProtocol({ version, source, id, swarpc }) {
if (!source) throw new Error("Le protocole n'a pas de source");
if (!version) throw new Error("Le protocole n'a pas de version");
if (!id) throw new Error("Le protocole n'a pas d'identifiant");
if (typeof source !== 'string')
throw new Error('Les requêtes HTTP ne sont pas encore supportées, utilisez une URL');
const { tables } = await import('./idb.svelte.js');
const contents = await fetch(cachebust(source), {
headers: {
Accept: 'application/json'
}
}).then((r) => r.text());
const result = await swarpc.importProtocol({ contents });
tables.Protocol.refresh(null);
tables.Metadata.refresh(null);
const { version: newVersion, ...rest } = result;
if (newVersion === undefined)
throw new Error("Le protocole a été importé mais n'a plus de version");
return { version: newVersion, ...rest };
}
/**
*
* Compare the in-database protocol with its remote counterpart, output any changes.
* @param {import('./idb.svelte.js').DatabaseHandle} db
* @param {import('$lib/database').ID} protocolId
* @param {object} [options]
* @param {(progress: number) => void | Promise<void>} [options.onProgress]
* @returns {Promise<import('microdiff').Difference[]>}
*/
export async function compareProtocolWithUpstream(db, protocolId, { onProgress } = {}) {
const databaseProtocol = await db.get('Protocol', protocolId).then(Protocol.assert);
await onProgress?.(0);
if (!databaseProtocol?.source) return [];
const [remoteProtocol, localProtocol] = await Promise.all([
fetchHttpRequest(databaseProtocol.source)
.then((r) => r.json())
.then((data) => ExportedProtocol(data)),
toExportedProtocol(db, databaseProtocol)
]);
Iif (remoteProtocol instanceof ArkErrors) {
console.warn('Remote protocol is invalid', remoteProtocol);
return [];
}
// Sort options for each metadata by key
const metadataIds = new Set([
...keys(remoteProtocol.metadata),
...keys(localProtocol.metadata)
]);
const optionsTotalCount = sum(
[...metadataIds].map((metadataId) => {
const localMetadata = localProtocol.metadata[metadataId];
const remoteMetadata = remoteProtocol.metadata[metadataId];
if (!localMetadata) return 0;
Iif (!remoteMetadata) return 0;
const localOptionsKeys = localMetadata.options?.map((o) => o.key) ?? [];
const remoteOptionsKeys = remoteMetadata.options?.map((o) => o.key) ?? [];
return new Set([...localOptionsKeys, ...remoteOptionsKeys]).size;
})
);
// Note: Totals are based on timings on a single machine,
// the values dont really matter as least as they're self-consistent,
// it's just to determine what part of the progress bar belongs to fetch+convert
// It's in ×2ms so that incrementing progress for options is just 1 per option
let progressCompleted = 0;
const progressTotals = {
fetchAndConvert: 250 /* ×2ms */,
microdiff: 25 /* ×2ms */,
options: optionsTotalCount /* ×2ms */,
postProcess: 2 /* ×2ms */
};
const incrementProgress = async (amount = 1) => {
progressCompleted += amount;
onProgress?.(progressCompleted / sum(Object.values(progressTotals)));
};
await incrementProgress(progressTotals.fetchAndConvert);
const DELETED_OPTION = {
description: '',
key: '',
label: '',
__deleted: true
};
for (const metadataId of metadataIds) {
Iif (!remoteProtocol.metadata[metadataId]) continue;
if (!localProtocol.metadata[metadataId]) continue;
const remoteOptions = remoteProtocol.metadata[metadataId].options ?? [];
const sortedRemoteOptions = [];
const localOptions = localProtocol.metadata[metadataId].options ?? [];
const sortedLocalOptions = [];
const optionKeys = [
...new Set([...remoteOptions.map((o) => o.key), ...localOptions.map((o) => o.key)])
].sort();
for (const key of optionKeys) {
const remoteOption = remoteOptions.find((o) => o.key === key);
const localOption = localOptions.find((o) => o.key === key);
sortedLocalOptions.push(localOption ?? DELETED_OPTION);
sortedRemoteOptions.push(remoteOption ?? DELETED_OPTION);
await incrementProgress();
}
remoteProtocol.metadata[metadataId].options = sortedRemoteOptions;
localProtocol.metadata[metadataId].options = sortedLocalOptions;
}
const diffs = microdiff(remoteProtocol, localProtocol, {
cyclesFix: true
});
await incrementProgress(progressTotals.microdiff);
// If an option was removed from one side, it'll appear as a all-empty-strings option object with an additional `__deleted: true` property.
let cleanedDiffs = structuredClone(diffs);
const diffStartsWith = (path, start) =>
path.length >= start.length && range(0, start.length).every((i) => path[i] === start[i]);
for (const { path, type } of diffs) {
const last = path.at(-1);
const prefix = path.slice(0, -1);
// If the diff indicates that an option was deleted
if (last === '__deleted') {
// __deleted entry was _created_ in localProtocol, so it was a deleted-from-remote option
if (type === 'CREATE') {
const pathToOption = prefix;
// Delete all diffs with a path starting with diff.path[..-1]
cleanedDiffs = cleanedDiffs.filter((d) => !diffStartsWith(d.path, pathToOption));
// and replace them with a single diff indicating the deletion of the option
cleanedDiffs.push({
type: 'REMOVE',
path: [...prefix],
// Restore old value by getting all oldValues from diffs
oldValue: fromEntries(
diffs
.filter((d) => diffStartsWith(d.path, pathToOption))
.filter((d) => d.path.at(-1) !== '__deleted')
.map(
(d) =>
/** @type {const} */ ([
d.path.at(-1)?.toString() ?? '',
d.oldValue
])
)
)
});
} else Eif (type === 'REMOVE') {
// __deleted entry was _removed_ from localProtocol, so it's an option that didn't exist in remoteProtocol
const pathToOption = prefix;
// Delete all diffs with a path starting with diff.path[..-1]
cleanedDiffs = cleanedDiffs.filter((d) => !diffStartsWith(d.path, pathToOption));
// and replace them with a single diff indicating the addition of the option
cleanedDiffs.push({
type: 'CREATE',
path: [...prefix],
value: fromEntries(
diffs
.filter((d) => diffStartsWith(d.path, pathToOption))
.filter((d) => d.path.at(-1) !== '__deleted')
.map(
(d) =>
/** @type {const} */ ([
d.path.at(-1)?.toString() ?? '',
d.value
])
)
)
});
}
}
}
await incrementProgress(progressTotals.postProcess);
return cleanedDiffs;
}
|