src/text.js
// Platform text rules, length counting, hashtags, UTM tagging and fitting for social-publisher.
// Everything here is pure: it only reformats text the user supplied.
import { ToolError } from "./errors.js";
export const PLATFORMS = ["x", "linkedin", "instagram", "tiktok", "youtube", "facebook"];
// limit: maximum post length measured with `method`. hardMaxHashtags: the platform rejects or ignores more.
export const RULES = {
x: { limit: 280, method: "x_weighted", linkInText: true, maxHashtags: 2, hardMaxHashtags: 30, joiner: " " },
linkedin: { limit: 3000, method: "code_points", linkInText: true, maxHashtags: 5, hardMaxHashtags: 30, joiner: "\n\n" },
instagram: { limit: 2200, method: "code_points", linkInText: false, maxHashtags: 5, hardMaxHashtags: 30, joiner: "\n\n" },
tiktok: { limit: 2200, method: "code_points", linkInText: false, maxHashtags: 5, hardMaxHashtags: 30, joiner: "\n\n" },
youtube: { limit: 5000, method: "utf8_bytes", linkInText: true, maxHashtags: 3, hardMaxHashtags: 15, titleLimit: 100, joiner: "\n\n" },
facebook: { limit: 5000, method: "code_points", linkInText: true, maxHashtags: 3, hardMaxHashtags: 30, joiner: "\n\n" },
};
const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
export const graphemes = (s) => Array.from(segmenter.segment(s), (x) => x.segment);
/** Removes control characters (keeps \n and \t), normalises to NFC and tidies spaces. */
export function cleanText(s) {
return String(s)
.normalize("NFC")
.replace(/\r\n?/g, "\n")
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u200b\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, "")
.replace(/[ \t]+/g, " ")
.replace(/ *\n */g, "\n")
.replace(/\n{3,}/g, "\n\n")
.trim();
}
// X / twitter-text v3 weighting: these code point ranges weigh 1, everything else 2; emoji weigh 2;
// each URL weighs 23 (t.co wrapping). An approximation of the official library, documented in README.
const LIGHT = [[0, 4351], [8192, 8205], [8208, 8223], [8242, 8247]];
const EMOJI_RE = /\p{Extended_Pictographic}|\p{Regional_Indicator}|\u20e3/u;
const URL_RE = /https?:\/\/[^\s]+/gi;
function weighChars(s) {
let w = 0;
for (const g of graphemes(s)) {
if (EMOJI_RE.test(g)) {
w += 2;
continue;
}
for (const ch of g) {
const cp = ch.codePointAt(0);
w += LIGHT.some(([a, b]) => cp >= a && cp <= b) ? 1 : 2;
}
}
return w;
}
export function xWeightedLength(text) {
const t = String(text).normalize("NFC");
let total = 0;
let last = 0;
for (const m of t.matchAll(URL_RE)) {
total += weighChars(t.slice(last, m.index)) + 23;
last = m.index + m[0].length;
}
return total + weighChars(t.slice(last));
}
export function measure(text, method) {
if (method === "x_weighted") return xWeightedLength(text);
if (method === "utf8_bytes") return Buffer.byteLength(text, "utf8");
return [...text].length;
}
// ------------------------------------------------------------------------------------------------
// Hashtags
// ------------------------------------------------------------------------------------------------
const INLINE_TAG_RE = /(^|[\s(])#([\p{L}\p{N}\p{M}_]+)/gu;
/** Returns the tag without '#', or null if nothing usable remains (empty or digits only). */
export function normalizeHashtag(raw) {
const t = String(raw).normalize("NFC").trim().replace(/^#+/, "").replace(/[^\p{L}\p{N}\p{M}_]/gu, "");
if (!t || /^[\p{N}_]+$/u.test(t)) return null;
return t.slice(0, 100);
}
export function inlineHashtags(text) {
return [...String(text).matchAll(INLINE_TAG_RE)].map((m) => m[2]);
}
// ------------------------------------------------------------------------------------------------
// Links and UTM parameters
// ------------------------------------------------------------------------------------------------
export function checkLink(link, field = "link") {
let u;
try {
u = new URL(link);
} catch {
throw new ToolError("invalid_input", `${field}: not a valid URL`);
}
if (!["https:", "http:"].includes(u.protocol)) throw new ToolError("invalid_input", `${field}: only http(s) links are allowed`);
if (u.username || u.password) throw new ToolError("invalid_input", `${field}: links with embedded credentials are not allowed`);
return u;
}
const utmValue = (v, normalize) => {
const t = String(v).replace(/[\u0000-\u001f\u007f]/g, "").trim();
return normalize ? t.toLowerCase().replace(/\s+/g, "_") : t;
};
export function tagLink(link, utm, platform) {
const u = checkLink(link);
if (!utm) return u.toString();
const normalize = utm.normalize !== false;
const params = { utm_source: utm.source ?? platform, utm_medium: utm.medium ?? "social", utm_campaign: utm.campaign, utm_content: utm.content, utm_term: utm.term };
for (const [k, v] of Object.entries(params)) if (v !== undefined) u.searchParams.set(k, utmValue(v, normalize));
return u.toString();
}
// ------------------------------------------------------------------------------------------------
// Fitting text into a limit
// ------------------------------------------------------------------------------------------------
/**
* Longest prefix of `body` that fits. Prefers ending at a complete sentence when that keeps at least
* half of the room (no ellipsis needed); otherwise cuts at a word boundary and adds an ellipsis.
*/
function fitBody(body, fits) {
if (fits(body)) return { text: body, truncated: false };
const gs = graphemes(body);
let lo = 0;
let hi = gs.length;
const cand = (n) => `${gs.slice(0, n).join("").trimEnd()}\u2026`;
if (!fits(cand(0))) return null;
while (lo < hi) {
const mid = Math.ceil((lo + hi) / 2);
if (fits(cand(mid))) lo = mid;
else hi = mid - 1;
}
const prefix = gs.slice(0, lo).join("");
// Sentence ends inside the fitting prefix (the next character in the full body must be whitespace).
const window = gs.slice(0, lo + 1).join("");
let sentenceEnd = -1;
for (const m of window.matchAll(/[.!?]["')\]\u201d\u2019]?(?=\s)/gu)) if (m.index + m[0].length <= prefix.length) sentenceEnd = m.index + m[0].length;
if (sentenceEnd >= prefix.length * 0.5 && fits(prefix.slice(0, sentenceEnd))) return { text: prefix.slice(0, sentenceEnd), truncated: true };
const ws = prefix.search(/\s\S*$/);
const cut = ws > prefix.length * 0.7 ? prefix.slice(0, ws) : prefix;
return { text: `${cut.replace(/[\s,;:.-]+$/u, "")}\u2026`, truncated: true };
}
const stripAngles = (s) => s.replace(/[<>]/g, "");
// Sentences that announce content ("Here are 5 points.", "These are three tips") or a thread. In a
// shortened post they would promise something that is no longer there, so condensed variants drop them.
const COUNT_WORD = String.raw`(?:\d+|two|three|four|five|six|seven|eight|nine|ten|a few|several|some)`;
const ANNOUNCE_RE = new RegExp(String.raw`\b(?:here(?:'s|’s| is| are)|these are|below are|in this (?:thread|post|video))\b[^.!?]*\b${COUNT_WORD}\b[^.!?]*\b(?:points?|things?|ways?|tips?|reasons?|facts?|takeaways?|lessons?|ideas?|steps?|findings?|sources?)\b`, "i");
const THREAD_RE = /\bthread\b|\u{1F9F5}|^\s*\d+\s*\/\s*\d*\s*$/iu;
/** Removes announcing sentences ("Here are 5 points.") from a paragraph. */
export function stripFraming(text) {
// Split after sentence punctuation that is followed by whitespace; every character is kept.
const sentences = String(text).split(/(?<=[.!?]["')\]”’]?)(?=\s)/u);
return sentences.filter((s) => !ANNOUNCE_RE.test(s) && !THREAD_RE.test(s.trim())).join("").replace(/[ \t]{2,}/g, " ").trim();
}
/**
* Whole points that fit, best first: `points` are already ranked. Ranked points that do not fit are
* skipped (a later, shorter one may fit); unranked points (a brief) stop at the first that does not,
* to keep the author's order. The tail (a script's call-to-action segment) is added when it fits.
*/
function condensedBody(points, tail, joiner, tags, fitsWith, ranked) {
for (let k = tags.length; k >= 0; k--) {
const t = tags.slice(0, k);
const chosen = [];
for (const p of points) {
if (fitsWith([...chosen, p.text].join(joiner), t)) chosen.push(p.text);
else if (!ranked || !chosen.length) break;
}
if (!chosen.length) continue;
if (tail && fitsWith([...chosen, tail].join(joiner), t)) chosen.push(tail);
return { body: chosen.join(joiner), k, used: chosen.length - (tail && chosen[chosen.length - 1] === tail ? 1 : 0) };
}
return null;
}
/** Builds one platform draft. `base` = { paragraphs, title, cta, link, hashtags, maxHashtags, account }. */
export function composePost(platform, base) {
const rule = RULES[platform];
const notes = [];
const joiner = rule.joiner;
let body = base.paragraphs.join(joiner);
if (joiner === " ") body = body.replace(/\s*\n+\s*/g, " ");
let cta = base.cta ?? "";
if (platform === "youtube" && /[<>]/.test(body + cta)) {
body = stripAngles(body);
cta = stripAngles(cta);
notes.push("Removed < and > characters: YouTube rejects them in titles and descriptions.");
}
// Hashtags: skip ones already in the text, cap per platform (never above the hard cap).
const inline = new Set(inlineHashtags(`${body} ${cta}`).map((t) => t.toLowerCase()));
const cap = Math.min(base.maxHashtags ?? rule.maxHashtags, rule.hardMaxHashtags);
const tags = [];
const dropped = [];
for (const h of base.hashtags) {
if (inline.has(h.toLowerCase())) continue;
if (inline.size + tags.length >= cap) dropped.push(h);
else tags.push(h);
}
if (dropped.length) notes.push(`Left out ${dropped.length} hashtag(s) to stay within ${cap} for ${platform}: ${dropped.map((t) => `#${t}`).join(" ")}`);
if (inline.size > rule.hardMaxHashtags) notes.push(`The text already contains ${inline.size} hashtags; ${platform} allows at most ${rule.hardMaxHashtags}.`);
let linkLine = base.link && rule.linkInText ? base.link : "";
if (base.link && !rule.linkInText) notes.push(`Links in ${platform} captions are not clickable, so the link is not in the text. Use the returned link in your bio or a link sticker.`);
const assemble = (b, t, l = linkLine) => [b, cta, l, t.map((x) => `#${x}`).join(" ")].filter(Boolean).join(joiner === " " ? "\n\n" : joiner);
const fits = (s) => measure(s, rule.method) <= rule.limit;
let text = assemble(body, tags);
let truncated = false;
if (!fits(text)) {
// 1. A self-contained variant made of whole points (best supported first), without the
// introduction, so the post never promises content that was cut ("here are 5 points").
const pts = (base.points ?? []).filter((p) => p.text);
const sourceLink = !linkLine && rule.linkInText && pts[0]?.source_url ? pts[0].source_url : "";
const condensed = pts.length ? condensedBody(pts, base.tail, joiner, tags, (b, t) => fits(assemble(b, t, sourceLink || linkLine)), base.ranked) : null;
if (condensed) {
if (condensed.k < tags.length) notes.push(`Dropped ${tags.length - condensed.k} hashtag(s) to make room for the text.`);
tags.splice(condensed.k);
if (sourceLink) {
linkLine = sourceLink;
notes.push(`Linked the lead point's source (${sourceLink}) because no link was given.`);
}
text = assemble(condensed.body, tags);
notes.push(`The full text is over the ${rule.limit} ${rule.method === "utf8_bytes" ? "byte" : "character"} limit, so this variant uses ${condensed.used} of ${pts.length} point(s)${base.ranked ? " (best supported first)" : ""} as whole sentences and leaves out the introduction; nothing in it refers to the parts left out.`);
} else {
// 2. Shorten text: the lead point alone (when points are known) or the whole body.
let done = false;
const src = pts.length ? pts[0].text : body;
if (sourceLink) linkLine = sourceLink;
const bodyLen = graphemes(src).length;
for (let k = tags.length; k >= 0 && !done; k--) {
const t = tags.slice(0, k);
const r = fitBody(src, (b) => fits(assemble(b, t)));
if (r && (graphemes(r.text).length >= Math.min(60, bodyLen) || k === 0)) {
if (k < tags.length) notes.push(`Dropped ${tags.length - k} hashtag(s) to make room for the text.`);
tags.splice(k);
text = assemble(r.text, tags);
truncated = r.truncated || src !== body;
done = true;
}
}
if (truncated) notes.push(`Body shortened to fit the ${rule.limit} ${rule.method === "utf8_bytes" ? "byte" : "character"} limit${pts.length > 1 ? " (only the lead point is used)" : ""}; review the cut before approving.`);
}
}
const length = measure(text, rule.method);
const post = { platform, text, hashtags: tags, length, limit: rule.limit, length_method: rule.method, within_limit: length <= rule.limit, truncated, notes };
if (!post.within_limit) notes.push(`Still ${length - rule.limit} over the limit (call to action and link alone are too long). Shorten them before approving.`);
if (base.account) post.account = base.account;
if (base.link) {
post.link = base.link;
post.link_in_text = Boolean(linkLine);
}
if (platform === "youtube") {
let title = cleanText(base.title ?? base.paragraphs[0]?.split(/(?<=[.!?])\s/)[0] ?? "").replace(/\s+/g, " ");
if (/[<>]/.test(title)) title = stripAngles(title);
const tg = graphemes(title);
if (tg.length > rule.titleLimit) {
const r = fitBody(title, (s) => graphemes(s).length <= rule.titleLimit);
title = r ? r.text : tg.slice(0, rule.titleLimit).join("");
notes.push(`Title shortened to ${rule.titleLimit} characters.`);
}
if (!title) notes.push("No title: pass title (or a script title) before publishing to YouTube.");
post.title = title;
post.title_length = graphemes(title).length;
post.title_limit = rule.titleLimit;
post.within_limit = post.within_limit && post.title_length > 0 && post.title_length <= rule.titleLimit;
}
if (platform === "x" && /\p{Script=Han}|\p{Script=Hiragana}|\p{Script=Katakana}|\p{Script=Hangul}/u.test(text)) notes.push("CJK characters count double on X.");
return post;
}
// ------------------------------------------------------------------------------------------------
// LinkedIn "little text" format for the Posts API commentary field
// ------------------------------------------------------------------------------------------------
const LITTLE_RESERVED = /[|{}@[\]()<>#\\*_~]/g;
/** Escapes reserved characters and turns #tags into LinkedIn hashtag templates. */
export function linkedinLittleText(text) {
const out = [];
let last = 0;
const re = /(^|\s)#([\p{L}\p{N}]+)(?=$|[\s.,!?;:])/gu;
for (const m of text.matchAll(re)) {
const start = m.index + m[1].length;
out.push(text.slice(last, start).replace(LITTLE_RESERVED, (c) => `\\${c}`));
out.push(`{hashtag|\\#|${m[2]}}`);
last = start + 1 + m[2].length;
}
out.push(text.slice(last).replace(LITTLE_RESERVED, (c) => `\\${c}`));
return out.join("");
}