Skip to content

refactor: split lint.ts into 10 focused modules - #46

Merged
luandro merged 11 commits into
mainfrom
refactor/34-split-lint-modules
Jul 22, 2026
Merged

luandro merged 11 commits into
mainfrom
refactor/34-split-lint-modules

Conversation

@luandro

@luandro luandro commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Problem

src/lint.ts was 4878 lines — a monolith handling all linting concerns. Hard to navigate, high merge conflict risk, difficult to review.

Changes

Pure file reorganization. No behavior changes. Split into src/lint/ directory:

Module Lines Responsibility
index.ts 224 Orchestrator: lintAllSheets(), lintSheet()
categories.ts 804 Category lint rules
details.ts 530 Detail lint rules
translations.ts 929 Translation lint rules
icons.ts 304 Icon sheet lint rules
metadata.ts 242 Metadata lint rules
shared.ts 971 Shared helpers, colors, whitespace
strictMetrics.ts 462 Strict metric checks
htmlValidation.ts 332 HTML/dialog validation
svgValidation.ts 84 Inline SVG size validation

GAS compatibility

  • Zero import/export statements (GAS global scope)
  • All functions available globally as before
  • Updated dialog.ts reference path to ./lint/htmlValidation.ts

Closes #34

Greptile Summary

This PR splits the lint monolith into focused Google Apps Script modules. The main changes are:

  • Extracted lint rules and shared helpers into src/lint/.
  • Updated references and removed top-level load-order dependencies.
  • Added GAS boot and lint parity checks.
  • Gated deployment on successful same-repository Plugin checks.

Confidence Score: 5/5

This looks safe to merge.

This looks safe to merge.

  • No blocking issues found in the changed code.

T-Rex T-Rex Logs

What T-Rex did

  • Validated that a timestamped log was produced to capture the exact command, working directory, exit status, complete stdout and stderr, any warnings, and the total number of passing fixtures for the code-execution run.

View all artifacts

T-Rex Ran code and verified through T-Rex

Important Files Changed

Filename Overview
src/lint/index.ts Provides the lint orchestration entry points after the module split.
src/lint/shared.ts Holds shared lint helpers, constants, caches, parsing, and cleanup logic.
src/lint/htmlValidation.ts Contains the extracted HTML and dialog validation functions.
src/scripts/check-gas-boot.cjs Adds a boot check for GAS global initialization and load order.
src/scripts/check-lint-parity.cjs Adds parity checks for behavior moved from the lint monolith.
.github/workflows/plugin.yml Runs TypeScript, Biome, GAS boot, and lint parity checks.
.github/workflows/deploy.yml Deploys the exact commit from a successful same-repository Plugin run.
src/data/languagesFallback.ts Builds the legacy language map locally to avoid a global load-order dependency.
src/importCategory/validateConfig.ts Defines accepted import field types locally to avoid a global load-order dependency.

Reviews (12): Last reviewed commit: "chore: refresh version banner" | Re-trigger Greptile

@qodo-code-review

Copy link
Copy Markdown

Review Summary by Qodo

Refactor: Split monolithic lint.ts into 10 focused modules

✨ Enhancement

Grey Divider

Walkthroughs

Description
• Split monolithic src/lint.ts (4878 lines) into 10 focused, maintainable modules under
  src/lint/ directory
• **Core modules**: index.ts (orchestrator), shared.ts (971 lines of utilities, type
  definitions, severity styling), categories.ts (804 lines), details.ts (530 lines),
  translations.ts (929 lines)
• **Specialized modules**: icons.ts (icon validation), metadata.ts (metadata validation),
  strictMetrics.ts (entity count validation), htmlValidation.ts (HTML/dialog validation),
  svgValidation.ts (SVG size validation)
• Maintained full GAS compatibility: zero import/export statements, all functions remain
  globally accessible
• Updated src/dialog.ts reference path to point to new ./lint/htmlValidation.ts module
• Pure refactoring with zero behavior changes, improving code navigation and reducing merge conflict
  risk
Diagram
flowchart LR
  A["src/lint.ts<br/>4878 lines"] -->|split| B["src/lint/index.ts<br/>Orchestrator"]
  A -->|split| C["src/lint/shared.ts<br/>971 lines<br/>Utilities & Styling"]
  A -->|split| D["src/lint/categories.ts<br/>804 lines"]
  A -->|split| E["src/lint/details.ts<br/>530 lines"]
  A -->|split| F["src/lint/translations.ts<br/>929 lines"]
  A -->|split| G["src/lint/icons.ts<br/>Icon Validation"]
  A -->|split| H["src/lint/metadata.ts<br/>Metadata Validation"]
  A -->|split| I["src/lint/strictMetrics.ts<br/>Entity Counts"]
  A -->|split| J["src/lint/htmlValidation.ts<br/>HTML Validation"]
  A -->|split| K["src/lint/svgValidation.ts<br/>SVG Validation"]
  B -->|uses| C
  D -->|uses| C
  E -->|uses| C
  F -->|uses| C
  G -->|uses| C
  H -->|uses| C
  I -->|uses| C
  J -->|uses| C
  K -->|uses| C
  L["src/dialog.ts"] -->|references| J

Loading

Grey Divider

File Changes

1. src/lint/shared.ts Refactoring +971/-0

Shared lint utilities and severity-based styling system

• Extracted 971 lines of shared lint utilities from the monolithic lint.ts, including type
 definitions (DriveIconInfo, LintSeverity), severity styling constants, and helper functions
• Implemented standardized lint note writers (setLintNote, appendLintNote) with severity-based
 visual styling (error/warning/advisory) and background/font color management
• Added range-scoped cleanup functions (clearLintArtifacts, clearRangeLintNotesWithPrefixes) to
 preserve user-managed colors while removing lint artifacts
• Provided utility functions for whitespace handling, Drive icon validation, slug collision
 detection, and canonical option parsing used across all lint modules

src/lint/shared.ts


2. src/lint/categories.ts Refactoring +804/-0

Category sheet linting with icon and Applies validation

• Implemented category-specific lint rules including duplicate ID detection
 (checkDuplicateCategoryIds), slug collision warnings, and primary language validation in A1
• Added validateAppliesColumn() to validate the Applies column with token parsing, recognizing
 "observation" and "track" prefixes while warning on unrecognized tokens and non-comma delimiters
• Implemented validateCategoryIcons() to validate icon sources (inline SVG, data URIs, Drive URLs,
 HTTPS URLs) and resolve icon IDs from the Icons sheet
• Orchestrated linting via lintCategoriesSheet() which runs validation phases in sequence:
 empty-sheet check, primary language validation, field reference validation, and post-lint edge-case
 checks

src/lint/categories.ts


3. src/lint/translations.ts Refactoring +929/-0

Translation sheet validation and mismatch detection system

• Implemented translation sheet validation including header parsing (validateTranslationHeaders),
 consistency checking between source and translation sheets (validateSheetConsistency), and
 duplicate slug detection
• Added critical primary-column mismatch detection with bright red highlighting to catch translation
 lookup failures (e.g., "Animal" vs "Animal Terrs")
• Implemented checkTranslationSourceOverwrites() to warn when multiple rows produce the same slug
 key, preventing silent overwrites during config generation
• Provided fixTranslationMismatches() to re-sync formulas from source sheets and optionally re-run
 translation for configured languages

src/lint/translations.ts


View more (9)
4. src/lint/details.ts Refactoring +530/-0

Details sheet linting with options and type validation

• Implemented detail-specific lint rules including duplicate ID detection
 (checkDuplicateDetailIds), unreferenced detail warnings, and field type validation
• Added comprehensive options validation (validateAndCapitalizeCommaList, parseCanonicalOptions,
 detectAmbiguousColonUsage) with duplicate option removal and colon-usage ambiguity detection
• Implemented checkUnreferencedDetails() using normalizeFieldTokens() to match builder parsing
 and detect details not referenced by any category
• Orchestrated linting via lintDetailsSheet() which validates field names, helper text, type
 values, options, and Universal flags in sequence

src/lint/details.ts


5. src/lint/strictMetrics.ts ✨ Enhancement +462/-0

Strict metrics collection and entity count validation

• New module containing strict metric collection and validation functions
• Implements buildLintCategorySummaries(), buildLintFieldSummaries(), and
 buildLintTranslationsByLocale() to gather entity counts
• Provides collectStrictLintMetrics() to aggregate categories, fields, icons, options, and
 translation entries
• Includes checkTranslationPayloadSizes() and checkTotalEntityCounts() for strict validation
 limits (1MB per locale, 10K total entities)

src/lint/strictMetrics.ts


6. src/lint/icons.ts ✨ Enhancement +304/-0

Icon sheet validation and collision detection

• New module for icon sheet validation and cross-sheet collision detection
• Implements lintIconsSheet() to validate icon IDs, sources, and detect duplicates
• Provides checkCrossSheetIconCollisions() to detect ID conflicts between Icons and Categories
 sheets
• Includes helper findCrossSheetIconIdCollisions() and validation for SVG data URIs, Drive URLs,
 and HTTP(S) URLs

src/lint/icons.ts


7. src/lint/htmlValidation.ts ✨ Enhancement +332/-0

HTML validation and dialog content verification

• New module for HTML content validation and dialog generation testing
• Implements validateHtmlContent() with tag matching, attribute validation, and DOCTYPE checks
• Provides validateDialogHtml() for pre-dialog validation and testHtmlValidation() for unit
 testing
• Includes integration test testDialogHtmlGeneration() and runAllHtmlValidationTests()
 orchestrator

src/lint/htmlValidation.ts


8. src/lint/metadata.ts ✨ Enhancement +242/-0

Metadata sheet validation and key normalization

• New module for Metadata sheet validation
• Implements lintMetadataSheet() to validate metadata keys (name, version, primaryLanguage) for
 unsafe characters and duplicates
• Provides normalizeMetadataPrimaryLanguageValue() to normalize language inputs using shared
 resolver
• Detects whitespace-padded keys, case-only typos, and validates strict character restrictions

src/lint/metadata.ts


9. src/lint/index.ts ✨ Enhancement +224/-0

Lint orchestration and main entry point

• New orchestrator module for the lint system
• Implements lintSheet() generic validation function with background/font color clearing and
 duplicate detection
• Provides lintAllSheets() main entry point that coordinates all lint phases (categories, details,
 icons, translations, metadata)
• Includes UI alerts summarizing lint results and error handling

src/lint/index.ts


10. src/lint/svgValidation.ts ✨ Enhancement +84/-0

Inline SVG size validation and limits

• New module for inline SVG size validation
• Implements checkInlineSvgSizes() to check SVG sizes in Categories and Icons sheets
• Enforces 300KB warning threshold and 2MB error threshold for inline SVG content
• Handles inline ``, data URI, and Google Drive SVG sources

src/lint/svgValidation.ts


11. src/dialog.ts ⚙️ Configuration changes +1/-1

Update lint module reference path

• Updated reference path from ./lint.ts to ./lint/htmlValidation.ts
• Maintains GAS compatibility by referencing the new modular structure

src/dialog.ts


12. src/lint.ts Additional files +0/-4878

...

src/lint.ts


Grey Divider

Qodo Logo

@qodo-code-review

qodo-code-review Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (8) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. driveIconInfoCache stores cross-run state 📘 Rule violation ≡ Correctness
Description
A module-level Map (driveIconInfoCache) is used as a cross-run cache and explicitly cleared at
the start of linting. Persisting cross-execution state in globals is unreliable in Apps Script and
violates the rule requiring PropertiesService (or passing state via parameters).
Code

src/lint/shared.ts[R31-34]

+/** Module-level cache for Drive icon info, shared across lint checks to avoid
+ *  redundant Drive API calls and keep Drive URL classification consistent. */
+const driveIconInfoCache = new Map<string, DriveIconInfo>();
+
Evidence
The rule forbids persisting cross-execution state in globals. The PR adds a module-level cache and
then references clearing it as a "cross-run" cache, indicating it is intended to persist beyond a
single call.

Rule 342703: Persist cross-execution state with PropertiesService or function parameters, not globals
src/lint/shared.ts[31-34]
src/lint/index.ts[155-159]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Cross-execution state is being stored in a module-level/global variable (`driveIconInfoCache`).

## Issue Context
Apps Script globals are not reliable for state across executions. Use `PropertiesService` (or pass state via parameters) for persistence, or scope the cache strictly to a single execution without relying on global retention.

## Fix Focus Areas
- src/lint/shared.ts[31-34]
- src/lint/index.ts[155-159]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. lintAllSheets bypasses showErrorDialog 📘 Rule violation ☼ Reliability
Description
lintAllSheets() catches errors but surfaces them via SpreadsheetApp.getUi().alert(...) instead
of showErrorDialog(...)/showIconErrorDialog(...). This violates the requirement to surface
major-operation errors via the standard error dialog helpers.
Code

src/lint/index.ts[R209-224]

+  } catch (error) {
+    console.error("Error during linting process:", error);
+
+    // Only show error alert if showAlerts is true
+    if (showAlerts) {
+      const ui = SpreadsheetApp.getUi();
+      ui.alert(
+        "Linting Error",
+        "An error occurred during the linting process: " +
+          error.message +
+          "\n\nSome sheets may not have been fully processed.",
+        ui.ButtonSet.OK,
+      );
+    }
+  }
+}
Evidence
The rule requires surfacing errors via showErrorDialog or showIconErrorDialog when catching
major-operation failures. The PR’s catch block uses ui.alert(...) instead.

Rule 342709: Wrap major operations in try-catch and surface errors via error dialogs
src/lint/index.ts[209-229]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Major-operation error handling does not use `showErrorDialog`/`showIconErrorDialog`.

## Issue Context
The checklist requires try/catch around major operations and surfacing errors via the standard error-dialog helpers.

## Fix Focus Areas
- src/lint/index.ts[209-229]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Single quotes in lint modules 📘 Rule violation ✧ Quality
Description
New code introduces single-quoted string literals (e.g., 'Test <> & "Title"', `'Inline SVG
markup...'`). This violates the requirement to enforce double-quoted string literals.
Code

src/lint/htmlValidation.ts[R303-304]

+    const title = 'Test <> & "Title"';
+    const message = "<p>" + escapeHtml('Message with <> & "quotes"') + "</p>";
Evidence
The rule requires all string literals to use double quotes. The added lines show strings delimited
with single quotes in both htmlValidation.ts and icons.ts.

Rule 342721: Enforce double-quoted string literals
src/lint/htmlValidation.ts[303-304]
src/lint/icons.ts[73-73]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
String literals are using single quotes instead of double quotes.

## Issue Context
The checklist mandates double-quoted string literals for consistency.

## Fix Focus Areas
- src/lint/htmlValidation.ts[303-304]
- src/lint/icons.ts[73-73]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

4. DriveIconInfo uses type alias 📘 Rule violation ✧ Quality
Description
Object-shape types are declared with type (DriveIconInfo, LintFieldSummary) instead of
interface. This violates the TypeScript style requirement and makes these shapes harder to
extend/merge consistently.
Code

src/lint/shared.ts[R6-11]

+type DriveIconInfo = {
+  slug: string | null;
+  isSvg: boolean;
+  svgContent: string | null;
+  errorMessage?: string;
+};
Evidence
The checklist requires object shapes to be declared using interface rather than type. The PR
introduces object-literal shapes using type in src/lint/shared.ts and
src/lint/strictMetrics.ts.

Rule 342708: Prefer interfaces over type aliases for object shapes in TypeScript
src/lint/shared.ts[6-11]
src/lint/strictMetrics.ts[54-66]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Object-shape TypeScript declarations are using `type ... = { ... }` where an `interface` should be used.

## Issue Context
Rule requires `interface` for object shapes to improve extensibility and consistency.

## Fix Focus Areas
- src/lint/shared.ts[6-11]
- src/lint/strictMetrics.ts[54-66]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Boolean names missing verb prefix 📘 Rule violation ✧ Quality
Description
Several new boolean variables do not start with auxiliary verb prefixes (e.g., updated,
bgUpdated, contributesIconAsset, resolvedPrimaryLanguage, seenValidPrimaryLanguage). This
violates the boolean naming convention and reduces clarity about boolean intent.
Code

src/lint/shared.ts[83]

+  let updated = false;
Evidence
The checklist requires boolean identifiers to start with auxiliary verbs. The cited lines introduce
booleans like updated, bgUpdated, contributesIconAsset, and resolvedPrimaryLanguage that do
not include an auxiliary verb prefix.

Rule 342697: Prefix boolean variable names with auxiliary verbs
src/lint/shared.ts[83-83]
src/lint/details.ts[93-106]
src/lint/icons.ts[65-66]
src/lint/metadata.ts[52-56]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Boolean variables are named without an auxiliary-verb prefix.

## Issue Context
Booleans should start with `is`/`has`/`should`/etc. to clearly indicate a boolean condition.

## Fix Focus Areas
- src/lint/shared.ts[83-83]
- src/lint/details.ts[93-106]
- src/lint/icons.ts[65-66]
- src/lint/metadata.ts[52-56]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. shared.ts constants before functions 📘 Rule violation ✧ Quality
Description
src/lint/shared.ts places types/constants before helper functions rather than keeping functions
first and constants last. This violates the required file-level declaration ordering and makes the
file harder to scan.
Code

src/lint/shared.ts[R4-57]

+// --- Types -----------------------------------------------------------------
+
+type DriveIconInfo = {
+  slug: string | null;
+  isSvg: boolean;
+  svgContent: string | null;
+  errorMessage?: string;
+};
+
+type LintSeverity = "error" | "warning" | "advisory";
+
+// --- Constants --------------------------------------------------------------
+
+// LINT_WARNING_BACKGROUND_COLORS is defined in lint-colors.ts (shared with tests)
+/**
+ * Lint warning font colors.
+ *
+ * IMPORTANT: See `src/test/testLint.ts` color synchronization table.
+ */
+// LINT_WARNING_FONT_COLORS is defined in lint-colors.ts (shared with tests)
+const LINT_WARNING_FONT_COLORS_WITHOUT_WHITE = LINT_WARNING_FONT_COLORS.filter(
+  (color) => color.toUpperCase() !== "#FFFFFF",
+);
+const LINT_NOTE_PREFIX = "[Lint] ";
+const SLUG_COLLISION_LINT_NOTE_PREFIX = `${LINT_NOTE_PREFIX}Slug collision:`;
+const SOURCE_OVERWRITE_LINT_NOTE_PREFIX = `${LINT_NOTE_PREFIX}Source value`;
+
+/** Module-level cache for Drive icon info, shared across lint checks to avoid
+ *  redundant Drive API calls and keep Drive URL classification consistent. */
+const driveIconInfoCache = new Map<string, DriveIconInfo>();
+
+/**
+ * Single source of truth for severity → visual style.
+ * `background`/`fontColor` of `null` mean "leave that property unchanged".
+ * Shared by all four lint-note writers so they can never drift apart.
+ */
+const LINT_SEVERITY_STYLE: Record<
+  LintSeverity,
+  { background: string | null; fontColor: string | null }
+> = {
+  error: { background: LINT_ERROR_BG, fontColor: "red" },
+  warning: { background: LINT_WARNING_BG, fontColor: "orange" },
+  advisory: { background: LINT_ADVISORY_BG, fontColor: null },
+};
+
+// --- Helper functions -------------------------------------------------------
+
+function capitalizeFirstLetter(str: string): string {
+  if (!str || typeof str !== "string") return "";
+  return str.charAt(0).toUpperCase() + str.slice(1);
+}
+
+function validateAndCapitalizeCommaList(value: string): string {
+  if (!value || typeof value !== "string") return "";
Evidence
The checklist requires file-level ordering of declarations; the new shared.ts starts with types
and then constants before helper functions, violating that ordering requirement.

Rule 342701: Enforce file-level ordering: exported functions → helper functions → types → constants
src/lint/shared.ts[4-57]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
File-level declarations are out of the required order (functions should come before types/constants per the checklist ordering).

## Issue Context
The rule enforces a consistent top-level structure to improve navigability.

## Fix Focus Areas
- src/lint/shared.ts[4-57]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (2)
7. index.ts helper precedes lintAllSheets 📘 Rule violation ✧ Quality
Description
In src/lint/index.ts, the helper lintSheet() is defined before the orchestrator
lintAllSheets(). This breaks the required ordering where primary/exposed functions should appear
before helpers.
Code

src/lint/index.ts[R3-156]

+// Generic linting function
+function lintSheet(
+  sheetName: string,
+  columnValidations: ((value: string, row: number, col: number) => void)[],
+  requiredColumns: number[] = [],
+  preserveBackgroundColumns: number[] = [],
+): void {
+  console.time(`Linting ${sheetName}`);
+
+  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
+  if (!sheet) {
+    console.log(`${sheetName} sheet not found`);
+    console.timeEnd(`Linting ${sheetName}`);
+    return;
+  }
+
+  const lastRow = sheet.getLastRow();
+  if (lastRow <= 1) {
+    console.log(`${sheetName} sheet is empty or contains only header`);
+    console.timeEnd(`Linting ${sheetName}`);
+    return;
+  }
+
+  try {
+    if (lastRow > 1 && columnValidations.length > 0) {
+      // Clear backgrounds, font colors, and stale lint notes for all columns
+      // except those that should be preserved
+      for (let col = 0; col < columnValidations.length; col++) {
+        // Skip columns that should preserve their backgrounds (e.g., Categories icon column with user colors)
+        const shouldClearBackground = !preserveBackgroundColumns.includes(col);
+        const colRange = sheet.getRange(2, col + 1, lastRow - 1, 1);
+
+        if (shouldClearBackground) {
+          clearRangeBackgroundIfMatches(
+            colRange,
+            LINT_WARNING_BACKGROUND_COLORS,
+          );
+        }
+        clearRangeFontColorIfMatches(colRange, LINT_WARNING_FONT_COLORS);
+        // Clear stale [Lint] notes so re-linting produces a clean result
+        clearRangeLintNotesWithPrefix(colRange, LINT_NOTE_PREFIX);
+      }
+    }
+
+    // First clean any whitespace-only cells
+    console.time(`Cleaning whitespace cells for ${sheetName}`);
+    cleanWhitespaceOnlyCells(
+      sheet,
+      2,
+      1,
+      lastRow - 1,
+      columnValidations.length,
+    );
+    console.timeEnd(`Cleaning whitespace cells for ${sheetName}`);
+
+    // Check for duplicates in the first column (usually the name/identifier column)
+    // Preserve background for columns in preserveBackgroundColumns (e.g., Categories
+    // column A has user-managed category colors that the builder reads at export time).
+    console.time(`Checking for duplicates in ${sheetName}`);
+    checkForDuplicates(sheet, 1, 2, preserveBackgroundColumns.includes(0));
+    console.timeEnd(`Checking for duplicates in ${sheetName}`);
+
+    console.time(`Getting data for ${sheetName}`);
+    // Get all data from the sheet, excluding the header row
+    const dataRange = sheet.getRange(
+      2,
+      1,
+      lastRow - 1,
+      columnValidations.length,
+    );
+    const data = dataRange.getValues();
+    console.timeEnd(`Getting data for ${sheetName}`);
+
+    console.time(`Validating cells for ${sheetName}`);
+
+    // Highlight required fields in batches before running column validations
+    if (requiredColumns.length > 0) {
+      const rangesToReset: string[] = [];
+      requiredColumns.forEach((colIndex) => {
+        // Skip columns that should preserve their backgrounds
+        if (!preserveBackgroundColumns.includes(colIndex)) {
+          const columnLetter = columnNumberToLetter(colIndex + 1);
+          rangesToReset.push(`${columnLetter}2:${columnLetter}${lastRow}`);
+        }
+      });
+
+      if (rangesToReset.length > 0) {
+        sheet.getRangeList(rangesToReset).setBackground(null);
+      }
+
+      const requiredHighlights = new Map<number, number[]>();
+      requiredColumns.forEach((colIndex) => {
+        // Skip columns that should preserve their backgrounds
+        if (!preserveBackgroundColumns.includes(colIndex)) {
+          requiredHighlights.set(colIndex, []);
+        }
+      });
+
+      data.forEach((row, rowIndex) => {
+        requiredColumns.forEach((colIndex) => {
+          // Skip columns that should preserve their backgrounds
+          if (
+            !preserveBackgroundColumns.includes(colIndex) &&
+            isEmptyOrWhitespace(row[colIndex])
+          ) {
+            const rows = requiredHighlights.get(colIndex);
+            if (rows) {
+              rows.push(rowIndex + 2); // +2 accounts for header row
+            }
+          }
+        });
+      });
+
+      requiredHighlights.forEach((rows, colIndex) => {
+        if (!rows || rows.length === 0) {
+          return;
+        }
+        const columnLetter = columnNumberToLetter(colIndex + 1);
+        const rangeAddresses = rows.map(
+          (rowNumber) => `${columnLetter}${rowNumber}`,
+        );
+        sheet.getRangeList(rangeAddresses).setBackground(LINT_WARNING_BG); // Light yellow for required fields
+      });
+    }
+
+    // Iterate through each cell and apply the corresponding validation function
+    data.forEach((row, rowIndex) => {
+      row.forEach((cellValue, colIndex) => {
+        if (columnValidations[colIndex]) {
+          columnValidations[colIndex](
+            String(cellValue || ""),
+            rowIndex + 2,
+            colIndex + 1,
+          );
+        }
+      });
+    });
+    console.timeEnd(`Validating cells for ${sheetName}`);
+
+    console.log(`${sheetName} sheet linting completed`);
+  } catch (error) {
+    console.error(`Error linting ${sheetName} sheet:`, error);
+  } finally {
+    console.timeEnd(`Linting ${sheetName}`);
+  }
+}
+
+/**
+ * Main linting function that validates all sheets in the spreadsheet.
+ *
+ * @param showAlerts - Whether to show UI alerts (default: true). Set to false when called from other functions.
+ */
+function lintAllSheets(showAlerts: boolean = true): void {
+  try {
Evidence
The ordering rule requires top-level exported/primary functions to appear before helper functions;
here the generic helper lintSheet is declared before the orchestrator lintAllSheets.

Rule 342701: Enforce file-level ordering: exported functions → helper functions → types → constants
src/lint/index.ts[3-156]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Top-level function ordering is inconsistent with the required file-level ordering guideline.

## Issue Context
`lintAllSheets()` is the main entry/orchestrator but appears after the generic helper `lintSheet()`.

## Fix Focus Areas
- src/lint/index.ts[3-156]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


8. Direct SpreadsheetApp calls in lint 📘 Rule violation ⌂ Architecture
Description
The new lint orchestrator/helper code calls Apps Script services (SpreadsheetApp...) directly from
procedural functions rather than through a service-wrapper class. This violates the preference for
wrapper classes for GAS service interactions.
Code

src/lint/index.ts[R10-13]

+  console.time(`Linting ${sheetName}`);
+
+  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
+  if (!sheet) {
Evidence
The checklist flags direct SpreadsheetApp usage scattered in functions and requires wrapper
classes for service interactions. The PR adds direct SpreadsheetApp.getActiveSpreadsheet() usage
in the new lint entry code.

Rule 342700: Prefer classes for Google Apps Script service wrappers and custom data objects; use functions for other logic
src/lint/index.ts[10-13]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Core GAS service calls are made directly inside procedural functions instead of being encapsulated in a wrapper class.

## Issue Context
The checklist requires new/modified code that interacts with services like `SpreadsheetApp` to do so through a class wrapper (improves testability and reduces scattered service calls).

## Fix Focus Areas
- src/lint/index.ts[10-13]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

Comment thread src/lint/htmlValidation.ts Resolved
Comment thread src/lint/shared.ts Resolved
Comment thread src/lint/index.ts Resolved
luandro added 2 commits June 5, 2026 22:46
Pure file reorganization — no behavior changes.

Modules created under src/lint/:
- index.ts (224 lines) — orchestrator: lintAllSheets, lintSheet
- categories.ts (804 lines) — category lint rules
- details.ts (530 lines) — detail lint rules
- translations.ts (929 lines) — translation lint rules
- icons.ts (304 lines) — icon sheet lint rules
- metadata.ts (242 lines) — metadata lint rules
- shared.ts (971 lines) — shared helpers, colors, whitespace
- strictMetrics.ts (462 lines) — strict metric checks
- htmlValidation.ts (332 lines) — HTML/dialog validation
- svgValidation.ts (84 lines) — inline SVG size validation

Also updated dialog.ts reference path from ./lint.ts to ./lint/htmlValidation.ts.

GAS global scope preserved: no import/export statements added.

Closes #34
Apply scoped logger migration to the split lint module files.
Replaces console.log/warn/error/time with getScopedLogger() calls
across 6 files (73 replacements total).

Test functions intentionally preserved.

This makes PR #43 (fix/35-lint-scoped-logger) redundant since the
logger migration is now included in the lint split.
@luandro
luandro force-pushed the refactor/34-split-lint-modules branch from 6078f09 to 328ebbb Compare June 6, 2026 01:47
luandro added 9 commits June 6, 2026 18:50
- translations.ts: guard getRange against translationRowCount=1 crash
  when sourceRowCount>1 (would throw invalid dimensions error)
- categories.ts: use case-insensitive comparison for duplicate category
  ID detection, matching details.ts behavior (was case-sensitive)
Boots the concatenated TypeScript sources in a vm context and runs
onOpen() to catch Apps Script's alphabetical file-load-order bugs
(the class the previous commit's fallback-language and field-type
fixes were papering over). Wired into the plugin CI workflow.

Also updates context docs to reflect the src/lint.ts -> src/lint/
module split and refreshes the generated version banner.
checkDuplicateCategoryIds() lowercased IDs before comparing, so valid
distinct IDs like "Foo" and "foo" were flagged as hard-error duplicates.
The package writer (package/src/writer.js) dedupes categories with an
exact-case Map and SAFE_ID_REGEX permits mixed case, so those are two
legitimate, non-colliding IDs. Switch to exact-case duplicate detection
(error) and demote case-only collisions to a non-blocking warning.

Unlike categories, field IDs genuinely are looked up case-insensitively
elsewhere in the builder (payloadBuilder.ts's fieldNameToId map), so
checkDuplicateDetailIds() is intentionally left untouched.

test(ci): run lint parity tests in CI, gate deploy on Plugin checks

- Extract the GAS-boot vm harness (mock APIs, file collection, transpile)
  out of check-gas-boot.cjs into gasSimHarness.cjs so it can be reused.
- Add check-lint-parity.cjs, which boots the full source tree (including
  src/test/, unlike the boot probe) and runs runLintParityTests(). Wire it
  into the Plugin workflow as `test:lint-parity`. This was previously only
  runnable manually from the Apps Script editor, so it never ran in CI —
  exactly how the category ID bug above went uncaught.
- Fix two stale assertions in testLint.ts uncovered by actually running the
  suite: a severity check expecting "warning" where production now (and
  correctly) emits "error", and a duplicate-primaryLanguage message
  substring that didn't match current wording. Both were drift from the
  message/severity text changing without the test being updated.
- Gate deploy.yml on the Plugin workflow succeeding via workflow_run
  instead of triggering independently on the same push, so clasp push can
  no longer race ahead of failing or in-progress checks. Pin checkout to
  workflow_run's head_sha since it doesn't default to the triggering
  commit.
github.ref resolves to the repo's default branch (main) on workflow_run
events, not the branch that triggered the upstream Plugin run. The Deploy
Script step's `github.ref == 'refs/heads/main'` guard (added in the
previous commit's workflow_run gating fix) would therefore evaluate true
for a develop-branch Plugin run too, running clasp deploy where only
clasp push was intended. Check event.workflow_run.head_branch for that
event type instead; github.ref stays reliable for workflow_dispatch and
release, which aren't affected.

Found by a second gpt-5.6-sol Codex readiness pass on commit 33c94dc,
verified against GitHub's documented workflow_run context behavior
before applying.
workflow_run runs in the base repo's privileged context (full CLASP
secrets) regardless of what triggered the upstream Plugin run, and the
branches: [main, develop] filter matches on head_branch — which a fork
can set by simply naming its own branch "main" or "develop". Without
further checks, a pull_request-triggered Plugin run from such a fork
branch would satisfy the gate and let deploy check out and `clasp
deploy` attacker-controlled code using this repo's secrets (the classic
GitHub Actions "pwn request" pattern).

Require the upstream run's underlying event to be 'push' and its head
repository to match this repository, closing both the fork-PR path and
the branch-name-spoofing path. workflow_dispatch and release triggers
are unaffected (no workflow_run context to check).

Found by a fourth gpt-5.6-sol Codex readiness pass on commit 6dd881f;
verified as a real, well-documented risk class (GitHub Security Lab's
"pwn request" writeup, GitHub's secure-use docs) before applying.
@luandro
luandro merged commit ecf6b7d into main Jul 22, 2026
3 checks passed
@luandro
luandro deleted the refactor/34-split-lint-modules branch July 22, 2026 19:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Split lint.ts (4878 lines) into focused modules

1 participant