@captiveorigins/payload-plugin-onephylogeny 0.0.0-stage → 0.1.0-alpha.0

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 ADDED
@@ -0,0 +1,75 @@
1
+ Required Notice: Copyright 2026 Captive Origins (https://captiveorigins.com)
2
+
3
+ # PolyForm Noncommercial License 1.0.0
4
+
5
+ <https://polyformproject.org/licenses/noncommercial/1.0.0>
6
+
7
+ ## Acceptance
8
+
9
+ In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
10
+
11
+ ## Copyright License
12
+
13
+ The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
14
+
15
+ ## Distribution License
16
+
17
+ The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
18
+
19
+ ## Notices
20
+
21
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
22
+
23
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
24
+
25
+ ## Changes and New Works License
26
+
27
+ The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
28
+
29
+ ## Patent License
30
+
31
+ The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
32
+
33
+ ## Noncommercial Purposes
34
+
35
+ Any noncommercial purpose is a permitted purpose.
36
+
37
+ ## Personal Uses
38
+
39
+ Personal use for research, experiment, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, amateur pursuits, or religious observance, without any anticipated commercial application, is use for a permitted purpose.
40
+
41
+ ## Noncommercial Organizations
42
+
43
+ Use by any charitable organization, educational institution, public research organization, public safety or health organization, environmental protection organization, or government institution is use for a permitted purpose regardless of the source of funding or obligations resulting from the funding.
44
+
45
+ ## Fair Use
46
+
47
+ You may have "fair use" rights for the software under the law. These terms do not limit them.
48
+
49
+ ## No Other Rights
50
+
51
+ These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
52
+
53
+ ## Patent Defense
54
+
55
+ If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
56
+
57
+ ## Violations
58
+
59
+ The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
60
+
61
+ ## No Liability
62
+
63
+ ***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
64
+
65
+ ## Definitions
66
+
67
+ The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
68
+
69
+ **You** refers to the individual or entity agreeing to these terms.
70
+
71
+ **Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
72
+
73
+ **Your licenses** are all the licenses granted to you for the software under these terms.
74
+
75
+ **Use** means anything you do with the software requiring one of your licenses.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @captiveorigins/payload-plugin-onephylogeny
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ OnePhylogeny for Payload: immutable reference panels and released results on your own collections, with server-enforced review, safe endpoints and no coordinates.
4
+
5
+ See the [repository](https://github.com/CaptiveOrigins/onephylogeny) for documentation.
@@ -0,0 +1,32 @@
1
+ import { Access, Plugin } from 'payload';
2
+
3
+ type OnePhylogenyPluginOptions = {
4
+ /** Slugs of the collections this plugin adds. */
5
+ slugs?: {
6
+ panels?: string;
7
+ assignments?: string;
8
+ };
9
+ /** Host collections to relate to. Leave one out and its field isn't added, so the plugin works in any site. */
10
+ relations?: {
11
+ subject?: string;
12
+ sequence?: string;
13
+ taxa?: string;
14
+ files?: string;
15
+ importRuns?: string;
16
+ };
17
+ /** Who may create panels and results, and activate panels. Default: nobody but trusted local scripts. */
18
+ manageAccess?: Access;
19
+ /** Who may approve or reject results. Default: same as manageAccess. */
20
+ reviewAccess?: Access;
21
+ /** Extra rule for reading released results, such as the host's own animal permissions. Default: signed-in users. */
22
+ readReleasedAccess?: Access;
23
+ /** Field added to assignments for multi-tenant hosts' isolation plugins to find. */
24
+ group?: string;
25
+ };
26
+ /**
27
+ * OnePhylogeny for Payload. Adds immutable panels and reviewed results, relating to whatever collections a site already
28
+ * has. It holds no species knowledge. Compute happens elsewhere: this stores what was computed and controls release.
29
+ */
30
+ declare const onePhylogeny: (options?: OnePhylogenyPluginOptions) => Plugin;
31
+
32
+ export { type OnePhylogenyPluginOptions, onePhylogeny };
package/dist/index.js ADDED
@@ -0,0 +1,160 @@
1
+ // src/index.ts
2
+ import { validateResult } from "@captiveorigins/onephylogeny-core";
3
+ import { APIError } from "payload";
4
+ var PANEL_TRANSITIONS = { candidate: ["active", "withdrawn"], active: ["superseded", "withdrawn"], superseded: ["withdrawn"], withdrawn: [] };
5
+ var LOCKED_PANEL_FIELDS = ["key", "version", "marker", "checksum", "artifact", "importRun", "taxa", "groups", "notCovered", "validatedScope"];
6
+ var REVIEW_TRANSITIONS = { pending: ["approved", "rejected"], approved: ["withdrawn"], rejected: [], withdrawn: [] };
7
+ var COORDINATES = /^(lat|lon|lng|latitude|longitude|latlon|lat_lon|coordinates?)$/i;
8
+ var hasCoordinates = (value) => {
9
+ if (Array.isArray(value)) return value.some(hasCoordinates);
10
+ if (!value || typeof value !== "object") return false;
11
+ return Object.entries(value).some(([k, v]) => COORDINATES.test(k) || hasCoordinates(v));
12
+ };
13
+ var fail = (message) => {
14
+ throw new APIError(message, 400, void 0, true);
15
+ };
16
+ var idOf = (v) => v && typeof v === "object" ? String(v.id) : v == null ? void 0 : String(v);
17
+ var same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
18
+ var stripIds = (rows) => Array.isArray(rows) ? rows.map((r) => {
19
+ const { id: _id, ...rest } = r;
20
+ return rest;
21
+ }) : rows;
22
+ var panelBeforeChange = ({ data, originalDoc, operation }) => {
23
+ if (hasCoordinates(data.groups)) fail("Panels use generalized regions and never hold coordinates.");
24
+ if (operation === "create") {
25
+ if ((data.status ?? "candidate") !== "candidate") fail("A new panel starts as a candidate.");
26
+ return data;
27
+ }
28
+ const from = String(originalDoc.status);
29
+ const to = String(data.status ?? from);
30
+ if (to !== from && !PANEL_TRANSITIONS[from]?.includes(to)) fail(`A panel can't go from ${from} to ${to}.`);
31
+ if (from === "candidate" && to === "active" && !(data.validatedScope ?? originalDoc.validatedScope)?.length) fail("A panel with no validated claims can't become active.");
32
+ if (from !== "candidate") {
33
+ for (const f of LOCKED_PANEL_FIELDS) {
34
+ if (!(f in data)) continue;
35
+ const changed = f === "groups" ? !same(stripIds(data[f]), stripIds(originalDoc[f])) : Array.isArray(data[f]) ? !same(data[f].map(idOf), (originalDoc[f] ?? []).map(idOf)) : idOf(data[f]) !== idOf(originalDoc[f]);
36
+ if (changed) fail(`A ${from} panel can't be edited. Build a new version instead.`);
37
+ }
38
+ }
39
+ return data;
40
+ };
41
+ var supersedeOthers = (panels) => async ({ doc, previousDoc, req }) => {
42
+ if (doc.status !== "active" || previousDoc?.status === "active") return doc;
43
+ 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 });
44
+ for (const other of others.docs) await req.payload.update({ collection: panels, id: other.id, data: { status: "superseded" }, req, overrideAccess: true });
45
+ return doc;
46
+ };
47
+ var assignmentBeforeChange = (panels) => async ({ data, originalDoc, operation, req }) => {
48
+ if (operation === "create") {
49
+ if ((data.reviewStatus ?? "pending") !== "pending") fail("A new result starts as pending review.");
50
+ const panel = await req.payload.findByID({ collection: panels, id: idOf(data.panel), depth: 0, req, overrideAccess: true });
51
+ if (panel.status !== "active") fail("Results can only be made against an active panel.");
52
+ const result = data.result;
53
+ const problems = validateResult(result).filter((d) => d.severity === "error");
54
+ if (problems.length) fail(problems.map((p) => p.message).join("; "));
55
+ if (result.panel.version !== panel.version || result.panel.checksum !== panel.checksum) fail("This result was not made with this panel version.");
56
+ const found = new Set(result.findings.map((f) => f.group));
57
+ const missing = (panel.groups ?? []).filter((g) => !found.has(g.groupId)).map((g) => g.groupId);
58
+ if (missing.length) fail(`Every group must be reported. Missing: ${missing.join(", ")}.`);
59
+ if (hasCoordinates(result)) fail("Results never hold coordinates.");
60
+ return data;
61
+ }
62
+ const from = String(originalDoc.reviewStatus);
63
+ const to = String(data.reviewStatus ?? from);
64
+ for (const f of ["result", "panel", "sequence", "subject", "summary", "importRun"]) {
65
+ if (f in data && (f === "result" || f === "summary" ? !same(data[f], originalDoc[f]) : idOf(data[f]) !== idOf(originalDoc[f]))) fail("A result can't be edited. Make a new one instead.");
66
+ }
67
+ if (to !== from) {
68
+ if (!REVIEW_TRANSITIONS[from]?.includes(to)) fail(`A result can't go from ${from} to ${to}.`);
69
+ if (to === "approved") {
70
+ if (!req.user) fail("Approving a result needs a signed-in reviewer.");
71
+ data.reviewer = String(req.user.id);
72
+ data.releasedAt = (/* @__PURE__ */ new Date()).toISOString();
73
+ }
74
+ } else {
75
+ if ("reviewer" in data && data.reviewer !== originalDoc.reviewer) fail("The reviewer is set by approving.");
76
+ if ("releasedAt" in data && String(data.releasedAt) !== String(originalDoc.releasedAt)) fail("The release date is set by approving.");
77
+ }
78
+ return data;
79
+ };
80
+ var relation = (name, relationTo, extra = {}) => relationTo ? [{ name, type: "relationship", relationTo, index: true, ...extra }] : [];
81
+ var onePhylogeny = (options = {}) => (config) => {
82
+ const panels = options.slugs?.panels ?? "panels";
83
+ const assignments = options.slugs?.assignments ?? "assignments";
84
+ const r = options.relations ?? {};
85
+ const group = options.group ?? "Genetics";
86
+ const manage = options.manageAccess ?? (() => false);
87
+ const review = options.reviewAccess ?? manage;
88
+ const readReleased = options.readReleasedAccess ?? (({ req }) => Boolean(req.user));
89
+ const panelCollection = {
90
+ slug: panels,
91
+ labels: { singular: "Reference panel", plural: "Reference panels" },
92
+ admin: { group, useAsTitle: "key", defaultColumns: ["key", "version", "status", "marker"] },
93
+ access: {
94
+ read: async (args) => {
95
+ if (await manage(args)) return true;
96
+ return { status: { in: ["active", "superseded"] } };
97
+ },
98
+ create: manage,
99
+ update: manage,
100
+ delete: () => false
101
+ },
102
+ fields: [
103
+ { name: "key", type: "text", required: true, index: true, admin: { description: "Stays the same across versions of one panel." } },
104
+ { name: "version", type: "text", required: true },
105
+ { name: "status", type: "select", required: true, defaultValue: "candidate", index: true, options: ["candidate", "active", "superseded", "withdrawn"] },
106
+ { name: "marker", type: "text", required: true },
107
+ { name: "checksum", type: "text", required: true, index: true },
108
+ ...relation("taxa", r.taxa, { hasMany: true }),
109
+ ...relation("artifact", r.files, { admin: { description: "The full panel: JSON manifest and sequences." } }),
110
+ ...relation("importRun", r.importRuns),
111
+ { name: "validatedScope", type: "text", hasMany: true, admin: { description: "The claims this panel is validated for. Pages show only these." } },
112
+ { name: "notCovered", type: "text", hasMany: true },
113
+ { 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." } }] }
114
+ ],
115
+ hooks: { beforeChange: [panelBeforeChange], afterChange: [supersedeOthers(panels)] }
116
+ };
117
+ const assignmentCollection = {
118
+ slug: assignments,
119
+ labels: { singular: "Lineage result", plural: "Lineage results" },
120
+ admin: { group, useAsTitle: "summary", defaultColumns: ["summary", "panel", "reviewStatus", "releasedAt"] },
121
+ access: {
122
+ read: async (args) => {
123
+ if (await manage(args) || await review(args)) return true;
124
+ const allowed = await readReleased(args);
125
+ if (!allowed) return false;
126
+ const released2 = { reviewStatus: { equals: "approved" } };
127
+ return allowed === true ? released2 : { and: [released2, allowed] };
128
+ },
129
+ create: manage,
130
+ update: review,
131
+ delete: () => false
132
+ },
133
+ fields: [
134
+ ...relation("subject", r.subject),
135
+ ...relation("sequence", r.sequence),
136
+ { name: "panel", type: "relationship", relationTo: panels, required: true, index: true },
137
+ { name: "summary", type: "text", required: true },
138
+ { name: "result", type: "json", required: true, admin: { description: "The OnePhylogeny result, stored exactly as computed." } },
139
+ ...relation("importRun", r.importRuns),
140
+ { name: "reviewStatus", type: "select", required: true, defaultValue: "pending", index: true, options: ["pending", "approved", "rejected", "withdrawn"] },
141
+ { name: "reviewer", type: "text", admin: { readOnly: true } },
142
+ { name: "releasedAt", type: "date", admin: { readOnly: true } }
143
+ ],
144
+ hooks: { beforeChange: [assignmentBeforeChange(panels)] }
145
+ };
146
+ const released = {
147
+ path: "/onephylogeny/released",
148
+ method: "get",
149
+ handler: async (req) => {
150
+ const subject = new URL(req.url ?? "", "http://x").searchParams.get("subject");
151
+ if (!subject || !r.subject) return Response.json({ error: "A subject is required" }, { status: 400 });
152
+ 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 });
153
+ return Response.json({ docs: found.docs });
154
+ }
155
+ };
156
+ return { ...config, collections: [...config.collections ?? [], panelCollection, assignmentCollection], endpoints: [...config.endpoints ?? [], released] };
157
+ };
158
+ export {
159
+ onePhylogeny
160
+ };
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@captiveorigins/payload-plugin-onephylogeny",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-alpha.0",
4
+ "description": "OnePhylogeny for Payload: immutable reference panels and released results on your own collections, with server-enforced review, safe endpoints and no coordinates.",
5
+ "keywords": [
6
+ "phylogenetics",
7
+ "reference-panel"
8
+ ],
9
+ "homepage": "https://github.com/CaptiveOrigins/onephylogeny#readme",
10
+ "bugs": {
11
+ "url": "https://github.com/CaptiveOrigins/onephylogeny/issues"
12
+ },
13
+ "license": "PolyForm-Noncommercial-1.0.0",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/CaptiveOrigins/onephylogeny.git",
17
+ "directory": "packages/payload"
18
+ },
19
+ "type": "module",
20
+ "sideEffects": false,
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "import": "./dist/index.js"
25
+ }
26
+ },
27
+ "main": "./dist/index.js",
28
+ "types": "./dist/index.d.ts",
29
+ "files": [
30
+ "dist",
31
+ "README.md",
32
+ "LICENSE"
33
+ ],
34
+ "engines": {
35
+ "node": ">=22"
36
+ },
37
+ "dependencies": {
38
+ "@captiveorigins/onephylogeny-core": "^0.1.0-alpha.0"
39
+ },
40
+ "peerDependencies": {
41
+ "payload": "^3.80.0"
42
+ },
43
+ "devDependencies": {
44
+ "@payloadcms/db-mongodb": "3.92.1",
45
+ "graphql": "^16.14.2",
46
+ "mongodb-memory-server": "^11.3.0",
47
+ "payload": "^3.92.1",
48
+ "@types/node": "^24.19.2"
49
+ },
50
+ "scripts": {
51
+ "build": "tsup src/index.ts --format esm --dts --clean --target es2022",
52
+ "typecheck": "tsc --noEmit",
53
+ "test": "vitest run"
54
+ }
6
55
  }