Skip to content

chore: Add tanstack/start example and fix docs #981

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed

chore: Add tanstack/start example and fix docs #981

wants to merge 6 commits into from

Conversation

juraj98
Copy link
Contributor

@juraj98 juraj98 commented Sep 24, 2024

This PR is mainly to add example for tanstack/start. The example works if it's started outside of the UT repo, but throws Uncaught TypeError: $RefreshSig$ is not a function if started from the repo. No idea why that is. I'm opening this draft pull request in case someone already encountered this issue and knows a quick fix. Otherwise, I'll revisit this in a few days.

There are also additional changes to docs for getting started in tanstack/start:

  • Changed absolute imports to relative. tanstack/start doesn't include vite-tsconfig-paths by default, so absolute imports do not work, even if paths are configured in tsconfig.json. More info here: TSS Docs: Path Aliases
  • Fixed the way css for UT components is included when not using tailwind.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added a new example for using Tanstack/Start in the documentation.
    • Introduced a file upload interface with real-time feedback for video and image uploads.
    • Implemented a server-side rendering handler for enhanced performance.
  • Documentation

    • Updated README.md with a new example link.
    • Added .env.example for environment variable configuration guidance.
  • Configuration

    • Introduced package.json and tsconfig.json for project setup.
    • Added new configuration files for routing and API handling.

Copy link

changeset-bot bot commented Sep 24, 2024

⚠️ No Changeset found

Latest commit: ba4a6a5

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

vercel bot commented Sep 24, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
docs-uploadthing ❌ Failed (Inspect) Sep 24, 2024 0:25am
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
legacy-docs-uploadthing ⬜️ Ignored (Inspect) Visit Preview Sep 24, 2024 0:25am

@juraj98 juraj98 changed the title [WIP] Add tanstack/start example and fix docs Add tanstack/start example and fix docs Sep 24, 2024
Copy link
Contributor

coderabbitai bot commented Sep 24, 2024

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The pull request introduces several enhancements to the uploadthing repository, including the addition of a new example using Tanstack/Start in the README.md, updates to import paths and CSS handling in the documentation, and the introduction of various new files for a minimal Tanstack application setup. These changes collectively improve the documentation and provide a foundational structure for users to build upon when implementing file uploads with UploadThing.

Changes

File Path Change Summary
README.md Added a new example entry for Tanstack/Start.
docs/src/app/(docs)/getting-started/tanstack-start/page.mdx Updated import paths and CSS inclusion instructions.
examples/minimal-tanstack-start/.env.example Introduced a new environment variable configuration file with a placeholder for UPLOADTHING_TOKEN.
examples/minimal-tanstack-start/app.config.ts Added a new configuration file with a basic setup for the application.
examples/minimal-tanstack-start/app/api.ts Introduced a new API handler file for handling uploads with TanStack.
examples/minimal-tanstack-start/app/client.tsx Added a React application entry point utilizing Tanstack/Start.
examples/minimal-tanstack-start/app/routeTree.gen.ts Created a routing structure file with defined interfaces and route configurations.
examples/minimal-tanstack-start/app/router.tsx Defined a function to create a router and extended the routing framework.
examples/minimal-tanstack-start/app/routes/__root.tsx Introduced a root route component for the application layout.
examples/minimal-tanstack-start/app/routes/api/uploadthing.ts Set up an API route for file uploads.
examples/minimal-tanstack-start/app/routes/index.tsx Created a file upload interface with real-time feedback for users.
examples/minimal-tanstack-start/app/server/uploadthing.ts Implemented a file upload router with custom error handling and configuration.
examples/minimal-tanstack-start/app/ssr.tsx Set up a server-side rendering handler for the application.
examples/minimal-tanstack-start/app/utils/uploadthing.ts Integrated UploadThing functionalities with reusable components and hooks.
examples/minimal-tanstack-start/package.json Introduced a package.json file with project dependencies and scripts.
examples/minimal-tanstack-start/tsconfig.json Added a TypeScript configuration file with specified compiler options.

Possibly related PRs

  • docs: Add getting started for tanstack/start #973: This PR adds a "getting started" guide for the @tanstack/start library, which includes instructions on using the UploadButton and UploadDropzone components, directly related to the new example added in the main PR.
  • docs: Fixed component exports for tanstack/start #979: This PR fixes the export statements for the UploadButton and UploadDropzone components, which are relevant to the example added in the main PR, ensuring that users have the correct import statements for these components.

Suggested labels

@uploadthing/react

Suggested reviewers

  • juliusmarminge

Poem

In the garden where we play,
New examples bloom today.
With uploads flying high and free,
Tanstack's magic, come and see!
Hops of joy, a code delight,
Let's share this with all in sight! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    -- I pushed a fix in commit <commit_id>, please review it.
    -- Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    -- @coderabbitai generate unit testing code for this file.
    -- @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    -- @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    -- @coderabbitai read src/utils.ts and generate unit testing code.
    -- @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    -- @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@juraj98
Copy link
Contributor Author

juraj98 commented Sep 24, 2024

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Sep 24, 2024

Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@juraj98 juraj98 changed the title Add tanstack/start example and fix docs chore: Add tanstack/start example and fix docs Sep 24, 2024
Copy link
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: 9

Outside diff range and nitpick comments (15)
examples/minimal-tanstack-start/.env.example (1)

1-2: LGTM! Consider adding a note about copying the file.

The .env.example file is well-structured and provides clear instructions for obtaining the UPLOADTHING_TOKEN. This is a good practice for maintaining security by not committing actual tokens to the repository.

Consider adding a comment suggesting users copy this file to .env and replace the placeholder with their actual token. For example:

 # Go to https://uploadthing.com/dashboard to get your token
+# Copy this file to .env and replace the placeholder with your actual token
 UPLOADTHING_TOKEN='...'

This additional instruction can help users, especially those new to environment variable configuration, set up their project correctly.

examples/minimal-tanstack-start/app.config.ts (1)

1-3: Consider adding documentation and expanding the configuration.

While the current setup is minimal and functional, it could be improved in the following ways:

  1. Add comments explaining the purpose of this file and how to extend the configuration.
  2. Consider adding some basic configuration options to demonstrate TanStack Start's capabilities.

Example:

import { defineConfig } from "@tanstack/start/config";

// This file configures the TanStack Start application.
// Add your custom configuration options here.
export default defineConfig({
  // Example configuration options:
  // server: {
  //   port: 3000,
  // },
  // build: {
  //   outDir: 'dist',
  // },
});

This would provide more context for developers new to TanStack Start and serve as a better example in the PR.

examples/minimal-tanstack-start/app/api.ts (1)

6-6: LGTM: Default API handler correctly exported

The default export creates an API handler using the imported functions, which is the correct setup for a TanStack Start application. This establishes a basic API handler for the application.

Consider adding a brief comment explaining the purpose of this file and how it integrates with the rest of the application. This would be helpful for developers who are new to TanStack Start. For example:

// This file sets up the default API handler for our TanStack Start application.
// It uses the createStartAPIHandler function with the defaultAPIFileRouteHandler
// to handle API routes defined in our application.
export default createStartAPIHandler(defaultAPIFileRouteHandler);
examples/minimal-tanstack-start/tsconfig.json (1)

4-4: LGTM: Modern module resolution strategy.

The "moduleResolution": "Bundler" setting is appropriate for projects using modern bundlers. It provides better integration with tools like Webpack, Vite, or esbuild.

Consider adding "allowImportingTsExtensions": true to the compiler options. This allows importing TypeScript files with .ts or .tsx extensions, which can be useful in a bundled environment.

examples/minimal-tanstack-start/app/client.tsx (2)

6-6: LGTM: Router creation is correct.

The router instance is created correctly using the imported createRouter function. This approach is suitable for a minimal example.

Consider adding a comment explaining the purpose of the router or any specific configuration it might have in the future. This can help other developers understand the router's role in the application.


8-8: Application rendering looks good, but consider handling potential null case.

The use of hydrateRoot for client-side hydration is correct, and the StartClient component is properly used with the router prop. However, the non-null assertion (!) when getting the root element might lead to runtime errors if the element is not found.

Consider adding a null check or using a more robust method to ensure the root element exists. Here's an example of how you could improve this:

-hydrateRoot(document.getElementById("root")!, <StartClient router={router} />);
+const rootElement = document.getElementById("root");
+if (rootElement) {
+  hydrateRoot(rootElement, <StartClient router={router} />);
+} else {
+  console.error("Root element not found");
+}

This change will prevent potential runtime errors and provide better error handling.

examples/minimal-tanstack-start/app/ssr.tsx (1)

9-12: SSR setup looks good, consider enhancements for production.

The SSR handler setup is correctly implemented using createStartHandler with the necessary configuration. The use of defaultStreamHandler is a good practice for streaming server-rendered content, which can improve performance.

For a minimal example, this setup is sufficient. However, for production use, consider the following enhancements:

  1. Add error handling to manage potential issues during SSR.
  2. Implement custom configurations or middleware if needed for your specific use case.
  3. Consider adding performance optimizations such as caching strategies.
examples/minimal-tanstack-start/app/routes/api/uploadthing.ts (1)

8-11: LGTM: API route export is correctly implemented.

The Route export is properly set up using createAPIFileRoute for the '/api/uploadthing' endpoint. Both GET and POST methods correctly use the same handlers, which is typical for file upload endpoints.

Consider destructuring the handlers object for improved readability:

export const Route = createAPIFileRoute("/api/uploadthing")({
-  GET: handlers,
-  POST: handlers,
+  GET: handlers.GET,
+  POST: handlers.POST,
});

This change makes it explicit which methods are being used from the handlers object.

examples/minimal-tanstack-start/app/router.tsx (2)

13-17: LGTM: Module augmentation is correct and enhances type safety.

The module augmentation for "@tanstack/react-router" is well-implemented:

  1. It extends the Register interface to include the custom router type.
  2. Using ReturnType<typeof createRouter> ensures type consistency.

This augmentation will improve type checking and autocompletion when using the router in other parts of the application.

Consider adding a brief comment explaining the purpose of this module augmentation for better code documentation:

 declare module "@tanstack/react-router" {
+  // Augment the Register interface to include our custom router type
   interface Register {
     router: ReturnType<typeof createRouter>;
   }
 }

1-17: Overall implementation looks great, with a minor suggestion for improvement.

The router setup is well-structured and follows best practices:

  1. Clear separation of concerns with route definitions in a separate file.
  2. Concise createRouter function for easy instantiation.
  3. Proper type augmentation for enhanced type safety.

Consider adding basic error handling to make the router creation more robust:

 export function createRouter() {
-  const router = createTanStackRouter({
-    routeTree,
-  });
+  try {
+    const router = createTanStackRouter({
+      routeTree,
+    });
+    return router;
+  } catch (error) {
+    console.error("Failed to create router:", error);
+    throw error; // Re-throw to allow handling by the caller if needed
+  }
-  return router;
 }

This change would help catch and log any unexpected errors during router creation, making debugging easier if issues arise.

examples/minimal-tanstack-start/app/utils/uploadthing.ts (1)

1-12: Consider adding explanatory comments.

The implementation is clean and follows best practices. To improve maintainability and ease of use for other developers, consider adding a brief comment at the top of the file explaining its purpose and how to use the exported components and hook.

Here's a suggested comment to add at the beginning of the file:

/**
 * This file sets up and exports the necessary components and hooks for file uploads
 * using the @uploadthing/react library. It includes:
 * - UploadButton: A button component for initiating file uploads
 * - UploadDropzone: A dropzone component for drag-and-drop file uploads
 * - useUploadThing: A custom hook for managing the upload process
 * 
 * All components and hooks are type-safe and integrated with the server-side upload router.
 */
examples/minimal-tanstack-start/app/routes/__root.tsx (1)

17-38: LGTM: Component structure is well-organized. Consider adding a lang attribute for accessibility.

The RootComponent and RootDocument are well-structured and follow best practices for a root component in a React application. The use of Outlet allows for proper rendering of nested routes, and the placement of ScrollRestoration and Scripts is correct for optimal performance.

Consider adding a lang attribute to the Html component for better accessibility:

- <Html>
+ <Html lang="en">

This helps screen readers and other assistive technologies to properly interpret the content.

examples/minimal-tanstack-start/app/server/uploadthing.ts (2)

1-16: LGTM! Consider enhancing error logging.

The imports and error formatter setup look good. The error formatter effectively logs detailed information while providing a simplified message to the client, which is a good security practice.

Consider using a structured logging format for better error tracking:

 errorFormatter: (err) => {
-  console.log("Error uploading file", err.message);
-  console.log("  - Above error caused by:", err.cause);
+  console.error({
+    message: "Error uploading file",
+    error: err.message,
+    cause: err.cause
+  });

   return { message: err.message };
 },

22-35: LGTM! Consider adding file type validation.

The uploadRouter configuration looks good, with appropriate size limits and access control settings for different file types.

Consider adding file type validation to ensure only specific image and video formats are accepted. This can be done using the accept option:

 image: {
   maxFileSize: "32MB",
   maxFileCount: 4,
   acl: "public-read",
+  accept: ["image/jpeg", "image/png", "image/gif"],
 },
 video: {
   maxFileSize: "16MB",
+  accept: ["video/mp4", "video/webm"],
 },

Also applies to: 60-60

docs/src/app/(docs)/getting-started/tanstack-start/page.mdx (1)

Line range hint 1-168: Summary: Documentation updates successfully address PR objectives

The changes in this file effectively address the PR objectives:

  1. Switching from absolute to relative imports: All import statements have been consistently updated to use relative paths, which should resolve the issues with absolute imports in tanstack/start.

  2. Updating CSS inclusion: The documentation now correctly specifies including CSS in the root route when Tailwind is not being used.

These modifications improve the getting started guide for using UploadThing with Tanstack/Start. However, there are two points that require further clarification:

  1. The reason for the TypeScript error suppression in the CSS import.
  2. The implications of using a URL query parameter for the CSS import.

Once these points are addressed, the documentation will provide a more robust and clear guide for users.

To further improve the documentation:

  1. Consider adding a troubleshooting section that addresses common issues, such as the Uncaught TypeError: $RefreshSig$ is not a function error mentioned in the PR summary.
  2. Provide more context on why relative imports are necessary for Tanstack/Start, possibly linking to relevant Tanstack documentation.
  3. If possible, include a complete working example of a Tanstack/Start project with UploadThing integration, which could help users quickly get up and running.
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 073c4ec and 2c96f6a.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (16)
  • README.md (1 hunks)
  • docs/src/app/(docs)/getting-started/tanstack-start/page.mdx (4 hunks)
  • examples/minimal-tanstack-start/.env.example (1 hunks)
  • examples/minimal-tanstack-start/app.config.ts (1 hunks)
  • examples/minimal-tanstack-start/app/api.ts (1 hunks)
  • examples/minimal-tanstack-start/app/client.tsx (1 hunks)
  • examples/minimal-tanstack-start/app/routeTree.gen.ts (1 hunks)
  • examples/minimal-tanstack-start/app/router.tsx (1 hunks)
  • examples/minimal-tanstack-start/app/routes/__root.tsx (1 hunks)
  • examples/minimal-tanstack-start/app/routes/api/uploadthing.ts (1 hunks)
  • examples/minimal-tanstack-start/app/routes/index.tsx (1 hunks)
  • examples/minimal-tanstack-start/app/server/uploadthing.ts (1 hunks)
  • examples/minimal-tanstack-start/app/ssr.tsx (1 hunks)
  • examples/minimal-tanstack-start/app/utils/uploadthing.ts (1 hunks)
  • examples/minimal-tanstack-start/package.json (1 hunks)
  • examples/minimal-tanstack-start/tsconfig.json (1 hunks)
Files skipped from review due to trivial changes (1)
  • examples/minimal-tanstack-start/app/routeTree.gen.ts
Additional comments not posted (31)
examples/minimal-tanstack-start/app.config.ts (1)

1-3: LGTM! Basic configuration setup is correct.

The file correctly imports defineConfig from @tanstack/start/config and exports a default configuration. This provides a good starting point for a TanStack Start application.

examples/minimal-tanstack-start/app/api.ts (2)

1-4: LGTM: Imports are correctly structured

The imports from "@tanstack/start/api" are well-organized and align with the PR objective of adding a TanStack Start example. These functions are essential for setting up the API handler in a TanStack Start application.


1-6: Overall: Well-structured and minimal TanStack Start API setup

This file successfully sets up a basic API handler for the TanStack Start example, aligning with the PR objectives. The implementation is concise, follows best practices, and effectively leverages the TanStack library's functionality.

To ensure this setup is consistent with other parts of the example, let's check for any other API-related files:

This will help verify that the API setup is consistent across the example and that we haven't missed any related files in our review.

Verification successful

Additional API-related file detected: routes/api/uploadthing.ts

To ensure consistency and completeness in the API setup, let's examine the contents of routes/api/uploadthing.ts:

[/run_scripts]


Verification Complete: API setup is consistent and follows best practices

Both app/api.ts and app/routes/api/uploadthing.ts have been reviewed and are consistently implemented. The API handlers are concise, adhere to best practices, and effectively utilize the TanStack library's functionality.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other API-related files in the example

# Test: Search for files with 'api' in their name
fd -t f api examples/minimal-tanstack-start

# Test: Search for files that import from @tanstack/start/api
rg -t ts "from\s+['\"]@tanstack/start/api['\"]" examples/minimal-tanstack-start

Length of output: 367


Script:

#!/bin/bash
# Description: Retrieve the contents of the uploadthing.ts file for review

cat examples/minimal-tanstack-start/app/routes/api/uploadthing.ts

Length of output: 406

examples/minimal-tanstack-start/tsconfig.json (4)

3-3: LGTM: Appropriate JSX setting for React.

The "jsx": "react-jsx" setting is correct for a modern React project. It enables the new JSX transform, which improves bundle size and simplifies code by not requiring React import in every file using JSX.


7-7: Consider the trade-offs of skipping library checks.

The "skipLibCheck": true setting can significantly speed up compilation, which is beneficial for large projects. However, be aware that this option skips type checking of declaration files (.d.ts), potentially missing some type errors in dependencies.

To ensure this setting doesn't hide critical type issues, consider running occasional full type checks in your CI pipeline. Here's a script to check if there's a CI configuration file that might be suitable for adding this check:

#!/bin/bash
# Description: Check for CI configuration files in the project.

# Test: Look for common CI configuration files
fd -g '.github/workflows/*.yml'
fd -g '.gitlab-ci.yml'
fd -g '.circleci/config.yml'
fd -g 'azure-pipelines.yml'

1-9: 🛠️ Refactor suggestion

Consider adding stricter type-checking options.

While the current configuration is suitable for a minimal setup, consider enhancing type safety by adding the following compiler options:

 {
   "compilerOptions": {
     "jsx": "react-jsx",
     "moduleResolution": "Bundler",
     "module": "ESNext",
     "target": "ES2022",
-    "skipLibCheck": true
+    "skipLibCheck": true,
+    "strict": true,
+    "esModuleInterop": true,
+    "forceConsistentCasingInFileNames": true
   }
 }

These additional options will:

  • Enable strict type-checking (strict)
  • Improve compatibility with CommonJS modules (esModuleInterop)
  • Ensure consistent file naming across different operating systems (forceConsistentCasingInFileNames)

To check if these stricter options might cause issues in the existing codebase, run the following script:

#!/bin/bash
# Description: Check for potential strict mode issues in TypeScript files.

# Test: Look for common patterns that might cause issues in strict mode
rg -g '!examples' --type typescript '(any|as\s+any|\!\w+|undefined|null)'

5-6: LGTM: Modern JavaScript settings.

The "module": "ESNext" and "target": "ES2022" settings are appropriate for leveraging modern JavaScript features. This configuration allows for the latest ECMAScript module syntax and targets recent language features.

Consider your target browser support. If you need to support older browsers, you might need to adjust these settings or ensure proper transpilation in your build process. Run the following script to check if there are any browser support specifications in your project:

Verification successful

LGTM: Modern JavaScript settings confirmed.

The project specifies a "browserslist": "defaults, not ie <= 11" in docs/package.json, ensuring compatibility with modern browsers while excluding older Internet Explorer versions. The "module": "ESNext" and "target": "ES2022" settings in tsconfig.json are appropriate based on these browser support specifications.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for browser support specifications in the project.

# Test: Look for browserslist config or similar in package.json or separate config files
rg -g '!examples' --type json '"browserslist":'
fd -g '.browserslistrc'

Length of output: 286


Script:

#!/bin/bash
# Description: Check for browser support specifications in the project.

# Search for "browserslist" configurations in JSON files, excluding the 'examples' directory
rg --glob '!examples/**' --type json '"browserslist"'

# Find any .browserslistrc files, excluding the 'examples' directory
fd --exclude 'examples' --glob '.browserslistrc'

Length of output: 372


Script:

#!/bin/bash
# Description: Check for browser support specifications in the project.

# Search for "browserslist" configurations in JSON files, excluding the 'examples' directory
rg --glob '!examples/**' --type json '"browserslist"'

# Find any .browserslistrc files, excluding the 'examples' directory and including hidden files
fd --exclude examples --hidden --glob '.browserslistrc'

Length of output: 173

examples/minimal-tanstack-start/app/client.tsx (2)

1-2: LGTM: Import statements are correct and concise.

The import statements are well-organized and include all necessary dependencies for the application. The use of a local import for the router configuration promotes good code organization.

Also applies to: 4-4


1-8: Overall, the minimal example is well-structured and functional.

This file successfully demonstrates a basic setup for a React application using @tanstack/start. It correctly imports necessary dependencies, creates a router instance, and renders the application using client-side hydration. The code is concise and achieves its purpose as a minimal example.

While there are no major issues, consider implementing the suggested improvements:

  1. Add comments to explain the router's purpose and potential future configurations.
  2. Implement a null check when getting the root element to enhance error handling.

These changes would further improve the code quality and make it more robust for educational purposes.

examples/minimal-tanstack-start/app/ssr.tsx (2)

1-7: Imports look good and align with PR objectives.

The imports are correctly structured and include the necessary functions for SSR setup. The use of a relative import for the router (./router) aligns with the PR objective of switching from absolute to relative imports, which addresses the issue with tanstack/start not including vite-tsconfig-paths by default.


1-12: Overall, the SSR setup looks correct, but further investigation is needed for the reported error.

This file successfully sets up a basic SSR handler for a TanStack application and aligns with the PR objectives. The implementation follows the recommended structure and uses the correct imports.

However, the reported error Uncaught TypeError: $RefreshSig$ is not a function is not directly related to the code in this file. This error typically occurs during development and is often associated with hot module replacement or fast refresh functionality.

To troubleshoot this issue:

  1. Verify that all dependencies are correctly installed and up-to-date.
  2. Check the build configuration (e.g., webpack or vite setup) for any conflicts or misconfigurations.
  3. Investigate how the application is initiated within the UploadThing repository, as the error only occurs in that context.
  4. Consider adding a minimal reproduction of the error in a separate branch or repository to isolate the issue.

To help identify potential causes, let's check for any custom configurations or development dependencies that might interfere with the normal operation of tanstack/start:

This script will help identify any custom configurations or dependencies that might be causing conflicts with tanstack/start.

examples/minimal-tanstack-start/app/routes/api/uploadthing.ts (3)

1-5: LGTM: Imports are correctly structured and align with PR objectives.

The imports are well-organized and include all necessary functions for the file's functionality. The use of a relative import for uploadRouter aligns with the PR objective of switching from absolute to relative imports, which addresses issues with tanstack/start not including vite-tsconfig-paths by default.


7-7: LGTM: Route handler creation is correct.

The route handlers are properly created using the createRouteHandler function with the imported uploadRouter. This setup ensures that the upload functionality is correctly integrated into the API route.


1-11: Overall implementation looks good, but verification needed.

The file successfully sets up an API route for handling file uploads, integrating well with both tanstack/start and uploadthing libraries. The implementation aligns with the PR objectives, particularly in using relative imports.

However, we need to verify if this implementation resolves the reported error: Uncaught TypeError: $RefreshSig$ is not a function. Please run the following script to check for any occurrences of $RefreshSig$ in the codebase:

If the script returns any results, it might indicate that the error is still present in some parts of the codebase. In that case, further investigation would be needed to resolve the issue.

examples/minimal-tanstack-start/app/router.tsx (2)

1-3: LGTM: Imports are correctly set up.

The imports are well-organized and follow good practices:

  1. Renaming createRouter to createTanStackRouter avoids naming conflicts.
  2. Importing routeTree from a separate file promotes modularity and maintainability.

5-11: LGTM: createRouter function is well-implemented.

The createRouter function is concise and correctly sets up the TanStack router with the imported routeTree. The implementation is clean and easy to understand.

examples/minimal-tanstack-start/app/utils/uploadthing.ts (3)

1-7: LGTM: Imports are well-structured and appropriate.

The import statements are clean and follow best practices. They import the necessary functions from "@uploadthing/react" and the custom type from the local server module, which is good for maintaining type safety across the client-server boundary.


9-10: LGTM: UploadButton and UploadDropzone are correctly generated and exported.

The UploadButton and UploadDropzone components are properly generated using the functions from @uploadthing/react, and they're correctly parameterized with the OurFileRouter type. This ensures type safety and consistency with your server-side router configuration.


12-12: LGTM: useUploadThing hook is correctly generated and exported.

The useUploadThing hook is properly generated using the generateReactHelpers function and correctly parameterized with the OurFileRouter type. The use of destructuring in the export statement is a clean way to expose only the necessary part of the generated helpers.

examples/minimal-tanstack-start/package.json (2)

1-4: LGTM: Project metadata is well-configured.

The project metadata is correctly set up:

  • The scoped package name is appropriate for an example project.
  • "private": true prevents accidental publication.
  • "type": "module" correctly specifies the use of ECMAScript modules.

5-9: LGTM: Scripts are appropriately defined.

The scripts section is well-configured:

  • It includes standard scripts for development, building, and starting the application.
  • The use of "vinxi" for all scripts is consistent with the project's dependencies.
examples/minimal-tanstack-start/app/routes/__root.tsx (1)

12-15: LGTM: Root route definition is correct and includes necessary styles.

The root route is properly defined using createRootRoute, specifying the RootComponent and including the UploadThing CSS. This ensures that the necessary styles are available throughout the application.

examples/minimal-tanstack-start/app/server/uploadthing.ts (1)

62-62: LGTM! Good type export practice.

Exporting the OurFileRouter type is a good practice. It allows other parts of the application to use the correct type for the upload router, maintaining type safety across the application.

examples/minimal-tanstack-start/app/routes/index.tsx (3)

1-7: LGTM: Imports are correctly structured and necessary.

The imports from "@tanstack/react-router" and "../utils/uploadthing" are appropriate for the functionality of this component.


9-11: LGTM: Route definition is correct.

The route is properly defined using createFileRoute from TanStack Router, setting the path to "/" and using the Home component.


1-79: Overall, the implementation is correct but could benefit from enhanced error handling and user feedback.

The file successfully implements a file upload interface using TanStack Router and UploadThing. The structure and logic are sound, but consider implementing the suggested improvements throughout the component:

  1. Enhance error handling in all upload-related functions.
  2. Replace alert and console.log statements with more appropriate user feedback mechanisms.
  3. Implement loading states to improve user experience during uploads.
  4. Add the suggested pre-upload processing for the file input.

These changes will significantly improve the robustness and user-friendliness of the component.

README.md (1)

26-27: Approve the new example addition with suggestions

The addition of the Tanstack/Start example to the list is good and consistent with the existing format. However, there are a few points to address:

  1. The PR objectives mention issues with the Tanstack/Start example when started from within the repository. Consider adding a note about this known issue in the description, such as:

    A simple example using Tanstack/Start (Note: Currently experiencing issues when started within the repository)
  2. The PR objectives also mention changes to documentation regarding imports and CSS. These changes are not reflected in the README.md. Could you clarify if these changes should be documented here or in a separate file?

To ensure the example directory exists and contains the necessary files, please run the following script:

docs/src/app/(docs)/getting-started/tanstack-start/page.mdx (4)

99-99: Approved: Import path updated to use relative import

This change from an absolute import to a relative import aligns with the PR objectives. It addresses the issue with absolute imports in tanstack/start, which doesn't include vite-tsconfig-paths by default. This modification should resolve the import problems mentioned in the PR summary.


123-123: Approved: Consistent update to use relative import

This change is consistent with the previous import modification, switching from an absolute import to a relative import for OurFileRouter. It further addresses the issue with absolute imports in tanstack/start and maintains consistency throughout the documentation.


148-157: Approved with comments: CSS inclusion updated, but clarification needed

The changes to include CSS in the root route instead of the root layout are appropriate and align with the PR objectives. However, there are two points that require attention:

  1. The addition of a TypeScript error suppression comment (// @ts-expect-error) suggests a potential type mismatch. Could you please clarify why this is necessary and if there's a way to resolve the type issue without suppressing the error?

  2. The use of a URL query parameter for the CSS import (from "@uploadthing/react/styles.css?url") is an interesting approach to ensure the latest version is loaded. However, this might have implications for caching and performance. Could you explain the reasoning behind this choice and confirm if this is the recommended approach for all users?


168-168: Approved: Consistent update to use relative import

This change is in line with the previous import modifications, switching from an absolute import to a relative import for UploadButton. It maintains consistency throughout the documentation and addresses the issue with absolute imports in tanstack/start.

Comment on lines +20 to +24
"devDependencies": {
"@types/react": "18.3.3",
"@types/react-dom": "18.3.0",
"typescript": "^5.5.2"
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Align devDependencies versions with dependencies.

The devDependencies section includes appropriate type definitions, but there are version mismatches:

  1. React type definitions: The versions for "@types/react" (18.3.3) and "@types/react-dom" (18.3.0) do not match the React versions in the dependencies (18.3.1).

  2. Version consistency: Consider using caret ranges for all devDependencies to allow for minor updates and bug fixes.

Consider applying these changes:

 "devDependencies": {
-  "@types/react": "18.3.3",
-  "@types/react-dom": "18.3.0",
+  "@types/react": "^18.2.0",
+  "@types/react-dom": "^18.2.0",
   "typescript": "^5.5.2"
 }

These changes will align the type definition versions with the React versions suggested in the previous comment and allow for minor updates across all devDependencies.

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"devDependencies": {
"@types/react": "18.3.3",
"@types/react-dom": "18.3.0",
"typescript": "^5.5.2"
}
"devDependencies": {
"@types/react": "^18.2.0",
"@types/react-dom": "^18.2.0",
"typescript": "^5.5.2"
}

Comment on lines 10 to 19
"dependencies": {
"@uploadthing/react": "7.0.2",
"@tanstack/react-router": "^1.58.7",
"@tanstack/start": "^1.58.7",
"@vitejs/plugin-react": "^4.3.1",
"react": "18.3.1",
"react-dom": "18.3.1",
"vinxi": "0.3.11",
"uploadthing": "7.0.2"
},
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Review and update dependency versions.

The dependencies section includes appropriate packages for the project, but there are some inconsistencies and potential issues:

  1. React version: The specified version "18.3.1" for both "react" and "react-dom" is not a released version. The latest stable version is 18.2.0.

  2. Version consistency: Some packages use exact versions, while others use caret ranges. Consider using consistent versioning across all dependencies.

  3. Vinxi version: The exact version "0.3.11" is used. For a build tool, it might be beneficial to use a caret range to allow for minor updates and bug fixes.

Consider applying these changes:

 "dependencies": {
   "@uploadthing/react": "^7.0.2",
   "@tanstack/react-router": "^1.58.7",
   "@tanstack/start": "^1.58.7",
   "@vitejs/plugin-react": "^4.3.1",
-  "react": "18.3.1",
-  "react-dom": "18.3.1",
+  "react": "^18.2.0",
+  "react-dom": "^18.2.0",
-  "vinxi": "0.3.11",
+  "vinxi": "^0.3.11",
-  "uploadthing": "7.0.2"
+  "uploadthing": "^7.0.2"
 }

These changes will ensure you're using the latest stable version of React and allow for minor updates and bug fixes across all dependencies.

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"dependencies": {
"@uploadthing/react": "7.0.2",
"@tanstack/react-router": "^1.58.7",
"@tanstack/start": "^1.58.7",
"@vitejs/plugin-react": "^4.3.1",
"react": "18.3.1",
"react-dom": "18.3.1",
"vinxi": "0.3.11",
"uploadthing": "7.0.2"
},
"dependencies": {
"@uploadthing/react": "^7.0.2",
"@tanstack/react-router": "^1.58.7",
"@tanstack/start": "^1.58.7",
"@vitejs/plugin-react": "^4.3.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"vinxi": "^0.3.11",
"uploadthing": "^7.0.2"
},

Comment on lines +9 to +10
// @ts-expect-error
import uploadthingCss from "@uploadthing/react/styles.css?url";
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consider addressing the TypeScript error for the uploadthingCss import.

The @ts-expect-error comment suggests there's a type issue with the uploadthingCss import. This might be due to missing type definitions for the CSS module.

Consider the following alternatives:

  1. Create a declaration file (e.g., custom.d.ts) to declare the module:
    declare module '@uploadthing/react/styles.css?url' {
      const content: string;
      export default content;
    }
  2. Use a more specific comment: // @ts-ignore: CSS module import
  3. Investigate why the types are missing and consider updating @uploadthing/react if it's outdated.

Comment on lines +53 to +59
.onUploadComplete(({ file, metadata }) => {
metadata;
// ^?
file.customId;
// ^?
console.log("upload completed", file);
}),
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove development assertions and enhance upload completion handling.

The onUploadComplete callback provides basic logging functionality. However, there are a few points to address:

  1. Remove the TypeScript assertions (^?) as they are likely leftover from development.
  2. Consider enhancing the upload completion handling with more detailed logging or additional actions.

Here's a suggested improvement:

 .onUploadComplete(({ file, metadata }) => {
-  metadata;
-  // ^?
-  file.customId;
-  //   ^?
-  console.log("upload completed", file);
+  console.log("Upload completed", {
+    fileId: file.id,
+    fileName: file.name,
+    fileSize: file.size,
+    customId: file.customId,
+    metadata
+  });
+  // Perform additional actions here, e.g., update database, send notifications, etc.
 }),
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
.onUploadComplete(({ file, metadata }) => {
metadata;
// ^?
file.customId;
// ^?
console.log("upload completed", file);
}),
.onUploadComplete(({ file, metadata }) => {
console.log("Upload completed", {
fileId: file.id,
fileName: file.name,
fileSize: file.size,
customId: file.customId,
metadata
});
// Perform additional actions here, e.g., update database, send notifications, etc.
}),

Comment on lines +36 to +52
.middleware(({ req, files }) => {
// Check some condition based on the incoming requrest
console.log("Request", req);
//^?
// if (!req.headers.get("x-some-header")) {
// throw new Error("x-some-header is required");
// }

// (Optional) Label your files with a custom identifier
const filesWithMyIds = files.map((file, idx) => ({
...file,
customId: `${idx}-${randomUUID()}`,
}));

// Return some metadata to be stored with the file
return { foo: "bar" as const, [UTFiles]: filesWithMyIds };
})
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

🛠️ Refactor suggestion

Implement the x-some-header security check.

The middleware currently does not enforce the required x-some-header security check, as the relevant code is only present in commented-out sections. To maintain security standards, please implement this header validation. If the security check is no longer necessary, consider removing the commented-out code to enhance code clarity.

Analysis chain

Consider implementing the commented-out security check.

The middleware implementation looks good, especially the addition of custom identifiers for file tracking. However, there's a commented-out section that suggests a potential security check.

If the header check is necessary for security, consider implementing it. If not, remove the commented code to improve readability.

Consider moving the file labeling logic to a separate function for better readability:

const labelFilesWithCustomId = (files: UTFiles) =>
  files.map((file, idx) => ({
    ...file,
    customId: `${idx}-${randomUUID()}`,
  }));

// In the middleware:
const filesWithMyIds = labelFilesWithCustomId(files);
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the x-some-header check is implemented elsewhere
rg --type typescript 'x-some-header'

Length of output: 71


Script:

#!/bin/bash
# Check if the x-some-header check is implemented elsewhere
rg --type ts 'x-some-header' || rg --type tsx 'x-some-header' || rg --glob '*.ts' 'x-some-header' || rg --glob '*.tsx' 'x-some-header'

Length of output: 2170

Comment on lines +14 to +31
const { startUpload } = useUploadThing("videoAndImage", {
/**
* @see https://docs.uploadthing.com/api-reference/react#useuploadthing
*/
onBeforeUploadBegin: (files) => {
console.log("Uploading", files.length, "files");
return files;
},
onUploadBegin: (name) => {
console.log("Beginning upload of", name);
},
onClientUploadComplete: (res) => {
console.log("Upload Completed.", res.length, "files uploaded");
},
onUploadProgress(p) {
console.log("onUploadProgress", p);
},
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider improving error handling and removing console.log statements.

The useUploadThing hook is correctly used, but consider the following improvements:

  1. Add error handling to the onClientUploadComplete callback.
  2. Remove or conditionally render console.log statements for production builds.

Here's a suggested improvement:

const { startUpload } = useUploadThing("videoAndImage", {
  onBeforeUploadBegin: (files) => {
    // Consider using a logger that can be disabled in production
    console.log("Uploading", files.length, "files");
    return files;
  },
  onUploadBegin: (name) => {
    console.log("Beginning upload of", name);
  },
  onClientUploadComplete: (res) => {
    console.log("Upload Completed.", res.length, "files uploaded");
    // Consider adding success feedback to the user
  },
  onUploadError: (error) => {
    console.error("Upload failed:", error);
    // Consider adding error feedback to the user
  },
  onUploadProgress(p) {
    console.log("onUploadProgress", p);
    // Consider updating a progress indicator for the user
  },
});

Comment on lines +35 to +48
<UploadButton
/**
* @see https://docs.uploadthing.com/api-reference/react#uploadbutton
*/
endpoint="videoAndImage"
onClientUploadComplete={(res) => {
console.log(`onClientUploadComplete`, res);
alert("Upload Completed");
}}
onUploadBegin={() => {
console.log("upload begin");
}}
config={{ appendOnPaste: true, mode: "manual" }}
/>
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance UploadButton with better user feedback and error handling.

The UploadButton is correctly implemented, but consider the following improvements:

  1. Add error handling with the onUploadError prop.
  2. Replace alert with a more user-friendly notification system.
  3. Consider adding a loading state while the upload is in progress.

Here's a suggested improvement:

<UploadButton
  endpoint="videoAndImage"
  onClientUploadComplete={(res) => {
    console.log(`onClientUploadComplete`, res);
    // Replace with a more user-friendly notification
    // notifyUser("Upload Completed");
  }}
  onUploadBegin={() => {
    console.log("upload begin");
    // Consider updating UI to show upload has started
  }}
  onUploadError={(error) => {
    console.error("Upload failed:", error);
    // notifyUser("Upload failed. Please try again.");
  }}
  config={{ appendOnPaste: true, mode: "manual" }}
/>

Comment on lines +49 to +64
<UploadDropzone
/**
* @see https://docs.uploadthing.com/api-reference/react#uploaddropzone
*/
endpoint="videoAndImage"
onUploadAborted={() => {
alert("Upload Aborted");
}}
onClientUploadComplete={(res) => {
console.log(`onClientUploadComplete`, res);
alert("Upload Completed");
}}
onUploadBegin={() => {
console.log("upload begin");
}}
/>
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance UploadDropzone with better user feedback and error handling.

The UploadDropzone is correctly implemented, but consider the following improvements:

  1. Add error handling with the onUploadError prop.
  2. Replace alert with a more user-friendly notification system.
  3. Consider adding a loading state while the upload is in progress.

Here's a suggested improvement:

<UploadDropzone
  endpoint="videoAndImage"
  onUploadAborted={() => {
    // Replace with a more user-friendly notification
    // notifyUser("Upload Aborted");
  }}
  onClientUploadComplete={(res) => {
    console.log(`onClientUploadComplete`, res);
    // Replace with a more user-friendly notification
    // notifyUser("Upload Completed");
  }}
  onUploadBegin={() => {
    console.log("upload begin");
    // Consider updating UI to show upload has started
  }}
  onUploadError={(error) => {
    console.error("Upload failed:", error);
    // notifyUser("Upload failed. Please try again.");
  }}
/>

Comment on lines +65 to +76
<input
type="file"
multiple
onChange={async (e) => {
const files = Array.from(e.target.files ?? []);

// Do something with files

// Then start the upload
await startUpload(files);
}}
/>
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance file input with error handling and consider pre-upload processing.

The file input is correctly implemented, but consider the following improvements:

  1. Add error handling for the startUpload function.
  2. Implement the suggested pre-upload processing.
  3. Provide user feedback during the upload process.

Here's a suggested improvement:

<input
  type="file"
  multiple
  onChange={async (e) => {
    const files = Array.from(e.target.files ?? []);

    // Implement pre-upload processing here
    // const processedFiles = await processFiles(files);

    try {
      // Update UI to show upload has started
      // setIsUploading(true);

      // Then start the upload
      const result = await startUpload(files);
      console.log("Upload completed:", result);
      // notifyUser("Upload Completed");
    } catch (error) {
      console.error("Upload failed:", error);
      // notifyUser("Upload failed. Please try again.");
    } finally {
      // Update UI to show upload has finished
      // setIsUploading(false);
    }
  }}
/>

@juraj98
Copy link
Contributor Author

juraj98 commented Sep 24, 2024

Closing this PR. The scope to make this work keeps growing. I'll create separate PRs for the doc changes, update for solidstart example, and finally the tanstack/start example.

@juraj98 juraj98 closed this Sep 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant