Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@steven-tey
Copy link
Collaborator

@steven-tey steven-tey commented Aug 22, 2025

Summary by CodeRabbit

  • New Features

    • Workspace Update API now accepts allowedHostnames and publishableKey, with validation and background cache sync for hostnames.
  • Documentation

    • OpenAPI spec updated to reflect the new request body schema and newly supported fields for workspace updates.
  • Refactor

    • Streamlined request validation across integration endpoints to use localized/centralized schemas without changing behavior.

@vercel
Copy link
Contributor

vercel bot commented Aug 22, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Updated (UTC)
dub Ready Ready Preview Aug 22, 2025 11:27pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 22, 2025

Walkthrough

Replaces module-level Zod schemas with inline schemas in Shopify and Stripe integration routes. Expands the Workspaces PATCH API to accept and validate allowedHostnames and publishableKey, updates persistence, and synchronizes hostname cache. OpenAPI spec now derives update body from createWorkspaceSchema.partial().

Changes

Cohort / File(s) Summary
Integration routes: inline body schemas
apps/web/app/(ee)/api/shopify/integration/callback/route.ts, apps/web/app/(ee)/api/stripe/integration/route.ts
Removed module-scoped updateWorkspaceSchema usage; replaced with inline z.object({ ... }).parse(...) for request body parsing. No control-flow changes.
Workspaces API: extended PATCH fields
apps/web/app/api/workspaces/[idOrSlug]/route.ts
Imported z and createWorkspaceSchema; defined local updateWorkspaceSchema extending create schema with allowedHostnames and publishableKey. Added validation, optional inclusion in update payload, and background cache sync for hostnames.
OpenAPI alignment
apps/web/lib/openapi/workspaces/update-workspace.ts
Switched to createWorkspaceSchema.partial() for requestBody schema; removed dependency on separate update schema. No response changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant R as Workspaces PATCH Route
  participant Z as Zod Schema
  participant V as validateAllowedHostnames
  participant DB as Database
  participant Cache as allowedHostnamesCache (bg)

  C->>R: PATCH /api/workspaces/:idOrSlug { body }
  R->>Z: parseAsync(body) using extended update schema
  Z-->>R: parsed { ...allowedHostnames?, publishableKey? }

  alt allowedHostnames provided
    R->>V: validate(allowedHostnames)
    V-->>R: validHostnames
  end

  R->>DB: Update workspace (fields incl. publishableKey?, validHostnames?)
  DB-->>R: Updated record

  note over R: Trigger background cache sync if hostnames changed
  R-->>Cache: sync(validHostnames) [async]

  R-->>C: 200 OK (updated workspace)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • TWilson023

Poem

I thump my paws at schemas neat,
New keys hop in—so light, so fleet! 🐇
Hostnames groomed, the cache aligned,
Publishable carrots—clearly signed.
With Zod as guard by burrow door,
We PATCH, we sync—then leap for more! ✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch simplify-schema

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
🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

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: 2

Caution

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

⚠️ Outside diff range comments (2)
apps/web/app/api/workspaces/[idOrSlug]/route.ts (2)

132-141: Guard defaultWorkspace updates when slug is undefined

If slug is omitted, slug !== workspace.slug evaluates true and attempts to set defaultWorkspace to undefined. Guard for a provided string.

-      if (slug !== workspace.slug) {
+      if (typeof slug === "string" && slug !== workspace.slug) {
         await prisma.user.updateMany({
           where: {
             defaultWorkspace: workspace.slug,
           },
           data: {
             defaultWorkspace: slug,
           },
         });
       }

172-180: flags are being added but parsed against WorkspaceSchema (likely stripped)

WorkspaceSchema probably doesn’t include flags/domains, so parse will drop flags. Use WorkspaceSchemaExtended to keep response parity with GET.

-      return NextResponse.json(
-        WorkspaceSchema.parse({
+      return NextResponse.json(
+        WorkspaceSchemaExtended.parse({
           ...response,
           id: prefixWorkspaceId(response.id),
           flags: await getFeatureFlags({
             workspaceId: response.id,
           }),
         }),
       );
🧹 Nitpick comments (3)
apps/web/app/(ee)/api/shopify/integration/callback/route.ts (1)

15-19: Inline Zod schema usage looks good; consider using the shared z instance

Validation change is fine. For consistency (and to keep any OpenAPI/brand/type extensions applied in "@/lib/zod"), consider importing z from "@/lib/zod" instead of zod directly (Line 9).

Example import outside the changed hunk:

import z from "@/lib/zod";
apps/web/app/api/workspaces/[idOrSlug]/route.ts (2)

21-34: Nit: simplify nullable union for publishableKey

Equivalent and shorter using nullable().

-  publishableKey: z
-    .union([
-      z
-        .string()
-        .regex(
-          /^dub_pk_[A-Za-z0-9_-]{16,64}$/,
-          "Invalid publishable key format",
-        ),
-      z.null(),
-    ])
-    .optional(),
+  publishableKey: z
+    .string()
+    .regex(/^dub_pk_[A-Za-z0-9_-]{16,64}$/, "Invalid publishable key format")
+    .nullable()
+    .optional(),

97-103: Avoid orphaned uploads on DB failure

The file is uploaded before the DB update; if update throws, the new blob isn’t cleaned up. Consider: upload after a successful update, or capture the new key and delete it in the catch path; alternatively, perform a two-phase update or transactional outbox.

Also applies to: 143-147

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 7e68146 and ee0e703.

📒 Files selected for processing (4)
  • apps/web/app/(ee)/api/shopify/integration/callback/route.ts (1 hunks)
  • apps/web/app/(ee)/api/stripe/integration/route.ts (1 hunks)
  • apps/web/app/api/workspaces/[idOrSlug]/route.ts (2 hunks)
  • apps/web/lib/openapi/workspaces/update-workspace.ts (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
apps/web/lib/openapi/workspaces/update-workspace.ts (1)
apps/web/lib/zod/schemas/workspaces.ts (1)
  • createWorkspaceSchema (130-146)
apps/web/app/api/workspaces/[idOrSlug]/route.ts (1)
apps/web/lib/zod/schemas/workspaces.ts (2)
  • updateWorkspaceSchema (148-161)
  • createWorkspaceSchema (130-146)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build
🔇 Additional comments (1)
apps/web/app/(ee)/api/stripe/integration/route.ts (1)

21-25: Inline Zod schema usage looks good

Localizing validation with an inline schema improves readability and removes unnecessary module coupling. No functional concerns here.

Comment on lines +21 to +34
const updateWorkspaceSchema = createWorkspaceSchema.extend({
allowedHostnames: z.array(z.string()).optional(),
publishableKey: z
.union([
z
.string()
.regex(
/^dub_pk_[A-Za-z0-9_-]{16,64}$/,
"Invalid publishable key format",
),
z.null(),
])
.optional(),
});
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

PATCH schema accidentally requires create-time fields (missing partial())

Using createWorkspaceSchema.extend(...) makes name/slug required for PATCH. This will break partial updates.

Apply this diff:

-const updateWorkspaceSchema = createWorkspaceSchema.extend({
+const updateWorkspaceSchema = createWorkspaceSchema.partial().extend({
   allowedHostnames: z.array(z.string()).optional(),
-  publishableKey: z
-    .union([
-      z
-        .string()
-        .regex(
-          /^dub_pk_[A-Za-z0-9_-]{16,64}$/,
-          "Invalid publishable key format",
-        ),
-      z.null(),
-    ])
-    .optional(),
+  publishableKey: z
+    .union([
+      z
+        .string()
+        .regex(
+          /^dub_pk_[A-Za-z0-9_-]{16,64}$/,
+          "Invalid publishable key format",
+        ),
+      z.null(),
+    ])
+    .optional(),
 });
📝 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
const updateWorkspaceSchema = createWorkspaceSchema.extend({
allowedHostnames: z.array(z.string()).optional(),
publishableKey: z
.union([
z
.string()
.regex(
/^dub_pk_[A-Za-z0-9_-]{16,64}$/,
"Invalid publishable key format",
),
z.null(),
])
.optional(),
});
const updateWorkspaceSchema = createWorkspaceSchema.partial().extend({
allowedHostnames: z.array(z.string()).optional(),
publishableKey: z
.union([
z
.string()
.regex(
/^dub_pk_[A-Za-z0-9_-]{16,64}$/,
"Invalid publishable key format",
),
z.null(),
])
.optional(),
});
🤖 Prompt for AI Agents
In apps/web/app/api/workspaces/[idOrSlug]/route.ts around lines 21 to 34, the
PATCH schema currently extends createWorkspaceSchema which keeps create-only
fields like name/slug required; change to use createWorkspaceSchema.partial()
before extending so all base fields become optional (e.g.,
createWorkspaceSchema.partial().extend({...})), keeping your existing
allowedHostnames and publishableKey definitions unchanged so PATCH accepts
partial updates.

content: {
"application/json": {
schema: updateWorkspaceSchema,
schema: createWorkspaceSchema.partial(),
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

OpenAPI request schema is now missing fields supported by the route (allowedHostnames, publishableKey)

The PATCH route accepts allowedHostnames and publishableKey, but the spec now exposes only createWorkspaceSchema.partial(). Clients generated from this spec won’t be able to send these fields.

Apply this diff to align the OpenAPI schema with the route:

-        schema: createWorkspaceSchema.partial(),
+        schema: createWorkspaceSchema
+          .partial()
+          .extend({
+            allowedHostnames: z.array(z.string()).optional(),
+            publishableKey: z
+              .union([
+                z
+                  .string()
+                  .regex(
+                    /^dub_pk_[A-Za-z0-9_-]{16,64}$/,
+                    "Invalid publishable key format",
+                  ),
+                z.null(),
+              ])
+              .optional(),
+          }),

Run this script to confirm the spec and route are in sync (prints occurrences for both files):


🏁 Script executed:

#!/bin/bash
set -euo pipefail
echo "Route fields:"
rg -n -C2 'allowedHostnames|publishableKey' apps/web/app/api/workspaces/\[idOrSlug\]/route.ts
echo
echo "OpenAPI fields:"
rg -n -C2 'allowedHostnames|publishableKey' apps/web/lib/openapi/workspaces/update-workspace.ts || echo "No matches in OpenAPI (mismatch)"

Length of output: 2154


Missing allowedHostnames & publishableKey in OpenAPI schema

The OpenAPI definition in apps/web/lib/openapi/workspaces/update-workspace.ts still uses only createWorkspaceSchema.partial(), but the PATCH route (in apps/web/app/api/workspaces/[idOrSlug]/route.ts) accepts both allowedHostnames and publishableKey (as confirmed by your ripgrep output). Clients generated from this spec won’t be able to send those fields.

• File: apps/web/lib/openapi/workspaces/update-workspace.ts at the schema: definition (around line 25)

Apply this change to include the missing fields:

-        schema: createWorkspaceSchema.partial(),
+        schema: createWorkspaceSchema
+          .partial()
+          .extend({
+            allowedHostnames: z.array(z.string()).optional(),
+            publishableKey: z
+              .union([
+                z
+                  .string()
+                  .regex(
+                    /^dub_pk_[A-Za-z0-9_-]{16,64}$/,
+                    "Invalid publishable key format",
+                  ),
+                z.null(),
+              ])
+              .optional(),
+          }),
📝 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
schema: createWorkspaceSchema.partial(),
schema: createWorkspaceSchema
.partial()
.extend({
allowedHostnames: z.array(z.string()).optional(),
publishableKey: z
.union([
z
.string()
.regex(
/^dub_pk_[A-Za-z0-9_-]{16,64}$/,
"Invalid publishable key format",
),
z.null(),
])
.optional(),
}),
🤖 Prompt for AI Agents
In apps/web/lib/openapi/workspaces/update-workspace.ts around line 25, the
OpenAPI schema currently uses createWorkspaceSchema.partial() but omits the
allowedHostnames and publishableKey fields accepted by the PATCH route; update
the schema to include those two fields (as optional) so generated clients can
send them — e.g., extend the partial createWorkspaceSchema with optional
allowedHostnames (array/string type matching your app route) and optional
publishableKey (string), ensuring the Zod/validator types and examples match the
route's expectations and that the overall schema remains a partial
(PATCH-friendly).

@steven-tey steven-tey merged commit e416a41 into main Aug 22, 2025
9 of 10 checks passed
@steven-tey steven-tey deleted the simplify-schema branch August 22, 2025 23:29
@coderabbitai coderabbitai bot mentioned this pull request Dec 15, 2025
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.

2 participants