From 735f12b0ff0fdab848c8d2089d181e1b516ba817 Mon Sep 17 00:00:00 2001 From: kzoeps Date: Thu, 26 Nov 2026 16:49:14 +0600 Subject: [PATCH 01/11] lint: flag duplicated shared Lua helpers Registry maps each shared helper family to its owning file. pnpm lint now flags redefinitions, lookalike names and inline re-implementations outside the owner. Existing copies are allowlisted with reasons, not refactored. --- AGENTS.md | 1 + biome.json | 3 +- happyview-modules/package.json | 3 +- .../unit/tooling/lint-shared-helpers.test.js | 133 ++++ .../tooling/lint-shared-helpers.js | 230 ++++++ .../tooling/shared-helpers.registry.json | 730 ++++++++++++++++++ package.json | 2 +- 7 files changed, 1099 insertions(+), 3 deletions(-) create mode 100644 happyview-modules/tests/unit/tooling/lint-shared-helpers.test.js create mode 100644 happyview-modules/tooling/lint-shared-helpers.js create mode 100644 happyview-modules/tooling/shared-helpers.registry.json diff --git a/AGENTS.md b/AGENTS.md index 64c2585c..d36b7e47 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,3 +8,4 @@ - `pnpm install:api` sends admin requests to a HappyView instance and uploads assets. Do not run it unless the user explicitly approves the target and token in the current conversation. - HTTP runtime tests use a task-owned local Compose project and disposable database. Do not target or tear down unrelated services; note that the Compose bridge network permits egress and the configured proxy is not network-level isolation. - Every new query endpoint needs a case in `happyview-modules/tooling/smoke-cases.js`. Add it to `happyview-modules/tooling/e2e.js` only if it has paging walks, count invariants or batch behaviour. When an endpoint's behavior changes, update the checks that cover it. +- Reuse and extend the canonical Lua helpers in `happyview-modules/lua/shared/` instead of writing a new copy in a handler or another shared file. Families: DID, NSID, record URI/key, subject URI, datetime, handle/resolver, list cursor, list limit/includeTotal/sortDirection, query parameter helpers (`invalid`, `keys_only`, `scalar`), record view, actor view and batch request-target. `pnpm lint` runs `happyview-modules/tooling/lint-shared-helpers.js` against `happyview-modules/tooling/shared-helpers.registry.json`, which maps each family to its owning file. Add every new shared helper to that registry. An allowlist entry needs a reason; use it only for an existing copy you are deliberately keeping. diff --git a/biome.json b/biome.json index 2317ee80..1cb26727 100644 --- a/biome.json +++ b/biome.json @@ -104,7 +104,8 @@ "happyview-modules/tooling/seed.js", "happyview-modules/tooling/smoke.js", "happyview-modules/tooling/e2e.js", - "happyview-modules/tooling/lint-lua.js" + "happyview-modules/tooling/lint-lua.js", + "happyview-modules/tooling/lint-shared-helpers.js" ], "linter": { "rules": { diff --git a/happyview-modules/package.json b/happyview-modules/package.json index 991d5467..1286703a 100644 --- a/happyview-modules/package.json +++ b/happyview-modules/package.json @@ -11,7 +11,8 @@ }, "scripts": { "lint:lua": "node tooling/lint-lua.js", - "lint": "pnpm run lint:lua", + "lint:shared-helpers": "node tooling/lint-shared-helpers.js", + "lint": "pnpm run lint:lua && pnpm run lint:shared-helpers", "typecheck": "tsc --project tsconfig.json", "check:generated": "node tooling/build-lua.js --check", "check": "pnpm run check:generated && pnpm run lint && pnpm run typecheck && pnpm run test:unit", diff --git a/happyview-modules/tests/unit/tooling/lint-shared-helpers.test.js b/happyview-modules/tests/unit/tooling/lint-shared-helpers.test.js new file mode 100644 index 00000000..89c2ce83 --- /dev/null +++ b/happyview-modules/tests/unit/tooling/lint-shared-helpers.test.js @@ -0,0 +1,133 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { checkSharedHelpers } from "../../../tooling/lint-shared-helpers.js"; + +const registry = (overrides = {}) => ({ + families: [ + { + id: "did-validation", + description: "DID syntax check", + owners: ["lua/shared/didValidation.lua"], + names: ["valid_did"], + lookalikes: ["^valid_[a-z_]*did$"], + inline: [{ id: "did-pattern", pattern: "\\^did:\\(", description: "the DID pattern" }], + }, + { + id: "repeated-query-array", + description: "array parsing", + owners: [], + unowned: "add a shared parser first", + lookalikes: ["^([a-z_]+_)?array$"], + }, + ], + allowlist: [], + ...overrides, +}); + +async function check(files, registryOverrides) { + const root = await mkdtemp(path.join(os.tmpdir(), "hypercerts-shared-helpers-")); + try { + await mkdir(path.join(root, "lua/shared"), { recursive: true }); + await mkdir(path.join(root, "lua/src"), { recursive: true }); + await mkdir(path.join(root, "lua/endpoints"), { recursive: true }); + for (const [file, source] of Object.entries(files)) { + await writeFile(path.join(root, file), source); + } + return (await checkSharedHelpers({ root, registry: registry(registryOverrides) })).errors; + } finally { + await rm(root, { recursive: true, force: true }); + } +} + +const owner = { + "lua/shared/didValidation.lua": "local function valid_did(value)\n return true\nend\n", +}; + +test("passes when only the owner defines the helper", async () => { + assert.deepEqual(await check(owner), []); +}); + +test("flags a redefinition outside the owner and says how to fix or allowlist it", async () => { + const [error, ...rest] = await check({ + ...owner, + "lua/src/getThing.lua": "local function valid_did(value)\n return false\nend\n", + }); + assert.equal(rest.length, 0); + assert.match(error, /^lua\/src\/getThing\.lua:1: defines "valid_did"/); + assert.match(error, /lua\/shared\/didValidation\.lua/); + assert.match(error, /sharedSourcePaths/); + assert.match(error, /"allowlist" in tooling\/shared-helpers\.registry\.json/); + assert.match(error, /"reason":""/); +}); + +test("flags lookalike names and inline re-implementations", async () => { + const errors = await check({ + ...owner, + "lua/src/getThing.lua": + 'local function valid_actor_did(v)\n return v:match("^did:([a-z]+):(.+)$")\nend\n', + }); + assert.equal(errors.length, 2); + assert.match( + errors.find((e) => e.includes(":1:")), + /looks like a new copy/, + ); + assert.match( + errors.find((e) => e.includes(":2:")), + /re-implements the DID pattern inline/, + ); +}); + +test("ignores commented code and generated endpoint bundles", async () => { + assert.deepEqual( + await check({ + ...owner, + "lua/src/getThing.lua": "-- local function valid_did(value)\nlocal x = 1 -- ^did:(\n", + "lua/endpoints/getThing.lua": "local function valid_did(value)\nend\n", + }), + [], + ); +}); + +test("unowned families tell the author to add a shared helper first", async () => { + const [error] = await check({ + ...owner, + "lua/src/listThings.lua": "local function array(params, key)\nend\n", + }); + assert.match(error, /No shared helper exists yet \(add a shared parser first\)/); +}); + +test("an allowlist entry silences exactly its file, family and symbol", async () => { + const files = { + ...owner, + "lua/src/a.lua": "local function valid_did(v)\nend\n", + "lua/src/b.lua": "local function valid_did(v)\nend\n", + }; + const errors = await check(files, { + allowlist: [ + { file: "lua/src/a.lua", family: "did-validation", symbol: "valid_did", reason: "kept" }, + ], + }); + assert.equal(errors.length, 1); + assert.match(errors[0], /^lua\/src\/b\.lua/); +}); + +test("a stale allowlist entry fails so the list cannot rot", async () => { + const [error] = await check(owner, { + allowlist: [ + { file: "lua/src/gone.lua", family: "did-validation", symbol: "valid_did", reason: "kept" }, + ], + }); + assert.match(error, /matches nothing.*delete the entry/); +}); + +test("rejects allowlist entries without a reason and owners that do not define the name", async () => { + await assert.rejects( + check(owner, { allowlist: [{ file: "x", family: "y", symbol: "z", reason: " " }] }), + /needs a nonempty "reason"/, + ); + const errors = await check({ "lua/shared/didValidation.lua": "local x = 1\n" }); + assert.match(errors[0], /protects "valid_did" but no owner file defines it/); +}); diff --git a/happyview-modules/tooling/lint-shared-helpers.js b/happyview-modules/tooling/lint-shared-helpers.js new file mode 100644 index 00000000..344e1c9c --- /dev/null +++ b/happyview-modules/tooling/lint-shared-helpers.js @@ -0,0 +1,230 @@ +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const defaultRoot = fileURLToPath(new URL("../", import.meta.url)); +const registryFile = "tooling/shared-helpers.registry.json"; +// Handwritten Lua only. lua/endpoints is generated by build-lua.js from these directories. +const scannedDirectories = ["lua/shared", "lua/src"]; + +const DEFINITION_PATTERNS = [ + /^\s*(?:local\s+)?function\s+([A-Za-z_]\w*)\s*\(/, + /^\s*(?:local\s+)?([A-Za-z_]\w*)\s*=\s*function\s*\(/, +]; + +async function luaFiles(root, directory) { + const entries = await readdir(path.join(root, directory), { withFileTypes: true }); + return entries + .filter((entry) => entry.isFile() && entry.name.endsWith(".lua")) + .map((entry) => `${directory}/${entry.name}`) + .sort(); +} + +function definitionName(line) { + for (const pattern of DEFINITION_PATTERNS) { + const match = pattern.exec(line); + if (match) return match[1]; + } + return null; +} + +function stripComment(line) { + const index = line.indexOf("--"); + return index === -1 ? line : line.slice(0, index); +} + +/** Throws one error listing every problem in the registry itself, so a bad edit fails loudly. */ +function validateRegistry(registry) { + const problems = []; + const seen = new Set(); + for (const family of registry.families ?? []) { + if (!family.id || seen.has(family.id)) + problems.push(`family id missing or duplicated: ${family.id}`); + seen.add(family.id); + if (!family.description) problems.push(`family ${family.id} needs a description`); + if (!Array.isArray(family.owners)) problems.push(`family ${family.id} needs an owners array`); + if (family.owners?.length === 0 && !family.unowned) { + problems.push( + `family ${family.id} has no owners; set "unowned": "" or name an owner file`, + ); + } + } + for (const entry of registry.allowlist ?? []) { + for (const key of ["file", "family", "symbol", "reason"]) { + if (typeof entry[key] !== "string" || !entry[key].trim()) { + problems.push( + `allowlist entry ${JSON.stringify(entry)} needs a nonempty "${key}" (reason says why the copy must stay)`, + ); + } + } + } + if (problems.length > 0) { + throw new Error(`Invalid ${registryFile}:\n- ${problems.join("\n- ")}`); + } +} + +function ownersDefine(family, sources) { + const defined = new Set(); + for (const owner of family.owners) { + const source = sources.get(owner); + if (source === undefined) continue; + for (const line of source.split("\n")) { + const name = definitionName(line); + if (name) defined.add(name); + } + } + return defined; +} + +function registryFindings(registry, sources) { + const findings = []; + for (const family of registry.families) { + for (const owner of family.owners) { + if (!sources.has(owner)) { + findings.push({ + kind: "registry", + message: `${registryFile}: family "${family.id}" owner ${owner} does not exist. Update the owner path or remove the family.`, + }); + } + } + const defined = ownersDefine(family, sources); + for (const name of family.names ?? []) { + if (family.owners.length > 0 && !defined.has(name)) { + findings.push({ + kind: "registry", + message: `${registryFile}: family "${family.id}" protects "${name}" but no owner file defines it. Fix the name or the owner list.`, + }); + } + } + } + return findings; +} + +function ownerHint(family) { + if (family.owners.length === 0) { + return `No shared helper exists yet (${family.unowned}).`; + } + return `Use the shared helper from ${family.owners.join(" or ")} (declare it in the module's sharedSourcePaths).`; +} + +function sourceFindings(registry, sources) { + const findings = []; + for (const [file, source] of sources) { + const lines = source.split("\n"); + for (const family of registry.families) { + if (family.owners.includes(file)) continue; + const protectedNames = new Set(family.names ?? []); + const lookalikes = (family.lookalikes ?? []).map((pattern) => new RegExp(pattern)); + const inline = (family.inline ?? []).map((rule) => ({ + ...rule, + regex: new RegExp(rule.pattern), + })); + lines.forEach((rawLine, index) => { + const line = stripComment(rawLine); + const name = definitionName(line); + if (name && protectedNames.has(name)) { + findings.push({ kind: "redefinition", file, line: index + 1, family, symbol: name }); + } else if (name && lookalikes.some((regex) => regex.test(name))) { + findings.push({ kind: "lookalike", file, line: index + 1, family, symbol: name }); + } + for (const rule of inline) { + if (rule.regex.test(line)) { + findings.push({ kind: "inline", file, line: index + 1, family, symbol: rule.id, rule }); + } + } + }); + } + } + return findings; +} + +function findingMessage(finding) { + const { kind, file, line, family, symbol, rule } = finding; + const where = `${file}:${line}`; + const what = { + redefinition: () => `defines "${symbol}", a protected shared helper (${family.description}).`, + lookalike: () => + `defines "${symbol}", which looks like a new copy of the ${family.id} helpers (${family.description}).`, + inline: () => `re-implements ${rule.description} inline (${family.description}).`, + }[kind](); + const entry = JSON.stringify({ + file, + family: family.id, + symbol, + reason: "", + }); + return [ + `${where}: ${what}`, + ` ${ownerHint(family)} If the copy must stay, add to "allowlist" in ${registryFile}:`, + ` ${entry}`, + ].join("\n"); +} + +function allowlistKey(file, family, symbol) { + return `${file}\u0000${family}\u0000${symbol}`; +} + +/** + * Checks handwritten Lua against the shared-helper registry. + * Returns { errors: string[] }; an empty list means the check passed. + */ +export async function checkSharedHelpers({ root = defaultRoot, registry } = {}) { + const loaded = registry ?? JSON.parse(await readFile(path.join(root, registryFile), "utf8")); + validateRegistry(loaded); + + const files = (await Promise.all(scannedDirectories.map((dir) => luaFiles(root, dir)))).flat(); + const sources = new Map( + await Promise.all( + files.map(async (file) => [file, await readFile(path.join(root, file), "utf8")]), + ), + ); + + const errors = registryFindings(loaded, sources).map((finding) => finding.message); + const allowed = new Map( + (loaded.allowlist ?? []).map((entry) => [ + allowlistKey(entry.file, entry.family, entry.symbol), + entry, + ]), + ); + const used = new Set(); + const reported = new Set(); + for (const finding of sourceFindings(loaded, sources)) { + const key = allowlistKey(finding.file, finding.family.id, finding.symbol); + if (allowed.has(key)) { + used.add(key); + } else if (!reported.has(key)) { + // One report per file, family and symbol, matching what an allowlist entry covers. + reported.add(key); + errors.push(findingMessage(finding)); + } + } + for (const [key, entry] of allowed) { + if (!used.has(key)) { + errors.push( + `${registryFile}: allowlist entry for ${entry.file} / ${entry.family} / ${entry.symbol} matches nothing. The copy was removed or renamed; delete the entry.`, + ); + } + } + return { errors }; +} + +async function main() { + const { errors } = await checkSharedHelpers(); + if (errors.length > 0) { + process.stderr.write( + `Shared helper check failed (${errors.length}):\n\n${errors.join("\n\n")}\n`, + ); + process.exitCode = 1; + return; + } + process.stdout.write("Shared helper check passed.\n"); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + try { + await main(); + } catch (error) { + process.stderr.write(`${error.message}\n`); + process.exitCode = 1; + } +} diff --git a/happyview-modules/tooling/shared-helpers.registry.json b/happyview-modules/tooling/shared-helpers.registry.json new file mode 100644 index 00000000..2b68b2ca --- /dev/null +++ b/happyview-modules/tooling/shared-helpers.registry.json @@ -0,0 +1,730 @@ +{ + "families": [ + { + "id": "did-validation", + "description": "DID syntax check", + "owners": ["lua/shared/didValidation.lua"], + "names": ["valid_did"], + "lookalikes": ["^valid_[a-z_]*did$"], + "inline": [ + { + "id": "did-pattern", + "pattern": "\\^did:\\(", + "description": "the DID syntax pattern" + } + ] + }, + { + "id": "nsid-validation", + "description": "NSID syntax check", + "owners": ["lua/shared/nsidValidation.lua"], + "names": ["valid_nsid"], + "lookalikes": ["^valid_[a-z_]*nsid$"] + }, + { + "id": "record-identifier", + "description": "AT-URI record key and record URI parsing", + "owners": ["lua/shared/recordIdentifier.lua"], + "names": ["valid_record_uri", "valid_record_key"], + "lookalikes": ["^[a-z_]+_valid_record_(uri|key)$", "^valid_record_[a-z_]+$"], + "inline": [ + { + "id": "at-uri-pattern", + "pattern": "\\^at://\\(", + "description": "the AT-URI parsing pattern" + } + ] + }, + { + "id": "subject-record-uri", + "description": "DID-authority subject AT-URI check", + "owners": ["lua/shared/subjectRecordUri.lua"], + "names": ["valid_subject_record_uri", "valid_did_percent_escapes"] + }, + { + "id": "datetime-validation", + "description": "RFC 3339 datetime check", + "owners": ["lua/shared/datetimeValidation.lua"], + "names": ["valid_datetime"], + "lookalikes": ["^valid_[a-z_]*(datetime|timestamp)$"] + }, + { + "id": "handle-resolver", + "description": "handle syntax check and handle resolution", + "owners": ["lua/shared/profileLookup.lua"], + "names": [ + "valid_handle", + "valid_resolver_authority", + "valid_ipv4", + "valid_ipv6", + "valid_port", + "resolver_base_url", + "resolve_handle", + "fail_resolver_config" + ], + "lookalikes": ["^valid_(handle|ipv4|ipv6|port)[a-z_]*$", "^[a-z_]*resolve_handle$"] + }, + { + "id": "list-cursor", + "description": "list cursor encoding and decoding", + "owners": ["lua/shared/listCursor.lua", "lua/shared/listQuery.lua"], + "names": ["decode_cursor", "cursor_encode"], + "lookalikes": [ + "^([a-z_]+_)?cursor_decode$", + "^decode_[a-z_]+_cursor$", + "^[a-z_]+_cursor_encode$", + "^[a-z_]+_decode_cursor$", + "^encode_[a-z_]*cursor$" + ], + "inline": [ + { + "id": "cursor-hex-decode", + "pattern": "tonumber\\(pair, 16\\)", + "description": "hex cursor decoding" + }, + { + "id": "cursor-length-cap", + "pattern": "#token > 8192", + "description": "the cursor length cap" + } + ] + }, + { + "id": "list-params", + "description": "limit, includeTotal and sortDirection parsing", + "owners": [ + "lua/shared/listValidation.lua", + "lua/shared/includeTotal.lua", + "lua/shared/listQuery.lua" + ], + "names": ["parse_list_limit", "parse_include_total", "parse_sort_direction"], + "lookalikes": ["^parse_[a-z_]*(limit|include_total|sort_direction)$"], + "inline": [ + { + "id": "limit-message", + "pattern": "limit must be an integer", + "description": "limit parsing" + }, + { + "id": "include-total-message", + "pattern": "includeTotal must be true or false", + "description": "includeTotal parsing" + }, + { + "id": "sort-direction-message", + "pattern": "sortDirection must be", + "description": "sortDirection parsing" + } + ] + }, + { + "id": "query-params", + "description": "InvalidRequest errors, unknown-parameter checks and single-value parameters", + "owners": ["lua/shared/query.lua"], + "names": ["invalid", "keys_only", "scalar"], + "lookalikes": ["^[a-z_]+_(invalid|keys_only|scalar)$"], + "inline": [ + { + "id": "occur-once-message", + "pattern": "must occur once", + "description": "single-value parameter parsing" + } + ] + }, + { + "id": "repeated-query-array", + "description": "repeated query parameter (array) parsing", + "owners": [], + "unowned": "each endpoint has its own; add a shared parser in lua/shared and register it before adding another", + "lookalikes": ["^([a-z_]+_)?array(_values)?$"] + }, + { + "id": "record-view", + "description": "the {uri, cid, indexedAt, did, record} view of an indexed row", + "owners": ["lua/shared/recordView.lua"], + "names": ["record_view"], + "lookalikes": ["^[a-z_]+_record_view$"], + "inline": [ + { + "id": "indexed-at-null", + "pattern": "indexed_at == nil and NULL", + "description": "the indexedAt null fallback" + } + ] + }, + { + "id": "actor-view", + "description": "actor profile/organization hydration", + "owners": ["lua/shared/actorView.lua"], + "names": ["hydrate_actor_views"], + "lookalikes": ["^[a-z_]*hydrate_[a-z_]*actor_views$"] + }, + { + "id": "batch-request-target", + "description": "batch GET request-target size limit", + "owners": ["lua/shared/batchRequestTarget.lua"], + "names": ["assert_batch_request_target", "encoded_query_value_length"], + "lookalikes": ["^[a-z_]*request_target[a-z_]*$"] + } + ], + "allowlist": [ + { + "file": "lua/shared/acknowledgement.lua", + "family": "record-view", + "symbol": "acknowledgement_record_view", + "reason": "Existing record view with endpoint-specific fields; kept to avoid a behavior change. Build on record_view where the shape allows." + }, + { + "file": "lua/shared/acknowledgementList.lua", + "family": "datetime-validation", + "symbol": "valid_cursor_timestamp", + "reason": "Existing cursor timestamp check with its own rules; kept to avoid a behavior change." + }, + { + "file": "lua/shared/acknowledgementList.lua", + "family": "list-cursor", + "symbol": "decode_acknowledgement_cursor", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/acknowledgementList.lua", + "family": "repeated-query-array", + "symbol": "acknowledgement_array", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/shared/activityList.lua", + "family": "list-cursor", + "symbol": "decode_activity_cursor", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/activityList.lua", + "family": "query-params", + "symbol": "activity_scalar", + "reason": "Existing endpoint-local copy of the shared query helpers; kept to avoid a behavior change. Use query.lua helpers instead." + }, + { + "file": "lua/shared/activityList.lua", + "family": "record-identifier", + "symbol": "at-uri-pattern", + "reason": "Existing record-URI check that predates the registry; kept to avoid a behavior change. Build on valid_record_uri where the shape allows." + }, + { + "file": "lua/shared/activityList.lua", + "family": "repeated-query-array", + "symbol": "activity_array", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/shared/activityProjection.lua", + "family": "record-view", + "symbol": "activity_projection_record_view", + "reason": "Existing record view with endpoint-specific fields; kept to avoid a behavior change. Build on record_view where the shape allows." + }, + { + "file": "lua/shared/actorFollowList.lua", + "family": "list-cursor", + "symbol": "cursor_decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/actorFollowList.lua", + "family": "list-cursor", + "symbol": "cursor-hex-decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/attachmentList.lua", + "family": "list-cursor", + "symbol": "attachment_cursor_decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/attachmentList.lua", + "family": "repeated-query-array", + "symbol": "attachment_array", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/shared/collection.lua", + "family": "record-identifier", + "symbol": "collection_valid_record_uri", + "reason": "Existing record-URI check that predates the registry; kept to avoid a behavior change. Build on valid_record_uri where the shape allows." + }, + { + "file": "lua/shared/collectionItems.lua", + "family": "list-cursor", + "symbol": "collection_items_cursor_decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/collectionItems.lua", + "family": "list-cursor", + "symbol": "collection_items_cursor_encode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/collectionItems.lua", + "family": "list-cursor", + "symbol": "cursor-hex-decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/collectionItems.lua", + "family": "list-cursor", + "symbol": "cursor-length-cap", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/collectionItems.lua", + "family": "query-params", + "symbol": "collection_items_invalid", + "reason": "Existing endpoint-local copy of the shared query helpers; kept to avoid a behavior change. Use query.lua helpers instead." + }, + { + "file": "lua/shared/collectionItems.lua", + "family": "query-params", + "symbol": "collection_items_keys_only", + "reason": "Existing endpoint-local copy of the shared query helpers; kept to avoid a behavior change. Use query.lua helpers instead." + }, + { + "file": "lua/shared/collectionList.lua", + "family": "list-cursor", + "symbol": "collection_list_cursor_decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/collectionList.lua", + "family": "query-params", + "symbol": "collection_scalar", + "reason": "Existing endpoint-local copy of the shared query helpers; kept to avoid a behavior change. Use query.lua helpers instead." + }, + { + "file": "lua/shared/collectionList.lua", + "family": "repeated-query-array", + "symbol": "collection_array", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/shared/collectionProjection.lua", + "family": "record-identifier", + "symbol": "collection_projection_valid_record_uri", + "reason": "Existing record-URI check that predates the registry; kept to avoid a behavior change. Build on valid_record_uri where the shape allows." + }, + { + "file": "lua/shared/collectionProjection.lua", + "family": "record-view", + "symbol": "collection_projection_record_view", + "reason": "Existing record view with endpoint-specific fields; kept to avoid a behavior change. Build on record_view where the shape allows." + }, + { + "file": "lua/shared/entityFollow.lua", + "family": "record-view", + "symbol": "entity_follow_indexed_record_view", + "reason": "Existing record view with endpoint-specific fields; kept to avoid a behavior change. Build on record_view where the shape allows." + }, + { + "file": "lua/shared/entityFollow.lua", + "family": "record-view", + "symbol": "entity_follow_record_view", + "reason": "Existing record view with endpoint-specific fields; kept to avoid a behavior change. Build on record_view where the shape allows." + }, + { + "file": "lua/shared/entityFollowPagination.lua", + "family": "list-cursor", + "symbol": "entity_follow_decode_cursor", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/evaluation.lua", + "family": "repeated-query-array", + "symbol": "evaluation_evaluator_array", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/shared/evaluationList.lua", + "family": "list-cursor", + "symbol": "decode_evaluation_cursor", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/evaluationList.lua", + "family": "repeated-query-array", + "symbol": "evaluation_array", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/shared/evmLinkIdentifier.lua", + "family": "record-identifier", + "symbol": "at-uri-pattern", + "reason": "Existing record-URI check that predates the registry; kept to avoid a behavior change. Build on valid_record_uri where the shape allows." + }, + { + "file": "lua/shared/evmLinkIdentifier.lua", + "family": "record-view", + "symbol": "evm_link_record_view", + "reason": "Existing record view with endpoint-specific fields; kept to avoid a behavior change. Build on record_view where the shape allows." + }, + { + "file": "lua/shared/featureProjection.lua", + "family": "record-view", + "symbol": "feature_projection_record_view", + "reason": "Existing record view with endpoint-specific fields; kept to avoid a behavior change. Build on record_view where the shape allows." + }, + { + "file": "lua/shared/feedActorReactions.lua", + "family": "record-view", + "symbol": "feed_actor_reaction_record_view", + "reason": "Existing record view with endpoint-specific fields; kept to avoid a behavior change. Build on record_view where the shape allows." + }, + { + "file": "lua/shared/feedReaction.lua", + "family": "list-cursor", + "symbol": "feed_reaction_decode_cursor", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/fundingReceipt.lua", + "family": "record-view", + "symbol": "indexed-at-null", + "reason": "funding_receipt_view repeats the record_view null indexedAt fallback because it also adds author; kept to avoid a behavior change." + }, + { + "file": "lua/shared/fundingReceiptList.lua", + "family": "list-cursor", + "symbol": "decode_funding_receipt_cursor", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/fundingReceiptList.lua", + "family": "repeated-query-array", + "symbol": "funding_receipt_array", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/shared/measurementQuery.lua", + "family": "record-identifier", + "symbol": "measurement_valid_record_uri", + "reason": "Existing record-URI check that predates the registry; kept to avoid a behavior change. Build on valid_record_uri where the shape allows." + }, + { + "file": "lua/shared/organizationList.lua", + "family": "list-cursor", + "symbol": "cursor_decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/organizationList.lua", + "family": "list-cursor", + "symbol": "cursor-hex-decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/organizationList.lua", + "family": "record-identifier", + "symbol": "at-uri-pattern", + "reason": "Existing record-URI check that predates the registry; kept to avoid a behavior change. Build on valid_record_uri where the shape allows." + }, + { + "file": "lua/shared/organizationList.lua", + "family": "repeated-query-array", + "symbol": "array", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/shared/profileList.lua", + "family": "list-cursor", + "symbol": "cursor_decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/profileList.lua", + "family": "list-cursor", + "symbol": "cursor-hex-decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/profileList.lua", + "family": "record-identifier", + "symbol": "at-uri-pattern", + "reason": "Existing record-URI check that predates the registry; kept to avoid a behavior change. Build on valid_record_uri where the shape allows." + }, + { + "file": "lua/shared/profileList.lua", + "family": "repeated-query-array", + "symbol": "array", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/shared/recentFollows.lua", + "family": "list-cursor", + "symbol": "cursor-hex-decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/recentFollows.lua", + "family": "list-cursor", + "symbol": "recent_cursor_decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/recentFollows.lua", + "family": "list-cursor", + "symbol": "recent_cursor_encode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/recentFollows.lua", + "family": "record-identifier", + "symbol": "recent_valid_record_uri", + "reason": "Existing record-URI check that predates the registry; kept to avoid a behavior change. Build on valid_record_uri where the shape allows." + }, + { + "file": "lua/shared/recentFollows.lua", + "family": "record-view", + "symbol": "recent_record_view", + "reason": "Existing record view with endpoint-specific fields; kept to avoid a behavior change. Build on record_view where the shape allows." + }, + { + "file": "lua/shared/rightsIdentifier.lua", + "family": "record-identifier", + "symbol": "rights_valid_record_uri", + "reason": "Existing record-URI check that predates the registry; kept to avoid a behavior change. Build on valid_record_uri where the shape allows." + }, + { + "file": "lua/shared/rightsView.lua", + "family": "actor-view", + "symbol": "rights_hydrate_actor_views", + "reason": "Existing actor hydration variant; kept to avoid a behavior change. Build on hydrate_actor_views where the shape allows." + }, + { + "file": "lua/shared/rightsView.lua", + "family": "record-view", + "symbol": "rights_record_view", + "reason": "Existing record view with endpoint-specific fields; kept to avoid a behavior change. Build on record_view where the shape allows." + }, + { + "file": "lua/shared/vocabTagValidation.lua", + "family": "actor-view", + "symbol": "hydrate_vocab_actor_views", + "reason": "Existing actor hydration variant; kept to avoid a behavior change. Build on hydrate_actor_views where the shape allows." + }, + { + "file": "lua/shared/workscopeRecordView.lua", + "family": "record-view", + "symbol": "record_view", + "reason": "Deliberately differs from recordView.lua: workscope sidecars omit a missing indexedAt instead of encoding JSON null (see the file comment). Both define record_view, so a bundle must not include both." + }, + { + "file": "lua/shared/workscopeTag.lua", + "family": "record-identifier", + "symbol": "workscope_tag_valid_record_uri", + "reason": "Existing record-URI check that predates the registry; kept to avoid a behavior change. Build on valid_record_uri where the shape allows." + }, + { + "file": "lua/shared/workscopeTagList.lua", + "family": "list-cursor", + "symbol": "workscope_tag_decode_cursor", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/shared/workscopeTagList.lua", + "family": "repeated-query-array", + "symbol": "workscope_tag_array", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/src/listBadgeAwards.lua", + "family": "list-cursor", + "symbol": "cursor-hex-decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/listBadgeAwards.lua", + "family": "list-cursor", + "symbol": "decode_badge_award_cursor", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/listBadgeAwards.lua", + "family": "list-params", + "symbol": "include-total-message", + "reason": "Existing endpoint-local list parameter parsing; kept to avoid a behavior change. Use includeTotal.lua instead." + }, + { + "file": "lua/src/listBadgeAwards.lua", + "family": "list-params", + "symbol": "parse_include_total", + "reason": "Existing endpoint-local list parameter parsing; kept to avoid a behavior change. Use includeTotal.lua instead." + }, + { + "file": "lua/src/listBadgeAwards.lua", + "family": "repeated-query-array", + "symbol": "array_values", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/src/listBadgeDefinitions.lua", + "family": "list-cursor", + "symbol": "cursor-hex-decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/listBadgeDefinitions.lua", + "family": "list-cursor", + "symbol": "decode_badge_definition_cursor", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/listBadgeDefinitions.lua", + "family": "repeated-query-array", + "symbol": "badge_definition_array", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/src/listBadgeResponses.lua", + "family": "list-cursor", + "symbol": "cursor-hex-decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/listBadgeResponses.lua", + "family": "list-cursor", + "symbol": "decode_badge_response_cursor", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/listContributions.lua", + "family": "list-cursor", + "symbol": "decode_contribution_cursor", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/listContributorInformation.lua", + "family": "list-cursor", + "symbol": "contributor_information_cursor_decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/listContributorInformation.lua", + "family": "repeated-query-array", + "symbol": "contributor_information_array", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/src/listEvmLinks.lua", + "family": "list-cursor", + "symbol": "cursor-hex-decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/listEvmLinks.lua", + "family": "list-cursor", + "symbol": "decode_evm_link_cursor", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/listEvmLinks.lua", + "family": "repeated-query-array", + "symbol": "array_values", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/src/listFeatures.lua", + "family": "list-cursor", + "symbol": "cursor-hex-decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/listFeatures.lua", + "family": "list-cursor", + "symbol": "feature_cursor_decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/listFeatures.lua", + "family": "query-params", + "symbol": "occur-once-message", + "reason": "Existing endpoint-local copy of the shared query helpers; kept to avoid a behavior change. Use query.lua helpers instead." + }, + { + "file": "lua/src/listFeatures.lua", + "family": "repeated-query-array", + "symbol": "feature_array", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/src/listLocations.lua", + "family": "list-cursor", + "symbol": "cursor_decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/listLocations.lua", + "family": "list-cursor", + "symbol": "cursor-hex-decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/listLocations.lua", + "family": "repeated-query-array", + "symbol": "array", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/src/listMeasurements.lua", + "family": "list-cursor", + "symbol": "decode_measurement_cursor", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/listMeasurements.lua", + "family": "repeated-query-array", + "symbol": "measurement_array", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/src/listRights.lua", + "family": "list-cursor", + "symbol": "rights_list_cursor_decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/listRights.lua", + "family": "repeated-query-array", + "symbol": "rights_list_array", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/src/listVocabTags.lua", + "family": "list-cursor", + "symbol": "cursor-hex-decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/listVocabTags.lua", + "family": "list-cursor", + "symbol": "decode_cursor", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/searchBadgeDefinitions.lua", + "family": "list-cursor", + "symbol": "cursor-hex-decode", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/searchBadgeDefinitions.lua", + "family": "list-cursor", + "symbol": "decode_badge_definition_cursor", + "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." + }, + { + "file": "lua/src/searchBadgeDefinitions.lua", + "family": "repeated-query-array", + "symbol": "badge_definition_array", + "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + } + ] +} diff --git a/package.json b/package.json index 2897a66b..cd96f8c5 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "packageManager": "pnpm@12.15.0", "scripts": { "prepare": "lefthook install", - "lint": "biome lint --error-on-warnings .", + "lint": "biome lint --error-on-warnings . && pnpm --filter @hypercerts-org/happyview-modules run lint:shared-helpers", "format": "biome format --write .", "format:check": "biome format .", "check": "pnpm lint && pnpm format:check && pnpm --filter @hypercerts-org/happyview-modules check && pnpm --filter hypercerts-api-endpoints test && pnpm --filter @hypercerts-org/api check", From b7690c2913ca78aa3811735e7587e7c1f579568f Mon Sep 17 00:00:00 2001 From: kzoeps Date: Thu, 26 Nov 2026 16:52:58 +0600 Subject: [PATCH 02/11] lint: tighten shared helper detection and allowlist counts Lookalike patterns match the family word anywhere, module-table definitions are detected by last segment, inline DID/AT-URI patterns are looser, and allowlist entries carry an occurrence count. Tests run the real registry against probe files; AGENTS.md explains registration. --- AGENTS.md | 3 +- .../unit/tooling/lint-shared-helpers.test.js | 78 ++++++++++++++++++- .../tooling/lint-shared-helpers.js | 60 ++++++++++---- .../tooling/shared-helpers.registry.json | 36 ++++----- 4 files changed, 138 insertions(+), 39 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d36b7e47..bc2b86e9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,4 +8,5 @@ - `pnpm install:api` sends admin requests to a HappyView instance and uploads assets. Do not run it unless the user explicitly approves the target and token in the current conversation. - HTTP runtime tests use a task-owned local Compose project and disposable database. Do not target or tear down unrelated services; note that the Compose bridge network permits egress and the configured proxy is not network-level isolation. - Every new query endpoint needs a case in `happyview-modules/tooling/smoke-cases.js`. Add it to `happyview-modules/tooling/e2e.js` only if it has paging walks, count invariants or batch behaviour. When an endpoint's behavior changes, update the checks that cover it. -- Reuse and extend the canonical Lua helpers in `happyview-modules/lua/shared/` instead of writing a new copy in a handler or another shared file. Families: DID, NSID, record URI/key, subject URI, datetime, handle/resolver, list cursor, list limit/includeTotal/sortDirection, query parameter helpers (`invalid`, `keys_only`, `scalar`), record view, actor view and batch request-target. `pnpm lint` runs `happyview-modules/tooling/lint-shared-helpers.js` against `happyview-modules/tooling/shared-helpers.registry.json`, which maps each family to its owning file. Add every new shared helper to that registry. An allowlist entry needs a reason; use it only for an existing copy you are deliberately keeping. +- Reuse and extend the canonical Lua helpers in `happyview-modules/lua/shared/` instead of writing a new copy in a handler or another shared file. Before writing a helper, search `happyview-modules/lua/shared/` and `happyview-modules/tooling/shared-helpers.registry.json` for an existing one; the lint only catches some copies. Families: DID, NSID, record URI/key, subject URI, datetime, handle/resolver, list cursor, list limit/includeTotal/sortDirection, query parameter helpers (`invalid`, `keys_only`, `scalar`), record view, actor view and batch request-target. Repeated-parameter (array) parsing has no shared helper yet. +- `pnpm lint` (so `pnpm check` and CI) runs `happyview-modules/tooling/lint-shared-helpers.js` on `lua/shared` and `lua/src`. Register each new shared helper in `shared-helpers.registry.json` (paths relative to `happyview-modules/`): add its name to the owning family's `names`, or add a family with `id`, `description`, `owners`, `names` and optional `lookalikes`/`inline` patterns. To keep an existing copy, add `{file, family, symbol, reason}` to `allowlist` (`symbol` is the function name or inline rule id; add `count` if it occurs more than once). The failure message prints a ready-made entry. An entry that no longer matches fails lint; delete it. The current allowlist is a baseline, not approval for new copies. diff --git a/happyview-modules/tests/unit/tooling/lint-shared-helpers.test.js b/happyview-modules/tests/unit/tooling/lint-shared-helpers.test.js index 89c2ce83..0b314fbe 100644 --- a/happyview-modules/tests/unit/tooling/lint-shared-helpers.test.js +++ b/happyview-modules/tests/unit/tooling/lint-shared-helpers.test.js @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import test from "node:test"; @@ -131,3 +131,79 @@ test("rejects allowlist entries without a reason and owners that do not define t const errors = await check({ "lua/shared/didValidation.lua": "local x = 1\n" }); assert.match(errors[0], /protects "valid_did" but no owner file defines it/); }); + +test("an allowlist count catches a second copy in an already-allowlisted file", async () => { + const files = { + ...owner, + "lua/src/a.lua": "local function valid_did(v)\nend\nlocal function valid_did(v)\nend\n", + }; + const entry = { + file: "lua/src/a.lua", + family: "did-validation", + symbol: "valid_did", + reason: "kept", + }; + const [error] = await check(files, { allowlist: [entry] }); + assert.match(error, /covers 1 occurrence\(s\) but 2 exist/); + assert.deepEqual(await check(files, { allowlist: [{ ...entry, count: 2 }] }), []); + const [stale] = await check( + { ...owner, "lua/src/a.lua": "local function valid_did(v)\nend\n" }, + { + allowlist: [{ ...entry, count: 2 }], + }, + ); + assert.match(stale, /allows 2 but only 1 remain/); +}); + +test("detects module-table definitions by their last segment", async () => { + const errors = await check({ + ...owner, + "lua/src/a.lua": + "function M.valid_did(v)\nend\nM.valid_did = function(v)\nend\nfunction M:valid_did(v)\nend\n", + }); + assert.equal(errors.length, 1); + assert.match(errors[0], /defines "valid_did"/); +}); + +// The real registry must catch the obvious new copy, not only exact names. +const realRegistryCases = [ + ["a suffixed DID validator", "local function valid_did_strict(v)\nend\n", /valid_did_strict/], + ["a module-table NSID validator", "function M.valid_nsid(v)\nend\n", /valid_nsid/], + [ + "a new datetime validator", + "local function valid_datetime_strict(v)\nend\n", + /valid_datetime_strict/, + ], + [ + "a prefixed cursor decoder", + "local function decode_widget_cursor(t)\nend\n", + /decode_widget_cursor/, + ], + ["a new array parser", "local function widget_array(p, k)\nend\n", /widget_array/], + ["an inline DID pattern", 'local ok = v:find("^did:[a-z]+:")\n', /DID syntax pattern/], + ["an inline AT-URI pattern", 'local a = v:match("^at://([^/]+)/")\n', /AT-URI parsing pattern/], + ["a local record view", "local function widget_record_view(r)\nend\n", /widget_record_view/], +]; + +for (const [name, source, expected] of realRegistryCases) { + test(`real registry flags ${name}`, async () => { + const packageRoot = path.resolve(import.meta.dirname, "../../.."); + const root = await mkdtemp(path.join(os.tmpdir(), "hypercerts-shared-helpers-real-")); + try { + await cp(path.join(packageRoot, "lua/shared"), path.join(root, "lua/shared"), { + recursive: true, + }); + await cp(path.join(packageRoot, "lua/src"), path.join(root, "lua/src"), { recursive: true }); + await writeFile(path.join(root, "lua/src/probe.lua"), source); + const realRegistry = JSON.parse( + await readFile(path.join(packageRoot, "tooling/shared-helpers.registry.json"), "utf8"), + ); + const { errors } = await checkSharedHelpers({ root, registry: realRegistry }); + assert.equal(errors.length, 1, errors.join("\n")); + assert.match(errors[0], /^lua\/src\/probe\.lua:1/); + assert.match(errors[0], expected); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); +} diff --git a/happyview-modules/tooling/lint-shared-helpers.js b/happyview-modules/tooling/lint-shared-helpers.js index 344e1c9c..12b024d7 100644 --- a/happyview-modules/tooling/lint-shared-helpers.js +++ b/happyview-modules/tooling/lint-shared-helpers.js @@ -7,9 +7,11 @@ const registryFile = "tooling/shared-helpers.registry.json"; // Handwritten Lua only. lua/endpoints is generated by build-lua.js from these directories. const scannedDirectories = ["lua/shared", "lua/src"]; +// Matches `function name(`, `function M.name(`, `function M:name(` and `M.name = function(`. +// Only the last segment is the helper's name, so a module-table copy is still a copy. const DEFINITION_PATTERNS = [ - /^\s*(?:local\s+)?function\s+([A-Za-z_]\w*)\s*\(/, - /^\s*(?:local\s+)?([A-Za-z_]\w*)\s*=\s*function\s*\(/, + /^\s*(?:local\s+)?function\s+([A-Za-z_][\w.:]*)\s*\(/, + /^\s*(?:local\s+)?([A-Za-z_][\w.]*)\s*=\s*function\s*\(/, ]; async function luaFiles(root, directory) { @@ -23,7 +25,7 @@ async function luaFiles(root, directory) { function definitionName(line) { for (const pattern of DEFINITION_PATTERNS) { const match = pattern.exec(line); - if (match) return match[1]; + if (match) return match[1].split(/[.:]/).pop(); } return null; } @@ -50,6 +52,11 @@ function validateRegistry(registry) { } } for (const entry of registry.allowlist ?? []) { + if (entry.count !== undefined && !(Number.isInteger(entry.count) && entry.count >= 1)) { + problems.push( + `allowlist entry ${JSON.stringify(entry)} has an invalid "count"; use a positive integer`, + ); + } for (const key of ["file", "family", "symbol", "reason"]) { if (typeof entry[key] !== "string" || !entry[key].trim()) { problems.push( @@ -109,11 +116,17 @@ function ownerHint(family) { function sourceFindings(registry, sources) { const findings = []; + // A name another family protects is that family's business, not a lookalike here. + const protectedElsewhere = (family) => + new Set( + registry.families.filter((other) => other !== family).flatMap((other) => other.names ?? []), + ); for (const [file, source] of sources) { const lines = source.split("\n"); for (const family of registry.families) { if (family.owners.includes(file)) continue; const protectedNames = new Set(family.names ?? []); + const elsewhere = protectedElsewhere(family); const lookalikes = (family.lookalikes ?? []).map((pattern) => new RegExp(pattern)); const inline = (family.inline ?? []).map((rule) => ({ ...rule, @@ -124,7 +137,7 @@ function sourceFindings(registry, sources) { const name = definitionName(line); if (name && protectedNames.has(name)) { findings.push({ kind: "redefinition", file, line: index + 1, family, symbol: name }); - } else if (name && lookalikes.some((regex) => regex.test(name))) { + } else if (name && !elsewhere.has(name) && lookalikes.some((regex) => regex.test(name))) { findings.push({ kind: "lookalike", file, line: index + 1, family, symbol: name }); } for (const rule of inline) { @@ -138,8 +151,8 @@ function sourceFindings(registry, sources) { return findings; } -function findingMessage(finding) { - const { kind, file, line, family, symbol, rule } = finding; +function findingMessage(finding, allowedCount) { + const { kind, file, line, family, symbol, rule, count } = finding; const where = `${file}:${line}`; const what = { redefinition: () => `defines "${symbol}", a protected shared helper (${family.description}).`, @@ -151,13 +164,14 @@ function findingMessage(finding) { file, family: family.id, symbol, + ...(count > 1 ? { count } : {}), reason: "", }); - return [ - `${where}: ${what}`, - ` ${ownerHint(family)} If the copy must stay, add to "allowlist" in ${registryFile}:`, - ` ${entry}`, - ].join("\n"); + const advice = + allowedCount === undefined + ? `If the copy must stay, add to "allowlist" in ${registryFile}:` + : `The allowlist covers ${allowedCount} occurrence(s) but ${count} exist now. Remove the new copy, or raise "count" with a reason:`; + return [`${where}: ${what}`, ` ${ownerHint(family)} ${advice}`, ` ${entry}`].join("\n"); } function allowlistKey(file, family, symbol) { @@ -187,15 +201,27 @@ export async function checkSharedHelpers({ root = defaultRoot, registry } = {}) ]), ); const used = new Set(); - const reported = new Set(); + // One report per file, family and symbol: the unit an allowlist entry covers. + const grouped = new Map(); for (const finding of sourceFindings(loaded, sources)) { const key = allowlistKey(finding.file, finding.family.id, finding.symbol); - if (allowed.has(key)) { - used.add(key); - } else if (!reported.has(key)) { - // One report per file, family and symbol, matching what an allowlist entry covers. - reported.add(key); + const existing = grouped.get(key); + if (existing) existing.count += 1; + else grouped.set(key, { ...finding, count: 1 }); + } + for (const [key, finding] of grouped) { + const entry = allowed.get(key); + if (!entry) { errors.push(findingMessage(finding)); + continue; + } + used.add(key); + const allowedCount = entry.count ?? 1; + if (finding.count > allowedCount) errors.push(findingMessage(finding, allowedCount)); + else if (finding.count < allowedCount) { + errors.push( + `${registryFile}: allowlist entry for ${entry.file} / ${entry.family} / ${entry.symbol} allows ${allowedCount} but only ${finding.count} remain. Lower or remove "count".`, + ); } } for (const [key, entry] of allowed) { diff --git a/happyview-modules/tooling/shared-helpers.registry.json b/happyview-modules/tooling/shared-helpers.registry.json index 2b68b2ca..08498391 100644 --- a/happyview-modules/tooling/shared-helpers.registry.json +++ b/happyview-modules/tooling/shared-helpers.registry.json @@ -5,11 +5,11 @@ "description": "DID syntax check", "owners": ["lua/shared/didValidation.lua"], "names": ["valid_did"], - "lookalikes": ["^valid_[a-z_]*did$"], + "lookalikes": ["^valid_[a-z_]*did"], "inline": [ { "id": "did-pattern", - "pattern": "\\^did:\\(", + "pattern": "\\^did:", "description": "the DID syntax pattern" } ] @@ -19,18 +19,18 @@ "description": "NSID syntax check", "owners": ["lua/shared/nsidValidation.lua"], "names": ["valid_nsid"], - "lookalikes": ["^valid_[a-z_]*nsid$"] + "lookalikes": ["^valid_[a-z_]*nsid"] }, { "id": "record-identifier", "description": "AT-URI record key and record URI parsing", "owners": ["lua/shared/recordIdentifier.lua"], "names": ["valid_record_uri", "valid_record_key"], - "lookalikes": ["^[a-z_]+_valid_record_(uri|key)$", "^valid_record_[a-z_]+$"], + "lookalikes": ["valid_record_(uri|key)"], "inline": [ { "id": "at-uri-pattern", - "pattern": "\\^at://\\(", + "pattern": "\\^at://", "description": "the AT-URI parsing pattern" } ] @@ -46,7 +46,7 @@ "description": "RFC 3339 datetime check", "owners": ["lua/shared/datetimeValidation.lua"], "names": ["valid_datetime"], - "lookalikes": ["^valid_[a-z_]*(datetime|timestamp)$"] + "lookalikes": ["^valid_[a-z_]*(datetime|timestamp)"] }, { "id": "handle-resolver", @@ -62,20 +62,14 @@ "resolve_handle", "fail_resolver_config" ], - "lookalikes": ["^valid_(handle|ipv4|ipv6|port)[a-z_]*$", "^[a-z_]*resolve_handle$"] + "lookalikes": ["^valid_(handle|ipv4|ipv6|port)", "resolve_handle"] }, { "id": "list-cursor", "description": "list cursor encoding and decoding", "owners": ["lua/shared/listCursor.lua", "lua/shared/listQuery.lua"], "names": ["decode_cursor", "cursor_encode"], - "lookalikes": [ - "^([a-z_]+_)?cursor_decode$", - "^decode_[a-z_]+_cursor$", - "^[a-z_]+_cursor_encode$", - "^[a-z_]+_decode_cursor$", - "^encode_[a-z_]*cursor$" - ], + "lookalikes": ["cursor_(decode|encode)", "(decode|encode)_([a-z_]+_)?cursor"], "inline": [ { "id": "cursor-hex-decode", @@ -98,7 +92,7 @@ "lua/shared/listQuery.lua" ], "names": ["parse_list_limit", "parse_include_total", "parse_sort_direction"], - "lookalikes": ["^parse_[a-z_]*(limit|include_total|sort_direction)$"], + "lookalikes": ["^parse_[a-z_]*(limit|include_total|sort_direction)"], "inline": [ { "id": "limit-message", @@ -122,7 +116,7 @@ "description": "InvalidRequest errors, unknown-parameter checks and single-value parameters", "owners": ["lua/shared/query.lua"], "names": ["invalid", "keys_only", "scalar"], - "lookalikes": ["^[a-z_]+_(invalid|keys_only|scalar)$"], + "lookalikes": ["(^|_)(invalid|keys_only|scalar)$"], "inline": [ { "id": "occur-once-message", @@ -136,14 +130,14 @@ "description": "repeated query parameter (array) parsing", "owners": [], "unowned": "each endpoint has its own; add a shared parser in lua/shared and register it before adding another", - "lookalikes": ["^([a-z_]+_)?array(_values)?$"] + "lookalikes": ["(^|_)array(_values)?$"] }, { "id": "record-view", "description": "the {uri, cid, indexedAt, did, record} view of an indexed row", "owners": ["lua/shared/recordView.lua"], "names": ["record_view"], - "lookalikes": ["^[a-z_]+_record_view$"], + "lookalikes": ["record_view"], "inline": [ { "id": "indexed-at-null", @@ -208,7 +202,8 @@ "file": "lua/shared/activityList.lua", "family": "record-identifier", "symbol": "at-uri-pattern", - "reason": "Existing record-URI check that predates the registry; kept to avoid a behavior change. Build on valid_record_uri where the shape allows." + "reason": "Existing record-URI check that predates the registry; kept to avoid a behavior change. Build on valid_record_uri where the shape allows.", + "count": 2 }, { "file": "lua/shared/activityList.lua", @@ -726,5 +721,6 @@ "symbol": "badge_definition_array", "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." } - ] + ], + "allowlistNote": "The allowlist is a baseline of copies that existed when the lint was added. It is not approval to add more: new entries need a specific reason, and count must match the occurrences exactly." } From b043c780134e53c4bd32d79ed3f98bc6085f0a42 Mon Sep 17 00:00:00 2001 From: kzoeps Date: Thu, 26 Nov 2026 17:39:30 +0600 Subject: [PATCH 03/11] lint/shared-helpers: drop self-test and split registry validation Removes the lint tool's own test file and the export/params that only it used. Splits validateRegistry into per-family and per-entry helpers. --- .../unit/tooling/lint-shared-helpers.test.js | 209 ------------------ .../tooling/lint-shared-helpers.js | 62 +++--- 2 files changed, 36 insertions(+), 235 deletions(-) delete mode 100644 happyview-modules/tests/unit/tooling/lint-shared-helpers.test.js diff --git a/happyview-modules/tests/unit/tooling/lint-shared-helpers.test.js b/happyview-modules/tests/unit/tooling/lint-shared-helpers.test.js deleted file mode 100644 index 0b314fbe..00000000 --- a/happyview-modules/tests/unit/tooling/lint-shared-helpers.test.js +++ /dev/null @@ -1,209 +0,0 @@ -import assert from "node:assert/strict"; -import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import os from "node:os"; -import path from "node:path"; -import test from "node:test"; -import { checkSharedHelpers } from "../../../tooling/lint-shared-helpers.js"; - -const registry = (overrides = {}) => ({ - families: [ - { - id: "did-validation", - description: "DID syntax check", - owners: ["lua/shared/didValidation.lua"], - names: ["valid_did"], - lookalikes: ["^valid_[a-z_]*did$"], - inline: [{ id: "did-pattern", pattern: "\\^did:\\(", description: "the DID pattern" }], - }, - { - id: "repeated-query-array", - description: "array parsing", - owners: [], - unowned: "add a shared parser first", - lookalikes: ["^([a-z_]+_)?array$"], - }, - ], - allowlist: [], - ...overrides, -}); - -async function check(files, registryOverrides) { - const root = await mkdtemp(path.join(os.tmpdir(), "hypercerts-shared-helpers-")); - try { - await mkdir(path.join(root, "lua/shared"), { recursive: true }); - await mkdir(path.join(root, "lua/src"), { recursive: true }); - await mkdir(path.join(root, "lua/endpoints"), { recursive: true }); - for (const [file, source] of Object.entries(files)) { - await writeFile(path.join(root, file), source); - } - return (await checkSharedHelpers({ root, registry: registry(registryOverrides) })).errors; - } finally { - await rm(root, { recursive: true, force: true }); - } -} - -const owner = { - "lua/shared/didValidation.lua": "local function valid_did(value)\n return true\nend\n", -}; - -test("passes when only the owner defines the helper", async () => { - assert.deepEqual(await check(owner), []); -}); - -test("flags a redefinition outside the owner and says how to fix or allowlist it", async () => { - const [error, ...rest] = await check({ - ...owner, - "lua/src/getThing.lua": "local function valid_did(value)\n return false\nend\n", - }); - assert.equal(rest.length, 0); - assert.match(error, /^lua\/src\/getThing\.lua:1: defines "valid_did"/); - assert.match(error, /lua\/shared\/didValidation\.lua/); - assert.match(error, /sharedSourcePaths/); - assert.match(error, /"allowlist" in tooling\/shared-helpers\.registry\.json/); - assert.match(error, /"reason":""/); -}); - -test("flags lookalike names and inline re-implementations", async () => { - const errors = await check({ - ...owner, - "lua/src/getThing.lua": - 'local function valid_actor_did(v)\n return v:match("^did:([a-z]+):(.+)$")\nend\n', - }); - assert.equal(errors.length, 2); - assert.match( - errors.find((e) => e.includes(":1:")), - /looks like a new copy/, - ); - assert.match( - errors.find((e) => e.includes(":2:")), - /re-implements the DID pattern inline/, - ); -}); - -test("ignores commented code and generated endpoint bundles", async () => { - assert.deepEqual( - await check({ - ...owner, - "lua/src/getThing.lua": "-- local function valid_did(value)\nlocal x = 1 -- ^did:(\n", - "lua/endpoints/getThing.lua": "local function valid_did(value)\nend\n", - }), - [], - ); -}); - -test("unowned families tell the author to add a shared helper first", async () => { - const [error] = await check({ - ...owner, - "lua/src/listThings.lua": "local function array(params, key)\nend\n", - }); - assert.match(error, /No shared helper exists yet \(add a shared parser first\)/); -}); - -test("an allowlist entry silences exactly its file, family and symbol", async () => { - const files = { - ...owner, - "lua/src/a.lua": "local function valid_did(v)\nend\n", - "lua/src/b.lua": "local function valid_did(v)\nend\n", - }; - const errors = await check(files, { - allowlist: [ - { file: "lua/src/a.lua", family: "did-validation", symbol: "valid_did", reason: "kept" }, - ], - }); - assert.equal(errors.length, 1); - assert.match(errors[0], /^lua\/src\/b\.lua/); -}); - -test("a stale allowlist entry fails so the list cannot rot", async () => { - const [error] = await check(owner, { - allowlist: [ - { file: "lua/src/gone.lua", family: "did-validation", symbol: "valid_did", reason: "kept" }, - ], - }); - assert.match(error, /matches nothing.*delete the entry/); -}); - -test("rejects allowlist entries without a reason and owners that do not define the name", async () => { - await assert.rejects( - check(owner, { allowlist: [{ file: "x", family: "y", symbol: "z", reason: " " }] }), - /needs a nonempty "reason"/, - ); - const errors = await check({ "lua/shared/didValidation.lua": "local x = 1\n" }); - assert.match(errors[0], /protects "valid_did" but no owner file defines it/); -}); - -test("an allowlist count catches a second copy in an already-allowlisted file", async () => { - const files = { - ...owner, - "lua/src/a.lua": "local function valid_did(v)\nend\nlocal function valid_did(v)\nend\n", - }; - const entry = { - file: "lua/src/a.lua", - family: "did-validation", - symbol: "valid_did", - reason: "kept", - }; - const [error] = await check(files, { allowlist: [entry] }); - assert.match(error, /covers 1 occurrence\(s\) but 2 exist/); - assert.deepEqual(await check(files, { allowlist: [{ ...entry, count: 2 }] }), []); - const [stale] = await check( - { ...owner, "lua/src/a.lua": "local function valid_did(v)\nend\n" }, - { - allowlist: [{ ...entry, count: 2 }], - }, - ); - assert.match(stale, /allows 2 but only 1 remain/); -}); - -test("detects module-table definitions by their last segment", async () => { - const errors = await check({ - ...owner, - "lua/src/a.lua": - "function M.valid_did(v)\nend\nM.valid_did = function(v)\nend\nfunction M:valid_did(v)\nend\n", - }); - assert.equal(errors.length, 1); - assert.match(errors[0], /defines "valid_did"/); -}); - -// The real registry must catch the obvious new copy, not only exact names. -const realRegistryCases = [ - ["a suffixed DID validator", "local function valid_did_strict(v)\nend\n", /valid_did_strict/], - ["a module-table NSID validator", "function M.valid_nsid(v)\nend\n", /valid_nsid/], - [ - "a new datetime validator", - "local function valid_datetime_strict(v)\nend\n", - /valid_datetime_strict/, - ], - [ - "a prefixed cursor decoder", - "local function decode_widget_cursor(t)\nend\n", - /decode_widget_cursor/, - ], - ["a new array parser", "local function widget_array(p, k)\nend\n", /widget_array/], - ["an inline DID pattern", 'local ok = v:find("^did:[a-z]+:")\n', /DID syntax pattern/], - ["an inline AT-URI pattern", 'local a = v:match("^at://([^/]+)/")\n', /AT-URI parsing pattern/], - ["a local record view", "local function widget_record_view(r)\nend\n", /widget_record_view/], -]; - -for (const [name, source, expected] of realRegistryCases) { - test(`real registry flags ${name}`, async () => { - const packageRoot = path.resolve(import.meta.dirname, "../../.."); - const root = await mkdtemp(path.join(os.tmpdir(), "hypercerts-shared-helpers-real-")); - try { - await cp(path.join(packageRoot, "lua/shared"), path.join(root, "lua/shared"), { - recursive: true, - }); - await cp(path.join(packageRoot, "lua/src"), path.join(root, "lua/src"), { recursive: true }); - await writeFile(path.join(root, "lua/src/probe.lua"), source); - const realRegistry = JSON.parse( - await readFile(path.join(packageRoot, "tooling/shared-helpers.registry.json"), "utf8"), - ); - const { errors } = await checkSharedHelpers({ root, registry: realRegistry }); - assert.equal(errors.length, 1, errors.join("\n")); - assert.match(errors[0], /^lua\/src\/probe\.lua:1/); - assert.match(errors[0], expected); - } finally { - await rm(root, { recursive: true, force: true }); - } - }); -} diff --git a/happyview-modules/tooling/lint-shared-helpers.js b/happyview-modules/tooling/lint-shared-helpers.js index 12b024d7..774f1f11 100644 --- a/happyview-modules/tooling/lint-shared-helpers.js +++ b/happyview-modules/tooling/lint-shared-helpers.js @@ -35,36 +35,45 @@ function stripComment(line) { return index === -1 ? line : line.slice(0, index); } -/** Throws one error listing every problem in the registry itself, so a bad edit fails loudly. */ -function validateRegistry(registry) { +function familyProblems(family, seen) { const problems = []; - const seen = new Set(); - for (const family of registry.families ?? []) { - if (!family.id || seen.has(family.id)) - problems.push(`family id missing or duplicated: ${family.id}`); - seen.add(family.id); - if (!family.description) problems.push(`family ${family.id} needs a description`); - if (!Array.isArray(family.owners)) problems.push(`family ${family.id} needs an owners array`); - if (family.owners?.length === 0 && !family.unowned) { - problems.push( - `family ${family.id} has no owners; set "unowned": "" or name an owner file`, - ); - } + if (!family.id || seen.has(family.id)) + problems.push(`family id missing or duplicated: ${family.id}`); + seen.add(family.id); + if (!family.description) problems.push(`family ${family.id} needs a description`); + if (!Array.isArray(family.owners)) problems.push(`family ${family.id} needs an owners array`); + if (family.owners?.length === 0 && !family.unowned) { + problems.push( + `family ${family.id} has no owners; set "unowned": "" or name an owner file`, + ); } - for (const entry of registry.allowlist ?? []) { - if (entry.count !== undefined && !(Number.isInteger(entry.count) && entry.count >= 1)) { + return problems; +} + +function allowlistEntryProblems(entry) { + const problems = []; + if (entry.count !== undefined && !(Number.isInteger(entry.count) && entry.count >= 1)) { + problems.push( + `allowlist entry ${JSON.stringify(entry)} has an invalid "count"; use a positive integer`, + ); + } + for (const key of ["file", "family", "symbol", "reason"]) { + if (typeof entry[key] !== "string" || !entry[key].trim()) { problems.push( - `allowlist entry ${JSON.stringify(entry)} has an invalid "count"; use a positive integer`, + `allowlist entry ${JSON.stringify(entry)} needs a nonempty "${key}" (reason says why the copy must stay)`, ); } - for (const key of ["file", "family", "symbol", "reason"]) { - if (typeof entry[key] !== "string" || !entry[key].trim()) { - problems.push( - `allowlist entry ${JSON.stringify(entry)} needs a nonempty "${key}" (reason says why the copy must stay)`, - ); - } - } } + return problems; +} + +/** Throws one error listing every problem in the registry itself, so a bad edit fails loudly. */ +function validateRegistry(registry) { + const seen = new Set(); + const problems = [ + ...(registry.families ?? []).flatMap((family) => familyProblems(family, seen)), + ...(registry.allowlist ?? []).flatMap(allowlistEntryProblems), + ]; if (problems.length > 0) { throw new Error(`Invalid ${registryFile}:\n- ${problems.join("\n- ")}`); } @@ -182,8 +191,9 @@ function allowlistKey(file, family, symbol) { * Checks handwritten Lua against the shared-helper registry. * Returns { errors: string[] }; an empty list means the check passed. */ -export async function checkSharedHelpers({ root = defaultRoot, registry } = {}) { - const loaded = registry ?? JSON.parse(await readFile(path.join(root, registryFile), "utf8")); +async function checkSharedHelpers() { + const root = defaultRoot; + const loaded = JSON.parse(await readFile(path.join(root, registryFile), "utf8")); validateRegistry(loaded); const files = (await Promise.all(scannedDirectories.map((dir) => luaFiles(root, dir)))).flat(); From 58e21f5faa564246bca7102770780e9b0360f8d5 Mon Sep 17 00:00:00 2001 From: kzoeps Date: Thu, 26 Nov 2026 17:44:43 +0600 Subject: [PATCH 04/11] lint/shared-helpers: protect every top-level lua/shared function automatically Redefining a name defined in lua/shared, or defining the same name in two shared files, fails lint and names the owning file. The registry now holds only lookalike and inline patterns, their home files and the allowlist. --- AGENTS.md | 2 +- .../tooling/lint-shared-helpers.js | 157 +++++----- .../tooling/shared-helpers.registry.json | 278 +++++++++++------- 3 files changed, 269 insertions(+), 168 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index bc2b86e9..99713c3d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,4 +9,4 @@ - HTTP runtime tests use a task-owned local Compose project and disposable database. Do not target or tear down unrelated services; note that the Compose bridge network permits egress and the configured proxy is not network-level isolation. - Every new query endpoint needs a case in `happyview-modules/tooling/smoke-cases.js`. Add it to `happyview-modules/tooling/e2e.js` only if it has paging walks, count invariants or batch behaviour. When an endpoint's behavior changes, update the checks that cover it. - Reuse and extend the canonical Lua helpers in `happyview-modules/lua/shared/` instead of writing a new copy in a handler or another shared file. Before writing a helper, search `happyview-modules/lua/shared/` and `happyview-modules/tooling/shared-helpers.registry.json` for an existing one; the lint only catches some copies. Families: DID, NSID, record URI/key, subject URI, datetime, handle/resolver, list cursor, list limit/includeTotal/sortDirection, query parameter helpers (`invalid`, `keys_only`, `scalar`), record view, actor view and batch request-target. Repeated-parameter (array) parsing has no shared helper yet. -- `pnpm lint` (so `pnpm check` and CI) runs `happyview-modules/tooling/lint-shared-helpers.js` on `lua/shared` and `lua/src`. Register each new shared helper in `shared-helpers.registry.json` (paths relative to `happyview-modules/`): add its name to the owning family's `names`, or add a family with `id`, `description`, `owners`, `names` and optional `lookalikes`/`inline` patterns. To keep an existing copy, add `{file, family, symbol, reason}` to `allowlist` (`symbol` is the function name or inline rule id; add `count` if it occurs more than once). The failure message prints a ready-made entry. An entry that no longer matches fails lint; delete it. The current allowlist is a baseline, not approval for new copies. +- `pnpm lint` (so `pnpm check` and CI) runs `happyview-modules/tooling/lint-shared-helpers.js` on `lua/shared` and `lua/src`. Every top-level function defined in `lua/shared` is protected automatically: defining the same name in another shared file or in `lua/src` fails lint and names the file that owns it. Nothing to register for a new shared helper, but check the names already there first. `shared-helpers.registry.json` (paths relative to `happyview-modules/`) holds only lookalike name patterns and inline code patterns per family (`id`, `description`, `homes` = files where the patterns legitimately appear, `lookalikes`/`inline`) and the `allowlist`. To keep an existing copy, add `{file, family, symbol, reason}` to `allowlist` (`family` is `shared-helper` for a name defined in `lua/shared`; `symbol` is the function name or inline rule id; add `count` if it occurs more than once). The failure message prints a ready-made entry. An entry that no longer matches fails lint; delete it. The current allowlist is a baseline, not approval for new copies. diff --git a/happyview-modules/tooling/lint-shared-helpers.js b/happyview-modules/tooling/lint-shared-helpers.js index 774f1f11..b3a26ae6 100644 --- a/happyview-modules/tooling/lint-shared-helpers.js +++ b/happyview-modules/tooling/lint-shared-helpers.js @@ -14,6 +14,18 @@ const DEFINITION_PATTERNS = [ /^\s*(?:local\s+)?([A-Za-z_][\w.]*)\s*=\s*function\s*\(/, ]; +// The same shapes anchored at column 0: only these count as a shared helper's definition. +const TOP_LEVEL_PATTERNS = DEFINITION_PATTERNS.map( + (pattern) => new RegExp(pattern.source.replace("^\\s*", "^")), +); + +// Every top-level function in lua/shared is protected. It is not a registry family, so it has no patterns. +const SHARED_FAMILY = { + id: "shared-helper", + description: "a function already defined in lua/shared", + homes: [], +}; + async function luaFiles(root, directory) { const entries = await readdir(path.join(root, directory), { withFileTypes: true }); return entries @@ -22,8 +34,8 @@ async function luaFiles(root, directory) { .sort(); } -function definitionName(line) { - for (const pattern of DEFINITION_PATTERNS) { +function definitionName(line, patterns = DEFINITION_PATTERNS) { + for (const pattern of patterns) { const match = pattern.exec(line); if (match) return match[1].split(/[.:]/).pop(); } @@ -41,12 +53,15 @@ function familyProblems(family, seen) { problems.push(`family id missing or duplicated: ${family.id}`); seen.add(family.id); if (!family.description) problems.push(`family ${family.id} needs a description`); - if (!Array.isArray(family.owners)) problems.push(`family ${family.id} needs an owners array`); - if (family.owners?.length === 0 && !family.unowned) { + if (!Array.isArray(family.homes)) problems.push(`family ${family.id} needs a homes array`); + if (family.homes?.length === 0 && !family.unowned) { problems.push( - `family ${family.id} has no owners; set "unowned": "" or name an owner file`, + `family ${family.id} has no homes; set "unowned": "" or name the shared file where its patterns belong`, ); } + if (!family.lookalikes?.length && !family.inline?.length) { + problems.push(`family ${family.id} needs "lookalikes" or "inline" patterns`); + } return problems; } @@ -79,82 +94,87 @@ function validateRegistry(registry) { } } -function ownersDefine(family, sources) { - const defined = new Set(); - for (const owner of family.owners) { - const source = sources.get(owner); - if (source === undefined) continue; +function registryFindings(registry, sources) { + return registry.families.flatMap((family) => + family.homes + .filter((home) => !sources.has(home)) + .map((home) => ({ + message: `${registryFile}: family "${family.id}" home ${home} does not exist. Update the path or remove it.`, + })), + ); +} + +function homeHint(family) { + if (family.homes.length === 0) { + return `No shared helper exists yet (${family.unowned}).`; + } + return `Use the shared helper from ${family.homes.join(" or ")} (declare it in the module's sharedSourcePaths).`; +} + +/** Maps each top-level function name in lua/shared to the first file that defines it. */ +function sharedHelperOwners(sources) { + const owners = new Map(); + for (const [file, source] of sources) { + if (!file.startsWith("lua/shared/")) continue; for (const line of source.split("\n")) { - const name = definitionName(line); - if (name) defined.add(name); + const name = definitionName(stripComment(line), TOP_LEVEL_PATTERNS); + if (name && !owners.has(name)) owners.set(name, file); } } - return defined; + return owners; } -function registryFindings(registry, sources) { +function patternFindings(family, file, lines, shared) { const findings = []; - for (const family of registry.families) { - for (const owner of family.owners) { - if (!sources.has(owner)) { - findings.push({ - kind: "registry", - message: `${registryFile}: family "${family.id}" owner ${owner} does not exist. Update the owner path or remove the family.`, - }); - } + const lookalikes = (family.lookalikes ?? []).map((pattern) => new RegExp(pattern)); + const inline = (family.inline ?? []).map((rule) => ({ + ...rule, + regex: new RegExp(rule.pattern), + })); + lines.forEach((rawLine, index) => { + const line = stripComment(rawLine); + const name = definitionName(line); + // A copy of a name another shared file defines is reported once, as a shared-helper copy. + const owner = name && shared.get(name); + if (name && (!owner || owner === file) && lookalikes.some((regex) => regex.test(name))) { + findings.push({ kind: "lookalike", file, line: index + 1, family, symbol: name }); } - const defined = ownersDefine(family, sources); - for (const name of family.names ?? []) { - if (family.owners.length > 0 && !defined.has(name)) { - findings.push({ - kind: "registry", - message: `${registryFile}: family "${family.id}" protects "${name}" but no owner file defines it. Fix the name or the owner list.`, - }); + for (const rule of inline) { + if (rule.regex.test(line)) { + findings.push({ kind: "inline", file, line: index + 1, family, symbol: rule.id, rule }); } } - } + }); return findings; } -function ownerHint(family) { - if (family.owners.length === 0) { - return `No shared helper exists yet (${family.unowned}).`; - } - return `Use the shared helper from ${family.owners.join(" or ")} (declare it in the module's sharedSourcePaths).`; -} - function sourceFindings(registry, sources) { + const shared = sharedHelperOwners(sources); const findings = []; - // A name another family protects is that family's business, not a lookalike here. - const protectedElsewhere = (family) => - new Set( - registry.families.filter((other) => other !== family).flatMap((other) => other.names ?? []), - ); for (const [file, source] of sources) { const lines = source.split("\n"); + lines.forEach((rawLine, index) => { + const line = stripComment(rawLine); + const name = definitionName(line); + const owner = name && shared.get(name); + // Inside lua/shared only a top-level definition can be a second copy; nested locals are private. + const counts = file.startsWith("lua/shared/") + ? definitionName(line, TOP_LEVEL_PATTERNS) === name + : true; + if (owner && owner !== file && counts) { + findings.push({ + kind: "redefinition", + file, + line: index + 1, + family: SHARED_FAMILY, + symbol: name, + owner, + }); + } + }); for (const family of registry.families) { - if (family.owners.includes(file)) continue; - const protectedNames = new Set(family.names ?? []); - const elsewhere = protectedElsewhere(family); - const lookalikes = (family.lookalikes ?? []).map((pattern) => new RegExp(pattern)); - const inline = (family.inline ?? []).map((rule) => ({ - ...rule, - regex: new RegExp(rule.pattern), - })); - lines.forEach((rawLine, index) => { - const line = stripComment(rawLine); - const name = definitionName(line); - if (name && protectedNames.has(name)) { - findings.push({ kind: "redefinition", file, line: index + 1, family, symbol: name }); - } else if (name && !elsewhere.has(name) && lookalikes.some((regex) => regex.test(name))) { - findings.push({ kind: "lookalike", file, line: index + 1, family, symbol: name }); - } - for (const rule of inline) { - if (rule.regex.test(line)) { - findings.push({ kind: "inline", file, line: index + 1, family, symbol: rule.id, rule }); - } - } - }); + if (family.homes.includes(file)) continue; + findings.push(...patternFindings(family, file, lines, shared)); } } return findings; @@ -162,9 +182,14 @@ function sourceFindings(registry, sources) { function findingMessage(finding, allowedCount) { const { kind, file, line, family, symbol, rule, count } = finding; + const hint = + kind === "redefinition" + ? `Use ${symbol} from ${finding.owner} (declare it in the module's sharedSourcePaths), or rename this one.` + : homeHint(family); const where = `${file}:${line}`; const what = { - redefinition: () => `defines "${symbol}", a protected shared helper (${family.description}).`, + redefinition: () => + `defines "${symbol}", which lua/shared already defines in ${finding.owner}.`, lookalike: () => `defines "${symbol}", which looks like a new copy of the ${family.id} helpers (${family.description}).`, inline: () => `re-implements ${rule.description} inline (${family.description}).`, @@ -180,7 +205,7 @@ function findingMessage(finding, allowedCount) { allowedCount === undefined ? `If the copy must stay, add to "allowlist" in ${registryFile}:` : `The allowlist covers ${allowedCount} occurrence(s) but ${count} exist now. Remove the new copy, or raise "count" with a reason:`; - return [`${where}: ${what}`, ` ${ownerHint(family)} ${advice}`, ` ${entry}`].join("\n"); + return [`${where}: ${what}`, ` ${hint} ${advice}`, ` ${entry}`].join("\n"); } function allowlistKey(file, family, symbol) { diff --git a/happyview-modules/tooling/shared-helpers.registry.json b/happyview-modules/tooling/shared-helpers.registry.json index 08498391..008dfbc0 100644 --- a/happyview-modules/tooling/shared-helpers.registry.json +++ b/happyview-modules/tooling/shared-helpers.registry.json @@ -3,8 +3,6 @@ { "id": "did-validation", "description": "DID syntax check", - "owners": ["lua/shared/didValidation.lua"], - "names": ["valid_did"], "lookalikes": ["^valid_[a-z_]*did"], "inline": [ { @@ -12,20 +10,18 @@ "pattern": "\\^did:", "description": "the DID syntax pattern" } - ] + ], + "homes": ["lua/shared/didValidation.lua"] }, { "id": "nsid-validation", "description": "NSID syntax check", - "owners": ["lua/shared/nsidValidation.lua"], - "names": ["valid_nsid"], - "lookalikes": ["^valid_[a-z_]*nsid"] + "lookalikes": ["^valid_[a-z_]*nsid"], + "homes": ["lua/shared/nsidValidation.lua"] }, { "id": "record-identifier", "description": "AT-URI record key and record URI parsing", - "owners": ["lua/shared/recordIdentifier.lua"], - "names": ["valid_record_uri", "valid_record_key"], "lookalikes": ["valid_record_(uri|key)"], "inline": [ { @@ -33,42 +29,24 @@ "pattern": "\\^at://", "description": "the AT-URI parsing pattern" } - ] - }, - { - "id": "subject-record-uri", - "description": "DID-authority subject AT-URI check", - "owners": ["lua/shared/subjectRecordUri.lua"], - "names": ["valid_subject_record_uri", "valid_did_percent_escapes"] + ], + "homes": ["lua/shared/recordIdentifier.lua"] }, { "id": "datetime-validation", "description": "RFC 3339 datetime check", - "owners": ["lua/shared/datetimeValidation.lua"], - "names": ["valid_datetime"], - "lookalikes": ["^valid_[a-z_]*(datetime|timestamp)"] + "lookalikes": ["^valid_[a-z_]*(datetime|timestamp)"], + "homes": ["lua/shared/datetimeValidation.lua"] }, { "id": "handle-resolver", "description": "handle syntax check and handle resolution", - "owners": ["lua/shared/profileLookup.lua"], - "names": [ - "valid_handle", - "valid_resolver_authority", - "valid_ipv4", - "valid_ipv6", - "valid_port", - "resolver_base_url", - "resolve_handle", - "fail_resolver_config" - ], - "lookalikes": ["^valid_(handle|ipv4|ipv6|port)", "resolve_handle"] + "lookalikes": ["^valid_(handle|ipv4|ipv6|port)", "resolve_handle"], + "homes": ["lua/shared/profileLookup.lua"] }, { "id": "list-cursor", "description": "list cursor encoding and decoding", - "owners": ["lua/shared/listCursor.lua", "lua/shared/listQuery.lua"], - "names": ["decode_cursor", "cursor_encode"], "lookalikes": ["cursor_(decode|encode)", "(decode|encode)_([a-z_]+_)?cursor"], "inline": [ { @@ -81,17 +59,12 @@ "pattern": "#token > 8192", "description": "the cursor length cap" } - ] + ], + "homes": ["lua/shared/listCursor.lua", "lua/shared/listQuery.lua"] }, { "id": "list-params", "description": "limit, includeTotal and sortDirection parsing", - "owners": [ - "lua/shared/listValidation.lua", - "lua/shared/includeTotal.lua", - "lua/shared/listQuery.lua" - ], - "names": ["parse_list_limit", "parse_include_total", "parse_sort_direction"], "lookalikes": ["^parse_[a-z_]*(limit|include_total|sort_direction)"], "inline": [ { @@ -109,13 +82,16 @@ "pattern": "sortDirection must be", "description": "sortDirection parsing" } + ], + "homes": [ + "lua/shared/listValidation.lua", + "lua/shared/includeTotal.lua", + "lua/shared/listQuery.lua" ] }, { "id": "query-params", "description": "InvalidRequest errors, unknown-parameter checks and single-value parameters", - "owners": ["lua/shared/query.lua"], - "names": ["invalid", "keys_only", "scalar"], "lookalikes": ["(^|_)(invalid|keys_only|scalar)$"], "inline": [ { @@ -123,20 +99,19 @@ "pattern": "must occur once", "description": "single-value parameter parsing" } - ] + ], + "homes": ["lua/shared/query.lua"] }, { "id": "repeated-query-array", "description": "repeated query parameter (array) parsing", - "owners": [], "unowned": "each endpoint has its own; add a shared parser in lua/shared and register it before adding another", - "lookalikes": ["(^|_)array(_values)?$"] + "lookalikes": ["(^|_)array(_values)?$"], + "homes": [] }, { "id": "record-view", "description": "the {uri, cid, indexedAt, did, record} view of an indexed row", - "owners": ["lua/shared/recordView.lua"], - "names": ["record_view"], "lookalikes": ["record_view"], "inline": [ { @@ -144,21 +119,20 @@ "pattern": "indexed_at == nil and NULL", "description": "the indexedAt null fallback" } - ] + ], + "homes": ["lua/shared/recordView.lua"] }, { "id": "actor-view", "description": "actor profile/organization hydration", - "owners": ["lua/shared/actorView.lua"], - "names": ["hydrate_actor_views"], - "lookalikes": ["^[a-z_]*hydrate_[a-z_]*actor_views$"] + "lookalikes": ["^[a-z_]*hydrate_[a-z_]*actor_views$"], + "homes": ["lua/shared/actorView.lua"] }, { "id": "batch-request-target", "description": "batch GET request-target size limit", - "owners": ["lua/shared/batchRequestTarget.lua"], - "names": ["assert_batch_request_target", "encoded_query_value_length"], - "lookalikes": ["^[a-z_]*request_target[a-z_]*$"] + "lookalikes": ["^[a-z_]*request_target[a-z_]*$"], + "homes": ["lua/shared/batchRequestTarget.lua"] } ], "allowlist": [ @@ -403,12 +377,6 @@ "symbol": "measurement_valid_record_uri", "reason": "Existing record-URI check that predates the registry; kept to avoid a behavior change. Build on valid_record_uri where the shape allows." }, - { - "file": "lua/shared/organizationList.lua", - "family": "list-cursor", - "symbol": "cursor_decode", - "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." - }, { "file": "lua/shared/organizationList.lua", "family": "list-cursor", @@ -427,12 +395,6 @@ "symbol": "array", "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." }, - { - "file": "lua/shared/profileList.lua", - "family": "list-cursor", - "symbol": "cursor_decode", - "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." - }, { "file": "lua/shared/profileList.lua", "family": "list-cursor", @@ -445,12 +407,6 @@ "symbol": "at-uri-pattern", "reason": "Existing record-URI check that predates the registry; kept to avoid a behavior change. Build on valid_record_uri where the shape allows." }, - { - "file": "lua/shared/profileList.lua", - "family": "repeated-query-array", - "symbol": "array", - "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." - }, { "file": "lua/shared/recentFollows.lua", "family": "list-cursor", @@ -505,12 +461,6 @@ "symbol": "hydrate_vocab_actor_views", "reason": "Existing actor hydration variant; kept to avoid a behavior change. Build on hydrate_actor_views where the shape allows." }, - { - "file": "lua/shared/workscopeRecordView.lua", - "family": "record-view", - "symbol": "record_view", - "reason": "Deliberately differs from recordView.lua: workscope sidecars omit a missing indexedAt instead of encoding JSON null (see the file comment). Both define record_view, so a bundle must not include both." - }, { "file": "lua/shared/workscopeTag.lua", "family": "record-identifier", @@ -547,12 +497,6 @@ "symbol": "include-total-message", "reason": "Existing endpoint-local list parameter parsing; kept to avoid a behavior change. Use includeTotal.lua instead." }, - { - "file": "lua/src/listBadgeAwards.lua", - "family": "list-params", - "symbol": "parse_include_total", - "reason": "Existing endpoint-local list parameter parsing; kept to avoid a behavior change. Use includeTotal.lua instead." - }, { "file": "lua/src/listBadgeAwards.lua", "family": "repeated-query-array", @@ -649,24 +593,12 @@ "symbol": "feature_array", "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." }, - { - "file": "lua/src/listLocations.lua", - "family": "list-cursor", - "symbol": "cursor_decode", - "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." - }, { "file": "lua/src/listLocations.lua", "family": "list-cursor", "symbol": "cursor-hex-decode", "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." }, - { - "file": "lua/src/listLocations.lua", - "family": "repeated-query-array", - "symbol": "array", - "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." - }, { "file": "lua/src/listMeasurements.lua", "family": "list-cursor", @@ -697,12 +629,6 @@ "symbol": "cursor-hex-decode", "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." }, - { - "file": "lua/src/listVocabTags.lua", - "family": "list-cursor", - "symbol": "decode_cursor", - "reason": "Existing endpoint-local cursor code that predates the registry; kept to avoid a behavior change. Move onto decode_cursor where the cursor shape allows." - }, { "file": "lua/src/searchBadgeDefinitions.lua", "family": "list-cursor", @@ -720,6 +646,156 @@ "family": "repeated-query-array", "symbol": "badge_definition_array", "reason": "Existing endpoint-local repeated-parameter parser; no shared parser exists yet. Kept to avoid a behavior change." + }, + { + "file": "lua/shared/actorFollow.lua", + "family": "shared-helper", + "symbol": "query", + "reason": "Per-module query entry point that shares a name; not a reusable helper." + }, + { + "file": "lua/shared/location.lua", + "family": "shared-helper", + "symbol": "query", + "reason": "Per-module query entry point that shares a name; not a reusable helper." + }, + { + "file": "lua/shared/organization.lua", + "family": "shared-helper", + "symbol": "query", + "reason": "Per-module query entry point that shares a name; not a reusable helper." + }, + { + "file": "lua/shared/organizationList.lua", + "family": "shared-helper", + "symbol": "cursor_decode", + "reason": "Existing duplicate of a lua/shared helper; baseline until the consolidation PRs land." + }, + { + "file": "lua/shared/profile.lua", + "family": "shared-helper", + "symbol": "query", + "reason": "Per-module query entry point that shares a name; not a reusable helper." + }, + { + "file": "lua/shared/profileList.lua", + "family": "shared-helper", + "symbol": "array", + "reason": "Existing duplicate of a lua/shared helper; baseline until the consolidation PRs land." + }, + { + "file": "lua/shared/profileList.lua", + "family": "shared-helper", + "symbol": "cursor_decode", + "reason": "Existing duplicate of a lua/shared helper; baseline until the consolidation PRs land." + }, + { + "file": "lua/shared/subjectRecordUri.lua", + "family": "did-validation", + "symbol": "valid_did_percent_escapes", + "reason": "Distinct check (percent escapes in a DID authority) for subject URIs, not a second DID validator." + }, + { + "file": "lua/shared/workscopeRecordView.lua", + "family": "shared-helper", + "symbol": "record_view", + "reason": "Existing duplicate of a lua/shared helper; baseline until the consolidation PRs land." + }, + { + "file": "lua/src/getBadgeAward.lua", + "family": "shared-helper", + "symbol": "query", + "reason": "Per-module query entry point that shares a name; not a reusable helper." + }, + { + "file": "lua/src/getBadgeDefinition.lua", + "family": "shared-helper", + "symbol": "query", + "reason": "Per-module query entry point that shares a name; not a reusable helper." + }, + { + "file": "lua/src/getBadgeResponse.lua", + "family": "shared-helper", + "symbol": "query", + "reason": "Per-module query entry point that shares a name; not a reusable helper." + }, + { + "file": "lua/src/getVocabTag.lua", + "family": "shared-helper", + "symbol": "query", + "reason": "Per-module query entry point that shares a name; not a reusable helper." + }, + { + "file": "lua/src/listBadgeAwards.lua", + "family": "shared-helper", + "symbol": "valid_badge_definition_uri", + "reason": "Existing duplicate of a lua/shared helper; baseline until the consolidation PRs land." + }, + { + "file": "lua/src/listBadgeAwards.lua", + "family": "shared-helper", + "symbol": "query", + "reason": "Per-module query entry point that shares a name; not a reusable helper." + }, + { + "file": "lua/src/listBadgeAwards.lua", + "family": "shared-helper", + "symbol": "parse_include_total", + "reason": "Existing duplicate of a lua/shared helper; baseline until the consolidation PRs land." + }, + { + "file": "lua/src/listBadgeDefinitions.lua", + "family": "shared-helper", + "symbol": "query", + "reason": "Per-module query entry point that shares a name; not a reusable helper." + }, + { + "file": "lua/src/listBadgeResponses.lua", + "family": "shared-helper", + "symbol": "query", + "reason": "Per-module query entry point that shares a name; not a reusable helper." + }, + { + "file": "lua/src/listLocations.lua", + "family": "shared-helper", + "symbol": "array", + "reason": "Existing duplicate of a lua/shared helper; baseline until the consolidation PRs land." + }, + { + "file": "lua/src/listLocations.lua", + "family": "shared-helper", + "symbol": "add_in", + "reason": "Existing duplicate of a lua/shared helper; baseline until the consolidation PRs land." + }, + { + "file": "lua/src/listLocations.lua", + "family": "shared-helper", + "symbol": "cursor_decode", + "reason": "Existing duplicate of a lua/shared helper; baseline until the consolidation PRs land." + }, + { + "file": "lua/src/listMeasurements.lua", + "family": "shared-helper", + "symbol": "bind_values", + "reason": "Existing duplicate of a lua/shared helper; baseline until the consolidation PRs land." + }, + { + "file": "lua/src/listVocabTags.lua", + "family": "shared-helper", + "symbol": "query", + "reason": "Per-module query entry point that shares a name; not a reusable helper." + }, + { + "file": "lua/src/listVocabTags.lua", + "family": "shared-helper", + "symbol": "decode_cursor", + "reason": "Existing duplicate of a lua/shared helper; baseline until the consolidation PRs land." + }, + { + "file": "lua/src/searchBadgeDefinitions.lua", + "family": "shared-helper", + "symbol": "query", + "reason": "Per-module query entry point that shares a name; not a reusable helper." } ], "allowlistNote": "The allowlist is a baseline of copies that existed when the lint was added. It is not approval to add more: new entries need a specific reason, and count must match the occurrences exactly." From b246b9d145f79c6ab5244098f6a5240d7a2f2974 Mon Sep 17 00:00:00 2001 From: kzoeps Date: Thu, 26 Nov 2026 17:48:25 +0600 Subject: [PATCH 05/11] lint/shared-helpers: drop allowlist entry for removed percent-escape helper --- happyview-modules/tooling/shared-helpers.registry.json | 6 ------ 1 file changed, 6 deletions(-) diff --git a/happyview-modules/tooling/shared-helpers.registry.json b/happyview-modules/tooling/shared-helpers.registry.json index 008dfbc0..c548c552 100644 --- a/happyview-modules/tooling/shared-helpers.registry.json +++ b/happyview-modules/tooling/shared-helpers.registry.json @@ -689,12 +689,6 @@ "symbol": "cursor_decode", "reason": "Existing duplicate of a lua/shared helper; baseline until the consolidation PRs land." }, - { - "file": "lua/shared/subjectRecordUri.lua", - "family": "did-validation", - "symbol": "valid_did_percent_escapes", - "reason": "Distinct check (percent escapes in a DID authority) for subject URIs, not a second DID validator." - }, { "file": "lua/shared/workscopeRecordView.lua", "family": "shared-helper", From a78ff72cb295c44f8c5d1b240748e8aba8de8885 Mon Sep 17 00:00:00 2001 From: kzoeps Date: Thu, 26 Nov 2026 17:51:44 +0600 Subject: [PATCH 06/11] lint/shared-helpers: write top-level definition patterns as literals --- happyview-modules/tooling/lint-shared-helpers.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/happyview-modules/tooling/lint-shared-helpers.js b/happyview-modules/tooling/lint-shared-helpers.js index b3a26ae6..ddb4e17c 100644 --- a/happyview-modules/tooling/lint-shared-helpers.js +++ b/happyview-modules/tooling/lint-shared-helpers.js @@ -15,9 +15,10 @@ const DEFINITION_PATTERNS = [ ]; // The same shapes anchored at column 0: only these count as a shared helper's definition. -const TOP_LEVEL_PATTERNS = DEFINITION_PATTERNS.map( - (pattern) => new RegExp(pattern.source.replace("^\\s*", "^")), -); +const TOP_LEVEL_PATTERNS = [ + /^(?:local\s+)?function\s+([A-Za-z_][\w.:]*)\s*\(/, + /^(?:local\s+)?([A-Za-z_][\w.]*)\s*=\s*function\s*\(/, +]; // Every top-level function in lua/shared is protected. It is not a registry family, so it has no patterns. const SHARED_FAMILY = { From 7a377f26b8b4dd5416aa16d49a6a6e7ffc9a15ca Mon Sep 17 00:00:00 2001 From: kzoeps Date: Thu, 26 Nov 2026 18:38:07 +0600 Subject: [PATCH 07/11] lint-shared-helpers: scan whole Lua source for definitions, comments and inline matches Definitions split across lines, indented top-level functions, long comments and repeated inline matches on one line were missed or misreported. Registry format is unchanged. --- .../tooling/lint-shared-helpers.js | 153 ++++++++++++------ 1 file changed, 104 insertions(+), 49 deletions(-) diff --git a/happyview-modules/tooling/lint-shared-helpers.js b/happyview-modules/tooling/lint-shared-helpers.js index ddb4e17c..87e206fa 100644 --- a/happyview-modules/tooling/lint-shared-helpers.js +++ b/happyview-modules/tooling/lint-shared-helpers.js @@ -9,15 +9,10 @@ const scannedDirectories = ["lua/shared", "lua/src"]; // Matches `function name(`, `function M.name(`, `function M:name(` and `M.name = function(`. // Only the last segment is the helper's name, so a module-table copy is still a copy. +// \s* also spans newlines, so a definition split across lines is still found. const DEFINITION_PATTERNS = [ - /^\s*(?:local\s+)?function\s+([A-Za-z_][\w.:]*)\s*\(/, - /^\s*(?:local\s+)?([A-Za-z_][\w.]*)\s*=\s*function\s*\(/, -]; - -// The same shapes anchored at column 0: only these count as a shared helper's definition. -const TOP_LEVEL_PATTERNS = [ - /^(?:local\s+)?function\s+([A-Za-z_][\w.:]*)\s*\(/, - /^(?:local\s+)?([A-Za-z_][\w.]*)\s*=\s*function\s*\(/, + /^[ \t]*(?:local\s+)?function\s+([A-Za-z_][\w.:]*)\s*\(/gm, + /^[ \t]*(?:local\s+)?([A-Za-z_][\w.]*)\s*=\s*function\s*\(/gm, ]; // Every top-level function in lua/shared is protected. It is not a registry family, so it has no patterns. @@ -35,17 +30,77 @@ async function luaFiles(root, directory) { .sort(); } -function definitionName(line, patterns = DEFINITION_PATTERNS) { - for (const pattern of patterns) { - const match = pattern.exec(line); - if (match) return match[1].split(/[.:]/).pop(); +const LONG_BRACKET = /^\[(=*)\[/; + +/** + * Returns the source with Lua comments blanked to spaces, and string contents too unless + * keepStrings is set. Newlines and offsets are preserved so matches map back to lines. + * Tracking both together is what keeps a `--` inside a string and a `function` inside a + * long comment from being misread. + */ +function blankLua(source, { keepStrings = false } = {}) { + let out = ""; + let i = 0; + const blank = (text) => text.replace(/[^\n]/g, " "); + while (i < source.length) { + const rest = source.slice(i); + const isComment = rest.startsWith("--"); + const long = LONG_BRACKET.exec(isComment ? rest.slice(2) : rest); + if (long) { + const close = `]${long[1]}]`; + const start = i + (isComment ? 2 : 0) + long[0].length; + const end = source.indexOf(close, start); + const stop = end === -1 ? source.length : end + close.length; + const text = source.slice(i, stop); + out += isComment || !keepStrings ? blank(text) : text; + i = stop; + } else if (isComment) { + const end = source.indexOf("\n", i); + const stop = end === -1 ? source.length : end; + out += blank(source.slice(i, stop)); + i = stop; + } else if (rest[0] === '"' || rest[0] === "'") { + let stop = i + 1; + while (stop < source.length && source[stop] !== rest[0] && source[stop] !== "\n") { + stop += source[stop] === "\\" ? 2 : 1; + } + stop = Math.min(stop + 1, source.length); + const text = source.slice(i, stop); + out += keepStrings ? text : rest[0] + blank(text.slice(1, -1)) + text.slice(-1); + i = stop; + } else { + out += source[i]; + i += 1; + } } - return null; + return out; } -function stripComment(line) { - const index = line.indexOf("--"); - return index === -1 ? line : line.slice(0, index); +/** Block nesting depth before each offset: function/if/do/repeat open, end/until close. */ +function depthTracker(code) { + const events = [...code.matchAll(/\b(function|if|do|repeat|end|until)\b/g)].map((m) => ({ + index: m.index, + delta: m[1] === "end" || m[1] === "until" ? -1 : 1, + })); + return (offset) => + events.filter((event) => event.index < offset).reduce((sum, event) => sum + event.delta, 0); +} + +/** Every function definition in a Lua file: last-segment name, 1-based line, top-level or nested. */ +function definitions(source) { + const code = blankLua(source); + const depthAt = depthTracker(code); + return DEFINITION_PATTERNS.flatMap((pattern) => + [...code.matchAll(pattern)].map((match) => { + const nameStart = match.index + match[0].indexOf(match[1]); + return { + name: match[1].split(/[.:]/).pop(), + // Report the line of the name, not of leading blank space. + line: code.slice(0, nameStart).split("\n").length, + topLevel: depthAt(match.index) === 0, + }; + }), + ); } function familyProblems(family, seen) { @@ -113,69 +168,69 @@ function homeHint(family) { } /** Maps each top-level function name in lua/shared to the first file that defines it. */ -function sharedHelperOwners(sources) { +function sharedHelperOwners(parsed) { const owners = new Map(); - for (const [file, source] of sources) { + for (const [file, { defs }] of parsed) { if (!file.startsWith("lua/shared/")) continue; - for (const line of source.split("\n")) { - const name = definitionName(stripComment(line), TOP_LEVEL_PATTERNS); - if (name && !owners.has(name)) owners.set(name, file); + for (const def of defs) { + if (def.topLevel && !owners.has(def.name)) owners.set(def.name, file); } } return owners; } -function patternFindings(family, file, lines, shared) { +function patternFindings(family, file, { defs, inlineLines }, shared) { const findings = []; const lookalikes = (family.lookalikes ?? []).map((pattern) => new RegExp(pattern)); - const inline = (family.inline ?? []).map((rule) => ({ - ...rule, - regex: new RegExp(rule.pattern), - })); - lines.forEach((rawLine, index) => { - const line = stripComment(rawLine); - const name = definitionName(line); + for (const { name, line } of defs) { + const owner = shared.get(name); // A copy of a name another shared file defines is reported once, as a shared-helper copy. - const owner = name && shared.get(name); - if (name && (!owner || owner === file) && lookalikes.some((regex) => regex.test(name))) { - findings.push({ kind: "lookalike", file, line: index + 1, family, symbol: name }); + if ((!owner || owner === file) && lookalikes.some((regex) => regex.test(name))) { + findings.push({ kind: "lookalike", file, line, family, symbol: name }); } - for (const rule of inline) { - if (rule.regex.test(line)) { + } + for (const rule of family.inline ?? []) { + const regex = new RegExp(rule.pattern, "g"); + inlineLines.forEach((text, index) => { + for (let n = [...text.matchAll(regex)].length; n > 0; n -= 1) { findings.push({ kind: "inline", file, line: index + 1, family, symbol: rule.id, rule }); } - } - }); + }); + } return findings; } function sourceFindings(registry, sources) { - const shared = sharedHelperOwners(sources); + const parsed = new Map( + [...sources].map(([file, source]) => [ + file, + { + defs: definitions(source), + inlineLines: blankLua(source, { keepStrings: true }).split("\n"), + }, + ]), + ); + const shared = sharedHelperOwners(parsed); const findings = []; - for (const [file, source] of sources) { - const lines = source.split("\n"); - lines.forEach((rawLine, index) => { - const line = stripComment(rawLine); - const name = definitionName(line); - const owner = name && shared.get(name); + for (const [file, entry] of parsed) { + for (const { name, line, topLevel } of entry.defs) { + const owner = shared.get(name); // Inside lua/shared only a top-level definition can be a second copy; nested locals are private. - const counts = file.startsWith("lua/shared/") - ? definitionName(line, TOP_LEVEL_PATTERNS) === name - : true; + const counts = file.startsWith("lua/shared/") ? topLevel : true; if (owner && owner !== file && counts) { findings.push({ kind: "redefinition", file, - line: index + 1, + line, family: SHARED_FAMILY, symbol: name, owner, }); } - }); + } for (const family of registry.families) { if (family.homes.includes(file)) continue; - findings.push(...patternFindings(family, file, lines, shared)); + findings.push(...patternFindings(family, file, entry, shared)); } } return findings; From b1ed9dfc298a71aed3579bf0206e07aad0edf1fa Mon Sep 17 00:00:00 2001 From: kzoeps Date: Thu, 26 Nov 2026 19:26:03 +0600 Subject: [PATCH 08/11] lint/shared-helpers: register identityResolver.lua as a home of the handle family valid_handle in lua/shared/identityResolver.lua is the canonical handle check; files listed in a family's homes are already skipped by that family's lookalike check. --- happyview-modules/tooling/shared-helpers.registry.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/happyview-modules/tooling/shared-helpers.registry.json b/happyview-modules/tooling/shared-helpers.registry.json index c548c552..4cc0731a 100644 --- a/happyview-modules/tooling/shared-helpers.registry.json +++ b/happyview-modules/tooling/shared-helpers.registry.json @@ -42,7 +42,7 @@ "id": "handle-resolver", "description": "handle syntax check and handle resolution", "lookalikes": ["^valid_(handle|ipv4|ipv6|port)", "resolve_handle"], - "homes": ["lua/shared/profileLookup.lua"] + "homes": ["lua/shared/identityResolver.lua", "lua/shared/profileLookup.lua"] }, { "id": "list-cursor", From ff7a410ff91d6621b998fe351ceb25a0b99db56b Mon Sep 17 00:00:00 2001 From: kzoeps Date: Thu, 26 Nov 2026 19:34:49 +0600 Subject: [PATCH 09/11] lint-shared-helpers: flag non-local nested redefinitions of shared helpers A nested definition without 'local' assigns a global, so once shared files are concatenated it replaces the helper's local binding. Only nested local functions stay exempt. --- happyview-modules/tooling/lint-shared-helpers.js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/happyview-modules/tooling/lint-shared-helpers.js b/happyview-modules/tooling/lint-shared-helpers.js index 87e206fa..1f0866b4 100644 --- a/happyview-modules/tooling/lint-shared-helpers.js +++ b/happyview-modules/tooling/lint-shared-helpers.js @@ -86,7 +86,7 @@ function depthTracker(code) { events.filter((event) => event.index < offset).reduce((sum, event) => sum + event.delta, 0); } -/** Every function definition in a Lua file: last-segment name, 1-based line, top-level or nested. */ +/** Every function definition in a Lua file: last-segment name, 1-based line, top-level or nested, local or not. */ function definitions(source) { const code = blankLua(source); const depthAt = depthTracker(code); @@ -98,6 +98,9 @@ function definitions(source) { // Report the line of the name, not of leading blank space. line: code.slice(0, nameStart).split("\n").length, topLevel: depthAt(match.index) === 0, + // A nested definition without `local` still assigns a global, so it replaces any + // earlier binding of the name once the files are concatenated into one chunk. + isLocal: /^\s*local\s/.test(match[0]), }; }), ); @@ -213,10 +216,11 @@ function sourceFindings(registry, sources) { const shared = sharedHelperOwners(parsed); const findings = []; for (const [file, entry] of parsed) { - for (const { name, line, topLevel } of entry.defs) { + for (const { name, line, topLevel, isLocal } of entry.defs) { const owner = shared.get(name); - // Inside lua/shared only a top-level definition can be a second copy; nested locals are private. - const counts = file.startsWith("lua/shared/") ? topLevel : true; + // Inside lua/shared only a top-level definition or a non-local one can be a second copy; + // a nested `local function` is private to its block. + const counts = file.startsWith("lua/shared/") ? topLevel || !isLocal : true; if (owner && owner !== file && counts) { findings.push({ kind: "redefinition", From d61135644a9fd11fa6b96a84ee4462f6b7cd8066 Mon Sep 17 00:00:00 2001 From: kzoeps Date: Fri, 27 Nov 2026 10:20:30 +0600 Subject: [PATCH 10/11] lint-shared-helpers: split blankLua into token helpers SonarCloud flagged blankLua's single loop with nested branches. Each comment, string or code character is now read by luaToken and rendered by renderToken. Output is unchanged: compared byte-for-byte against the old function on every Lua file in the stack, in both modes. --- .../tooling/lint-shared-helpers.js | 77 +++++++++++-------- 1 file changed, 46 insertions(+), 31 deletions(-) diff --git a/happyview-modules/tooling/lint-shared-helpers.js b/happyview-modules/tooling/lint-shared-helpers.js index 1f0866b4..b22e1704 100644 --- a/happyview-modules/tooling/lint-shared-helpers.js +++ b/happyview-modules/tooling/lint-shared-helpers.js @@ -30,7 +30,49 @@ async function luaFiles(root, directory) { .sort(); } -const LONG_BRACKET = /^\[(=*)\[/; +// Sticky: matches only at lastIndex. +const LONG_BRACKET = /\[(=*)\[/y; + +const blank = (text) => text.replace(/[^\n]/g, " "); + +/** End offset of the long bracket (`[[`, `[==[`) opening at `open`, or null if there is none. */ +function longBracketEnd(source, open) { + LONG_BRACKET.lastIndex = open; + const long = LONG_BRACKET.exec(source); + if (!long) return null; + const close = `]${long[1]}]`; + const end = source.indexOf(close, open + long[0].length); + return end === -1 ? source.length : end + close.length; +} + +/** End offset of the quoted string opening at `i`; an unclosed string stops after the newline. */ +function quotedEnd(source, i) { + let stop = i + 1; + while (stop < source.length && source[stop] !== source[i] && source[stop] !== "\n") { + stop += source[stop] === "\\" ? 2 : 1; + } + return Math.min(stop + 1, source.length); +} + +/** The comment, string or single code character starting at `i`, with its end offset. */ +function luaToken(source, i) { + if (source.startsWith("--", i)) { + const longStop = longBracketEnd(source, i + 2); + if (longStop !== null) return { kind: "comment", stop: longStop }; + const end = source.indexOf("\n", i); + return { kind: "comment", stop: end === -1 ? source.length : end }; + } + const longStop = longBracketEnd(source, i); + if (longStop !== null) return { kind: "longString", stop: longStop }; + if (source[i] === '"' || source[i] === "'") return { kind: "quoted", stop: quotedEnd(source, i) }; + return { kind: "code", stop: i + 1 }; +} + +function renderToken(kind, text, keepStrings) { + if (kind === "code" || (keepStrings && kind !== "comment")) return text; + if (kind === "quoted") return text[0] + blank(text.slice(1, -1)) + text.slice(-1); + return blank(text); +} /** * Returns the source with Lua comments blanked to spaces, and string contents too unless @@ -41,37 +83,10 @@ const LONG_BRACKET = /^\[(=*)\[/; function blankLua(source, { keepStrings = false } = {}) { let out = ""; let i = 0; - const blank = (text) => text.replace(/[^\n]/g, " "); while (i < source.length) { - const rest = source.slice(i); - const isComment = rest.startsWith("--"); - const long = LONG_BRACKET.exec(isComment ? rest.slice(2) : rest); - if (long) { - const close = `]${long[1]}]`; - const start = i + (isComment ? 2 : 0) + long[0].length; - const end = source.indexOf(close, start); - const stop = end === -1 ? source.length : end + close.length; - const text = source.slice(i, stop); - out += isComment || !keepStrings ? blank(text) : text; - i = stop; - } else if (isComment) { - const end = source.indexOf("\n", i); - const stop = end === -1 ? source.length : end; - out += blank(source.slice(i, stop)); - i = stop; - } else if (rest[0] === '"' || rest[0] === "'") { - let stop = i + 1; - while (stop < source.length && source[stop] !== rest[0] && source[stop] !== "\n") { - stop += source[stop] === "\\" ? 2 : 1; - } - stop = Math.min(stop + 1, source.length); - const text = source.slice(i, stop); - out += keepStrings ? text : rest[0] + blank(text.slice(1, -1)) + text.slice(-1); - i = stop; - } else { - out += source[i]; - i += 1; - } + const { kind, stop } = luaToken(source, i); + out += renderToken(kind, source.slice(i, stop), keepStrings); + i = stop; } return out; } From 5b7f5faa58be8c1755c3d6fa2205992b30addfdf Mon Sep 17 00:00:00 2001 From: kzoeps Date: Fri, 27 Nov 2026 17:00:43 +0600 Subject: [PATCH 11/11] lint-shared-helpers: handle spaced qualified names, nested dirs, home ownership, duplicate allowlist keys Registry cursor patterns now tolerate whitespace. --- .../tooling/lint-shared-helpers.js | 41 ++++++++++++++----- .../tooling/shared-helpers.registry.json | 4 +- 2 files changed, 33 insertions(+), 12 deletions(-) diff --git a/happyview-modules/tooling/lint-shared-helpers.js b/happyview-modules/tooling/lint-shared-helpers.js index b22e1704..357a41bc 100644 --- a/happyview-modules/tooling/lint-shared-helpers.js +++ b/happyview-modules/tooling/lint-shared-helpers.js @@ -11,8 +11,8 @@ const scannedDirectories = ["lua/shared", "lua/src"]; // Only the last segment is the helper's name, so a module-table copy is still a copy. // \s* also spans newlines, so a definition split across lines is still found. const DEFINITION_PATTERNS = [ - /^[ \t]*(?:local\s+)?function\s+([A-Za-z_][\w.:]*)\s*\(/gm, - /^[ \t]*(?:local\s+)?([A-Za-z_][\w.]*)\s*=\s*function\s*\(/gm, + /^[ \t]*(?:local\s+)?function\s+([A-Za-z_]\w*(?:\s*[.:]\s*[A-Za-z_]\w*)*)\s*\(/gm, + /^[ \t]*(?:local\s+)?([A-Za-z_]\w*(?:\s*\.\s*[A-Za-z_]\w*)*)\s*=\s*function\s*\(/gm, ]; // Every top-level function in lua/shared is protected. It is not a registry family, so it has no patterns. @@ -23,10 +23,15 @@ const SHARED_FAMILY = { }; async function luaFiles(root, directory) { - const entries = await readdir(path.join(root, directory), { withFileTypes: true }); + const entries = await readdir(path.join(root, directory), { + withFileTypes: true, + recursive: true, + }); return entries .filter((entry) => entry.isFile() && entry.name.endsWith(".lua")) - .map((entry) => `${directory}/${entry.name}`) + .map((entry) => + path.relative(root, path.join(entry.parentPath, entry.name)).split(path.sep).join("/"), + ) .sort(); } @@ -109,7 +114,7 @@ function definitions(source) { [...code.matchAll(pattern)].map((match) => { const nameStart = match.index + match[0].indexOf(match[1]); return { - name: match[1].split(/[.:]/).pop(), + name: match[1].split(/[.:]/).pop().trim(), // Report the line of the name, not of leading blank space. line: code.slice(0, nameStart).split("\n").length, topLevel: depthAt(match.index) === 0, @@ -139,8 +144,17 @@ function familyProblems(family, seen) { return problems; } -function allowlistEntryProblems(entry) { +function allowlistEntryProblems(entry, index, entries) { const problems = []; + const first = entries.findIndex( + (other) => + other.file === entry.file && other.family === entry.family && other.symbol === entry.symbol, + ); + if (first !== index) { + problems.push( + `allowlist has more than one entry for ${entry.file} / ${entry.family} / ${entry.symbol}; keep one and set "count"`, + ); + } if (entry.count !== undefined && !(Number.isInteger(entry.count) && entry.count >= 1)) { problems.push( `allowlist entry ${JSON.stringify(entry)} has an invalid "count"; use a positive integer`, @@ -185,13 +199,20 @@ function homeHint(family) { return `Use the shared helper from ${family.homes.join(" or ")} (declare it in the module's sharedSourcePaths).`; } -/** Maps each top-level function name in lua/shared to the first file that defines it. */ -function sharedHelperOwners(parsed) { +/** + * Maps each top-level function name in lua/shared to the file that owns it: a registered home + * if one defines it, otherwise the first file that does. + */ +function sharedHelperOwners(parsed, registry) { + const homes = new Set(registry.families.flatMap((family) => family.homes)); const owners = new Map(); for (const [file, { defs }] of parsed) { if (!file.startsWith("lua/shared/")) continue; for (const def of defs) { - if (def.topLevel && !owners.has(def.name)) owners.set(def.name, file); + if (!def.topLevel) continue; + if (!owners.has(def.name) || (homes.has(file) && !homes.has(owners.get(def.name)))) { + owners.set(def.name, file); + } } } return owners; @@ -228,7 +249,7 @@ function sourceFindings(registry, sources) { }, ]), ); - const shared = sharedHelperOwners(parsed); + const shared = sharedHelperOwners(parsed, registry); const findings = []; for (const [file, entry] of parsed) { for (const { name, line, topLevel, isLocal } of entry.defs) { diff --git a/happyview-modules/tooling/shared-helpers.registry.json b/happyview-modules/tooling/shared-helpers.registry.json index 4cc0731a..35ea9908 100644 --- a/happyview-modules/tooling/shared-helpers.registry.json +++ b/happyview-modules/tooling/shared-helpers.registry.json @@ -51,12 +51,12 @@ "inline": [ { "id": "cursor-hex-decode", - "pattern": "tonumber\\(pair, 16\\)", + "pattern": "tonumber\\(pair,\\s*16\\)", "description": "hex cursor decoding" }, { "id": "cursor-length-cap", - "pattern": "#token > 8192", + "pattern": "#token\\s*>\\s*8192", "description": "the cursor length cap" } ],