@extantape/payload-plugin-onephylogeny 0.0.0-stage → 0.1.0-alpha.10
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/LICENSE +75 -0
- package/README.md +90 -2
- package/dist/index.d.ts +334 -0
- package/dist/index.js +810 -0
- package/package.json +56 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,810 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { validateResult } from "@extantape/onephylogeny-core";
|
|
3
|
+
import { relationship as validateRelationship } from "payload/shared";
|
|
4
|
+
|
|
5
|
+
// src/access.ts
|
|
6
|
+
function either(...grants) {
|
|
7
|
+
if (grants.some((g) => g === true)) return true;
|
|
8
|
+
const queries = grants.filter((g) => Boolean(g) && typeof g === "object");
|
|
9
|
+
return queries.length === 0 ? false : queries.length === 1 ? queries[0] : { or: queries };
|
|
10
|
+
}
|
|
11
|
+
var anyOf = (...rules) => async (args) => either(...await Promise.all(rules.map((r) => r ? r(args) : false)));
|
|
12
|
+
|
|
13
|
+
// src/external.ts
|
|
14
|
+
import { APIError, ValidationError } from "payload";
|
|
15
|
+
var ORIGINS = ["internal", "external"];
|
|
16
|
+
var SOURCE_TYPES = ["paper", "public-database", "validated-panel", "institution"];
|
|
17
|
+
var DATA_LICENSES = ["cc0", "cc-by", "cc-by-nc", "insdc", "other", "unknown"];
|
|
18
|
+
var DATE_PRECISIONS = ["day", "month", "year", "unknown"];
|
|
19
|
+
var READ_TIERS = ["external", "cache", "hot", "deep-archive"];
|
|
20
|
+
var REALMS = ["land", "marine", "freshwater"];
|
|
21
|
+
function licenseTerms(license) {
|
|
22
|
+
switch (license) {
|
|
23
|
+
case "cc0":
|
|
24
|
+
case "insdc":
|
|
25
|
+
case "cc-by":
|
|
26
|
+
return { keepCopy: true, redistribute: true, commercial: true, pointerOnly: false };
|
|
27
|
+
case "cc-by-nc":
|
|
28
|
+
return { keepCopy: true, redistribute: true, commercial: false, pointerOnly: false };
|
|
29
|
+
default:
|
|
30
|
+
return { keepCopy: false, redistribute: false, commercial: false, pointerOnly: true };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
var normalize = (v) => String(v).replace(/\s+/g, "").toLowerCase();
|
|
34
|
+
var sourceKeyOf = (database, accession) => hasValue(database) && hasValue(accession) ? `${normalize(database)}:${normalize(accession)}` : void 0;
|
|
35
|
+
var SOURCE_KEY_PATH = /(^|[._])external[._]source_?key$/i;
|
|
36
|
+
var SOURCE_KEY_COLUMN = /external_source_key/i;
|
|
37
|
+
var duplicateMessage = (database, accession) => `Another sample already records ${String(database)} ${String(accession)}. Edit that sample instead of adding a second.`;
|
|
38
|
+
var collidedMessage = (database, accession) => `Another write landed in the same instant, most likely a sample with ${String(database)} ${String(accession)}. Try again: if that sample exists, you'll be told so.`;
|
|
39
|
+
var isDuplicateKey = (e) => {
|
|
40
|
+
if (e instanceof ValidationError) return Boolean(e.data?.errors?.some((f) => SOURCE_KEY_PATH.test(String(f.path ?? ""))));
|
|
41
|
+
for (let err = e, depth = 0; err && typeof err === "object" && depth < 5; err = err.cause, depth++) {
|
|
42
|
+
if (err.code === "23505") return [err.constraint, err.detail, err.message].some((v) => SOURCE_KEY_COLUMN.test(String(v ?? "")));
|
|
43
|
+
}
|
|
44
|
+
return false;
|
|
45
|
+
};
|
|
46
|
+
var isWriteConflict = (e) => {
|
|
47
|
+
const err = e;
|
|
48
|
+
return Boolean(err && typeof err === "object" && (err.code === 112 || err.codeName === "WriteConflict" || /WriteConflict|retry your operation/i.test(String(err.message ?? ""))));
|
|
49
|
+
};
|
|
50
|
+
var withSourceKeyErrors = (db, samples) => {
|
|
51
|
+
if (!db) return db;
|
|
52
|
+
const rethrow = (e, args) => {
|
|
53
|
+
const ext = args.data?.external;
|
|
54
|
+
if (args.collection !== samples || !hasValue(ext?.sourceKey)) throw e;
|
|
55
|
+
if (isDuplicateKey(e)) throw new APIError(duplicateMessage(ext?.database, ext?.accession), 400, void 0, true);
|
|
56
|
+
if (isWriteConflict(e)) throw new APIError(collidedMessage(ext?.database, ext?.accession), 409, void 0, true);
|
|
57
|
+
throw e;
|
|
58
|
+
};
|
|
59
|
+
return {
|
|
60
|
+
...db,
|
|
61
|
+
init: (args) => {
|
|
62
|
+
const adapter = db.init(args);
|
|
63
|
+
for (const op of ["create", "updateOne", "upsert"]) {
|
|
64
|
+
const original = adapter[op];
|
|
65
|
+
if (typeof original !== "function") continue;
|
|
66
|
+
adapter[op] = async (a) => {
|
|
67
|
+
try {
|
|
68
|
+
return await original.call(adapter, a);
|
|
69
|
+
} catch (e) {
|
|
70
|
+
return rethrow(e, a);
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
return adapter;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
};
|
|
78
|
+
var fail = (message) => {
|
|
79
|
+
throw new APIError(message, 400, void 0, true);
|
|
80
|
+
};
|
|
81
|
+
var nobody = () => false;
|
|
82
|
+
var COORDINATES = /^(lat|lon|lng|latitude|longitude|latlon|lat_lon|coordinates?|geometry|point)$/i;
|
|
83
|
+
var SHA256 = /^[0-9a-f]{64}$/;
|
|
84
|
+
var hasValue = (v) => {
|
|
85
|
+
if (v == null || v === "") return false;
|
|
86
|
+
if (Array.isArray(v)) return v.some(hasValue);
|
|
87
|
+
if (typeof v === "object") return v instanceof Date || Object.values(v).some(hasValue);
|
|
88
|
+
return true;
|
|
89
|
+
};
|
|
90
|
+
var DEG = String.raw`-?\d{1,3}(?:\.\d+)?`;
|
|
91
|
+
var COORDINATE_TEXT = [
|
|
92
|
+
// Decimal degrees with hemispheres: 4.61 N 74.08 W, 4.61N, 74.08W, 4.61° S, 74.08° E.
|
|
93
|
+
new RegExp(String.raw`(?<![\w.])${DEG}\s*[°º]?\s*[NS]\b[\s,;/]*${DEG}\s*[°º]?\s*[EW]\b`, "i"),
|
|
94
|
+
// Hemisphere first: N 4.61 W 74.08, N4.61, W74.08.
|
|
95
|
+
new RegExp(String.raw`\b[NS]\s*${DEG}\s*[°º]?[\s,;/]*[EW]\s*${DEG}(?![\w.])`, "i"),
|
|
96
|
+
// Degrees and minutes, with or without seconds, and a hemisphere: 4°36'35"N, 74° 04.9' W.
|
|
97
|
+
new RegExp(String.raw`\d{1,3}\s*[°º]\s*\d{1,2}(?:\.\d+)?\s*['′’]\s*(?:\d{1,2}(?:\.\d+)?\s*["″”]\s*)?[NSEW]\b`, "i")
|
|
98
|
+
];
|
|
99
|
+
var DECIMAL_PAIR = /(?<![\w.-])(-?\d{1,2}\.\d{2,})(?:\s*,\s*|\s+)(-?\d{1,3}\.\d{2,})(?![\w.])/;
|
|
100
|
+
var looksLikeCoordinates = (text) => {
|
|
101
|
+
if (COORDINATE_TEXT.some((re) => re.test(text))) return true;
|
|
102
|
+
const pair = DECIMAL_PAIR.exec(text);
|
|
103
|
+
return pair !== null && Math.abs(Number(pair[1])) <= 90 && Math.abs(Number(pair[2])) <= 180;
|
|
104
|
+
};
|
|
105
|
+
var findCoordinate = (value, path = "") => {
|
|
106
|
+
if (typeof value === "string") return looksLikeCoordinates(value) ? path : void 0;
|
|
107
|
+
if (Array.isArray(value)) {
|
|
108
|
+
for (const [i, v] of value.entries()) {
|
|
109
|
+
const hit = findCoordinate(v, `${path}[${i}]`);
|
|
110
|
+
if (hit !== void 0) return hit;
|
|
111
|
+
}
|
|
112
|
+
return void 0;
|
|
113
|
+
}
|
|
114
|
+
if (!value || typeof value !== "object" || value instanceof Date) return void 0;
|
|
115
|
+
for (const [k, v] of Object.entries(value)) {
|
|
116
|
+
const at = path ? `${path}.${k}` : k;
|
|
117
|
+
if (COORDINATES.test(k)) return at;
|
|
118
|
+
const hit = findCoordinate(v, at);
|
|
119
|
+
if (hit !== void 0) return hit;
|
|
120
|
+
}
|
|
121
|
+
return void 0;
|
|
122
|
+
};
|
|
123
|
+
var whenExternal = { condition: ((data) => data?.origin === "external") };
|
|
124
|
+
var whenInternal = (data) => data?.origin !== "external";
|
|
125
|
+
var relation = (name, relationTo, extra = {}) => relationTo ? [{ name, type: "relationship", relationTo, index: true, ...extra }] : [];
|
|
126
|
+
var realm = (name, example) => ({
|
|
127
|
+
name,
|
|
128
|
+
type: "group",
|
|
129
|
+
admin: { description: `Set with its dataset and version, for example ${example}. Never a coordinate.` },
|
|
130
|
+
fields: [
|
|
131
|
+
{ name: "code", type: "text", admin: { description: "The ecoregion's identifier in its dataset." } },
|
|
132
|
+
{ name: "name", type: "text" },
|
|
133
|
+
{ name: "dataset", type: "text" },
|
|
134
|
+
{ name: "version", type: "text" }
|
|
135
|
+
]
|
|
136
|
+
});
|
|
137
|
+
function externalFields(o) {
|
|
138
|
+
const restricted = o.restrictedAccess ?? nobody;
|
|
139
|
+
const url = o.urlAccess ?? nobody;
|
|
140
|
+
return {
|
|
141
|
+
origin: {
|
|
142
|
+
name: "origin",
|
|
143
|
+
type: "select",
|
|
144
|
+
required: true,
|
|
145
|
+
defaultValue: "internal",
|
|
146
|
+
index: true,
|
|
147
|
+
options: [...ORIGINS],
|
|
148
|
+
admin: { description: "Internal: the host's own material. External: a record from a paper, database, panel or institution. Set once." }
|
|
149
|
+
},
|
|
150
|
+
external: {
|
|
151
|
+
name: "external",
|
|
152
|
+
type: "group",
|
|
153
|
+
admin: { ...whenExternal, description: "Where an external sample came from. Never a keeper's data, and never a locality." },
|
|
154
|
+
fields: [
|
|
155
|
+
{ name: "sourceType", type: "select", options: [...SOURCE_TYPES] },
|
|
156
|
+
{ name: "accession", type: "text", index: true, admin: { description: "The source's own identifier, such as a GenBank or ENA accession. Unique with its database, without regard to case or spacing." } },
|
|
157
|
+
{ name: "database", type: "text", admin: { description: "The database the accession belongs to, such as GenBank, ENA, BOLD or GBIF. Empty for a paper or institution with no public record." } },
|
|
158
|
+
// Filled by the hook, never by hand. Not required, so the adapters give it a sparse unique index that skips samples with no public record.
|
|
159
|
+
{ name: "sourceKey", type: "text", unique: true, hidden: true, admin: { readOnly: true, hidden: true } },
|
|
160
|
+
{ name: "voucher", type: "group", fields: [{ name: "institution", type: "text", admin: { description: "The collection's code." } }, { name: "catalogNumber", type: "text" }] },
|
|
161
|
+
{ name: "collector", type: "text", access: { read: restricted, update: restricted }, admin: { description: "Who collected it, as the source names them. Restricted." } },
|
|
162
|
+
{ name: "collectionDatePrecision", type: "select", options: [...DATE_PRECISIONS], admin: { description: "How much of the collection date to trust. Sources often give a year only." } },
|
|
163
|
+
{ name: "permit", type: "text", access: { read: restricted, update: restricted }, admin: { description: "The permit reference the source gives, as written. Restricted." } },
|
|
164
|
+
{ name: "dataLicense", type: "select", options: [...DATA_LICENSES], admin: { description: "Decides what may be done with the sequence. Unknown and other mean pointer only: no copy kept and nothing passed on, until a curator who has read the terms sets a real license." } },
|
|
165
|
+
{ name: "dataLicenseNote", type: "text", admin: { description: "For other: the terms as written, or a link to them, for a person to read." } },
|
|
166
|
+
{ name: "citation", type: "text" },
|
|
167
|
+
{ name: "doi", type: "text" },
|
|
168
|
+
{ name: "url", type: "text", access: { read: url }, admin: { description: "The source's own page for this record. Shown only where the host allows." } },
|
|
169
|
+
...relation("sourceRelease", o.relations?.sourceReleases, { admin: { description: "The release this sample came in with, when it was imported." } }),
|
|
170
|
+
...relation("importRun", o.relations?.importRuns, { admin: { description: "The run that created it, for the audit trail." } })
|
|
171
|
+
]
|
|
172
|
+
},
|
|
173
|
+
rawReads: {
|
|
174
|
+
name: "rawReads",
|
|
175
|
+
type: "array",
|
|
176
|
+
admin: { description: "Where the raw reads are, never the reads themselves. The host's own download rules apply." },
|
|
177
|
+
fields: [
|
|
178
|
+
{ name: "pointer", type: "text", required: true, admin: { description: "An SRA run accession, a URL or the host's own storage key." } },
|
|
179
|
+
{ name: "sha256", type: "text", required: true, admin: { description: "Checked whenever the file is fetched." } },
|
|
180
|
+
{ name: "bytes", type: "number" },
|
|
181
|
+
{ name: "tier", type: "select", required: true, options: [...READ_TIERS], admin: { description: "External: the source holds it, no copy here. Cache: a copy that may be cleared. Hot and deep-archive: the host's own reads." } },
|
|
182
|
+
{ name: "fetchedAt", type: "date", admin: { description: "Last time the cache held it." } }
|
|
183
|
+
]
|
|
184
|
+
},
|
|
185
|
+
ecoregion: {
|
|
186
|
+
name: "ecoregion",
|
|
187
|
+
type: "group",
|
|
188
|
+
admin: { description: "The most any page may show of where a sample came from. Precise localities live in the host's own collection, never here." },
|
|
189
|
+
fields: [
|
|
190
|
+
realm("land", "RESOLVE Ecoregions 2017"),
|
|
191
|
+
realm("marine", "Marine Ecoregions of the World 2007"),
|
|
192
|
+
realm("freshwater", "Freshwater Ecoregions of the World 2008"),
|
|
193
|
+
{ name: "source", type: "select", options: ["lookup", "curator", "source-record"], admin: { description: "How the ecoregion was found: a lookup from the locality, a curator, or the source record itself." } }
|
|
194
|
+
]
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
var group = (doc, data, name) => ({ ...doc?.[name] ?? {}, ...data[name] ?? {} });
|
|
199
|
+
var sampleRules = (c) => async ({ data, originalDoc, operation, req }) => {
|
|
200
|
+
const coordinate = findCoordinate(data);
|
|
201
|
+
if (coordinate !== void 0) fail(`Samples never hold coordinates, and ${coordinate || "this sample"} holds one or reads like one. Keep precise localities in your own collection, outside the plugin.`);
|
|
202
|
+
const doc = { ...originalDoc, ...data };
|
|
203
|
+
const origin = String(doc.origin ?? "internal");
|
|
204
|
+
const external = group(originalDoc, data, "external");
|
|
205
|
+
if (origin === "internal") {
|
|
206
|
+
if (hasValue(external)) fail("An internal sample has no external source. Record a sample from a paper, database, panel or institution with origin set to external.");
|
|
207
|
+
if (!hasValue(doc.source)) fail("An internal sample needs how its material arrived: kit, upload or historic.");
|
|
208
|
+
} else {
|
|
209
|
+
if (c.hasKit && hasValue(doc.kit)) fail("An external sample has no kit. Kits are the host's own material.");
|
|
210
|
+
if (hasValue(doc.consent)) fail("An external sample has no keeper consent. Its terms are its data license.");
|
|
211
|
+
if (hasValue(doc.source)) fail("An external sample has no source; that field says how the host's own material arrived.");
|
|
212
|
+
if (!hasValue(external.sourceType)) fail("An external sample needs its source type: paper, public database, validated panel or institution.");
|
|
213
|
+
if (!hasValue(external.dataLicense)) {
|
|
214
|
+
external.dataLicense = "unknown";
|
|
215
|
+
data.external = { ...data.external, dataLicense: "unknown" };
|
|
216
|
+
}
|
|
217
|
+
const key = sourceKeyOf(external.database, external.accession);
|
|
218
|
+
const sent = { ...data.external };
|
|
219
|
+
delete sent.sourceKey;
|
|
220
|
+
const hadKey = operation === "update" && hasValue(originalDoc?.external?.sourceKey);
|
|
221
|
+
data.external = key ? { ...sent, sourceKey: key } : hadKey && req.payload.db.name !== "mongoose" ? { ...sent, sourceKey: null } : sent;
|
|
222
|
+
if (key) {
|
|
223
|
+
const where = { and: [{ "external.sourceKey": { equals: key } }, ...operation === "update" && originalDoc?.id != null ? [{ id: { not_equals: originalDoc.id } }] : []] };
|
|
224
|
+
const taken = await req.payload.find({ collection: c.samples, where, limit: 1, depth: 0, overrideAccess: true });
|
|
225
|
+
if (taken.docs.length) fail(duplicateMessage(external.database, external.accession));
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
const terms = licenseTerms(origin === "external" ? String(external.dataLicense) : "cc0");
|
|
229
|
+
for (const read of doc.rawReads ?? []) {
|
|
230
|
+
const sha = String(read.sha256 ?? "").replace(/^sha256:/i, "").toLowerCase();
|
|
231
|
+
if (!SHA256.test(sha)) fail(`A raw read's SHA-256 is missing or malformed (${String(read.pointer ?? "no pointer")}).`);
|
|
232
|
+
read.sha256 = sha;
|
|
233
|
+
const tier = String(read.tier);
|
|
234
|
+
if (origin === "internal" && (tier === "external" || tier === "cache")) fail("The host's own reads are kept as hot or deep-archive, never as an outside pointer or a cache copy only.");
|
|
235
|
+
if (origin === "external" && (tier === "hot" || tier === "deep-archive")) fail("An external sample's reads stay the source's: external, or a cache copy that may be cleared.");
|
|
236
|
+
if (origin === "external" && tier !== "external" && !terms.keepCopy) fail("This source's data license is unknown, so only a pointer may be kept, with no copy, until a curator sets the license.");
|
|
237
|
+
}
|
|
238
|
+
const eco = group(originalDoc, data, "ecoregion");
|
|
239
|
+
for (const name of REALMS) {
|
|
240
|
+
const value = eco[name];
|
|
241
|
+
if (!hasValue(value)) continue;
|
|
242
|
+
const pin = c.ecoregions[name];
|
|
243
|
+
if (!hasValue(value.dataset) || !hasValue(value.version)) fail(`A ${name} ecoregion needs the dataset and version it came from.`);
|
|
244
|
+
if (pin && (value.dataset !== pin.dataset || value.version !== pin.version)) fail(`This site's ${name} ecoregions are ${pin.dataset} ${pin.version}; ${value.dataset} ${value.version} isn't that set.`);
|
|
245
|
+
}
|
|
246
|
+
return data;
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
// src/records.ts
|
|
250
|
+
import { assessRead, ChromatogramError, parseFasta, readAbif, sha256Hex, sha256HexBytes } from "@extantape/onephylogeny-core";
|
|
251
|
+
import { APIError as APIError2 } from "payload";
|
|
252
|
+
var CUSTOM_KEY = "onePhylogenyRecords";
|
|
253
|
+
var DNA = /^[ACGTRYKMSWBDHVN]+$/;
|
|
254
|
+
var DEFAULT_LENGTH = { minLength: 100, maxLength: 5e4 };
|
|
255
|
+
var fail2 = (message) => {
|
|
256
|
+
throw new APIError2(message, 400, void 0, true);
|
|
257
|
+
};
|
|
258
|
+
var idOf = (v) => v && typeof v === "object" ? String(v.id) : v == null ? void 0 : String(v);
|
|
259
|
+
var relation2 = (name, relationTo, extra = {}) => relationTo ? [{ name, type: "relationship", relationTo, index: true, ...extra }] : [];
|
|
260
|
+
var comparable = (v) => {
|
|
261
|
+
if (v == null) return null;
|
|
262
|
+
if (typeof v !== "object") return String(v);
|
|
263
|
+
if (Array.isArray(v)) return v.map(comparable);
|
|
264
|
+
if ("id" in v) return String(v.id);
|
|
265
|
+
const set = Object.entries(v).filter(([, x]) => x != null).sort(([a], [b]) => a.localeCompare(b));
|
|
266
|
+
return set.length ? Object.fromEntries(set.map(([k, x]) => [k, comparable(x)])) : null;
|
|
267
|
+
};
|
|
268
|
+
var locked = (fields, message) => ({ data, originalDoc, operation }) => {
|
|
269
|
+
if (operation === "update") {
|
|
270
|
+
for (const f of fields) if (f in data && JSON.stringify(comparable(data[f])) !== JSON.stringify(comparable(originalDoc[f]))) fail2(message);
|
|
271
|
+
}
|
|
272
|
+
return data;
|
|
273
|
+
};
|
|
274
|
+
function recordCollections(o, base) {
|
|
275
|
+
const samples = o.slugs?.samples ?? "samples";
|
|
276
|
+
const sequences = o.slugs?.sequences ?? "sequences";
|
|
277
|
+
const manage = base.manage;
|
|
278
|
+
const read = anyOf(manage, o.readAccess);
|
|
279
|
+
const access = { read, create: manage, update: manage, delete: () => false };
|
|
280
|
+
const tenantField = o.tenantField ?? "tenant";
|
|
281
|
+
const ext = externalFields(o.external ?? {});
|
|
282
|
+
const sampleCollection = {
|
|
283
|
+
slug: samples,
|
|
284
|
+
labels: { singular: "Sample", plural: "Samples" },
|
|
285
|
+
admin: { group: "Genetics", defaultColumns: ["subject", "origin", "source", "kit", "createdAt"] },
|
|
286
|
+
access,
|
|
287
|
+
fields: [
|
|
288
|
+
...relation2("subject", base.subject, { required: true }),
|
|
289
|
+
ext.origin,
|
|
290
|
+
...relation2("kit", o.relations?.kit, { admin: { condition: whenInternal } }),
|
|
291
|
+
...relation2("taxon", base.taxa),
|
|
292
|
+
{ name: "source", type: "select", options: ["kit", "upload", "historic"], admin: { condition: whenInternal, description: "How the host's own material arrived. Internal samples only." } },
|
|
293
|
+
{ name: "material", type: "text", admin: { description: "What was sampled, such as a shell scrape or blood." } },
|
|
294
|
+
{ name: "collectedAt", type: "date", admin: { description: "For an external sample, see collectionDatePrecision for how much of it to trust." } },
|
|
295
|
+
{ name: "consent", type: "text", admin: { condition: whenInternal, description: "The keeper's consent, as recorded with the kit or upload. Internal samples only." } },
|
|
296
|
+
ext.external,
|
|
297
|
+
ext.rawReads,
|
|
298
|
+
ext.ecoregion
|
|
299
|
+
],
|
|
300
|
+
hooks: { beforeChange: [
|
|
301
|
+
locked(["subject", "kit", "source", "origin", tenantField], "A sample's animal, kit, source, origin and site can't change. Record a new sample instead."),
|
|
302
|
+
sampleRules({ samples, hasKit: Boolean(o.relations?.kit), ecoregions: o.ecoregions ?? {} })
|
|
303
|
+
] }
|
|
304
|
+
};
|
|
305
|
+
const sequenceCollection = {
|
|
306
|
+
slug: sequences,
|
|
307
|
+
labels: { singular: "Sequence", plural: "Sequences" },
|
|
308
|
+
admin: { group: "Genetics", useAsTitle: "recordId", defaultColumns: ["recordId", "marker", "status", "length", "createdAt"] },
|
|
309
|
+
access,
|
|
310
|
+
fields: [
|
|
311
|
+
{ name: "sample", type: "relationship", relationTo: samples, required: true, index: true },
|
|
312
|
+
{ name: "marker", type: "text", required: true, index: true },
|
|
313
|
+
...relation2("lab", o.relations?.lab),
|
|
314
|
+
...relation2("file", base.files, { admin: { description: "The file the lab sent. It stays the record of what was received." } }),
|
|
315
|
+
{ name: "sha256", type: "text", required: true, index: true, admin: { description: "SHA-256 of the file, checked against its text when it was registered." } },
|
|
316
|
+
{ name: "recordId", type: "text", admin: { description: "The FASTA header the lab gave this sequence." } },
|
|
317
|
+
{ name: "residues", type: "textarea", required: true, admin: { description: "The bases, cleaned of gaps and line breaks. Used for analysis." } },
|
|
318
|
+
{ name: "length", type: "number", required: true },
|
|
319
|
+
{ name: "status", type: "select", required: true, defaultValue: "received", index: true, options: ["received", "assigned", "not-assessable"] },
|
|
320
|
+
{ name: "statusReason", type: "text", admin: { description: "Why it couldn't be assessed, in plain words." } },
|
|
321
|
+
{
|
|
322
|
+
name: "trace",
|
|
323
|
+
type: "group",
|
|
324
|
+
admin: { description: "Set when the sequence came from a Sanger chromatogram (.ab1): how the read was judged. Empty for FASTA." },
|
|
325
|
+
fields: [
|
|
326
|
+
{ name: "status", type: "select", options: ["usable"], admin: { description: "Only usable reads are stored; failed and too-short reads are refused." } },
|
|
327
|
+
{ name: "keptStart", type: "number", admin: { description: "First kept base of the raw read, counting from 1." } },
|
|
328
|
+
{ name: "keptEnd", type: "number", admin: { description: "Last kept base of the raw read." } },
|
|
329
|
+
{ name: "rawLength", type: "number" },
|
|
330
|
+
{ name: "meanQuality", type: "number", admin: { description: "Mean Phred quality of the kept bases." } },
|
|
331
|
+
{ name: "maskedBases", type: "number", admin: { description: "Kept bases below Q20, stored as N." } },
|
|
332
|
+
{ name: "mixedPeaks", type: "number", admin: { description: "Positions with a strong second peak. Empty when the file has no traces to check." } }
|
|
333
|
+
]
|
|
334
|
+
}
|
|
335
|
+
],
|
|
336
|
+
hooks: { beforeChange: [locked(["sample", "marker", "file", "sha256", "residues", "recordId", "length", "trace", tenantField], "A sequence can't be edited. Register the corrected file instead.")] }
|
|
337
|
+
};
|
|
338
|
+
const config = {
|
|
339
|
+
samples,
|
|
340
|
+
sequences,
|
|
341
|
+
panels: base.panels,
|
|
342
|
+
assignments: base.assignments,
|
|
343
|
+
tenantField,
|
|
344
|
+
markers: o.markers,
|
|
345
|
+
subject: base.subject,
|
|
346
|
+
hasTaxa: Boolean(base.taxa),
|
|
347
|
+
hasKit: Boolean(o.relations?.kit),
|
|
348
|
+
hasLab: Boolean(o.relations?.lab),
|
|
349
|
+
hasFiles: Boolean(base.files),
|
|
350
|
+
againstShown: base.againstShown
|
|
351
|
+
};
|
|
352
|
+
return { collections: [sampleCollection, sequenceCollection], config, customKey: CUSTOM_KEY };
|
|
353
|
+
}
|
|
354
|
+
var configOf = (payload) => {
|
|
355
|
+
const c = payload.config.custom?.[CUSTOM_KEY];
|
|
356
|
+
if (!c) throw new Error("OnePhylogeny samples and sequences aren't turned on. Pass `records` to the plugin.");
|
|
357
|
+
return c;
|
|
358
|
+
};
|
|
359
|
+
function readSingleSequence(text, marker, markers) {
|
|
360
|
+
if (markers && !markers[marker]) fail2(`This site doesn't test the marker "${marker}".`);
|
|
361
|
+
let entries;
|
|
362
|
+
try {
|
|
363
|
+
entries = parseFasta(text.replace(/^/, ""));
|
|
364
|
+
} catch {
|
|
365
|
+
return fail2(`This file isn't FASTA: it has bases before the first ">" header line.`);
|
|
366
|
+
}
|
|
367
|
+
if (!entries.length) fail2(`This file is empty or has no ">" header line, so it isn't FASTA.`);
|
|
368
|
+
if (entries.length > 1) fail2(`This file holds ${entries.length} sequences. Send one file per kit, with one sequence in it.`);
|
|
369
|
+
const entry = entries[0];
|
|
370
|
+
return { recordId: entry.id, residues: checkResidues(entry.sequence.replace(/[\s\-.]/g, "").toUpperCase(), marker, markers) };
|
|
371
|
+
}
|
|
372
|
+
function checkResidues(residues, marker, markers) {
|
|
373
|
+
if (markers && !markers[marker]) fail2(`This site doesn't test the marker "${marker}".`);
|
|
374
|
+
const { minLength, maxLength } = { ...DEFAULT_LENGTH, ...markers?.[marker] };
|
|
375
|
+
if (!residues) fail2("This file's sequence is empty.");
|
|
376
|
+
if (!DNA.test(residues)) {
|
|
377
|
+
const bad = [...new Set(residues.replace(/[ACGTRYKMSWBDHVN]/g, ""))].slice(0, 5).join(" ");
|
|
378
|
+
fail2(`This sequence has characters that aren't DNA bases: ${bad}.`);
|
|
379
|
+
}
|
|
380
|
+
if (residues.length < minLength) fail2(`This sequence is ${residues.length} bases long, shorter than the ${minLength} needed for ${marker}.`);
|
|
381
|
+
if (residues.length > maxLength) fail2(`This sequence is ${residues.length} bases long, longer than the ${maxLength} expected for ${marker}.`);
|
|
382
|
+
const unresolved = (residues.match(/[^ACGT]/g) ?? []).length;
|
|
383
|
+
if (unresolved > residues.length / 2) fail2(`More than half of this sequence's bases are unresolved (${unresolved} of ${residues.length}).`);
|
|
384
|
+
return residues;
|
|
385
|
+
}
|
|
386
|
+
function readTrace(bytes, marker, markers) {
|
|
387
|
+
let read;
|
|
388
|
+
try {
|
|
389
|
+
read = readAbif(bytes);
|
|
390
|
+
} catch (e) {
|
|
391
|
+
return fail2(e instanceof ChromatogramError ? `${e.message}.` : "This file couldn't be read as a chromatogram (.ab1).");
|
|
392
|
+
}
|
|
393
|
+
const a = assessRead(read);
|
|
394
|
+
if (a.status === "failed") fail2(`This read failed, so it isn't stored or tested. ${a.notes[0]}`);
|
|
395
|
+
if (a.status === "short") fail2(`This read is too short to use: only ${a.sequence.length} bases are good enough, under the ${a.settings.minLength} needed. It isn't stored or tested.`);
|
|
396
|
+
const residues = checkResidues(a.sequence, marker, markers);
|
|
397
|
+
return {
|
|
398
|
+
recordId: read.sampleName,
|
|
399
|
+
residues,
|
|
400
|
+
trace: { status: "usable", keptStart: a.kept.start + 1, keptEnd: a.kept.end, rawLength: a.rawLength, meanQuality: a.meanQuality, maskedBases: a.maskedBases, mixedPeaks: a.mixedPeaks ? a.mixedPeaks.length : null }
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
function registerSequence(payload, input) {
|
|
404
|
+
return register(payload, input, (sha256) => {
|
|
405
|
+
if (sha256Hex(input.text) !== sha256) fail2("This file's text doesn't match its SHA-256. It may have changed after upload; upload it again.");
|
|
406
|
+
return readSingleSequence(input.text, input.marker, configOf(payload).markers);
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
function registerTrace(payload, input) {
|
|
410
|
+
return register(payload, input, (sha256) => {
|
|
411
|
+
if (sha256HexBytes(input.bytes) !== sha256) fail2("This file doesn't match its SHA-256. It may have changed after upload; upload it again.");
|
|
412
|
+
const { recordId, residues, trace } = readTrace(input.bytes, input.marker, configOf(payload).markers);
|
|
413
|
+
return { recordId: recordId ?? input.fileName ?? "chromatogram", residues, trace };
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
async function register(payload, input, read) {
|
|
417
|
+
const c = configOf(payload);
|
|
418
|
+
const opts = { req: input.req, overrideAccess: true, depth: 0 };
|
|
419
|
+
const sha256 = input.sha256.replace(/^sha256:/i, "").toLowerCase();
|
|
420
|
+
if (!/^[0-9a-f]{64}$/.test(sha256)) fail2("The file's SHA-256 is missing or malformed.");
|
|
421
|
+
const { recordId, residues, trace } = read(sha256);
|
|
422
|
+
if ((input.source ?? "kit") === "kit" && input.kit == null) fail2("A kit sample needs its kit.");
|
|
423
|
+
if (input.animal == null || input.animal === "") fail2("This kit isn't linked to an animal yet. It has to be activated first.");
|
|
424
|
+
let taxon = input.taxon;
|
|
425
|
+
if (taxon == null && c.hasTaxa) {
|
|
426
|
+
const subject = c.subject ? await payload.findByID({ collection: c.subject, id: input.animal, ...opts }).catch(() => null) : null;
|
|
427
|
+
taxon = idOf(subject?.taxon);
|
|
428
|
+
}
|
|
429
|
+
if (c.hasTaxa && taxon == null) fail2("This animal has no species recorded, so its sequence can't be matched to a panel.");
|
|
430
|
+
let sample;
|
|
431
|
+
if (input.kit != null && c.hasKit) {
|
|
432
|
+
sample = (await payload.find({ collection: c.samples, where: { kit: { equals: input.kit } }, limit: 1, ...opts })).docs[0];
|
|
433
|
+
if (sample && idOf(sample.subject) !== String(input.animal)) fail2("This kit is already recorded for another animal.");
|
|
434
|
+
}
|
|
435
|
+
if (sample) {
|
|
436
|
+
const existing = (await payload.find({ collection: c.sequences, where: { and: [{ sample: { equals: sample.id } }, { sha256: { equals: sha256 } }] }, limit: 1, ...opts })).docs[0];
|
|
437
|
+
if (existing) return { sample, sequence: existing, created: false };
|
|
438
|
+
} else {
|
|
439
|
+
sample = await payload.create({ collection: c.samples, data: {
|
|
440
|
+
...c.subject ? { subject: input.animal } : {},
|
|
441
|
+
...c.hasKit && input.kit != null ? { kit: input.kit } : {},
|
|
442
|
+
...c.hasTaxa ? { taxon } : {},
|
|
443
|
+
source: input.source ?? "kit",
|
|
444
|
+
...input.collectedAt ? { collectedAt: input.collectedAt } : {},
|
|
445
|
+
...input.tenant != null ? { [c.tenantField]: input.tenant } : {}
|
|
446
|
+
}, ...opts });
|
|
447
|
+
}
|
|
448
|
+
const sequence = await payload.create({ collection: c.sequences, data: {
|
|
449
|
+
sample: sample.id,
|
|
450
|
+
marker: input.marker,
|
|
451
|
+
sha256,
|
|
452
|
+
recordId,
|
|
453
|
+
residues,
|
|
454
|
+
length: residues.length,
|
|
455
|
+
status: "received",
|
|
456
|
+
...trace ? { trace } : {},
|
|
457
|
+
...c.hasLab && input.lab != null ? { lab: input.lab } : {},
|
|
458
|
+
...c.hasFiles && input.file != null ? { file: input.file } : {},
|
|
459
|
+
...input.tenant != null ? { [c.tenantField]: input.tenant } : {}
|
|
460
|
+
}, ...opts });
|
|
461
|
+
return { sample, sequence, created: true };
|
|
462
|
+
}
|
|
463
|
+
function summarize(result, panel) {
|
|
464
|
+
const label = (id) => panel.groups?.find((g) => g.groupId === id)?.label ?? id;
|
|
465
|
+
const consistent = result.findings.filter((f) => f.status === "consistent").map((f) => label(f.group));
|
|
466
|
+
if (consistent.length === 1) return `Consistent with ${consistent[0]}`;
|
|
467
|
+
if (consistent.length > 1) return `Consistent with ${consistent.slice(0, -1).join(", ")} or ${consistent.at(-1)}`;
|
|
468
|
+
return "No single lineage";
|
|
469
|
+
}
|
|
470
|
+
async function assignWaiting(payload, args) {
|
|
471
|
+
const c = configOf(payload);
|
|
472
|
+
const opts = { req: args.req, overrideAccess: true, depth: 0 };
|
|
473
|
+
const tally = { assigned: 0, notAssessable: 0, noPanel: 0, skipped: 0 };
|
|
474
|
+
const skippedPanels = /* @__PURE__ */ new Map();
|
|
475
|
+
const waiting = await payload.find({ collection: c.sequences, where: { status: { equals: "received" } }, sort: "createdAt", limit: args.limit ?? 200, ...opts });
|
|
476
|
+
const usable = c.againstShown ? { or: [{ status: { equals: "active" } }, { and: [{ status: { equals: "candidate" } }, { shownAsExploratory: { equals: true } }] }] } : { status: { equals: "active" } };
|
|
477
|
+
for (const seq of waiting.docs) {
|
|
478
|
+
const sample = await payload.findByID({ collection: c.samples, id: idOf(seq.sample), ...opts });
|
|
479
|
+
const taxon = idOf(sample.taxon);
|
|
480
|
+
const found = await payload.find({ collection: c.panels, where: { and: [{ marker: { equals: seq.marker } }, usable] }, sort: "-createdAt", limit: 50, ...opts });
|
|
481
|
+
const fits = found.docs.filter((p) => !c.hasTaxa || !p.taxa?.length || p.taxa.map(idOf).includes(taxon));
|
|
482
|
+
const panel = fits.find((p) => p.status === "active") ?? fits[0];
|
|
483
|
+
if (!panel) {
|
|
484
|
+
tally.noPanel++;
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
487
|
+
const already = await payload.find({ collection: c.assignments, where: { and: [{ sequence: { equals: seq.id } }, { panel: { equals: panel.id } }] }, limit: 1, ...opts });
|
|
488
|
+
if (already.docs.length) {
|
|
489
|
+
await payload.update({ collection: c.sequences, id: seq.id, data: { status: "assigned" }, ...opts });
|
|
490
|
+
continue;
|
|
491
|
+
}
|
|
492
|
+
const outcome = await args.evaluate({ residues: String(seq.residues), queryId: String(seq.id), panel });
|
|
493
|
+
if ("skip" in outcome) {
|
|
494
|
+
tally.skipped++;
|
|
495
|
+
skippedPanels.set(String(panel.id), { panel: String(panel.id), key: String(panel.key), version: String(panel.version), reason: outcome.skip });
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
const { result, problems } = outcome;
|
|
499
|
+
if (!result) {
|
|
500
|
+
await payload.update({ collection: c.sequences, id: seq.id, data: { status: "not-assessable", statusReason: (problems.join("; ") || "The panel's checks refused this sequence.").slice(0, 1e3) }, ...opts });
|
|
501
|
+
tally.notAssessable++;
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
504
|
+
const tenant = sample[c.tenantField];
|
|
505
|
+
await payload.create({ collection: c.assignments, data: {
|
|
506
|
+
...c.subject ? { subject: idOf(sample.subject) } : {},
|
|
507
|
+
sequence: seq.id,
|
|
508
|
+
panel: panel.id,
|
|
509
|
+
summary: summarize(result, panel),
|
|
510
|
+
result,
|
|
511
|
+
...tenant != null ? { [c.tenantField]: idOf(tenant) } : {}
|
|
512
|
+
}, ...opts });
|
|
513
|
+
await payload.update({ collection: c.sequences, id: seq.id, data: { status: "assigned" }, ...opts });
|
|
514
|
+
tally.assigned++;
|
|
515
|
+
}
|
|
516
|
+
return { ...tally, checked: waiting.docs.length, skippedPanels: [...skippedPanels.values()] };
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// src/index.ts
|
|
520
|
+
import { APIError as APIError3 } from "payload";
|
|
521
|
+
|
|
522
|
+
// src/import.ts
|
|
523
|
+
import { parseGenBank, toSequenceRecord } from "@extantape/onephylogeny-core";
|
|
524
|
+
var MONTHS = /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)$/i;
|
|
525
|
+
var DIRECT_SUBMISSION = /^direct submission$/i;
|
|
526
|
+
function datePrecision(value) {
|
|
527
|
+
const v = (value ?? "").trim().split(/[T/\s]/)[0] ?? "";
|
|
528
|
+
if (/^\d{4}$/.test(v)) return "year";
|
|
529
|
+
if (/^\d{4}-\d{2}$/.test(v) || /^[A-Za-z]{3}-\d{4}$/.test(v) && MONTHS.test(v.slice(0, 3))) return "month";
|
|
530
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(v) || /^\d{1,2}-[A-Za-z]{3}-\d{4}$/.test(v) && MONTHS.test(v.split("-")[1])) return "day";
|
|
531
|
+
return "unknown";
|
|
532
|
+
}
|
|
533
|
+
function splitVoucher(v) {
|
|
534
|
+
const at = v.search(/[:\s]/);
|
|
535
|
+
return at > 0 ? { institution: v.slice(0, at), catalogNumber: v.slice(at + 1).trim() } : { catalogNumber: v };
|
|
536
|
+
}
|
|
537
|
+
function genBankToExternalSample(rec, o = {}) {
|
|
538
|
+
const source = rec.features.find((f) => f.key === "source")?.qualifiers ?? {};
|
|
539
|
+
const flat = toSequenceRecord(rec);
|
|
540
|
+
const published = rec.references.find((r) => r.title && !DIRECT_SUBMISSION.test(r.title.trim()));
|
|
541
|
+
const ref = published ?? rec.references[0];
|
|
542
|
+
const parts = published ? [ref.authors, ref.title, ref.journal] : [ref?.authors, ref?.title];
|
|
543
|
+
const citation = ref ? parts.filter(Boolean).map((v) => String(v).replace(/\.$/, "")).join(". ") : void 0;
|
|
544
|
+
const collectedBy = source.collected_by?.[0];
|
|
545
|
+
const precision = source.collection_date?.[0] ? datePrecision(source.collection_date[0]) : void 0;
|
|
546
|
+
const versioned = rec.version || rec.accession;
|
|
547
|
+
const external = {
|
|
548
|
+
sourceType: "public-database",
|
|
549
|
+
database: "GenBank",
|
|
550
|
+
accession: rec.accession,
|
|
551
|
+
dataLicense: "unknown",
|
|
552
|
+
url: `https://www.ncbi.nlm.nih.gov/nuccore/${encodeURIComponent(versioned)}`,
|
|
553
|
+
...source.specimen_voucher?.[0] ? { voucher: splitVoucher(source.specimen_voucher[0]) } : {},
|
|
554
|
+
...collectedBy ? { collector: collectedBy } : {},
|
|
555
|
+
...precision ? { collectionDatePrecision: precision } : {},
|
|
556
|
+
...citation ? { citation } : {}
|
|
557
|
+
};
|
|
558
|
+
return {
|
|
559
|
+
origin: "external",
|
|
560
|
+
external,
|
|
561
|
+
rawReads: [{ pointer: versioned, sha256: flat.sequenceSha256, tier: o.tier ?? "external" }]
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
async function importGenBank(payload, text, o) {
|
|
565
|
+
const collection = o.samples ?? "samples";
|
|
566
|
+
const report = { created: [], duplicates: [], failed: [] };
|
|
567
|
+
const existing = async (accession) => {
|
|
568
|
+
const where = { "external.sourceKey": { equals: sourceKeyOf("GenBank", accession) } };
|
|
569
|
+
const found = (await payload.find({ collection, where, limit: 1, depth: 0, overrideAccess: true })).docs[0];
|
|
570
|
+
if (!found) return void 0;
|
|
571
|
+
if (!o.req) return { id: found.id, readable: true };
|
|
572
|
+
const seen = await payload.findByID({ collection, id: found.id, depth: 0, req: o.req, overrideAccess: false, disableErrors: true });
|
|
573
|
+
return { id: found.id, readable: Boolean(seen) };
|
|
574
|
+
};
|
|
575
|
+
const duplicate = (accession, found) => {
|
|
576
|
+
if (found.readable) report.duplicates.push({ accession, id: found.id });
|
|
577
|
+
else report.failed.push({ accession, reason: duplicateMessage("GenBank", accession) });
|
|
578
|
+
};
|
|
579
|
+
for (const rec of parseGenBank(text)) {
|
|
580
|
+
const found = await existing(rec.accession);
|
|
581
|
+
if (found) {
|
|
582
|
+
duplicate(rec.accession, found);
|
|
583
|
+
continue;
|
|
584
|
+
}
|
|
585
|
+
try {
|
|
586
|
+
const subject = typeof o.subject === "function" ? await o.subject(rec) : o.subject;
|
|
587
|
+
const data = { ...genBankToExternalSample(rec, { tier: o.tier }), subject, ...o.extra?.(rec) ?? {} };
|
|
588
|
+
const made = await payload.create({ collection, data, depth: 0, ...o.req ? { req: o.req, overrideAccess: false } : {} });
|
|
589
|
+
report.created.push({ accession: rec.accession, id: made.id });
|
|
590
|
+
} catch (e) {
|
|
591
|
+
const raced = await existing(rec.accession);
|
|
592
|
+
if (raced) duplicate(rec.accession, raced);
|
|
593
|
+
else report.failed.push({ accession: rec.accession, reason: e instanceof Error ? e.message : String(e) });
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
return report;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// src/index.ts
|
|
600
|
+
var PANEL_TRANSITIONS = { candidate: ["active", "withdrawn"], active: ["superseded", "withdrawn"], superseded: ["withdrawn"], withdrawn: [] };
|
|
601
|
+
var LOCKED_PANEL_FIELDS = ["key", "version", "marker", "checksum", "artifact", "importRun", "taxa", "groups", "notCovered", "validatedScope"];
|
|
602
|
+
var REVIEW_TRANSITIONS = { pending: ["approved", "rejected"], approved: ["withdrawn"], rejected: [], withdrawn: [] };
|
|
603
|
+
var COORDINATES2 = /^(lat|lon|lng|latitude|longitude|latlon|lat_lon|coordinates?)$/i;
|
|
604
|
+
var hasCoordinates = (value) => {
|
|
605
|
+
if (Array.isArray(value)) return value.some(hasCoordinates);
|
|
606
|
+
if (!value || typeof value !== "object") return false;
|
|
607
|
+
return Object.entries(value).some(([k, v]) => COORDINATES2.test(k) || hasCoordinates(v));
|
|
608
|
+
};
|
|
609
|
+
var fail3 = (message) => {
|
|
610
|
+
throw new APIError3(message, 400, void 0, true);
|
|
611
|
+
};
|
|
612
|
+
var idOf2 = (v) => v && typeof v === "object" ? String(v.id) : v == null ? void 0 : String(v);
|
|
613
|
+
var same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
|
|
614
|
+
var stripIds = (rows) => Array.isArray(rows) ? rows.map((r) => {
|
|
615
|
+
const { id: _id, ...rest } = r;
|
|
616
|
+
return rest;
|
|
617
|
+
}) : rows;
|
|
618
|
+
var stamp = (v) => v == null || v === "" ? "" : v instanceof Date ? v.toISOString() : String(v);
|
|
619
|
+
var ACTIVATION_FIELDS = ["activatedBy", "activatedAt"];
|
|
620
|
+
var panelBeforeChange = ({ data, originalDoc, operation, req }) => {
|
|
621
|
+
const leaving = operation === "update" && String(data.status ?? originalDoc.status) !== "candidate";
|
|
622
|
+
if (leaving) {
|
|
623
|
+
if (data.shownAsExploratory === true && String(originalDoc.status) !== "candidate") fail3("Only a candidate panel can be shown as exploratory.");
|
|
624
|
+
data.shownAsExploratory = false;
|
|
625
|
+
}
|
|
626
|
+
if (hasCoordinates(data.groups)) fail3("Panels use generalized regions and never hold coordinates.");
|
|
627
|
+
if (operation === "create") {
|
|
628
|
+
if ((data.status ?? "candidate") !== "candidate") fail3("A new panel starts as a candidate.");
|
|
629
|
+
if (ACTIVATION_FIELDS.some((f) => stamp(data[f]))) fail3("Who activated a panel, and when, are set by activating.");
|
|
630
|
+
return data;
|
|
631
|
+
}
|
|
632
|
+
const from = String(originalDoc.status);
|
|
633
|
+
const to = String(data.status ?? from);
|
|
634
|
+
if (to !== from && !PANEL_TRANSITIONS[from]?.includes(to)) fail3(`A panel can't go from ${from} to ${to}.`);
|
|
635
|
+
if (from === "candidate" && to === "active") {
|
|
636
|
+
if (!(data.validatedScope ?? originalDoc.validatedScope)?.length) fail3("A panel with no validated claims can't become active.");
|
|
637
|
+
if (!req.user) fail3("Activating a panel needs a signed-in person, who is recorded.");
|
|
638
|
+
data.activatedBy = String(req.user.id);
|
|
639
|
+
data.activatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
640
|
+
} else if (ACTIVATION_FIELDS.some((f) => f in data && stamp(data[f]) !== stamp(originalDoc[f]))) {
|
|
641
|
+
fail3("Who activated a panel, and when, are set by activating.");
|
|
642
|
+
}
|
|
643
|
+
if (from !== "candidate") {
|
|
644
|
+
for (const f of LOCKED_PANEL_FIELDS) {
|
|
645
|
+
if (!(f in data)) continue;
|
|
646
|
+
const changed = f === "groups" ? !same(stripIds(data[f]), stripIds(originalDoc[f])) : Array.isArray(data[f]) ? !same(data[f].map(idOf2), (originalDoc[f] ?? []).map(idOf2)) : idOf2(data[f]) !== idOf2(originalDoc[f]);
|
|
647
|
+
if (changed) fail3(`A ${from} panel can't be edited. Build a new version instead.`);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
return data;
|
|
651
|
+
};
|
|
652
|
+
var supersedeOthers = (panels) => async ({ doc, previousDoc, req }) => {
|
|
653
|
+
if (doc.status !== "active" || previousDoc?.status === "active") return doc;
|
|
654
|
+
const others = await req.payload.find({ collection: panels, where: { and: [{ key: { equals: doc.key } }, { status: { equals: "active" } }, { id: { not_equals: doc.id } }] }, limit: 100, depth: 0, req, overrideAccess: true });
|
|
655
|
+
for (const other of others.docs) await req.payload.update({ collection: panels, id: other.id, data: { status: "superseded" }, req, overrideAccess: true });
|
|
656
|
+
return doc;
|
|
657
|
+
};
|
|
658
|
+
var assignmentBeforeChange = (panels, againstShown, tenantField) => async ({ data, originalDoc, operation, req }) => {
|
|
659
|
+
if (operation === "create") {
|
|
660
|
+
if ((data.reviewStatus ?? "pending") !== "pending") fail3("A new result starts as pending review.");
|
|
661
|
+
const panel = await req.payload.findByID({ collection: panels, id: idOf2(data.panel), depth: 0, req, overrideAccess: true });
|
|
662
|
+
const shown = panel.status === "candidate" && panel.shownAsExploratory === true;
|
|
663
|
+
if (panel.status !== "active" && !(againstShown && shown)) fail3(againstShown ? "Results can only be made against an active panel, or a candidate shown as exploratory." : "Results can only be made against an active panel.");
|
|
664
|
+
data.panelStatus = panel.status;
|
|
665
|
+
data.panelShownAsExploratory = shown;
|
|
666
|
+
const result = data.result;
|
|
667
|
+
const problems = validateResult(result).filter((d) => d.severity === "error");
|
|
668
|
+
if (problems.length) fail3(problems.map((p) => p.message).join("; "));
|
|
669
|
+
if (result.panel.version !== panel.version || result.panel.checksum !== panel.checksum) fail3("This result was not made with this panel version.");
|
|
670
|
+
const found = new Set(result.findings.map((f) => f.group));
|
|
671
|
+
const missing = (panel.groups ?? []).filter((g) => !found.has(g.groupId)).map((g) => g.groupId);
|
|
672
|
+
if (missing.length) fail3(`Every group must be reported. Missing: ${missing.join(", ")}.`);
|
|
673
|
+
if (hasCoordinates(result)) fail3("Results never hold coordinates.");
|
|
674
|
+
return data;
|
|
675
|
+
}
|
|
676
|
+
const from = String(originalDoc.reviewStatus);
|
|
677
|
+
const to = String(data.reviewStatus ?? from);
|
|
678
|
+
for (const f of ["result", "panel", "sequence", "subject", "summary", "importRun"]) {
|
|
679
|
+
if (f in data && (f === "result" || f === "summary" ? !same(data[f], originalDoc[f]) : idOf2(data[f]) !== idOf2(originalDoc[f]))) fail3("A result can't be edited. Make a new one instead.");
|
|
680
|
+
}
|
|
681
|
+
if (tenantField in data && idOf2(data[tenantField]) !== idOf2(originalDoc[tenantField])) fail3("A result stays on the site it was made for.");
|
|
682
|
+
for (const f of ["panelStatus", "panelShownAsExploratory"]) {
|
|
683
|
+
if (f in data && !same(data[f], originalDoc[f])) fail3("The panel status a result was made against is set when it is made.");
|
|
684
|
+
}
|
|
685
|
+
if (to !== from) {
|
|
686
|
+
if (!REVIEW_TRANSITIONS[from]?.includes(to)) fail3(`A result can't go from ${from} to ${to}.`);
|
|
687
|
+
if (to === "approved") {
|
|
688
|
+
if (!req.user) fail3("Approving a result needs a signed-in reviewer.");
|
|
689
|
+
data.reviewer = String(req.user.id);
|
|
690
|
+
data.releasedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
691
|
+
}
|
|
692
|
+
} else {
|
|
693
|
+
if ("reviewer" in data && data.reviewer !== originalDoc.reviewer) fail3("The reviewer is set by approving.");
|
|
694
|
+
if ("releasedAt" in data && String(data.releasedAt) !== String(originalDoc.releasedAt)) fail3("The release date is set by approving.");
|
|
695
|
+
}
|
|
696
|
+
return data;
|
|
697
|
+
};
|
|
698
|
+
var relation3 = (name, relationTo, extra = {}) => relationTo ? [{ name, type: "relationship", relationTo, index: true, ...extra }] : [];
|
|
699
|
+
var checkedWhenMade = { validate: (value, options) => options.operation === "update" ? true : validateRelationship(value, options) };
|
|
700
|
+
var onePhylogeny = (options = {}) => (config) => {
|
|
701
|
+
const panels = options.slugs?.panels ?? "panels";
|
|
702
|
+
const assignments = options.slugs?.assignments ?? "assignments";
|
|
703
|
+
const tenantField = options.tenantField ?? options.records?.tenantField ?? "tenant";
|
|
704
|
+
const records = options.records ? recordCollections({ tenantField, ...options.records }, { panels, assignments, subject: options.relations?.subject, taxa: options.relations?.taxa, files: options.relations?.files, manage: options.manageAccess ?? (() => false), againstShown: options.resultsAgainst === "activeOrShown" }) : void 0;
|
|
705
|
+
const r = { ...options.relations, ...records && !options.relations?.sequence ? { sequence: records.config.sequences } : {} };
|
|
706
|
+
const group2 = options.group ?? "Genetics";
|
|
707
|
+
const manage = options.manageAccess ?? (() => false);
|
|
708
|
+
const review = options.reviewAccess ?? manage;
|
|
709
|
+
const readReleased = options.readReleasedAccess ?? (({ req }) => Boolean(req.user));
|
|
710
|
+
const againstShown = options.resultsAgainst === "activeOrShown";
|
|
711
|
+
const panelCollection = {
|
|
712
|
+
slug: panels,
|
|
713
|
+
labels: { singular: "Reference panel", plural: "Reference panels" },
|
|
714
|
+
admin: { group: group2, useAsTitle: "key", defaultColumns: ["key", "version", "status", "marker"] },
|
|
715
|
+
access: {
|
|
716
|
+
read: async (args) => {
|
|
717
|
+
const published = { status: { in: ["active", "superseded"] } };
|
|
718
|
+
const shown = { and: [{ status: { equals: "candidate" } }, { shownAsExploratory: { equals: true } }] };
|
|
719
|
+
return either(await manage(args), published, againstShown ? shown : false);
|
|
720
|
+
},
|
|
721
|
+
create: manage,
|
|
722
|
+
update: manage,
|
|
723
|
+
delete: () => false
|
|
724
|
+
},
|
|
725
|
+
fields: [
|
|
726
|
+
{ name: "key", type: "text", required: true, index: true, admin: { description: "Stays the same across versions of one panel." } },
|
|
727
|
+
{ name: "version", type: "text", required: true },
|
|
728
|
+
{ name: "status", type: "select", required: true, defaultValue: "candidate", index: true, options: ["candidate", "active", "superseded", "withdrawn"] },
|
|
729
|
+
{ name: "shownAsExploratory", type: "checkbox", defaultValue: false, index: true, admin: { description: "Show this candidate as exploratory, before review. Only candidates; cleared when it moves on." } },
|
|
730
|
+
{ name: "marker", type: "text", required: true },
|
|
731
|
+
{ name: "checksum", type: "text", required: true, index: true },
|
|
732
|
+
...relation3("taxa", r.taxa, { hasMany: true }),
|
|
733
|
+
...relation3("artifact", r.files, { admin: { description: "The full panel: JSON manifest and sequences." } }),
|
|
734
|
+
...relation3("importRun", r.importRuns),
|
|
735
|
+
{ name: "validatedScope", type: "text", hasMany: true, admin: { description: "The claims this panel is validated for. Pages show only these." } },
|
|
736
|
+
{ name: "notCovered", type: "text", hasMany: true },
|
|
737
|
+
{ name: "groups", type: "array", fields: [{ name: "groupId", type: "text", required: true }, { name: "label", type: "text", required: true }, { name: "regionName", type: "text", admin: { description: "A general region, never coordinates." } }] },
|
|
738
|
+
{ name: "activatedBy", type: "text", admin: { readOnly: true, description: "The signed-in user who activated this panel. Set by activating." } },
|
|
739
|
+
{ name: "activatedAt", type: "date", admin: { readOnly: true } }
|
|
740
|
+
],
|
|
741
|
+
hooks: { beforeChange: [panelBeforeChange], afterChange: [supersedeOthers(panels)] }
|
|
742
|
+
};
|
|
743
|
+
const assignmentCollection = {
|
|
744
|
+
slug: assignments,
|
|
745
|
+
labels: { singular: "Lineage result", plural: "Lineage results" },
|
|
746
|
+
admin: { group: group2, useAsTitle: "summary", defaultColumns: ["summary", "panel", "reviewStatus", "releasedAt"] },
|
|
747
|
+
access: {
|
|
748
|
+
// Managers and reviewers see what their own rules allow, including pending results; everyone else only released ones.
|
|
749
|
+
read: async (args) => {
|
|
750
|
+
const released2 = { reviewStatus: { equals: "approved" } };
|
|
751
|
+
const allowed = await readReleased(args);
|
|
752
|
+
return either(await manage(args), await review(args), allowed === true ? released2 : allowed ? { and: [released2, allowed] } : false);
|
|
753
|
+
},
|
|
754
|
+
create: manage,
|
|
755
|
+
update: review,
|
|
756
|
+
delete: () => false
|
|
757
|
+
},
|
|
758
|
+
fields: [
|
|
759
|
+
...relation3("subject", r.subject, checkedWhenMade),
|
|
760
|
+
...relation3("sequence", r.sequence, checkedWhenMade),
|
|
761
|
+
{ name: "panel", type: "relationship", relationTo: panels, required: true, index: true, ...checkedWhenMade },
|
|
762
|
+
{ name: "summary", type: "text", required: true },
|
|
763
|
+
{ name: "result", type: "json", required: true, admin: { description: "The OnePhylogeny result, stored exactly as computed." } },
|
|
764
|
+
...relation3("importRun", r.importRuns, checkedWhenMade),
|
|
765
|
+
{ name: "reviewStatus", type: "select", required: true, defaultValue: "pending", index: true, options: ["pending", "approved", "rejected", "withdrawn"] },
|
|
766
|
+
{ name: "reviewer", type: "text", admin: { readOnly: true } },
|
|
767
|
+
{ name: "releasedAt", type: "date", admin: { readOnly: true } },
|
|
768
|
+
{ name: "panelStatus", type: "text", admin: { readOnly: true, description: "The panel's status when this result was made." } },
|
|
769
|
+
{ name: "panelShownAsExploratory", type: "checkbox", admin: { readOnly: true } }
|
|
770
|
+
],
|
|
771
|
+
hooks: { beforeChange: [assignmentBeforeChange(panels, againstShown, tenantField)] }
|
|
772
|
+
};
|
|
773
|
+
const released = {
|
|
774
|
+
path: "/onephylogeny/released",
|
|
775
|
+
method: "get",
|
|
776
|
+
handler: async (req) => {
|
|
777
|
+
const subject = new URL(req.url ?? "", "http://x").searchParams.get("subject");
|
|
778
|
+
if (!subject || !r.subject) return Response.json({ error: "A subject is required" }, { status: 400 });
|
|
779
|
+
const found = await req.payload.find({ collection: assignments, where: { and: [{ subject: { equals: subject } }, { reviewStatus: { equals: "approved" } }] }, sort: "-releasedAt", limit: 20, depth: 1, req, overrideAccess: false });
|
|
780
|
+
return Response.json({ docs: found.docs });
|
|
781
|
+
}
|
|
782
|
+
};
|
|
783
|
+
return {
|
|
784
|
+
...config,
|
|
785
|
+
...records ? { db: withSourceKeyErrors(config.db, records.config.samples) } : {},
|
|
786
|
+
collections: [...config.collections ?? [], ...records?.collections ?? [], panelCollection, assignmentCollection],
|
|
787
|
+
endpoints: [...config.endpoints ?? [], released],
|
|
788
|
+
...records ? { custom: { ...config.custom, [records.customKey]: records.config } } : {}
|
|
789
|
+
};
|
|
790
|
+
};
|
|
791
|
+
export {
|
|
792
|
+
DATA_LICENSES,
|
|
793
|
+
READ_TIERS,
|
|
794
|
+
SOURCE_TYPES,
|
|
795
|
+
anyOf,
|
|
796
|
+
assignWaiting,
|
|
797
|
+
datePrecision,
|
|
798
|
+
either,
|
|
799
|
+
genBankToExternalSample,
|
|
800
|
+
importGenBank,
|
|
801
|
+
licenseTerms,
|
|
802
|
+
looksLikeCoordinates,
|
|
803
|
+
onePhylogeny,
|
|
804
|
+
readSingleSequence,
|
|
805
|
+
readTrace,
|
|
806
|
+
registerSequence,
|
|
807
|
+
registerTrace,
|
|
808
|
+
sourceKeyOf,
|
|
809
|
+
summarize
|
|
810
|
+
};
|