Skip to content

chore: upgrade to TypeScript 6.0.3 and clean up legacy patterns#1295

Open
curfew-marathon wants to merge 1 commit into
mainfrom
chore/typescript-6-upgrade
Open

chore: upgrade to TypeScript 6.0.3 and clean up legacy patterns#1295
curfew-marathon wants to merge 1 commit into
mainfrom
chore/typescript-6-upgrade

Conversation

@curfew-marathon

@curfew-marathon curfew-marathon commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

Summary

Upgrades TypeScript from 5.9.3 → 6.0.3 (latest stable) and clears out the TS5-era patterns surfaced by the transition release. The goal was a clean upgrade with no strict-mode migration and no legacy
mess left behind — all @typescript-eslint/no-explicit-any suppressions are now gone from src.

No dependency bumps beyond typescript itself were required: @typescript-eslint 8.61.1 already declares support for typescript <6.1.0, and @tsconfig/docusaurus 2.0.9 is already the latest.

Configuration changes

  • Bump typescript 5.9.3 → 6.0.3.
  • Drop the stale module/moduleResolution: "Node16" override — now inherits the modern esnext / bundler settings from @tsconfig/docusaurus, which is correct for a webpack-bundled Docusaurus site.
  • jsx "react" → "react-jsx" to align with the ESLint jsx-runtime config already in use.
  • Pin "strict": false explicitly. TS6 flips strict on by default; the codebase was written against non-strict TS5, so this preserves the existing contract (~50 null-check errors would otherwise appear).
    A full strict migration was intentionally out of scope for this PR.
  • Add "ignoreDeprecations": "6.0" for the inherited baseUrl option, which TS6 deprecates (hard-removed in TS7). baseUrl comes from the base config we don't control, so this is the officially documented
    bridge.
  • Simplify scripts: tsc --skipLibCheck → tsc (skipLibCheck is already set in the base config) and eslint . --ext .ts --ext .tsx → eslint . (--ext is deprecated under the ESLint 9 flat config).

Code cleanup (no behavior change)

  • Lottie data: replace any with a shared LottieAnimationData type (6 *.lottie.ts files + new types.ts).
  • Snippet serializer: introduce a JsonValue union in ExecuteApiRequestViewer and thread it through the per-language value serializers and body fields.
  • Viewer context fields: type as Record<string, unknown> instead of any across the Check / BatchCheck / ListUsers / ListObjects / RelationshipTuples viewers.
  • Casts removed: replace as unknown as TypeDefinition with an isTypeDefinition type guard in SyntaxTransformer; replace the JSON.parse(...) as unknown as sessionStorage cast with a validating
    readCachedGithubStars helper in NavbarNavLink.
  • require() → ESM: convert the SwaggerUI page and AnimatedIcon to React.lazy + dynamic import() inside their existing BrowserOnly guards (also produces proper code-split chunks).

The dynamic, variable-path require() in prism-include-languages.ts is intentionally retained — it's a legitimate synchronous side-effect import that ESM import() can't replace without changing
language-registration timing.

Test plan

  • npm run typecheck — passes (0 errors)
  • npm run lint — passes (0 errors; zero no-explicit-any suppressions remain in src)
  • npm run format:check — clean
  • npx madge --circular . --extensions ts,js,jsx,tsx — no circular dependencies
  • npm run build — full Docusaurus build succeeds; SSR-renders all pages
  • Runtime spot-checks: /api/service (SwaggerUI) serves 200 and renders its Loading... fallback before client hydration; landing-page animated icons render; both lazy components emit as separate JS
    chunks; ABAC conditions page still renders context values into snippets

Notes for reviewers

  • This is a type-only cleanup on top of the version bump — no runtime logic changed, so generated code snippets and rendered output are unchanged.
  • static/llms.txt was deliberately excluded: npm run build regenerates it and it had drifted (a new "Adopters" section), but that's an unrelated docs-content change and belongs in its own PR.

Summary by CodeRabbit

  • Bug Fixes

    • Improved loading behavior for some documentation and API preview views, helping pages open more smoothly.
    • Tightened data handling in several docs snippets and viewers for more reliable rendering.
  • Chores

    • Updated TypeScript and project checks to use newer defaults.
    • Strengthened internal type safety across animation assets and request examples.
    • Adjusted app configuration to align with the latest TypeScript settings.

Copilot AI review requested due to automatic review settings June 24, 2026 15:09
@curfew-marathon curfew-marathon requested review from a team as code owners June 24, 2026 15:09
@coderabbitai

coderabbitai Bot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Upgrades TypeScript from 5.9.3 to 6.0.3, updates tsconfig.json for compatibility, and eliminates any types across Docs viewer components and Lottie animation data files. Migrates AnimatedIcon and SwaggerUI dynamic require() calls to React.lazy+Suspense. Adds an isTypeDefinition type-guard in SyntaxTransformer and a readCachedGithubStars helper in NavbarNavLink.

Changes

TypeScript 6.0 upgrade and type safety

Layer / File(s) Summary
TS 6.0 tooling and tsconfig updates
package.json, tsconfig.json
Bumps typescript to 6.0.3, removes --skipLibCheck and simplifies ESLint script, updates tsconfig.json with react-jsx, strict: false, and ignoreDeprecations: "6.0".
anyunknown/JsonValue in Docs viewer types
src/components/Docs/SnippetViewer/ExecuteApiRequestViewer.tsx, src/components/Docs/SnippetViewer/CheckRequestViewer.tsx, src/components/Docs/SnippetViewer/BatchCheckRequestViewer.tsx, src/components/Docs/SnippetViewer/ListObjectsRequestViewer.tsx, src/components/Docs/SnippetViewer/ListUsersRequestViewer.tsx, src/components/Docs/RelationshipTuples/Viewer.tsx
Introduces a recursive JsonValue type alias and updates all language-specific serializer helpers and ExecuteApiRequestViewerOpts.body to use it; tightens context fields from Record<string, any> to Record<string, unknown> across five viewer interfaces.
LottieAnimationData type, animation files, and lazy loading
src/components/icons/animations/types.ts, src/components/icons/animations/*.lottie.ts, src/components/icons/animations/AnimatedIcon.tsx, src/pages/api/service.tsx
Adds LottieAnimationData = Record<string, unknown> type; updates six Lottie data files from any to LottieAnimationData. Migrates AnimatedIcon and SwaggerUI from BrowserOnly+require() to React.lazy+Suspense.
isTypeDefinition guard and readCachedGithubStars helper
src/components/Docs/AuthorizationModel/SyntaxTransformer.ts, src/theme/NavbarItem/NavbarNavLink.tsx
Adds isTypeDefinition type-guard replacing inline cast logic in SyntaxTransformer's DSL branch; extracts readCachedGithubStars() in NavbarNavLink to encapsulate sessionStorage parsing and field validation.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • openfga/openfga.dev#1272: Touches src/theme/Root.tsx, which is in the same theme directory as NavbarNavLink.tsx modified in this PR.

Suggested reviewers

  • rhamzeh
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: a TypeScript 6.0.3 upgrade and cleanup of legacy patterns.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/typescript-6-upgrade

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed: one or more packages not found in the registry.


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.

@github-actions

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1

QR code for preview link

🚀 View preview at
https://openfga.github.io/openfga.dev/pr-preview/pr-1295/

Built to branch gh-pages at 2026-06-24 15:11 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR upgrades the repo to TypeScript 6.0.3 and performs related type-driven cleanups to remove legacy TS5-era patterns (notably eliminating no-explicit-any suppressions and replacing require() usage under BrowserOnly with React.lazy/import()).

Changes:

  • Bump TypeScript to 6.0.3, adjust tsconfig.json (JSX runtime, explicit strict: false, and TS6 deprecation bridge).
  • Replace any usage with more precise types (Record<string, unknown>, JsonValue, LottieAnimationData) across multiple viewers and animation data files.
  • Replace client-only require() calls with React.lazy + Suspense under existing BrowserOnly guards.

Reviewed changes

Copilot reviewed 18 out of 20 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
tsconfig.json Updates compiler options for TS6 (jsx runtime, strict pin, deprecation bridge).
src/theme/NavbarItem/NavbarNavLink.tsx Adds a cache-reading helper for GitHub stars sessionStorage data.
src/pages/api/service.tsx Converts Swagger UI loading to React.lazy + Suspense under BrowserOnly.
src/components/icons/animations/types.ts Introduces shared LottieAnimationData type.
src/components/icons/animations/open.lottie.ts Replaces any Lottie export type with LottieAnimationData.
src/components/icons/animations/model.lottie.ts Replaces any Lottie export type with LottieAnimationData.
src/components/icons/animations/fast.lottie.ts Replaces any Lottie export type with LottieAnimationData.
src/components/icons/animations/community.lottie.ts Replaces any Lottie export type with LottieAnimationData.
src/components/icons/animations/code.lottie.ts Replaces any Lottie export type with LottieAnimationData.
src/components/icons/animations/auth0.lottie.ts Replaces any Lottie export type with LottieAnimationData.
src/components/icons/animations/AnimatedIcon.tsx Switches Lottie Player loading from require() to React.lazy + Suspense.
src/components/Docs/SnippetViewer/ListUsersRequestViewer.tsx Changes context typing from Record<string, any> to Record<string, unknown>.
src/components/Docs/SnippetViewer/ListObjectsRequestViewer.tsx Changes context typing from Record<string, any> to Record<string, unknown>.
src/components/Docs/SnippetViewer/ExecuteApiRequestViewer.tsx Introduces JsonValue and threads it through request-body serialization typing.
src/components/Docs/SnippetViewer/CheckRequestViewer.tsx Changes context typing from Record<string, any> to Record<string, unknown>.
src/components/Docs/SnippetViewer/BatchCheckRequestViewer.tsx Changes context typing from Record<string, any> to Record<string, unknown>.
src/components/Docs/RelationshipTuples/Viewer.tsx Changes condition context typing from Record<string, any> to Record<string, unknown>.
src/components/Docs/AuthorizationModel/SyntaxTransformer.ts Replaces a cast-based check with a type guard for TypeDefinition handling.
package.json Bumps TypeScript and simplifies typecheck/lint scripts.
package-lock.json Locks TypeScript dependency update to 6.0.3.
Comments suppressed due to low confidence (2)

src/components/Docs/SnippetViewer/ExecuteApiRequestViewer.tsx:31

  • pyValue() always appends a comma before the closing } for object values. When val is an empty object ({}), this renders as {\n,\n}, which is invalid Python and will break generated snippets.
function pyValue(val: JsonValue, indent: number): string {
  if (typeof val === 'string') return `"${val}"`;
  if (typeof val === 'number') return String(val);
  if (typeof val === 'boolean') return val ? 'True' : 'False';
  if (Array.isArray(val)) {

src/components/Docs/SnippetViewer/ExecuteApiRequestViewer.tsx:48

  • goValue() currently treats arrays as generic objects (because it doesn’t check Array.isArray) and always adds a trailing comma before the closing } for maps. This can produce invalid Go (e.g. for {} it renders map[string]interface{}{\n,\n}) and incorrect output for JSON arrays.
function goValue(val: JsonValue, indent: number): string {
  if (typeof val === 'string') return `"${val}"`;
  if (typeof val === 'number' || typeof val === 'boolean') return String(val);
  if (typeof val === 'object' && val !== null) {
    const pad = ' '.repeat(indent);

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +16 to +23
function readCachedGithubStars(): GithubStarsSessionStorage | null {
const raw = sessionStorage.getItem(GITHUB_STARS_SESSION_STORAGE_NAME);
if (!raw) {
return null;
}
const parsed = JSON.parse(raw);
return typeof parsed?.count === 'number' && typeof parsed?.retrievedTime === 'number' ? parsed : null;
}
Comment thread src/pages/api/service.tsx
Comment on lines 1 to +2
import * as React from 'react';
import { lazy, Suspense } from 'react';
Comment on lines 1 to +2
import * as React from 'react';
import { lazy, Suspense } from 'react';
@socket-security

Copy link
Copy Markdown

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Updatedtypescript@​5.9.3 ⏵ 6.0.3100 +110090 +19790

View full report

@socket-security

Copy link
Copy Markdown

Warning

Review the following alerts detected in dependencies.

According to your organization's Security Policy, it is recommended to resolve "Warn" alerts. Learn more about Socket for GitHub.

Action Severity Alert  (click "▶" to expand/collapse)
Warn High
License policy violation: npm typescript under CC-BY-4.0

License: CC-BY-4.0 - The applicable license policy does not permit this license (5) (package/ThirdPartyNoticeText.txt)

License: MIT-Khronos-old - The applicable license policy does not permit this license (5) (package/ThirdPartyNoticeText.txt)

License: LicenseRef-W3C-Community-Final-Specification-Agreement - The applicable license policy does not permit this license (5) (package/ThirdPartyNoticeText.txt)

From: package-lock.jsonnpm/typescript@6.0.3

ℹ Read more on: This package | This alert | What is a license policy violation?

Next steps: Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support@socket.dev.

Suggestion: Find a package that does not violate your license policy or adjust your policy to allow this package's license.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/typescript@6.0.3. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

View full report

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
src/components/Docs/SnippetViewer/ListUsersRequestViewer.tsx (1)

15-15: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Align context with the JSON serialization contract.

Record<string, unknown> still allows non-serializable values. Prefer Record<string, JsonValue> so this option matches the existing request/snippet serialization model and avoids unsafe values leaking into generated payloads.

♻️ Proposed change
+type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
+
 interface ListUsersRequestViewerOpts {
@@
-  context?: Record<string, unknown>;
+  context?: Record<string, JsonValue>;
   expectedResults: ListUsersResponse;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/Docs/SnippetViewer/ListUsersRequestViewer.tsx` at line 15, The
`context` field in `ListUsersRequestViewer` is too permissive for the JSON
serialization model and can admit non-serializable values. Update the `context`
type to use the same JSON-safe value type as the existing request/snippet
serialization contract (for example, `Record<string, JsonValue>`), and make sure
the relevant `ListUsersRequestViewer` prop/interface type references that shared
JSON type consistently.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/components/Docs/SnippetViewer/ExecuteApiRequestViewer.tsx`:
- Around line 9-11: Serializer handling for JsonValue is incomplete in jsValue,
pyValue, goValue, javaValue, and csharpValue: null and array inputs are not
consistently converted into valid target-language literals. Update each
serializer to explicitly handle null and arrays from the shared JsonValue type,
ensuring the emitted snippets use the correct language-specific representation
and remain syntactically valid for every supported JsonValue case.

In `@src/components/Docs/SnippetViewer/ListObjectsRequestViewer.tsx`:
- Line 13: Snippet generation is still treating the ListObjectsRequestViewer
context values as strings even though context now allows non-string JSON-like
values. Update the snippet serializer logic in ListObjectsRequestViewer (and any
shared snippet generation helper it uses) to emit booleans, numbers, and objects
as proper JSON values instead of quoted strings, or tighten the context type
back to strings if that is the only supported shape. Use the context prop and
any serializer/formatter methods connected to snippet output as the entry points
for the fix.

In `@src/theme/NavbarItem/NavbarNavLink.tsx`:
- Around line 16-23: `readCachedGithubStars()` can throw before `getData()`
reaches its existing fallback handling, so wrap the sessionStorage read and
JSON.parse inside the same guarded flow used by `getData()`. Update
`readCachedGithubStars` (or move its call into `getData`) so storage access and
cache parsing failures are caught and return null, preserving the effect’s
fallback path and preventing uncaught errors from escaping.

---

Nitpick comments:
In `@src/components/Docs/SnippetViewer/ListUsersRequestViewer.tsx`:
- Line 15: The `context` field in `ListUsersRequestViewer` is too permissive for
the JSON serialization model and can admit non-serializable values. Update the
`context` type to use the same JSON-safe value type as the existing
request/snippet serialization contract (for example, `Record<string,
JsonValue>`), and make sure the relevant `ListUsersRequestViewer` prop/interface
type references that shared JSON type consistently.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: dc053c79-81cd-4c22-9f7f-98ac35de6f60

📥 Commits

Reviewing files that changed from the base of the PR and between 7335bf7 and 6872b87.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (19)
  • package.json
  • src/components/Docs/AuthorizationModel/SyntaxTransformer.ts
  • src/components/Docs/RelationshipTuples/Viewer.tsx
  • src/components/Docs/SnippetViewer/BatchCheckRequestViewer.tsx
  • src/components/Docs/SnippetViewer/CheckRequestViewer.tsx
  • src/components/Docs/SnippetViewer/ExecuteApiRequestViewer.tsx
  • src/components/Docs/SnippetViewer/ListObjectsRequestViewer.tsx
  • src/components/Docs/SnippetViewer/ListUsersRequestViewer.tsx
  • src/components/icons/animations/AnimatedIcon.tsx
  • src/components/icons/animations/auth0.lottie.ts
  • src/components/icons/animations/code.lottie.ts
  • src/components/icons/animations/community.lottie.ts
  • src/components/icons/animations/fast.lottie.ts
  • src/components/icons/animations/model.lottie.ts
  • src/components/icons/animations/open.lottie.ts
  • src/components/icons/animations/types.ts
  • src/pages/api/service.tsx
  • src/theme/NavbarItem/NavbarNavLink.tsx
  • tsconfig.json

Comment on lines +9 to +11
type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };

function jsValue(val: JsonValue, indent: number): string {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Serializer coverage is incomplete for declared JsonValue inputs.

JsonValue includes null and arrays, but pyValue/goValue/javaValue/csharpValue don’t consistently emit valid literals for those cases, so some generated snippets become invalid or semantically wrong.

💡 Suggested fix
 function pyValue(val: JsonValue, indent: number): string {
+  if (val === null) return 'None';
   if (typeof val === 'string') return `"${val}"`;
   if (typeof val === 'number') return String(val);
   if (typeof val === 'boolean') return val ? 'True' : 'False';
@@
 function goValue(val: JsonValue, indent: number): string {
+  if (val === null) return 'nil';
   if (typeof val === 'string') return `"${val}"`;
   if (typeof val === 'number' || typeof val === 'boolean') return String(val);
+  if (Array.isArray(val)) {
+    const items = val.map((v) => goValue(v, indent + 4));
+    return `[]interface{}{${items.join(', ')}}`;
+  }
   if (typeof val === 'object' && val !== null) {
@@
 function javaValue(val: JsonValue, indent: number): string {
+  if (val === null) return 'null';
   if (typeof val === 'string') return `"${val}"`;
   if (typeof val === 'number' || typeof val === 'boolean') return String(val);
+  if (Array.isArray(val)) {
+    const items = val.map((v) => javaValue(v, indent + 4));
+    return `List.of(${items.join(', ')})`;
+  }
   if (typeof val === 'object' && val !== null) {
@@
 function csharpValue(val: JsonValue, indent: number): string {
+  if (val === null) return 'null';
   if (typeof val === 'string') return `"${val}"`;
   if (typeof val === 'number' || typeof val === 'boolean') return String(val).toLowerCase();
+  if (Array.isArray(val)) {
+    const items = val.map((v) => csharpValue(v, indent + 4));
+    return `new[] { ${items.join(', ')} }`;
+  }
   if (typeof val === 'object' && val !== null) {

Also applies to: 27-27, 44-44, 56-56, 68-68

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/Docs/SnippetViewer/ExecuteApiRequestViewer.tsx` around lines 9
- 11, Serializer handling for JsonValue is incomplete in jsValue, pyValue,
goValue, javaValue, and csharpValue: null and array inputs are not consistently
converted into valid target-language literals. Update each serializer to
explicitly handle null and arrays from the shared JsonValue type, ensuring the
emitted snippets use the correct language-specific representation and remain
syntactically valid for every supported JsonValue case.


// eslint-disable-next-line @typescript-eslint/no-explicit-any
context?: Record<string, any>;
context?: Record<string, unknown>;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

context now accepts non-string values, but snippet generation still stringifies them incorrectly.

Several SDK branches quote context values as strings, so booleans/numbers/objects are emitted incorrectly (e.g., "true", "[object Object]"). Align generation with JSON-value-aware serializers, or narrow the type if only strings are supported.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/Docs/SnippetViewer/ListObjectsRequestViewer.tsx` at line 13,
Snippet generation is still treating the ListObjectsRequestViewer context values
as strings even though context now allows non-string JSON-like values. Update
the snippet serializer logic in ListObjectsRequestViewer (and any shared snippet
generation helper it uses) to emit booleans, numbers, and objects as proper JSON
values instead of quoted strings, or tighten the context type back to strings if
that is the only supported shape. Use the context prop and any
serializer/formatter methods connected to snippet output as the entry points for
the fix.

Comment on lines +16 to +23
function readCachedGithubStars(): GithubStarsSessionStorage | null {
const raw = sessionStorage.getItem(GITHUB_STARS_SESSION_STORAGE_NAME);
if (!raw) {
return null;
}
const parsed = JSON.parse(raw);
return typeof parsed?.count === 'number' && typeof parsed?.retrievedTime === 'number' ? parsed : null;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Guard cache parsing/storage access so errors don’t escape getData().

readCachedGithubStars() can throw (invalid JSON or storage access), and it’s called before the try block in getData(). That bypasses your fallback path and can break the effect flow.

🛡️ Proposed fix
 function readCachedGithubStars(): GithubStarsSessionStorage | null {
-  const raw = sessionStorage.getItem(GITHUB_STARS_SESSION_STORAGE_NAME);
-  if (!raw) {
+  try {
+    const raw = sessionStorage.getItem(GITHUB_STARS_SESSION_STORAGE_NAME);
+    if (!raw) {
+      return null;
+    }
+    const parsed: unknown = JSON.parse(raw);
+    if (
+      typeof parsed === 'object' &&
+      parsed !== null &&
+      typeof (parsed as { count?: unknown }).count === 'number' &&
+      typeof (parsed as { retrievedTime?: unknown }).retrievedTime === 'number'
+    ) {
+      return parsed as GithubStarsSessionStorage;
+    }
     return null;
+  } catch {
+    return null;
   }
-  const parsed = JSON.parse(raw);
-  return typeof parsed?.count === 'number' && typeof parsed?.retrievedTime === 'number' ? parsed : null;
 }

Also applies to: 47-47

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/theme/NavbarItem/NavbarNavLink.tsx` around lines 16 - 23,
`readCachedGithubStars()` can throw before `getData()` reaches its existing
fallback handling, so wrap the sessionStorage read and JSON.parse inside the
same guarded flow used by `getData()`. Update `readCachedGithubStars` (or move
its call into `getData`) so storage access and cache parsing failures are caught
and return null, preserving the effect’s fallback path and preventing uncaught
errors from escaping.

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.

4 participants