@teleporthq/teleport-project-generator-next 0.45.21 → 0.45.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/__tests__/code-copy-runtime.test.ts +31 -24
- package/__tests__/forum-files-route.test.ts +147 -0
- package/__tests__/forum-markdown.test.ts +136 -0
- package/__tests__/forum-page-data.test.ts +1329 -0
- package/__tests__/forum-project-plugin.test.ts +789 -0
- package/__tests__/forum-replies-route.test.ts +82 -0
- package/__tests__/forum-topics-only-end2end.test.ts +124 -0
- package/__tests__/i18n-app-runtime.test.ts +187 -0
- package/__tests__/page-revalidate-plugin.test.ts +111 -0
- package/__tests__/rich-text-editor-frame.test.ts +25 -0
- package/dist/cjs/forum/files-route.d.ts +26 -0
- package/dist/cjs/forum/files-route.d.ts.map +1 -0
- package/dist/cjs/forum/files-route.js +42 -0
- package/dist/cjs/forum/files-route.js.map +1 -0
- package/dist/cjs/forum/markdown-source.d.ts +17 -0
- package/dist/cjs/forum/markdown-source.d.ts.map +1 -0
- package/dist/cjs/forum/markdown-source.js +23 -0
- package/dist/cjs/forum/markdown-source.js.map +1 -0
- package/dist/cjs/forum/notifications-route.d.ts +17 -0
- package/dist/cjs/forum/notifications-route.d.ts.map +1 -0
- package/dist/cjs/forum/notifications-route.js +30 -0
- package/dist/cjs/forum/notifications-route.js.map +1 -0
- package/dist/cjs/forum/page-data-source.d.ts +58 -0
- package/dist/cjs/forum/page-data-source.d.ts.map +1 -0
- package/dist/cjs/forum/page-data-source.js +168 -0
- package/dist/cjs/forum/page-data-source.js.map +1 -0
- package/dist/cjs/forum/page-rewrite.d.ts +50 -0
- package/dist/cjs/forum/page-rewrite.d.ts.map +1 -0
- package/dist/cjs/forum/page-rewrite.js +473 -0
- package/dist/cjs/forum/page-rewrite.js.map +1 -0
- package/dist/cjs/forum/project-plugin.d.ts +34 -0
- package/dist/cjs/forum/project-plugin.d.ts.map +1 -0
- package/dist/cjs/forum/project-plugin.js +272 -0
- package/dist/cjs/forum/project-plugin.js.map +1 -0
- package/dist/cjs/forum/replies-route.d.ts +21 -0
- package/dist/cjs/forum/replies-route.d.ts.map +1 -0
- package/dist/cjs/forum/replies-route.js +33 -0
- package/dist/cjs/forum/replies-route.js.map +1 -0
- package/dist/cjs/forum/seo.d.ts +29 -0
- package/dist/cjs/forum/seo.d.ts.map +1 -0
- package/dist/cjs/forum/seo.js +61 -0
- package/dist/cjs/forum/seo.js.map +1 -0
- package/dist/cjs/forum/settings.d.ts +97 -0
- package/dist/cjs/forum/settings.d.ts.map +1 -0
- package/dist/cjs/forum/settings.js +162 -0
- package/dist/cjs/forum/settings.js.map +1 -0
- package/dist/cjs/index.d.ts +1 -0
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +87 -80
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/instant-search/sections.d.ts.map +1 -1
- package/dist/cjs/instant-search/sections.js +18 -0
- package/dist/cjs/instant-search/sections.js.map +1 -1
- package/dist/cjs/instant-search/settings.d.ts +1 -1
- package/dist/cjs/instant-search/settings.d.ts.map +1 -1
- package/dist/cjs/instant-search/settings.js +2 -0
- package/dist/cjs/instant-search/settings.js.map +1 -1
- package/dist/cjs/internationalization/app-i18n-runtime.d.ts +39 -0
- package/dist/cjs/internationalization/app-i18n-runtime.d.ts.map +1 -0
- package/dist/cjs/internationalization/app-i18n-runtime.js +126 -0
- package/dist/cjs/internationalization/app-i18n-runtime.js.map +1 -0
- package/dist/cjs/internationalization/project.d.ts.map +1 -1
- package/dist/cjs/internationalization/project.js +6 -0
- package/dist/cjs/internationalization/project.js.map +1 -1
- package/dist/cjs/page-revalidate/project-plugin.d.ts.map +1 -1
- package/dist/cjs/page-revalidate/project-plugin.js +5 -1
- package/dist/cjs/page-revalidate/project-plugin.js.map +1 -1
- package/dist/cjs/rich-text-editor/content-support-source.d.ts +2 -1
- package/dist/cjs/rich-text-editor/content-support-source.d.ts.map +1 -1
- package/dist/cjs/rich-text-editor/content-support-source.js +9 -2
- package/dist/cjs/rich-text-editor/content-support-source.js.map +1 -1
- package/dist/cjs/tsconfig.tsbuildinfo +1 -1
- package/dist/esm/forum/files-route.d.ts +26 -0
- package/dist/esm/forum/files-route.d.ts.map +1 -0
- package/dist/esm/forum/files-route.js +38 -0
- package/dist/esm/forum/files-route.js.map +1 -0
- package/dist/esm/forum/markdown-source.d.ts +17 -0
- package/dist/esm/forum/markdown-source.d.ts.map +1 -0
- package/dist/esm/forum/markdown-source.js +19 -0
- package/dist/esm/forum/markdown-source.js.map +1 -0
- package/dist/esm/forum/notifications-route.d.ts +17 -0
- package/dist/esm/forum/notifications-route.d.ts.map +1 -0
- package/dist/esm/forum/notifications-route.js +26 -0
- package/dist/esm/forum/notifications-route.js.map +1 -0
- package/dist/esm/forum/page-data-source.d.ts +58 -0
- package/dist/esm/forum/page-data-source.d.ts.map +1 -0
- package/dist/esm/forum/page-data-source.js +164 -0
- package/dist/esm/forum/page-data-source.js.map +1 -0
- package/dist/esm/forum/page-rewrite.d.ts +50 -0
- package/dist/esm/forum/page-rewrite.d.ts.map +1 -0
- package/dist/esm/forum/page-rewrite.js +446 -0
- package/dist/esm/forum/page-rewrite.js.map +1 -0
- package/dist/esm/forum/project-plugin.d.ts +34 -0
- package/dist/esm/forum/project-plugin.d.ts.map +1 -0
- package/dist/esm/forum/project-plugin.js +269 -0
- package/dist/esm/forum/project-plugin.js.map +1 -0
- package/dist/esm/forum/replies-route.d.ts +21 -0
- package/dist/esm/forum/replies-route.d.ts.map +1 -0
- package/dist/esm/forum/replies-route.js +29 -0
- package/dist/esm/forum/replies-route.js.map +1 -0
- package/dist/esm/forum/seo.d.ts +29 -0
- package/dist/esm/forum/seo.d.ts.map +1 -0
- package/dist/esm/forum/seo.js +56 -0
- package/dist/esm/forum/seo.js.map +1 -0
- package/dist/esm/forum/settings.d.ts +97 -0
- package/dist/esm/forum/settings.d.ts.map +1 -0
- package/dist/esm/forum/settings.js +158 -0
- package/dist/esm/forum/settings.js.map +1 -0
- package/dist/esm/index.d.ts +1 -0
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +6 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/instant-search/sections.d.ts.map +1 -1
- package/dist/esm/instant-search/sections.js +18 -0
- package/dist/esm/instant-search/sections.js.map +1 -1
- package/dist/esm/instant-search/settings.d.ts +1 -1
- package/dist/esm/instant-search/settings.d.ts.map +1 -1
- package/dist/esm/instant-search/settings.js +2 -0
- package/dist/esm/instant-search/settings.js.map +1 -1
- package/dist/esm/internationalization/app-i18n-runtime.d.ts +39 -0
- package/dist/esm/internationalization/app-i18n-runtime.d.ts.map +1 -0
- package/dist/esm/internationalization/app-i18n-runtime.js +120 -0
- package/dist/esm/internationalization/app-i18n-runtime.js.map +1 -0
- package/dist/esm/internationalization/project.d.ts.map +1 -1
- package/dist/esm/internationalization/project.js +6 -0
- package/dist/esm/internationalization/project.js.map +1 -1
- package/dist/esm/page-revalidate/project-plugin.d.ts.map +1 -1
- package/dist/esm/page-revalidate/project-plugin.js +5 -1
- package/dist/esm/page-revalidate/project-plugin.js.map +1 -1
- package/dist/esm/rich-text-editor/content-support-source.d.ts +2 -1
- package/dist/esm/rich-text-editor/content-support-source.d.ts.map +1 -1
- package/dist/esm/rich-text-editor/content-support-source.js +9 -2
- package/dist/esm/rich-text-editor/content-support-source.js.map +1 -1
- package/dist/esm/tsconfig.tsbuildinfo +1 -1
- package/package.json +19 -19
- package/src/forum/files-route.ts +133 -0
- package/src/forum/markdown-source.ts +177 -0
- package/src/forum/notifications-route.ts +87 -0
- package/src/forum/page-data-source.ts +810 -0
- package/src/forum/page-rewrite.ts +567 -0
- package/src/forum/project-plugin.ts +328 -0
- package/src/forum/replies-route.ts +91 -0
- package/src/forum/seo.ts +245 -0
- package/src/forum/settings.ts +261 -0
- package/src/index.ts +6 -0
- package/src/instant-search/sections.ts +20 -0
- package/src/instant-search/settings.ts +2 -0
- package/src/internationalization/app-i18n-runtime.ts +165 -0
- package/src/internationalization/project.ts +7 -0
- package/src/page-revalidate/project-plugin.ts +5 -1
- package/src/rich-text-editor/content-support-source.ts +14 -2
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildForumMarkdownSource = exports.FORUM_MARKDOWN_MODULE_NAME = exports.FORUM_MARKDOWN_MODULE_PATH = void 0;
|
|
4
|
+
var source_literals_1 = require("../pwa/source-literals");
|
|
5
|
+
exports.FORUM_MARKDOWN_MODULE_PATH = ['utils'];
|
|
6
|
+
exports.FORUM_MARKDOWN_MODULE_NAME = 'forum-markdown';
|
|
7
|
+
/**
|
|
8
|
+
* `utils/forum-markdown.js`: the allow-list renderer every piece of member
|
|
9
|
+
* content goes through (plan 7.5). The whole text is HTML-escaped FIRST, then
|
|
10
|
+
* the Markdown subset is recognised on the escaped text, so no character a
|
|
11
|
+
* member typed ever reaches the page as markup: raw HTML renders as the text
|
|
12
|
+
* it is. Links are http(s) only and open in a new tab with
|
|
13
|
+
* `rel="nofollow ugc noopener"`; images only from `https://` or the project's
|
|
14
|
+
* own upload base; `@handle` is emphasised text in v1 (no profile link: the
|
|
15
|
+
* handle alone does not name the user id). Pure, CommonJS, no dependency —
|
|
16
|
+
* the data module and the composer preview require the same file.
|
|
17
|
+
*/
|
|
18
|
+
var buildForumMarkdownSource = function (options) {
|
|
19
|
+
if (options === void 0) { options = {}; }
|
|
20
|
+
return "'use strict';\n// Forum Markdown renderer \u2014 generated by TeleportHQ. Pure: no I/O, no DOM.\n// The project's upload base: baked when known, else the server's RUNTIME_STORAGE_URL\n// (a browser preview has neither and keeps the https-only rule).\nvar STORAGE_BASE = ".concat((0, source_literals_1.toJsLiteral)(options.storageBase || ''), " ||\n (typeof process !== 'undefined' && process.env && process.env.RUNTIME_STORAGE_URL ? String(process.env.RUNTIME_STORAGE_URL) : '');\nvar ESCAPES = { '&': '&', '<': '<', '>': '>', '\"': '"', \"'\": ''' };\nvar MAX_LENGTH = 40000;\n\nfunction escapeHtml(text) {\n return String(text == null ? '' : text).replace(/[&<>\"']/g, function (ch) { return ESCAPES[ch]; });\n}\n\n// A URL a link may point at: http(s) only, nothing that could leave the\n// attribute (the text is already escaped, so quotes are entities by now).\nfunction linkUrl(raw) {\n var url = String(raw || '').trim();\n return /^https?:\\/\\/[^\\s]+$/i.test(url) ? url : null;\n}\n\nfunction imageUrl(raw) {\n var url = String(raw || '').trim();\n if (!/^[^\\s]+$/.test(url)) return null;\n if (/^https:\\/\\//i.test(url)) return url;\n return STORAGE_BASE && url.indexOf(STORAGE_BASE) === 0 ? url : null;\n}\n\n// Inline marks on ONE escaped line. Code spans are lifted out first so their\n// content is never formatted, then put back as <code>.\nfunction inline(text) {\n var spans = [];\n var out = text.replace(/`([^`\\n]+)`/g, function (_m, code) {\n spans.push('<code>' + code + '</code>');\n return '\\u0000' + (spans.length - 1) + '\\u0000';\n });\n out = out.replace(/!\\[([^\\]]*)\\]\\(([^\\s()]+)\\)/g, function (_m, alt, url) {\n var src = imageUrl(url);\n return src ? '<img src=\"' + src + '\" alt=\"' + alt + '\" loading=\"lazy\" />' : alt;\n });\n out = out.replace(/\\[([^\\]]+)\\]\\(([^\\s()]+)\\)/g, function (_m, label, url) {\n var href = linkUrl(url);\n return href\n ? '<a href=\"' + href + '\" rel=\"nofollow ugc noopener\" target=\"_blank\">' + label + '</a>'\n : label;\n });\n // A bare address in the text is linked too; one already inside a tag is left.\n out = out.replace(/(^|[\\s(])(https?:\\/\\/[^\\s<)]+)/g, function (_m, lead, url) {\n return lead + '<a href=\"' + url + '\" rel=\"nofollow ugc noopener\" target=\"_blank\">' + url + '</a>';\n });\n out = out.replace(/\\*\\*([^*\\n]+)\\*\\*/g, '<strong>$1</strong>');\n out = out.replace(/(^|[^\\w*])\\*([^*\\n]+)\\*(?!\\w)/g, '$1<em>$2</em>');\n out = out.replace(/(^|[^\\w_])_([^_\\n]+)_(?!\\w)/g, '$1<em>$2</em>');\n out = out.replace(/~~([^~\\n]+)~~/g, '<s>$1</s>');\n out = out.replace(/(^|[^\\w@])@([a-z0-9_]{3,40})\\b/gi, '$1<em class=\"forum-mention\">@$2</em>');\n return out.replace(/\\u0000(\\d+)\\u0000/g, function (_m, index) { return spans[Number(index)]; });\n}\n\nfunction paragraph(lines) {\n return '<p>' + lines.map(inline).join('<br />') + '</p>';\n}\n\nvar LIST_ITEM = /^(\\s*)([-*]|\\d+[.)])\\s+(.*)$/;\n\n// A list of at most two levels: an item indented by two or more spaces under\n// another item nests; deeper indents are flattened into that level.\nfunction list(items) {\n var html = '';\n var open = null;\n var nested = [];\n var flushNested = function () {\n if (nested.length) html += list(nested);\n nested = [];\n };\n for (var i = 0; i < items.length; i++) {\n var item = items[i];\n if (item.depth > 0 && open) {\n nested.push({ depth: 0, ordered: item.ordered, text: item.text });\n continue;\n }\n if (open) { flushNested(); html += '</li>'; }\n if (!open || open !== (item.ordered ? 'ol' : 'ul')) {\n if (open) html += '</' + open + '>';\n open = item.ordered ? 'ol' : 'ul';\n html += '<' + open + '>';\n }\n html += '<li>' + inline(item.text);\n }\n if (open) { flushNested(); html += '</li></' + open + '>'; }\n return html;\n}\n\nfunction blocks(lines, depth) {\n var html = '';\n var i = 0;\n while (i < lines.length) {\n var line = lines[i];\n if (!line.trim()) { i++; continue; }\n var fence = /^```\\s*([a-z0-9+-]*)\\s*$/i.exec(line);\n if (fence) {\n var code = [];\n i++;\n while (i < lines.length && !/^```\\s*$/.test(lines[i])) code.push(lines[i++]);\n i++;\n html += '<pre><code' + (fence[1] ? ' class=\"language-' + fence[1] + '\"' : '') + '>' + code.join('\\n') + '</code></pre>';\n continue;\n }\n var heading = /^(##|###)\\s+(.+?)\\s*#*\\s*$/.exec(line);\n if (heading) {\n var level = heading[1].length;\n html += '<h' + level + '>' + inline(heading[2]) + '</h' + level + '>';\n i++;\n continue;\n }\n if (/^\\s*([-*_])(\\s*\\1){2,}\\s*$/.test(line)) { html += '<hr />'; i++; continue; }\n // \"> \" reads as \"> \" once escaped.\n if (/^>/.test(line) && depth < 2) {\n var quoted = [];\n while (i < lines.length && /^>/.test(lines[i])) quoted.push(lines[i++].replace(/^> ?/, ''));\n html += '<blockquote>' + blocks(quoted, depth + 1) + '</blockquote>';\n continue;\n }\n if (LIST_ITEM.test(line)) {\n var items = [];\n var match;\n while (i < lines.length && (match = LIST_ITEM.exec(lines[i]))) {\n items.push({ depth: match[1].length >= 2 ? 1 : 0, ordered: /\\d/.test(match[2]), text: match[3] });\n i++;\n }\n html += list(items);\n continue;\n }\n var para = [];\n while (i < lines.length && lines[i].trim() && !/^(```|##|>)/.test(lines[i]) && !LIST_ITEM.test(lines[i])) {\n para.push(lines[i++]);\n }\n html += paragraph(para);\n }\n return html;\n}\n\n// Markdown (member text) -> HTML made only of the tags above.\nfunction renderForumMarkdown(markdown) {\n var text = String(markdown == null ? '' : markdown).slice(0, MAX_LENGTH).replace(/\\r\\n?/g, '\\n');\n return blocks(escapeHtml(text).split('\\n'), 0);\n}\n\n// The words of a Markdown text, on one line, for search and excerpts.\nfunction forumPlainText(markdown) {\n var text = String(markdown == null ? '' : markdown).slice(0, MAX_LENGTH).replace(/\\r\\n?/g, '\\n');\n text = text.replace(/```[a-z0-9+-]*\\n?([\\s\\S]*?)```/gi, ' $1 ');\n text = text.replace(/!\\[([^\\]]*)\\]\\([^)]*\\)/g, '$1');\n text = text.replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, '$1');\n text = text.replace(/^\\s*(#{1,6}|>|>|[-*+]|\\d+[.)])\\s+/gm, '');\n text = text.replace(/^\\s*([-*_])(\\s*\\1){2,}\\s*$/gm, ' ');\n text = text.replace(/(\\*\\*|__|~~|\\*|_|`)/g, '');\n return text.replace(/<[^>]*>/g, ' ').replace(/\\s+/g, ' ').trim();\n}\n\nmodule.exports = { renderForumMarkdown: renderForumMarkdown, forumPlainText: forumPlainText, escapeHtml: escapeHtml };\n");
|
|
21
|
+
};
|
|
22
|
+
exports.buildForumMarkdownSource = buildForumMarkdownSource;
|
|
23
|
+
//# sourceMappingURL=markdown-source.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"markdown-source.js","sourceRoot":"","sources":["../../../src/forum/markdown-source.ts"],"names":[],"mappings":";;;AAAA,0DAAoD;AAEvC,QAAA,0BAA0B,GAAG,CAAC,OAAO,CAAC,CAAA;AACtC,QAAA,0BAA0B,GAAG,gBAAgB,CAAA;AAE1D;;;;;;;;;;GAUG;AACI,IAAM,wBAAwB,GAAG,UAAC,OAA6C;IAA7C,wBAAA,EAAA,YAA6C;IACpF,OAAA,wRAImB,IAAA,6BAAW,EAAC,OAAO,CAAC,WAAW,IAAI,EAAE,CAAC,4tMA2J1D;AA/JC,CA+JD,CAAA;AAhKY,QAAA,wBAAwB,4BAgKpC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export declare const FORUM_NOTIFICATIONS_ROUTE = "/api/plugins/forum/notifications";
|
|
2
|
+
/**
|
|
3
|
+
* `isSameOrigin(req)`: a write the forum's routes take only from the site's
|
|
4
|
+
* own pages (the browser's `Sec-Fetch-Site`, else the `Origin` against the host).
|
|
5
|
+
*/
|
|
6
|
+
export declare const FORUM_SAME_ORIGIN_SOURCE = "function isSameOrigin(req) {\n var site = req.headers['sec-fetch-site'];\n if (site) {\n return site === 'same-origin';\n }\n var origin = req.headers.origin;\n if (!origin) {\n return true;\n }\n try {\n return new URL(origin).host === req.headers.host;\n } catch (error) {\n return false;\n }\n}";
|
|
7
|
+
/**
|
|
8
|
+
* `pages/api/plugins/forum/notifications.js`: the bell. `GET` answers the
|
|
9
|
+
* signed-in member's latest notifications and their unread count; `POST`
|
|
10
|
+
* (`{ ids?: [] }`, same-origin JSON) marks them — or all of them — read.
|
|
11
|
+
* The member is the session cookie's, never a body value; a visitor without
|
|
12
|
+
* a session gets 401. 60 requests per 10 minutes per visitor.
|
|
13
|
+
*/
|
|
14
|
+
export declare const buildForumNotificationsRouteSource: (options?: {
|
|
15
|
+
withSessionRevocation?: boolean;
|
|
16
|
+
}) => string;
|
|
17
|
+
//# sourceMappingURL=notifications-route.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"notifications-route.d.ts","sourceRoot":"","sources":["../../../src/forum/notifications-route.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,yBAAyB,qCAAqC,CAAA;AAE3E;;;GAGG;AACH,eAAO,MAAM,wBAAwB,mUAcnC,CAAA;AAKF;;;;;;GAMG;AACH,eAAO,MAAM,kCAAkC,aACpC;IAAE,qBAAqB,CAAC,EAAE,OAAO,CAAA;CAAE,KAC3C,MA8CF,CAAA"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildForumNotificationsRouteSource = exports.FORUM_SAME_ORIGIN_SOURCE = exports.FORUM_NOTIFICATIONS_ROUTE = void 0;
|
|
4
|
+
var teleport_shared_1 = require("@teleporthq/teleport-shared");
|
|
5
|
+
var teleport_plugin_next_workflows_1 = require("@teleporthq/teleport-plugin-next-workflows");
|
|
6
|
+
var source_literals_1 = require("../pwa/source-literals");
|
|
7
|
+
var page_data_source_1 = require("./page-data-source");
|
|
8
|
+
var replies_route_1 = require("./replies-route");
|
|
9
|
+
exports.FORUM_NOTIFICATIONS_ROUTE = '/api/plugins/forum/notifications';
|
|
10
|
+
/**
|
|
11
|
+
* `isSameOrigin(req)`: a write the forum's routes take only from the site's
|
|
12
|
+
* own pages (the browser's `Sec-Fetch-Site`, else the `Origin` against the host).
|
|
13
|
+
*/
|
|
14
|
+
exports.FORUM_SAME_ORIGIN_SOURCE = "function isSameOrigin(req) {\n var site = req.headers['sec-fetch-site'];\n if (site) {\n return site === 'same-origin';\n }\n var origin = req.headers.origin;\n if (!origin) {\n return true;\n }\n try {\n return new URL(origin).host === req.headers.host;\n } catch (error) {\n return false;\n }\n}";
|
|
15
|
+
var DATA_MODULE_IMPORT = "".concat(replies_route_1.FORUM_ROUTE_ROOT, "/").concat(page_data_source_1.FORUM_PAGE_DATA_MODULE_PATH.join('/'), "/").concat(page_data_source_1.FORUM_PAGE_DATA_MODULE_NAME);
|
|
16
|
+
/**
|
|
17
|
+
* `pages/api/plugins/forum/notifications.js`: the bell. `GET` answers the
|
|
18
|
+
* signed-in member's latest notifications and their unread count; `POST`
|
|
19
|
+
* (`{ ids?: [] }`, same-origin JSON) marks them — or all of them — read.
|
|
20
|
+
* The member is the session cookie's, never a body value; a visitor without
|
|
21
|
+
* a session gets 401. 60 requests per 10 minutes per visitor.
|
|
22
|
+
*/
|
|
23
|
+
var buildForumNotificationsRouteSource = function (options) {
|
|
24
|
+
if (options === void 0) { options = {}; }
|
|
25
|
+
return "var forum = require(".concat((0, source_literals_1.toJsLiteral)(DATA_MODULE_IMPORT), ");\nvar security = require(").concat((0, source_literals_1.toJsLiteral)((0, teleport_plugin_next_workflows_1.securityRuntimeSpecifier)(replies_route_1.FORUM_ROUTE_ROOT)), ");\n\n").concat(teleport_shared_1.SessionCookieResolver.generateCommonJsSessionTokenResolverCode(replies_route_1.FORUM_ROUTE_ROOT, {
|
|
26
|
+
withRevocation: options.withSessionRevocation !== false,
|
|
27
|
+
}), "\n\nvar RATE_LIMIT = { scope: 'forum-notifications', limit: 60, windowSeconds: 600 };\n\n").concat(exports.FORUM_SAME_ORIGIN_SOURCE, "\n\nexport default async function handler(req, res) {\n res.setHeader('Cache-Control', 'private, no-store');\n if (req.method !== 'GET' && req.method !== 'POST') {\n res.setHeader('Allow', 'GET, POST');\n return res.status(405).json({ success: false, error: 'Method not allowed' });\n }\n if (!(await security.rateLimitRequest(req, res, RATE_LIMIT))) {\n return;\n }\n var session = null;\n try {\n session = await __tqSessionToken(req);\n } catch (error) {\n session = null;\n }\n if (!session || !(session.id || session.sub)) {\n return res.status(401).json({ success: false, error: 'Sign in to see your notifications.' });\n }\n try {\n if (req.method === 'GET') {\n var limit = parseInt(String(Array.isArray(req.query.limit) ? req.query.limit[0] : req.query.limit || ''), 10);\n var page = await forum.loadNotifications(session, { limit: limit });\n return res.status(200).json({ success: true, items: page.items, unreadCount: page.unreadCount });\n }\n if (!isSameOrigin(req)) {\n return res.status(403).json({ success: false, error: 'Forbidden' });\n }\n var body = req.body && typeof req.body === 'object' ? req.body : {};\n var marked = await forum.markNotificationsRead(session, Array.isArray(body.ids) ? body.ids : null);\n return res.status(200).json({ success: true, marked: marked });\n } catch (error) {\n console.error('[forum] notifications failed:', error && error.message);\n return res.status(500).json({ success: false, error: 'Your notifications could not be loaded.' });\n }\n}\n");
|
|
28
|
+
};
|
|
29
|
+
exports.buildForumNotificationsRouteSource = buildForumNotificationsRouteSource;
|
|
30
|
+
//# sourceMappingURL=notifications-route.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"notifications-route.js","sourceRoot":"","sources":["../../../src/forum/notifications-route.ts"],"names":[],"mappings":";;;AAAA,+DAAmE;AACnE,6FAAqF;AACrF,0DAAoD;AACpD,uDAA6F;AAC7F,iDAAkD;AAErC,QAAA,yBAAyB,GAAG,kCAAkC,CAAA;AAE3E;;;GAGG;AACU,QAAA,wBAAwB,GAAG,gUActC,CAAA;AACF,IAAM,kBAAkB,GAAG,UAAG,gCAAgB,cAAI,8CAA2B,CAAC,IAAI,CAChF,GAAG,CACJ,cAAI,8CAA2B,CAAE,CAAA;AAElC;;;;;;GAMG;AACI,IAAM,kCAAkC,GAAG,UAChD,OAAiD;IAAjD,wBAAA,EAAA,YAAiD;IACtC,OAAA,8BAAuB,IAAA,6BAAW,EAAC,kBAAkB,CAAC,wCAC1C,IAAA,6BAAW,EAAC,IAAA,yDAAwB,EAAC,gCAAgB,CAAC,CAAC,mBAE9E,uCAAqB,CAAC,wCAAwC,CAAC,gCAAgB,EAAE;QACjF,cAAc,EAAE,OAAO,CAAC,qBAAqB,KAAK,KAAK;KACxD,CAAC,sGAIA,gCAAwB,ijDAqCzB;AA9CY,CA8CZ,CAAA;AAhDY,QAAA,kCAAkC,sCAgD9C"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { ForumConfig } from './settings';
|
|
2
|
+
export declare const FORUM_PAGE_DATA_MODULE_PATH: string[];
|
|
3
|
+
export declare const FORUM_PAGE_DATA_MODULE_NAME = "forum-page-data";
|
|
4
|
+
/** How many replies one read of the tree or of `/api/plugins/forum/replies` takes. */
|
|
5
|
+
export declare const FORUM_REPLIES_PAGE = 50;
|
|
6
|
+
/**
|
|
7
|
+
* `utils/forum-page-data.js` (plan D14b): what the topic, community, Manage
|
|
8
|
+
* and New topic pages render per request, and what the replies and
|
|
9
|
+
* notifications routes answer. Parameterised SQL only, over the forum tables,
|
|
10
|
+
* through the project's own database connection (the one the data API opens:
|
|
11
|
+
* `TELEPORT_DB_*`).
|
|
12
|
+
*
|
|
13
|
+
* Rules, applied here and nowhere else:
|
|
14
|
+
* - a topic or reply is served when `published`, or to a viewer who moderates
|
|
15
|
+
* it or wrote it (their own pending post);
|
|
16
|
+
* - a private community is read by its active members and moderators only:
|
|
17
|
+
* to anyone else its topics answer `null` (the page answers `notFound`) and
|
|
18
|
+
* its own page only the About side (`viewer.can_read` false, no topics);
|
|
19
|
+
* - a community that is not `active` is answered to who moderates it, and one
|
|
20
|
+
* still `pending` (waiting for approval) to its creator too
|
|
21
|
+
* (`viewer.is_creator`); its topics are in no public list;
|
|
22
|
+
* - Manage is served to who moderates the community, New topic to a signed-in
|
|
23
|
+
* viewer who can read it (`loadCommunityGate`): `null` for anyone else;
|
|
24
|
+
* - the reply tree is at most three levels from its root, in `path` order,
|
|
25
|
+
* the accepted answer first under `best`; a removed reply keeps its place
|
|
26
|
+
* with its body masked so the thread under it still reads. With flat
|
|
27
|
+
* replies (`SETTINGS.replyNesting` is `flat`) it is one level: every reply
|
|
28
|
+
* of the topic in the chosen order, an old reply to a reply among them;
|
|
29
|
+
* - without votes (`SETTINGS.votes` is `off`) there is no score, so no `top`
|
|
30
|
+
* order of a community's topics;
|
|
31
|
+
* - the viewer block says what the pages gate on: `signed_in`, `my_vote` (by
|
|
32
|
+
* target id), `my_membership`, `my_role`, `can_moderate`, `can_read`,
|
|
33
|
+
* `can_post` (anyone signed in where the community is public, an active
|
|
34
|
+
* member elsewhere; where only moderators post, one who moderates),
|
|
35
|
+
* `can_reply` (the reply statement's rule: as `can_post`, but only a
|
|
36
|
+
* `moderators` posting rule keeps members out — an announcements community
|
|
37
|
+
* takes its members' replies), and on
|
|
38
|
+
* a topic `is_subscribed`, `is_author`, `can_accept`, `can_edit` (every
|
|
39
|
+
* reply carries its own `can_edit`): as the edit statement decides it,
|
|
40
|
+
* never banned nor a removed post, and who moderates it or its author within
|
|
41
|
+
* `SETTINGS.editWindowMinutes` of writing it (0: always);
|
|
42
|
+
* - the shapes the pages bind are listed in the editor's
|
|
43
|
+
* `features/forum/constants/forum-shapes.ts`: `tags` as `[{ name }]`,
|
|
44
|
+
* `attachments` as `[{ url }]`, `body_html`, `community_name`,
|
|
45
|
+
* `community_url`, `accepted_reply`, `is_mine`, `thread_url`, `rules_text`;
|
|
46
|
+
* - author profiles carry public columns only;
|
|
47
|
+
* - a forum without communities (`SETTINGS.structure` is `topics`) keeps every
|
|
48
|
+
* topic in one community of its own. It is read for the rights like any
|
|
49
|
+
* other and never answered: no topic names it or links to it, the composer's
|
|
50
|
+
* gate answers the viewer alone, and it has no page and no place in the
|
|
51
|
+
* public index.
|
|
52
|
+
*
|
|
53
|
+
* Every row goes out JSON-plain (dates as ISO strings): Next.js props.
|
|
54
|
+
*/
|
|
55
|
+
export declare const buildForumPageDataSource: (config: ForumConfig, options?: {
|
|
56
|
+
withSessionRevocation?: boolean;
|
|
57
|
+
}) => string;
|
|
58
|
+
//# sourceMappingURL=page-data-source.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"page-data-source.d.ts","sourceRoot":"","sources":["../../../src/forum/page-data-source.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,WAAW,EAAgB,MAAM,YAAY,CAAA;AAGtD,eAAO,MAAM,2BAA2B,UAAY,CAAA;AACpD,eAAO,MAAM,2BAA2B,oBAAoB,CAAA;AAE5D,sFAAsF;AACtF,eAAO,MAAM,kBAAkB,KAAK,CAAA;AA4FpC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDG;AACH,eAAO,MAAM,wBAAwB,WAC3B,WAAW,YACV;IAAE,qBAAqB,CAAC,EAAE,OAAO,CAAA;CAAE,KAC3C,MA8oBF,CAAA"}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildForumPageDataSource = exports.FORUM_REPLIES_PAGE = exports.FORUM_PAGE_DATA_MODULE_NAME = exports.FORUM_PAGE_DATA_MODULE_PATH = void 0;
|
|
4
|
+
var teleport_shared_1 = require("@teleporthq/teleport-shared");
|
|
5
|
+
var teleport_plugin_next_workflows_1 = require("@teleporthq/teleport-plugin-next-workflows");
|
|
6
|
+
var source_literals_1 = require("../pwa/source-literals");
|
|
7
|
+
var seo_1 = require("./seo");
|
|
8
|
+
var settings_1 = require("./settings");
|
|
9
|
+
var markdown_source_1 = require("./markdown-source");
|
|
10
|
+
exports.FORUM_PAGE_DATA_MODULE_PATH = ['utils'];
|
|
11
|
+
exports.FORUM_PAGE_DATA_MODULE_NAME = 'forum-page-data';
|
|
12
|
+
/** How many replies one read of the tree or of `/api/plugins/forum/replies` takes. */
|
|
13
|
+
exports.FORUM_REPLIES_PAGE = 50;
|
|
14
|
+
var TOPIC_COLUMNS = [
|
|
15
|
+
'id',
|
|
16
|
+
'community_id',
|
|
17
|
+
'community_slug',
|
|
18
|
+
'community_name',
|
|
19
|
+
'community_visibility',
|
|
20
|
+
'author_id',
|
|
21
|
+
'author_handle',
|
|
22
|
+
'author_name',
|
|
23
|
+
'author_avatar',
|
|
24
|
+
'title',
|
|
25
|
+
'slug',
|
|
26
|
+
'body',
|
|
27
|
+
'body_text',
|
|
28
|
+
'tags',
|
|
29
|
+
'attachments',
|
|
30
|
+
'status',
|
|
31
|
+
'is_pinned',
|
|
32
|
+
'is_locked',
|
|
33
|
+
'accepted_reply_id',
|
|
34
|
+
'score',
|
|
35
|
+
'upvotes',
|
|
36
|
+
'downvotes',
|
|
37
|
+
'reply_count',
|
|
38
|
+
'view_count',
|
|
39
|
+
'last_activity_at',
|
|
40
|
+
'edited_at',
|
|
41
|
+
'removed_reason',
|
|
42
|
+
'created_at',
|
|
43
|
+
'updated_at',
|
|
44
|
+
];
|
|
45
|
+
var REPLY_COLUMNS = [
|
|
46
|
+
'id',
|
|
47
|
+
'topic_id',
|
|
48
|
+
'community_id',
|
|
49
|
+
'parent_id',
|
|
50
|
+
'depth',
|
|
51
|
+
'path',
|
|
52
|
+
'author_id',
|
|
53
|
+
'author_handle',
|
|
54
|
+
'author_name',
|
|
55
|
+
'author_avatar',
|
|
56
|
+
'body',
|
|
57
|
+
'body_text',
|
|
58
|
+
'attachments',
|
|
59
|
+
'status',
|
|
60
|
+
'score',
|
|
61
|
+
'upvotes',
|
|
62
|
+
'downvotes',
|
|
63
|
+
'is_accepted',
|
|
64
|
+
'quote_of',
|
|
65
|
+
'edited_at',
|
|
66
|
+
'removed_reason',
|
|
67
|
+
'created_at',
|
|
68
|
+
'updated_at',
|
|
69
|
+
];
|
|
70
|
+
var COMMUNITY_COLUMNS = [
|
|
71
|
+
'id',
|
|
72
|
+
'slug',
|
|
73
|
+
'name',
|
|
74
|
+
'description',
|
|
75
|
+
'rules',
|
|
76
|
+
'icon_url',
|
|
77
|
+
'banner_url',
|
|
78
|
+
'kind',
|
|
79
|
+
'visibility',
|
|
80
|
+
'posting',
|
|
81
|
+
'status',
|
|
82
|
+
'created_by',
|
|
83
|
+
'member_count',
|
|
84
|
+
'topic_count',
|
|
85
|
+
'last_activity_at',
|
|
86
|
+
'is_featured',
|
|
87
|
+
'sort_order',
|
|
88
|
+
'created_at',
|
|
89
|
+
'updated_at',
|
|
90
|
+
];
|
|
91
|
+
/** The public columns of a member's forum profile: never an e-mail, never a note. */
|
|
92
|
+
var PROFILE_COLUMNS = [
|
|
93
|
+
'user_id',
|
|
94
|
+
'handle',
|
|
95
|
+
'display_name',
|
|
96
|
+
'avatar_url',
|
|
97
|
+
'reputation',
|
|
98
|
+
'badges',
|
|
99
|
+
'role',
|
|
100
|
+
];
|
|
101
|
+
var columns = function (alias, names) {
|
|
102
|
+
return names.map(function (name) { return "".concat(alias, ".").concat(name); }).join(', ');
|
|
103
|
+
};
|
|
104
|
+
/**
|
|
105
|
+
* `utils/forum-page-data.js` (plan D14b): what the topic, community, Manage
|
|
106
|
+
* and New topic pages render per request, and what the replies and
|
|
107
|
+
* notifications routes answer. Parameterised SQL only, over the forum tables,
|
|
108
|
+
* through the project's own database connection (the one the data API opens:
|
|
109
|
+
* `TELEPORT_DB_*`).
|
|
110
|
+
*
|
|
111
|
+
* Rules, applied here and nowhere else:
|
|
112
|
+
* - a topic or reply is served when `published`, or to a viewer who moderates
|
|
113
|
+
* it or wrote it (their own pending post);
|
|
114
|
+
* - a private community is read by its active members and moderators only:
|
|
115
|
+
* to anyone else its topics answer `null` (the page answers `notFound`) and
|
|
116
|
+
* its own page only the About side (`viewer.can_read` false, no topics);
|
|
117
|
+
* - a community that is not `active` is answered to who moderates it, and one
|
|
118
|
+
* still `pending` (waiting for approval) to its creator too
|
|
119
|
+
* (`viewer.is_creator`); its topics are in no public list;
|
|
120
|
+
* - Manage is served to who moderates the community, New topic to a signed-in
|
|
121
|
+
* viewer who can read it (`loadCommunityGate`): `null` for anyone else;
|
|
122
|
+
* - the reply tree is at most three levels from its root, in `path` order,
|
|
123
|
+
* the accepted answer first under `best`; a removed reply keeps its place
|
|
124
|
+
* with its body masked so the thread under it still reads. With flat
|
|
125
|
+
* replies (`SETTINGS.replyNesting` is `flat`) it is one level: every reply
|
|
126
|
+
* of the topic in the chosen order, an old reply to a reply among them;
|
|
127
|
+
* - without votes (`SETTINGS.votes` is `off`) there is no score, so no `top`
|
|
128
|
+
* order of a community's topics;
|
|
129
|
+
* - the viewer block says what the pages gate on: `signed_in`, `my_vote` (by
|
|
130
|
+
* target id), `my_membership`, `my_role`, `can_moderate`, `can_read`,
|
|
131
|
+
* `can_post` (anyone signed in where the community is public, an active
|
|
132
|
+
* member elsewhere; where only moderators post, one who moderates),
|
|
133
|
+
* `can_reply` (the reply statement's rule: as `can_post`, but only a
|
|
134
|
+
* `moderators` posting rule keeps members out — an announcements community
|
|
135
|
+
* takes its members' replies), and on
|
|
136
|
+
* a topic `is_subscribed`, `is_author`, `can_accept`, `can_edit` (every
|
|
137
|
+
* reply carries its own `can_edit`): as the edit statement decides it,
|
|
138
|
+
* never banned nor a removed post, and who moderates it or its author within
|
|
139
|
+
* `SETTINGS.editWindowMinutes` of writing it (0: always);
|
|
140
|
+
* - the shapes the pages bind are listed in the editor's
|
|
141
|
+
* `features/forum/constants/forum-shapes.ts`: `tags` as `[{ name }]`,
|
|
142
|
+
* `attachments` as `[{ url }]`, `body_html`, `community_name`,
|
|
143
|
+
* `community_url`, `accepted_reply`, `is_mine`, `thread_url`, `rules_text`;
|
|
144
|
+
* - author profiles carry public columns only;
|
|
145
|
+
* - a forum without communities (`SETTINGS.structure` is `topics`) keeps every
|
|
146
|
+
* topic in one community of its own. It is read for the rights like any
|
|
147
|
+
* other and never answered: no topic names it or links to it, the composer's
|
|
148
|
+
* gate answers the viewer alone, and it has no page and no place in the
|
|
149
|
+
* public index.
|
|
150
|
+
*
|
|
151
|
+
* Every row goes out JSON-plain (dates as ISO strings): Next.js props.
|
|
152
|
+
*/
|
|
153
|
+
var buildForumPageDataSource = function (config, options) {
|
|
154
|
+
var _a, _b;
|
|
155
|
+
if (options === void 0) { options = {}; }
|
|
156
|
+
var settings = config.settings;
|
|
157
|
+
// Where the details pages are served (`forum-markers.ts` there: `/forum/t`, `/forum/c`);
|
|
158
|
+
// a forum without communities has no community page to link to.
|
|
159
|
+
var urls = {
|
|
160
|
+
topic: ((_a = config.routes.topic) === null || _a === void 0 ? void 0 : _a.staticBase) || '/forum/t',
|
|
161
|
+
community: settings.structure === 'communities' ? ((_b = config.routes.community) === null || _b === void 0 ? void 0 : _b.staticBase) || '/forum/c' : '',
|
|
162
|
+
};
|
|
163
|
+
return "'use strict';\n// Forum page data \u2014 generated by TeleportHQ. Server-side only.\n".concat((0, teleport_plugin_next_workflows_1.generateLazyPgClientCode)(), "\nvar markdown = require('./").concat(markdown_source_1.FORUM_MARKDOWN_MODULE_NAME, "');\n\n").concat(teleport_shared_1.SessionCookieResolver.generateCommonJsSessionTokenResolverCode('..', {
|
|
164
|
+
withRevocation: options.withSessionRevocation !== false,
|
|
165
|
+
}), "\n// The session cookie's token for a page or route, or null: who is asking.\nasync function readSession(req) {\n try {\n return (await __tqSessionToken(req)) || null;\n } catch (error) {\n return null;\n }\n}\n\nvar SETTINGS = ").concat((0, source_literals_1.toJsLiteral)(settings), ";\n// A forum without communities keeps its topics in one community of its own: read for the rights, never answered.\nvar HAS_COMMUNITIES = SETTINGS.structure !== 'topics';\n// Flat replies: one list of every reply, an old reply to a reply among them rather than lost.\nvar FLAT_REPLIES = SETTINGS.replyNesting === 'flat';\nvar T =").concat((0, source_literals_1.toJsLiteral)(settings_1.FORUM_TABLES), ";\nvar REPLIES_PAGE = ").concat(exports.FORUM_REPLIES_PAGE, ";\nvar TOPICS_PER_PAGE = ").concat(config.communityTopicsPerPage, ";\nvar MAX_DEPTH = 3;\nvar EXCERPT_LENGTH = 240;\nvar NOTIFICATIONS_PAGE = 30;\nvar URLS = ").concat((0, source_literals_1.toJsLiteral)(urls), ";\nvar STAFF_ROLES = ['admin'];\nvar TOPIC_SQL = ").concat((0, source_literals_1.toJsLiteral)(columns('t', TOPIC_COLUMNS)), ";\nvar REPLY_SQL = ").concat((0, source_literals_1.toJsLiteral)(columns('r', REPLY_COLUMNS)), ";\nvar COMMUNITY_SQL = ").concat((0, source_literals_1.toJsLiteral)(columns('c', COMMUNITY_COLUMNS)), ";\nvar PROFILE_SQL = ").concat((0, source_literals_1.toJsLiteral)(columns('p', PROFILE_COLUMNS)), ";\nvar REPLY_SORTS = {\n best: 'r.is_accepted DESC, r.score DESC, r.created_at ASC',\n new: 'r.created_at DESC',\n old: 'r.created_at ASC',\n};\nvar TOPIC_SORTS = {\n latest: 't.last_activity_at DESC NULLS LAST, t.created_at DESC',\n top: 't.score DESC, t.created_at DESC',\n new: 't.created_at DESC',\n unanswered: 't.reply_count ASC, t.created_at DESC',\n};\n\n").concat(seo_1.FORUM_SEO_RUNTIME, "\n// --- helpers ------------------------------------------------------------------\nfunction text(value) { return value === undefined || value === null ? '' : String(value); }\nfunction num(value) { var n = Number(value); return isFinite(n) ? n : 0; }\nfunction list(value) {\n if (Array.isArray(value)) return value;\n try { var parsed = JSON.parse(text(value) || '[]'); return Array.isArray(parsed) ? parsed : []; } catch (e) { return []; }\n}\n// A row as JSON-plain values: a Date becomes its ISO string, undefined null.\nfunction plain(row) {\n var out = {};\n Object.keys(row || {}).forEach(function (key) {\n var value = row[key];\n out[key] = value instanceof Date ? value.toISOString() : value === undefined ? null : value;\n });\n return out;\n}\nfunction stringList(value) { return list(value).filter(function (item) { return typeof item === 'string' && item !== ''; }); }\n// The rules column as the manage form's textarea shows it: one rule per line, \"title: text\".\nfunction rulesText(rules) {\n return list(rules).map(function (rule) {\n if (!rule || typeof rule !== 'object') return '';\n var title = text(rule.title).trim();\n var body = text(rule.text).trim();\n return title && body ? title + ': ' + body : title || body;\n }).filter(Boolean).join('\\n');\n}\nfunction threadUrlOf(topicSlug, replyId) {\n return URLS.topic + '/' + encodeURIComponent(text(topicSlug)) + '?reply=' + encodeURIComponent(text(replyId));\n}\nfunction communityUrlOf(communitySlug) {\n return URLS.community + '/' + encodeURIComponent(text(communitySlug));\n}\n// A topic's community as the pages bind it: its name (the topic's own column, the community's for a topic\n// written before the column existed) and where its page is. A forum without communities answers neither, nor its slug.\nfunction nameCommunity(post, community) {\n post.community_name = HAS_COMMUNITIES ? text(post.community_name) || text(community.name) : '';\n post.community_url = HAS_COMMUNITIES ? communityUrlOf(community.slug) : '';\n if (!HAS_COMMUNITIES) post.community_slug = '';\n}\nfunction excerptOf(bodyText) {\n var words = text(bodyText).replace(/\\s+/g, ' ').trim();\n return words.length > EXCERPT_LENGTH ? words.slice(0, EXCERPT_LENGTH).replace(/\\s+\\S*$/, '') + '\u2026' : words;\n}\nfunction sessionOf(session) {\n var token = session && typeof session === 'object' ? session : null;\n var id = token ? text(token.id || token.sub) : '';\n var role = token ? (typeof token.role === 'string' ? token.role : Array.isArray(token.roles) ? token.roles[0] : null) : null;\n return { id: id, role: role || null };\n}\nfunction sortKey(value, sorts, fallback) {\n var key = text(value);\n return Object.prototype.hasOwnProperty.call(sorts, key) ? key : fallback;\n}\n\n// One connection per call: opened, used for every read of the call, closed.\nasync function withClient(work) {\n var client = getClient();\n await client.connect();\n try {\n return await work(function query(sql, params) {\n return client.query(sql, params || []).then(function (result) { return result.rows || []; });\n });\n } finally {\n try { await client.end(); } catch (e) {}\n }\n}\n\n// --- the viewer ------------------------------------------------------------------\nasync function viewerOf(q, user, community) {\n var viewer = {\n signed_in: !!user.id,\n user_id: user.id || null,\n my_membership: null,\n my_role: null,\n can_moderate: false,\n can_delete: false,\n can_read: true,\n can_post: false,\n can_reply: false,\n is_author: false,\n can_accept: false,\n can_edit: false,\n my_vote: 0,\n profile_role: null,\n is_banned: false,\n };\n if (user.id) {\n var profiles = await q('SELECT ' + PROFILE_SQL + ' FROM ' + T.profiles + ' p WHERE p.user_id = $1 LIMIT 1', [user.id]);\n var profile = profiles[0] || null;\n viewer.profile_role = profile ? text(profile.role) || 'member' : null;\n viewer.is_banned = !!profile && profile.role === 'banned';\n var staff = STAFF_ROLES.indexOf(text(user.role)) !== -1 || viewer.profile_role === 'moderator';\n viewer.can_moderate = staff;\n if (community) {\n var memberships = await q(\n 'SELECT m.role, m.status FROM ' + T.memberships + ' m WHERE m.community_id = $1 AND m.user_id = $2 LIMIT 1',\n [community.id, user.id]\n );\n var membership = memberships[0] || null;\n viewer.my_membership = membership ? text(membership.status) : null;\n viewer.my_role = membership ? text(membership.role) : null;\n var active = !!membership && membership.status === 'active';\n viewer.can_moderate = staff || (active && (membership.role === 'moderator' || membership.role === 'owner'));\n // Who deletes the whole community, as its statement decides: the owner, a site moderator or an admin.\n viewer.can_delete = HAS_COMMUNITIES && (staff || (active && membership.role === 'owner'));\n }\n }\n if (community) {\n var member = viewer.my_membership === 'active';\n viewer.can_read = community.visibility !== 'private' || member || viewer.can_moderate;\n // Posting, as the statements decide it: anyone signed in where the community\n // is public (unless banned from it), its active members elsewhere; where only\n // moderators post (the community's setting, or an announcements community),\n // the ones who moderate it.\n var moderatorsOnly = community.posting === 'moderators' || community.kind === 'announcements';\n var admitted = member || (viewer.signed_in && community.visibility === 'public' && viewer.my_membership !== 'banned');\n viewer.can_post = admitted && !viewer.is_banned && community.status === 'active' && (!moderatorsOnly || viewer.can_moderate);\n viewer.can_reply = admitted && !viewer.is_banned && community.status === 'active' && (community.posting !== 'moderators' || viewer.can_moderate);\n }\n return viewer;\n}\n\n// Whether the viewer may edit this topic or reply, as the edit statement decides it: never banned, never a\n// removed post; who moderates it, or its author within SETTINGS.editWindowMinutes of writing it (0: always).\nfunction canEdit(viewer, row) {\n if (!viewer.signed_in || viewer.is_banned || row.status === 'removed') return false;\n if (viewer.can_moderate) return true;\n if (text(row.author_id) !== viewer.user_id) return false;\n return SETTINGS.editWindowMinutes === 0 || new Date(row.created_at).getTime() > Date.now() - SETTINGS.editWindowMinutes * 60000;\n}\n\nasync function votesOf(q, user, targetIds) {\n var votes = {};\n if (!user.id || !targetIds.length) return votes;\n var rows = await q('SELECT v.target_id, v.value FROM ' + T.votes + ' v WHERE v.user_id = $1 AND v.target_id = ANY($2::uuid[])', [user.id, targetIds]);\n rows.forEach(function (row) { votes[text(row.target_id)] = num(row.value); });\n return votes;\n}\n\n// Following is a topic's: joining a community is how it is followed.\nasync function followsTopic(q, user, topicId) {\n if (!user.id) return false;\n var rows = await q('SELECT 1 FROM ' + T.subscriptions + \" s WHERE s.user_id = $1 AND s.target_kind = 'topic' AND s.target_id = $2 LIMIT 1\", [user.id, topicId]);\n return rows.length > 0;\n}\n\n// { [targetId]: { [emoji]: { count, mine } } } for every target asked.\nasync function reactionsOf(q, user, targetIds) {\n var byTarget = {};\n targetIds.forEach(function (id) { byTarget[id] = {}; });\n if (!SETTINGS.reactions || !targetIds.length) return byTarget;\n var rows = await q(\n 'SELECT x.target_id, x.emoji, COUNT(*)::int AS count, BOOL_OR(x.user_id = $2) AS mine FROM ' + T.reactions +\n ' x WHERE x.target_id = ANY($1::uuid[]) GROUP BY x.target_id, x.emoji',\n [targetIds, user.id || '']\n );\n rows.forEach(function (row) {\n var id = text(row.target_id);\n if (!id || !row.emoji) return;\n if (!byTarget[id]) byTarget[id] = {};\n byTarget[id][text(row.emoji)] = { count: num(row.count), mine: !!row.mine && !!user.id };\n });\n return byTarget;\n}\n\nfunction authorOf(row) {\n return {\n id: text(row.author_id),\n handle: text(row.author_handle),\n name: text(row.author_name),\n avatar: row.author_avatar || null,\n reputation: SETTINGS.reputation ? num(row.author_reputation) : 0,\n badges: SETTINGS.badges ? list(row.author_badges) : [],\n initials: text(row.author_name).split(/\\s+/).map(function (w) { return w.charAt(0); }).join('').slice(0, 2).toUpperCase(),\n };\n}\n\n// The public shape of a topic or reply: Markdown rendered, JSON columns parsed,\n// a removed one masked so the thread keeps its place.\nfunction shapePost(row, votes, reactions) {\n var out = plain(row);\n delete out.author_badges;\n // The page's author line binds author_reputation as a number of its own.\n out.author_reputation = SETTINGS.reputation ? num(row.author_reputation) : 0;\n var removed = row.status === 'removed';\n out.body = removed ? '' : text(row.body);\n out.body_text = removed ? '[removed]' : text(row.body_text);\n out.body_html = removed ? '<p><em>[removed]</em></p>' : markdown.renderForumMarkdown(row.body);\n out.excerpt = excerptOf(out.body_text);\n // The pages bind tags as [{ name }] and attachments as [{ url }] (forum-shapes.ts there);\n // the plain lists stay beside them.\n out.tag_list = stringList(row.tags);\n out.tags = out.tag_list.map(function (name) { return { name: name }; });\n out.attachment_list = removed ? [] : stringList(row.attachments);\n out.attachments = out.attachment_list.map(function (url) { return { url: url }; });\n out.author = authorOf(row);\n out.my_vote = votes[text(row.id)] || 0;\n out.is_mine = false;\n out.reactions = reactions[text(row.id)] || {};\n // The same derived fields the feed transform gives a card (forum-feed.ts).\n out.is_solved = !!row.accepted_reply_id;\n out.is_answered = num(row.reply_count) > 0;\n out.author_initials = out.author.initials;\n return out;\n}\n\nfunction shapeCommunity(row) {\n var out = plain(row);\n out.rule_list = list(row.rules).filter(function (rule) { return rule && typeof rule === 'object'; });\n out.rules_text = rulesText(row.rules);\n out.excerpt = excerptOf(row.description);\n out.is_private = row.visibility === 'private';\n out.initials = text(row.name).split(/s+/).filter(Boolean).map(function (w) { return w.charAt(0); }).join('').slice(0, 2).toUpperCase();\n return out;\n}\n\n// --- replies -----------------------------------------------------------------------\nfunction postVisibility(alias, viewer, user, params) {\n // Published and removed rows for everyone (a removed one is masked); pending\n // ones for a moderator, and to their own author.\n if (viewer.can_moderate) return \"(\" + alias + \".status IN ('published', 'removed', 'pending'))\";\n if (user.id) {\n params.push(user.id);\n return \"(\" + alias + \".status IN ('published', 'removed') OR (\" + alias + \".status = 'pending' AND \" + alias + \".author_id = $\" + params.length + '))';\n }\n return \"(\" + alias + \".status IN ('published', 'removed'))\";\n}\n\n// A community's list: published topics, plus the pending ones a moderator\n// reviews and a member's own; removed topics are gone from every list.\nfunction topicVisibility(viewer, user, params) {\n if (viewer.can_moderate) return \"(t.status IN ('published', 'pending'))\";\n if (user.id) {\n params.push(user.id);\n return \"(t.status = 'published' OR (t.status = 'pending' AND t.author_id = $\" + params.length + '))';\n }\n return \"(t.status = 'published')\";\n}\n\nfunction nest(rows, rootDepth, sort) {\n var byId = {};\n var roots = [];\n rows.forEach(function (row) { row.children = []; byId[row.id] = row; });\n rows.forEach(function (row) {\n var parent = row.depth > rootDepth && row.parent_id ? byId[text(row.parent_id)] : null;\n if (parent) parent.children.push(row); else roots.push(row);\n });\n var compare = sort === 'new'\n ? function (a, b) { return text(b.created_at).localeCompare(text(a.created_at)); }\n : sort === 'old'\n ? function (a, b) { return text(a.created_at).localeCompare(text(b.created_at)); }\n : function (a, b) { return (b.is_accepted ? 1 : 0) - (a.is_accepted ? 1 : 0) || num(b.score) - num(a.score) || text(a.created_at).localeCompare(text(b.created_at)); };\n var sortTree = function (nodes) { nodes.sort(compare); nodes.forEach(function (node) { sortTree(node.children); }); };\n sortTree(roots);\n return roots;\n}\n\n// The tree under a topic (or under one reply, \"Continue this thread\"): the\n// first REPLIES_PAGE roots after the offset and what is under them. MAX_DEPTH\n// levels are drawn, the roots being the first; one level more is read, only so\n// a reply of the last drawn level can say its thread goes on. Flat replies are\n// one level: the first REPLIES_PAGE of every reply, whatever it answers (a\n// \"Continue this thread\" link reads the same list).\nasync function replyTree(q, user, viewer, topic, rootReplyId, sort, offset) {\n var rootDepth = -1;\n var params = [topic.id];\n var where = 'r.topic_id = $1';\n if (rootReplyId && !FLAT_REPLIES) {\n var roots = await q('SELECT r.id, r.depth, r.path FROM ' + T.replies + ' r WHERE r.topic_id = $1 AND r.id = $2 LIMIT 1', [topic.id, rootReplyId]);\n if (!roots.length) return { replies: [], hasMore: false, nextOffset: 0 };\n rootDepth = num(roots[0].depth);\n params.push(roots[0].id);\n where += ' AND r.parent_id = $2';\n } else if (!FLAT_REPLIES) {\n where += ' AND r.parent_id IS NULL';\n }\n where += ' AND ' + postVisibility('r', viewer, user, params);\n params.push(REPLIES_PAGE + 1, Math.max(0, num(offset)));\n var heads = await q(\n 'SELECT ' + REPLY_SQL + ', p.reputation AS author_reputation, p.badges AS author_badges FROM ' + T.replies + ' r LEFT JOIN ' + T.profiles +\n ' p ON p.user_id = r.author_id WHERE ' + where + ' ORDER BY ' + REPLY_SORTS[sort] + ' LIMIT $' + (params.length - 1) + ' OFFSET $' + params.length,\n params\n );\n var hasMore = heads.length > REPLIES_PAGE;\n heads = heads.slice(0, REPLIES_PAGE);\n var rows = heads;\n if (heads.length && !FLAT_REPLIES) {\n var patterns = heads.map(function (head) { return text(head.path) + '%'; });\n var childParams = [topic.id, patterns, rootDepth + MAX_DEPTH + 1, heads.map(function (head) { return head.id; })];\n var children = await q(\n 'SELECT ' + REPLY_SQL + ', p.reputation AS author_reputation, p.badges AS author_badges FROM ' + T.replies + ' r LEFT JOIN ' + T.profiles +\n ' p ON p.user_id = r.author_id WHERE r.topic_id = $1 AND r.path LIKE ANY($2::text[]) AND r.depth <= $3 AND NOT (r.id = ANY($4::uuid[])) AND ' +\n postVisibility('r', viewer, user, childParams) + ' ORDER BY r.path',\n childParams\n );\n rows = heads.concat(children);\n }\n var ids = rows.map(function (row) { return row.id; });\n var votes = await votesOf(q, user, ids);\n var reactions = await reactionsOf(q, user, ids);\n var shaped = rows.map(function (row) { return shapeReply(row, user, viewer, topic, votes, reactions); });\n // A flat list is in the database's order already, and nests nothing.\n return { replies: FLAT_REPLIES ? shaped : nest(shaped, rootDepth, sort), hasMore: hasMore, nextOffset: num(offset) + heads.length };\n}\n\n// One reply as the Reply component binds it: the viewer's own, whether they may edit it, and where its thread continues.\nfunction shapeReply(row, user, viewer, topic, votes, reactions) {\n var post = shapePost(row, votes, reactions);\n post.is_author = !!user.id && text(row.author_id) === user.id;\n post.is_mine = post.is_author;\n post.can_edit = canEdit(viewer, row);\n post.thread_url = threadUrlOf(topic.slug, row.id);\n if (!Array.isArray(post.children)) post.children = [];\n return post;\n}\n\n// The accepted answer as a reply row (the \"Accepted answer\" block), from the\n// tree when it is on this page, else read by id; null when there is none.\nasync function acceptedReplyOf(q, user, viewer, topic, replies) {\n var acceptedId = text(topic.accepted_reply_id);\n if (!acceptedId) return null;\n var inTree = flatten(replies).filter(function (reply) { return text(reply.id) === acceptedId; })[0];\n if (inTree) return inTree;\n var params = [topic.id, acceptedId];\n var rows = await q(\n 'SELECT ' + REPLY_SQL + ', p.reputation AS author_reputation, p.badges AS author_badges FROM ' + T.replies + ' r LEFT JOIN ' + T.profiles +\n ' p ON p.user_id = r.author_id WHERE r.topic_id = $1 AND r.id = $2 AND ' + postVisibility('r', viewer, user, params) + ' LIMIT 1',\n params\n );\n if (!rows.length) return null;\n var votes = await votesOf(q, user, [rows[0].id]);\n var reactions = await reactionsOf(q, user, [rows[0].id]);\n var reply = shapeReply(rows[0], user, viewer, topic, votes, reactions);\n reply.children = [];\n return reply;\n}\n\nasync function readableTopic(q, user, slugOrId, byId) {\n var topics = await q(\n 'SELECT ' + TOPIC_SQL + ', p.reputation AS author_reputation, p.badges AS author_badges FROM ' + T.topics + ' t LEFT JOIN ' + T.profiles +\n ' p ON p.user_id = t.author_id WHERE t.' + (byId ? 'id' : 'slug') + ' = $1 LIMIT 1',\n [slugOrId]\n );\n var topic = topics[0];\n if (!topic) return null;\n var communities = await q('SELECT ' + COMMUNITY_SQL + ' FROM ' + T.communities + ' c WHERE c.id = $1 LIMIT 1', [topic.community_id]);\n var community = communities[0];\n if (!community) return null;\n var viewer = await viewerOf(q, user, community);\n viewer.is_author = !!user.id && text(topic.author_id) === user.id;\n viewer.can_accept = (viewer.is_author || viewer.can_moderate) && SETTINGS.acceptedAnswers !== 'off' &&\n (SETTINGS.acceptedAnswers === 'all' || community.kind === 'questions');\n viewer.can_edit = canEdit(viewer, topic);\n if (!viewer.can_read) return null;\n if (topic.status !== 'published' && !(viewer.can_moderate || viewer.is_author)) return null;\n if (community.status !== 'active' && !viewer.can_moderate) return null;\n return { topic: topic, community: community, viewer: viewer };\n}\n\n// --- the pages ---------------------------------------------------------------------\n// { topic, community, viewer, replies, reactions, score, myVote, hasMoreReplies,\n// replySort, replyTo, nextReplyOffset, seo } \u2014 or null: the page answers notFound.\nasync function loadTopicPage(args) {\n var user = sessionOf(args.session);\n var sort = sortKey(args.sort, REPLY_SORTS, 'best');\n return withClient(async function (q) {\n var found = await readableTopic(q, user, text(args.slug), false);\n if (!found) return null;\n var topic = found.topic;\n var viewer = found.viewer;\n var tree = await replyTree(q, user, viewer, topic, text(args.rootReplyId) || null, sort, 0);\n var votes = await votesOf(q, user, [topic.id]);\n var reactions = await reactionsOf(q, user, [topic.id]);\n // The viewer's vote on the topic itself: a number (the replies carry their own).\n viewer.my_vote = votes[text(topic.id)] || 0;\n viewer.is_subscribed = await followsTopic(q, user, topic.id);\n var post = shapePost(topic, votes, reactions);\n post.is_author = viewer.is_author;\n post.is_mine = viewer.is_author;\n nameCommunity(post, found.community);\n post.accepted_reply = await acceptedReplyOf(q, user, viewer, topic, tree.replies);\n var community = shapeCommunity(found.community);\n var url = text(args.url);\n return {\n topic: post,\n community: HAS_COMMUNITIES ? community : null,\n viewer: viewer,\n replies: tree.replies,\n reactions: post.reactions,\n score: num(topic.score),\n myVote: post.my_vote,\n hasMoreReplies: tree.hasMore,\n nextReplyOffset: tree.nextOffset,\n replySort: sort,\n replyTo: text(args.rootReplyId) || '',\n seo: {\n noindex: topicNoIndex(topic, found.community),\n jsonLd: url && !topicNoIndex(topic, found.community) ? topicJsonLd(post, community, flatten(tree.replies), url) : null,\n },\n };\n });\n}\n\nfunction flatten(nodes) {\n var out = [];\n (nodes || []).forEach(function (node) { out.push(node); out = out.concat(flatten(node.children)); });\n return out;\n}\n\n// { community, viewer, topics, sortBy, paging, rules, moderators, pendingJoinCount,\n// openReportCount, seo } \u2014 or null. topics is one page of the list, in the order\n// sortBy names; paging says where it stands: { page, pages, previous, next }, the\n// last two the page numbers the pager's links open, 0 where there is none.\n// A private community's non-member gets the About side only: can_read false, no topics.\nasync function loadCommunityPage(args) {\n if (!HAS_COMMUNITIES) return null; // a forum without communities has no such page\n var user = sessionOf(args.session);\n var sort = sortKey(args.sort, TOPIC_SORTS, 'latest');\n // Without votes there is no score to order by.\n if (sort === 'top' && SETTINGS.votes === 'off') sort = 'latest';\n var page = Math.max(1, num(args.page) || 1);\n return withClient(async function (q) {\n var communities = await q('SELECT ' + COMMUNITY_SQL + ' FROM ' + T.communities + ' c WHERE c.slug = $1 LIMIT 1', [text(args.slug)]);\n var row = communities[0];\n if (!row) return null;\n var viewer = await viewerOf(q, user, row);\n // A community waiting for approval is its creator's to see (the page tells them so) and its\n // moderators'; an archived one its moderators' only.\n viewer.is_creator = !!user.id && text(row.created_by) === user.id;\n if (row.status !== 'active' && !viewer.can_moderate && !(row.status === 'pending' && viewer.is_creator)) return null;\n var community = shapeCommunity(row);\n // Who runs it, the owner first. The role is the membership's, never the profile's.\n var moderators = await q(\n 'SELECT m.user_id, m.role, p.handle, p.display_name, p.avatar_url FROM ' + T.memberships + ' m LEFT JOIN ' + T.profiles +\n \" p ON p.user_id = m.user_id WHERE m.community_id = $1 AND m.status = 'active' AND m.role IN ('owner', 'moderator') AND COALESCE(p.role, '') <> 'banned' ORDER BY (m.role = 'owner') DESC, m.joined_at LIMIT 20\",\n [row.id]\n );\n var result = {\n community: community,\n viewer: viewer,\n topics: [],\n sortBy: sort,\n paging: { page: 1, pages: 1, previous: 0, next: 0 },\n rules: community.rule_list.map(function (rule) { return { title: text(rule.title), text: text(rule.text) }; }),\n moderators: moderators.map(function (m) {\n return { user_id: text(m.user_id), handle: text(m.handle), name: text(m.display_name) || text(m.handle) || 'Member', avatar: m.avatar_url || null, role: text(m.role) };\n }),\n pendingJoinCount: 0,\n openReportCount: 0,\n seo: { noindex: row.status !== 'active' || row.visibility === 'private' },\n };\n if (!viewer.can_read) return result;\n var params = [row.id];\n var where = 't.community_id = $1 AND ' + topicVisibility(viewer, user, params);\n var counted = await q('SELECT COUNT(*)::int AS total FROM ' + T.topics + ' t WHERE ' + where, params);\n var pages = Math.max(1, Math.ceil(num(counted[0] && counted[0].total) / TOPICS_PER_PAGE));\n // A page past the last one (an old link, topics removed since) is the last one.\n page = Math.min(page, pages);\n result.paging = { page: page, pages: pages, previous: page > 1 ? page - 1 : 0, next: page < pages ? page + 1 : 0 };\n params.push(TOPICS_PER_PAGE, (page - 1) * TOPICS_PER_PAGE);\n var topics = await q(\n 'SELECT ' + TOPIC_SQL + ', p.reputation AS author_reputation, p.badges AS author_badges FROM ' + T.topics + ' t LEFT JOIN ' + T.profiles +\n ' p ON p.user_id = t.author_id WHERE ' + where + ' ORDER BY t.is_pinned DESC, ' + TOPIC_SORTS[sort] + ' LIMIT $' + (params.length - 1) + ' OFFSET $' + params.length,\n params\n );\n var votes = await votesOf(q, user, topics.map(function (t) { return t.id; }));\n result.topics = topics.map(function (t) {\n var post = shapePost(t, votes, {});\n post.body = '';\n post.body_html = '';\n post.is_mine = !!user.id && text(t.author_id) === user.id;\n nameCommunity(post, row);\n return post;\n });\n if (viewer.can_moderate) {\n var joins = await q('SELECT COUNT(*)::int AS total FROM ' + T.memberships + \" m WHERE m.community_id = $1 AND m.status = 'pending'\", [row.id]);\n var reports = await q('SELECT COUNT(*)::int AS total FROM ' + T.reports + \" x WHERE x.community_id = $1 AND x.status = 'open'\", [row.id]);\n result.pendingJoinCount = num(joins[0] && joins[0].total);\n result.openReportCount = num(reports[0] && reports[0].total);\n }\n return result;\n });\n}\n\n// A community's Manage (need 'moderate') and New topic (need 'post') pages:\n// { community, viewer } \u2014 or null (notFound). The row is read whatever its\n// visibility; the viewer decides: Manage for who moderates it, New topic for a\n// signed-in viewer who can read it (one who may not post yet is told to join there).\nasync function loadCommunityGate(args) {\n var user = sessionOf(args.session);\n if (!user.id) return null;\n return withClient(async function (q) {\n var communities = await q('SELECT ' + COMMUNITY_SQL + ' FROM ' + T.communities + ' c WHERE c.slug = $1 LIMIT 1', [text(args.slug)]);\n var row = communities[0];\n if (!row) return null;\n var viewer = await viewerOf(q, user, row);\n var admitted = args.need === 'moderate' ? viewer.can_moderate : args.need === 'post' && (viewer.can_post || viewer.can_read);\n if (!admitted || (row.status !== 'active' && !viewer.can_moderate)) return null;\n if (!HAS_COMMUNITIES) return { community: null, viewer: viewer }; // its composer is answered the rights alone\n // What the Manage page's own load answers beside the rights (forum-shapes.ts there).\n viewer.community_id = text(row.id);\n viewer.community_slug = text(row.slug);\n viewer.community_name = text(row.name);\n return { community: shapeCommunity(row), viewer: viewer };\n });\n}\n\n// { replies, hasMore, nextOffset, replyCount } for the replies route \u2014 or null\n// when the topic cannot be read by this viewer. replyCount is the topic's\n// published replies as stored now: the page's count follows a reply posted.\nasync function loadReplies(args) {\n var user = sessionOf(args.session);\n var sort = sortKey(args.sort, REPLY_SORTS, 'best');\n return withClient(async function (q) {\n var found = await readableTopic(q, user, text(args.topicId), true);\n if (!found) return null;\n var tree = await replyTree(q, user, found.viewer, found.topic, text(args.rootReplyId) || null, sort, num(args.after));\n tree.replyCount = num(found.topic.reply_count);\n return tree;\n });\n}\n\n// --- notifications ---------------------------------------------------------------------\nasync function loadNotifications(session, args) {\n var user = sessionOf(session);\n if (!user.id) return { items: [], unreadCount: 0 };\n var limit = Math.min(100, Math.max(1, num(args && args.limit) || NOTIFICATIONS_PAGE));\n return withClient(async function (q) {\n var rows = await q(\n 'SELECT n.id, n.kind, n.title, n.body, n.url, n.actor_handle, n.read_at, n.created_at FROM ' + T.notifications +\n ' n WHERE n.user_id = $1 ORDER BY n.created_at DESC LIMIT $2',\n [user.id, limit]\n );\n var unread = await q('SELECT COUNT(*)::int AS total FROM ' + T.notifications + ' n WHERE n.user_id = $1 AND n.read_at IS NULL', [user.id]);\n // text is what the profile tab's row binds; the overlay binds title and body.\n return {\n items: rows.map(function (row) { var out = plain(row); out.text = text(row.title); return out; }),\n unreadCount: num(unread[0] && unread[0].total),\n };\n });\n}\n\nasync function markNotificationsRead(session, ids) {\n var user = sessionOf(session);\n if (!user.id) return 0;\n var only = Array.isArray(ids) ? ids.map(text).filter(Boolean).slice(0, 200) : null;\n return withClient(async function (q) {\n var rows = await q(\n 'UPDATE ' + T.notifications + ' SET read_at = NOW() WHERE user_id = $1 AND read_at IS NULL' + (only ? ' AND id = ANY($2::uuid[])' : '') + ' RETURNING id',\n only ? [user.id, only] : [user.id]\n );\n return rows.length;\n });\n}\n\n// Of these storage file ids, the ones a topic, a reply or a community's icon or banner\n// still shows: they hold the file's address, `<bucket>/<project>/<file id>/<name>`.\nasync function filesStillShown(fileIds) {\n return withClient(async function (q) {\n var rows = await q(\n 'SELECT f.id FROM unnest($1::text[]) AS f(id) WHERE EXISTS (SELECT 1 FROM ' + T.topics + \" t WHERE t.attachments::text LIKE '%/' || f.id || '/%') OR EXISTS (SELECT 1 FROM \" + T.replies + \" r WHERE r.attachments::text LIKE '%/' || f.id || '/%') OR EXISTS (SELECT 1 FROM \" + T.communities + \" c WHERE COALESCE(c.icon_url, '') LIKE '%/' || f.id || '/%' OR COALESCE(c.banner_url, '') LIKE '%/' || f.id || '/%')\",\n [fileIds]\n );\n return rows.map(function (row) { return text(row.id); });\n });\n}\n\n// --- the live index ------------------------------------------------------------------------\nasync function listPublicIndex() {\n return withClient(async function (q) {\n var communities = HAS_COMMUNITIES ? await q(\n 'SELECT c.slug, c.name, c.description, c.updated_at FROM ' + T.communities + \" c WHERE c.status = 'active' AND c.visibility <> 'private' ORDER BY c.sort_order, c.created_at LIMIT 5000\"\n ) : [];\n var topics = await q(\n // A topic of an archived community, or of one still waiting for approval, is not public.\n 'SELECT t.slug, t.title, t.body_text, t.updated_at FROM ' + T.topics + \" t WHERE t.status = 'published' AND t.community_visibility <> 'private' AND EXISTS (SELECT 1 FROM \" +\n T.communities + \" c WHERE c.id = t.community_id AND c.status = 'active') ORDER BY t.created_at DESC LIMIT 50000\"\n );\n return {\n communities: communities.map(plain),\n topics: topics.map(function (t) { var out = plain(t); out.excerpt = excerptOf(t.body_text); delete out.body_text; return out; }),\n };\n });\n}\n\nmodule.exports = {\n readSession: readSession,\n loadTopicPage: loadTopicPage,\n loadCommunityPage: loadCommunityPage,\n loadCommunityGate: loadCommunityGate,\n loadReplies: loadReplies,\n loadNotifications: loadNotifications,\n markNotificationsRead: markNotificationsRead,\n filesStillShown: filesStillShown,\n listPublicIndex: listPublicIndex,\n settings: SETTINGS,\n};\n");
|
|
166
|
+
};
|
|
167
|
+
exports.buildForumPageDataSource = buildForumPageDataSource;
|
|
168
|
+
//# sourceMappingURL=page-data-source.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"page-data-source.js","sourceRoot":"","sources":["../../../src/forum/page-data-source.ts"],"names":[],"mappings":";;;AAAA,+DAAmE;AACnE,6FAAqF;AACrF,0DAAoD;AACpD,6BAAyC;AACzC,uCAAsD;AACtD,qDAA8D;AAEjD,QAAA,2BAA2B,GAAG,CAAC,OAAO,CAAC,CAAA;AACvC,QAAA,2BAA2B,GAAG,iBAAiB,CAAA;AAE5D,sFAAsF;AACzE,QAAA,kBAAkB,GAAG,EAAE,CAAA;AACpC,IAAM,aAAa,GAAG;IACpB,IAAI;IACJ,cAAc;IACd,gBAAgB;IAChB,gBAAgB;IAChB,sBAAsB;IACtB,WAAW;IACX,eAAe;IACf,aAAa;IACb,eAAe;IACf,OAAO;IACP,MAAM;IACN,MAAM;IACN,WAAW;IACX,MAAM;IACN,aAAa;IACb,QAAQ;IACR,WAAW;IACX,WAAW;IACX,mBAAmB;IACnB,OAAO;IACP,SAAS;IACT,WAAW;IACX,aAAa;IACb,YAAY;IACZ,kBAAkB;IAClB,WAAW;IACX,gBAAgB;IAChB,YAAY;IACZ,YAAY;CACb,CAAA;AACD,IAAM,aAAa,GAAG;IACpB,IAAI;IACJ,UAAU;IACV,cAAc;IACd,WAAW;IACX,OAAO;IACP,MAAM;IACN,WAAW;IACX,eAAe;IACf,aAAa;IACb,eAAe;IACf,MAAM;IACN,WAAW;IACX,aAAa;IACb,QAAQ;IACR,OAAO;IACP,SAAS;IACT,WAAW;IACX,aAAa;IACb,UAAU;IACV,WAAW;IACX,gBAAgB;IAChB,YAAY;IACZ,YAAY;CACb,CAAA;AACD,IAAM,iBAAiB,GAAG;IACxB,IAAI;IACJ,MAAM;IACN,MAAM;IACN,aAAa;IACb,OAAO;IACP,UAAU;IACV,YAAY;IACZ,MAAM;IACN,YAAY;IACZ,SAAS;IACT,QAAQ;IACR,YAAY;IACZ,cAAc;IACd,aAAa;IACb,kBAAkB;IAClB,aAAa;IACb,YAAY;IACZ,YAAY;IACZ,YAAY;CACb,CAAA;AACD,qFAAqF;AACrF,IAAM,eAAe,GAAG;IACtB,SAAS;IACT,QAAQ;IACR,cAAc;IACd,YAAY;IACZ,YAAY;IACZ,QAAQ;IACR,MAAM;CACP,CAAA;AAED,IAAM,OAAO,GAAG,UAAC,KAAa,EAAE,KAAe;IAC7C,OAAA,KAAK,CAAC,GAAG,CAAC,UAAC,IAAI,IAAK,OAAA,UAAG,KAAK,cAAI,IAAI,CAAE,EAAlB,CAAkB,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;AAAlD,CAAkD,CAAA;AAEpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDG;AACI,IAAM,wBAAwB,GAAG,UACtC,MAAmB,EACnB,OAAiD;;IAAjD,wBAAA,EAAA,YAAiD;IAEzC,IAAA,QAAQ,GAAK,MAAM,SAAX,CAAW;IAC3B,yFAAyF;IACzF,gEAAgE;IAChE,IAAM,IAAI,GAAG;QACX,KAAK,EAAE,CAAA,MAAA,MAAM,CAAC,MAAM,CAAC,KAAK,0CAAE,UAAU,KAAI,UAAU;QACpD,SAAS,EACP,QAAQ,CAAC,SAAS,KAAK,aAAa,CAAC,CAAC,CAAC,CAAA,MAAA,MAAM,CAAC,MAAM,CAAC,SAAS,0CAAE,UAAU,KAAI,UAAU,CAAC,CAAC,CAAC,EAAE;KAChG,CAAA;IACD,OAAO,+FAEP,IAAA,yDAAwB,GAAE,yCACA,4CAA0B,oBAEpD,uCAAqB,CAAC,wCAAwC,CAAC,IAAI,EAAE;QACrE,cAAc,EAAE,OAAO,CAAC,qBAAqB,KAAK,KAAK;KACxD,CAAC,0PAUe,IAAA,6BAAW,EAAC,QAAQ,CAAC,wVAK7B,IAAA,6BAAW,EAAC,uBAAY,CAAC,mCACb,0BAAkB,sCACf,MAAM,CAAC,sBAAsB,wGAIxC,IAAA,6BAAW,EAAC,IAAI,CAAC,8DAEZ,IAAA,6BAAW,EAAC,OAAO,CAAC,GAAG,EAAE,aAAa,CAAC,CAAC,gCACxC,IAAA,6BAAW,EAAC,OAAO,CAAC,GAAG,EAAE,aAAa,CAAC,CAAC,oCACpC,IAAA,6BAAW,EAAC,OAAO,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAC,kCAC9C,IAAA,6BAAW,EAAC,OAAO,CAAC,GAAG,EAAE,eAAe,CAAC,CAAC,+XAa5D,uBAAiB,ql8BAslBlB,CAAA;AACD,CAAC,CAAA;AAjpBY,QAAA,wBAAwB,4BAipBpC"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { ForumDetailsPage } from './settings';
|
|
2
|
+
/** The prop the page's extra data travels under (SEO, the community, the reply cursor). */
|
|
3
|
+
export declare const FORUM_PAGE_PROP = "__tqForum";
|
|
4
|
+
/** Which record a page is about. */
|
|
5
|
+
export type ForumPageRecord =
|
|
6
|
+
/** The one its address ends with, by the route column (`slug`): `context.params[column]`. */
|
|
7
|
+
{
|
|
8
|
+
column: string;
|
|
9
|
+
}
|
|
10
|
+
/** Always the same one, by its slug: a page with a static address (`/forum/new`). */
|
|
11
|
+
| {
|
|
12
|
+
slug: string;
|
|
13
|
+
};
|
|
14
|
+
export type ForumPageRewrite = ForumPageRecord & {
|
|
15
|
+
kind: ForumDetailsPage;
|
|
16
|
+
/** The prop the page reads its row from (`initialPropsData.exposeAs.name`), or null when it binds none. */
|
|
17
|
+
exposeAs: string | null;
|
|
18
|
+
/** From the page's folder to the project root (`../../../` for `pages/forum/t/`). */
|
|
19
|
+
rootPrefix: string;
|
|
20
|
+
/** `utils/forum-page-data`, under `rootPrefix`. */
|
|
21
|
+
dataModulePath: string;
|
|
22
|
+
/** `utils/page-arrival`, under `rootPrefix`. */
|
|
23
|
+
pageArrivalPath: string;
|
|
24
|
+
};
|
|
25
|
+
/** The states each page declares (`forum-markers.ts` there) that start from the module's answer. */
|
|
26
|
+
export declare const FORUM_SEEDED_STATES: Record<ForumDetailsPage, string[]>;
|
|
27
|
+
export interface ForumPageRewriteResult {
|
|
28
|
+
content: string;
|
|
29
|
+
/** The states now seeded from the page's props. */
|
|
30
|
+
seededStates: string[];
|
|
31
|
+
/** The page's head got the robots and JSON-LD lines. */
|
|
32
|
+
headInjected: boolean;
|
|
33
|
+
/** The page now remounts on every arrival (needs `utils/page-arrival.js`). */
|
|
34
|
+
remounts: boolean;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Rewrites a generated forum details page (the topic, the community, its
|
|
38
|
+
* Manage and New topic pages) — or the static New topic page of a forum
|
|
39
|
+
* without communities — so it renders per request from the forum data
|
|
40
|
+
* module: its `getStaticProps` / `getStaticPaths` (or an earlier
|
|
41
|
+
* `getServerSideProps`) are replaced by one that reads the session, calls the
|
|
42
|
+
* module, answers `notFound` when it refuses and sets the cache header; the
|
|
43
|
+
* page's own states start from the module's answer through its props, and
|
|
44
|
+
* keep it (no copy of the record over them on mount); the
|
|
45
|
+
* head carries `noindex` and the JSON-LD when the module says so; and the page
|
|
46
|
+
* remounts on every arrival, as every page seeded from props does. Returns
|
|
47
|
+
* null when the file is not a page this can rewrite (no default export).
|
|
48
|
+
*/
|
|
49
|
+
export declare const rewriteForumPage: (content: string, rewrite: ForumPageRewrite) => ForumPageRewriteResult | null;
|
|
50
|
+
//# sourceMappingURL=page-rewrite.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"page-rewrite.d.ts","sourceRoot":"","sources":["../../../src/forum/page-rewrite.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAE7C,2FAA2F;AAC3F,eAAO,MAAM,eAAe,cAAc,CAAA;AAG1C,oCAAoC;AACpC,MAAM,MAAM,eAAe;AACzB,6FAA6F;AAC3F;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE;AACpB,qFAAqF;GACnF;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAA;AAEpB,MAAM,MAAM,gBAAgB,GAAG,eAAe,GAAG;IAC/C,IAAI,EAAE,gBAAgB,CAAA;IACtB,2GAA2G;IAC3G,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;IACvB,qFAAqF;IACrF,UAAU,EAAE,MAAM,CAAA;IAClB,mDAAmD;IACnD,cAAc,EAAE,MAAM,CAAA;IACtB,gDAAgD;IAChD,eAAe,EAAE,MAAM,CAAA;CACxB,CAAA;AAED,oGAAoG;AACpG,eAAO,MAAM,mBAAmB,EAAE,MAAM,CAAC,gBAAgB,EAAE,MAAM,EAAE,CAwBlE,CAAA;AAyaD,MAAM,WAAW,sBAAsB;IACrC,OAAO,EAAE,MAAM,CAAA;IACf,mDAAmD;IACnD,YAAY,EAAE,MAAM,EAAE,CAAA;IACtB,wDAAwD;IACxD,YAAY,EAAE,OAAO,CAAA;IACrB,8EAA8E;IAC9E,QAAQ,EAAE,OAAO,CAAA;CAClB;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,gBAAgB,YAClB,MAAM,WACN,gBAAgB,KACxB,sBAAsB,GAAG,IA6D3B,CAAA"}
|