@milaboratories/pl-model-middle-layer 1.32.2 → 1.34.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.
Files changed (87) hide show
  1. package/dist/folders/commit.cjs +79 -0
  2. package/dist/folders/commit.cjs.map +1 -0
  3. package/dist/folders/commit.d.ts +82 -0
  4. package/dist/folders/commit.d.ts.map +1 -0
  5. package/dist/folders/commit.js +78 -0
  6. package/dist/folders/commit.js.map +1 -0
  7. package/dist/folders/decode.cjs +79 -0
  8. package/dist/folders/decode.cjs.map +1 -0
  9. package/dist/folders/decode.d.ts +57 -0
  10. package/dist/folders/decode.d.ts.map +1 -0
  11. package/dist/folders/decode.js +77 -0
  12. package/dist/folders/decode.js.map +1 -0
  13. package/dist/folders/document.cjs +49 -0
  14. package/dist/folders/document.cjs.map +1 -0
  15. package/dist/folders/document.d.ts +56 -0
  16. package/dist/folders/document.d.ts.map +1 -0
  17. package/dist/folders/document.js +45 -0
  18. package/dist/folders/document.js.map +1 -0
  19. package/dist/folders/index.cjs +37 -0
  20. package/dist/folders/index.d.ts +10 -0
  21. package/dist/folders/index.js +10 -0
  22. package/dist/folders/inheritance.cjs +23 -0
  23. package/dist/folders/inheritance.cjs.map +1 -0
  24. package/dist/folders/inheritance.d.ts +19 -0
  25. package/dist/folders/inheritance.d.ts.map +1 -0
  26. package/dist/folders/inheritance.js +23 -0
  27. package/dist/folders/inheritance.js.map +1 -0
  28. package/dist/folders/invariants.cjs +115 -0
  29. package/dist/folders/invariants.cjs.map +1 -0
  30. package/dist/folders/invariants.d.ts +50 -0
  31. package/dist/folders/invariants.d.ts.map +1 -0
  32. package/dist/folders/invariants.js +114 -0
  33. package/dist/folders/invariants.js.map +1 -0
  34. package/dist/folders/naming.cjs +54 -0
  35. package/dist/folders/naming.cjs.map +1 -0
  36. package/dist/folders/naming.d.ts +32 -0
  37. package/dist/folders/naming.d.ts.map +1 -0
  38. package/dist/folders/naming.js +52 -0
  39. package/dist/folders/naming.js.map +1 -0
  40. package/dist/folders/planner.cjs +192 -0
  41. package/dist/folders/planner.cjs.map +1 -0
  42. package/dist/folders/planner.d.ts +100 -0
  43. package/dist/folders/planner.d.ts.map +1 -0
  44. package/dist/folders/planner.js +190 -0
  45. package/dist/folders/planner.js.map +1 -0
  46. package/dist/folders/removal.cjs +47 -0
  47. package/dist/folders/removal.cjs.map +1 -0
  48. package/dist/folders/removal.d.ts +42 -0
  49. package/dist/folders/removal.d.ts.map +1 -0
  50. package/dist/folders/removal.js +45 -0
  51. package/dist/folders/removal.js.map +1 -0
  52. package/dist/folders/view.cjs +212 -0
  53. package/dist/folders/view.cjs.map +1 -0
  54. package/dist/folders/view.d.ts +98 -0
  55. package/dist/folders/view.d.ts.map +1 -0
  56. package/dist/folders/view.js +207 -0
  57. package/dist/folders/view.js.map +1 -0
  58. package/dist/index.cjs +43 -2
  59. package/dist/index.d.ts +12 -2
  60. package/dist/index.js +12 -1
  61. package/dist/project.cjs +23 -0
  62. package/dist/project.cjs.map +1 -0
  63. package/dist/project.d.ts +13 -0
  64. package/dist/project.d.ts.map +1 -1
  65. package/dist/project.js +22 -0
  66. package/dist/project.js.map +1 -0
  67. package/package.json +6 -3
  68. package/src/folders/commit.ts +133 -0
  69. package/src/folders/decode.test.ts +128 -0
  70. package/src/folders/decode.ts +142 -0
  71. package/src/folders/document.ts +96 -0
  72. package/src/folders/index.ts +9 -0
  73. package/src/folders/inheritance.test.ts +91 -0
  74. package/src/folders/inheritance.ts +33 -0
  75. package/src/folders/invariants.test.ts +166 -0
  76. package/src/folders/invariants.ts +159 -0
  77. package/src/folders/naming.test.ts +62 -0
  78. package/src/folders/naming.ts +59 -0
  79. package/src/folders/planner.test.ts +450 -0
  80. package/src/folders/planner.ts +279 -0
  81. package/src/folders/removal.test.ts +142 -0
  82. package/src/folders/removal.ts +77 -0
  83. package/src/folders/test_utils.ts +86 -0
  84. package/src/folders/view.test.ts +433 -0
  85. package/src/folders/view.ts +334 -0
  86. package/src/index.ts +1 -0
  87. package/src/project.ts +21 -0
@@ -0,0 +1,133 @@
1
+ import type { ProjectId, TemplateId } from "@milaboratories/pl-model-common";
2
+ import type { FoldersDocument } from "./document";
3
+ import type {
4
+ FoldersLabelRename,
5
+ FoldersMoveIssue,
6
+ FoldersMovePlan,
7
+ FoldersMovePlanResult,
8
+ } from "./planner";
9
+ import { applyFoldersMove, foldersMovePlansEqual } from "./planner";
10
+ import type { FoldersRemoval, FoldersRemovalIssue, FoldersRemovalPlanResult } from "./removal";
11
+ import { applyFoldersRemoval, foldersRemovalsEqual } from "./removal";
12
+ import type { FoldersView } from "./view";
13
+
14
+ /** What one attempt of a folder write decided to do. */
15
+ export interface FoldersEdit<T> {
16
+ /** Value handed back to the caller, whether or not anything is written. */
17
+ readonly result: T;
18
+ /** The document to persist. Absent means write nothing — a refused plan, or a no-op. */
19
+ readonly document?: FoldersDocument;
20
+ /** Project and template labels the edit changes; their names live in their own metadata. */
21
+ readonly labelRenames?: readonly FoldersLabelRename[];
22
+ /** Projects the edit destroys. A folder deletion is the only edit that sets this. */
23
+ readonly deletedProjects?: readonly ProjectId[];
24
+ /** Templates the edit destroys. A folder deletion is the only edit that sets this. */
25
+ readonly deletedTemplates?: readonly TemplateId[];
26
+ }
27
+
28
+ /**
29
+ * What a move did.
30
+ *
31
+ * `plan-changed` is the whole point of the confirm step: the plan was recomputed inside the write
32
+ * transaction, it no longer matches the one the user confirmed, and nothing was written. The
33
+ * fresh plan comes back to be confirmed again, so a confirmation dialog cannot lie about what an
34
+ * item will end up called. `needs-confirmation` is the same guarantee reached from the other
35
+ * side — a caller that supplied no plan at all for a move that renames something.
36
+ *
37
+ * All four cases have to be handled by whoever calls a move, which is why this type lives in this
38
+ * package rather than in the node package.
39
+ */
40
+ export type FoldersMoveOutcome =
41
+ | { readonly ok: true; readonly plan: FoldersMovePlan }
42
+ | { readonly ok: false; readonly reason: "plan-changed"; readonly plan: FoldersMovePlan }
43
+ | {
44
+ readonly ok: false;
45
+ readonly reason: "needs-confirmation";
46
+ readonly plan: FoldersMovePlan;
47
+ }
48
+ | {
49
+ readonly ok: false;
50
+ readonly reason: "cannot-plan";
51
+ readonly issues: readonly FoldersMoveIssue[];
52
+ };
53
+
54
+ /** What a folder deletion did. */
55
+ export type FoldersRemovalOutcome =
56
+ | { readonly ok: true; readonly removal: FoldersRemoval }
57
+ | {
58
+ readonly ok: false;
59
+ readonly reason: "plan-changed";
60
+ readonly removal: FoldersRemoval;
61
+ }
62
+ | {
63
+ readonly ok: false;
64
+ readonly reason: "needs-confirmation";
65
+ readonly removal: FoldersRemoval;
66
+ }
67
+ | {
68
+ readonly ok: false;
69
+ readonly reason: "cannot-plan";
70
+ readonly issues: readonly FoldersRemovalIssue[];
71
+ };
72
+
73
+ /**
74
+ * The one place a move plan turns into a write.
75
+ *
76
+ * A move that renames nothing commits without a confirmed plan, because there is nothing to
77
+ * confirm. A move that renames something needs one, and a confirmed plan must equal the plan
78
+ * recomputed here, or nothing is written and the fresh plan goes back to be confirmed. A move of
79
+ * nothing writes nothing.
80
+ */
81
+ export function commitFoldersMove(
82
+ view: FoldersView,
83
+ planned: FoldersMovePlanResult,
84
+ confirmedPlan: FoldersMovePlan | undefined,
85
+ ): FoldersEdit<FoldersMoveOutcome> {
86
+ if (!planned.ok) return { result: { ok: false, reason: "cannot-plan", issues: planned.issues } };
87
+
88
+ if (confirmedPlan !== undefined) {
89
+ if (!foldersMovePlansEqual(planned.plan, confirmedPlan))
90
+ return { result: { ok: false, reason: "plan-changed", plan: planned.plan } };
91
+ } else if (planned.plan.entries.some((entry) => entry.renamed)) {
92
+ return { result: { ok: false, reason: "needs-confirmation", plan: planned.plan } };
93
+ }
94
+
95
+ // A move of nothing changes nothing. Without this it still mints a value and re-points the
96
+ // field, so an empty selection would conflict with whatever else is editing the tree and would
97
+ // persist a heal nobody asked for.
98
+ if (planned.plan.entries.length === 0) return { result: { ok: true, plan: planned.plan } };
99
+
100
+ const applied = applyFoldersMove(view, planned.plan);
101
+ return {
102
+ result: { ok: true, plan: planned.plan },
103
+ document: applied.document,
104
+ labelRenames: applied.labelRenames,
105
+ };
106
+ }
107
+
108
+ /**
109
+ * The one place a removal turns into a write.
110
+ *
111
+ * A deletion always needs a confirmed removal, however little it destroys: unlike a move, it has
112
+ * no harmless outcome to fall back on.
113
+ */
114
+ export function commitFoldersRemoval(
115
+ view: FoldersView,
116
+ planned: FoldersRemovalPlanResult,
117
+ confirmed: FoldersRemoval | undefined,
118
+ ): FoldersEdit<FoldersRemovalOutcome> {
119
+ if (!planned.ok) return { result: { ok: false, reason: "cannot-plan", issues: planned.issues } };
120
+
121
+ if (confirmed === undefined)
122
+ return { result: { ok: false, reason: "needs-confirmation", removal: planned.removal } };
123
+
124
+ if (!foldersRemovalsEqual(planned.removal, confirmed))
125
+ return { result: { ok: false, reason: "plan-changed", removal: planned.removal } };
126
+
127
+ return {
128
+ result: { ok: true, removal: planned.removal },
129
+ document: applyFoldersRemoval(view, planned.removal),
130
+ deletedProjects: planned.removal.projects,
131
+ deletedTemplates: planned.removal.templates,
132
+ };
133
+ }
@@ -0,0 +1,128 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import {
3
+ decodeFoldersDocument,
4
+ decodeStoredFoldersDocument,
5
+ encodeFoldersDocument,
6
+ } from "./decode";
7
+ import { FOLDERS_SCHEMA_VERSION, emptyFoldersDocument } from "./document";
8
+ import { document } from "./test_utils";
9
+
10
+ const validDocument = document(
11
+ [
12
+ { id: "f1", name: "Samples" },
13
+ { id: "f2", name: "Runs", parent: "f1" },
14
+ ],
15
+ { p1: "f2" },
16
+ { t1: "f1" },
17
+ );
18
+
19
+ describe("decodeStoredFoldersDocument", () => {
20
+ test("no stored document is a user with no folders, and writes stay allowed", () => {
21
+ const decoded = decodeStoredFoldersDocument({ present: false });
22
+ expect(decoded.document).toEqual(emptyFoldersDocument());
23
+ expect(decoded.writable).toBe(true);
24
+ expect(decoded.problem).toBeUndefined();
25
+ });
26
+
27
+ test("a stored document without bytes reads as no folders and refuses writes", () => {
28
+ for (const raw of [undefined, ""]) {
29
+ const decoded = decodeStoredFoldersDocument({ present: true, raw });
30
+ expect(decoded.document).toEqual(emptyFoldersDocument());
31
+ expect(decoded.writable).toBe(false);
32
+ expect(decoded.problem).toEqual({
33
+ kind: "unreadable",
34
+ message: "the folder document is stored in a shape this build cannot read",
35
+ });
36
+ }
37
+ });
38
+
39
+ test("a stored document of whitespace only is not JSON, and refuses writes", () => {
40
+ const decoded = decodeStoredFoldersDocument({ present: true, raw: " " });
41
+ expect(decoded.writable).toBe(false);
42
+ expect(decoded.problem?.kind).toBe("unreadable");
43
+ });
44
+
45
+ test("a stored document with bytes is decoded", () => {
46
+ const decoded = decodeStoredFoldersDocument({
47
+ present: true,
48
+ raw: JSON.stringify(validDocument),
49
+ });
50
+ expect(decoded.writable).toBe(true);
51
+ expect(decoded.document).toEqual(validDocument);
52
+ });
53
+ });
54
+
55
+ describe("decodeFoldersDocument", () => {
56
+ test("a current document round-trips", () => {
57
+ const encoded = encodeFoldersDocument(validDocument);
58
+ const decoded = decodeFoldersDocument(encoded);
59
+ expect(decoded.writable).toBe(true);
60
+ expect(decoded.document).toEqual(validDocument);
61
+ });
62
+
63
+ test("a document written by a newer build reads as no folders and refuses writes", () => {
64
+ const decoded = decodeFoldersDocument(
65
+ JSON.stringify({ ...validDocument, schemaVersion: FOLDERS_SCHEMA_VERSION + 1 }),
66
+ );
67
+ expect(decoded.document).toEqual(emptyFoldersDocument());
68
+ expect(decoded.writable).toBe(false);
69
+ expect(decoded.problem?.kind).toBe("newer-schema");
70
+ if (decoded.problem?.kind === "newer-schema")
71
+ expect(decoded.problem.documentSchemaVersion).toBe(FOLDERS_SCHEMA_VERSION + 1);
72
+ });
73
+
74
+ test("invalid JSON reads as no folders and refuses writes", () => {
75
+ const decoded = decodeFoldersDocument("{not json");
76
+ expect(decoded.document).toEqual(emptyFoldersDocument());
77
+ expect(decoded.writable).toBe(false);
78
+ expect(decoded.problem?.kind).toBe("unreadable");
79
+ });
80
+
81
+ test("a document of the right version but the wrong shape refuses writes", () => {
82
+ for (const value of [
83
+ { ...validDocument, folders: "nope" },
84
+ { ...validDocument, folders: [{ id: "f1" }] },
85
+ { ...validDocument, folders: [{ id: "f1", name: "" }] },
86
+ { ...validDocument, assignments: { p1: 7 } },
87
+ { ...validDocument, templateAssignments: { t1: 7 } },
88
+ { ...validDocument, extra: 1 },
89
+ { schemaVersion: FOLDERS_SCHEMA_VERSION, folders: [], assignments: {} },
90
+ ]) {
91
+ const decoded = decodeFoldersDocument(JSON.stringify(value));
92
+ expect(decoded.writable).toBe(false);
93
+ expect(decoded.problem?.kind).toBe("unreadable");
94
+ expect(decoded.document).toEqual(emptyFoldersDocument());
95
+ }
96
+ });
97
+
98
+ test("a value that is not an object, or carries no usable version, refuses writes", () => {
99
+ for (const value of [
100
+ null,
101
+ 7,
102
+ [],
103
+ "text",
104
+ {},
105
+ { schemaVersion: "1" },
106
+ { schemaVersion: 0 },
107
+ { schemaVersion: 1.5 },
108
+ ]) {
109
+ const decoded = decodeFoldersDocument(JSON.stringify(value));
110
+ expect(decoded.writable).toBe(false);
111
+ expect(decoded.problem?.kind).toBe("unreadable");
112
+ }
113
+ });
114
+
115
+ test("the problem names the schema version it checked against", () => {
116
+ const decoded = decodeFoldersDocument(
117
+ JSON.stringify({ ...validDocument, folders: [{ id: "f1" }] }),
118
+ );
119
+ expect(decoded.problem?.message).toBe(
120
+ `the folder document does not match schema ${FOLDERS_SCHEMA_VERSION}: folders.0.name: Required`,
121
+ );
122
+ });
123
+
124
+ test("the problem carries a message a log can be read from", () => {
125
+ const decoded = decodeFoldersDocument("{not json");
126
+ expect(decoded.problem?.message).toMatch(/folder document/);
127
+ });
128
+ });
@@ -0,0 +1,142 @@
1
+ import { FOLDERS_SCHEMA_VERSION, FoldersDocument, emptyFoldersDocument } from "./document";
2
+
3
+ /** Why a stored document could not be read as it stands. */
4
+ export type FoldersDocumentProblem =
5
+ | {
6
+ readonly kind: "newer-schema";
7
+ /** Version found in the document, which is higher than this build understands. */
8
+ readonly documentSchemaVersion: number;
9
+ readonly message: string;
10
+ }
11
+ | {
12
+ readonly kind: "unreadable";
13
+ readonly message: string;
14
+ };
15
+
16
+ /**
17
+ * A stored document as this build sees it.
18
+ *
19
+ * A document written by a newer build, or one that cannot be parsed at all, reads as no folders
20
+ * so that the project list still renders, and turns `writable` off: an old build that both
21
+ * degraded the read and kept writing would silently replace a newer build's tree with its own
22
+ * truncated view of it. Every refusal says why.
23
+ */
24
+ export type FoldersDecoded =
25
+ | {
26
+ readonly document: FoldersDocument;
27
+ readonly writable: true;
28
+ readonly problem?: undefined;
29
+ }
30
+ | {
31
+ readonly document: FoldersDocument;
32
+ /** Every folder write must be refused. */
33
+ readonly writable: false;
34
+ readonly problem: FoldersDocumentProblem;
35
+ };
36
+
37
+ /**
38
+ * What the store holds for the folder document: nothing at all, or a stored value and its bytes
39
+ * when they could be obtained.
40
+ */
41
+ export type FoldersStoredDocument =
42
+ | { readonly present: false }
43
+ | {
44
+ readonly present: true;
45
+ /** The stored JSON; undefined when the value carries no bytes this build can fetch. */
46
+ readonly raw: string | undefined;
47
+ };
48
+
49
+ /**
50
+ * Decode whatever the store holds for the folder document.
51
+ *
52
+ * An absent document is a user with no folders, and is writable. A document that is present but
53
+ * carries no bytes, or empty ones, is not the same thing: it exists and cannot be read here — a
54
+ * newer build keeping the tree in another shape, or a value this build cannot fetch — so it reads
55
+ * as no folders and is **not** writable, because writing an empty tree over one that is merely
56
+ * unreadable from this build destroys it.
57
+ */
58
+ export function decodeStoredFoldersDocument(stored: FoldersStoredDocument): FoldersDecoded {
59
+ if (!stored.present) return readable(emptyFoldersDocument());
60
+ if (stored.raw === undefined || stored.raw === "")
61
+ return unreadable("the folder document is stored in a shape this build cannot read");
62
+ return decodeFoldersDocument(stored.raw);
63
+ }
64
+
65
+ /** Decode the stored JSON of a document that is present. */
66
+ export function decodeFoldersDocument(raw: string): FoldersDecoded {
67
+ let parsed: unknown;
68
+ try {
69
+ parsed = JSON.parse(raw);
70
+ } catch (error: unknown) {
71
+ return unreadable(`the folder document is not valid JSON: ${errorText(error)}`);
72
+ }
73
+
74
+ return decodeFoldersValue(parsed);
75
+ }
76
+
77
+ /** Serialise a document for storage. */
78
+ export function encodeFoldersDocument(document: FoldersDocument): string {
79
+ return JSON.stringify(document);
80
+ }
81
+
82
+ //
83
+ // Internals
84
+ //
85
+
86
+ function decodeFoldersValue(value: unknown): FoldersDecoded {
87
+ if (!isMapping(value)) return unreadable("the folder document is not an object");
88
+
89
+ const version = value.schemaVersion;
90
+ if (typeof version !== "number" || !Number.isInteger(version) || version < 1)
91
+ return unreadable("the folder document carries no usable schema version");
92
+
93
+ if (version > FOLDERS_SCHEMA_VERSION)
94
+ return {
95
+ document: emptyFoldersDocument(),
96
+ writable: false,
97
+ problem: {
98
+ kind: "newer-schema",
99
+ documentSchemaVersion: version,
100
+ message:
101
+ `the folder document was written by a newer version of the application ` +
102
+ `(schema ${version}, this build understands ${FOLDERS_SCHEMA_VERSION})`,
103
+ },
104
+ };
105
+
106
+ const result = FoldersDocument.safeParse(value);
107
+ if (!result.success)
108
+ return unreadable(
109
+ `the folder document does not match schema ${FOLDERS_SCHEMA_VERSION}: ` +
110
+ result.error.issues.map(formatIssue).join("; "),
111
+ );
112
+
113
+ return readable(result.data);
114
+ }
115
+
116
+ function readable(document: FoldersDocument): FoldersDecoded {
117
+ return { document, writable: true };
118
+ }
119
+
120
+ function unreadable(message: string): FoldersDecoded {
121
+ return {
122
+ document: emptyFoldersDocument(),
123
+ writable: false,
124
+ problem: { kind: "unreadable", message },
125
+ };
126
+ }
127
+
128
+ function isMapping(value: unknown): value is Record<string, unknown> {
129
+ return typeof value === "object" && value !== null && !Array.isArray(value);
130
+ }
131
+
132
+ function formatIssue(issue: {
133
+ readonly path: readonly PropertyKey[];
134
+ readonly message: string;
135
+ }): string {
136
+ const path = issue.path.map((segment) => String(segment)).join(".");
137
+ return path === "" ? issue.message : `${path}: ${issue.message}`;
138
+ }
139
+
140
+ function errorText(error: unknown): string {
141
+ return error instanceof Error ? error.message : String(error);
142
+ }
@@ -0,0 +1,96 @@
1
+ import type { Branded } from "@milaboratories/pl-model-common";
2
+ import { z } from "zod";
3
+
4
+ /**
5
+ * Schema version this build writes and fully understands.
6
+ *
7
+ * A document carrying a higher version is not readable here, and folder writes are refused rather
8
+ * than allowed to truncate whatever the newer build stored.
9
+ */
10
+ export const FOLDERS_SCHEMA_VERSION = 1;
11
+
12
+ /** Identifier of a folder, unique within one user's folder document. */
13
+ export type FolderId = Branded<string, "FolderId">;
14
+
15
+ /** Brands a string already known to be a folder id, such as one handed back by a caller. */
16
+ export function asFolderId(id: string): FolderId {
17
+ return id as FolderId;
18
+ }
19
+
20
+ /**
21
+ * A folder as it is persisted: a name, a reference to the folder that contains it, and what the
22
+ * user wrote about it.
23
+ *
24
+ * A folder nobody described carries no description at all rather than an empty one, so clearing
25
+ * a description leaves the same document a folder that never had one has.
26
+ */
27
+ export interface FolderEntry {
28
+ readonly id: FolderId;
29
+ readonly name: string;
30
+ /** Absent for a top-level folder. */
31
+ readonly parent?: FolderId;
32
+ /** Free text the user wrote about the folder. Absent when there is none. */
33
+ readonly description?: string;
34
+ }
35
+
36
+ export const FolderEntry: z.ZodType<FolderEntry, z.ZodTypeDef, unknown> = z
37
+ .object({
38
+ id: folderId(),
39
+ name: z.string().min(1),
40
+ parent: folderId().optional(),
41
+ description: z.string().optional(),
42
+ })
43
+ .strict();
44
+
45
+ /**
46
+ * The whole folder tree of one user, as one persisted document.
47
+ *
48
+ * Projects and templates live in the same tree, so one folder holds both, and each has its own
49
+ * assignment map. They are separate maps rather than one because the two ids are looked up in
50
+ * two different lists: merged, an id present in neither list could not be told apart from a
51
+ * project that was deleted, and the dead-entry pruning a read performs would have nothing to go
52
+ * on.
53
+ *
54
+ * Each map points from the item to the folder holding it, not the other way round: an item lives
55
+ * in at most one folder, so one entry per item can never contradict itself, and an item the map
56
+ * does not mention needs no entry at all — it is at the top level.
57
+ */
58
+ export interface FoldersDocument {
59
+ readonly schemaVersion: typeof FOLDERS_SCHEMA_VERSION;
60
+ readonly folders: readonly FolderEntry[];
61
+ /** Project id to the folder holding it. Projects at the top level are absent. */
62
+ readonly assignments: Readonly<Record<string, FolderId>>;
63
+ /** Template id to the folder holding it. Templates at the top level are absent. */
64
+ readonly templateAssignments: Readonly<Record<string, FolderId>>;
65
+ }
66
+
67
+ export const FoldersDocument: z.ZodType<FoldersDocument, z.ZodTypeDef, unknown> = z
68
+ .object({
69
+ schemaVersion: z.literal(FOLDERS_SCHEMA_VERSION),
70
+ folders: z.array(FolderEntry),
71
+ assignments: z.record(z.string().min(1), folderId()),
72
+ templateAssignments: z.record(z.string().min(1), folderId()),
73
+ })
74
+ .strict();
75
+
76
+ /** The document of a user who has never made a folder. */
77
+ export function emptyFoldersDocument(): FoldersDocument {
78
+ return {
79
+ schemaVersion: FOLDERS_SCHEMA_VERSION,
80
+ folders: [],
81
+ assignments: {},
82
+ templateAssignments: {},
83
+ };
84
+ }
85
+
86
+ //
87
+ // Internals
88
+ //
89
+
90
+ /**
91
+ * Folder ids are plain strings on the wire; the brand exists so that a project id and a folder id
92
+ * cannot be swapped by accident in the code consuming them.
93
+ */
94
+ function folderId() {
95
+ return z.string().min(1).transform(asFolderId);
96
+ }
@@ -0,0 +1,9 @@
1
+ export * from "./document";
2
+ export * from "./decode";
3
+ export * from "./view";
4
+ export * from "./invariants";
5
+ export * from "./naming";
6
+ export * from "./planner";
7
+ export * from "./commit";
8
+ export * from "./removal";
9
+ export * from "./inheritance";
@@ -0,0 +1,91 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import { inheritedFolder } from "./inheritance";
3
+ import { fid, pid, project, template, view } from "./test_utils";
4
+
5
+ describe("what a new item inherits from the project it was made from", () => {
6
+ test("a copy lands in the folder holding its source", () => {
7
+ const tree = view([{ id: "a", name: "Samples" }], [{ id: "p1", name: "Run", folder: "a" }]);
8
+
9
+ expect(inheritedFolder(tree, pid("p1"), project("p2"), "Run (Copy)")).toBe(fid("a"));
10
+ });
11
+
12
+ test("a template taken from a project lands in that project's folder", () => {
13
+ const tree = view([{ id: "a", name: "Samples" }], [{ id: "p1", name: "Run", folder: "a" }]);
14
+
15
+ expect(inheritedFolder(tree, pid("p1"), template("t1"), "Run (Copy)")).toBe(fid("a"));
16
+ });
17
+
18
+ test("a template is held to the names of the templates in that folder only", () => {
19
+ const tree = view(
20
+ [{ id: "a", name: "Samples" }],
21
+ [{ id: "p1", name: "Run", folder: "a" }],
22
+ [{ id: "t2", name: "Pilot", folder: "a" }],
23
+ );
24
+
25
+ // "Run" is the source project's own name, which a template may carry beside it.
26
+ expect(inheritedFolder(tree, pid("p1"), template("t1"), "Run")).toBe(fid("a"));
27
+ expect(inheritedFolder(tree, pid("p1"), template("t1"), "pilot")).toBeUndefined();
28
+ });
29
+
30
+ test("a source at the top level leaves the new item at the top level", () => {
31
+ const tree = view([{ id: "a", name: "Samples" }], [{ id: "p1", name: "Run" }]);
32
+
33
+ expect(inheritedFolder(tree, pid("p1"), project("p2"), "Run (Copy)")).toBeUndefined();
34
+ });
35
+
36
+ test("a source that is no longer in the tree places nothing", () => {
37
+ const tree = view([{ id: "a", name: "Samples" }], []);
38
+
39
+ expect(inheritedFolder(tree, pid("ghost"), project("p2"), "Run (Copy)")).toBeUndefined();
40
+ });
41
+
42
+ test("a name already taken in that folder leaves the copy at the top level", () => {
43
+ const tree = view(
44
+ [{ id: "a", name: "Samples" }],
45
+ [
46
+ { id: "p1", name: "Run", folder: "a" },
47
+ { id: "p2", name: "Run (Copy)", folder: "a" },
48
+ ],
49
+ );
50
+
51
+ expect(inheritedFolder(tree, pid("p1"), project("p3"), "Run (Copy)")).toBeUndefined();
52
+ });
53
+
54
+ test("a child folder's name does not block a project: each kind has its own namespace", () => {
55
+ const tree = view(
56
+ [
57
+ { id: "a", name: "Samples" },
58
+ { id: "b", name: "Run (Copy)", parent: "a" },
59
+ ],
60
+ [{ id: "p1", name: "Run", folder: "a" }],
61
+ );
62
+
63
+ expect(inheritedFolder(tree, pid("p1"), project("p2"), "Run (Copy)")).toBe(fid("a"));
64
+ });
65
+
66
+ test("a name taken elsewhere in the tree does not block the placement", () => {
67
+ // Uniqueness is per parent, never global: the copy is placed although another project at the
68
+ // top level already carries the name it is being given.
69
+ const tree = view(
70
+ [{ id: "a", name: "Samples" }],
71
+ [
72
+ { id: "p1", name: "Run", folder: "a" },
73
+ { id: "p2", name: "Run (Copy)" },
74
+ ],
75
+ );
76
+
77
+ expect(inheritedFolder(tree, pid("p1"), project("p2"), "Run (Copy)")).toBe(fid("a"));
78
+ });
79
+
80
+ test("the comparison ignores case, exactly as the naming rule does", () => {
81
+ const tree = view(
82
+ [{ id: "a", name: "Samples" }],
83
+ [
84
+ { id: "p1", name: "Run", folder: "a" },
85
+ { id: "p2", name: "RUN (COPY)", folder: "a" },
86
+ ],
87
+ );
88
+
89
+ expect(inheritedFolder(tree, pid("p1"), project("p3"), "Run (Copy)")).toBeUndefined();
90
+ });
91
+ });
@@ -0,0 +1,33 @@
1
+ import type { ProjectId } from "@milaboratories/pl-model-common";
2
+ import type { FolderId } from "./document";
3
+ import { foldersNameTaken } from "./naming";
4
+ import type { FoldersLeafItem } from "./planner";
5
+ import type { FoldersView } from "./view";
6
+ import { foldersSiblingNames } from "./view";
7
+
8
+ /**
9
+ * The folder a newly created item should land in, given the project it was made from.
10
+ *
11
+ * A copy of a project, and a template taken from one, belong beside their source; landing at the
12
+ * top level reads as the app having lost them. `undefined` means leave it at the top level:
13
+ *
14
+ * - the source is itself at the top level, or is no longer in the tree at all;
15
+ * - an item of the created one's kind already carries the name where the source sits. The
16
+ * creating caller chose that name, so suffixing it here would disagree with what it reported,
17
+ * and refusing the whole creation over a placement would be the worse trade.
18
+ */
19
+ export function inheritedFolder(
20
+ view: FoldersView,
21
+ source: ProjectId,
22
+ created: FoldersLeafItem,
23
+ name: string,
24
+ ): FolderId | undefined {
25
+ const folder = view.projects.find((candidate) => candidate.id === source)?.folder;
26
+ if (folder === undefined) return undefined;
27
+
28
+ // Scoped to the destination and to the created item's kind, because the rule is: names are
29
+ // unique among one kind within a parent, never globally. The item being created is left out in
30
+ // case the view already lists it.
31
+ const siblings = foldersSiblingNames(view, folder, [created.id], { kind: created.kind });
32
+ return foldersNameTaken(name, siblings) ? undefined : folder;
33
+ }