Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 101 additions & 0 deletions .claude/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# SDK Maintenance Instructions

## Your Role
You are an expert at Kotlin and Java and maintain the Nylas Kotlin/Java SDK which is an interface for Nylas' APIs.

Your job is to maintain parity with the API to ensure that the SDK supports all that the API supports.

## Task Workflow

When asked to add support for a new feature, query parameter, or API endpoint, follow this workflow:

### 1. Understand the Codebase
- Scan the project structure
- Understand the architecture and how it's organized
- Identify existing patterns and conventions
- Review similar existing implementations

### 2. Write Tests First (TDD)
- Implement tests for the new feature BEFORE writing implementation code
- Ensure backward compatibility is maintained
- **Never modify existing tests unless absolutely necessary**
- **IF BACKWARDS COMPATIBILITY CANNOT BE ACHIEVED, STOP AND INFORM THE USER**

### 3. Implement the Solution
- Follow existing code patterns and conventions
- Maintain consistency with the rest of the codebase
- Keep changes minimal and focused
- Only modify production code in `src/main/`
- Only modify test code in `src/test/`

### 4. Update the CHANGELOG
- Update `CHANGELOG.md` following conventional commits format
- Always add changes under an "Unreleased" version section
- Keep updates concise - one line per change
- Never include code examples in the changelog
- Format: `* Brief description of the change`

### 5. Create Examples (if applicable)
- If the feature is user-facing, create an example in `examples/`
- Follow the pattern of existing examples
- Provide both Java and Kotlin examples when relevant

### 6. Run Linters and Fix Formatting
- Run: `./gradlew formatKotlin`
- Run: `./gradlew lintKotlin`
- Fix any formatting or linting errors

### 7. Verify Tests Pass
- Run: `./gradlew test`
- Ensure all tests pass before proceeding

### 8. Git Commit
- Follow conventional commits format
- Format: `type(scope): description`
- Types: `feat`, `fix`, `docs`, `test`, `refactor`, `chore`
- Examples:
- `feat(folders): add include_hidden_folders query parameter`
- `fix(messages): correct attachment encoding for files < 3MB`
- `test(calendars): add coverage for event recurrence`

## Important Notes

- **Production Code Safety**: The SDK is live in production. Never break existing functionality.
- **Test Coverage**: Aim to maintain or improve test coverage. Current target is 99% by Q3.
- **Backward Compatibility**: This is critical. If you can't maintain it, stop and inform the user.
- **Java Version**: Project uses Java 11 (toolchain set to Java 8 for compatibility)
- **JAVA_HOME**: `/Users/gordan.o@nylas.com/Library/Java/JavaVirtualMachines/temurin-11.0.29/Contents/Home`

## Code Patterns

### Query Parameters
Query parameters are defined in `src/main/kotlin/com/nylas/models/*QueryParams.kt` files using:
- Data classes with nullable properties
- Builder pattern for construction
- `@Json(name = "...")` annotations for JSON serialization

### Resource Methods
Resource classes in `src/main/kotlin/com/nylas/resources/*.kt` follow this pattern:
- Inherit from `Resource(client)`
- Use HTTP methods: `list()`, `find()`, `create()`, `update()`, `destroy()`
- Accept query params as optional parameters
- Return typed responses: `Response<T>`, `ListResponse<T>`, `DeleteResponse`

### Tests
Test files in `src/test/kotlin/com/nylas/resources/*Tests.kt` use:
- Mockito for HTTP mocking
- JUnit 5 for test framework
- Nested test classes for organization
- Pattern: mock HTTP client → execute method → verify request → assert response

## Quality Checklist

Before considering a task complete:
- [ ] Tests written and passing
- [ ] Implementation follows existing patterns
- [ ] CHANGELOG.md updated
- [ ] Examples created (if applicable)
- [ ] Linters pass
- [ ] All tests pass
- [ ] Backward compatibility maintained
- [ ] Git commit created with conventional commit message
16 changes: 16 additions & 0 deletions .claude/settings.local.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"permissions": {
"allow": [
"Bash(export JAVA_HOME=/Users/gordan.o@nylas.com/Library/Java/JavaVirtualMachines/corretto-11.0.29/Contents/Home:*)",
"Bash(./gradlew test:*)",
"Bash(export JAVA_HOME:*)",
"Bash(./gradlew jacocoTestReport:*)",
"Bash(open build/reports/jacoco/test/html/index.html)",
"Bash(cat:*)",
"Bash(find:*)",
"Bash(./gradlew clean build:*)",
"Bash(java -version:*)",
"Bash(/usr/libexec/java_home:*)"
]
}
}
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# Nylas Java SDK Changelog

## [Unreleased]

### Added
* Client-side validation for `CreateEventRequest.When.Timespan` and `UpdateEventRequest.When.Timespan` to ensure `endTime` is after `startTime`, preventing confusing API errors
* `validationErrors` field to `NylasApiError` to capture field-level validation errors from the API
* Enhanced error messages in `NylasApiError.toString()` to display validation errors, provider errors, and request IDs for easier debugging

### Fixed
* Improved error handling in `NylasClient` to provide more descriptive error messages when API responses cannot be parsed, including response body preview and status codes

## [2.14.0]

### Added
Expand Down
1 change: 0 additions & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ repositories {

java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
withJavadocJar()
withSourcesJar()
}
Expand Down
16 changes: 14 additions & 2 deletions src/main/kotlin/com/nylas/NylasClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -433,9 +433,15 @@ open class NylasClient(
} catch (ex: Exception) {
when (ex) {
is IOException, is JsonDataException -> {
// Attempt to extract useful error information even from malformed responses
val errorMessage = if (responseBody.isNotBlank()) {
"API request failed with status ${response.code}. Response body: ${responseBody.take(500)}"
} else {
"API request failed with status ${response.code} and empty response body"
}
throw NylasApiError(
type = "unknown",
message = "Unknown error received from the API: $responseBody",
message = errorMessage,
statusCode = response.code,
headers = response.headers.toMultimap(),
)
Expand All @@ -451,9 +457,15 @@ open class NylasClient(
throw parsedError
}

// Final fallback if parsing succeeded but returned null
val errorMessage = if (responseBody.isNotBlank()) {
"API request failed with status ${response.code}. Response body: ${responseBody.take(500)}"
} else {
"API request failed with status ${response.code} and empty response body"
}
throw NylasApiError(
type = "unknown",
message = "Unknown error received from the API: $responseBody",
message = errorMessage,
statusCode = response.code,
headers = response.headers.toMultimap(),
)
Expand Down
11 changes: 10 additions & 1 deletion src/main/kotlin/com/nylas/models/CreateEventRequest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -235,8 +235,17 @@ data class CreateEventRequest(
/**
* Builds the [Timespan] object.
* @return [Timespan] object.
* @throws IllegalArgumentException if endTime is not after startTime.
*/
fun build() = Timespan(startTime, endTime, startTimezone, endTimezone)
fun build(): Timespan {
// Validate that endTime must be after startTime
require(endTime > startTime) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Hmm, this is a breaking change. If we introduce this, then customers had to now handle the new exception thrown. I'd avoid it unless you plan on doing a major release, or make it backwards compatible

Copy link
Author

Choose a reason for hiding this comment

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

but that is the whole problem of the ticket, the customer was sending the identical start and end date instead of using the when-time event

"Invalid Timespan: endTime ($endTime) must be after startTime ($startTime). " +
"Timespan events require a positive duration. " +
"For point-in-time events, use CreateEventRequest.When.Time instead."
}
return Timespan(startTime, endTime, startTimezone, endTimezone)
}
}
}
}
Expand Down
46 changes: 45 additions & 1 deletion src/main/kotlin/com/nylas/models/NylasApiError.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ data class NylasApiError(
*/
@Json(name = "provider_error")
val providerError: Map<String, Any?>? = null,
/**
* Field-level validation errors from the API.
* Maps field names to their specific error messages.
*/
@Json(name = "validation_errors")
val validationErrors: Map<String, String>? = null,
/**
* The HTTP status code of the error response
*/
Expand All @@ -33,4 +39,42 @@ data class NylasApiError(
* The HTTP headers of the error response
*/
override var headers: Map<String, List<String>>? = null,
) : AbstractNylasApiError(message, statusCode, requestId, headers)
) : AbstractNylasApiError(message, statusCode, requestId, headers) {

/**
* Formats the error as a human-readable string.
*
* Example output:
* ```
* NylasApiError: Bad Request (HTTP 400)
* Validation errors:
* - when.end_time: must be after start_time
* Request ID: abc-123
* ```
*/
override fun toString(): String {
Copy link
Collaborator

Choose a reason for hiding this comment

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

What is the current value prior to this override?

Copy link
Author

Choose a reason for hiding this comment

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

Claude says previously with no customized "toString":

NylasApiError(message=Bad Request, statusCode=400, requestId=abc-123, ...)

and now:

NylasApiError: Bad Request (HTTP 400)
Validation errors:
  - when.end_time: must be after start_time
Request ID: abc-123

for me it is a better experience, but I'm new to this SDK - so.... :)

val sb = StringBuilder()
sb.append("NylasApiError: $message")

if (statusCode != null) {
sb.append(" (HTTP $statusCode)")
}

if (!validationErrors.isNullOrEmpty()) {
sb.append("\nValidation errors:")
validationErrors.forEach { (field, error) ->
sb.append("\n - $field: $error")
}
}

if (providerError != null) {
sb.append("\nProvider error: $providerError")
}

if (requestId != null) {
sb.append("\nRequest ID: $requestId")
}

return sb.toString()
}
}
16 changes: 15 additions & 1 deletion src/main/kotlin/com/nylas/models/UpdateEventRequest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -277,8 +277,22 @@ data class UpdateEventRequest(
/**
* Builds the [Timespan] object.
* @return [Timespan] object.
* @throws IllegalArgumentException if both startTime and endTime are provided and endTime is not after startTime.
*/
fun build() = Timespan(startTime, endTime, startTimezone, endTimezone)
fun build(): Timespan {
// Validate that if both times are set, endTime must be after startTime
// Local variables for smart-cast null safety
val start = startTime
val end = endTime
if (start != null && end != null) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Same about this being a breaking change

Copy link
Author

Choose a reason for hiding this comment

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

same answer as for create

require(end > start) {
"Invalid Timespan: endTime ($end) must be after startTime ($start). " +
"Timespan events require a positive duration. " +
"For point-in-time events, use UpdateEventRequest.When.Time instead."
}
}
return Timespan(startTime, endTime, startTimezone, endTimezone)
}
}
}
}
Expand Down
Loading
Loading