Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(skills): social post previews, with local videos that play in the chat (#4209)
Milind Sonid58ef29f8e1e
diff --git a/NOTICE b/NOTICEindex 2abb0da4dc..0abb3ef54a 100644--- a/NOTICE+++ b/NOTICE@@ -57,6 +57,13 @@ viewers and screencast pacing, tool definitions and snapshot bound(apps/server/src/preview and apps/server/src/mcp), Copyright 2026 T3 ToolsInc., used under the MIT License (third_party/t3-code/LICENSE).+The social post previews template (skills/social-posts/posts.html) adapts the+post card markup and platform styling of MiniMock,+https://github.com/minianon/MiniMock, Copyright (c) 2026 Tushar Bhardwaj, used+under the MIT License (third_party/minimock/LICENSE). Its icon paths are from+Lucide, https://lucide.dev, Copyright Lucide Contributors, used under the ISC+License; the template carries both notices, so every copy of it keeps them.+The browser desktop viewer bundles the unmodified noVNC 1.7.0 library,Copyright the noVNC authors, under MPL-2.0 and its accompanying licenses.Attribution, license terms and the corresponding source location are indiff --git a/server/app-docs.ts b/server/app-docs.tsindex d18ab92bf9..5fbcf28285 100644--- a/server/app-docs.ts+++ b/server/app-docs.ts@@ -6,6 +6,7 @@ import { mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync,import { join } from "node:path";import type { AppNetwork, AppSource, AppToolDefinition, AppToolResult } from "../shared/app.ts";+import type { PageVideo } from "./pages/bundle.ts";export const APP_DOCS_MAX_BYTES = 512 * 1024 * 1024;export const APP_DOCS_SWEEP_GRACE_MS = 10 * 60_000;@@ -21,6 +22,8 @@ export interface AppDocData {* index.html by its path in the folder. */folder?: string;files?: Record<string, string>;+ /** Videos that stay on disk, by path in the folder. They take no room in this store. */+ videos?: Record<string, PageVideo>;tool?: AppToolDefinition;toolInput?: Record<string, unknown>;toolResult?: AppToolResult;@@ -99,6 +102,12 @@ export class AppDocs {try { return readFileSync(this.path("file", id)); } catch { return null; }}+ /** A video this document recorded when it was shown; nothing else is ever a video of this page. */+ video(doc: string, path: string): PageVideo | null {+ const videos = this.read(doc)?.data?.videos;+ return videos && Object.hasOwn(videos, path) ? videos[path]! : null;+ }+put(input: { source: AppSource; html: string; data?: AppDocData; files?: ReadonlyArray<{ path: string; data: Buffer }> }): AppDocPut {const html = input.html;const blobs = (input.files ?? []).map((file) => ({ path: file.path, data: file.data, id: createHash("sha256").update(file.data).digest("hex") }));diff --git a/server/chat-apps.test.ts b/server/chat-apps.test.tsindex e1d3a69265..e8f2f757f5 100644--- a/server/chat-apps.test.ts+++ b/server/chat-apps.test.ts@@ -1,4 +1,4 @@-import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from "node:fs";+import { mkdirSync, mkdtempSync, realpathSync, statSync, symlinkSync, truncateSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";@@ -225,6 +225,39 @@ describe("a folder page", () => {expect(appDocument({ store, docs, threadId: THREAD, messageId: "m2", files: FILES })!.srcdoc).not.toContain("<base");});+ it("records a video where it is, for the chat only: not stored, not counted, not published", async () => {+ const { docs, store, row } = setup([], 2_000);+ const where = folders();+ const film = join(where.mine, "dash", "clip.mp4");+ writeFileSync(film, "");+ truncateSync(film, 6 * 1024 * 1024 * 1024);+ writeFileSync(join(where.mine, "dash", "notes.mkv"), "not a page's video");+ expect(await createAppCard({ store, docs, bot: SCOUT, threadId: THREAD, input: { tool: "show_html", path: "dash", title: "Dash" }, folders: where.of })).toEqual({ ok: true, messageId: "m1" });+ const doc = row("m1").app!.doc;+ const before = statSync(film, { bigint: true });+ expect(docs.video(doc, "clip.mp4")).toEqual({ file: realpathSync.native(film), bytes: 6 * 1024 * 1024 * 1024, dev: String(before.dev), ino: String(before.ino), mtimeNs: String(before.mtimeNs) });+ expect(docs.video(doc, "notes.mkv")).toBeNull();+ expect(row("m1").app!.bytes).toBe(58 + 6 * 1024 * 1024 * 1024);+ expect(docs.usage()).toBeLessThan(2_000);+ expect(docs.readFile(doc, "clip.mp4")).toBeNull();+ const page = publishablePage({ store, docs, threadId: THREAD, messageId: "m1" });+ if (!page.ok) throw new Error(page.error);+ expect(page.files.map((file) => file.path).sort()).toEqual(["app.js", "data.parquet", "index.html"]);++ const published = await readPageBundle("dash", [where.mine]);+ expect(published.skipped.sort()).toEqual(["clip.mp4", "notes.mkv"]);+ expect(published.videos).toBeUndefined();+ });++ it("will not record a video reached by a link out of the bot's folders", async () => {+ const { docs, store, row } = setup();+ const where = folders();+ writeFileSync(join(where.theirs, "secret", "theirs.mp4"), "moov");+ symlinkSync(join(where.theirs, "secret", "theirs.mp4"), join(where.mine, "dash", "link.mp4"));+ await createAppCard({ store, docs, bot: SCOUT, threadId: THREAD, input: { tool: "show_html", path: "dash", title: "Dash" }, folders: where.of });+ expect(docs.video(row("m1").app!.doc, "link.mp4")).toBeNull();+ });+it("is refused outside the bot's own folders, without index.html, or where folders aren't known", async () => {const { rows, docs, store } = setup();const where = folders();@@ -290,6 +323,20 @@ describe("publish_page in the chat", () => {expect(row("m1")).toMatchObject({ app: { rev: 1 }, publishedPage: { url: `${LIVE.url}?again` } });});+ it("keeps the card's video playing when the same folder is published", async () => {+ const { store, docs, row } = setup();+ const { base, bundle } = await folder();+ writeFileSync(join(base, "dash", "clip.webm"), "webm");+ await createAppCard({ store, docs, bot: SCOUT, threadId: THREAD, input: { tool: "show_html", path: "dash", title: "Dash" }, folders: async () => ({ roots: [base], vmWorkspace: null }) });+ writeFileSync(join(base, "dash", "index.html"), "<h1>Dash, edited</h1>");+ const published = await bundle();+ expect(published.skipped).toEqual(["clip.webm"]);+ expect(showPublishedPage({ store, docs, threadId: THREAD, card: LIVE, bundle: published })).toBe("m1");+ expect(row("m1")).toMatchObject({ publishedPage: LIVE, app: { rev: 1 } });+ expect(docs.read(row("m1").app!.doc)!.html).toBe("<h1>Dash, edited</h1>");+ expect(docs.video(row("m1").app!.doc, "clip.webm")).toMatchObject({ bytes: 4 });+ });+it("leaves a room, a limit card and a page with no index.html to the plain link card", async () => {const { store, docs, rows } = setup(["room-1"]);const { bundle } = await folder();diff --git a/server/chat-apps.ts b/server/chat-apps.tsindex d3c9827e82..b685a725d4 100644--- a/server/chat-apps.ts+++ b/server/chat-apps.ts@@ -7,7 +7,7 @@ import {import { BOT_HTML_NETWORK } from "../shared/app-frame/csp.ts";import { botHtmlDocument, mcpAppDocument, publishedBotHtml } from "../shared/app-frame/document.ts";import { jsxPublishedHtml } from "../shared/app-frame/jsx-page.ts";-import { AppDocs, type AppDocPut } from "./app-docs.ts";+import { AppDocs, type AppDocData, type AppDocPut } from "./app-docs.ts";import type { AgentCardResult, AgentCardStore } from "./chat-widgets.ts";import { compileJsxPage } from "./jsx-compile.ts";import { appDocRefs } from "./message-db.ts";@@ -46,7 +46,7 @@ function scrubbed(html: string, title: string): { html: string; title: string; m}/** A folder page also carries the files beside its index.html and where they were read. */-type PageText = { html: string; format?: "jsx"; files?: PageFile[]; folder?: string };+type PageText = { html: string; format?: "jsx"; files?: PageFile[]; folder?: string; videos?: AppDocData["videos"] };type MadePage = { ok: true; page: PageText; title: string; masked: boolean };/** The page's text, scrubbed; a jsx page is transpiled first, so one that cannot run is refused with where. */@@ -68,7 +68,8 @@ export function bundlePage(bundle: PageBundle, title: string): MadePage | { ok:return { ok: false, error: `path: index.html is over the ${APP_LIMITS.htmlBytes}-byte limit; move data into files beside it.` };}const page = scrubbed(html, title);- return { ok: true, page: { html: page.html, files: bundle.files.filter((file) => file !== index), folder: bundle.source }, title: page.title, masked: page.masked };+ const videos = bundle.videos && Object.keys(bundle.videos).length ? { videos: bundle.videos } : {};+ return { ok: true, page: { html: page.html, files: bundle.files.filter((file) => file !== index), folder: bundle.source, ...videos }, title: page.title, masked: page.masked };}async function folderPage(path: string, title: string, folders: BotFolders): Promise<MadePage | { ok: false; status: 400 | 403 | 404; error: string }> {@@ -83,11 +84,12 @@ async function folderPage(path: string, title: string, folders: BotFolders): Pro}function storePage(docs: AppDocs, page: PageText): AppDocPut {- const data = { ...(page.format ? { format: page.format } : {}), ...(page.folder ? { folder: page.folder } : {}) };+ const data = { ...(page.format ? { format: page.format } : {}), ...(page.folder ? { folder: page.folder } : {}), ...(page.videos ? { videos: page.videos } : {}) };return docs.put({ source: "html", html: page.html, ...(Object.keys(data).length ? { data } : {}), ...(page.files ? { files: page.files } : {}) });}-const pageBytes = (page: PageText) => Buffer.byteLength(page.html) + (page.files ?? []).reduce((sum, file) => sum + file.data.byteLength, 0);+const pageBytes = (page: PageText) => Buffer.byteLength(page.html) + (page.files ?? []).reduce((sum, file) => sum + file.data.byteLength, 0) ++ Object.values(page.videos ?? {}).reduce((sum, video) => sum + video.bytes, 0);const pageFallback = (title: string, page: PageText, given?: string) =>redactSecretsInText(htmlFallbackText(title, page.format === "jsx" ? "" : page.html, given));@@ -270,6 +272,8 @@ export function showPublishedPage(args: {message.kind === "app" && isRecord(message.app) && message.app.source === "html" && !message.from).reverse().find((message) => message.app.doc && docs.read(message.app.doc)?.data?.folder === bundle.source);if (shown) {+ const videos = docs.read(shown.app.doc)?.data?.videos;+ if (videos) made.page.videos = videos;const replaced = replacePage(store, docs, threadId, shown, made);return replaced && store.patchMessage(threadId, shown.id, { publishedPage: card }) ? shown.id : null;}diff --git a/server/folder-pages.e2e.test.ts b/server/folder-pages.e2e.test.tsindex f5b5044fcd..f46489684f 100644--- a/server/folder-pages.e2e.test.ts+++ b/server/folder-pages.e2e.test.ts@@ -3,7 +3,7 @@// folder gives the same card its link. One loopback stub stands in for the pages service; no model is called.import { randomBytes } from "node:crypto";import { createServer, type Server } from "node:http";-import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { join } from "node:path";import { afterAll, beforeAll, expect, it } from "vitest";import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";@@ -106,3 +106,42 @@ it("shows a dashboard folder inline, serves its Parquet to the frame by token on.toEqual([[appId, "live", `https://${pageId}.mausbot.page/`]]);expect(rows.filter((message) => message.publishedPage && message.kind !== "app")).toEqual([]);}, 120_000);++it("streams a folder's video to the card by byte range, leaves it out of a publish, and refuses it once the file is replaced", async () => {+ const cli = (...args: string[]) => runControlOmb(args, { env: { OPENMAUSBOT_URL: fixture.info.url } }) as Promise<any>;+ const api = async (path: string) => (await fetch(`${fixture.info.url}${path}`, { headers: { "content-type": "application/json" } })).json() as Promise<any>;+ const planPath = join(fixture.info.dataDir, "room-plan.json");+ const reply = (botId: string) => readFileSync(`${planPath}.evidence.jsonl`, "utf8").trim().split("\n").map((line) => JSON.parse(line)).filter((entry: any) => entry.botId === botId)+ .at(-1).evidence.find((entry: any) => entry.step).response.result.content[0].text as string;+ const turn = async (bot: any, step: unknown) => {+ writeFileSync(planPath, JSON.stringify({ [bot.id]: { steps: [step], reply: "Done." } }));+ await cli("send", "--bot", bot.id, "--task", bot.activeTaskId, "--text", "Show the film.");+ expect((await cli("wait", "--bot", bot.id, "--task", bot.activeTaskId, "--timeout", "30")).status).toBe("settled");+ return reply(bot.id);+ };+ const bot = (await cli("new-bot", "--name", "Film")).bot;+ const folder = join(fixture.info.dataDir, "workspaces", bot.id, "film");+ const movie = randomBytes(3 * 1024 * 1024);+ mkdirSync(folder, { recursive: true });+ writeFileSync(join(folder, "index.html"), "<!doctype html><video src=\"clip.webm\" controls></video>");+ writeFileSync(join(folder, "clip.webm"), movie);++ const appId = /^Shown as app ([\w-]+)\./.exec(await turn(bot, { tool: "show_html", arguments: { path: "film", title: "Film" } }))?.[1];+ expect(appId).toBeTruthy();+ const base = async () => /<base href="([^"]+)">/.exec((await api(`/api/threads/${bot.activeTaskId}/messages/${appId}/app?origin=${encodeURIComponent(fixture.info.url)}`)).srcdoc)?.[1] ?? "";+ const seek = await realFetch(`${await base()}clip.webm`, { headers: { range: "bytes=2000000-2000099" } });+ expect(seek.status).toBe(206);+ expect(seek.headers.get("content-type")).toBe("video/webm");+ expect(Buffer.from(await seek.arrayBuffer()).equals(movie.subarray(2_000_000, 2_000_100))).toBe(true);++ const published = await turn(bot, { tool: "publish_page", arguments: { path: "film", title: "Film" } });+ expect(published).toContain("Left out 1 file a page can't serve: clip.webm");+ expect([...[...stub.service.pages.values()].at(-1)!.files.keys()]).not.toContain("clip.webm");+ const kept = await realFetch(`${await base()}clip.webm`, { headers: { range: "bytes=0-9" } });+ expect(kept.status).toBe(206);+ expect(Buffer.from(await kept.arrayBuffer()).equals(movie.subarray(0, 10))).toBe(true);++ rmSync(join(folder, "clip.webm"));+ writeFileSync(join(folder, "clip.webm"), movie);+ expect((await realFetch(`${await base()}clip.webm`)).status).toBe(404);+}, 120_000);diff --git a/server/page-files.test.ts b/server/page-files.test.tsindex bb8a6e75aa..fdaa9b8a69 100644--- a/server/page-files.test.ts+++ b/server/page-files.test.ts@@ -1,10 +1,19 @@-import { mkdtempSync } from "node:fs";+import { mkdtempSync, renameSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { describe, expect, it } from "vitest";+import { Writable } from "node:stream";+import { finished } from "node:stream/promises";+import { describe, expect, it, vi } from "vitest";import { AppDocs } from "./app-docs.ts";import { createPageFiles, pageFilePath, PAGE_FILES_PREFIX } from "./page-files.ts";+import type { PageVideo } from "./pages/bundle.ts";++const opened = vi.hoisted(() => [] as import("node:fs/promises").FileHandle[]);+vi.mock("node:fs/promises", async (original) => {+ const real = await original<typeof import("node:fs/promises")>();+ return { ...real, open: async (...args: Parameters<typeof real.open>) => { const handle = await real.open(...args); opened.push(handle); return handle; } };+});const PARQUET = Buffer.from("PAR1\u0000\u0001\u0002\u0003 rows and columns PAR1", "latin1");@@ -85,3 +94,125 @@ describe("a folder page's files route", () => {.toEqual(["index.html", "a/b.js", "my data.csv", null, null, null]);});});++describe("a folder page's video", () => {+ const MOVIE = Buffer.alloc(3 * 1024 * 1024, "movie");++ function recorded(path: string): PageVideo {+ const info = statSync(path, { bigint: true });+ return { file: path, bytes: Number(info.size), dev: String(info.dev), ino: String(info.ino), mtimeNs: String(info.mtimeNs) };+ }+ function setupVideo(videos: (dir: string) => Record<string, PageVideo> = (dir) => ({ "clip.mp4": recorded(join(dir, "clip.mp4")) })) {+ const dir = mkdtempSync(join(tmpdir(), "omb-page-video-"));+ writeFileSync(join(dir, "clip.mp4"), MOVIE);+ const docs = new AppDocs(join(dir, "app-docs"));+ const stored = docs.put({ source: "html", html: "<video src=\"clip.mp4\">", data: { folder: dir, videos: videos(dir) } });+ if (!stored.ok) throw new Error("not stored");+ const files = createPageFiles({ docs });+ const folder = files.folder({ threadId: "t1", messageId: "m1", doc: stored.doc });+ const get = async (path: string, init: { method?: string; range?: string } = {}) => {+ const out = { status: 0, headers: {} as Record<string, string>, body: Buffer.alloc(0) };+ const chunks: Buffer[] = [];+ const res = Object.assign(new Writable({ write(chunk: Buffer, _encoding, done) { chunks.push(chunk); done(); } }), {+ writeHead(status: number, headers: Record<string, string>) { out.status = status; out.headers = headers; return res; },+ });+ expect(files.serve({ headers: init.range ? { range: init.range } : {} } as never, res as never, `${folder}${path}`, init.method ?? "GET")).toBe(true);+ await finished(res);+ out.body = Buffer.concat(chunks);+ return out;+ };+ return { dir, docs, doc: stored.doc, get, files, folder };+ }++ it("streams the asked-for bytes, with the type from its own table and the same headers as any page file", async () => {+ const { get, dir } = setupVideo((at) => {+ writeFileSync(join(at, "page.webm"), "<script>alert(1)</script>");+ writeFileSync(join(at, "film.mov"), "moov");+ return { "clip.mp4": recorded(join(at, "clip.mp4")), "page.webm": recorded(join(at, "page.webm")), "film.mov": recorded(join(at, "film.mov")) };+ });+ const part = await get("clip.mp4", { range: "bytes=1000000-1000009" });+ expect(part).toMatchObject({ status: 206, headers: {+ "content-type": "video/mp4", "accept-ranges": "bytes", "content-length": "10", "content-range": `bytes 1000000-1000009/${MOVIE.byteLength}`, "cache-control": "private, no-store",+ "x-content-type-options": "nosniff", "content-security-policy": "sandbox allow-scripts; default-src 'none'" } });+ expect(part.body.equals(MOVIE.subarray(1_000_000, 1_000_010))).toBe(true);+ expect((await get("clip.mp4", { range: "bytes=-4" })).body.equals(MOVIE.subarray(-4))).toBe(true);+ expect((await get("clip.mp4", { range: "bytes=3145720-" })).headers["content-length"]).toBe("8");+ expect(await get("clip.mp4", { range: `bytes=${MOVIE.byteLength}-` })).toMatchObject({ status: 416, headers: { "content-range": `bytes */${MOVIE.byteLength}` } });+ expect((await get("clip.mp4", { range: "lines=1-2" })).status).toBe(416);+ const whole = await get("clip.mp4");+ expect(whole).toMatchObject({ status: 200, headers: { "content-length": String(MOVIE.byteLength) } });+ expect(whole.body.equals(MOVIE)).toBe(true);+ expect(await get("clip.mp4", { method: "HEAD", range: "bytes=0-1" })).toMatchObject({ status: 206, body: Buffer.alloc(0) });+ expect((await get("page.webm")).headers["content-type"]).toBe("video/webm");+ expect((await get("film.mov")).headers["content-type"]).toBe("video/quicktime");+ expect(dir).toBeTruthy();+ });++ it("serves no path the document did not record, whatever is beside it on disk", async () => {+ const { get, dir, docs, doc } = setupVideo();+ writeFileSync(join(dir, "other.mp4"), MOVIE);+ expect(docs.video(doc, "__proto__")).toBeNull();+ expect(docs.video(doc, "constructor")).toBeNull();+ expect((await get("other.mp4")).status).toBe(404);+ expect((await get("__proto__")).status).toBe(404);+ expect((await get("constructor")).status).toBe(404);+ expect((await get("CLIP.MP4")).status).toBe(404);+ expect((await get("../clip.mp4")).status).toBe(400);+ });++ it("refuses a file deleted, replaced or edited since the page was shown", async () => {+ const deleted = setupVideo();+ rmSync(join(deleted.dir, "clip.mp4"));+ expect((await deleted.get("clip.mp4")).status).toBe(404);++ const FIXED = new Date(1_700_000_000_000);+ const pinned = (at: string) => { utimesSync(join(at, "clip.mp4"), FIXED, FIXED); return { "clip.mp4": recorded(join(at, "clip.mp4")) }; };+ const replaced = setupVideo(pinned);+ expect((await replaced.get("clip.mp4", { range: "bytes=0-9" })).status).toBe(206);+ writeFileSync(join(replaced.dir, "new.mp4"), MOVIE);+ utimesSync(join(replaced.dir, "new.mp4"), FIXED, FIXED);+ renameSync(join(replaced.dir, "new.mp4"), join(replaced.dir, "clip.mp4"));+ expect((await replaced.get("clip.mp4", { range: "bytes=0-9" })).status).toBe(404);++ const resized = setupVideo(pinned);+ writeFileSync(join(resized.dir, "clip.mp4"), Buffer.alloc(MOVIE.byteLength + 1));+ utimesSync(join(resized.dir, "clip.mp4"), FIXED, FIXED);+ expect((await resized.get("clip.mp4")).status).toBe(404);++ const edited = setupVideo();+ writeFileSync(join(edited.dir, "clip.mp4"), Buffer.alloc(MOVIE.byteLength, "other"));+ utimesSync(join(edited.dir, "clip.mp4"), new Date(), new Date(Date.now() + 60_000));+ expect((await edited.get("clip.mp4")).status).toBe(404);+ });++ it.skipIf(process.platform === "win32")("refuses a symlink swapped in after showing, even to the very same file", async () => {+ const { get, dir } = setupVideo();+ renameSync(join(dir, "clip.mp4"), join(dir, "moved.mp4"));+ symlinkSync(join(dir, "moved.mp4"), join(dir, "clip.mp4"));+ expect((await get("clip.mp4")).status).toBe(404);+ });++ it("plays an older version only while its file is unchanged, and a copy at the same path is not the same file", async () => {+ const { get, dir } = setupVideo();+ expect((await get("clip.mp4", { range: "bytes=0-0" })).status).toBe(206);+ const copy = join(dir, "copied.mp4");+ writeFileSync(copy, MOVIE);+ rmSync(join(dir, "clip.mp4"));+ renameSync(copy, join(dir, "clip.mp4"));+ expect((await get("clip.mp4", { range: "bytes=0-0" })).status).toBe(404);+ });++ it("closes the file when the client goes away", async () => {+ const { files, folder } = setupVideo();+ const res = Object.assign(new Writable({ highWaterMark: 1, write() { /* a client that stopped reading */ } }), {+ writeHead() { return res; },+ });+ opened.length = 0;+ files.serve({ headers: {} } as never, res as never, `${folder}clip.mp4`, "GET");+ await expect.poll(() => opened[0]?.fd ?? -1).toBeGreaterThan(-1);+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(opened[0]!.fd).toBeGreaterThan(-1);+ res.destroy();+ await expect.poll(() => opened[0]!.fd).toBe(-1);+ });+});diff --git a/server/page-files.ts b/server/page-files.tsindex 20230350b6..1f167eff49 100644--- a/server/page-files.ts+++ b/server/page-files.ts@@ -3,14 +3,20 @@//// - a token is made only for a document the person was allowed to fetch, names that one document (one version of one// page in one conversation), and is forgotten after a day unused;-// - only the files stored with that document are served, by their exact path; nothing on disk is read by path;+// - only the files stored with that document are served, by their exact path. The one exception is a video the document+// recorded when it was shown: it stays in the bot's folder, and is served only while the file that was checked then+// is still the file on disk, compared on the open handle;// - every answer is read-only, sandboxed if opened directly (no app origin, no cookies), and readable from the frame's// opaque origin.import { randomBytes } from "node:crypto";+import { constants as fsConstants } from "node:fs";+import { open, type FileHandle } from "node:fs/promises";import type { IncomingMessage, ServerResponse } from "node:http";import { extname } from "node:path";+import { pipeline } from "node:stream";import type { AppDocs } from "./app-docs.ts";+import type { PageVideo } from "./pages/bundle.ts";export const PAGE_FILES_PREFIX = "/api/page-files/";const TOKEN = /^[A-Za-z0-9_-]{43}$/;@@ -23,7 +29,11 @@ const TYPES: Readonly<Record<string, string>> = {md: "text/markdown; charset=utf-8", parquet: "application/vnd.apache.parquet", arrow: "application/vnd.apache.arrow.file", svg: "image/svg+xml",png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", avif: "image/avif", ico: "image/x-icon",woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf", otf: "font/otf",+ mp4: "video/mp4", webm: "video/webm", mov: "video/quicktime",};+// O_NOFOLLOW refuses a symlink swapped in at the last step, and O_NONBLOCK keeps a FIFO swapped in from hanging the open.+// Windows has neither; there the identity check on the open handle alone refuses a different file.+const VIDEO_OPEN_FLAGS = fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0) | (fsConstants.O_NONBLOCK ?? 0);const SHARED_HEADERS = {"access-control-allow-origin": "*",@@ -56,6 +66,24 @@ export function pageFilePath(raw: string): string | null {return segments.join("/");}+/** The bytes a Range header asks of a file this size, or null when it can't be met. */+function rangeOf(header: string, size: number): { start: number; end: number } | null {+ const range = /^bytes=(\d*)-(\d*)$/.exec(header);+ const start = range?.[1] ? Number(range[1]) : range?.[2] ? Math.max(0, size - Number(range[2])) : NaN;+ const end = range?.[1] && range[2] ? Math.min(size - 1, Number(range[2])) : size - 1;+ return !range || !Number.isSafeInteger(start) || start >= size || end < start ? null : { start, end };+}++/** The open video, if it is still the regular file the page recorded. */+async function openRecordedVideo(video: PageVideo): Promise<FileHandle | null> {+ const handle = await open(video.file, VIDEO_OPEN_FLAGS).catch(() => null);+ if (!handle) return null;+ const now = await handle.stat({ bigint: true }).catch(() => null);+ if (now?.isFile() && String(now.dev) === video.dev && String(now.ino) === video.ino && Number(now.size) === video.bytes && String(now.mtimeNs) === video.mtimeNs) return handle;+ await handle.close().catch(() => {});+ return null;+}+export function createPageFiles(deps: { docs: AppDocs; now?: () => number }) {const now = deps.now ?? Date.now;const tokens = new Map<string, PageFilesTarget & { used: number }>();@@ -72,6 +100,27 @@ export function createPageFiles(deps: { docs: AppDocs; now?: () => number }) {res.end(text);};+ const sendVideo = async (req: IncomingMessage, res: ServerResponse, video: PageVideo, type: string, method: string) => {+ const handle = await openRecordedVideo(video);+ if (!handle) return answer(res, 404, "Not found.");+ const size = video.bytes, headers = { ...SHARED_HEADERS, "content-type": type, "accept-ranges": "bytes" };+ const part = req.headers.range === undefined ? null : rangeOf(String(req.headers.range), size);+ if (req.headers.range !== undefined && !part) {+ await handle.close().catch(() => {});+ res.writeHead(416, { ...headers, "content-range": `bytes */${size}` });+ res.end();+ return;+ }+ const start = part?.start ?? 0, end = part?.end ?? size - 1;+ res.writeHead(part ? 206 : 200, { ...headers, "content-length": String(end - start + 1), ...(part ? { "content-range": `bytes ${start}-${end}/${size}` } : {}) });+ if (method === "HEAD" || size === 0) {+ await handle.close().catch(() => {});+ res.end();+ return;+ }+ pipeline(handle.createReadStream({ start, end }), res, () => {});+ };+return {/** The folder URL path a document's files load from: the same token while it is in use. */folder(target: PageFilesTarget): string {@@ -113,24 +162,28 @@ export function createPageFiles(deps: { docs: AppDocs; now?: () => number }) {return true;}target.used = now();+ const type = TYPES[extname(file).slice(1).toLowerCase()] ?? "application/octet-stream";+ const video = deps.docs.video(target.doc, file);+ if (video) {+ void sendVideo(req, res, video, type, method).catch(() => res.destroy());+ return true;+ }const stored = file === "index.html" ? deps.docs.read(target.doc) : null;const body = stored ? Buffer.from(stored.html) : deps.docs.readFile(target.doc, file);if (!body) {answer(res, 404, "Not found.");return true;}- const type = TYPES[extname(file).slice(1).toLowerCase()] ?? "application/octet-stream";const headers = { ...SHARED_HEADERS, "content-type": type, "accept-ranges": "bytes" };- const range = /^bytes=(\d*)-(\d*)$/.exec(String(req.headers.range ?? ""));if (req.headers.range !== undefined) {const size = body.byteLength;- const start = range?.[1] ? Number(range[1]) : range?.[2] ? Math.max(0, size - Number(range[2])) : NaN;- const end = range?.[1] && range[2] ? Math.min(size - 1, Number(range[2])) : size - 1;- if (!range || !Number.isSafeInteger(start) || start >= size || end < start) {+ const part = rangeOf(String(req.headers.range), size);+ if (!part) {res.writeHead(416, { ...headers, "content-range": `bytes */${size}` });res.end();return true;}+ const { start, end } = part;const slice = body.subarray(start, end + 1);res.writeHead(206, { ...headers, "content-range": `bytes ${start}-${end}/${size}`, "content-length": String(slice.byteLength) });res.end(method === "HEAD" ? undefined : slice);diff --git a/server/pages/bundle.ts b/server/pages/bundle.tsindex 1ad44d0708..7e8ccce0b7 100644--- a/server/pages/bundle.ts+++ b/server/pages/bundle.ts@@ -11,6 +11,16 @@ export interface PageFile {path: string;data: Buffer;}+/** A video beside a chat page's index.html, kept where it is on disk: never read into memory or copied. The identity+ * is what lets the page's files route refuse a file that was replaced after the page was shown. BigInt stat fields as text,+ * since inode numbers can pass 2^53. */+export interface PageVideo {+ file: string;+ bytes: number;+ dev: string;+ ino: string;+ mtimeNs: string;+}export interface PageBundle {/** The file or folder published, canonical: the same source publishes to the same link again. */source: string;@@ -18,6 +28,8 @@ export interface PageBundle {bytes: number;/** Files left out because a page can't serve them. */skipped: string[];+ /** Only when asked for, by path in the folder: the pages Worker refuses video, so a published page leaves it out. */+ videos?: Record<string, PageVideo>;}const SKIPPED_FOLDERS = new Set(["node_modules", "__pycache__"]);@@ -37,6 +49,7 @@ const containedBy = (root: string, candidate: string) => {};const servable = (name: string) => PAGE_FILE_EXTENSIONS.has(extname(name).slice(1).toLowerCase());const isHtml = (name: string) => /^\.html?$/i.test(extname(name));+const isVideo = (name: string) => /^\.(?:mp4|webm|mov)$/i.test(extname(name));async function canonicalRoots(roots: readonly string[]): Promise<string[]> {const found = await Promise.all(roots.map(async (root) => {@@ -79,7 +92,7 @@ export async function pageSource(requested: string, roots: readonly string[]): P}/** The page at `requested`: one .html file (published as index.html), or a folder with index.html at its top. */-export async function readPageBundle(requested: string, roots: readonly string[], limits = { bytes: PAGE_MAX_BYTES, files: PAGE_MAX_FILES }): Promise<PageBundle> {+export async function readPageBundle(requested: string, roots: readonly string[], limits = { bytes: PAGE_MAX_BYTES, files: PAGE_MAX_FILES }, options: { videos?: boolean } = {}): Promise<PageBundle> {const { target, root } = await locate(requested, roots);const info = await stat(target);if (info.isFile()) {@@ -89,7 +102,7 @@ export async function readPageBundle(requested: string, roots: readonly string[]return { source: target, files: [{ path: "index.html", data }], bytes: data.byteLength, skipped: [] };}if (!info.isDirectory()) throw new PageBundleError("Publish an .html file or a folder.");- const files: PageFile[] = [], skipped: string[] = [];+ const files: PageFile[] = [], skipped: string[] = [], videos: Record<string, PageVideo> = {};let bytes = 0;const walk = async (folder: string, depth: number): Promise<void> => {for (const name of (await readdir(folder)).sort()) {@@ -105,6 +118,12 @@ export async function readPageBundle(requested: string, roots: readonly string[]continue;}if (!entry.isFile()) continue;+ if (options.videos && isVideo(name) && SEGMENT.test(name) && !name.endsWith(".")) {+ if (files.length + Object.keys(videos).length >= limits.files) throw new PageBundleError(`The folder has more than ${limits.files} files a page can hold. Publish a smaller folder.`, 413);+ const identity = await stat(real, { bigint: true });+ videos[path] = { file: real, bytes: Number(identity.size), dev: String(identity.dev), ino: String(identity.ino), mtimeNs: String(identity.mtimeNs) };+ continue;+ }if (!servable(name) || !SEGMENT.test(name) || name.endsWith(".")) { skipped.push(path); continue; }if (files.length >= limits.files) throw new PageBundleError(`The folder has more than ${limits.files} files a page can hold. Publish a smaller folder.`, 413);bytes += entry.size;@@ -116,17 +135,17 @@ export async function readPageBundle(requested: string, roots: readonly string[]if (!files.some((file) => file.path === "index.html")) {throw new PageBundleError(`${basename(target)} has no index.html at its top. Name the main page index.html, then publish again.`);}- return { source: target, files, bytes, skipped };+ return { source: target, files, bytes, skipped, ...(options.videos ? { videos } : {}) };}/** The bot's own folders for a turn, and its Local VM's workspace on this computer when it has one. */export type BotFolders = () => Promise<{ roots: readonly string[]; vmWorkspace: string | null }>;-/** readPageBundle within a bot's own folders; a path inside its Local VM's workspace means the same file here. */+/** A chat page's bundle, videos included: readPageBundle within a bot's own folders; a path inside its Local VM's workspace means the same file here. */export async function readBotPageBundle(requested: string, folders: BotFolders): Promise<PageBundle> {const { roots, vmWorkspace } = await folders();const path = vmWorkspace ? guestWorkspaceToHost(requested, VM_WORKSPACE_GUEST, vmWorkspace) ?? requested : requested;- return readPageBundle(path, vmWorkspace ? [vmWorkspace, ...roots] : roots);+ return readPageBundle(path, vmWorkspace ? [vmWorkspace, ...roots] : roots, undefined, { videos: true });}/** A file inside a bot's own folders (or its Local VM's workspace), by the same rules as a page: the `extract` tool's. */diff --git a/server/skill-social-posts.test.ts b/server/skill-social-posts.test.tsnew file mode 100644index 0000000000..d33c0333bb--- /dev/null+++ b/server/skill-social-posts.test.ts@@ -0,0 +1,27 @@+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { loadBundledSkills, selectBundledSkills } from "./skill-library.ts";++describe("social-posts skill guide", () => {+ const skills = loadBundledSkills(join(process.cwd(), "skills"));+ const guide = skills.find((skill) => skill.manifest.id === "social-posts")?.instructions ?? "";+ const ids = (text: string) => selectBundledSkills(text, [], skills).map((skill) => skill.manifest.id);++ it("mounts when a bot is asked for a social post, and stays out of other uses of the word post", () => {+ for (const text of ["Plan next week's posts for LinkedIn and X", "Draft three posts about our launch and add them to Postiz", "Write a LinkedIn post about hiring", "make me an Instagram carousel",+ "tweet this for me", "Plan next week's social posts from memory/social.md", "write a post about our launch", "a caption for an instagram reel", "write a post for x"]) {+ expect(ids(text), text).toContain("social-posts");+ }+ for (const text of ["post the invoice to accounting", "send a POST request to the API", "go to the post office", "write a blog post-mortem", "fix the box post", "the fence post is broken", "freely choose a reel of film", "write a post-mortem"]) {+ expect(ids(text), text).not.toContain("social-posts");+ }+ });++ it("keeps the guide short, in plain words, and pointing at its template", () => {+ expect(guide.split("\n").length).toBeLessThanOrEqual(95);+ expect(guide).not.toMatch(/\b(engines?|servers?)\b/i);+ expect(guide).toContain("posts.html");+ expect(guide).toContain("show_html");+ expect(guide).toContain("integrationSchema");+ });+});diff --git a/skills/social-posts/SKILL.md b/skills/social-posts/SKILL.mdnew file mode 100644index 0000000000..95f6669b62--- /dev/null+++ b/skills/social-posts/SKILL.md@@ -0,0 +1,92 @@+---+name: social-posts+description: "Show how a social post will look on each platform, with show_html: Instagram (with carousels), LinkedIn (with document carousels), X, Threads, Facebook, TikTok, Reels and Shorts. Use whenever you write a social post, whether or not Postiz is connected."+---++# Social post previews++Whenever you write a social post, show it as it will look. Don't ask first, and don't wait for an answer: show the preview and+carry on with the work. It's for social posts only, so skip it for a blog post or an article.++## Fill the template++`posts.html` sits next to this guide, in the folder named by this skill's `root`. Copy it to your working folder and replace+only the JSON in the `posts-data` block at the top. Keep the rest, including the licence notice at the top of the file.++```json+{+ "account": { "name": "Juniper Coffee", "handle": "junipercoffee", "subtitle": "Roasters in Leeds", "avatar": "avatar.png" },+ "posts": [{+ "title": "Autumn launch",+ "when": "Draft",+ "text": "Text for every platform that has none of its own.",+ "media": [{ "src": "photo.jpg", "alt": "A bag of coffee" }],+ "platforms": {+ "instagram": { "text": "Its own caption.", "media": [] },+ "x": {}+ }+ }]+}+```++- `platforms` decides which previews show: `instagram`, `linkedin`, `x`, `threads`, `facebook`, `tiktok`, `reels`, `shorts`. Each can+ have its own `text`, `media` and `when`; anything left out comes from the post. Write each platform's text for that platform.+- A plan of several posts is several entries in `posts`; they stack on one page.+- With no `avatar` the card shows initials. No media and empty text still draw properly.+- `media` items: an image `{ "src", "alt" }`, a video `{ "video", "poster", "duration" }` (seconds), or a slide (below). Add `width` and+ `height` when a file's size can't be read, so its shape can be checked.++## Show it++Pick by what the post has:++| The post has | Do this |+|---|---|+| Only text, or slides you wrote | Send the file's whole text as `html`. At most 256 KB, and the template is about 48 KB. |+| Images on disk | Make a folder: the template as `index.html`, the images beside it, named in `src` (`"src": "photo.jpg"`). Show it with `path`. png, jpg, gif, webp, avif and svg work. The folder holds at most 5 MB and 200 files, and `index.html` at most 256 KB, so shrink big images first. |+| An image on the web | Download it into the folder first. The chat blocks images from other sites, and the card says so. |+| A video on disk | Put it in the folder and name it: `{ "video": "clip.mp4", "poster": "frame.jpg" }`. It plays and seeks in the chat, at any size: mp4 (H.264), webm or mov. It plays from the folder and isn't copied, so keep the file there unchanged. If it is moved, edited or deleted, the card falls back to the poster until you show the page again. Always add a poster. |+| A public link | `publish_page` leaves video out and says so, and the public page shows the poster with a play mark. The chat card keeps playing the video. |++Call `show_html` with `title` and the `path`, or the `html`. To change a preview, call it again with the page's `app_id`.+When the person shares it, `publish_page` publishes the same folder; only do that when they ask.++## Carousels without images++You can make a carousel with no image tool: write the slides. `layout` slides take care of the design, and set the shape with+`"slideShape": "4:5"` (the default) or `"1:1"` on the post.++```json+"brand": { "background": "#2b1d16", "text": "#fbf3e6", "accent": "#e8a15b" },+"media": [+ { "layout": "cover", "kicker": "New on Friday", "title": "Three things to know", "note": "Swipe to read" },+ { "layout": "points", "title": "What's in the bag", "points": ["Plum", "Cocoa", "Smoke"] },+ { "layout": "quote", "quote": "Like the first cold morning.", "by": "Priya, head roaster" },+ { "html": "<p class=\"slide-kicker\">Your own</p><h3 class=\"slide-title\">Any HTML you like</h3>" }+]+```++Write a good carousel like this: one idea per slide, a cover that promises something specific, 5 to 10 slides, about 20 words a+slide, and a last slide that says what to do next. In your own `html` slides size text in `cqw` (a percentage of the slide's width),+so it fits at every size.++These slides show in the preview only. To post them for real, the person needs them as images, or as a PDF for LinkedIn: say so+plainly. This skill can't export them.++## What each platform wants++From each platform's own docs. The cards note these quietly; nothing is ever blocked.++| Platform | Text | Media |+|---|---|---|+| Instagram | 2,200 characters, 30 hashtags, 20 @ tags | Images 4:5 to 1.91:1. Carousel up to 20; every slide crops to the first one's shape |+| LinkedIn | 3,000 characters. LinkedIn's guidance is to stay within 150 to avoid a cut, so put the hook first | A "carousel" is a document (usually a PDF): up to 300 pages, 100 MB |+| X | 280, where emoji and CJK count as 2 and any link as 23 | Up to 4 photos, or 1 video |+| Threads | 500; an emoji counts as its UTF-8 bytes | Carousel 2 to 20. Video up to 5 minutes |+| Facebook | No published limit, so no check | |+| TikTok | Video caption 2,200; photo description 4,000 | Up to 35 photos |+| Reels | As Instagram | 9:16 recommended; 3 seconds to 15 minutes |+| Shorts | | Square or vertical; up to 3 minutes |++When Postiz is connected, its `integrationSchema` is the authority for that channel's rules; follow it where it differs.+The preview is a close likeness, not a pixel match: say so if the person asks.diff --git a/skills/social-posts/manifest.json b/skills/social-posts/manifest.jsonnew file mode 100644index 0000000000..13cefe680e--- /dev/null+++ b/skills/social-posts/manifest.json@@ -0,0 +1,46 @@+{+ "id": "social-posts",+ "name": "Social Post Previews",+ "version": "1.0.0",+ "description": "Show how a social post will look on Instagram, LinkedIn, X, Threads, Facebook, TikTok, Reels and Shorts.",+ "defaultEnabled": true,+ "triggerTerms": [+ "social post",+ "social media post",+ "write a post about",+ "write a post for",+ "draft a post about",+ "draft a post for",+ "linkedin post",+ "post on linkedin",+ "post to linkedin",+ "post for linkedin",+ "posts for linkedin",+ "linkedin carousel",+ "instagram post",+ "post on instagram",+ "post to instagram",+ "post for instagram",+ "posts for instagram",+ "instagram caption",+ "instagram carousel",+ "instagram reel",+ "reel caption",+ "carousel post",+ "tweet",+ "post for x",+ "posts for x",+ "threads post",+ "post on threads",+ "post for threads",+ "facebook post",+ "tiktok post",+ "tiktok caption",+ "tiktok video",+ "for tiktok",+ "youtube short",+ "post preview",+ "postiz"+ ],+ "requiredCapabilities": []+}diff --git a/skills/social-posts/posts.html b/skills/social-posts/posts.htmlnew file mode 100644index 0000000000..4a396a68e5--- /dev/null+++ b/skills/social-posts/posts.html@@ -0,0 +1,676 @@+<!doctype html>+<!--+Card markup and platform styling adapted from MiniMock, https://github.com/minianon/MiniMock++MIT License++Copyright (c) 2026 Tushar Bhardwaj++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.++Icon paths are from Lucide, https://lucide.dev, ISC License.+Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of+Feather (MIT). All other copyright (c) for Lucide are held by Lucide Contributors+2022. Permission to use, copy, modify, and/or distribute this software for any+purpose with or without fee is hereby granted, provided that the above copyright+notice and this permission notice appear in all copies.+-->+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>Post preview</title>+<script id="posts-data" type="application/json">+{+ "account": { "name": "Juniper Coffee", "handle": "junipercoffee", "subtitle": "Small-batch roasters in Leeds", "avatar": "" },+ "posts": [+ {+ "title": "Autumn blend launch",+ "when": "Draft",+ "text": "Our autumn blend is out on Friday: plum, cocoa and a little smoke. #coffee",+ "brand": { "background": "#2b1d16", "text": "#fbf3e6", "accent": "#e8a15b" },+ "media": [+ { "layout": "cover", "kicker": "New on Friday", "title": "Three things to know about our autumn blend", "note": "Swipe to read" },+ { "layout": "points", "title": "What's in the bag", "points": ["Washed Ethiopian for the plum", "Brazilian natural for the cocoa", "A slow finish for the smoke"] },+ { "layout": "quote", "quote": "It tastes like the first cold morning of the year.", "by": "Priya, head roaster" }+ ],+ "platforms": {+ "instagram": { "text": "Our autumn blend is out on Friday: plum, cocoa and a little smoke. Swipe for what's in the bag, then tell us how you brew yours. #coffee #leeds" },+ "linkedin": { "documentTitle": "Three things to know about our autumn blend", "text": "We spent nine weeks on one coffee.\n\nOur autumn blend is out on Friday, and the slides below show why it took that long: three farms, eleven roasts and one very patient head roaster.\n\nWhat have you spent too long getting right? #coffee" },+ "x": { "media": [], "text": "Autumn blend, out Friday. Plum, cocoa, a little smoke." },+ "threads": { "text": "We roasted this one eleven times. It's out on Friday." },+ "facebook": { "media": [], "text": "Our autumn blend is out on Friday! Come and try it at the Kirkgate shop this weekend, on us." },+ "reels": { "text": "Eleven roasts in thirty seconds. #coffee", "media": [{ "video": "", "poster": "", "duration": 30 }] }+ }+ }+ ]+}+</script>+<style>+:root {+ color-scheme: light;+ --page: light-dark(#f4f4f5, #18181b);+ --ink: light-dark(#18181b, #f4f4f5);+ --quiet: light-dark(#5c5c66, #a1a1aa);+ --edge: light-dark(#d9d9de, #3a3a40);+ --warn: light-dark(#8a4b00, #f5b35c);+}+@media (prefers-color-scheme: dark) {+ :root:not([data-theme="light"]) { color-scheme: dark; }+}+:root[data-theme="dark"] { color-scheme: dark; }+* { box-sizing: border-box; }+html { -webkit-text-size-adjust: 100%; }+body {+ margin: 0;+ padding: 12px;+ background: var(--page);+ color: var(--ink);+ font: 14px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;+ overflow-wrap: anywhere;+}+button { font: inherit; color: inherit; }+.preview-note { margin: 0 0 12px; font-size: 12px; color: var(--quiet); }+.problem { padding: 12px; border: 1px solid var(--edge); border-radius: 8px; }+.post-set + .post-set { margin-top: 28px; padding-top: 20px; border-top: 1px solid var(--edge); }+.post-set-head { display: flex; flex-wrap: wrap; gap: 4px 8px; align-items: baseline; margin-bottom: 8px; }+.post-set-head h2 { margin: 0; font-size: 15px; font-weight: 600; }+.post-set-head span { font-size: 12px; color: var(--quiet); }+.tabs { display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 12px; }+.tab {+ display: inline-flex; align-items: center; gap: 6px; min-height: 32px; padding: 4px 10px;+ border: 1px solid var(--edge); border-radius: 999px; background: none; color: var(--quiet); font-size: 13px; cursor: pointer;+}+.tab[aria-selected="true"] { background: var(--ink); border-color: var(--ink); color: var(--page); }+.tab-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--warn); }+.tab-dot[hidden] { display: none; }+:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }+.cards { display: grid; gap: 16px; justify-items: center; }+.card-wrap { width: 100%; max-width: 440px; min-width: 0; }+.card-wrap.off { display: none; }+.card-title { display: none; margin-bottom: 6px; font-size: 12px; color: var(--quiet); }+@media (min-width: 1040px) {+ .tabs { display: none; }+ .cards { grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); align-items: start; }+ .card-wrap.off { display: block; }+ .card-title { display: block; }+}+.checks { list-style: none; margin: 8px 2px 0; padding: 0; font-size: 12px; color: var(--quiet); }+.checks li + li { margin-top: 2px; }+.checks .warn { color: var(--warn); }+.checks .warn::before { content: "\25B2\00A0"; font-size: 9px; }++.post-card {+ --bg: #fff; --fg: #1d1d1d; --sub: #65676b; --line: #e4e6eb; --link: #0a66c2; --text-size: 14px; --clip: 3;+ background: var(--bg); color: var(--fg); border: 1px solid var(--line); border-radius: 10px; overflow: hidden;+}+.post-card[data-platform="linkedin"] { --bg: light-dark(#fff, #1b1f23); --fg: light-dark(rgba(0,0,0,.9), rgba(255,255,255,.9)); --sub: light-dark(rgba(0,0,0,.6), rgba(255,255,255,.6)); --line: light-dark(#e0dfdc, #38434f); --link: light-dark(#0a66c2, #71b7fb); }+.post-card[data-platform="facebook"] { --bg: light-dark(#fff, #242526); --fg: light-dark(#050505, #e4e6eb); --sub: light-dark(#65676b, #b0b3b8); --line: light-dark(#ced0d4, #3e4042); --link: light-dark(#0866ff, #4599ff); --text-size: 15px; --clip: 5; }+.post-card[data-platform="instagram"] { --bg: light-dark(#fff, #000); --fg: light-dark(#000, #f5f5f5); --sub: light-dark(#737373, #a8a8a8); --line: light-dark(#dbdbdb, #363636); --link: light-dark(#00376b, #e0f1ff); --clip: 2; border-radius: 4px; }+.post-card[data-platform="x"] { --bg: light-dark(#fff, #000); --fg: light-dark(#0f1419, #e7e9ea); --sub: light-dark(#536471, #71767b); --line: light-dark(#eff3f4, #2f3336); --link: #1d9bf0; --text-size: 15px; --clip: 40; border-radius: 4px; }+.post-card[data-platform="threads"] { --bg: light-dark(#fff, #101010); --fg: light-dark(#000, #f3f5f7); --sub: light-dark(#6b6b6b, #8a8a8a); --line: light-dark(#e5e5e5, #323232); --link: light-dark(#0095f6, #6cb8f6); --text-size: 15px; --clip: 40; border-radius: 14px; }++.post-header { display: flex; align-items: flex-start; gap: 10px; padding: 12px 14px 0; }+.post-avatar {+ width: 44px; height: 44px; flex: none; border-radius: 50%; overflow: hidden; display: flex; align-items: center; justify-content: center;+ color: #fff; font-size: 16px; font-weight: 600;+}+.post-avatar img { width: 100%; height: 100%; object-fit: cover; display: block; }+.post-header-text { flex: 1; min-width: 0; }+.post-author-name { font-weight: 600; line-height: 1.3; }+.post-author-subtitle, .post-author-meta { font-size: 12px; color: var(--sub); line-height: 1.35; }+.post-author-subtitle { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.post-author-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; }+.post-header-actions { display: flex; align-items: center; gap: 10px; flex: none; color: var(--sub); }+.post-follow { display: inline-flex; align-items: center; gap: 2px; font-weight: 600; font-size: 14px; color: var(--link); }+.post-body { padding: 10px 14px; }+.post-caption { position: relative; font-size: var(--text-size); line-height: 1.42; }+.clip { white-space: pre-wrap; unicode-bidi: plaintext; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: var(--clip); line-clamp: var(--clip); overflow: hidden; }+.post-caption.open .clip { display: block; overflow: visible; }+.see-more { display: none; position: absolute; inset-block-end: 0; inset-inline-end: 0; padding: 0 0 0 16px; border: 0; background: linear-gradient(to right, transparent, var(--bg) 14px); color: var(--sub); cursor: pointer; font-size: inherit; line-height: inherit; }+.see-more:dir(rtl) { padding: 0 16px 0 0; background: linear-gradient(to left, transparent, var(--bg) 14px); }+.post-caption.cut .see-more { display: block; }+.post-caption.open .see-more { display: none; }+.tok { color: var(--link); }+.empty-text { color: var(--sub); font-style: italic; }+.post-actions { display: flex; align-items: center; justify-content: space-around; padding: 4px 8px; border-top: 1px solid var(--line); color: var(--sub); }+.post-action { display: inline-flex; align-items: center; justify-content: center; gap: 6px; flex: 1; padding: 8px 4px; font-size: 13px; font-weight: 600; }++.post-card[data-platform="x"], .post-card[data-platform="threads"] { position: relative; }+.post-card[data-platform="x"] .post-header, .post-card[data-platform="threads"] .post-header { padding-left: 64px; }+.post-card[data-platform="x"] .post-avatar, .post-card[data-platform="threads"] .post-avatar { position: absolute; top: 12px; left: 14px; width: 40px; height: 40px; }+.post-card[data-platform="x"] .post-author-name, .post-card[data-platform="threads"] .post-author-name { display: inline; }+.post-card[data-platform="x"] .post-author-meta, .post-card[data-platform="threads"] .post-author-meta { font-size: 14px; }+.post-card[data-platform="x"] .post-body, .post-card[data-platform="threads"] .post-body { padding: 2px 14px 8px 64px; }+.post-card[data-platform="x"] .media, .post-card[data-platform="threads"] .media { margin: 0 14px 8px 64px; }+.post-card[data-platform="x"] .media { border: 1px solid var(--line); border-radius: 16px; overflow: hidden; }+.post-card[data-platform="x"] .post-actions, .post-card[data-platform="threads"] .post-actions { justify-content: flex-start; padding: 0 8px 8px 58px; border-top: 0; }+.post-card[data-platform="x"] .post-action { flex: 1 1 0; justify-content: flex-start; }+.post-card[data-platform="threads"] .post-action { flex: 0 0 auto; padding: 8px; }+.post-card[data-platform="threads"] .swipe-item { flex-basis: 72%; border-radius: 10px; overflow: hidden; }+.post-card[data-platform="threads"] .swipe { gap: 6px; }+.post-card[data-platform="threads"] .media > .frame { border-radius: 10px; overflow: hidden; }+.post-card[data-platform="instagram"] .post-avatar { width: 34px; height: 34px; font-size: 13px; box-shadow: 0 0 0 2px var(--bg), 0 0 0 3.5px #d6249f; }+.post-card[data-platform="instagram"] .post-header { align-items: center; padding-bottom: 10px; }+.post-card[data-platform="instagram"] .post-follow { color: var(--fg); font-size: 13px; }+.post-card[data-platform="instagram"] .post-actions { justify-content: flex-start; gap: 6px; padding: 6px 8px 0; border-top: 0; color: var(--fg); }+.post-card[data-platform="instagram"] .post-action { flex: 0 0 auto; padding: 4px; }+.post-card[data-platform="instagram"] .post-action:last-child { margin-inline-start: auto; }+.post-card[data-platform="instagram"] .post-body { padding: 4px 14px 12px; }+.post-card[data-platform="facebook"] .post-actions { margin: 0 12px; padding: 2px 0; }++.media { position: relative; }+.frame { position: relative; width: 100%; aspect-ratio: var(--r, 1); max-height: 560px; overflow: hidden; container-type: inline-size; background: light-dark(#eceef0, #26282b); }+.frame > img, .frame > video { display: block; width: 100%; height: 100%; object-fit: cover; }+.frame > video { object-fit: contain; background: #000; }+.poster-frame { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; background: linear-gradient(160deg, #3a3f47, #15171a); color: #fff; }+.poster-frame img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }+.play-mark { position: relative; display: flex; align-items: center; justify-content: center; width: 56px; height: 56px; border-radius: 50%; background: rgba(0,0,0,.55); color: #fff; }+.video-time { position: absolute; inset-block-end: 8px; inset-inline-end: 8px; padding: 1px 6px; border-radius: 4px; background: rgba(0,0,0,.65); color: #fff; font-size: 12px; }+.missing-image { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; padding: 12px; text-align: center; color: var(--sub); font-size: 13px; }++.carousel { position: relative; }+.swipe { display: flex; overflow-x: auto; scroll-snap-type: x mandatory; scrollbar-width: none; overscroll-behavior-x: contain; }+.swipe::-webkit-scrollbar { display: none; }+.swipe-item { flex: 0 0 100%; min-width: 0; scroll-snap-align: start; }+.swipe-count { position: absolute; top: 10px; right: 10px; padding: 2px 8px; border-radius: 12px; background: rgba(0,0,0,.65); color: #fff; font-size: 12px; pointer-events: none; }+.nav { position: absolute; top: 50%; width: 30px; height: 30px; margin-top: -15px; display: flex; align-items: center; justify-content: center; border: 0; border-radius: 50%; background: rgba(255,255,255,.88); color: #111; cursor: pointer; opacity: .9; }+.nav:disabled { display: none; }+.nav.prev { left: 8px; }+.nav.next { right: 8px; }+.dots { display: flex; justify-content: center; flex-wrap: wrap; gap: 4px; padding-top: 8px; }+.dots i { width: 6px; height: 6px; border-radius: 50%; background: var(--line); }+.dots i.on { background: var(--link); }+.doc-head { display: flex; justify-content: space-between; gap: 8px; padding: 8px 14px; background: rgba(0,0,0,.72); color: #fff; font-size: 13px; font-weight: 600; }+.doc-head span:last-child { flex: none; font-weight: 400; }+.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 2px; }+.grid .frame { --r: 1 !important; }+.grid .grid-three:first-child { grid-row: span 2; height: 100%; aspect-ratio: auto; }+.grid-more { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; background: rgba(0,0,0,.5); color: #fff; font-size: 24px; font-weight: 600; }++.slide {+ --slide-bg: #16213a; --slide-ink: #f7f7f2; --slide-accent: #f2b84b;+ position: absolute; inset: 0; display: flex; flex-direction: column; justify-content: center; gap: 3.5cqw; padding: 8cqw;+ overflow: hidden; background: var(--slide-bg); color: var(--slide-ink); font-size: 4.4cqw; line-height: 1.35; overflow-wrap: anywhere; unicode-bidi: plaintext;+}+.slide h3, .slide p, .slide ol, .slide blockquote { margin: 0; }+.slide-kicker { color: var(--slide-accent); font-size: 3.6cqw; font-weight: 600; text-transform: uppercase; letter-spacing: .06em; }+.slide-title { font-size: 8.4cqw; line-height: 1.12; font-weight: 700; letter-spacing: -.01em; }+.slide-note { font-size: 4cqw; opacity: .78; }+.slide-points { padding: 0; list-style: none; counter-reset: point; display: grid; gap: 3cqw; }+.slide-points li { counter-increment: point; display: grid; grid-template-columns: 9cqw 1fr; align-items: baseline; font-size: 5cqw; }+.slide-points li::before { content: counter(point); color: var(--slide-accent); font-size: 6cqw; font-weight: 700; }+.slide-points + .slide-note { margin-top: 2cqw; }+.slide-quote { font-size: 7.4cqw; line-height: 1.2; font-weight: 600; }+.slide-quote::before { content: "\201C"; display: block; height: 9cqw; color: var(--slide-accent); font-size: 16cqw; line-height: 1; }+.slide-foot { position: absolute; inset-inline: 8cqw; bottom: 4.5cqw; display: flex; justify-content: space-between; gap: 2cqw; font-size: 3cqw; opacity: .7; }++.phone { position: relative; width: min(100%, 300px); margin-inline: auto; aspect-ratio: 9 / 16; border: 6px solid #0b0b0c; border-radius: 28px; background: #000; color: #fff; overflow: hidden; }+.phone .media, .phone .carousel, .phone .swipe, .phone .swipe-item { height: 100%; }+.phone .frame { height: 100%; aspect-ratio: auto; max-height: none; background: #000; }+.phone .frame > img { object-fit: contain; }+.phone-label { position: absolute; top: 12px; left: 14px; font-size: 14px; font-weight: 700; text-shadow: 0 1px 2px rgba(0,0,0,.6); pointer-events: none; }+.phone-rail { position: absolute; right: 8px; bottom: 76px; display: grid; gap: 16px; justify-items: center; pointer-events: none; filter: drop-shadow(0 1px 1px rgba(0,0,0,.6)); }+.phone-foot { position: absolute; inset-inline: 0; bottom: 0; padding: 40px 54px 12px 12px; background: linear-gradient(transparent, rgba(0,0,0,.72)); font-size: 13px; pointer-events: none; }+.phone-author { display: flex; align-items: center; gap: 8px; margin-bottom: 4px; font-weight: 600; }+.phone-author .post-avatar { width: 28px; height: 28px; font-size: 11px; }+.phone .post-caption { --clip: 2; --bg: #111; --sub: #e8e8e8; --link: #fff; font-size: 13px; pointer-events: auto; }+.phone:has(video) .phone-foot { bottom: 44px; padding-top: 12px; }+.phone:has(video) .phone-rail { bottom: 120px; }+.phone .see-more { background: linear-gradient(to right, transparent, rgba(0,0,0,.8) 14px); color: #fff; font-weight: 600; }+.phone .video-time { inset-block: 12px auto; inset-inline-end: 12px; }+.phone .tok { font-weight: 600; }+.phone .dots { position: absolute; left: 0; right: 0; bottom: 4px; padding: 0; pointer-events: none; }+.phone .dots i { background: rgba(255,255,255,.4); }+.phone .dots i.on { background: #fff; }+.phone .play-mark { pointer-events: none; }+.no-video { position: absolute; inset: 0; display: flex; flex-direction: column; gap: 8px; align-items: center; justify-content: center; background: linear-gradient(160deg, #2c2f36, #0c0d0f); }+</style>+</head>+<body>+<p class="preview-note">Preview: a close likeness of each platform, not a promise of a pixel match.</p>+<main id="root"></main>+<script>+/* Limits, as each platform's own docs stated them on 2 Nov 2026. A number with no source here is not checked.+ X: 280 weighted characters, emoji 2, URLs 23: https://docs.x.com/fundamentals/counting-characters+ weight-1 ranges: https://github.com/twitter/twitter-text/blob/master/config/v3.json+ up to 4 photos: https://docs.x.com/x-api/posts/manage-tweets/introduction+ Instagram: caption 2200 characters, 30 hashtags, 20 @ tags; images 4:5 to 1.91:1; carousel 20 items; reels 3 s to 15 min,+ 9:16 recommended: https://developers.facebook.com/docs/instagram-platform/instagram-graph-api/reference/ig-user/media+ a carousel crops to its first image: https://developers.facebook.com/docs/instagram-platform/content-publishing+ Threads: 500 characters, an emoji counts as its UTF-8 bytes; carousel 20 items; aspect ratio up to 10:1; video 5 min:+ https://developers.facebook.com/docs/threads/overview and https://developers.facebook.com/docs/threads/posts/+ LinkedIn: 3000 characters: https://www.linkedin.com/help/linkedin/answer/a528176+ 150 characters "to avoid truncation" is LinkedIn's ad guidance, its only published cut-off:+ https://www.linkedin.com/help/linkedin/answer/a426534+ documents 300 pages: https://learn.microsoft.com/en-us/linkedin/marketing/community-management/shares/documents-api+ TikTok: video caption 2200 UTF-16 units: https://developers.tiktok.com/docs/en/content-posting-api-reference-direct-post+ photo description 4000, 35 photos: https://developers.tiktok.com/docs/en/content-posting-api-reference-photo-post+ YouTube Shorts: up to 3 minutes, square or vertical: https://support.google.com/youtube/answer/15424877+ Facebook publishes no organic post limit, so its card has no checks. */+const X_WEIGHT_ONE = [[0, 4351], [8192, 8205], [8208, 8223], [8242, 8247]];+const URL_TEXT = /https?:\/\/\S+/g;+const EMOJI = /\p{Emoji_Presentation}|\p{Extended_Pictographic}[️]|\p{Regional_Indicator}|⃣/u;+const graphemes = (text) => Array.from(new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(text), (part) => part.segment);+const codePoints = (text) => Array.from(text).length;+const utf8 = (text) => new TextEncoder().encode(text).length;++function countX(text) {+ const links = text.match(URL_TEXT) ?? [];+ let total = links.length * 23;+ for (const part of graphemes(text.replace(URL_TEXT, ""))) {+ if (EMOJI.test(part)) { total += 2; continue; }+ for (const char of part) {+ const point = char.codePointAt(0);+ total += X_WEIGHT_ONE.some(([low, high]) => point >= low && point <= high) ? 1 : 2;+ }+ }+ return total;+}+const countThreads = (text) => graphemes(text).reduce((sum, part) => sum + (EMOJI.test(part) ? utf8(part) : codePoints(part)), 0);++const RULES = {+ instagram: { name: "Instagram", text: 2200, tags: 30, mentions: 20, imageShape: [4 / 5, 1.91], shapeWords: "4:5 to 1.91:1", most: 20 },+ linkedin: { name: "LinkedIn", text: 3000, cut: 150, pages: 300 },+ x: { name: "X", text: 280, count: countX, most: 4 },+ threads: { name: "Threads", text: 500, count: countThreads, imageShape: [1 / 10, 10], shapeWords: "1:10 to 10:1", most: 20, seconds: [0, 300] },+ facebook: { name: "Facebook" },+ tiktok: { name: "TikTok", phone: "For You", text: 2200, count: (text) => text.length, photoText: 4000, most: 35 },+ reels: { name: "Reels", phone: "Reels", text: 2200, tags: 30, mentions: 20, tall: "recommend", seconds: [3, 900] },+ shorts: { name: "Shorts", phone: "Shorts", tall: "require", seconds: [0, 180] },+};++const ICONS = {+ heart: '<path d="M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"/>',+ comment: '<path d="M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"/>',+ send: '<path d="M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"/><path d="m21.854 2.147-10.94 10.939"/>',+ repost: '<path d="m2 9 3-3 3 3"/><path d="M13 18H7a2 2 0 0 1-2-2V6"/><path d="m22 15-3 3-3-3"/><path d="M11 6h6a2 2 0 0 1 2 2v10"/>',+ bookmark: '<path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"/>',+ like: '<path d="M7 10v12"/><path d="M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"/>',+ share: '<circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" x2="15.42" y1="13.51" y2="17.49"/><line x1="15.41" x2="8.59" y1="6.51" y2="10.49"/>',+ globe: '<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>',+ more: '<circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>',+ upload: '<path d="M12 3v12"/><path d="m17 8-5-5-5 5"/><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>',+ play: '<path d="M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"/>',+ left: '<path d="m15 18-6-6 6-6"/>',+ right: '<path d="m9 18 6-6-6-6"/>',+ plus: '<path d="M5 12h14"/><path d="M12 5v14"/>',+};+const icon = (name, size = 18) => `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${ICONS[name]}</svg>`;+const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);++const isVideo = (item) => "video" in item || "poster" in item;+const isSlide = (item) => "layout" in item || "html" in item;+const ratioOf = (item) => (item.width > 0 && item.height > 0 ? item.width / item.height : null);+const parseShape = (value) => {+ const match = /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/.exec(String(value ?? ""));+ return match && Number(match[2]) > 0 ? Number(match[1]) / Number(match[2]) : null;+};+const shapeWords = (ratio) => (ratio >= 1 ? `${ratio.toFixed(2).replace(/\.?0+$/, "")}:1` : `1:${(1 / ratio).toFixed(2).replace(/\.?0+$/, "")}`);++function variantOf(post, id) {+ const own = post.platforms?.[id] && typeof post.platforms[id] === "object" ? post.platforms[id] : {};+ const list = own.media ?? post.media ?? [];+ const media = (Array.isArray(list) ? list : [list]).filter((item) => item && typeof item === "object");+ const shape = parseShape(own.slideShape ?? post.slideShape) ?? 4 / 5;+ for (const item of media) if (isSlide(item)) { item.width = shape * 1000; item.height = 1000; }+ return {+ text: String(own.text ?? post.text ?? ""),+ media,+ when: own.when ?? post.when ?? "Now",+ documentTitle: own.documentTitle ?? post.documentTitle ?? post.title ?? "Document",+ brand: post.brand ?? {},+ };+}++function checksFor(id, variant) {+ const rule = RULES[id], out = [];+ const { text, media } = variant;+ const limit = rule.photoText && media.length && !media.some(isVideo) ? rule.photoText : rule.text;+ if (limit) {+ const used = (rule.count ?? codePoints)(text);+ if (used > limit) out.push(["warn", `${used} of ${limit} characters: ${used - limit} over ${rule.name}'s limit.`]);+ else if (used) out.push(["note", `${used} of ${limit} characters.`]);+ }+ const tags = text.match(/#[\p{L}\p{N}_]+/gu)?.length ?? 0, mentions = text.match(/@[\p{L}\p{N}_.]+/gu)?.length ?? 0;+ if (rule.tags && tags > rule.tags) out.push(["warn", `${tags} hashtags: ${rule.name} takes up to ${rule.tags}.`]);+ if (rule.mentions && mentions > rule.mentions) out.push(["warn", `${mentions} @ tags: ${rule.name} takes up to ${rule.mentions}.`]);+ if (rule.cut && codePoints(text) > rule.cut) {+ const shown = Array.from(text).slice(0, rule.cut).join("").trim();+ out.push(["note", `${rule.name} can cut the text around here, with "...see more": "...${Array.from(shown).slice(-28).join("")}"`]);+ }+ const count = media.length;+ if (rule.pages && count > rule.pages) out.push(["warn", `${count} pages: a ${rule.name} document takes up to ${rule.pages}.`]);+ if (rule.most && count > rule.most) out.push(["warn", `${count} items: ${rule.name} takes up to ${rule.most}.`]);+ const off = media.find((item) => !isVideo(item) && rule.imageShape && ratioOf(item) && (ratioOf(item) < rule.imageShape[0] * 0.99 || ratioOf(item) > rule.imageShape[1] * 1.01));+ if (off) out.push(["warn", `An image is ${shapeWords(ratioOf(off))}: ${rule.name} takes ${rule.shapeWords}.`]);+ if (id === "instagram" && count > 1 && media.every(ratioOf) && media.some((item) => Math.abs(ratioOf(item) - ratioOf(media[0])) > 0.02)) {+ out.push(["note", "Instagram crops every slide to the first one's shape."]);+ }+ const moving = media.find((item) => isVideo(item) && ratioOf(item));+ if (rule.tall === "recommend" && moving && Math.abs(ratioOf(moving) - 9 / 16) > 0.02) out.push(["warn", `This video is ${shapeWords(ratioOf(moving))}: ${rule.name} recommends 9:16 to avoid cropping or blank space.`]);+ if (rule.tall === "require" && moving && ratioOf(moving) > 1.01) out.push(["warn", `This video is ${shapeWords(ratioOf(moving))}: ${rule.name} must be square or vertical.`]);+ if (rule.seconds) for (const item of media) {+ const seconds = Number(item.duration);+ if (!isVideo(item) || !(seconds > 0)) continue;+ if (seconds > rule.seconds[1]) out.push(["warn", `This video runs ${Math.round(seconds)} s: ${rule.name} takes up to ${rule.seconds[1]} s.`]);+ if (seconds < rule.seconds[0]) out.push(["warn", `This video runs ${Math.round(seconds)} s: ${rule.name} needs at least ${rule.seconds[0]} s.`]);+ }+ if (media.some((item) => item.failed && !isVideo(item))) out.push(["warn", "An image can't load here. Use a file beside index.html or a data: URL."]);+ if (media.some((item) => item.failed && isVideo(item))) out.push(["note", "The video can't play here, so its poster stands in."]);+ return out;+}++function initials(name) {+ const words = String(name ?? "").trim().split(/\s+/).map((word) => graphemes(word).find((part) => /[\p{L}\p{N}]/u.test(part))).filter(Boolean);+ return (words.length > 1 ? words[0] + words.at(-1) : words[0] ?? "?").toLocaleUpperCase();+}+function avatarHtml(account) {+ const hue = Array.from(String(account.name ?? "")).reduce((sum, char) => (sum * 31 + char.codePointAt(0)) % 360, 210);+ const fallback = `<span dir="auto">${esc(initials(account.name))}</span>`;+ return `<div class="post-avatar" style="background:hsl(${hue} 42% 36%)" data-initials="${esc(initials(account.name))}">${account.avatar ? `<img src="${esc(account.avatar)}" alt="">` : fallback}</div>`;+}+function richText(text) {+ return String(text).split(/(https?:\/\/\S+|[#@][\p{L}\p{N}_.]*[\p{L}\p{N}_])/u)+ .map((part, index) => (index % 2 ? `<span class="tok">${esc(part)}</span>` : esc(part))).join("");+}+function captionHtml(variant, lead = "", more = "...more") {+ if (!variant.text) return `<div class="post-caption"><span class="empty-text">No text yet</span></div>`;+ return `<div class="post-caption" dir="auto"><div class="clip" dir="auto">${lead}${richText(variant.text)}</div><button type="button" class="see-more">${esc(more)}</button></div>`;+}++const brandStyle = (brand) => [["--slide-bg", brand.background], ["--slide-ink", brand.text], ["--slide-accent", brand.accent]]+ .filter(([, value]) => typeof value === "string" && /^[#\w(),.%\s-]+$/.test(value)).map(([name, value]) => `${name}:${value}`).join(";");++function slideHtml(item, variant, account) {+ const style = esc(brandStyle(variant.brand));+ const foot = `<div class="slide-foot"><span dir="auto">${esc(account.handle ? `@${account.handle}` : account.name)}</span></div>`;+ if ("html" in item) return `<div class="slide" style="${style}">${item.html}</div>`;+ const note = item.note ? `<p class="slide-note" dir="auto">${esc(item.note)}</p>` : "";+ if (item.layout === "points") {+ const points = (Array.isArray(item.points) ? item.points : []).map((point) => `<li dir="auto">${esc(point)}</li>`).join("");+ return `<div class="slide" style="${style}"><h3 class="slide-title" dir="auto">${esc(item.title)}</h3><ol class="slide-points">${points}</ol>${note}${foot}</div>`;+ }+ if (item.layout === "quote") {+ return `<div class="slide" style="${style}"><blockquote class="slide-quote" dir="auto">${esc(item.quote)}</blockquote>${item.by ? `<p class="slide-note" dir="auto">${esc(item.by)}</p>` : ""}${foot}</div>`;+ }+ return `<div class="slide" style="${style}">${item.kicker ? `<p class="slide-kicker" dir="auto">${esc(item.kicker)}</p>` : ""}<h3 class="slide-title" dir="auto">${esc(item.title)}</h3>${note}${foot}</div>`;+}+function posterHtml(item) {+ const time = Number(item.duration) > 0 ? `<span class="video-time">${Math.floor(item.duration / 60)}:${String(Math.round(item.duration % 60)).padStart(2, "0")}</span>` : "";+ return `<div class="poster-frame">${item.poster ? `<img src="${esc(item.poster)}" alt="${esc(item.alt)}">` : ""}<span class="play-mark">${icon("play", 26)}</span>${time}</div>`;+}+function itemHtml(item, variant, account, index) {+ if (isSlide(item)) return slideHtml(item, variant, account);+ if (isVideo(item)) {+ if (!item.video || item.failed) return posterHtml(item);+ return `<video src="${esc(item.video)}" controls playsinline preload="metadata"${item.poster ? ` poster="${esc(item.poster)}"` : ""} data-item="${index}"></video>`;+ }+ if (item.failed) return `<div class="missing-image">${esc(item.alt || "Image not available")}</div>`;+ return `<img src="${esc(item.src)}" alt="${esc(item.alt)}" data-item="${index}">`;+}++function frameRatio(id, media) {+ const rule = RULES[id], first = ratioOf(media[0]) ?? 1;+ const [low, high] = id === "instagram" ? rule.imageShape : [0.5, 2];+ return Math.min(high, Math.max(low, first));+}+const frameHtml = (item, variant, account, index, ratio) =>+ `<div class="frame" style="--r:${ratio ?? ratioOf(item) ?? 1.5}" data-frame="${index}">${itemHtml(item, variant, account, index)}</div>`;++function carouselHtml(id, variant, account) {+ const { media } = variant, ratio = frameRatio(id, media);+ const items = media.map((item, index) => `<div class="swipe-item">${frameHtml(item, variant, account, index, ratio)}</div>`).join("");+ const label = id === "linkedin" ? "Document pages" : "Carousel slides";+ const head = id === "linkedin" ? `<div class="doc-head"><span dir="auto">${esc(variant.documentTitle)}</span><span data-count>1 of ${media.length} pages</span></div>` : "";+ const counter = id === "instagram" ? `<span class="swipe-count" data-count>1/${media.length}</span>` : "";+ const dots = id === "instagram" || RULES[id].phone ? `<div class="dots" aria-hidden="true">${media.map((_, index) => `<i class="${index ? "" : "on"}"></i>`).join("")}</div>` : "";+ return `${head}<div class="carousel"><div class="swipe" dir="ltr" tabindex="0" role="group" aria-label="${label}">${items}</div>${counter}<button type="button" class="nav prev" aria-label="Previous" disabled>${icon("left", 16)}</button><button type="button" class="nav next" aria-label="Next">${icon("right", 16)}</button></div>${dots}`;+}+function gridHtml(id, variant, account) {+ const { media } = variant, shown = media.slice(0, 4);+ const tiles = shown.map((item, index) => {+ const more = id === "facebook" && index === 3 && media.length > 4 ? `<span class="grid-more">+${media.length - 4}</span>` : "";+ return `<div class="frame${shown.length === 3 && index === 0 ? " grid-three" : ""}" style="--r:1" data-frame="${index}">${itemHtml(item, variant, account, index)}${more}</div>`;+ }).join("");+ return `<div class="grid">${tiles}</div>`;+}+function mediaHtml(id, variant, account) {+ const { media } = variant;+ if (!media.length) return "";+ if (media.length === 1) {+ const ratio = id === "instagram" ? frameRatio(id, media) : undefined;+ return `<div class="media">${frameHtml(media[0], variant, account, 0, ratio)}</div>`;+ }+ if (id === "x" || id === "facebook") return `<div class="media">${gridHtml(id, variant, account)}</div>`;+ return `<div class="media">${carouselHtml(id, variant, account)}</div>`;+}++const label = (name, words) => `<span class="post-action">${icon(name)}${words ? ` ${words}` : ""}</span>`;+const ACTIONS = {+ linkedin: [["like", "Like"], ["comment", "Comment"], ["repost", "Repost"], ["send", "Send"]],+ facebook: [["like", "Like"], ["comment", "Comment"], ["share", "Share"]],+ instagram: [["heart"], ["comment"], ["send"], ["bookmark"]],+ x: [["comment"], ["repost"], ["heart"], ["bookmark"], ["upload"]],+ threads: [["heart"], ["comment"], ["repost"], ["send"]],+};+const actionsHtml = (id) => `<div class="post-actions" aria-hidden="true">${ACTIONS[id].map(([name, words]) => label(name, words)).join("")}</div>`;+const dotsMeta = (parts) => parts.filter(Boolean).join(" · ");++function feedCardHtml(id, variant, account) {+ const handle = account.handle ? `@${account.handle}` : "";+ const name = `<div class="post-author-name" dir="auto">${esc(account.name)}</div>`;+ const moreIcon = icon("more");+ if (id === "instagram") {+ const shownName = account.handle || account.name;+ return `<header class="post-header">${avatarHtml(account)}<div class="post-header-text"><div class="post-author-name" dir="auto">${esc(shownName)}</div></div><div class="post-header-actions"><span class="post-follow">Follow</span>${moreIcon}</div></header>${mediaHtml(id, variant, account)}${actionsHtml(id)}<div class="post-body">${captionHtml(variant, variant.text ? `<b>${esc(shownName)}</b> ` : "", "more")}</div>`;+ }+ if (id === "x") {+ return `<header class="post-header">${avatarHtml(account)}<div class="post-header-text">${name} <span class="post-author-meta" style="display:inline" dir="auto">${esc(dotsMeta([handle, variant.when]))}</span></div><div class="post-header-actions">${moreIcon}</div></header><div class="post-body">${captionHtml(variant)}</div>${mediaHtml(id, variant, account)}${actionsHtml(id)}`;+ }+ if (id === "threads") {+ const shownName = account.handle || account.name;+ return `<header class="post-header">${avatarHtml(account)}<div class="post-header-text"><div class="post-author-name" dir="auto">${esc(shownName)}</div> <span class="post-author-meta" style="display:inline">${esc(variant.when)}</span></div><div class="post-header-actions">${moreIcon}</div></header><div class="post-body">${captionHtml(variant)}</div>${mediaHtml(id, variant, account)}${actionsHtml(id)}`;+ }+ const subtitle = account.subtitle && id === "linkedin" ? `<div class="post-author-subtitle" dir="auto">${esc(account.subtitle)}</div>` : "";+ const follow = id === "linkedin" ? `<span class="post-follow">${icon("plus", 14)} Follow</span>` : "";+ return `<header class="post-header">${avatarHtml(account)}<div class="post-header-text">${name}${subtitle}<div class="post-author-meta"><span dir="auto">${esc(variant.when)}</span> · ${icon("globe", 12)}</div></div><div class="post-header-actions">${follow}${moreIcon}</div></header><div class="post-body">${captionHtml(variant, "", id === "facebook" ? "See more" : "...more")}</div>${mediaHtml(id, variant, account)}${actionsHtml(id)}`;+}+function phoneCardHtml(id, variant, account) {+ const rule = RULES[id], { media } = variant;+ const stage = !media.length+ ? `<div class="no-video"><span class="play-mark">${icon("play", 26)}</span><span>No video yet</span></div>`+ : `<div class="media">${media.length === 1 ? frameHtml(media[0], variant, account, 0) : carouselHtml(id, variant, account)}</div>`;+ const rail = ["heart", "comment", id === "tiktok" ? "bookmark" : "repost", "send"].map((name) => icon(name, 24)).join("");+ return `${stage}<span class="phone-label">${esc(rule.phone)}</span><div class="phone-rail" aria-hidden="true">${rail}</div><div class="phone-foot"><div class="phone-author">${avatarHtml(account)}<span dir="auto">${esc(account.handle ? `@${account.handle}` : account.name)}</span></div>${variant.text ? captionHtml(variant, "", "more") : ""}</div>`;+}+function cardHtml(id, variant, account) {+ const body = RULES[id].phone ? `<div class="phone" data-name="${esc(RULES[id].name)} preview">${phoneCardHtml(id, variant, account)}</div>`+ : `<article class="post-card" data-platform="${id}" data-name="${esc(RULES[id].name)} preview">${feedCardHtml(id, variant, account)}</article>`;+ return `<div class="card-title">${esc(RULES[id].name)}</div>${body}<ul class="checks"></ul>`;+}++function renderChecks(entry) {+ const checks = checksFor(entry.id, entry.variant);+ entry.wrap.querySelector(".checks").innerHTML = checks.map(([level, words]) => `<li class="${level}" dir="auto">${esc(words)}</li>`).join("");+ entry.tab?.querySelector(".tab-dot")?.toggleAttribute("hidden", !checks.some(([level]) => level === "warn"));+}++const cards = new WeakMap();+function measureClip(clip) {+ const caption = clip.closest(".post-caption");+ if (caption && !caption.classList.contains("open")) caption.classList.toggle("cut", clip.scrollHeight > clip.clientHeight + 1);+}+const clipWatcher = window.ResizeObserver ? new ResizeObserver((entries) => entries.forEach((entry) => measureClip(entry.target))) : null;++function fillCard(entry, account) {+ entry.wrap.innerHTML = cardHtml(entry.id, entry.variant, account);+ entry.wrap.querySelectorAll(".clip").forEach((clip) => { clipWatcher?.observe(clip); measureClip(clip); });+ renderChecks(entry);+}++function tellBot(post, id) {+ window.mausbot?.setContext?.(`The person is looking at the ${RULES[id].name} preview of "${post.title ?? "this post"}".`)?.catch?.(() => {});+}++function renderPost(post, account, root, index) {+ const asked = Object.keys(post.platforms ?? {});+ const ids = asked.filter((id) => id in RULES);+ const unknown = asked.filter((id) => !(id in RULES));+ const set = document.createElement("section");+ set.className = "post-set";+ const title = post.title ? `<h2 dir="auto">${esc(post.title)}</h2>` : "";+ const when = post.when ? `<span dir="auto">${esc(post.when)}</span>` : "";+ set.innerHTML = `${title || when ? `<div class="post-set-head">${title}${when}</div>` : ""}<div class="tabs" role="tablist" aria-label="Platforms"></div><div class="cards"></div>`;+ if (!ids.length) {+ set.querySelector(".cards").innerHTML = `<p class="problem">No platforms to show for this post. Use: ${Object.keys(RULES).join(", ")}.</p>`;+ set.querySelector(".tabs").remove();+ root.append(set);+ return;+ }+ if (unknown.length) set.insertAdjacentHTML("beforeend", `<p class="preview-note">No preview for: ${esc(unknown.join(", "))}.</p>`);+ const tabs = set.querySelector(".tabs"), holder = set.querySelector(".cards");+ const entries = ids.map((id, position) => {+ const tab = document.createElement("button");+ tab.type = "button";+ tab.className = "tab";+ tab.setAttribute("role", "tab");+ tab.setAttribute("aria-selected", String(position === 0));+ tab.dataset.tab = id;+ tab.innerHTML = `${esc(RULES[id].name)}<span class="tab-dot" hidden></span>`;+ tabs.append(tab);+ const wrap = document.createElement("div");+ wrap.className = `card-wrap${position ? " off" : ""}`;+ wrap.setAttribute("role", "tabpanel");+ wrap.dataset.panel = id;+ holder.append(wrap);+ const entry = { id, wrap, tab, variant: variantOf(post, id), account };+ cards.set(wrap, entry);+ fillCard(entry, account);+ return entry;+ });+ tabs.addEventListener("click", (event) => {+ const chosen = event.target.closest?.("[data-tab]");+ if (!chosen) return;+ for (const entry of entries) {+ const on = entry.id === chosen.dataset.tab;+ entry.tab.setAttribute("aria-selected", String(on));+ entry.wrap.classList.toggle("off", !on);+ if (on) entry.wrap.querySelectorAll(".clip").forEach(measureClip);+ }+ tellBot(post, chosen.dataset.tab);+ });+ root.append(set);+ if (index === 0) tellBot(post, ids[0]);+}++function itemFor(element) {+ const wrap = element.closest(".card-wrap");+ const entry = wrap && cards.get(wrap);+ const frame = element.closest("[data-frame]");+ return entry && frame ? { entry, frame, item: entry.variant.media[Number(frame.dataset.frame)] } : null;+}+document.addEventListener("load", (event) => {+ const image = event.target;+ if (!(image instanceof HTMLImageElement) || !image.dataset.item) return;+ const found = itemFor(image);+ if (!found?.item || !image.naturalWidth) return;+ found.item.width = image.naturalWidth;+ found.item.height = image.naturalHeight;+ if (!found.frame.closest(".grid, .phone")) {+ const inCarousel = found.frame.closest(".carousel");+ const shape = found.entry.id === "instagram" || inCarousel ? frameRatio(found.entry.id, found.entry.variant.media) : ratioOf(found.item);+ if (inCarousel) inCarousel.querySelectorAll(".frame").forEach((frame) => frame.style.setProperty("--r", shape));+ else found.frame.style.setProperty("--r", shape);+ }+ renderChecks(found.entry);+}, true);+document.addEventListener("loadedmetadata", (event) => {+ const video = event.target;+ const found = video instanceof HTMLVideoElement ? itemFor(video) : null;+ if (!found?.item) return;+ found.item.width = video.videoWidth;+ found.item.height = video.videoHeight;+ found.item.duration = video.duration;+ if (!found.frame.closest(".grid, .phone, .carousel") && video.videoWidth) found.frame.style.setProperty("--r", video.videoWidth / video.videoHeight);+ renderChecks(found.entry);+}, true);+document.addEventListener("error", (event) => {+ const target = event.target;+ if (target instanceof HTMLImageElement && target.closest(".post-avatar")) {+ const avatar = target.closest(".post-avatar");+ avatar.textContent = avatar.dataset.initials;+ return;+ }+ if (target instanceof HTMLImageElement && target.closest(".poster-frame")) { target.remove(); return; }+ if (!(target instanceof HTMLImageElement || target instanceof HTMLVideoElement)) return;+ const found = itemFor(target);+ if (!found?.item) return;+ found.item.failed = true;+ const index = Number(found.frame.dataset.frame);+ target.outerHTML = itemHtml(found.item, found.entry.variant, found.entry.account, index);+ renderChecks(found.entry);+}, true);++function syncCarousel(swipe) {+ const items = swipe.children, step = items[1] ? items[1].offsetLeft - items[0].offsetLeft : 0;+ if (!step) return;+ const at = Math.max(0, Math.min(items.length - 1, Math.round(swipe.scrollLeft / step)));+ const media = swipe.closest(".media");+ const counter = media.querySelector("[data-count]");+ if (counter) counter.textContent = counter.closest(".doc-head") ? `${at + 1} of ${items.length} pages` : `${at + 1}/${items.length}`;+ media.querySelectorAll(".dots i").forEach((dot, index) => dot.classList.toggle("on", index === at));+ media.querySelector(".nav.prev").disabled = at === 0;+ media.querySelector(".nav.next").disabled = swipe.scrollLeft + swipe.clientWidth >= swipe.scrollWidth - 1;+}+document.addEventListener("scroll", (event) => {+ if (event.target instanceof Element && event.target.matches(".swipe")) syncCarousel(event.target);+}, true);+document.addEventListener("click", (event) => {+ const nav = event.target.closest?.(".nav");+ if (nav) {+ const swipe = nav.closest(".carousel").querySelector(".swipe");+ const step = swipe.children[1].offsetLeft - swipe.children[0].offsetLeft;+ swipe.scrollBy({ left: nav.classList.contains("next") ? step : -step, behavior: "smooth" });+ return;+ }+ const more = event.target.closest?.(".see-more");+ if (more) more.closest(".post-caption").classList.add("open");+});++function start() {+ const root = document.getElementById("root");+ let data;+ try {+ data = JSON.parse(document.getElementById("posts-data").textContent);+ } catch (error) {+ root.innerHTML = `<p class="problem">The posts-data block isn't valid JSON: ${esc(error.message)}</p>`;+ return;+ }+ const given = data.account ?? {};+ const handle = String(given.handle ?? "").trim().replace(/^@/, "");+ const account = { ...given, name: String(given.name ?? "").trim() || handle || "Your name", handle };+ const posts = Array.isArray(data.posts) ? data.posts : [];+ if (!posts.length) root.innerHTML = `<p class="problem">No posts yet.</p>`;+ posts.forEach((post, index) => renderPost(post && typeof post === "object" ? post : {}, account, root, index));+}+start();+</script>+</body>+</html>diff --git a/src/lib/ready-bots.test.ts b/src/lib/ready-bots.test.tsindex 940209e226..0e6fd419ea 100644--- a/src/lib/ready-bots.test.ts+++ b/src/lib/ready-bots.test.ts@@ -92,6 +92,7 @@ describe("the social media manager", () => {expect(social).toMatchObject({ title: "Social media manager", category: "work", apps: ["postiz"] });expect(social.soul).toContain("Add every post to Postiz as a draft, unless the user gave it a time to go out: then schedule it for that time.");expect(social.soul).toContain("Never publish a post straight away (type now) unless the user asks for that post to go out now.");+ expect(social.soul).toContain("show a preview of it with show_html, then add it to Postiz without waiting for a reply.");expect(social.routines).toEqual([expect.objectContaining({ name: "Weekly post plan", enabled: false })]);expect(social.routines![0]!.prompt).toContain("as drafts");});diff --git a/src/lib/ready-bots.ts b/src/lib/ready-bots.tsindex a70ba29965..9879184d48 100644--- a/src/lib/ready-bots.ts+++ b/src/lib/ready-bots.ts@@ -120,6 +120,7 @@ export const READY_BOTS: ReadyBot[] = [soul: ["You manage the user's social media through Postiz, with the postiz tools.","Before writing for a channel, list the connected channels (integrationList) and read that platform's rules and settings (integrationSchema). Never guess a channel id.",+ "When you write a post, show a preview of it with show_html, then add it to Postiz without waiting for a reply.","Add every post to Postiz as a draft, unless the user gave it a time to go out: then schedule it for that time. Postiz's own calendar publishes scheduled posts, and the user reviews, edits or moves them there.","Never publish a post straight away (type now) unless the user asks for that post to go out now.","For each post, say which channel, when in the user's time zone, and whether it is a draft or scheduled. Postiz takes dates in UTC.",diff --git a/src/lib/social-posts-template.test.ts b/src/lib/social-posts-template.test.tsnew file mode 100644index 0000000000..fefedc11ec--- /dev/null+++ b/src/lib/social-posts-template.test.ts@@ -0,0 +1,154 @@+// @vitest-environment happy-dom+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { APP_LIMITS } from "../../shared/app";++const folder = join(process.cwd(), "skills", "social-posts");+const template = readFileSync(join(folder, "posts.html"), "utf8");+const pageScript = [...template.matchAll(/<script>([\s\S]*?)<\/script>/g)].at(-1)![1]!;+const DATA_BLOCK = /<script id="posts-data" type="application\/json">\s*([\s\S]*?)\s*<\/script>/;++function mount(data: unknown): void {+ const json = typeof data === "string" ? data : JSON.stringify(data);+ const script = document.createElement("script");+ script.id = "posts-data";+ script.type = "application/json";+ script.textContent = json;+ document.head.replaceChildren(script);+ document.body.innerHTML = '<main id="root"></main>';+ new Function(pageScript)();+}+const post = (platforms: Record<string, unknown>, rest: Record<string, unknown> = {}) => ({ account: { name: "Ada Stone", handle: "ada" }, posts: [{ title: "T", platforms, ...rest }] });+const panel = (id: string) => document.querySelector(`[data-panel="${id}"]`)!;+const checks = (id: string) => [...panel(id).querySelectorAll(".checks li")].map((item) => item.textContent ?? "");+const warnings = (id: string) => [...panel(id).querySelectorAll(".checks li.warn")].map((item) => item.textContent ?? "");+const images = (count: number) => Array.from({ length: count }, (_, index) => ({ src: `${index}.png` }));++describe("social-posts template", () => {+ it("is self-contained, carries its licence notices and leaves room for a bot's data", () => {+ const code = template.replace(/<!--[\s\S]*?-->/, "").replace(/\/\*[\s\S]*?\*\//g, "");+ expect(code).not.toMatch(/(?:src|href)="https?:/);+ expect(code).not.toMatch(/<script[^>]+src=|<link\b|@import/);+ expect(template).toContain("Copyright (c) 2026 Tushar Bhardwaj");+ expect(template).toContain("Lucide Contributors");+ expect(readFileSync(join(process.cwd(), "NOTICE"), "utf8")).toContain("third_party/minimock/LICENSE");+ expect(Buffer.byteLength(template)).toBeLessThan(APP_LIMITS.htmlBytes / 4);+ expect(() => JSON.parse(DATA_BLOCK.exec(template)![1]!)).not.toThrow();+ });++ it("shows the sample with one tab per platform, one card at a time, and says it is a preview", () => {+ mount(DATA_BLOCK.exec(template)![1]!);+ const tabs = [...document.querySelectorAll<HTMLElement>("[data-tab]")];+ expect(tabs.map((tab) => tab.dataset.tab)).toEqual(["instagram", "linkedin", "x", "threads", "facebook", "reels"]);+ expect(document.querySelectorAll(".card-wrap:not(.off)")).toHaveLength(1);+ tabs[1]!.click();+ expect(panel("linkedin").classList.contains("off")).toBe(false);+ expect(panel("instagram").classList.contains("off")).toBe(true);+ expect(template).toMatch(/Preview: a close likeness/);+ });++ it("counts X as X does: weighted characters, a whole emoji as 2, any link as 23", () => {+ mount(post({ x: { text: "a".repeat(280) } }));+ expect(warnings("x")).toEqual([]);+ mount(post({ x: { text: "a".repeat(281) } }));+ expect(warnings("x")[0]).toContain("281 of 280 characters: 1 over");+ mount(post({ x: { text: `${"a".repeat(278)}👨👩👧👦` } }));+ expect(checks("x")[0]).toContain("280 of 280");+ mount(post({ x: { text: `${"中".repeat(140)}a` } }));+ expect(warnings("x")[0]).toContain("281 of 280");+ mount(post({ x: { text: `https://example.com/${"p".repeat(400)}` } }));+ expect(checks("x")[0]).toContain("23 of 280");+ });++ it("warns past each platform's sourced limit, and never on a platform that publishes none", () => {+ mount(post({+ threads: { text: `${"a".repeat(497)}👍` },+ linkedin: { text: "a".repeat(3001), media: images(301) },+ instagram: { text: `${"#tag ".repeat(31)}${"@me ".repeat(21)}`, media: images(21) },+ x: { text: "hi", media: images(5) },+ facebook: { text: "a".repeat(70000), media: images(30) },+ tiktok: { text: "a".repeat(2201), media: [{ video: "", poster: "" }] },+ reels: { text: "a".repeat(2201), media: [{ video: "", width: 1920, height: 1080, duration: 901 }] },+ shorts: { media: [{ video: "", width: 1920, height: 1080, duration: 181 }] },+ }));+ expect(warnings("threads")[0]).toContain("501 of 500");+ expect(warnings("linkedin")).toEqual(expect.arrayContaining([expect.stringContaining("3001 of 3000"), expect.stringContaining("301 pages")]));+ expect(warnings("instagram")).toEqual(expect.arrayContaining([expect.stringContaining("31 hashtags"), expect.stringContaining("21 @ tags"), expect.stringContaining("21 items")]));+ expect(warnings("x")).toEqual([expect.stringContaining("5 items: X takes up to 4")]);+ expect(checks("facebook")).toEqual([]);+ expect(warnings("tiktok")[0]).toContain("2201 of 2200");+ expect(warnings("reels")).toEqual(expect.arrayContaining([expect.stringContaining("2201 of 2200"), expect.stringContaining("recommends 9:16"), expect.stringContaining("901 s")]));+ expect(warnings("shorts")).toEqual(expect.arrayContaining([expect.stringContaining("must be square or vertical"), expect.stringContaining("181 s")]));+ });++ it("uses TikTok's larger description limit for a photo post", () => {+ mount(post({ tiktok: { text: "a".repeat(3000), media: images(2) } }));+ expect(warnings("tiktok")).toEqual([]);+ expect(checks("tiktok")[0]).toContain("3000 of 4000");+ });++ it("says where LinkedIn can cut the text, as a note and not a warning", () => {+ mount(post({ linkedin: { text: `${"a".repeat(140)} end of hook, and more words after it` } }));+ expect(warnings("linkedin")).toEqual([]);+ expect(checks("linkedin").join()).toContain("...see more");+ expect(checks("linkedin").join()).toContain("end of h");+ mount(post({ linkedin: { text: "a".repeat(150) } }));+ expect(checks("linkedin").join()).not.toContain("see more");+ });++ it("flags an image of the wrong shape, and a carousel whose slides differ, from the sizes it is given", () => {+ mount(post({ instagram: { media: [{ src: "a.png", width: 2400, height: 800 }] } }));+ expect(warnings("instagram")[0]).toContain("3:1");+ expect(warnings("instagram")[0]).toContain("4:5 to 1.91:1");+ mount(post({ instagram: { media: [{ src: "a.png", width: 1080, height: 1350 }] } }));+ expect(warnings("instagram")).toEqual([]);+ mount(post({ instagram: { media: [{ src: "a.png", width: 1080, height: 1350 }, { src: "b.png", width: 1080, height: 1080 }] } }));+ expect(checks("instagram").join()).toContain("first one's shape");+ });++ it("draws a swipeable carousel with dots on Instagram and a paged document on LinkedIn", () => {+ const slides = [{ layout: "cover", title: "One" }, { layout: "points", title: "Two", points: ["a", "b"] }, { layout: "quote", quote: "Three" }, { html: '<b id="own">Four</b>' }];+ mount(post({ instagram: {}, linkedin: { documentTitle: "My doc" } }, { media: slides }));+ expect(panel("instagram").querySelectorAll(".swipe-item")).toHaveLength(4);+ expect(panel("instagram").querySelectorAll(".dots i")).toHaveLength(4);+ expect(panel("instagram").querySelector("[data-count]")!.textContent).toBe("1/4");+ expect(panel("linkedin").querySelector(".doc-head")!.textContent).toContain("My doc");+ expect(panel("linkedin").querySelector("[data-count]")!.textContent).toBe("1 of 4 pages");+ expect(panel("linkedin").querySelector("#own")!.textContent).toBe("Four");+ expect(panel("linkedin").querySelectorAll(".slide-points li")).toHaveLength(2);+ });++ it("plays a video it can, shows a poster with a play mark when it can't, and notes the swap", () => {+ mount(post({ reels: { media: [{ video: "clip.mp4", poster: "p.jpg" }] }, shorts: { media: [{ poster: "p.jpg" }] }, tiktok: {} }));+ expect(panel("reels").querySelector("video")!.getAttribute("src")).toBe("clip.mp4");+ expect(panel("shorts").querySelector(".poster-frame .play-mark")).not.toBeNull();+ expect(panel("tiktok").querySelector(".no-video")).not.toBeNull();+ panel("reels").querySelector("video")!.dispatchEvent(new Event("error"));+ expect(panel("reels").querySelector("video")).toBeNull();+ expect(panel("reels").querySelector(".poster-frame .play-mark")).not.toBeNull();+ expect(checks("reels").join()).toContain("poster stands in");+ });++ it("survives empty and odd data: initials, a failed image, right-to-left text and hostile words", () => {+ mount(post({ linkedin: { text: "<img src=x onerror=alert(1)> مرحبا", media: [{ src: "gone.png", alt: "Gone" }] }, facebook: { text: "" } }));+ expect(panel("linkedin").querySelector(".post-avatar")!.textContent).toBe("AS");+ expect(panel("linkedin").querySelector(".clip img")).toBeNull();+ expect(panel("linkedin").querySelector(".clip")!.getAttribute("dir")).toBe("auto");+ expect(panel("facebook").querySelector(".empty-text")).not.toBeNull();+ panel("linkedin").querySelector(".frame img")!.dispatchEvent(new Event("error"));+ expect(panel("linkedin").querySelector(".missing-image")!.textContent).toBe("Gone");+ expect(warnings("linkedin").join()).toContain("can't load here");++ mount({ account: { avatar: "gone.png", name: "نور الهدى" }, posts: [{ platforms: { x: { text: "hi" } } }] });+ panel("x").querySelector(".post-avatar img")!.dispatchEvent(new Event("error"));+ expect(panel("x").querySelector(".post-avatar")!.textContent).toBe("نا");++ mount({ posts: [{ platforms: { nosuch: {} } }] });+ expect(document.querySelector(".problem")!.textContent).toContain("No platforms");+ mount({});+ expect(document.querySelector(".problem")!.textContent).toBe("No posts yet.");+ mount("{ not json");+ expect(document.querySelector(".problem")!.textContent).toContain("isn't valid JSON");+ });+});diff --git a/third_party/minimock/LICENSE b/third_party/minimock/LICENSEnew file mode 100644index 0000000000..9b7f30fb48--- /dev/null+++ b/third_party/minimock/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Tushar Bhardwaj++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.