inkwire-receiver-core 0.1.1 → 1.0.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.
@@ -0,0 +1,223 @@
1
+ import assert from "node:assert/strict";
2
+ const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64");
3
+ const T0 = Date.parse("2026-07-22T04:00:00.000Z");
4
+ const iso = (minutes) => new Date(T0 + minutes * 60_000).toISOString();
5
+ export function entry(over = {}) {
6
+ const slug = over.slug ?? "hello";
7
+ return {
8
+ key: "default",
9
+ external_id: over.external_id === undefined ? `ext-${slug}` : over.external_id,
10
+ kind: "post",
11
+ title: "Hello",
12
+ slug,
13
+ markdown: "# Hello\n\nbody",
14
+ html: "<h1>Hello</h1>\n<p>body</p>",
15
+ seo: null,
16
+ status: "published",
17
+ published_at: iso(0),
18
+ updated_at: iso(0),
19
+ version: 1,
20
+ ...over,
21
+ };
22
+ }
23
+ export function runStoreContract(o) {
24
+ const { describe, test } = o;
25
+ const A = "scope-a";
26
+ const B = "scope-b";
27
+ async function withStore(fn) {
28
+ const { store, cleanup } = await o.create();
29
+ try {
30
+ await fn(store);
31
+ }
32
+ finally {
33
+ await cleanup?.();
34
+ }
35
+ }
36
+ const page = (store, key, limit, cursor) => store.list(key, { limit, ...(cursor ? { cursor } : {}) });
37
+ describe(`Inkwire store contract: ${o.name}`, () => {
38
+ test("save creates an entry; get returns it with an id, the scope, a url and an etag", () => withStore(async (store) => {
39
+ const saved = await store.save(A, entry({ tags: ["seo", "ai"], categories: ["Guides", "News"], excerpt: "Short", cover_image_url: "https://x.test/c.jpg", cover_image_alt: "A cover", canonical_url: "https://x.test/p", author: { name: "Isaac", email: "i@x.test" }, seo: { title: "T", noindex: true, og_title: "OG", og_description: "OGD", json_ld: '{"@type":"FAQPage"}' } }));
40
+ assert.ok(saved.id, "id");
41
+ assert.equal(saved.key, A);
42
+ assert.ok(saved.url, "url");
43
+ if (o.expectUrl)
44
+ assert.equal(saved.url, o.expectUrl(saved));
45
+ assert.ok(saved.etag, "etag");
46
+ const got = await store.get(A, saved.id);
47
+ assert.ok(got);
48
+ for (const k of ["external_id", "kind", "title", "slug", "markdown", "html", "excerpt", "tags", "categories", "cover_image_url", "cover_image_alt", "canonical_url", "seo", "author", "status", "published_at", "updated_at", "version"]) {
49
+ assert.deepEqual(got[k], saved[k], `get() and save() agree on ${k}`);
50
+ }
51
+ assert.deepEqual(got.tags, ["seo", "ai"]);
52
+ assert.deepEqual(got.categories, ["Guides", "News"]);
53
+ assert.equal(got.cover_image_alt, "A cover");
54
+ assert.deepEqual(got.seo, { title: "T", noindex: true, og_title: "OG", og_description: "OGD", json_ld: '{"@type":"FAQPage"}' });
55
+ assert.deepEqual(got.author, { name: "Isaac", email: "i@x.test" });
56
+ assert.equal(got.published_at, iso(0), "dates come back as the same ISO string");
57
+ }));
58
+ test("get of an unknown id is null, not an error", () => withStore(async (store) => {
59
+ assert.equal(await store.get(A, "does-not-exist"), null);
60
+ }));
61
+ test("optional fields that were not set come back absent (undefined), never null or empty", () => withStore(async (store) => {
62
+ const saved = await store.save(A, entry());
63
+ const got = (await store.get(A, saved.id));
64
+ for (const k of ["excerpt", "tags", "categories", "cover_image_url", "cover_image_alt", "canonical_url", "author"]) {
65
+ assert.equal(got[k], undefined, `${k} must be undefined, not ${JSON.stringify(got[k])} (map a NULL column to undefined)`);
66
+ }
67
+ assert.equal(got.seo, null, "seo is null when there are no overrides");
68
+ assert.equal(got.external_id, saved.external_id);
69
+ }));
70
+ test("an entry written by hand has external_id null and is first-class", () => withStore(async (store) => {
71
+ const saved = await store.save(A, entry({ slug: "by-hand", external_id: null }));
72
+ assert.equal((await store.get(A, saved.id))?.external_id, null);
73
+ assert.equal((await store.list(A, { limit: 10 })).items.length, 1);
74
+ }));
75
+ test("an update keeps the id, moves the etag, and a slug or kind change moves the entry", () => withStore(async (store) => {
76
+ const first = await store.save(A, entry({ slug: "old-slug" }));
77
+ const second = await store.save(A, entry({ id: first.id, slug: "new-slug", title: "Renamed", version: 2, updated_at: iso(5) }));
78
+ const opaque = o.opaqueIds !== false;
79
+ if (opaque)
80
+ assert.equal(second.id, first.id, "id survives a slug change");
81
+ else
82
+ assert.equal(await store.get(A, first.id), null, "a place-derived id stops resolving after the move");
83
+ assert.notEqual(second.etag, first.etag, "etag changes on every accepted write");
84
+ assert.equal((await store.get(A, second.id))?.slug, "new-slug");
85
+ assert.equal((await store.list(A, { slug: "old-slug", limit: 5 })).items.length, 0, "the old slug is free");
86
+ assert.equal((await store.list(A, { slug: "new-slug", limit: 5 })).items.length, 1);
87
+ assert.equal((await store.list(A, { limit: 10 })).items.length, 1, "no duplicate left behind");
88
+ if (o.singleKind)
89
+ return;
90
+ const third = await store.save(A, entry({ id: second.id, slug: "new-slug", kind: "page", version: 3, updated_at: iso(6) }));
91
+ if (opaque)
92
+ assert.equal(third.id, first.id);
93
+ assert.equal((await store.list(A, { kind: "post", limit: 5 })).items.length, 0);
94
+ assert.equal((await store.list(A, { kind: "page", limit: 5 })).items.length, 1);
95
+ }));
96
+ test("the etag changes when only the body changes", () => withStore(async (store) => {
97
+ const first = await store.save(A, entry());
98
+ const second = await store.save(A, entry({ id: first.id, markdown: "changed", html: "<p>changed</p>", version: 2, updated_at: iso(1) }));
99
+ assert.notEqual(second.etag, first.etag);
100
+ assert.equal((await store.get(A, first.id))?.etag, second.etag, "get() reports the etag the last save returned");
101
+ }));
102
+ test("list filters: status, kind, tag, search, external_id, slug", () => withStore(async (store) => {
103
+ await store.save(A, entry({ slug: "one", external_id: "e1", title: "The Needle", tags: ["a", "b"], categories: ["Guides"] }));
104
+ await store.save(A, entry({ slug: "two", external_id: "e2", status: "draft", kind: o.singleKind ? "post" : "page", markdown: "haystack with a NEEDLE inside", updated_at: iso(1) }));
105
+ await store.save(A, entry({ slug: "three", external_id: "e3", excerpt: "needle in the excerpt", tags: ["b"], updated_at: iso(2) }));
106
+ const slugs = async (f) => (await store.list(A, f)).items.map((e) => e.slug).sort();
107
+ assert.deepEqual(await slugs({ limit: 10 }), ["one", "three", "two"]);
108
+ assert.deepEqual(await slugs({ status: "draft", limit: 10 }), ["two"]);
109
+ assert.deepEqual(await slugs({ kind: "page", limit: 10 }), o.singleKind ? [] : ["two"]);
110
+ assert.deepEqual(await slugs({ tag: "b", limit: 10 }), ["one", "three"]);
111
+ assert.deepEqual(await slugs({ tag: "nope", limit: 10 }), []);
112
+ assert.deepEqual(await slugs({ category: "Guides", limit: 10 }), ["one"]);
113
+ assert.deepEqual(await slugs({ category: "guides", limit: 10 }), [], "category matches exactly");
114
+ assert.deepEqual(await slugs({ search: "needle", limit: 10 }), ["one", "three", "two"], "case-insensitive over title, excerpt and markdown");
115
+ assert.deepEqual(await slugs({ external_id: "e2", limit: 10 }), ["two"], "exact external_id");
116
+ assert.deepEqual(await slugs({ external_id: "e", limit: 10 }), [], "external_id is not a prefix match");
117
+ assert.deepEqual(await slugs({ slug: "one", limit: 10 }), ["one"]);
118
+ assert.deepEqual(await slugs({ slug: "on", limit: 10 }), [], "slug is not a prefix match");
119
+ assert.deepEqual(await slugs({ kind: "post", slug: "one", limit: 10 }), ["one"], "filters combine");
120
+ }));
121
+ test("list is newest first by updated_at and pages without repeating or skipping, even when an entry changes between pages", () => withStore(async (store) => {
122
+ for (let i = 0; i < 7; i++)
123
+ await store.save(A, entry({ slug: `p${i}`, external_id: `e${i}`, updated_at: iso(i) }));
124
+ const first = await page(store, A, 3);
125
+ assert.deepEqual(first.items.map((e) => e.slug), ["p6", "p5", "p4"], "newest first");
126
+ assert.ok(first.next_cursor, "a cursor when there is more");
127
+ // a new entry and an edit to an entry already on page one, between the two requests
128
+ await store.save(A, entry({ slug: "fresh", external_id: "efresh", updated_at: iso(50) }));
129
+ const edited = first.items[0];
130
+ await store.save(A, entry({ id: edited.id, slug: edited.slug, external_id: edited.external_id, version: 2, updated_at: iso(60) }));
131
+ const second = await page(store, A, 3, first.next_cursor);
132
+ assert.deepEqual(second.items.map((e) => e.slug), ["p3", "p2", "p1"], "page two continues where page one stopped");
133
+ const third = await page(store, A, 3, second.next_cursor);
134
+ assert.deepEqual(third.items.map((e) => e.slug), ["p0"]);
135
+ assert.equal(third.next_cursor, null, "no cursor on the last page");
136
+ }));
137
+ test("a cursor the store did not issue is rejected with an invalid_payload error", () => withStore(async (store) => {
138
+ await store.save(A, entry());
139
+ await assert.rejects(() => page(store, A, 3, "not-a-cursor"), (e) => e.code === "invalid_payload");
140
+ }));
141
+ test("scopes are isolated: another key sees none of it, can not read, list or remove it", () => withStore(async (store) => {
142
+ if (o.scoped === false)
143
+ return;
144
+ const mine = await store.save(A, entry({ slug: "mine" }));
145
+ await store.save(B, entry({ slug: "mine", external_id: "ext-mine" }));
146
+ assert.equal((await store.list(B, { limit: 10 })).items.length, 1, "B sees only its own entry, same slug and external_id are allowed in each scope");
147
+ assert.equal(await store.get(B, mine.id), null);
148
+ assert.equal(await store.remove(B, mine.id), false);
149
+ assert.ok(await store.get(A, mine.id), "A's entry survived B's remove");
150
+ assert.equal((await store.list(A, { external_id: "ext-mine", limit: 5 })).items.length, 1);
151
+ }));
152
+ test("remove returns true once, false after, and the entry is gone", () => withStore(async (store) => {
153
+ const saved = await store.save(A, entry());
154
+ assert.equal(await store.remove(A, saved.id), true);
155
+ assert.equal(await store.remove(A, saved.id), false);
156
+ assert.equal(await store.get(A, saved.id), null);
157
+ assert.equal((await store.list(A, { limit: 5 })).items.length, 0);
158
+ }));
159
+ test("concurrent saves of different entries all land", () => withStore(async (store) => {
160
+ await Promise.all(Array.from({ length: 12 }, (_, i) => store.save(A, entry({ slug: `c${i}`, external_id: `ec${i}`, updated_at: iso(i) }))));
161
+ const all = await store.list(A, { limit: 100 });
162
+ assert.equal(all.items.length, 12);
163
+ assert.equal(new Set(all.items.map((e) => e.id)).size, 12, "ids are unique");
164
+ }));
165
+ test("unicode and long markdown survive the round trip", () => withStore(async (store) => {
166
+ const markdown = `# Été à Paris — ñ 日本 🚀\n\n${"line of text\n".repeat(5000)}`;
167
+ const saved = await store.save(A, entry({ slug: "unicode", title: "Été à Paris — ñ 日本 🚀", markdown }));
168
+ const got = await store.get(A, saved.id);
169
+ assert.equal(got?.title, "Été à Paris — ñ 日本 🚀");
170
+ assert.equal(got?.markdown, markdown);
171
+ }));
172
+ test("saveMedia (when the store has it) returns an id and a url, and keeps the alt text", () => withStore(async (store) => {
173
+ if (!store.saveMedia)
174
+ return;
175
+ const m = await store.saveMedia(A, { bytes: PNG, contentType: "image/png", filename: "px.png", alt: "One pixel" });
176
+ assert.ok(m.id && m.url);
177
+ assert.equal(m.alt, "One pixel");
178
+ assert.equal(m.mime_type, "image/png");
179
+ assert.ok(!Number.isNaN(Date.parse(m.created_at)), "created_at is a timestamp");
180
+ const bare = await store.saveMedia(A, { bytes: PNG, contentType: "image/png", filename: "px.png" });
181
+ assert.equal(bare.alt, undefined);
182
+ assert.notEqual(bare.id, m.id);
183
+ }));
184
+ test("listMedia (when the store has it): newest first, search over alt, title and filename, stable paging", () => withStore(async (store) => {
185
+ if (!store.saveMedia || !store.listMedia)
186
+ return;
187
+ const ids = [];
188
+ for (const [i, alt] of ["alpha", "beta", "gamma"].entries()) {
189
+ ids.push((await store.saveMedia(A, { bytes: PNG, contentType: "image/png", filename: `${alt}-file.png`, alt: `${alt} alt` })).id);
190
+ if (i < 2)
191
+ await new Promise((r) => setTimeout(r, 15));
192
+ }
193
+ const all = await store.listMedia(A, { limit: 10 });
194
+ assert.deepEqual(all.items.map((m) => m.id), [ids[2], ids[1], ids[0]], "newest first");
195
+ assert.equal(all.next_cursor, null);
196
+ assert.deepEqual((await store.listMedia(A, { search: "BETA", limit: 10 })).items.map((m) => m.id), [ids[1]], "alt, case-insensitive");
197
+ assert.deepEqual((await store.listMedia(A, { search: "gamma-file", limit: 10 })).items.map((m) => m.id), [ids[2]], "filename");
198
+ const first = await store.listMedia(A, { limit: 2 });
199
+ assert.equal(first.items.length, 2);
200
+ assert.ok(first.next_cursor);
201
+ const second = await store.listMedia(A, { limit: 2, cursor: first.next_cursor });
202
+ assert.deepEqual([...first.items, ...second.items].map((m) => m.id), [ids[2], ids[1], ids[0]]);
203
+ assert.equal(second.next_cursor, null);
204
+ await assert.rejects(() => store.listMedia(A, { limit: 2, cursor: "!!!" }), (e) => e.code === "invalid_payload");
205
+ }));
206
+ test("updateMedia (when the store has it) sets, clears and keeps; an unknown id is null", () => withStore(async (store) => {
207
+ if (!store.saveMedia || !store.updateMedia)
208
+ return;
209
+ const m = await store.saveMedia(A, { bytes: PNG, contentType: "image/png", filename: "px.png", alt: "old" });
210
+ const set = await store.updateMedia(A, m.id, { alt: "new", title: "A title" });
211
+ assert.deepEqual([set?.alt, set?.title, set?.id, set?.url, set?.mime_type, set?.created_at], ["new", "A title", m.id, m.url, "image/png", m.created_at]);
212
+ const cleared = await store.updateMedia(A, m.id, { alt: null });
213
+ assert.equal(cleared?.alt, undefined);
214
+ assert.equal(cleared?.title, "A title", "an absent key keeps its value");
215
+ if (store.listMedia) {
216
+ const listed = (await store.listMedia(A, { limit: 10 })).items.find((x) => x.id === m.id);
217
+ assert.deepEqual([listed?.alt, listed?.title], [undefined, "A title"], "the library shows the edit");
218
+ }
219
+ assert.equal(await store.updateMedia(A, "0123456789abcdef", { alt: "x" }), null);
220
+ assert.equal(await store.updateMedia(A, "../../etc/passwd", { alt: "x" }), null, "a hostile id never reaches a path");
221
+ }));
222
+ });
223
+ }
package/package.json CHANGED
@@ -1,12 +1,50 @@
1
1
  {
2
- "name": "inkwire-receiver-core", "version": "0.1.1", "type": "module",
3
- "description": "Shared TS core (validate, render, sanitize, upsert) for building an Inkwire receiver.",
2
+ "name": "inkwire-receiver-core",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "Shared TS core (validate, render, sanitize, read, edit, media, stores) for building an Inkwire receiver.",
4
6
  "license": "MIT",
5
- "repository": { "type": "git", "url": "git+https://github.com/etugrand/inkwire.git", "directory": "inkwire/receivers/core-ts" },
6
- "main": "dist/index.js", "types": "dist/index.d.ts",
7
- "files": ["dist"],
8
- "scripts": { "build": "tsc", "test": "vitest run" },
9
- "dependencies": { "zod": "^3.23.8", "markdown-it": "^14.1.0", "sanitize-html": "^2.13.1" },
10
- "devDependencies": { "vitest": "^2.1.0", "typescript": "^5.5.0",
11
- "@types/markdown-it": "^14.1.2", "@types/sanitize-html": "^2.13.0", "@types/node": "^22.5.0" }
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/dahoai/inkwire.git",
10
+ "directory": "inkwire/receivers/core-ts"
11
+ },
12
+ "main": "dist/index.js",
13
+ "types": "dist/index.d.ts",
14
+ "files": [
15
+ "dist/**/*.js",
16
+ "dist/**/*.d.ts",
17
+ "!dist/**/*.test.*"
18
+ ],
19
+ "scripts": {
20
+ "build": "tsc -p tsconfig.build.json",
21
+ "typecheck": "tsc -p tsconfig.json",
22
+ "test": "node --import tsx --test \"test/*.test.ts\"",
23
+ "conformance": "npm run build && node test/run-conformance.mjs",
24
+ "prepublishOnly": "npm run build"
25
+ },
26
+ "dependencies": {
27
+ "markdown-it": "^14.1.0",
28
+ "sanitize-html": "^2.13.1",
29
+ "yaml": "^2.9.1",
30
+ "zod": "^3.23.8"
31
+ },
32
+ "devDependencies": {
33
+ "@types/markdown-it": "^14.1.2",
34
+ "@types/node": "^22.5.0",
35
+ "@types/sanitize-html": "^2.13.0",
36
+ "tsx": "^4.19.0",
37
+ "typescript": "^5.5.0"
38
+ },
39
+ "exports": {
40
+ ".": {
41
+ "types": "./dist/index.d.ts",
42
+ "default": "./dist/index.js"
43
+ },
44
+ "./testing": {
45
+ "types": "./dist/testing.d.ts",
46
+ "default": "./dist/testing.js"
47
+ },
48
+ "./package.json": "./package.json"
49
+ }
12
50
  }
@@ -1 +0,0 @@
1
- export {};
@@ -1,56 +0,0 @@
1
- import { it, expect, beforeEach } from "vitest";
2
- import { handlePost } from "../handle";
3
- import { MemoryStore } from "../store";
4
- let store;
5
- const keys = ["secret-key"];
6
- const auth = "Bearer secret-key";
7
- beforeEach(() => { store = new MemoryStore(); });
8
- it("creates a published post", async () => {
9
- const r = await handlePost({ authHeader: auth, apiKeys: keys, store,
10
- rawBody: { external_id: "a", title: "T", markdown: "# H", status: "published" } });
11
- expect(r.status).toBe(200);
12
- expect(r.body).toMatchObject({ created: true, status: "published" });
13
- expect(r.headers["Inkwire-Version"]).toBe("1");
14
- });
15
- it("upserts on external_id", async () => {
16
- const base = { external_id: "a", markdown: "x" };
17
- await handlePost({ authHeader: auth, apiKeys: keys, store, rawBody: { ...base, title: "One" } });
18
- const r = await handlePost({ authHeader: auth, apiKeys: keys, store, rawBody: { ...base, title: "Two" } });
19
- expect(r.body).toMatchObject({ created: false });
20
- });
21
- it("defaults status to draft", async () => {
22
- const r = await handlePost({ authHeader: auth, apiKeys: keys, store,
23
- rawBody: { external_id: "b", title: "T", markdown: "x" } });
24
- expect(r.body).toMatchObject({ status: "draft" });
25
- });
26
- it("rejects missing title with 400 invalid_payload", async () => {
27
- const r = await handlePost({ authHeader: auth, apiKeys: keys, store, rawBody: { external_id: "c", markdown: "x" } });
28
- expect(r.status).toBe(400);
29
- expect(r.body.error.code).toBe("invalid_payload");
30
- });
31
- it("rejects bad auth with 401", async () => {
32
- const r = await handlePost({ authHeader: "Bearer nope", apiKeys: keys, store,
33
- rawBody: { external_id: "d", title: "T", markdown: "x" } });
34
- expect(r.status).toBe(401);
35
- expect(r.body.error.code).toBe("unauthorized");
36
- });
37
- it("dedupes a 255-char slug without exceeding the length cap", async () => {
38
- const longTitle = "a".repeat(300);
39
- const first = await handlePost({ authHeader: auth, apiKeys: keys, store,
40
- rawBody: { external_id: "long-1", title: longTitle, markdown: "x" } });
41
- const second = await handlePost({ authHeader: auth, apiKeys: keys, store,
42
- rawBody: { external_id: "long-2", title: longTitle, markdown: "x" } });
43
- const firstSlug = first.body.slug;
44
- const secondSlug = second.body.slug;
45
- expect(firstSlug.length).toBe(255);
46
- expect(secondSlug.length).toBeLessThanOrEqual(255);
47
- expect(secondSlug).not.toBe(firstSlug);
48
- });
49
- it("409 on explicit slug owned by a different external_id", async () => {
50
- await handlePost({ authHeader: auth, apiKeys: keys, store,
51
- rawBody: { external_id: "owner", title: "O", markdown: "x", slug: "taken" } });
52
- const r = await handlePost({ authHeader: auth, apiKeys: keys, store,
53
- rawBody: { external_id: "other", title: "X", markdown: "x", slug: "taken" } });
54
- expect(r.status).toBe(409);
55
- expect(r.body.error.code).toBe("conflict");
56
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,17 +0,0 @@
1
- import { describe, it, expect } from "vitest";
2
- import { renderMarkdown } from "../render";
3
- describe("renderMarkdown", () => {
4
- it("renders markdown to html", () => {
5
- expect(renderMarkdown("# Hi")).toContain("<h1>Hi</h1>");
6
- });
7
- it("strips script tags and their contents", () => {
8
- const html = renderMarkdown("Hi\n\n<script>alert(1)</script>");
9
- expect(html).not.toContain("<script>");
10
- expect(html).not.toContain("alert(1)");
11
- });
12
- it("strips event handlers and javascript: urls", () => {
13
- const html = renderMarkdown('<a href="javascript:alert(1)" onclick="x()">z</a>');
14
- expect(html).not.toContain("onclick");
15
- expect(html).not.toContain("javascript:");
16
- });
17
- });