chore: import upstream snapshot with attribution
Publish CLI Package / publish-npm (push) Waiting to run
Publish Python SDK / publish-pypi (push) Waiting to run
Publish TypeScript SDK / publish-npm (push) Waiting to run
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:20:55 +08:00
commit d25d482dc2
13754 changed files with 4996608 additions and 0 deletions
+107
View File
@@ -0,0 +1,107 @@
export interface ApiClientErrorOptions {
status: number
message: string
body: unknown
rawBody?: string
code?: string
}
export class ApiClientError extends Error {
readonly status: number
readonly body: unknown
readonly rawBody?: string
readonly code?: string
constructor(options: ApiClientErrorOptions) {
super(options.message)
this.name = 'ApiClientError'
this.status = options.status
this.body = options.body
this.rawBody = options.rawBody
this.code = options.code
}
}
export function isApiClientError(error: unknown): error is ApiClientError {
return error instanceof ApiClientError
}
export interface ValidationIssue {
/** Path of the failing field, e.g. ['updates', 'name']. */
path: ReadonlyArray<string | number>
/** Human-readable message — uses the schema's custom error string when set. */
message: string
}
interface UnknownIssue {
path?: unknown
message?: unknown
}
function normalizeIssue(raw: unknown): ValidationIssue | null {
if (!raw || typeof raw !== 'object') return null
const { path, message } = raw as UnknownIssue
if (typeof message !== 'string' || message.length === 0) return null
if (!Array.isArray(path)) return null
const cleanPath = path.filter(
(segment): segment is string | number =>
typeof segment === 'string' || typeof segment === 'number'
)
return { path: cleanPath, message }
}
/**
* Pull a list of validation issues out of an unknown error. Recognises both
* shapes the boundary produces:
*
* - Client-side contract validation: `requestJson` calls `schema.parse(input)`
* before fetch; failure throws a raw `ZodError` whose `.issues` is the array.
* - Server-side contract validation: route returns `{ error, details: [...] }`,
* which `requestJson` re-throws as `ApiClientError` carrying the body.
*
* Returns an empty array when the error isn't a recognised validation shape so
* callers can fall back to toast/log paths.
*/
export function extractValidationIssues(error: unknown): ValidationIssue[] {
if (!error || typeof error !== 'object') return []
if (isApiClientError(error)) {
const body = error.body
if (body && typeof body === 'object') {
const details = (body as { details?: unknown }).details
if (Array.isArray(details)) {
return details.map(normalizeIssue).filter((i): i is ValidationIssue => i !== null)
}
}
return []
}
const issues = (error as { issues?: unknown }).issues
if (Array.isArray(issues)) {
return issues.map(normalizeIssue).filter((i): i is ValidationIssue => i !== null)
}
return []
}
/**
* Match a single issue by suffix path. `pathSuffix` lets callers ignore the
* outer body wrapper — `findValidationIssue(err, ['name'])` matches both
* `path: ['name']` and `path: ['updates', 'name']`.
*/
export function findValidationIssue(
error: unknown,
pathSuffix: ReadonlyArray<string | number>
): ValidationIssue | null {
const issues = extractValidationIssues(error)
for (const issue of issues) {
if (issue.path.length < pathSuffix.length) continue
const tail = issue.path.slice(issue.path.length - pathSuffix.length)
if (tail.every((segment, i) => segment === pathSuffix[i])) return issue
}
return null
}
/** True when the error is a recognised validation failure (client or server). */
export function isValidationError(error: unknown): boolean {
return extractValidationIssues(error).length > 0
}
+2
View File
@@ -0,0 +1,2 @@
export * from './errors'
export * from './request'
+71
View File
@@ -0,0 +1,71 @@
/**
* @vitest-environment node
*/
import { afterEach, describe, expect, it, vi } from 'vitest'
import { z } from 'zod'
import { requestJson } from '@/lib/api/client/request'
import { listKnowledgeDocumentsContract } from '@/lib/api/contracts/knowledge'
import { defineRouteContract } from '@/lib/api/contracts/types'
/**
* Captures the URL of the last fetch call and returns a valid JSON response so
* `requestJson`'s response validation passes.
*/
function mockFetchReturning(body: unknown) {
const fetchMock = vi.fn(
async () =>
new Response(JSON.stringify(body), {
status: 200,
headers: { 'content-type': 'application/json' },
})
)
vi.stubGlobal('fetch', fetchMock)
return fetchMock
}
describe('requestJson query serialization', () => {
afterEach(() => {
vi.unstubAllGlobals()
})
it('serializes a JSON-string query param verbatim (regression: tagFilters)', async () => {
const fetchMock = mockFetchReturning({
success: true,
data: {
documents: [],
pagination: { total: 0, limit: 50, offset: 0, hasMore: false },
},
})
const tagFilters = JSON.stringify([
{ tagSlot: 'tag1', fieldType: 'text', operator: 'contains', value: 'Ada Lovelace' },
])
await requestJson(listKnowledgeDocumentsContract, {
params: { id: 'kb-1' },
query: { tagFilters },
})
const calledUrl = String(fetchMock.mock.calls[0][0])
const url = new URL(calledUrl, 'https://example.test')
// The param must round-trip as the exact JSON, never "[object Object]".
expect(url.searchParams.get('tagFilters')).toBe(tagFilters)
expect(calledUrl).not.toContain('object+Object')
expect(calledUrl).not.toContain('[object Object]')
})
it('throws instead of silently corrupting an array-of-objects query param', async () => {
mockFetchReturning({ ok: true })
const badContract = defineRouteContract({
method: 'GET',
path: '/api/test',
query: z.object({ items: z.array(z.object({ a: z.string() })) }),
response: { mode: 'json', schema: z.object({ ok: z.boolean() }) },
})
await expect(requestJson(badContract, { query: { items: [{ a: 'x' }] } })).rejects.toThrow(
/arrays of objects are not URL-safe/
)
})
})
+249
View File
@@ -0,0 +1,249 @@
import { ApiClientError } from '@/lib/api/client/errors'
import type {
AnyApiRouteContract,
ApiSchema,
ContractBodyInput,
ContractHeadersInput,
ContractJsonResponse,
ContractParamsInput,
ContractQueryInput,
EmptySchemaOutput,
} from '@/lib/api/contracts'
// Tuple-wrapped to suppress distributive conditionals: when `Value` is a
// union (e.g. a discriminated union body), naked `Value extends undefined`
// distributes and produces `{ body: A } | { body: B }` instead of
// `{ body: A | B }`. The `[Value] extends [undefined]` form preserves the
// union as-is. See request.test.ts for repro and rationale.
type MaybeField<Key extends string, Value> = [Value] extends [undefined]
? { [K in Key]?: never }
: { [K in Key]: Value }
export type ApiClientRequest<C extends AnyApiRouteContract> = MaybeField<
'params',
ContractParamsInput<C>
> &
MaybeField<'query', ContractQueryInput<C>> &
MaybeField<'body', ContractBodyInput<C>> &
MaybeField<'headers', ContractHeadersInput<C>> & {
signal?: AbortSignal
}
export interface ApiRawRequestOptions {
cache?: RequestCache
headers?: Record<string, string>
}
function replacePathParams(path: string, params: unknown): string {
if (!params || typeof params !== 'object') return path
const values = params as Record<string, unknown>
return path.replace(
/\[\[?(\.\.\.)?([^\][]+)\]\]?/g,
(match, rest: string | undefined, key: string) => {
const value = values[key]
const isOptionalCatchAll = match.startsWith('[[...')
if (rest && Array.isArray(value)) {
return value.map((item) => encodeURIComponent(String(item))).join('/')
}
if (value === undefined && isOptionalCatchAll) return ''
if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') {
throw new Error(`Missing route param "${key}"`)
}
return encodeURIComponent(String(value))
}
)
}
function appendQuery(path: string, query: unknown): string {
if (!query || typeof query !== 'object') return path
const searchParams = new URLSearchParams()
for (const [key, value] of Object.entries(query as Record<string, unknown>)) {
if (value === undefined || value === null || value === '') continue
if (Array.isArray(value)) {
for (const item of value) {
if (item === undefined || item === null || item === '') continue
// A non-scalar in a query array would stringify to "[object Object]" and
// silently corrupt the request. Encode such values as a single JSON
// string param and decode them server-side instead. Failing loudly here
// keeps the boundary honest (this is how the knowledge tagFilters bug
// shipped undetected).
if (typeof item === 'object') {
throw new Error(
`Cannot serialize query param "${key}": arrays of objects are not URL-safe — ` +
'encode the value as a JSON string param and decode it server-side.'
)
}
searchParams.append(key, String(item))
}
continue
}
if (typeof value === 'object') {
searchParams.set(key, JSON.stringify(value))
continue
}
searchParams.set(key, String(value))
}
const queryString = searchParams.toString()
if (!queryString) return path
return `${path}${path.includes('?') ? '&' : '?'}${queryString}`
}
function buildHeaders(headers: unknown, hasBody: boolean): Record<string, string> {
const output: Record<string, string> = {}
if (hasBody) {
output['Content-Type'] = 'application/json'
}
if (headers && typeof headers === 'object') {
for (const [key, value] of Object.entries(headers as Record<string, unknown>)) {
if (typeof value === 'string') output[key] = value
}
}
return output
}
function parseOptionalSchema<S extends ApiSchema | undefined>(
schema: S,
value: unknown
): EmptySchemaOutput<S> {
if (!schema) return undefined as EmptySchemaOutput<S>
return schema.parse(value) as EmptySchemaOutput<S>
}
async function readResponseBody(response: Response): Promise<{ parsed: unknown; raw?: string }> {
const text = await response.text()
if (!text) return { parsed: undefined }
try {
return { parsed: JSON.parse(text) as unknown, raw: text }
} catch {
return { parsed: text, raw: text }
}
}
function messageFromErrorBody(body: unknown, fallback: string): string {
if (body && typeof body === 'object') {
const record = body as Record<string, unknown>
const message = record.message ?? record.error
if (typeof message === 'string' && message.length > 0) return message
}
return fallback
}
function codeFromErrorBody(body: unknown): string | undefined {
if (body && typeof body === 'object') {
const record = body as Record<string, unknown>
if (typeof record.code === 'string' && record.code.length > 0) return record.code
}
return undefined
}
function isSchemaValidationError(error: unknown): boolean {
return Boolean(
error &&
typeof error === 'object' &&
'issues' in error &&
Array.isArray((error as { issues?: unknown }).issues)
)
}
export async function requestJson<C extends AnyApiRouteContract>(
contract: C,
input: ApiClientRequest<C>
): Promise<ContractJsonResponse<C>> {
if (contract.response.mode !== 'json') {
throw new Error(`Contract ${contract.method} ${contract.path} does not declare a JSON response`)
}
const parsedParams = parseOptionalSchema(contract.params, input.params)
const parsedQuery = parseOptionalSchema(contract.query, input.query)
const parsedBody = parseOptionalSchema(contract.body, input.body)
const parsedHeaders = parseOptionalSchema(contract.headers, input.headers)
const url = appendQuery(replacePathParams(contract.path, parsedParams), parsedQuery)
const hasBody = parsedBody !== undefined && contract.method !== 'GET'
const response = await fetch(url, {
method: contract.method,
headers: buildHeaders(parsedHeaders, hasBody),
body: hasBody ? JSON.stringify(parsedBody) : undefined,
signal: input.signal,
})
const { parsed, raw } = await readResponseBody(response)
if (!response.ok) {
throw new ApiClientError({
status: response.status,
message: messageFromErrorBody(parsed, `Request failed with ${response.status}`),
body: parsed,
rawBody: raw,
code: codeFromErrorBody(parsed),
})
}
try {
return contract.response.schema.parse(parsed) as ContractJsonResponse<C>
} catch (error) {
if (isSchemaValidationError(error)) {
throw new ApiClientError({
status: response.status,
message: 'Response failed contract validation',
body: parsed,
rawBody: raw,
})
}
throw error
}
}
export async function requestRaw<C extends AnyApiRouteContract>(
contract: C,
input: ApiClientRequest<C>,
options: ApiRawRequestOptions = {}
): Promise<Response> {
const parsedParams = parseOptionalSchema(contract.params, input.params)
const parsedQuery = parseOptionalSchema(contract.query, input.query)
const parsedBody = parseOptionalSchema(contract.body, input.body)
const parsedHeaders = parseOptionalSchema(contract.headers, input.headers)
const url = appendQuery(replacePathParams(contract.path, parsedParams), parsedQuery)
const hasBody = parsedBody !== undefined && contract.method !== 'GET'
const headers = {
...buildHeaders(parsedHeaders, hasBody),
...options.headers,
}
const response = await fetch(url, {
method: contract.method,
headers,
body: hasBody ? JSON.stringify(parsedBody) : undefined,
signal: input.signal,
cache: options.cache,
})
if (!response.ok) {
const { parsed, raw } = await readResponseBody(response)
throw new ApiClientError({
status: response.status,
message: messageFromErrorBody(parsed, `Request failed with ${response.status}`),
body: parsed,
rawBody: raw,
})
}
return response
}