Skip to content

Well known headers in typescript file#3014

Merged
RobinTail merged 2 commits intomasterfrom
gen-headers-ts
Oct 21, 2025
Merged

Well known headers in typescript file#3014
RobinTail merged 2 commits intomasterfrom
gen-headers-ts

Conversation

@RobinTail
Copy link
Copy Markdown
Owner

@RobinTail RobinTail commented Oct 21, 2025

Need this for #3011
For some weird reason it's no longer working with latest rolldown.

Todo: align the generator tool

Summary by CodeRabbit

  • Chores
    • Migrated headers data storage from JSON to TypeScript module format for improved maintainability.

@RobinTail RobinTail added the refactoring The better way to achieve the same result label Oct 21, 2025
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Oct 21, 2025

Walkthrough

The codebase migrates well-known headers from a JSON file approach to a TypeScript module approach. The generation tool now produces a TypeScript file with a default export, imports are updated accordingly, and the generation script integrates prettier formatting.

Changes

Cohort / File(s) Summary
Import/Export Updates
express-zod-api/src/documentation-helpers.ts, express-zod-api/src/well-known-headers.ts
Updated import statement in documentation-helpers.ts to source well-known headers from the TypeScript module instead of JSON file. Modified well-known-headers.ts to export the array as a default export instead of an unnamed export.
Build Tool Modification
tools/headers.ts
Updated the headers generation script to output a TypeScript file instead of JSON. Added prettier import and now generates JSON, wraps it as export default <json>, formats the result with prettier, and writes the formatted TypeScript code to disk.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

The changes follow a consistent, homogeneous pattern of migrating JSON to TypeScript. Individual modifications are straightforward—simple import/export syntax updates and a moderate build tool enhancement. Logic density is low, and the repetitive nature of the pattern reduces review complexity.

Poem

🐰 From JSON fields to TypeScript's grace,
Our headers find their new TypeScript place,
With prettier's touch, so formatted fine,
Default exports in every line,
Migrations complete—no more JSON space! ✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The PR title "Well known headers in typescript file" directly and clearly describes the main change in the changeset. The primary objective of this pull request is to migrate the well-known headers from a JSON file format to a TypeScript module format, which is exactly what the title communicates. The title is concise, specific, and avoids vague language. A teammate scanning the repository history would immediately understand that this PR converts the well-known headers to TypeScript, which is the core intent of the changeset across all modified files.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch gen-headers-ts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coveralls-official
Copy link
Copy Markdown

coveralls-official Bot commented Oct 21, 2025

Coverage Status

coverage: 100.0%. remained the same
when pulling 2a20000 on gen-headers-ts
into b3ada6e on master.

@RobinTail RobinTail marked this pull request as ready for review October 21, 2025 14:58
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tools/headers.ts (1)

241-253: CSV parsing is brittle (CRLF, whitespace) and can drop rows — normalize and trim; also dedupe and sort.

IANA CSV may use CRLF and trailing whitespace. Current logic can misclassify category (e.g., permanent\r) and filter out everything. Also, no dedupe/sort leads to unstable output.

Apply:

-const lines = csv.split("\n").slice(1, -1);
+const lines = csv.split(/\r?\n/).slice(1).filter(Boolean);
 const headers = lines
-  .map((line) => {
-    const [name, category] = line.split(",").slice(0, 2);
-    return { name, category };
-  })
+  .map((line) => {
+    const [nameRaw, categoryRaw] = line.split(",").slice(0, 2);
+    const name = nameRaw?.trim();
+    const category = categoryRaw?.trim();
+    return { name, category };
+  })
   .filter(
     ({ name, category }) =>
       /^[\w-]+$/.test(name) && categories.includes(category),
   )
-  .map(({ name }) => name.toLowerCase())
-  .filter((name) => !(name in responseOnlyHeaders));
+  .map(({ name }) => name.toLowerCase())
+  .filter((name) => !(name in responseOnlyHeaders));
+
+// stabilize and dedupe
+const headersSet = new Set(headers);
+const stableHeaders = Array.from(headersSet).sort();

And below replace subsequent uses of headers with stableHeaders.

🧹 Nitpick comments (3)
tools/headers.ts (1)

256-258: Emit a banner and readonly typing in the generated TS for clarity and safety.

Mark the file as generated and hint immutability. Prettier will keep formatting stable.

-const json = JSON.stringify(headers, undefined, 2);
-const tsCode = await format(`export default ${json};`, { filepath: dest });
+const json = JSON.stringify(stableHeaders ?? headers, undefined, 2);
+const tsCode = await format(
+  `// This file is auto-generated by tools/headers.ts. Do not edit manually.
+export default ${json} as string[];
+`,
+  { filepath: dest },
+);
 await writeFile(dest, tsCode, "utf-8");

Optional next step: generate a Set for O(1) membership checks if lookups are hot.

express-zod-api/src/well-known-headers.ts (1)

1-205: LGTM, matches the new import shape.

Optional: add a header comment indicating the file is generated and consider freezing or exporting a Set for faster membership checks.

Example:

// Auto-generated by tools/headers.ts. Do not edit.
export default /* readonly */ [
  // ...
] as string[];
express-zod-api/src/documentation-helpers.ts (1)

48-48: TS extension import confirmed; optional refactoring suggestion is valid.

Verification passed: allowImportingTsExtensions is enabled in the root tsconfig.json, so the .ts extension import is supported.

The optional refactoring suggestion is sound: defaultIsHeader() at line 273-274 uses wellKnownHeaders.includes() on a large array (~260+ entries). Switching to a Set would improve lookup performance from O(n) to O(1), which is worth considering since this function can be called multiple times per request during header parameter processing.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b3ada6e and 2a20000.

📒 Files selected for processing (3)
  • express-zod-api/src/documentation-helpers.ts (1 hunks)
  • express-zod-api/src/well-known-headers.ts (2 hunks)
  • tools/headers.ts (3 hunks)
🔇 Additional comments (2)
tools/headers.ts (2)

3-3: No issue — Prettier v3.6.2 is already in use.

The repository uses Prettier 3.6.2 (devDependencies in package.json), which fully supports named exports. The import syntax is valid and compatible.


212-212: All prerequisites for TS extension imports are already satisfied.

The original review comment's concerns are already addressed:

  1. allowImportingTsExtensions is enabled: The express-zod-api/tsconfig.json extends the root tsconfig.json, which has allowImportingTsExtensions: true. This setting applies to the subdirectory.

  2. Bundler is in place: tsdown (modern successor to tsup) is configured as the build tool and performs module specifier rewriting during the build.

  3. Only compiled artifacts are published: The package.json exports only dist/index.js and dist/index.d.ts—TypeScript source files are not included in the distribution.

Likely an incorrect or invalid review comment.

@RobinTail RobinTail merged commit 38b9547 into master Oct 21, 2025
12 of 13 checks passed
@RobinTail RobinTail deleted the gen-headers-ts branch October 21, 2025 15:10
@coderabbitai coderabbitai Bot mentioned this pull request Dec 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI/CD refactoring The better way to achieve the same result

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant