@william_jin/vireo 0.0.0-stage → 0.20.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 (70) hide show
  1. package/LICENSE.md +61 -0
  2. package/README.md +136 -2
  3. package/dist/bin.d.ts +2 -0
  4. package/dist/bin.js +61 -0
  5. package/dist/bin.js.map +1 -0
  6. package/dist/board.d.ts +87 -0
  7. package/dist/board.js +310 -0
  8. package/dist/board.js.map +1 -0
  9. package/dist/calls.d.ts +19 -0
  10. package/dist/calls.js +9 -0
  11. package/dist/calls.js.map +1 -0
  12. package/dist/cli.d.ts +26 -0
  13. package/dist/cli.js +530 -0
  14. package/dist/cli.js.map +1 -0
  15. package/dist/collect.d.ts +43 -0
  16. package/dist/collect.js +41 -0
  17. package/dist/collect.js.map +1 -0
  18. package/dist/db.d.ts +18 -0
  19. package/dist/db.js +18 -0
  20. package/dist/db.js.map +1 -0
  21. package/dist/index.d.ts +10 -0
  22. package/dist/index.js +8 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/live.d.ts +28 -0
  25. package/dist/live.js +121 -0
  26. package/dist/live.js.map +1 -0
  27. package/dist/media.d.ts +36 -0
  28. package/dist/media.js +87 -0
  29. package/dist/media.js.map +1 -0
  30. package/dist/migrations.d.ts +5 -0
  31. package/dist/migrations.js +12 -0
  32. package/dist/migrations.js.map +1 -0
  33. package/dist/schema.d.ts +2105 -0
  34. package/dist/schema.js +364 -0
  35. package/dist/schema.js.map +1 -0
  36. package/dist/stats.d.ts +72 -0
  37. package/dist/stats.js +185 -0
  38. package/dist/stats.js.map +1 -0
  39. package/dist/store.d.ts +1078 -0
  40. package/dist/store.js +1242 -0
  41. package/dist/store.js.map +1 -0
  42. package/dist/sync.d.ts +26 -0
  43. package/dist/sync.js +47 -0
  44. package/dist/sync.js.map +1 -0
  45. package/drizzle/0000_init.sql +116 -0
  46. package/drizzle/0001_lineage.sql +18 -0
  47. package/drizzle/0002_drop_parent_id.sql +1 -0
  48. package/drizzle/0003_batch_n.sql +8 -0
  49. package/drizzle/0004_score.sql +7 -0
  50. package/drizzle/0005_steers.sql +26 -0
  51. package/drizzle/0006_steers_fk_index.sql +3 -0
  52. package/drizzle/0007_batch_title.sql +1 -0
  53. package/drizzle/0008_calls.sql +24 -0
  54. package/drizzle/0009_content_type.sql +1 -0
  55. package/drizzle/0010_board_pins.sql +33 -0
  56. package/drizzle/0011_pins_fk_indexes.sql +2 -0
  57. package/drizzle/meta/0000_snapshot.json +816 -0
  58. package/drizzle/meta/0001_snapshot.json +918 -0
  59. package/drizzle/meta/0002_snapshot.json +912 -0
  60. package/drizzle/meta/0003_snapshot.json +927 -0
  61. package/drizzle/meta/0004_snapshot.json +941 -0
  62. package/drizzle/meta/0005_snapshot.json +1120 -0
  63. package/drizzle/meta/0006_snapshot.json +1165 -0
  64. package/drizzle/meta/0007_snapshot.json +1171 -0
  65. package/drizzle/meta/0008_snapshot.json +1256 -0
  66. package/drizzle/meta/0009_snapshot.json +1262 -0
  67. package/drizzle/meta/0010_snapshot.json +1493 -0
  68. package/drizzle/meta/0011_snapshot.json +1523 -0
  69. package/drizzle/meta/_journal.json +90 -0
  70. package/package.json +91 -4
package/LICENSE.md ADDED
@@ -0,0 +1,61 @@
1
+ # PolyForm Strict License 1.0.0
2
+
3
+ <https://polyformproject.org/licenses/strict/1.0.0>
4
+
5
+ ## Acceptance
6
+
7
+ In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
8
+
9
+ ## Copyright License
10
+
11
+ 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, other than distributing the software or making changes or new works based on the software.
12
+
13
+ ## Patent License
14
+
15
+ 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.
16
+
17
+ ## Noncommercial Purposes
18
+
19
+ Any noncommercial purpose is a permitted purpose.
20
+
21
+ ## Personal Uses
22
+
23
+ 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.
24
+
25
+ ## Noncommercial Organizations
26
+
27
+ 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.
28
+
29
+ ## Fair Use
30
+
31
+ You may have "fair use" rights for the software under the law. These terms do not limit them.
32
+
33
+ ## No Other Rights
34
+
35
+ 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.
36
+
37
+ ## Patent Defense
38
+
39
+ 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.
40
+
41
+ ## Violations
42
+
43
+ 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.
44
+
45
+ ## No Liability
46
+
47
+ ***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.***
48
+
49
+ ## Definitions
50
+
51
+ The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
52
+
53
+ **You** refers to the individual or entity agreeing to these terms.
54
+
55
+ **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.
56
+
57
+ **Your licenses** are all the licenses granted to you for the software under these terms.
58
+
59
+ **Use** means anything you do with the software requiring one of your licenses.
60
+
61
+ Required Notice: Copyright 2026 William Jin (https://wrenautomation.com)
package/README.md CHANGED
@@ -1,3 +1,137 @@
1
- # Temporary Holding Version
1
+ # vireo
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
+ The variant loop. An agent makes a batch of samples (copy, cuts, images, pages). A person marks
4
+ each one on a 1-10 score (zones Bad, Okay, Good, Amazing), with notes pinned to words, a box or a time. The agent reads the
5
+ calls and makes the next batch. Ship a sample and its real numbers come back per segment, beside
6
+ the taste rank.
7
+
8
+ Vireo is the backend: tables, the store, stats, collectors, a CLI. The host renders it.
9
+
10
+ ## Use it alone
11
+
12
+ ```sh
13
+ npx @william_jin/vireo new hero --name "Hero line" --kind text --type text-post # --type: what the piece is
14
+ echo '{"title":"Hero lines, 2 openers","why":"number first vs story first","samples":[{"body":"3x replies"},{"body":"A story"}]}' \
15
+ | npx @william_jin/vireo add hero
16
+ npx @william_jin/vireo judge 1 amazing # or a score: judge 1 8
17
+ npx @william_jin/vireo note 1 --quote "3x" --tone good
18
+ npx @william_jin/vireo close hero:1 --note "more numbers"
19
+ npx @william_jin/vireo show hero # what the agent reads for the next batch
20
+ ```
21
+
22
+ Data goes to one PGlite folder, `~/.vireo/` (`VIREO_DIR` moves it), or to Postgres when `DATABASE_URL` is set. Migrations run
23
+ on open. Files (`{"file": "cut.mp4"}`) go to `VIREO_BUCKET` (any S3: set `VIREO_S3_ENDPOINT` for
24
+ R2 or MinIO). `VIREO_BY` names who acts.
25
+
26
+ Lineage: `{"name": "Warm grid", "parents": [{"id": 4, "took": "the palette"}, 7], "change": "…"}`.
27
+ The first parent is the main one; two or more make a cross. `name`, `took` and `change` are for
28
+ the agent and the tree: a host hides them while the person judges.
29
+
30
+ Batches count per subject (`n`, from 1; a deleted batch leaves a gap). Name a batch `hero:3`:
31
+ every output leads with that ref, and `close`, `queue`, `append` and `merge` take it. The id
32
+ is secondary; a plain id still works.
33
+
34
+ More than one person can judge. Each has one call per sample (`calls`, by `VIREO_BY` or
35
+ `judge --for <person>`). While a batch is open, a person sees only their own calls and notes;
36
+ `batch hero:3 --as <person>` reads it that way. The agent sees every call. `batches` pages the
37
+ list: `--sort waiting|newest|oldest|subject|good`, `--state open|closed|waits`, `--kind`,
38
+ `--subject`, `--who`, `--limit`, `--after`.
39
+
40
+ ```sh
41
+ npx @william_jin/vireo append hero:3 more.json # more samples in open batch 3
42
+ npx @william_jin/vireo merge hero:4 hero:3 # batch 4 should have been an append
43
+ ```
44
+
45
+ `append` refuses a closed batch. `merge` moves an open batch's samples into another open batch of
46
+ its subject and deletes the empty one.
47
+
48
+ ```sh
49
+ npx @william_jin/vireo rename subject hero "Hero line, spring" # the slug stays the ref
50
+ npx @william_jin/vireo type hero short-video # set or change its content type
51
+ npx @william_jin/vireo rename batch hero:3 "Warmer openers" # the batch's title
52
+ npx @william_jin/vireo edit 4 --name "Warm grid" --change "warmer opener" # "" clears
53
+ npx @william_jin/vireo edit 4 --file out/cut-b.mp4 --poster-file out/cut-b.jpg # only before a call or a note
54
+ npx @william_jin/vireo edit --json fixes.json # {samples: [{id, ...}]}, all or nothing
55
+ ```
56
+
57
+ Each new batch needs a `title`: one line the person sees, what the batch is. A host shows it while
58
+ the person judges, so it names the batch, not the idea under test or a likely winner (that is `why`).
59
+ `append` keeps the title.
60
+
61
+ Steers are the person's hand on the tree. `add` refuses a batch that breaks a live one:
62
+
63
+ ```sh
64
+ npx @william_jin/vireo steer pin 4 # every new batch grows a sample from 4
65
+ npx @william_jin/vireo steer prune 7 # nothing new grows from 7 or what grew from it
66
+ npx @william_jin/vireo steer cross 4 9 # the next batch has a sample with both as parents
67
+ npx @william_jin/vireo steer width hero wide # narrow | normal | wide: how far to move
68
+ npx @william_jin/vireo steer list hero
69
+ npx @william_jin/vireo steer lift 3
70
+ ```
71
+
72
+ A page that runs code (WebGL, scroll scenes) is a link: deploy it, then add
73
+ `{"media": "https://…", "posterFile": "still.jpg"}`. The host frames the link; vireo never serves
74
+ it. Use a URL that does not change (a preview deploy), so a call stays tied to what was seen.
75
+ A host with a `shoot(url)` port (`CliHost`) shoots the poster when the sample has none;
76
+ `vireo posters [subject]` fills the ones still missing.
77
+
78
+ Every command prints one JSON document on stdout. A command about one batch or subject also
79
+ names its card on stderr, for a chat that draws cards: `add`, `append`, `close`, `batch` and
80
+ `queue hero:3` print `::view vireo.batch {"batch":"hero:3"}`; `new` and `show` print
81
+ `::view vireo.subject {"subject":1}` (the subject's id). The host reads the data itself.
82
+
83
+ ## Slot it into a system
84
+
85
+ ```ts
86
+ import { vireo, type Collector } from "@william_jin/vireo";
87
+ import { MIGRATIONS } from "@william_jin/vireo/migrations";
88
+ import { migrate } from "drizzle-orm/postgres-js/migrator";
89
+
90
+ await migrate(db, MIGRATIONS); // schema "vireo", journal drizzle.__vireo_migrations
91
+
92
+ const page: Collector = {
93
+ channel: "page",
94
+ target: "page id",
95
+ rates: [{ name: "form", wins: "forms", of: "views" }],
96
+ read: async (ship) => [{ segment: "all", metric: "views", value: 1000 } /* ... */],
97
+ };
98
+
99
+ const v = vireo({ db, collectors: [page], hooks: { onWrite: (tx, by) => setActor(tx, by) } });
100
+ await v.ship(sampleId, { channel: "page", target: "landing-b" }, "me");
101
+ await v.collect(); // run from your scheduler; Restate in wren
102
+ const { live } = await v.feedback("hero"); // rates, 95% range, P(best) per segment
103
+ ```
104
+
105
+ | Port | You give |
106
+ |---|---|
107
+ | `db` | any drizzle pg database (postgres-js, node-postgres, PGlite) |
108
+ | `collectors` | one per channel: its rates, `read(ship)` → totals per segment |
109
+ | `hooks.onWrite` | first step of each write: audit actor, session settings |
110
+ | `hooks.afterWrite` | after each write commits (and after `collect`): a host's push to open views; never fails the write |
111
+ | bucket | `s3Bucket({bucket, endpoint?})` for the CLI's uploads |
112
+
113
+ Add the commands to your own CLI: `registerCommands(program.command("variants"), {by, withVireo})` from
114
+ `@william_jin/vireo/cli`. Render the read models (`batches`, `batch`, `queue`, `feedback`, `catalog`); pass the
115
+ viewer so an open batch stays blind for them; their types
116
+ are exported. Errors are `VireoError` with an HTTP status.
117
+
118
+ | Export | Is |
119
+ |---|---|
120
+ | `.` | `vireo()`, `Vireo`, types, `VireoError` |
121
+ | `/schema` | drizzle tables |
122
+ | `/migrations` | `MIGRATIONS` for your driver's migrator |
123
+ | `/stats` | Plackett-Luce, Beta posteriors, P(best), Wilson |
124
+ | `/sync` | cut spans ↔ footage time (browser safe) |
125
+ | `/media` | S3 bucket: put by content hash, signed GET |
126
+ | `/cli` | `registerCommands` |
127
+
128
+ ## How it ranks
129
+
130
+ Each person's calls in a batch are one partial ranking by score, 10 down to 1; unmarked reads as 5. Plackett-Luce fits a
131
+ strength per sample across batches. Good rate counts every (sample, person) pair of a closed
132
+ batch. Guides (tips under test) get a with-vs-without good rate on the same pairs.
133
+ Live numbers get a Wilson 95% range and P(best) from Beta posteriors.
134
+
135
+ ## License
136
+
137
+ PolyForm Strict 1.0.0. See `LICENSE.md`.
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `vireo` on its own: DATABASE_URL (postgres) or a local PGlite at VIREO_DIR (default
4
+ * `~/.vireo`: one ledger per person, whatever folder runs it).
5
+ * Migrates on open. VIREO_BUCKET (+ VIREO_S3_ENDPOINT) for files; VIREO_BY names who acts.
6
+ */
7
+ import { homedir, userInfo } from "node:os";
8
+ import { join } from "node:path";
9
+ import { Command } from "commander";
10
+ import { registerCommands } from "./cli.js";
11
+ import { vireo } from "./index.js";
12
+ import { s3Bucket } from "./media.js";
13
+ import { MIGRATIONS } from "./migrations.js";
14
+ async function open() {
15
+ const url = process.env.DATABASE_URL;
16
+ if (url) {
17
+ const { default: postgres } = await import("postgres");
18
+ const { drizzle } = await import("drizzle-orm/postgres-js");
19
+ const { migrate } = await import("drizzle-orm/postgres-js/migrator");
20
+ const sql = postgres(url, { max: 1, onnotice: () => { } });
21
+ const db = drizzle(sql);
22
+ await migrate(db, MIGRATIONS);
23
+ return { db, close: () => sql.end() };
24
+ }
25
+ const { PGlite } = await import("@electric-sql/pglite");
26
+ const { drizzle } = await import("drizzle-orm/pglite");
27
+ const { migrate } = await import("drizzle-orm/pglite/migrator");
28
+ const pg = new PGlite(process.env.VIREO_DIR ?? join(homedir(), ".vireo"));
29
+ const db = drizzle(pg);
30
+ await migrate(db, MIGRATIONS);
31
+ return { db, close: () => pg.close() };
32
+ }
33
+ const bucketName = process.env.VIREO_BUCKET;
34
+ const program = new Command("vireo")
35
+ .description("The variant loop: batches an agent makes, a person's calls and notes, live numbers")
36
+ .showHelpAfterError();
37
+ registerCommands(program, {
38
+ by: process.env.VIREO_BY ?? userInfo().username,
39
+ ...(bucketName
40
+ ? {
41
+ bucket: s3Bucket({
42
+ bucket: bucketName,
43
+ ...(process.env.VIREO_S3_ENDPOINT ? { endpoint: process.env.VIREO_S3_ENDPOINT } : {}),
44
+ }),
45
+ }
46
+ : {}),
47
+ async withVireo(fn) {
48
+ const { db, close } = await open();
49
+ try {
50
+ return await fn(vireo({ db }), db);
51
+ }
52
+ finally {
53
+ await close();
54
+ }
55
+ },
56
+ });
57
+ program.parseAsync().catch((err) => {
58
+ console.error(err instanceof Error ? err.message : String(err));
59
+ process.exit(1);
60
+ });
61
+ //# sourceMappingURL=bin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.js","sourceRoot":"","sources":["../src/bin.ts"],"names":[],"mappings":";AACA;;;;GAIG;AACH,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAE5C,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7C,KAAK,UAAU,IAAI;IACjB,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG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ind, pins } from "./schema.js";
3
+ export type PinRow = typeof pins.$inferSelect;
4
+ /** a sample pin's sample: enough to draw it */
5
+ export interface PinSample {
6
+ id: number;
7
+ batchId: number;
8
+ name: string | null;
9
+ media: string | null;
10
+ poster: string | null;
11
+ keptAt: Date | null;
12
+ }
13
+ /** a pin with its board position (x and y plus its frame's corner); a sample pin, its sample */
14
+ export type PinView = PinRow & {
15
+ at: {
16
+ x: number;
17
+ y: number;
18
+ };
19
+ sample?: PinSample;
20
+ };
21
+ export interface NewPin {
22
+ kind?: PinKind;
23
+ url?: string | null;
24
+ file?: string | null;
25
+ poster?: string | null;
26
+ title?: string | null;
27
+ body?: string | null;
28
+ why?: string | null;
29
+ sampleId?: number | null;
30
+ frameId?: number | null;
31
+ from?: PinFrom | null;
32
+ x?: number | null;
33
+ y?: number | null;
34
+ w?: number | null;
35
+ h?: number | null;
36
+ }
37
+ export interface PinMove {
38
+ id: number;
39
+ x?: number;
40
+ y?: number;
41
+ w?: number | null;
42
+ h?: number | null;
43
+ z?: number;
44
+ /** null: out of its frame, onto the board */
45
+ frameId?: number | null;
46
+ }
47
+ export interface PinEdit {
48
+ id: number;
49
+ title?: string | null;
50
+ body?: string | null;
51
+ why?: string | null;
52
+ url?: string | null;
53
+ poster?: string | null;
54
+ }
55
+ /** the size placement assumes for a pin with none (B5) */
56
+ export declare const PIN_SIZE: Record<PinKind, {
57
+ w: number;
58
+ h: number;
59
+ }>;
60
+ /** The first free cell, row by row, among `taken` (same frame, frame-relative). */
61
+ export declare function freeCell(taken: readonly {
62
+ x: number;
63
+ y: number;
64
+ w: number;
65
+ h: number;
66
+ }[], size: {
67
+ w: number;
68
+ h: number;
69
+ }, top?: number): {
70
+ x: number;
71
+ y: number;
72
+ };
73
+ /** A link's kind from its address: a picture file, a video file, else a link (a post, a page). */
74
+ export declare function kindOfUrl(url: string): PinKind;
75
+ /** Every pin of a subject, frames first, then by z. */
76
+ export declare function boardOf(db: Queryable, subjectId: number): Promise<PinView[]>;
77
+ /** Adds pins; one with no x and y takes the first free cell of its frame or the board (B5). */
78
+ export declare function addPins(tx: Tx, subjectId: number, list: readonly NewPin[], by: string | null): Promise<PinRow[]>;
79
+ /** Moves, resizes and reframes pins of one board in one write. */
80
+ export declare function movePins(tx: Tx, moves: readonly PinMove[]): Promise<PinRow[]>;
81
+ export declare function editPin(tx: Tx, e: PinEdit): Promise<PinRow>;
82
+ /** Removes pins; a removed frame's pins stay where they were on the board. */
83
+ export declare function unpin(tx: Tx, ids: readonly number[]): Promise<number[]>;
84
+ /** A person keeps a pin (B4): a reference, so never a note or a frame. */
85
+ export declare function keepPin(tx: Tx, id: number, on: boolean, by: string | null): Promise<PinRow>;
86
+ /** The Canon add or record a keep made. */
87
+ export declare function setPinCanon(tx: Tx, id: number, canon: string): Promise<PinRow>;
package/dist/board.js ADDED
@@ -0,0 +1,310 @@
1
+ /**
2
+ * A subject's board (designs/2026-11-16-board.md): pins, frames, placement, keep. The store's
3
+ * methods call these inside its write; reads take any queryable.
4
+ */
5
+ import { and, asc, eq, inArray, max, sql } from "drizzle-orm";
6
+ import { VireoError } from "./db.js";
7
+ import { PIN_KINDS, pins, samples } from "./schema.js";
8
+ /** the size placement assumes for a pin with none (B5) */
9
+ export const PIN_SIZE = {
10
+ link: { w: 240, h: 280 },
11
+ image: { w: 240, h: 280 },
12
+ video: { w: 240, h: 280 },
13
+ sample: { w: 240, h: 280 },
14
+ note: { w: 240, h: 160 },
15
+ frame: { w: 820, h: 620 },
16
+ };
17
+ const GAP = 24;
18
+ const ROW = 6;
19
+ const sizeOf = (p) => ({
20
+ w: p.w ?? PIN_SIZE[p.kind].w,
21
+ h: p.h ?? PIN_SIZE[p.kind].h,
22
+ });
23
+ const hits = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
24
+ /** The first free cell, row by row, among `taken` (same frame, frame-relative). */
25
+ export function freeCell(taken, size, top = 0) {
26
+ const cw = PIN_SIZE.link.w + GAP;
27
+ const ch = PIN_SIZE.link.h + GAP;
28
+ for (let i = 0;; i++) {
29
+ const at = { x: (i % ROW) * cw, y: top + Math.floor(i / ROW) * ch };
30
+ if (!taken.some((t) => hits({ ...at, ...size }, t)))
31
+ return at;
32
+ }
33
+ }
34
+ /** A link's kind from its address: a picture file, a video file, else a link (a post, a page). */
35
+ export function kindOfUrl(url) {
36
+ const path = url.split(/[?#]/)[0]?.toLowerCase() ?? "";
37
+ if (/\.(png|jpe?g|gif|webp|avif|svg)$/.test(path))
38
+ return "image";
39
+ if (/\.(mp4|mov|webm|m4v)$/.test(path))
40
+ return "video";
41
+ return "link";
42
+ }
43
+ function kindOf(p) {
44
+ if (p.kind) {
45
+ if (!PIN_KINDS.includes(p.kind))
46
+ throw new VireoError(`a pin is one of ${PIN_KINDS.join(", ")}`);
47
+ return p.kind;
48
+ }
49
+ if (p.sampleId)
50
+ return "sample";
51
+ if (p.url)
52
+ return kindOfUrl(p.url);
53
+ if (p.file)
54
+ return kindOfUrl(p.file) === "video" ? "video" : "image";
55
+ if (p.body)
56
+ return "note";
57
+ throw new VireoError("a pin needs a link, a file, a note or a sample");
58
+ }
59
+ const isUri = (u) => /^(https|s3):\/\/\S+$/i.test(u);
60
+ function checkNew(p, kind) {
61
+ if (p.url && !/^https?:\/\/\S+$/i.test(p.url))
62
+ throw new VireoError(`not a link: ${p.url}`);
63
+ if (p.file && !/^s3:\/\/\S+$/i.test(p.file))
64
+ throw new VireoError(`a file is an s3:// uri`);
65
+ if (p.poster && !isUri(p.poster))
66
+ throw new VireoError(`a poster is an https or s3 uri`);
67
+ if (kind === "note" && !p.body?.trim())
68
+ throw new VireoError("a note needs its text");
69
+ if (kind === "frame" && !p.title?.trim())
70
+ throw new VireoError("a frame needs a title");
71
+ if (kind === "sample" && !p.sampleId)
72
+ throw new VireoError("a sample pin needs --sample");
73
+ if ((kind === "link" || kind === "image" || kind === "video") && !p.url && !p.file)
74
+ throw new VireoError(`a ${kind} pin needs a link or a file`);
75
+ for (const n of ["x", "y", "w", "h"]) {
76
+ const v = p[n];
77
+ if (v != null && !Number.isFinite(v))
78
+ throw new VireoError(`${n} is a number`);
79
+ }
80
+ if ((p.w != null && p.w <= 0) || (p.h != null && p.h <= 0))
81
+ throw new VireoError("a size is above 0");
82
+ }
83
+ /** A pin's frame must be a frame on the same board; frames do not nest. */
84
+ async function checkFrame(db, subjectId, frameId, kind) {
85
+ if (frameId == null)
86
+ return;
87
+ if (kind === "frame")
88
+ throw new VireoError("frames do not nest");
89
+ const [f] = await db.select().from(pins).where(eq(pins.id, frameId));
90
+ if (!f || f.subjectId !== subjectId || f.kind !== "frame")
91
+ throw new VireoError(`no frame ${frameId} on this board`, 404);
92
+ }
93
+ /** Every pin of a subject, frames first, then by z. */
94
+ export async function boardOf(db, subjectId) {
95
+ const rows = await db
96
+ .select()
97
+ .from(pins)
98
+ .where(eq(pins.subjectId, subjectId))
99
+ .orderBy(sql `${pins.kind} = 'frame' desc`, asc(pins.z), asc(pins.id));
100
+ const frames = new Map(rows.filter((r) => r.kind === "frame").map((r) => [r.id, r]));
101
+ const ids = [...new Set(rows.flatMap((r) => (r.sampleId ? [r.sampleId] : [])))];
102
+ const got = ids.length
103
+ ? await db
104
+ .select({
105
+ id: samples.id,
106
+ batchId: samples.batchId,
107
+ name: samples.name,
108
+ media: samples.media,
109
+ poster: samples.poster,
110
+ keptAt: samples.keptAt,
111
+ })
112
+ .from(samples)
113
+ .where(inArray(samples.id, ids))
114
+ : [];
115
+ const sampleOf = new Map(got.map((x) => [x.id, x]));
116
+ return rows.map((r) => {
117
+ const f = r.frameId ? frames.get(r.frameId) : undefined;
118
+ const sample = r.sampleId ? sampleOf.get(r.sampleId) : undefined;
119
+ return {
120
+ ...r,
121
+ at: { x: r.x + (f?.x ?? 0), y: r.y + (f?.y ?? 0) },
122
+ ...(sample ? { sample } : {}),
123
+ };
124
+ });
125
+ }
126
+ /** Adds pins; one with no x and y takes the first free cell of its frame or the board (B5). */
127
+ export async function addPins(tx, subjectId, list, by) {
128
+ if (!list.length)
129
+ throw new VireoError("no pins to add");
130
+ const have = await tx.select().from(pins).where(eq(pins.subjectId, subjectId));
131
+ const [{ top } = { top: null }] = await tx
132
+ .select({ top: max(pins.z) })
133
+ .from(pins)
134
+ .where(eq(pins.subjectId, subjectId));
135
+ let z = (top ?? 0) + 1;
136
+ const out = [];
137
+ for (const p of list) {
138
+ const kind = kindOf(p);
139
+ checkNew(p, kind);
140
+ await checkFrame(tx, subjectId, p.frameId, kind);
141
+ if (p.sampleId) {
142
+ const [s] = await tx
143
+ .select({ subjectId: samples.subjectId })
144
+ .from(samples)
145
+ .where(eq(samples.id, p.sampleId));
146
+ if (!s)
147
+ throw new VireoError(`no sample ${p.sampleId}`, 404);
148
+ }
149
+ const size = { w: p.w ?? PIN_SIZE[kind].w, h: p.h ?? PIN_SIZE[kind].h };
150
+ const frame = p.frameId ?? null;
151
+ // a new frame goes below everything on the board; a pin goes in its frame's free cell
152
+ const at = p.x != null && p.y != null
153
+ ? { x: p.x, y: p.y }
154
+ : kind === "frame"
155
+ ? {
156
+ x: 0,
157
+ y: Math.max(0, ...have.filter((r) => !r.frameId).map((r) => r.y + sizeOf(r).h + GAP * 2)),
158
+ }
159
+ : freeCell(have
160
+ .filter((r) => (r.frameId ?? null) === frame && r.kind !== "frame")
161
+ .map((r) => ({ x: r.x, y: r.y, ...sizeOf(r) })), size, frame ? 56 : 0);
162
+ const [row] = await tx
163
+ .insert(pins)
164
+ .values({
165
+ subjectId,
166
+ kind,
167
+ url: p.url ?? null,
168
+ file: p.file ?? null,
169
+ poster: p.poster ?? null,
170
+ title: p.title?.trim() || null,
171
+ body: p.body?.trim() || null,
172
+ why: p.why?.trim() || null,
173
+ sampleId: p.sampleId ?? null,
174
+ frameId: frame,
175
+ from: p.from ?? null,
176
+ // a Canon reference is in Canon already: keep never adds it again (references feed boards)
177
+ canon: p.from?.canon ?? null,
178
+ x: at.x,
179
+ y: at.y,
180
+ w: p.w ?? null,
181
+ h: p.h ?? null,
182
+ z: kind === "frame" ? 0 : z++,
183
+ by,
184
+ })
185
+ .returning();
186
+ have.push(row);
187
+ out.push(row);
188
+ }
189
+ return out;
190
+ }
191
+ async function pinsOf(tx, ids) {
192
+ const rows = ids.length
193
+ ? await tx
194
+ .select()
195
+ .from(pins)
196
+ .where(inArray(pins.id, [...ids]))
197
+ : [];
198
+ const got = new Map(rows.map((r) => [r.id, r]));
199
+ for (const id of ids)
200
+ if (!got.has(id))
201
+ throw new VireoError(`no pin ${id}`, 404);
202
+ return got;
203
+ }
204
+ /** Moves, resizes and reframes pins of one board in one write. */
205
+ export async function movePins(tx, moves) {
206
+ if (!moves.length)
207
+ return [];
208
+ const got = await pinsOf(tx, moves.map((m) => m.id));
209
+ const subjects = new Set([...got.values()].map((r) => r.subjectId));
210
+ if (subjects.size > 1)
211
+ throw new VireoError("one board per move");
212
+ const out = [];
213
+ for (const m of moves) {
214
+ const cur = got.get(m.id);
215
+ for (const n of ["x", "y", "w", "h", "z"]) {
216
+ const v = m[n];
217
+ if (v != null && !Number.isFinite(v))
218
+ throw new VireoError(`${n} is a number`);
219
+ }
220
+ if ((m.w != null && m.w <= 0) || (m.h != null && m.h <= 0))
221
+ throw new VireoError("a size is above 0");
222
+ if (m.frameId !== undefined)
223
+ await checkFrame(tx, cur.subjectId, m.frameId, cur.kind);
224
+ const [row] = await tx
225
+ .update(pins)
226
+ .set({
227
+ ...(m.x !== undefined ? { x: m.x } : {}),
228
+ ...(m.y !== undefined ? { y: m.y } : {}),
229
+ ...(m.w !== undefined ? { w: m.w } : {}),
230
+ ...(m.h !== undefined ? { h: m.h } : {}),
231
+ ...(m.z !== undefined ? { z: m.z } : {}),
232
+ ...(m.frameId !== undefined ? { frameId: m.frameId } : {}),
233
+ updatedAt: sql `now()`,
234
+ })
235
+ .where(eq(pins.id, m.id))
236
+ .returning();
237
+ out.push(row);
238
+ }
239
+ return out;
240
+ }
241
+ export async function editPin(tx, e) {
242
+ const cur = (await pinsOf(tx, [e.id])).get(e.id);
243
+ if (e.url && !/^https?:\/\/\S+$/i.test(e.url))
244
+ throw new VireoError(`not a link: ${e.url}`);
245
+ if (e.poster && !isUri(e.poster))
246
+ throw new VireoError(`a poster is an https or s3 uri`);
247
+ const text = (v) => (v === undefined ? undefined : v?.trim() || null);
248
+ const set = {
249
+ title: text(e.title),
250
+ body: text(e.body),
251
+ why: text(e.why),
252
+ url: e.url === undefined ? undefined : e.url || null,
253
+ poster: e.poster === undefined ? undefined : e.poster || null,
254
+ };
255
+ if (cur.kind === "note" && set.body === null)
256
+ throw new VireoError("a note needs its text");
257
+ if (cur.kind === "frame" && set.title === null)
258
+ throw new VireoError("a frame needs a title");
259
+ const [row] = await tx
260
+ .update(pins)
261
+ .set({
262
+ ...Object.fromEntries(Object.entries(set).filter(([, v]) => v !== undefined)),
263
+ updatedAt: sql `now()`,
264
+ })
265
+ .where(eq(pins.id, e.id))
266
+ .returning();
267
+ return row;
268
+ }
269
+ /** Removes pins; a removed frame's pins stay where they were on the board. */
270
+ export async function unpin(tx, ids) {
271
+ const got = await pinsOf(tx, ids);
272
+ for (const f of got.values()) {
273
+ if (f.kind !== "frame")
274
+ continue;
275
+ await tx
276
+ .update(pins)
277
+ .set({ x: sql `${pins.x} + ${f.x}`, y: sql `${pins.y} + ${f.y}`, frameId: null })
278
+ .where(eq(pins.frameId, f.id));
279
+ }
280
+ await tx.delete(pins).where(inArray(pins.id, [...ids]));
281
+ return [...ids];
282
+ }
283
+ /** A person keeps a pin (B4): a reference, so never a note or a frame. */
284
+ export async function keepPin(tx, id, on, by) {
285
+ const cur = (await pinsOf(tx, [id])).get(id);
286
+ if (on && (cur.kind === "note" || cur.kind === "frame"))
287
+ throw new VireoError(`a ${cur.kind} is not a reference: keep a link, a picture or a video`);
288
+ if (on && !by)
289
+ throw new VireoError("a keep needs a person");
290
+ const [row] = await tx
291
+ .update(pins)
292
+ .set(on
293
+ ? { keptAt: cur.keptAt ?? sql `now()`, keptBy: cur.keptBy ?? by, updatedAt: sql `now()` }
294
+ : { keptAt: null, keptBy: null, updatedAt: sql `now()` })
295
+ .where(eq(pins.id, id))
296
+ .returning();
297
+ return row;
298
+ }
299
+ /** The Canon add or record a keep made. */
300
+ export async function setPinCanon(tx, id, canon) {
301
+ const [row] = await tx
302
+ .update(pins)
303
+ .set({ canon })
304
+ .where(and(eq(pins.id, id)))
305
+ .returning();
306
+ if (!row)
307
+ throw new VireoError(`no pin ${id}`, 404);
308
+ return row;
309
+ }
310
+ //# sourceMappingURL=board.js.map