diff --git a/.github/ISSUE_TEMPLATE/request_feature.yml b/.github/ISSUE_TEMPLATE/request_feature.yml index 1437cce4f1..a0303b2f25 100644 --- a/.github/ISSUE_TEMPLATE/request_feature.yml +++ b/.github/ISSUE_TEMPLATE/request_feature.yml @@ -33,7 +33,7 @@ body: required: true - label: I understand that app-specific features should be requested in the [app repository](https://github.com/LNReader/lnreader/issues/new/choose). required: true - - label: I have updated the app to the latest version **[1.1.19](https://github.com/LNReader/lnreader/releases/latest)**. + - label: I have updated the app to the **[latest version](https://github.com/LNReader/lnreader/releases/latest)**. required: true - label: I have provided all requested information in this form. required: true diff --git a/.github/scripts/auto-label-issue.cjs b/.github/scripts/auto-label-issue.cjs new file mode 100644 index 0000000000..f4ec58eb7b --- /dev/null +++ b/.github/scripts/auto-label-issue.cjs @@ -0,0 +1,306 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const { + VALID_SEVERITIES, + buildSelectionMatcher, + comparisonValue, + extractSection, + nonEmptySectionLines, +} = require('./issue-parsing.cjs'); + +const MAX_LABEL_LENGTH = 50; + +const LANGUAGE_ALIASES = new Map([ + // Arabic + ['arabic', 'arabic'], + ['ar', 'arabic'], + ['العربية', 'arabic'], + ['عربي', 'arabic'], + // Bengali + ['bengali', 'bengali'], + ['bangla', 'bengali'], + ['bn', 'bengali'], + ['বাংলা', 'bengali'], + // Burmese + ['burmese', 'burmese'], + ['my', 'burmese'], + ['မြန်မာ', 'burmese'], + // Chinese + ['chinese', 'chinese'], + ['zh', 'chinese'], + ['zh-cn', 'chinese'], + ['zh-tw', 'chinese'], + ['cn', 'chinese'], + ['中文', 'chinese'], + ['汉语', 'chinese'], + ['漢語', 'chinese'], + ['简体中文', 'chinese'], + ['繁體中文', 'chinese'], + // Czech + ['czech', 'czech'], + ['cs', 'czech'], + ['čeština', 'czech'], + ['cestina', 'czech'], + // Dutch + ['dutch', 'dutch'], + ['nl', 'dutch'], + ['nederlands', 'dutch'], + // Filipino / Tagalog + ['filipino', 'filipino'], + ['tagalog', 'filipino'], + ['tl', 'filipino'], + ['fil', 'filipino'], + // French + ['french', 'french'], + ['fr', 'french'], + ['français', 'french'], + ['francais', 'french'], + // German + ['german', 'german'], + ['de', 'german'], + ['deutsch', 'german'], + // Greek + ['greek', 'greek'], + ['el', 'greek'], + ['ελληνικά', 'greek'], + ['ellinika', 'greek'], + // Hebrew + ['hebrew', 'hebrew'], + ['he', 'hebrew'], + ['עברית', 'hebrew'], + // Hindi + ['hindi', 'hindi'], + ['hi', 'hindi'], + ['हिन्दी', 'hindi'], + ['हिंदी', 'hindi'], + // Indonesian + ['indonesian', 'indonesian'], + ['id', 'indonesian'], + ['bahasa indonesia', 'indonesian'], + ['indo', 'indonesian'], + // Italian + ['italian', 'italian'], + ['it', 'italian'], + ['italiano', 'italian'], + // Japanese + ['japanese', 'japanese'], + ['ja', 'japanese'], + ['jp', 'japanese'], + ['日本語', 'japanese'], + // Korean + ['korean', 'korean'], + ['ko', 'korean'], + ['kr', 'korean'], + ['한국어', 'korean'], + ['조선말', 'korean'], + // Malay + ['malay', 'malay'], + ['ms', 'malay'], + ['bahasa melayu', 'malay'], + // Persian / Farsi + ['persian', 'persian'], + ['farsi', 'persian'], + ['fa', 'persian'], + ['فارسی', 'persian'], + // Polish + ['polish', 'polish'], + ['pl', 'polish'], + ['polski', 'polish'], + // Portuguese + ['portuguese', 'portuguese'], + ['pt', 'portuguese'], + ['pt-br', 'portuguese'], + ['português', 'portuguese'], + ['portugues', 'portuguese'], + // Romanian + ['romanian', 'romanian'], + ['ro', 'romanian'], + ['română', 'romanian'], + ['romana', 'romanian'], + // Russian + ['russian', 'russian'], + ['ru', 'russian'], + ['русский', 'russian'], + // Spanish + ['spanish', 'spanish'], + ['es', 'spanish'], + ['español', 'spanish'], + ['espanol', 'spanish'], + // Thai + ['thai', 'thai'], + ['th', 'thai'], + ['ไทย', 'thai'], + ['ภาษาไทย', 'thai'], + // Turkish + ['turkish', 'turkish'], + ['tr', 'turkish'], + ['türkçe', 'turkish'], + ['turkce', 'turkish'], + // Ukrainian + ['ukrainian', 'ukrainian'], + ['uk', 'ukrainian'], + ['ua', 'ukrainian'], + ['українська', 'ukrainian'], + // Vietnamese + ['vietnamese', 'vietnamese'], + ['vi', 'vietnamese'], + ['vn', 'vietnamese'], + ['tiếng việt', 'vietnamese'], + ['tieng viet', 'vietnamese'], +]); + +const MANAGED_LANGUAGE_LABELS = new Set( + [...LANGUAGE_ALIASES.values()].map(lang => `language: ${lang}`), +); + +function resolveLanguageAlias(rawLanguage) { + if (!rawLanguage) return null; + const direct = LANGUAGE_ALIASES.get(rawLanguage); + if (direct) return direct; + const firstSegment = comparisonValue(rawLanguage.split(/[,/(]/)[0]); + return firstSegment ? LANGUAGE_ALIASES.get(firstSegment) || null : null; +} + +function formatPluginLabel(displayKey, id) { + const idx = displayKey.indexOf(': '); + const rawName = idx >= 0 ? displayKey.slice(idx + 2) : displayKey; + const name = comparisonValue(rawName); + const cleanId = comparisonValue(id); + if (!name || !cleanId) return null; + const full = `plugin: ${name}[${cleanId}]`; + if (full.length <= MAX_LABEL_LENGTH) return full; + + const suffix = `[${cleanId}]`; + const maxNameLen = MAX_LABEL_LENGTH - 'plugin: '.length - suffix.length; + if (maxNameLen >= 4) { + const truncated = name.slice(0, maxNameLen - 1).trimEnd(); + if (truncated) return `plugin: ${truncated}…${suffix}`; + } + const maxIdLen = MAX_LABEL_LENGTH - 'plugin: []'.length; + return `plugin: [${cleanId.slice(0, maxIdLen)}]`; +} + +function matchPluginLabels(lines, pluginKeys) { + if (!pluginKeys || typeof pluginKeys !== 'object' || lines.length === 0) { + return []; + } + + const entriesByKey = new Map(); + for (const [displayKey, id] of Object.entries(pluginKeys)) { + if (typeof id !== 'string') continue; + const normalizedKey = comparisonValue(displayKey); + if (!normalizedKey || !comparisonValue(id)) continue; + entriesByKey.set(normalizedKey, { displayKey, id }); + } + + const regex = buildSelectionMatcher(entriesByKey.keys()); + if (!regex) return []; + const selection = comparisonValue(lines.join(', ')); + + const labels = []; + let match; + while ((match = regex.exec(selection)) !== null) { + const entry = entriesByKey.get(match[1]); + if (!entry) continue; + const label = formatPluginLabel(entry.displayKey, entry.id); + if (label) labels.push(label); + } + return labels; +} + +function computeLabelPlan({ body, existingLabels = [], pluginKeys = {} }) { + const rawExisting = ( + Array.isArray(existingLabels) ? existingLabels : [] + ).filter(label => typeof label === 'string'); + const normalizedExisting = new Set(rawExisting.map(comparisonValue)); + + const desired = []; + const seenDesired = new Set(); + const addLabel = label => { + const normalized = comparisonValue(label); + if (!normalized || seenDesired.has(normalized)) return; + seenDesired.add(normalized); + desired.push(label); + }; + + const pluginSection = extractSection(body, 'Plugin'); + const manageBug = normalizedExisting.has('bug') && pluginSection.present; + if (manageBug) { + const severityLines = nonEmptySectionLines( + extractSection(body, 'Severity'), + ); + const rawSeverity = + severityLines.length > 0 ? comparisonValue(severityLines[0]) : ''; + const severity = VALID_SEVERITIES.has(rawSeverity) ? rawSeverity : 'other'; + addLabel(`severity: ${severity}`); + + for (const pluginLabel of matchPluginLabels( + nonEmptySectionLines(pluginSection), + pluginKeys, + )) { + addLabel(pluginLabel); + } + } + + const languageSection = extractSection(body, 'Language'); + const manageLanguage = + normalizedExisting.has('plugin request') && languageSection.present; + if (manageLanguage) { + const languageLines = nonEmptySectionLines(languageSection); + const rawLanguage = + languageLines.length > 0 ? comparisonValue(languageLines[0]) : ''; + const canonical = resolveLanguageAlias(rawLanguage); + if (canonical) { + addLabel(`language: ${canonical}`); + } + } + + const isManagedLabel = normalized => { + if ( + manageBug && + (normalized === 'plugin:' || + normalized.startsWith('plugin: ') || + normalized.startsWith('severity: ')) + ) { + return true; + } + return manageLanguage && MANAGED_LANGUAGE_LABELS.has(normalized); + }; + + const add = desired.filter( + label => !normalizedExisting.has(comparisonValue(label)), + ); + + const remove = []; + const seenRemove = new Set(); + for (const label of rawExisting) { + const normalized = comparisonValue(label); + if ( + !normalized || + !isManagedLabel(normalized) || + seenDesired.has(normalized) || + seenRemove.has(normalized) + ) { + continue; + } + seenRemove.add(normalized); + remove.push(label); + } + + return { desired, add, remove }; +} + +if (require.main === module) { + const keysPath = path.join(__dirname, 'keys.json'); + const pluginKeys = JSON.parse(fs.readFileSync(keysPath, 'utf8')); + const body = process.env.ISSUE_BODY || ''; + const existingLabels = JSON.parse(process.env.ISSUE_LABELS || '[]'); + const plan = computeLabelPlan({ body, existingLabels, pluginKeys }); + process.stdout.write( + `${JSON.stringify({ add: plan.add, remove: plan.remove })}\n`, + ); +} + +module.exports = { computeLabelPlan }; diff --git a/.github/scripts/auto-label-issue.test.cjs b/.github/scripts/auto-label-issue.test.cjs new file mode 100644 index 0000000000..4b287134db --- /dev/null +++ b/.github/scripts/auto-label-issue.test.cjs @@ -0,0 +1,445 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { execFileSync } = require('node:child_process'); + +const { computeLabelPlan } = require('./auto-label-issue.cjs'); +const { + renderIssueTemplate, +} = require('./generate-issue-template-options.cjs'); + +const pluginKeys = JSON.parse( + fs.readFileSync(path.join(__dirname, 'keys.json'), 'utf8'), +); + +test('bug issue with single English plugin and valid severity', () => { + const body = [ + '### Plugin', + '', + 'English: Novel Fire', + '', + '### Severity', + '', + "Can't Load Novels", + ].join('\n'); + + assert.deepEqual( + computeLabelPlan({ body, existingLabels: ['bug'], pluginKeys }).desired, + ["severity: can't load novels", 'plugin: novel fire[novelfire]'], + ); +}); + +test('bug issue with comma-containing Chinese and Korean plugin keys', () => { + const body = [ + '### Plugin', + '', + '中文, 汉语, 漢語: 69书吧, 조선말, 한국어: Agitoon', + '', + '### Severity', + '', + 'Wrong Formatting', + ].join('\n'); + + assert.deepEqual( + computeLabelPlan({ body, existingLabels: ['bug'], pluginKeys }).desired, + [ + 'severity: wrong formatting', + 'plugin: 69书吧[69shu]', + 'plugin: agitoon[agit.xyz]', + ], + ); +}); + +test('bug issue with Arabic plugin with or without leading LRM directional control', () => { + const withLrm = [ + '### Plugin', + '', + '\u200eالعربية: ArNovel', + '', + '### Severity', + '', + 'Missing Chapter', + ].join('\n'); + + const withoutLrm = [ + '### Plugin', + '', + 'العربية: ArNovel', + '', + '### Severity', + '', + 'Missing Chapter', + ].join('\n'); + + assert.deepEqual( + computeLabelPlan({ body: withLrm, existingLabels: ['bug'], pluginKeys }) + .desired, + ['severity: missing chapter', 'plugin: arnovel[arnovel]'], + ); + assert.deepEqual( + computeLabelPlan({ + body: withoutLrm, + existingLabels: ['bug'], + pluginKeys, + }).desired, + ['severity: missing chapter', 'plugin: arnovel[arnovel]'], + ); +}); + +test('bug issue with colon inside plugin name preserves colon after language prefix', () => { + const body = [ + '### Plugin', + '', + 'English: Re:Library', + '', + '### Severity', + '', + 'Wrong Content', + ].join('\n'); + + assert.deepEqual( + computeLabelPlan({ body, existingLabels: ['bug'], pluginKeys }).desired, + ['severity: wrong content', 'plugin: re:library[relib]'], + ); +}); + +test('bug issue with unmatched plugin or _No response_ never emits bare plugin: label', () => { + const staleBody = [ + '### Plugin', + '', + 'English: NonExistentPlugin', + '', + '### Severity', + '', + 'Unknown Severity', + ].join('\n'); + + const noResponseBody = [ + '### Plugin', + '', + '_No response_', + '', + '### Severity', + '', + '_No response_', + ].join('\n'); + + for (const body of [staleBody, noResponseBody]) { + const labels = computeLabelPlan({ + body, + existingLabels: ['bug'], + pluginKeys, + }).desired; + assert.deepEqual(labels, ['severity: other']); + assert.ok(!labels.some(label => label.trim() === 'plugin:')); + } +}); + +test('bug issue handles CRLF line endings and extra blank lines', () => { + const body = [ + '### Plugin', + '', + '', + ' English: NovelBuddy ', + '', + '### Severity', + '', + '', + ' Domain Changed ', + '', + ].join('\r\n'); + + assert.deepEqual( + computeLabelPlan({ body, existingLabels: ['bug'], pluginKeys }).desired, + ['severity: domain changed', 'plugin: novelbuddy[novelbuddy]'], + ); +}); + +test('plugin request issue maps non-English language names and native aliases', () => { + const cases = [ + ['Arabic', 'language: arabic'], + ['Vietnamese', 'language: vietnamese'], + ['Tiếng Việt', 'language: vietnamese'], + ['中文', 'language: chinese'], + ]; + + for (const [languageInput, expectedLabel] of cases) { + const body = ['### Language', '', languageInput].join('\n'); + assert.deepEqual( + computeLabelPlan({ + body, + existingLabels: ['plugin request'], + pluginKeys, + }).desired, + [expectedLabel], + ); + } +}); + +test('plugin request issue with English, Multi, empty, _No response_, or unrecognized language emits []', () => { + for (const languageInput of [ + 'English', + 'en', + 'Multi', + '', + '_No response_', + 'Please add support for this website soon', + ]) { + const body = ['### Language', '', languageInput].join('\n'); + assert.deepEqual( + computeLabelPlan({ + body, + existingLabels: ['plugin request'], + pluginKeys, + }).desired, + [], + ); + } +}); + +test('unrelated issue emits []', () => { + const body = [ + '### Feature Description', + '', + 'Add dark mode', + '', + '### Language', + '', + 'English', + ].join('\n'); + + assert.deepEqual( + computeLabelPlan({ + body, + existingLabels: ['feature request'], + pluginKeys, + }).desired, + [], + ); +}); + +test('all plugin labels in keys.json stay within GitHub 50-character limit and preserve [id]', () => { + for (const [displayKey, id] of Object.entries(pluginKeys)) { + const body = [ + '### Plugin', + '', + displayKey, + '', + '### Severity', + '', + 'Other', + ].join('\n'); + + const labels = computeLabelPlan({ + body, + existingLabels: ['bug'], + pluginKeys, + }).desired; + const pluginLabels = labels.filter(label => label.startsWith('plugin:')); + assert.equal(pluginLabels.length, 1, `Expected 1 label for ${displayKey}`); + const [pluginLabel] = pluginLabels; + assert.ok( + pluginLabel.length <= 50, + `Label too long (${pluginLabel.length}): ${pluginLabel}`, + ); + assert.match(pluginLabel, /^plugin: .*\[[^\]]+\]$/); + assert.ok(pluginLabel.includes(`[${id.toLowerCase()}]`)); + assert.notEqual(pluginLabel.trim(), 'plugin:'); + } + + const longestBody = [ + '### Plugin', + '', + "English: TaxingCorn117's Translations", + '', + '### Severity', + '', + 'Other', + ].join('\n'); + assert.deepEqual( + computeLabelPlan({ + body: longestBody, + existingLabels: ['bug'], + pluginKeys, + }).desired, + ['severity: other', 'plugin: taxingcorn117…[taxingcorn117stranslations]'], + ); + + const syntheticLongIdBody = [ + '### Plugin', + '', + 'English: Ultra Long Plugin Name', + '', + '### Severity', + '', + 'Other', + ].join('\n'); + const syntheticPlan = computeLabelPlan({ + body: syntheticLongIdBody, + existingLabels: ['bug'], + pluginKeys: { 'English: Ultra Long Plugin Name': 'a'.repeat(45) }, + }); + const syntheticPluginLabel = syntheticPlan.desired.find(label => + label.startsWith('plugin:'), + ); + assert.ok(syntheticPluginLabel); + assert.ok(syntheticPluginLabel.length <= 50); + assert.match(syntheticPluginLabel, /^plugin: .*\[[^\]]+\]$/); +}); + +test('computeLabelPlan reconciles stale labels and preserves unlisted manual language labels', () => { + const editedBugBody = [ + '### Plugin', + '', + 'English: NovelBuddy', + '', + '### Severity', + '', + 'Domain Changed', + ].join('\n'); + + assert.deepEqual( + computeLabelPlan({ + body: editedBugBody, + existingLabels: [ + 'bug', + 'severity: wrong formatting', + 'plugin: novel fire[novelfire]', + 'plugin:', + 'duplicate', + ], + pluginKeys, + }), + { + desired: ['severity: domain changed', 'plugin: novelbuddy[novelbuddy]'], + add: ['severity: domain changed', 'plugin: novelbuddy[novelbuddy]'], + remove: [ + 'severity: wrong formatting', + 'plugin: novel fire[novelfire]', + 'plugin:', + ], + }, + ); + + assert.deepEqual( + computeLabelPlan({ + body: editedBugBody, + existingLabels: [ + 'bug', + 'severity: domain changed', + 'plugin: novelbuddy[novelbuddy]', + ], + pluginKeys, + }), + { + desired: ['severity: domain changed', 'plugin: novelbuddy[novelbuddy]'], + add: [], + remove: [], + }, + ); + + assert.deepEqual( + computeLabelPlan({ + body: '### Language\n\nEnglish', + existingLabels: ['plugin request', 'language: vietnamese'], + pluginKeys, + }), + { + desired: [], + add: [], + remove: ['language: vietnamese'], + }, + ); + + assert.deepEqual( + computeLabelPlan({ + body: '### Language\n\nVietnamese (Tiếng Việt)', + existingLabels: ['plugin request', 'language: arabic'], + pluginKeys, + }), + { + desired: ['language: vietnamese'], + add: ['language: vietnamese'], + remove: ['language: arabic'], + }, + ); + + assert.deepEqual( + computeLabelPlan({ + body: '### Language\n\nSwedish', + existingLabels: ['plugin request', 'language: swedish'], + pluginKeys, + }), + { + desired: [], + add: [], + remove: [], + }, + ); +}); + +test('plugin request issue supports all expanded language aliases and delimited primary language', () => { + const cases = [ + ['Burmese', ['language: burmese']], + ['မြန်မာ', ['language: burmese']], + ['Czech', ['language: czech']], + ['Čeština', ['language: czech']], + ['Greek', ['language: greek']], + ['Hebrew', ['language: hebrew']], + ['Romanian', ['language: romanian']], + ['Hindi', ['language: hindi']], + ['Tagalog', ['language: filipino']], + ['Filipino', ['language: filipino']], + ['Bahasa Melayu', ['language: malay']], + ['Persian', ['language: persian']], + ['Dutch', ['language: dutch']], + ['Vietnamese (Tiếng Việt)', ['language: vietnamese']], + ['English / Vietnamese', []], + ]; + + for (const [languageInput, expected] of cases) { + const body = ['### Language', '', languageInput].join('\n'); + assert.deepEqual( + computeLabelPlan({ + body, + existingLabels: ['plugin request'], + pluginKeys, + }).desired, + expected, + ); + } +}); + +test('auto-label-issue CLI outputs add and remove JSON', () => { + const stdout = execFileSync( + process.execPath, + [path.join(__dirname, 'auto-label-issue.cjs')], + { + env: { + ...process.env, + ISSUE_BODY: + '### Plugin\n\nEnglish: Novel Fire\n\n### Severity\n\nMissing Chapter', + ISSUE_LABELS: JSON.stringify(['bug', 'severity: other']), + }, + encoding: 'utf8', + }, + ); + + assert.deepEqual(JSON.parse(stdout), { + add: ['severity: missing chapter', 'plugin: novel fire[novelfire]'], + remove: ['severity: other'], + }); +}); + +test('renderIssueTemplate substitutes {#CHANGE#} placeholder with YAML list options', () => { + assert.equal( + renderIssueTemplate('options:\n {#CHANGE#}\n', [ + 'English: A', + 'English: B', + ]), + 'options:\n - "English: A"\n - "English: B"\n', + ); +}); diff --git a/.github/scripts/blank_report_issue.yml b/.github/scripts/blank_report_issue.yml index 6427259f2b..603424121b 100644 --- a/.github/scripts/blank_report_issue.yml +++ b/.github/scripts/blank_report_issue.yml @@ -75,7 +75,7 @@ body: label: LNReader Version description: Find this in **More → About**. placeholder: | - Example: "2.0.0" + Example: "2.1.4" validations: required: true @@ -117,7 +117,7 @@ body: required: true - label: I have written a clear and descriptive title. required: true - - label: I have updated the app to the latest version **[2.0.0](https://github.com/LNReader/lnreader/releases/tag/v2.0.0-beta.3)**. + - label: I have updated the app to the **[latest version](https://github.com/LNReader/lnreader/releases/latest)**. required: true - label: I have updated all installed plugins to the latest version. required: true diff --git a/.github/scripts/generate-issue-index.cjs b/.github/scripts/generate-issue-index.cjs index 9cafd5b426..f2985b3de2 100644 --- a/.github/scripts/generate-issue-index.cjs +++ b/.github/scripts/generate-issue-index.cjs @@ -1,39 +1,12 @@ 'use strict'; const fs = require('node:fs'); - -const CATEGORY_CODES = new Map([ - ['wrong formatting', 1], - ['wrong content', 2], - ['missing chapter', 3], - ['missing images', 4], - ["can't load novels", 5], - ['domain changed', 6], -]); -const DIRECTIONAL_CONTROLS = /[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g; - -function comparisonValue(value) { - return value - .replace(DIRECTIONAL_CONTROLS, '') - .trim() - .toLocaleLowerCase('en-US'); -} - -function extractSection(body, name) { - const lines = (body || '').replace(/\r\n?/g, '\n').split('\n'); - const heading = new RegExp(`^\\s{0,3}###\\s+${name}\\s*#*\\s*$`, 'i'); - const start = lines.findIndex(line => - heading.test(line.replace(DIRECTIONAL_CONTROLS, '')), - ); - if (start < 0) return { present: false, lines: [] }; - let end = start + 1; - while ( - end < lines.length && - !/^\s{0,3}#{1,6}(?:\s|$)/.test(lines[end].replace(DIRECTIONAL_CONTROLS, '')) - ) - end += 1; - return { present: true, lines: lines.slice(start + 1, end) }; -} +const { + CATEGORY_CODES, + buildSelectionMatcher, + comparisonValue, + extractSection, +} = require('./issue-parsing.cjs'); function createLookups(pluginKeys) { const prototype = @@ -94,11 +67,10 @@ function resolveSelection(lines, lookups, issueNumber, warn) { .filter(Boolean) .join(', '); const normalized = comparisonValue(selection); - const alternatives = lookups.candidates - .map(candidate => candidate.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) - .join('|'); - if (!alternatives) return { ids: new Set(), unresolved: selection }; - const regex = new RegExp(`(?:^|, )(${alternatives})(?=, |$)`, 'g'); + const regex = buildSelectionMatcher( + lookups.candidates.map(candidate => candidate.value), + ); + if (!regex) return { ids: new Set(), unresolved: selection }; const ids = new Set(); const spans = []; let match; diff --git a/.github/scripts/generate-issue-index.test.cjs b/.github/scripts/generate-issue-index.test.cjs new file mode 100644 index 0000000000..bb098f13b8 --- /dev/null +++ b/.github/scripts/generate-issue-index.test.cjs @@ -0,0 +1,108 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const { + buildIssueIndex, + updateIssueIndex, +} = require('./generate-issue-index.cjs'); + +const pluginKeys = JSON.parse( + fs.readFileSync(path.join(__dirname, 'keys.json'), 'utf8'), +); + +test('buildIssueIndex resolves English, Chinese comma keys, Arabic LRM keys, and severity codes', () => { + const issues = [ + { + number: 101, + state: 'open', + labels: [{ name: 'bug' }], + body: [ + '### Plugin', + '', + 'English: Novel Fire, 中文, 汉语, 漢語: 69书吧', + '', + '### Severity', + '', + "Can't Load Novels", + ].join('\n'), + }, + { + number: 102, + state: 'open', + labels: [{ name: 'bug' }], + body: [ + '### Plugin', + '', + '\u200eالعربية: ArNovel', + '', + '### Severity', + '', + 'Wrong Formatting', + ].join('\n'), + }, + { + number: 103, + state: 'closed', + labels: [{ name: 'bug' }], + body: '### Plugin\n\nEnglish: Novel Fire\n\n### Severity\n\nOther', + }, + { + number: 104, + state: 'open', + pull_request: {}, + labels: [], + body: '### Plugin\n\nEnglish: Novel Fire\n\n### Severity\n\nOther', + }, + ]; + + const warnings = []; + assert.deepEqual( + buildIssueIndex(issues, pluginKeys, msg => warnings.push(msg)), + { + '69shu': [[5, 101]], + arnovel: [[1, 102]], + novelfire: [[5, 101]], + }, + ); + assert.deepEqual(warnings, []); +}); + +test('updateIssueIndex adds, updates, and removes open issues cleanly', () => { + const warnings = []; + const warn = msg => warnings.push(msg); + + const initial = buildIssueIndex( + [ + { + number: 201, + state: 'open', + labels: [{ name: 'bug' }], + body: '### Plugin\n\nEnglish: Novel Fire\n\n### Severity\n\nMissing Chapter', + }, + ], + pluginKeys, + warn, + ); + + const updated = updateIssueIndex( + initial, + 201, + { + number: 201, + state: 'open', + labels: [{ name: 'bug' }], + body: '### Plugin\n\nEnglish: Novel Fire\n\n### Severity\n\nDomain Changed', + }, + pluginKeys, + warn, + ); + assert.deepEqual(updated, { novelfire: [[6, 201]] }); + + const removed = updateIssueIndex(updated, 201, null, pluginKeys, warn); + assert.deepEqual(removed, {}); + assert.deepEqual(warnings, []); +}); diff --git a/.github/scripts/generate-issue-template-options.cjs b/.github/scripts/generate-issue-template-options.cjs index 8af5784764..c5c217be7f 100644 --- a/.github/scripts/generate-issue-template-options.cjs +++ b/.github/scripts/generate-issue-template-options.cjs @@ -2,12 +2,16 @@ const version = require('../../package.json').version; const dist = `plugins/v${version}`; const fs = require('fs'); -const rawText = fs.readFileSync( - '.github/scripts/blank_report_issue.yml', - 'utf8', -); +function renderIssueTemplate(rawText, keys) { + const text = keys.join('"\n - "'); + return rawText.replace(/{#CHANGE#}/g, '- "' + text + '"'); +} async function main() { + const rawText = fs.readFileSync( + '.github/scripts/blank_report_issue.yml', + 'utf8', + ); console.log(`Fetching published plugin manifest from ${dist}...`); try { @@ -41,8 +45,7 @@ async function main() { console.log('No saved plugin keys found; a new key map will be created.'); } - const text = newKeys.join('"\n - "'); - const issueTemplate = rawText.replace(/{#CHANGE#}/g, '- "' + text + '"'); + const issueTemplate = renderIssueTemplate(rawText, newKeys); const keysChanged = !sameKeys(newKeys, savedKeys) && Array.isArray(newKeys); if (keysChanged) { @@ -80,7 +83,11 @@ async function main() { } } -main().catch(err => { - console.error('Fatal error:', err); - process.exit(1); -}); +if (require.main === module) { + main().catch(err => { + console.error('Fatal error:', err); + process.exit(1); + }); +} + +module.exports = { renderIssueTemplate }; diff --git a/.github/scripts/issue-parsing.cjs b/.github/scripts/issue-parsing.cjs new file mode 100644 index 0000000000..2c12738c0e --- /dev/null +++ b/.github/scripts/issue-parsing.cjs @@ -0,0 +1,87 @@ +'use strict'; + +const DIRECTIONAL_CONTROLS = /[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g; + +const CATEGORY_CODES = new Map([ + ['wrong formatting', 1], + ['wrong content', 2], + ['missing chapter', 3], + ['missing images', 4], + ["can't load novels", 5], + ['domain changed', 6], +]); + +const VALID_SEVERITIES = new Set([...CATEGORY_CODES.keys(), 'other']); + +function stripDirectional(value) { + return String(value || '').replace(DIRECTIONAL_CONTROLS, ''); +} + +function comparisonValue(value) { + return stripDirectional(value).trim().toLocaleLowerCase('en-US'); +} + +function escapeRegExp(value) { + return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function buildSelectionMatcher(normalizedKeys) { + const sorted = [...new Set(normalizedKeys)].sort( + (a, b) => b.length - a.length || (a < b ? -1 : a > b ? 1 : 0), + ); + if (sorted.length === 0) return null; + const alternatives = sorted.map(escapeRegExp).join('|'); + return new RegExp(`(?:^|, )(${alternatives})(?=, |$)`, 'g'); +} + +function extractSection(body, headingName, boundaryHeadings) { + const lines = String(body || '') + .replace(/\r\n?/g, '\n') + .split('\n'); + const heading = new RegExp( + `^\\s{0,3}###\\s+${escapeRegExp(headingName)}\\s*#*\\s*$`, + 'i', + ); + const start = lines.findIndex(line => heading.test(stripDirectional(line))); + if (start < 0) return { present: false, lines: [] }; + + const validBoundaries = Array.isArray(boundaryHeadings) + ? [...new Set(boundaryHeadings.filter(Boolean))] + : []; + const stopHeading = + validBoundaries.length > 0 + ? new RegExp( + `^\\s{0,3}###\\s+(?:${validBoundaries.map(escapeRegExp).join('|')})\\s*#*\\s*$`, + 'i', + ) + : /^\s{0,3}#{1,6}(?:\s|$)/; + + let end = start + 1; + while ( + end < lines.length && + !stopHeading.test(stripDirectional(lines[end])) + ) { + end += 1; + } + + return { present: true, lines: lines.slice(start + 1, end) }; +} + +function nonEmptySectionLines(section) { + if (!section || !Array.isArray(section.lines)) return []; + return section.lines + .map(line => stripDirectional(line).trim()) + .filter( + line => line.length > 0 && comparisonValue(line) !== '_no response_', + ); +} + +module.exports = { + CATEGORY_CODES, + VALID_SEVERITIES, + stripDirectional, + comparisonValue, + buildSelectionMatcher, + extractSection, + nonEmptySectionLines, +}; diff --git a/.github/scripts/validate-issue-template.cjs b/.github/scripts/validate-issue-template.cjs new file mode 100644 index 0000000000..b30e2c94ee --- /dev/null +++ b/.github/scripts/validate-issue-template.cjs @@ -0,0 +1,267 @@ +'use strict'; + +const { + comparisonValue, + extractSection, + nonEmptySectionLines, + stripDirectional, +} = require('./issue-parsing.cjs'); + +const EXEMPT_ASSOCIATIONS = new Set(['owner', 'member', 'collaborator']); + +const TEMPLATES = [ + { + name: 'Report Issue', + label: 'bug', + requiredSections: [ + 'Plugin', + 'Severity', + 'Steps To Reproduce', + 'Expected Behavior', + 'Actual Behavior', + 'LNReader Version', + 'Plugin Version', + 'Android Version', + ], + optionalSections: ['Other Details'], + requiredAcknowledgements: 5, + }, + { + name: 'Request Plugin', + label: 'plugin request', + requiredSections: ['Plugin Name', 'Website URL', 'Language'], + optionalSections: ['Other Details'], + requiredAcknowledgements: 4, + }, + { + name: 'Request Feature', + label: 'feature request', + requiredSections: ['Feature Description'], + optionalSections: ['Other Details'], + requiredAcknowledgements: 5, + }, +]; + +function checkAcknowledgements(body, expectedCount, boundaryHeadings) { + const section = extractSection(body, 'Acknowledgements', boundaryHeadings); + if (!section.present) { + return ['Missing required section: `Acknowledgements`.']; + } + + let checked = 0; + let unchecked = 0; + for (const line of section.lines) { + const trimmed = stripDirectional(line).trim(); + if (/^[-*]\s+\[[xX]\]\s+\S/.test(trimmed)) { + checked += 1; + } else if (/^[-*]\s+\[\s*\]\s+\S/.test(trimmed)) { + unchecked += 1; + } + } + + if (unchecked > 0) { + return ['All required checkboxes in `Acknowledgements` must be checked.']; + } + if (checked < expectedCount) { + return [ + `Incomplete \`Acknowledgements\` section (expected at least ${expectedCount} checked items).`, + ]; + } + return []; +} + +function evaluateTemplate(body, template) { + const boundaryHeadings = [ + ...template.requiredSections, + ...template.optionalSections, + 'Acknowledgements', + ]; + let matchedSections = 0; + const missingOrEmpty = []; + + for (const heading of template.requiredSections) { + const section = extractSection(body, heading, boundaryHeadings); + if (section.present) { + matchedSections += 1; + } + if (!section.present || nonEmptySectionLines(section).length === 0) { + missingOrEmpty.push(heading); + } + } + + const reasons = []; + if (missingOrEmpty.length > 0) { + const formatted = missingOrEmpty + .map(heading => `\`${heading}\``) + .join(', '); + reasons.push(`Missing or empty required section(s): ${formatted}.`); + } + reasons.push( + ...checkAcknowledgements( + body, + template.requiredAcknowledgements, + boundaryHeadings, + ), + ); + + return { + template: template.name, + valid: reasons.length === 0, + matchedSections, + reasons, + }; +} + +function isValidAuthor(author) { + return ( + typeof author === 'string' && + /^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(author) + ); +} + +function isValidRepository(repository) { + if (typeof repository !== 'string') return false; + const parts = repository.split('/'); + if (parts.length !== 2) return false; + const [owner, repo] = parts; + return ( + isValidAuthor(owner) && + /^[a-zA-Z0-9._-]+$/.test(repo) && + repo !== '.' && + repo !== '..' + ); +} + +function buildCloseComment({ author, repository, templateName, reasons }) { + const mention = isValidAuthor(author) ? `@${author} ` : ''; + const chooseUrl = isValidRepository(repository) + ? `https://github.com/${repository}/issues/new/choose` + : ''; + + const intro = templateName + ? `${mention}this issue was automatically closed because it does not match the **${templateName}** template requirements:` + : `${mention}this issue was automatically closed because it does not follow one of the repository's issue templates:`; + + const bulletList = reasons.map(reason => `- ${reason}`).join('\n'); + const instructions = chooseUrl + ? `Please open a new issue using one of the [issue templates](${chooseUrl}) and fill out all required fields.` + : "Please open a new issue using one of the repository's issue templates and fill out all required fields."; + + return [ + intro, + '', + bulletList, + '', + instructions, + '', + '*If you believe this was closed in error, please comment below so a maintainer can review and reopen it.*', + ].join('\n'); +} + +function makeResult({ + shouldClose = false, + skipped = null, + template = null, + reasons = [], + comment = '', +} = {}) { + return { shouldClose, skipped, template, reasons, comment }; +} + +function evaluateCandidates(body, candidates) { + const evaluations = candidates.map(template => + evaluateTemplate(body, template), + ); + const validMatch = evaluations.find(evaluation => evaluation.valid); + if (validMatch) { + return { valid: validMatch, best: null }; + } + + evaluations.sort( + (a, b) => + b.matchedSections - a.matchedSections || + a.reasons.length - b.reasons.length, + ); + return { valid: null, best: evaluations[0] || null }; +} + +function validateIssueTemplate({ + body = '', + labels = [], + author = '', + authorAssociation = '', + authorType = '', + state = 'open', + repository = '', +} = {}) { + if (comparisonValue(state) !== 'open') { + return makeResult({ skipped: 'not-open' }); + } + + if ( + EXEMPT_ASSOCIATIONS.has(comparisonValue(authorAssociation)) || + comparisonValue(authorType) === 'bot' + ) { + return makeResult({ skipped: 'exempt-author' }); + } + + const normalizedLabels = new Set( + (Array.isArray(labels) ? labels : []) + .filter(label => typeof label === 'string') + .map(comparisonValue) + .filter(Boolean), + ); + + const labeledTemplates = TEMPLATES.filter(template => + normalizedLabels.has(template.label), + ); + const candidates = labeledTemplates.length > 0 ? labeledTemplates : TEMPLATES; + + const { valid, best } = evaluateCandidates(body, candidates); + if (valid) { + return makeResult({ template: valid.template }); + } + + if (best && (labeledTemplates.length > 0 || best.matchedSections > 0)) { + return makeResult({ + shouldClose: true, + template: best.template, + reasons: best.reasons, + comment: buildCloseComment({ + author, + repository, + templateName: best.template, + reasons: best.reasons, + }), + }); + } + + const reasons = [ + "The issue body does not use one of the repository's issue templates (Report Issue, Request Plugin, or Request Feature).", + ]; + return makeResult({ + shouldClose: true, + reasons, + comment: buildCloseComment({ + author, + repository, + templateName: null, + reasons, + }), + }); +} + +if (require.main === module) { + const result = validateIssueTemplate({ + body: process.env.ISSUE_BODY || '', + labels: JSON.parse(process.env.ISSUE_LABELS || '[]'), + author: process.env.ISSUE_AUTHOR || '', + authorAssociation: process.env.ISSUE_AUTHOR_ASSOCIATION || '', + authorType: process.env.ISSUE_AUTHOR_TYPE || '', + state: process.env.ISSUE_STATE || 'open', + repository: process.env.REPOSITORY || '', + }); + process.stdout.write(`${JSON.stringify(result)}\n`); +} + +module.exports = { TEMPLATES, validateIssueTemplate }; diff --git a/.github/scripts/validate-issue-template.test.cjs b/.github/scripts/validate-issue-template.test.cjs new file mode 100644 index 0000000000..8bcc1835be --- /dev/null +++ b/.github/scripts/validate-issue-template.test.cjs @@ -0,0 +1,553 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { execFileSync } = require('node:child_process'); + +const { + TEMPLATES, + validateIssueTemplate, +} = require('./validate-issue-template.cjs'); + +const VALID_REPORT_ISSUE_BODY = [ + '### Plugin', + '', + 'English: Ranobes', + '', + '### Severity', + '', + "Can't Load Novels", + '', + '### Steps To Reproduce', + '', + 'chapter list wont load', + '', + '### Expected Behavior', + '', + 'it should load chapter list', + '', + '### Actual Behavior', + '', + 'its just empty cant see the chapters', + '', + '### LNReader Version', + '', + '2.1.4', + '', + '### Plugin Version', + '', + '2.0.3', + '', + '### Android Version', + '', + '13', + '', + '### Other Details', + '', + '_No response_', + '', + '### Acknowledgements', + '', + '- [x] I have searched existing issues and confirmed this is not a duplicate.', + '- [x] I have written a clear and descriptive title.', + '- [x] I have updated the app to the **[latest version](https://github.com/LNReader/lnreader/releases/latest)**.', + '- [x] I have updated all installed plugins to the latest version.', + '- [x] I understand that app-specific issues should be reported in the [app repository](https://github.com/LNReader/lnreader/issues/new/choose).', +].join('\n'); + +const VALID_PLUGIN_REQUEST_BODY = [ + '### Plugin Name', + '', + 'Puffberry', + '', + '### Website URL', + '', + 'https://example.com', + '', + '### Language', + '', + 'English', + '', + '### Other Details', + '', + '_No response_', + '', + '### Acknowledgements', + '', + '- [x] I have searched existing issues and confirmed this plugin has not been requested before.', + '- [x] I have used the plugin name as the issue title.', + '- [x] I have verified this plugin does not already exist in the [repository](https://github.com/LNReader/lnreader-plugins).', + '- [X] I have provided all requested information in this form.', +].join('\n'); + +const VALID_FEATURE_REQUEST_BODY = [ + '### Feature Description', + '', + 'Add a toggle to hide disabled books.', + '', + '### Other Details', + '', + '_No response_', + '', + '### Acknowledgements', + '', + '- [x] I have searched existing issues and confirmed this is not a duplicate.', + '- [x] I have written a clear and descriptive title.', + '- [x] I understand that app-specific features should be requested in the [app repository](https://github.com/LNReader/lnreader/issues/new/choose).', + '- [x] I have updated the app to the **[latest version](https://github.com/LNReader/lnreader/releases/latest)**.', + '- [x] I have provided all requested information in this form.', +].join('\n'); + +function parseIssueTemplateSchema(filePath) { + const lines = fs + .readFileSync(filePath, 'utf8') + .replace(/\r\n?/g, '\n') + .split('\n'); + let label = null; + const requiredSections = []; + const optionalSections = []; + let requiredAcknowledgements = 0; + + let inBody = false; + let currentType = null; + let currentLabel = null; + let currentRequired = false; + let inValidations = false; + let inOptions = false; + + const flushBlock = () => { + if ( + currentType && + currentType !== 'markdown' && + currentType !== 'checkboxes' && + currentLabel + ) { + if (currentRequired) { + requiredSections.push(currentLabel); + } else { + optionalSections.push(currentLabel); + } + } + currentType = null; + currentLabel = null; + currentRequired = false; + inValidations = false; + inOptions = false; + }; + + for (const line of lines) { + const topLabelMatch = /^labels:\s*\[([^\]]+)\]/.exec(line); + if (topLabelMatch) { + label = topLabelMatch[1].split(',')[0].trim().toLowerCase(); + continue; + } + if (/^body:\s*$/.test(line)) { + inBody = true; + continue; + } + if (!inBody) continue; + + const itemMatch = /^ {2}- type:\s*(\S+)/.exec(line); + if (itemMatch) { + flushBlock(); + currentType = itemMatch[1]; + continue; + } + + const labelMatch = /^ {6}label:\s*(.+)$/.exec(line); + if (labelMatch && !inOptions) { + currentLabel = labelMatch[1].trim(); + continue; + } + + if (/^ {4}validations:\s*$/.test(line)) { + inValidations = true; + inOptions = false; + continue; + } + if (/^ {6}options:\s*$/.test(line)) { + inOptions = true; + inValidations = false; + continue; + } + if (/^ {4}[a-z]+:/.test(line)) { + inValidations = false; + inOptions = false; + } + + if (inValidations && /^\s+required:\s*true\s*$/.test(line)) { + currentRequired = true; + } + if ( + currentType === 'checkboxes' && + inOptions && + /^\s+required:\s*true\s*$/.test(line) + ) { + requiredAcknowledgements += 1; + } + } + flushBlock(); + + return { + label, + requiredSections, + optionalSections, + requiredAcknowledgements, + }; +} + +test('valid Report Issue, Request Plugin, and Request Feature pass validation', () => { + const cases = [ + { + body: VALID_REPORT_ISSUE_BODY.replace(/\n/g, '\r\n'), + labels: ['bug'], + expectedTemplate: 'Report Issue', + }, + { + body: VALID_PLUGIN_REQUEST_BODY, + labels: ['plugin request'], + expectedTemplate: 'Request Plugin', + }, + { + body: VALID_FEATURE_REQUEST_BODY, + labels: ['feature request'], + expectedTemplate: 'Request Feature', + }, + ]; + + for (const { body, labels, expectedTemplate } of cases) { + const result = validateIssueTemplate({ + body, + labels, + author: 'reader123', + authorAssociation: 'NONE', + repository: 'lnreader/lnreader-plugins', + }); + assert.equal(result.shouldClose, false); + assert.equal(result.template, expectedTemplate); + assert.deepEqual(result.reasons, []); + assert.equal(result.comment, ''); + } +}); + +test('valid unlabeled issue matching a template passes validation', () => { + const result = validateIssueTemplate({ + body: VALID_FEATURE_REQUEST_BODY, + labels: [], + author: 'reader123', + authorAssociation: 'NONE', + repository: 'lnreader/lnreader-plugins', + }); + assert.equal(result.shouldClose, false); + assert.equal(result.template, 'Request Feature'); +}); + +test('blank body and freeform body with no labels are closed with template link', () => { + for (const body of [ + '', + 'I cannot load the content but i can access the content from webview', + ]) { + const result = validateIssueTemplate({ + body, + labels: [], + author: 'some-user', + authorAssociation: 'NONE', + repository: 'lnreader/lnreader-plugins', + }); + assert.equal(result.shouldClose, true); + assert.equal(result.template, null); + assert.ok(result.comment.includes('@some-user ')); + assert.ok( + result.comment.includes( + 'https://github.com/lnreader/lnreader-plugins/issues/new/choose', + ), + ); + } +}); + +test('bug issue with missing heading or _No response_ in required field is closed with specific reasons', () => { + const brokenBody = VALID_REPORT_ISSUE_BODY.replace( + '### Plugin\n\nEnglish: Ranobes', + '### Plugin\n\n_No response_', + ).replace('### Android Version\n\n13\n\n', ''); + + const result = validateIssueTemplate({ + body: brokenBody, + labels: ['bug'], + author: 'reader123', + authorAssociation: 'NONE', + repository: 'lnreader/lnreader-plugins', + }); + + assert.equal(result.shouldClose, true); + assert.equal(result.template, 'Report Issue'); + assert.ok( + result.reasons.some( + reason => + reason.includes('`Plugin`') && reason.includes('`Android Version`'), + ), + ); + assert.ok(result.comment.includes('**Report Issue**')); +}); + +test('plugin request issue with unchecked box in Acknowledgements is closed', () => { + const uncheckedBody = VALID_PLUGIN_REQUEST_BODY.replace( + '- [x] I have used the plugin name as the issue title.', + '- [ ] I have used the plugin name as the issue title.', + ); + + const result = validateIssueTemplate({ + body: uncheckedBody, + labels: ['plugin request'], + author: 'reader123', + authorAssociation: 'NONE', + }); + + assert.equal(result.shouldClose, true); + assert.equal(result.template, 'Request Plugin'); + assert.ok( + result.reasons.some(reason => + reason.includes('All required checkboxes in `Acknowledgements`'), + ), + ); +}); + +test('feature request issue with missing or plain-text Acknowledgements is closed', () => { + const fewerBoxes = VALID_FEATURE_REQUEST_BODY.replace( + '- [x] I have provided all requested information in this form.', + '', + ); + const plainTextAck = VALID_FEATURE_REQUEST_BODY.replace( + /### Acknowledgements[\s\S]*$/, + '### Acknowledgements\n\nYes I agree', + ); + + for (const body of [fewerBoxes, plainTextAck]) { + const result = validateIssueTemplate({ + body, + labels: ['feature request'], + author: 'reader123', + authorAssociation: 'NONE', + }); + assert.equal(result.shouldClose, true); + assert.equal(result.template, 'Request Feature'); + assert.ok( + result.reasons.some(reason => + reason.includes('expected at least 5 checked items'), + ), + ); + } +}); + +test('unlabeled partial template reports specific missing sections for matched template', () => { + const partialBug = [ + '### Plugin', + '', + 'English: Ranobes', + '', + '### Severity', + '', + "Can't Load Novels", + ].join('\n'); + + const result = validateIssueTemplate({ + body: partialBug, + labels: [], + author: 'reader123', + authorAssociation: 'NONE', + }); + + assert.equal(result.shouldClose, true); + assert.equal(result.template, 'Report Issue'); + assert.ok( + result.reasons.some(reason => reason.includes('`Steps To Reproduce`')), + ); +}); + +test('exempt authors (OWNER, MEMBER, COLLABORATOR, Bot) are skipped even with blank body', () => { + for (const [authorAssociation, authorType] of [ + ['OWNER', 'User'], + ['MEMBER', 'User'], + ['COLLABORATOR', 'User'], + ['NONE', 'Bot'], + ]) { + const result = validateIssueTemplate({ + body: '', + labels: [], + author: 'maintainer', + authorAssociation, + authorType, + }); + assert.equal(result.shouldClose, false); + assert.equal(result.skipped, 'exempt-author'); + } +}); + +test('already closed issues are skipped', () => { + const result = validateIssueTemplate({ + body: '', + labels: [], + state: 'closed', + author: 'reader123', + authorAssociation: 'NONE', + }); + assert.equal(result.shouldClose, false); + assert.equal(result.skipped, 'not-open'); +}); + +test('invalid or unsafe author login is omitted instead of interpolated', () => { + const result = validateIssueTemplate({ + body: '', + labels: [], + author: 'bad user @everyone\n