Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/projections/self-topology/releases.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ export function actionScripts(text) {

/** A TOML array's strings: `key = ["a", "b"]` (on one or more lines) in `text`, or undefined when absent. */
export function tomlList(text, key) {
const match = new RegExp(`^\\s*${key.replace(/[-]/g, '\\-')}\\s*=\\s*\\[([^\\]]*)\\]`, 'm').exec(text)
const literal = key.replace(/[\\^$.*+?()[\]{}|/-]/g, '\\$&')
const match = new RegExp(`^\\s*${literal}\\s*=\\s*\\[([^\\]]*)\\]`, 'm').exec(text)
return match ? [...match[1].matchAll(/["']([^"']+)["']/g)].map(([, value]) => value) : undefined
}

Expand Down
10 changes: 9 additions & 1 deletion .github/projections/self-topology/releases.test.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// node --test .github/projections/self-topology/
import {test} from 'node:test'
import assert from 'node:assert/strict'
import {releaseChannels} from './releases.mjs'
import {releaseChannels, tomlList} from './releases.mjs'

const crate = {id: 'crate:tool', kind: 'rust-crate', root: '', directory: 'tool', data: {package: 'tool', targets: ['bin']}}
const extension = {id: 'npm:ext', kind: 'npm-package', root: '', directory: 'ext', meta: {vscode: true}, data: {}}
Expand Down Expand Up @@ -51,3 +51,11 @@ ${condition} steps:
assert.deepEqual(inert, {})
assert.deepEqual(channels({'.github/workflows/publish.yml': publish()}), {'npm:sdk': ['npm'], 'npm:ext': ['Marketplace']})
})

test('a TOML list is found by its literal key', () => {
const text = 'a.b = ["dot"]\naxb = ["any"]\npublish-jobs = ["./npm", \'homebrew\']\n'
assert.deepEqual(tomlList(text, 'a.b'), ['dot'])
assert.deepEqual(tomlList('axb = ["any"]', 'a.b'), undefined)
assert.deepEqual(tomlList(text, 'publish-jobs'), ['./npm', 'homebrew'])
assert.equal(tomlList(text, 'a\\'), undefined)
})
6 changes: 3 additions & 3 deletions packages/cli/tests/comparator_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -397,8 +397,8 @@ fn revision_cases_extract_with_the_working_tree_definition_or_are_skipped() {
fs::write(root.join(".projections/deps.json"), serde_json::to_vec(&definition).unwrap()).unwrap();
git(root, &["add", "."]);
git(root, &["commit", "--quiet", "-m", "Extractor"]);
let (trusted, _) = step(root, "deps", &["--trust"]);
assert_eq!(trusted["status"], "pass", "{trusted}");
assert_eq!(trusted["message"], "2 cases pass");
let (with_trust, _) = step(root, "deps", &["--trust"]);
assert_eq!(with_trust["status"], "pass", "{with_trust}");
assert_eq!(with_trust["message"], "2 cases pass");
}
}
18 changes: 15 additions & 3 deletions packages/integrations/vscode/scripts/docs.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,20 @@ const withoutCode = text =>
.replace(/^[ \t]*(```|~~~)[^\n]*\n[\s\S]*?^[ \t]*\1[ \t]*$/gm, block => block.replace(/[^\n]/g, ' '))
.replace(/(`+)(?!`)[\s\S]*?(?<!`)\1(?!`)/g, span => span.replace(/[^\n]/g, ' '))

/** The text outside HTML tags, in one pass: each `<…>` with something inside is dropped; a `<` that closes nothing stays. */
function withoutTags(text) {
let result = ''
let index = 0
for (;;) {
const open = text.indexOf('<', index)
const close = open < 0 ? -1 : text.indexOf('>', open + 1)
if (close < 0) return result + text.slice(index)
// `<>` is text, not a tag.
result += close === open + 1 ? text.slice(index, close + 1) : text.slice(index, open)
index = close + 1
}
}

/** A page's anchors: its headings' slugs (repeats numbered) and HTML `id`s. */
export function anchors(text) {
const found = new Set()
Expand All @@ -114,9 +128,7 @@ export function anchors(text) {
.slice(match.index, match.index + match[0].length)
.replace(/^#{1,6} +/, '')
.replace(/[ \t]*#*[ \t]*$/, '')
const plain = heading
.replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
.replace(/<[^>]+>/g, '')
const plain = withoutTags(heading.replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1'))
.replace(/`([^`]*)`/g, '$1')
.replace(/(\*\*|__)(.*?)\1/g, '$2')
.trim()
Expand Down
7 changes: 7 additions & 0 deletions packages/integrations/vscode/test/build.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,13 @@ test('every link in the bundle must open in the preview: a bundled page and its
])
})

test('heading anchors drop HTML tags but keep a lone `<`, in linear time', () => {
assert.deepEqual([...anchors('# The <code>x</code> extractor\n\n## a < b\n')], ['the-x-extractor', 'a--b'])
const started = performance.now()
anchors(`# ${'<'.repeat(100_000)}\n`)
assert.ok(performance.now() - started < 1000, `took ${Math.round(performance.now() - started)} ms`)
})

test("the repository's bundle: every built-in extractor and renderer handle has a page, and every page links within it or to GitHub", async () => {
const root = fileURLToPath(new URL('../../../../', import.meta.url))
const {pages, index} = await planDocs(root)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {createRulesRuntime} from '@githubnext/projections-comparator-runtime'
import {buildModel, entries, findingsOf} from '../node_modules/.cache/test/model.js'
import {agenticWorkflowsFacts} from '../node_modules/.cache/test/summary.js'
import {AgenticWorkflowsView} from '../node_modules/.cache/test/view.js'
import {plain} from '../../kit/test/markup.mjs'

const runtime = createRulesRuntime()
const rules = new Uint8Array(
Expand All @@ -17,17 +18,6 @@ const fixture = name =>
JSON.parse(readFileSync(new URL(`../../../extractors/github-agentic-workflows/tests/fixtures/${name}`, import.meta.url), 'utf8'))
const before = fixture('docs-bot/before.expected.json')
const after = fixture('docs-bot/after.expected.json')
/** The text of rendered markup: everything outside its tags. */
function plain(markup) {
let text = ''
let inTag = false
for (const char of markup) {
if (char === '<') inTag = true
else if (char === '>') inTag = false
else if (!inTag) text += char
}
return text
}

// The agentic-workflows rules, run in the rules interpreter as hosts run them.
const interpreted = (a = before, b = after) => runtime.compare(rules, {protocolVersion: 0, before: a, after: b, baseline: {}, options: {}})
Expand Down
8 changes: 4 additions & 4 deletions packages/renderers/api/test/api.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {compatibilityOf} from '../node_modules/.cache/test/compatibility.js'
import {changesFirst, comparisonRows, qualifiedNames, readableId, revisionRows} from '../node_modules/.cache/test/model.js'
import {signatureLayout, signatureSegments, signatureTokens} from '../node_modules/.cache/test/signature.js'
import {ApiView} from '../node_modules/.cache/test/view.js'
import {plain} from '../../kit/test/markup.mjs'

const engine = createNativeEngine()
const api = entities => ({protocolVersion: 0, schema: 'api/v0', entities, relationships: []})
Expand Down Expand Up @@ -62,7 +63,7 @@ const render = p => renderToStaticMarkup(createElement(ApiView, p))
const footer = '<div class="pk-change-footer api-declaration-footer" data-change-footer=""></div>'
/** A row's footer status text: the word per part (icons carry no text), empty for an unchanged row. */
const statusOf = body =>
(/<div class="pk-change-footer api-declaration-footer" data-change-footer="">(.*?)<\/div>/.exec(body)?.[1] ?? '').replace(/<[^>]+>/g, '')
plain(/<div class="pk-change-footer api-declaration-footer" data-change-footer="">(.*?)<\/div>/.exec(body)?.[1] ?? '')
const rowsOf = markup =>
Object.fromEntries(
[...markup.matchAll(/<section [^>]*data-entity-id="([^"]+)"[^>]*>(.*?)<\/section>/g)].map(([, id, body]) => [id, body]),
Expand Down Expand Up @@ -206,7 +207,7 @@ test('a nested declaration is named as code spells it, not by its encoded ID', a
const model = await comparison(member('headers'), member('headers'))
const html = render(props(model, {diff: true}))
assert.match(html, /<code class="semantic-id"[^>]*>Response\.headers<\/code>/)
assert.doesNotMatch(html.replace(/<[^>]*>/g, ''), /%3A/)
assert.doesNotMatch(plain(html), /%3A/)
// A top-level declaration's name is its label, so no second line repeats it.
assert.equal(html.match(/class="semantic-id"/g).length, 1)
})
Expand Down Expand Up @@ -296,8 +297,7 @@ async function classified(options = {}, metadata = {compatibility}) {
const model = await comparison()
return {...props(model, options), init: {mode: 'comparison', comparison: {metadata}}}
}
const compatibilityOfRow = body =>
(/<span class="api-compatibility [a-z]+"[^>]*>(.*?)<\/span><\/div>/.exec(body)?.[1] ?? '').replace(/<[^>]+>/g, '')
const compatibilityOfRow = body => plain(/<span class="api-compatibility [a-z]+"[^>]*>(.*?)<\/span><\/div>/.exec(body)?.[1] ?? '')

test('a classified diff keeps its notices, lists breaking changes first and states each level with its reason', async () => {
const markup = render(await classified({diff: true}))
Expand Down
3 changes: 2 additions & 1 deletion packages/renderers/code-statistics/test/diff.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {codeStatisticsFacts, codeStatisticsNouns} from '../node_modules/.cache/t
import {signed} from '../node_modules/.cache/test/timeline.js'
import {compared} from './engine.mjs'
import {loadPair} from './fixtures.mjs'
import {plain} from '../../kit/test/markup.mjs'

/** Diff mode as the shell presents it: one static frame at progress 1 with no schedule. */
async function renderDiff(scenario, overrides = {}) {
Expand Down Expand Up @@ -56,7 +57,7 @@ async function barSentence(scenario, controls = {}) {
const facts = codeStatisticsFacts({init, model, controls, rendererName: 'code-statistics'})
return {sentence: summarySentence(rendererSummary(init, codeStatisticsNouns, facts).items, 'en-US'), before, after, comparison}
}
const words = html => html.replace(/<span class="sr-only">.*?<\/span>/g, '').replace(/<[^>]+>/g, '')
const words = html => plain(html.replace(/<span class="sr-only">.*?<\/span>/g, ''))
/** Each bar row's markup, by entity ID. */
const rows = html =>
new Map(
Expand Down
3 changes: 2 additions & 1 deletion packages/renderers/database/test/types.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {createNativeEngine} from '@githubnext/projections-engine/native'
import {comparisonModel, scheduleSteps} from '@githubnext/projections-renderer-kit'
import {columnType, declaredType, typeChange} from '../node_modules/.cache/test/types.js'
import {DatabaseRenderer} from '../node_modules/.cache/test/view.js'
import {plain} from '../../kit/test/markup.mjs'

const fixture = name => JSON.parse(readFileSync(new URL(`../fixtures/${name}.json`, import.meta.url), 'utf8'))
const column = data => ({id: 'c', kind: 'column', label: 'c', data})
Expand Down Expand Up @@ -75,7 +76,7 @@ test('real Prisma and Django retypes read as type changes', async () => {
)
assert.ok(html.includes(`Modified, type ${from} to ${to}`), `${id} in the markup`)
// Types are drawn whole, in pieces the browser may wrap between.
const shown = [...html.matchAll(/<code[^>]*>(.*?)<\/code>/g)].map(match => match[1].replace(/<[^>]+>/g, ''))
const shown = [...html.matchAll(/<code[^>]*>(.*?)<\/code>/g)].map(match => plain(match[1]))
assert.ok(shown.includes(to), `${id} shows ${to}`)
}
})
2 changes: 1 addition & 1 deletion packages/renderers/kit/test/diff.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ import {
} from '../dist/index.js'
import {ChangePills, SvgValueChange, ValueChange} from '../dist/react.js'
import {compare, entity, extraction, relationship} from './engine.mjs'
import {plain} from './markup.mjs'

const html = node => renderToStaticMarkup(node)
const plain = markup => markup.replace(/<[^>]+>/g, '')

async function rewired() {
const before = extraction(
Expand Down
2 changes: 1 addition & 1 deletion packages/renderers/kit/test/group.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import {readFileSync} from 'node:fs'
import {createElement} from 'react'
import {renderToStaticMarkup} from 'react-dom/server'
import {Group} from '../dist/react.js'
import {plain} from './markup.mjs'

const html = (props, children = createElement('table', {className: 'body'})) => renderToStaticMarkup(createElement(Group, props, children))
const plain = markup => markup.replace(/<[^>]+>/g, '')

test('a group is a titled panel: a heading inside its header band labels the section, then its body', () => {
const markup = html({title: 'Policies'})
Expand Down
13 changes: 13 additions & 0 deletions packages/renderers/kit/test/markup.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Shared by the renderers' unit tests: reading rendered markup as text.

/** The text of rendered markup: everything outside its tags, found in one pass. */
export function plain(markup) {
let text = ''
let inTag = false
for (const character of markup) {
if (character === '<') inTag = true
else if (character === '>') inTag = false
else if (!inTag) text += character
}
return text
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import {buildModel} from '../node_modules/.cache/test/build.js'
import {chipPrefix, conditionLines, effectProse, warnings} from '../node_modules/.cache/test/prose.js'
import {findingLabels, interpretationIcons} from '../node_modules/.cache/test/model.js'

const plain = markup => markup.replace(/<[^>]+>/g, '')
import {RuntimePolicyView} from '../node_modules/.cache/test/view.js'
import {plain} from '../../kit/test/markup.mjs'

const engine = createNativeEngine()
const runtime = createRulesRuntime()
Expand Down
17 changes: 15 additions & 2 deletions packages/renderers/sdk/build/notices.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,17 @@ const licenseFile = /^(licen[cs]e|copying|notice)([-_.].*)?$/i
// Licenses whose binary-form distribution must say where the source is.
const sourceRequired = /\b(EPL|MPL|LGPL|GPL|CDDL|EUPL|CPL)\b/

/** An SPDX expression's first `OR` alternative, without parentheses: `(MPL-2.0 OR Apache-2.0)` is MPL-2.0. */
function firstAlternative(expression) {
const words = expression.split(/\s+/)
const or = words.indexOf('OR', 1)
return words
.slice(0, or < 0 ? undefined : or)
.join(' ')
.replace(/[()]/g, '')
.trim()
}

/**
* The npm packages among a bundle's module IDs (as Rollup or esbuild report
* them, with or without plugin prefixes and queries), except this
Expand All @@ -28,7 +39,9 @@ const sourceRequired = /\b(EPL|MPL|LGPL|GPL|CDDL|EUPL|CPL)\b/
export function bundledPackages(moduleIds) {
const found = new Map()
for (const id of moduleIds) {
const file = id.replace(/^\0/, '').replace(/\?.*$/, '')
const unprefixed = id.replace(/^\0/, '')
const query = unprefixed.indexOf('?')
const file = query < 0 ? unprefixed : unprefixed.slice(0, query)
const match = packageRoot.exec(file)
// Vendored data is attributed wherever it is, including inside an installed package (`@githubnext/projections`
// ships the SDK's `vendor/linguist` beside its bundles).
Expand Down Expand Up @@ -112,7 +125,7 @@ export function packageNotice(entry) {
if (copyleft) {
const source = repository(entry.directory)
if (!source) throw new Error(`Bundled package ${entry.name}@${entry.version} (${entry.license}) declares no repository for its source`)
const elected = entry.license.split(/\s+OR\s+/)[0].replace(/[()]/g, '')
const elected = firstAlternative(entry.license)
lines.push(`Distributed under ${elected}. Source: ${source}/tree/${entry.version}, unmodified.`)
}
// Copyleft packages are attributed from every script they publish, not just those bundled.
Expand Down
27 changes: 26 additions & 1 deletion packages/renderers/sdk/test/notices.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {tmpdir} from 'node:os'
import {join} from 'node:path'
import {fileURLToPath} from 'node:url'
import {build, loadConfigFromFile} from 'vite'
import {bundleNotices, bundledPackages, mergeNotices, noticeSections} from '../build/notices.mjs'
import {bundleNotices, bundledPackages, mergeNotices, noticeSections, packageNotice} from '../build/notices.mjs'
import {rendererConfig} from '../dist/vite.js'

const workspace = fileURLToPath(new URL('../../../../', import.meta.url))
Expand Down Expand Up @@ -138,3 +138,28 @@ test('vendored data is attributed inside an installed package too, and @githubne
await rm(root, {recursive: true, force: true})
}
})

test('module ID queries and SPDX alternatives are read in linear time', async () => {
const root = await mkdtemp(join(tmpdir(), 'projections-notices-'))
try {
const directory = join(root, 'node_modules/elected')
await mkdir(directory, {recursive: true})
await writeFile(
join(directory, 'package.json'),
JSON.stringify({name: 'elected', version: '1.0.0', license: 'MPL-2.0', repository: 'git+https://example.com/elected.git'}),
)
await writeFile(join(directory, 'LICENSE'), 'MPL text')
assert.deepEqual(
bundledPackages([`\0${join(directory, 'index.js')}?commonjs-proxy?x`]).map(entry => entry.name),
['elected'],
)
const entry = license => ({name: 'elected', version: '1.0.0', license, directory, files: []})
assert.match(packageNotice(entry('(MPL-2.0 OR Apache-2.0)')), /Distributed under MPL-2\.0\. Source/)
const started = performance.now()
assert.deepEqual(bundledPackages([`${'?'.repeat(100_000)}\n`]), [])
assert.match(packageNotice(entry(`MPL-2.0${' '.repeat(100_000)}x`)), /Distributed under MPL-2\.0 x\. Source/)
assert.ok(performance.now() - started < 1000, `took ${Math.round(performance.now() - started)} ms`)
} finally {
await rm(root, {recursive: true, force: true})
}
})
3 changes: 2 additions & 1 deletion packages/renderers/testing/playwright/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,8 @@ export async function startInspector(options: InspectorOptions): Promise<Fixture
)
send(response, result.status, result.contentType || 'application/octet-stream', payload(result), result.headers)
} catch (error) {
if (!aborted.signal.aborted) send(response, 502, 'text/plain', error instanceof Error ? error.message : String(error))
// The message only: the backend's errors and a bad body say what went wrong, and a stack says nothing more.
if (!aborted.signal.aborted) send(response, 502, 'text/plain', error instanceof Error ? error.message : 'The request failed')
}
})()
})
Expand Down
9 changes: 5 additions & 4 deletions packages/renderers/text-diff/test/view.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {outputDiff, wordDiff} from '../node_modules/.cache/test/rows.js'
import {readOutput, validateModel} from '../node_modules/.cache/test/model.js'
import {segments} from '../node_modules/.cache/test/folding.js'
import {outputOrder, TextDiffView} from '../node_modules/.cache/test/view.js'
import {plain} from '../../kit/test/markup.mjs'

const engine = createNativeEngine()
const graph = entities => ({protocolVersion: 0, schema: 'graph/v0', entities, relationships: []})
Expand Down Expand Up @@ -180,13 +181,13 @@ test("each changed output states its status as text in a reserved cell at its he
const {model} = await comparison()
const markup = render(props(model, 1))
const status = id =>
markup
.match(
plain(
markup.match(
new RegExp(
`<section[^>]*data-entity-id="${id}"[^>]*><header class="pk-group-header">.*?<span class="pk-change-status pk-group-status"[^>]*>(.*?)</span></header>`,
),
)[1]
.replace(/<[^>]+>/g, '')
)[1],
)
assert.deepEqual(['report', 'gone', 'new', 'help'].map(status), ['Modified', 'Removed', 'Added', ''])
assert.match(markup, /--pk-status-width:11ch/)
})
Expand Down
2 changes: 1 addition & 1 deletion tools/cli/src/lib/link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ export function launcherText(path: string, launcher: Launcher, platform: Platfor
`checkout=${shellQuote(launcher.checkout)}`,
`node=${shellQuote(launcher.node)}`,
'if [ ! -f "$checkout/tools/cli/src/launch.ts" ]; then',
` echo "${message.replace(/`/g, '\\`')}: $checkout" >&2`,
` printf '%s: %s\\n' ${shellQuote(message)} "$checkout" >&2`,
' exit 3',
'fi',
'[ -x "$node" ] || node=node',
Expand Down
18 changes: 16 additions & 2 deletions tools/cli/src/lib/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,27 @@ export function stripFrontMatter(text: string): string {
return present ? body.replace(/^\n+/, '') : text
}

/** The text outside HTML tags, in one pass: each `<…>` with something inside is dropped; a `<` that closes nothing stays. */
export function withoutTags(text: string): string {
let result = ''
let index = 0
for (;;) {
const open = text.indexOf('<', index)
const close = open < 0 ? -1 : text.indexOf('>', open + 1)
if (close < 0) return result + text.slice(index)
// `<>` is text, not a tag.
result += close === open + 1 ? text.slice(index, close + 1) : text.slice(index, open)
index = close + 1
}
}

/** Inline Markdown to plain text: links and images to their text; code spans, emphasis and HTML tags removed. */
export function plain(markdown: string): string {
return markdown
const text = markdown
.replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
.replace(/\[([^\]]+)\]\[[^\]]*\]/g, '$1')
.replace(/<[^>]+>/g, '')
return withoutTags(text)
.replace(/`([^`]*)`/g, '$1')
.replace(/(\*\*|__)(.*?)\1/g, '$2')
.replace(/\s+/g, ' ')
Expand Down
Loading
Loading