Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

refactor(api/reports): build the flow registry on the compiler

Hampusd3d276be0cf7
diff --git a/fluxer_api/src/api/report/flows/ReportFlowRegistry.ts b/fluxer_api/src/api/report/flows/ReportFlowRegistry.ts
index f5ae22bea..ee0f3e64e 100644
--- a/fluxer_api/src/api/report/flows/ReportFlowRegistry.ts
+++ b/fluxer_api/src/api/report/flows/ReportFlowRegistry.ts
@@ -1,30 +1,34 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {createHash} from 'node:crypto';
import {Config} from '@app/api/Config';
import {getContentMessage} from '@app/api/content_i18n/ContentI18n';
-import {CONTENT_I18N_MESSAGES} from '@app/api/content_i18n/ContentI18nMessages';
import {getLegalUrls} from '@app/api/instance/LegalUrls';
import {getInstanceProductName} from '@app/api/instance/ProductName';
-import {REPORT_FLOWS, type ReportFlowDef} from '@app/api/report/flows/ReportFlowDefinitions';
+import {
+ assertValidReportFlowLibrary,
+ buildReportFlowVariant,
+ type ReportFlowInstance,
+ type ReportFlowLibrary,
+ type ReportFlowVariant,
+ type ReportFlowVariantScreen,
+} from '@app/api/report/flows/ReportFlowCompiler';
+import {REPORT_FLOWS} from '@app/api/report/flows/ReportFlowDefinitions';
import {
REPORT_FLOW_NOTICES,
REPORT_FLOW_SCREENS,
type ReportFlowCopyKey,
type ReportFlowLinkId,
- type ReportFlowNoticeDef,
- type ReportFlowOptionDef,
type ReportFlowOutcomeDef,
- type ReportFlowScreenDef,
} from '@app/api/report/flows/ReportFlowScreens';
-import {getLegacyCategory, isReportReasonKey, type ReportReasonKey} from '@app/api/report/flows/ReportReasonCatalog';
-import {isStringArray} from '@app/api/utils/JsonBoundaryUtils';
+import {getLegacyCategory, type ReportReasonKey} from '@app/api/report/flows/ReportReasonCatalog';
+import {isStringArray, parseJsonArray} from '@app/api/utils/JsonBoundaryUtils';
import type {LocaleCode} from '@fluxer/constants/src/Locales';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
import {InvalidReportFlowAnswersError} from '@fluxer/errors/src/domains/moderation/InvalidReportFlowAnswersError';
import {ReportFlowOutdatedError} from '@fluxer/errors/src/domains/moderation/ReportFlowOutdatedError';
import {parseAcceptLanguage} from '@fluxer/i18n/src/locale/resolution/AcceptLanguageNegotiation';
+import {isObjectLike} from '@fluxer/record_utils/src/RecordGuards';
import type {
ReportFlowOutcome,
ReportFlowResponse,
@@ -33,48 +37,19 @@ import type {
ReportFlowTargetType,
} from '@fluxer/schema/src/domains/report/ReportFlowSchemas';
-export interface ReportFlowLibrary {
- flows: Record<ReportFlowTargetType, ReportFlowDef>;
- screens: ReadonlyArray<ReportFlowScreenDef>;
- notices: ReadonlyArray<ReportFlowNoticeDef>;
-}
-
-export interface ReportFlowInstance {
- selfHosted: boolean;
- guidelinesLinked: boolean;
-}
-
-type ReportFlowScreenKind = 'choice' | 'checklist' | 'info';
-
-interface ReportFlowVariantScreen {
- def: ReportFlowScreenDef;
- kind: ReportFlowScreenKind;
- subtitle: ReportFlowCopyKey | null;
- options: ReadonlyArray<ReportFlowOptionDef>;
-}
-
-export interface ReportFlowVariant {
- target: ReportFlowTargetType;
- surface: ReportFlowSurface;
- startScreenId: string;
- screens: ReadonlyMap<string, ReportFlowVariantScreen>;
- notices: ReadonlyArray<ReportFlowNoticeDef>;
- revisionHash: string;
-}
-
export interface ReportFlowStepRecord {
screen_id: string;
option_id?: string;
item_ids?: Array<string>;
}
-export interface ReportFlowStepInput {
+interface ReportFlowStepInput {
screen_id: string;
option_id?: string | undefined;
item_ids?: ReadonlyArray<string> | undefined;
}
-export interface ResolvedReportFlowAnswers {
+interface ResolvedReportFlowAnswers {
reason: ReportReasonKey;
legacyCategory: string;
steps: Array<ReportFlowStepRecord>;
@@ -83,7 +58,7 @@ export interface ResolvedReportFlowAnswers {
isCurrentRevision: boolean;
}
-export interface ReportFlowAnswersDescription {
+interface ReportFlowAnswersDescription {
revision_hash: string;
surface: string;
locale: string | null;
@@ -96,436 +71,16 @@ export interface ReportFlowAnswersDescription {
}>;
}
-export const REPORT_FLOW_LIBRARY: ReportFlowLibrary = {
+const REPORT_FLOW_LIBRARY: ReportFlowLibrary = {
flows: REPORT_FLOWS,
screens: REPORT_FLOW_SCREENS,
notices: REPORT_FLOW_NOTICES,
};
-const REPORT_FLOW_TARGETS: ReadonlyArray<ReportFlowTargetType> = ['message', 'user', 'guild'];
-const REPORT_FLOW_SURFACES: ReadonlyArray<ReportFlowSurface> = ['in_app', 'dsa'];
-const REPORT_FLOW_ID_PATTERN = /^[a-z0-9_]{1,48}$/;
-const MAX_WALK_SCREENS = 10;
const CRISIS_LINES_URL = 'https://befrienders.org';
const COPYRIGHT_HELP_URL = 'https://fluxer.app/help/copyright';
-const HOSTED_REPORT_FLOW_INSTANCE: ReportFlowInstance = {selfHosted: false, guidelinesLinked: true};
-const REPORT_FLOW_CHECKED_INSTANCES: ReadonlyArray<ReportFlowInstance> = [
- HOSTED_REPORT_FLOW_INSTANCE,
- {selfHosted: true, guidelinesLinked: false},
- {selfHosted: true, guidelinesLinked: true},
-];
const ADMIN_LOCALE = 'en-US';
-function getReportFlowScreenKind(screen: ReportFlowScreenDef): ReportFlowScreenKind {
- if (screen.checklist) {
- return 'checklist';
- }
- if (screen.nextScreenId !== undefined) {
- return 'info';
- }
- return 'choice';
-}
-
-function isLinkAvailable(link: ReportFlowLinkId, instance: ReportFlowInstance): boolean {
- switch (link) {
- case 'crisis_lines':
- return true;
- case 'guidelines':
- return instance.guidelinesLinked;
- case 'copyright':
- return !instance.selfHosted;
- }
-}
-
-function resolveScreenSubtitle(
- def: ReportFlowScreenDef,
- surface: ReportFlowSurface,
- instance: ReportFlowInstance,
-): ReportFlowCopyKey | null {
- const variants = def.subtitleVariants;
- if (surface === 'dsa' && variants?.dsa !== undefined) {
- return variants.dsa;
- }
- if (instance.selfHosted && variants?.selfHosted !== undefined) {
- return variants.selfHosted;
- }
- return def.subtitle ?? null;
-}
-
-function isOptionInVariant(
- option: ReportFlowOptionDef,
- surface: ReportFlowSurface,
- instance: ReportFlowInstance,
-): boolean {
- if (option.surface !== undefined && option.surface !== surface) {
- return false;
- }
- return option.outcome.type !== 'link' || isLinkAvailable(option.outcome.link, instance);
-}
-
-function getScreenEdges(screen: ReportFlowVariantScreen): Array<string> {
- const edges: Array<string> = [];
- for (const option of screen.options) {
- if (option.outcome.type === 'screen') {
- edges.push(option.outcome.screenId);
- }
- }
- if (screen.def.checklist?.outcome.type === 'screen') {
- edges.push(screen.def.checklist.outcome.screenId);
- }
- if (screen.def.nextScreenId !== undefined) {
- edges.push(screen.def.nextScreenId);
- }
- return edges;
-}
-
-function getScreenOutcomes(screen: ReportFlowVariantScreen): Array<ReportFlowOutcomeDef> {
- const outcomes = screen.options.map((option) => option.outcome);
- if (screen.def.checklist) {
- outcomes.push(screen.def.checklist.outcome);
- }
- return outcomes;
-}
-
-function canonicalOutcome(outcome: ReportFlowOutcomeDef): string {
- switch (outcome.type) {
- case 'screen':
- return `screen:${outcome.screenId}`;
- case 'submit':
- return `submit:${outcome.reason}`;
- case 'end':
- return outcome.noticeId === undefined ? 'end' : `end:${outcome.noticeId}`;
- case 'link':
- return `link:${outcome.link}`;
- }
-}
-
-function computeRevisionHash(
- target: ReportFlowTargetType,
- surface: ReportFlowSurface,
- startScreenId: string,
- screens: ReadonlyMap<string, ReportFlowVariantScreen>,
- notices: ReadonlyArray<ReportFlowNoticeDef>,
-): string {
- const canonical = {
- target,
- surface,
- start: startScreenId,
- screens: [...screens.values()]
- .sort((a, b) => (a.def.id < b.def.id ? -1 : a.def.id > b.def.id ? 1 : 0))
- .map((screen) => ({
- id: screen.def.id,
- kind: screen.kind,
- title: screen.def.title,
- subtitle: screen.subtitle,
- options_heading: screen.options.length > 0 ? (screen.def.optionsHeading ?? null) : null,
- urgent: screen.def.urgent === true,
- next: screen.def.nextScreenId ?? null,
- options: screen.options.map((option) => ({
- id: option.id,
- label: option.label,
- outcome: canonicalOutcome(option.outcome),
- })),
- checklist: screen.def.checklist
- ? {
- items: screen.def.checklist.items.map((item) => ({
- id: item.id,
- label: item.label,
- description: item.description ?? null,
- reason: item.reason ?? null,
- })),
- min_checked: screen.def.checklist.minChecked,
- outcome: canonicalOutcome(screen.def.checklist.outcome),
- }
- : null,
- })),
- notices: notices.map((notice) => ({id: notice.id, title: notice.title, body: notice.body})),
- };
- return createHash('sha256').update(JSON.stringify(canonical)).digest('hex').slice(0, 16);
-}
-
-export function buildReportFlowVariant(
- library: ReportFlowLibrary,
- target: ReportFlowTargetType,
- surface: ReportFlowSurface,
- instance: ReportFlowInstance,
-): ReportFlowVariant | null {
- const startScreenId = library.flows[target].start[surface];
- if (startScreenId === undefined) {
- return null;
- }
- const screenDefs = new Map(library.screens.map((screen) => [screen.id, screen]));
- const screens = new Map<string, ReportFlowVariantScreen>();
- const noticeIds = new Set<string>();
- const queue = [startScreenId];
- for (let index = 0; index < queue.length; index++) {
- const screenId = queue[index];
- if (screens.has(screenId)) {
- continue;
- }
- const def = screenDefs.get(screenId);
- if (!def) {
- throw new Error(`Report flow ${target}/${surface} references an unknown screen: ${screenId}`);
- }
- const screen: ReportFlowVariantScreen = {
- def,
- kind: getReportFlowScreenKind(def),
- subtitle: resolveScreenSubtitle(def, surface, instance),
- options: (def.options ?? []).filter((option) => isOptionInVariant(option, surface, instance)),
- };
- screens.set(screenId, screen);
- for (const outcome of getScreenOutcomes(screen)) {
- if (outcome.type === 'end' && outcome.noticeId !== undefined) {
- noticeIds.add(outcome.noticeId);
- }
- }
- queue.push(...getScreenEdges(screen));
- }
- const notices = library.notices.filter((notice) => noticeIds.has(notice.id));
- return {
- target,
- surface,
- startScreenId,
- screens,
- notices,
- revisionHash: computeRevisionHash(target, surface, startScreenId, screens, notices),
- };
-}
-
-function collectDefinitionErrors(library: ReportFlowLibrary): Array<string> {
- const errors: Array<string> = [];
- const screenIds = new Set<string>();
- const noticeIds = new Set(library.notices.map((notice) => notice.id));
- const checkId = (id: string, where: string) => {
- if (!REPORT_FLOW_ID_PATTERN.test(id)) {
- errors.push(`${where}: id "${id}" does not match ${REPORT_FLOW_ID_PATTERN}`);
- }
- };
- const checkKey = (key: string | undefined, where: string) => {
- if (key !== undefined && !Object.hasOwn(CONTENT_I18N_MESSAGES, key)) {
- errors.push(`${where}: unknown copy key ${key}`);
- }
- };
- const checkOutcome = (outcome: ReportFlowOutcomeDef, where: string) => {
- if (outcome.type === 'submit' && !isReportReasonKey(outcome.reason)) {
- errors.push(`${where}: unknown reason ${outcome.reason}`);
- }
- if (outcome.type === 'end' && outcome.noticeId !== undefined && !noticeIds.has(outcome.noticeId)) {
- errors.push(`${where}: unknown notice ${outcome.noticeId}`);
- }
- };
- for (const notice of library.notices) {
- checkId(notice.id, `notice ${notice.id}`);
- checkKey(notice.title, `notice ${notice.id}`);
- checkKey(notice.body, `notice ${notice.id}`);
- }
- if (noticeIds.size !== library.notices.length) {
- errors.push('notice ids are not unique');
- }
- for (const screen of library.screens) {
- const where = `screen ${screen.id}`;
- checkId(screen.id, where);
- if (screenIds.has(screen.id)) {
- errors.push(`${where}: duplicate screen id`);
- }
- screenIds.add(screen.id);
- checkKey(screen.title, where);
- checkKey(screen.subtitle, where);
- checkKey(screen.subtitleVariants?.dsa ?? undefined, where);
- checkKey(screen.subtitleVariants?.selfHosted ?? undefined, where);
- checkKey(screen.optionsHeading, where);
- const options = screen.options ?? [];
- const kind = getReportFlowScreenKind(screen);
- if (kind === 'checklist' && (options.length > 0 || screen.nextScreenId !== undefined)) {
- errors.push(`${where}: a checklist screen has no options and no next screen`);
- }
- if (kind === 'info' && options.some((option) => option.outcome.type !== 'link')) {
- errors.push(`${where}: an info screen only has link options`);
- }
- if (kind === 'choice' && !options.some((option) => option.outcome.type !== 'link')) {
- errors.push(`${where}: a choice screen needs at least one option that is not a link`);
- }
- const optionIds = new Set<string>();
- for (const option of options) {
- const optionWhere = `${where} option ${option.id}`;
- checkId(option.id, optionWhere);
- if (optionIds.has(option.id)) {
- errors.push(`${optionWhere}: duplicate option id`);
- }
- optionIds.add(option.id);
- checkKey(option.label, optionWhere);
- checkOutcome(option.outcome, optionWhere);
- const endsWithoutNotice = option.outcome.type === 'end' && option.outcome.noticeId === undefined;
- const linksToCopyright = option.outcome.type === 'link' && option.outcome.link === 'copyright';
- if ((endsWithoutNotice || linksToCopyright) && option.surface !== 'in_app') {
- errors.push(`${optionWhere}: a no-report or copyright link option must be limited to in_app`);
- }
- }
- if (screen.checklist) {
- const {items, minChecked, outcome} = screen.checklist;
- const itemIds = new Set<string>();
- for (const item of items) {
- const itemWhere = `${where} item ${item.id}`;
- checkId(item.id, itemWhere);
- if (itemIds.has(item.id)) {
- errors.push(`${itemWhere}: duplicate item id`);
- }
- itemIds.add(item.id);
- checkKey(item.label, itemWhere);
- checkKey(item.description, itemWhere);
- if (item.reason !== undefined && !isReportReasonKey(item.reason)) {
- errors.push(`${itemWhere}: unknown reason ${item.reason}`);
- }
- }
- if (!Number.isInteger(minChecked) || minChecked < 1 || minChecked > items.length) {
- errors.push(`${where}: min checked must be between 1 and the item count`);
- }
- checkOutcome(outcome, `${where} checklist`);
- }
- }
- for (const screen of library.screens) {
- const targets = [
- ...(screen.options ?? []).flatMap((option) =>
- option.outcome.type === 'screen' ? [option.outcome.screenId] : [],
- ),
- ...(screen.checklist?.outcome.type === 'screen' ? [screen.checklist.outcome.screenId] : []),
- ...(screen.nextScreenId !== undefined ? [screen.nextScreenId] : []),
- ];
- for (const next of targets) {
- if (!screenIds.has(next)) {
- errors.push(`screen ${screen.id}: next screen ${next} is not defined`);
- }
- }
- }
- for (const target of REPORT_FLOW_TARGETS) {
- for (const surface of REPORT_FLOW_SURFACES) {
- const start = library.flows[target].start[surface];
- if (start !== undefined && !screenIds.has(start)) {
- errors.push(`flow ${target}/${surface}: start screen ${start} is not defined`);
- }
- }
- }
- return errors;
-}
-
-function collectVariantErrors(variant: ReportFlowVariant): Array<string> {
- const errors: Array<string> = [];
- const name = `flow ${variant.target}/${variant.surface}`;
- const startKind = variant.screens.get(variant.startScreenId)?.kind;
- const mustStartWithInfo = variant.target === 'user' && variant.surface === 'in_app';
- if (mustStartWithInfo !== (startKind === 'info')) {
- errors.push(
- mustStartWithInfo
- ? `${name}: the start screen must be an info screen`
- : `${name}: the start screen must not be an info screen`,
- );
- }
- for (const screen of variant.screens.values()) {
- if (screen.kind === 'choice' && !screen.options.some((option) => option.outcome.type !== 'link')) {
- errors.push(`${name} screen ${screen.def.id}: no option that is not a link remains`);
- }
- for (const outcome of getScreenOutcomes(screen)) {
- if (outcome.type === 'submit') {
- checkLegacyCategory(outcome.reason, variant.target, `${name} screen ${screen.def.id}`, errors);
- }
- }
- for (const item of screen.def.checklist?.items ?? []) {
- if (item.reason !== undefined) {
- checkLegacyCategory(item.reason, variant.target, `${name} screen ${screen.def.id}`, errors);
- }
- }
- }
- const depth = new Map<string, number>();
- const visiting = new Set<string>();
- const measure = (screenId: string): number => {
- const known = depth.get(screenId);
- if (known !== undefined) {
- return known;
- }
- if (visiting.has(screenId)) {
- errors.push(`${name}: cycle through screen ${screenId}`);
- return Number.POSITIVE_INFINITY;
- }
- visiting.add(screenId);
- const screen = variant.screens.get(screenId);
- let longest = 0;
- for (const next of screen ? getScreenEdges(screen) : []) {
- longest = Math.max(longest, measure(next));
- }
- visiting.delete(screenId);
- depth.set(screenId, longest + 1);
- return longest + 1;
- };
- const longestWalk = measure(variant.startScreenId);
- if (Number.isFinite(longestWalk) && longestWalk > MAX_WALK_SCREENS) {
- errors.push(`${name}: longest walk is ${longestWalk} screens, the limit is ${MAX_WALK_SCREENS}`);
- }
- return errors;
-}
-
-function checkLegacyCategory(reason: string, target: ReportFlowTargetType, where: string, errors: Array<string>) {
- if (!isReportReasonKey(reason) || !getLegacyCategory(reason, target)) {
- errors.push(`${where}: reason ${reason} has no legacy category for ${target}`);
- }
-}
-
-export function assertValidReportFlowLibrary(library: ReportFlowLibrary): void {
- const errors = collectDefinitionErrors(library);
- if (errors.length === 0) {
- const reachable = new Set<string>();
- for (const instance of REPORT_FLOW_CHECKED_INSTANCES) {
- for (const target of REPORT_FLOW_TARGETS) {
- for (const surface of REPORT_FLOW_SURFACES) {
- const variant = buildReportFlowVariant(library, target, surface, instance);
- if (!variant) {
- continue;
- }
- errors.push(...collectVariantErrors(variant));
- for (const screenId of variant.screens.keys()) {
- reachable.add(screenId);
- }
- }
- }
- }
- for (const screen of library.screens) {
- if (!reachable.has(screen.id)) {
- errors.push(`screen ${screen.id}: not reachable from any flow`);
- }
- }
- }
- if (errors.length > 0) {
- throw new Error(`Invalid report flow definitions:\n${[...new Set(errors)].join('\n')}`);
- }
-}
-
-export function buildReportFlowLedger(library: ReportFlowLibrary): Record<string, string> {
- const ledger: Record<string, string> = {};
- for (const target of REPORT_FLOW_TARGETS) {
- for (const surface of REPORT_FLOW_SURFACES) {
- const variant = buildReportFlowVariant(library, target, surface, HOSTED_REPORT_FLOW_INSTANCE);
- if (!variant) {
- continue;
- }
- for (const screen of variant.screens.values()) {
- const prefix = `${target}/${screen.def.id}`;
- for (const option of screen.options) {
- ledger[`${prefix}/${option.id}`] = canonicalOutcome(option.outcome);
- }
- if (screen.def.checklist) {
- for (const item of screen.def.checklist.items) {
- ledger[`${prefix}/${item.id}`] = item.reason === undefined ? 'item' : `item:${item.reason}`;
- }
- ledger[`${prefix}/#next`] = canonicalOutcome(screen.def.checklist.outcome);
- }
- if (screen.def.nextScreenId !== undefined) {
- ledger[`${prefix}/#next`] = `screen:${screen.def.nextScreenId}`;
- }
- }
- }
- }
- return Object.fromEntries(Object.entries(ledger).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
-}
-
assertValidReportFlowLibrary(REPORT_FLOW_LIBRARY);
const variantCache = new Map<string, ReportFlowVariant | null>();
@@ -570,10 +125,6 @@ function requireReportFlowVariant(
return variant;
}
-export function getReportFlowVariant(target: ReportFlowTargetType, surface: ReportFlowSurface): ReportFlowVariant {
- return requireReportFlowVariant(target, surface, getReportFlowInstance(getLegalUrls().guidelinesUrl));
-}
-
export function resolveReportFlowLocale(raw: string | null | undefined): LocaleCode {
return parseAcceptLanguage(raw);
}
@@ -732,7 +283,11 @@ export function resolveReportFlowAnswers(params: {
revisionHash: string;
steps: ReadonlyArray<ReportFlowStepInput>;
}): ResolvedReportFlowAnswers {
- const variant = getReportFlowVariant(params.target, params.surface);
+ const variant = requireReportFlowVariant(
+ params.target,
+ params.surface,
+ getReportFlowInstance(getLegalUrls().guidelinesUrl),
+ );
const isCurrentRevision = params.revisionHash === variant.revisionHash;
const result = findInvalidStep(variant, params.steps);
if ('invalidStep' in result) {
@@ -755,21 +310,16 @@ export function parseReportFlowSteps(json: string | null | undefined): Array<Rep
if (!json) {
return null;
}
- let parsed: unknown;
- try {
- parsed = JSON.parse(json);
- } catch {
- return null;
- }
- if (!Array.isArray(parsed)) {
+ const parsed = parseJsonArray(json);
+ if (!parsed) {
return null;
}
const steps: Array<ReportFlowStepRecord> = [];
for (const entry of parsed) {
- if (typeof entry !== 'object' || entry === null) {
+ if (!isObjectLike(entry)) {
return null;
}
- const {screen_id, option_id, item_ids} = entry as Record<string, unknown>;
+ const {screen_id, option_id, item_ids} = entry;
if (
typeof screen_id !== 'string' ||
(option_id !== undefined && typeof option_id !== 'string') ||
@@ -803,12 +353,16 @@ export function describeReportFlowAnswers(params: {
step.option_id === undefined
? undefined
: screen?.options?.find((candidate) => candidate.id === step.option_id);
+ const screenTitle = screen ? renderCopy(screen.title, ADMIN_LOCALE) : step.screen_id;
+ let optionLabel: string | null = null;
+ if (step.option_id !== undefined) {
+ optionLabel = option ? renderCopy(option.label, ADMIN_LOCALE) : step.option_id;
+ }
return {
screen_id: step.screen_id,
- screen_title: screen ? renderCopy(screen.title, ADMIN_LOCALE) : step.screen_id,
+ screen_title: screenTitle,
option_id: step.option_id ?? null,
- option_label:
- step.option_id === undefined ? null : option ? renderCopy(option.label, ADMIN_LOCALE) : step.option_id,
+ option_label: optionLabel,
items: (step.item_ids ?? []).map((itemId) => {
const item = screen?.checklist?.items.find((candidate) => candidate.id === itemId);
return {id: itemId, label: item ? renderCopy(item.label, ADMIN_LOCALE) : itemId};
diff --git a/fluxer_api/src/api/report/tests/ReportFlowRegistry.test.ts b/fluxer_api/src/api/report/tests/ReportFlowRegistry.test.ts
index 4b08cb6dc..a4d9e7e36 100644
--- a/fluxer_api/src/api/report/tests/ReportFlowRegistry.test.ts
+++ b/fluxer_api/src/api/report/tests/ReportFlowRegistry.test.ts
@@ -8,25 +8,32 @@ import {setCachedConfiguredLegalUrls} from '@app/api/instance/LegalUrls';
import {setCachedProductName} from '@app/api/instance/ProductName';
import {
assertValidReportFlowLibrary,
- buildReportFlowLedger,
buildReportFlowVariant,
- describeReportFlowAnswers,
- getReportFlowResponse,
- getReportFlowVariant,
- parseReportFlowSteps,
- REPORT_FLOW_LIBRARY,
type ReportFlowInstance,
type ReportFlowLibrary,
- type ReportFlowStepInput,
type ReportFlowVariant,
+} from '@app/api/report/flows/ReportFlowCompiler';
+import {REPORT_FLOWS} from '@app/api/report/flows/ReportFlowDefinitions';
+import {
+ describeReportFlowAnswers,
+ getReportFlowResponse,
+ parseReportFlowSteps,
resolveReportFlowAnswers,
} from '@app/api/report/flows/ReportFlowRegistry';
-import type {ReportFlowOptionDef, ReportFlowScreenDef} from '@app/api/report/flows/ReportFlowScreens';
+import {
+ REPORT_FLOW_NOTICES,
+ REPORT_FLOW_SCREENS,
+ type ReportFlowOptionDef,
+ type ReportFlowOutcomeDef,
+ type ReportFlowScreenDef,
+} from '@app/api/report/flows/ReportFlowScreens';
import {getLegacyCategory, listReportReasons, REPORT_REASONS} from '@app/api/report/flows/ReportReasonCatalog';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
+import {HttpStatus} from '@fluxer/constants/src/HttpConstants';
import {FluxerError} from '@fluxer/errors/src/FluxerError';
import {
ReportFlowResponse,
+ type ReportFlowStep,
type ReportFlowSurface,
type ReportFlowTargetType,
} from '@fluxer/schema/src/domains/report/ReportFlowSchemas';
@@ -36,25 +43,86 @@ import {
ReportUserRequest,
} from '@fluxer/schema/src/domains/report/ReportSchemas';
import {afterEach, describe, expect, test} from 'vitest';
+import {z} from 'zod';
+
+const REPORT_FLOW_LIBRARY: ReportFlowLibrary = {
+ flows: REPORT_FLOWS,
+ screens: REPORT_FLOW_SCREENS,
+ notices: REPORT_FLOW_NOTICES,
+};
const THIS_DIR = path.dirname(fileURLToPath(import.meta.url));
const LEDGER_PATH = path.join(THIS_DIR, '../flows/ReportFlowIds.snapshot.json');
-const VARIANTS: ReadonlyArray<[ReportFlowTargetType, ReportFlowSurface]> = [
- ['message', 'in_app'],
- ['message', 'dsa'],
- ['user', 'in_app'],
- ['user', 'dsa'],
- ['guild', 'dsa'],
+const VARIANTS: ReadonlyArray<[ReportFlowTargetType, ReportFlowSurface, 'choice' | 'checklist' | 'info']> = [
+ ['message', 'in_app', 'choice'],
+ ['message', 'dsa', 'choice'],
+ ['user', 'in_app', 'info'],
+ ['user', 'dsa', 'checklist'],
+ ['guild', 'dsa', 'checklist'],
];
-interface Ledger {
- active: Record<string, string>;
- retired: Record<string, string>;
-}
+const LedgerSchema = z.object({
+ active: z.record(z.string(), z.string()),
+ retired: z.record(z.string(), z.string()),
+});
+type Ledger = z.infer<typeof LedgerSchema>;
function readLedger(): Ledger {
- return JSON.parse(fs.readFileSync(LEDGER_PATH, 'utf8')) as Ledger;
+ const value: unknown = JSON.parse(fs.readFileSync(LEDGER_PATH, 'utf8'));
+ return LedgerSchema.parse(value);
+}
+
+function canonicalOutcome(outcome: ReportFlowOutcomeDef): string {
+ switch (outcome.type) {
+ case 'screen':
+ return `screen:${outcome.screenId}`;
+ case 'submit':
+ return `submit:${outcome.reason}`;
+ case 'end':
+ return outcome.noticeId === undefined ? 'end' : `end:${outcome.noticeId}`;
+ case 'link':
+ return `link:${outcome.link}`;
+ }
+}
+
+function buildReportFlowLedger(library: ReportFlowLibrary): Record<string, string> {
+ const ledger: Record<string, string> = {};
+ const variants = (['message', 'user', 'guild'] as const).flatMap((target) =>
+ (['in_app', 'dsa'] as const).map((surface) => ({target, surface})),
+ );
+ for (const {target, surface} of variants) {
+ const variant = buildReportFlowVariant(library, target, surface, HOSTED);
+ if (!variant) {
+ continue;
+ }
+ for (const screen of variant.screens.values()) {
+ const prefix = `${target}/${screen.def.id}`;
+ for (const option of screen.options) {
+ ledger[`${prefix}/${option.id}`] = canonicalOutcome(option.outcome);
+ }
+ if (screen.def.checklist) {
+ for (const item of screen.def.checklist.items) {
+ ledger[`${prefix}/${item.id}`] = item.reason === undefined ? 'item' : `item:${item.reason}`;
+ }
+ ledger[`${prefix}/#next`] = canonicalOutcome(screen.def.checklist.outcome);
+ }
+ if (screen.def.nextScreenId !== undefined) {
+ ledger[`${prefix}/#next`] = `screen:${screen.def.nextScreenId}`;
+ }
+ }
+ }
+ return Object.fromEntries(
+ Object.entries(ledger).sort(([a], [b]) => {
+ if (a < b) {
+ return -1;
+ }
+ if (a > b) {
+ return 1;
+ }
+ return 0;
+ }),
+ );
}
function findLedgerViolations(ledger: Ledger, current: Record<string, string>): Array<string> {
@@ -130,11 +198,11 @@ function variantReasons(variant: ReportFlowVariant): Set<string> {
return reasons;
}
-function resolve(target: ReportFlowTargetType, surface: ReportFlowSurface, steps: ReadonlyArray<ReportFlowStepInput>) {
+function resolve(target: ReportFlowTargetType, surface: ReportFlowSurface, steps: ReadonlyArray<ReportFlowStep>) {
return resolveReportFlowAnswers({
target,
surface,
- revisionHash: getReportFlowVariant(target, surface).revisionHash,
+ revisionHash: getReportFlowResponse(target, surface, 'en-US').revision_hash,
steps,
});
}
@@ -154,12 +222,12 @@ function captureError(run: () => unknown): FluxerError {
function expectInvalidStep(
target: ReportFlowTargetType,
surface: ReportFlowSurface,
- steps: ReadonlyArray<ReportFlowStepInput>,
+ steps: ReadonlyArray<ReportFlowStep>,
stepIndex: number,
) {
const error = captureError(() => resolve(target, surface, steps));
expect(error.code).toBe(APIErrorCodes.INVALID_REPORT_FLOW_ANSWERS);
- expect(error.status).toBe(400);
+ expect(error.status).toBe(HttpStatus.BAD_REQUEST);
expect(error.data).toEqual({step_index: stepIndex});
}
@@ -178,35 +246,39 @@ describe('report flow definitions', () => {
test('the shipped library passes every rule on every variant', () => {
expect(() => assertValidReportFlowLibrary(REPORT_FLOW_LIBRARY)).not.toThrow();
for (const instance of [HOSTED, SELF_HOSTED, SELF_HOSTED_WITH_GUIDELINES]) {
- for (const [target, surface] of VARIANTS) {
+ for (const [target, surface, expectedStartKind] of VARIANTS) {
const variant = variantOf(target, surface, REPORT_FLOW_LIBRARY, instance);
- for (const screen of variant.screens.values()) {
- const hasOptions = (screen.def.options ?? []).length > 0;
- if (screen.kind === 'checklist') {
- expect(hasOptions || screen.def.nextScreenId !== undefined).toBe(false);
- }
- if (screen.kind === 'info') {
- expect(screen.options.every((option) => option.outcome.type === 'link')).toBe(true);
- }
- if (screen.kind === 'choice') {
- expect(screen.options.some((option) => option.outcome.type !== 'link')).toBe(true);
- }
- for (const option of screen.options) {
- expect(option.id).toMatch(/^[a-z0-9_]{1,48}$/);
- if (surface === 'dsa') {
- expect(option.surface).not.toBe('in_app');
- expect(option.outcome.type === 'end' && option.outcome.noticeId === undefined).toBe(false);
- }
- }
+ const screens = [...variant.screens.values()];
+ for (const screen of screens.filter(({kind}) => kind === 'checklist')) {
+ expect((screen.def.options ?? []).length > 0 || screen.def.nextScreenId !== undefined).toBe(false);
+ }
+ for (const screen of screens.filter(({kind}) => kind === 'info')) {
+ expect(screen.options.every((option) => option.outcome.type === 'link')).toBe(true);
+ }
+ for (const screen of screens.filter(({kind}) => kind === 'choice')) {
+ expect(screen.options.some((option) => option.outcome.type !== 'link')).toBe(true);
}
- expect(variant.screens.get(variant.startScreenId)?.kind === 'info').toBe(
- target === 'user' && surface === 'in_app',
- );
+ for (const option of screens.flatMap((screen) => screen.options)) {
+ expect(option.id).toMatch(/^[a-z0-9_]{1,48}$/);
+ }
+ expect(variant.screens.get(variant.startScreenId)?.kind).toBe(expectedStartKind);
}
}
expect(buildReportFlowVariant(REPORT_FLOW_LIBRARY, 'guild', 'in_app', HOSTED)).toBeNull();
});
+ test('DSA variants omit in-app options and no-report outcomes', () => {
+ for (const instance of [HOSTED, SELF_HOSTED, SELF_HOSTED_WITH_GUIDELINES]) {
+ for (const [target, surface] of VARIANTS.filter(([, surface]) => surface === 'dsa')) {
+ const variant = variantOf(target, surface, REPORT_FLOW_LIBRARY, instance);
+ for (const option of [...variant.screens.values()].flatMap((screen) => screen.options)) {
+ expect(option.surface).not.toBe('in_app');
+ expect(option.outcome.type === 'end' && option.outcome.noticeId === undefined).toBe(false);
+ }
+ }
+ }
+ });
+
test('every screen in the library is used by a variant', () => {
const used = new Set<string>();
for (const [target, surface] of VARIANTS) {
@@ -352,7 +424,7 @@ describe('report flow walks', () => {
name: string;
target: ReportFlowTargetType;
surface?: ReportFlowSurface;
- steps: ReadonlyArray<ReportFlowStepInput>;
+ steps: ReadonlyArray<ReportFlowStep>;
reason: string;
category: string;
}> = [
@@ -718,7 +790,7 @@ describe('report flow walks', () => {
});
expect(stale.reason).toBe('spam');
expect(stale.isCurrentRevision).toBe(false);
- expect(stale.currentRevisionHash).toBe(getReportFlowVariant('message', 'in_app').revisionHash);
+ expect(stale.currentRevisionHash).toBe(getReportFlowResponse('message', 'in_app', 'en-US').revision_hash);
const outdated = captureError(() =>
resolveReportFlowAnswers({
target: 'message',
@@ -728,14 +800,13 @@ describe('report flow walks', () => {
}),
);
expect(outdated.code).toBe(APIErrorCodes.REPORT_FLOW_OUTDATED);
- expect(outdated.status).toBe(409);
+ expect(outdated.status).toBe(HttpStatus.CONFLICT);
});
test('a flow without a variant for the surface is a validation error on surface', () => {
- const error = captureError(() => getReportFlowVariant('guild', 'in_app'));
+ const error = captureError(() => getReportFlowResponse('guild', 'in_app', 'en-US'));
expect(error.code).toBe(APIErrorCodes.INVALID_FORM_BODY);
expect(JSON.stringify(error.data)).toContain('"path":"surface"');
- expect(() => getReportFlowResponse('guild', 'in_app', 'en-US')).toThrow(FluxerError);
});
});
@@ -758,11 +829,10 @@ describe('report reasons and legacy categories', () => {
});
test('child reasons are child_safety for every target', () => {
- for (const key of Object.keys(REPORT_REASONS) as Array<keyof typeof REPORT_REASONS>) {
- if (key.startsWith('minor_') || key === 'csam') {
- for (const target of ['message', 'user', 'guild'] as const) {
- expect(getLegacyCategory(key, target), key).toBe('child_safety');
- }
+ const childReasons = listReportReasons().filter(({key}) => key.startsWith('minor_') || key === 'csam');
+ for (const {key} of childReasons) {
+ for (const target of ['message', 'user', 'guild'] as const) {
+ expect(getLegacyCategory(key, target), key).toBe('child_safety');
}
}
});
@@ -820,7 +890,7 @@ describe('report flow rendering', () => {
for (const [target, surface] of VARIANTS) {
const response = getReportFlowResponse(target, surface, 'en-US');
expect(ReportFlowResponse.parse(response)).toEqual(response);
- const variant = getReportFlowVariant(target, surface);
+ const variant = variantOf(target, surface);
expect(response.start_screen_id).toBe(variant.startScreenId);
expect(response.screens.map((screen) => screen.id).sort()).toEqual([...variant.screens.keys()].sort());
expect(response.screens[0].id).toBe(response.start_screen_id);
@@ -895,7 +965,6 @@ describe('report flow rendering', () => {
expect(intro.options[0].outcome.url).toBe('https://rules.example.org/community');
const userScreens = new Map(user.screens.map((screen) => [screen.id, screen]));
expect(userScreens.get('root_user')?.options.map((option) => option.id)).not.toContain('dsa');
- expect(getReportFlowVariant('user', 'in_app').revisionHash).toBe(user.revision_hash);
resolveReportFlowAnswers({
target: 'user',
surface: 'in_app',
@@ -923,7 +992,6 @@ describe('report flow rendering', () => {
setCachedProductName('Renamed Chat');
expect(getReportFlowResponse(target, surface, 'en-US').revision_hash).toBe(hosted);
expect(getReportFlowResponse(target, surface, 'de').revision_hash).toBe(hosted);
- expect(getReportFlowVariant(target, surface).revisionHash).toBe(hosted);
}
});
});