Skip to content
Merged
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
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@
"ssh2": "^1.17.0"
},
"devDependencies": {
"@toon-format/toon": "^2.3.0",
"@types/js-yaml": "^4.0.9",
"@types/jsdom": "^28.0.3",
"@types/json-schema": "^7.0.15",
Expand All @@ -312,12 +313,16 @@
"zod": "^4.3.6"
},
"peerDependencies": {
"@toon-format/toon": "^2.0.0",
"fastest-validator": "^1.17.0",
"joi": "^17.0.0",
"yup": "^1.0.0",
"zod": "^3.0.0 || ^4.0.0"
},
"peerDependenciesMeta": {
"@toon-format/toon": {
"optional": true
},
"fastest-validator": {
"optional": true
},
Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src/http/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ export const MimeTypes = {
// Application
JSON: 'application/json',
XML: 'application/xml',
TOON: 'application/toon',
JAVASCRIPT: 'application/javascript',
FORM: 'application/x-www-form-urlencoded',
OCTET_STREAM: 'application/octet-stream',
Expand Down
4 changes: 3 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -437,11 +437,13 @@ export {
jsonCodec,
csvCodec,
textCodec,
xmlCodec,
createToonCodec,
selectCodecForAccept,
selectCodecForContentType,
resolveCodecs,
} from './utils/content-codecs.js'
export type { Codec } from './utils/content-codecs.js'
export type { Codec, ToonEncoder, ToonCodecOptions } from './utils/content-codecs.js'

// ID Generation (sid - replacement for nanoid)
export {
Expand Down
213 changes: 212 additions & 1 deletion src/utils/content-codecs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,218 @@ export const textCodec: Codec = {
decode: (body: string) => body,
}

export const defaultCodecs: Codec[] = [jsonCodec, textCodec, csvCodec]
// ─────────────────────────────────────────────────────────────────────────────
// XML Codec
// ─────────────────────────────────────────────────────────────────────────────

function isPlainObject(value: unknown): value is Record<string, unknown> {
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
const proto = Object.getPrototypeOf(value)
return proto === Object.prototype || proto === null
}

function escapeXmlText(value: string): string {
return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
}

function unescapeXmlText(value: string): string {
return value.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&').trim()
}

function xmlLeafToString(value: unknown): string {
if (typeof value === 'string') return value
if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
return String(value)
}
return JSON.stringify(value)
}

/**
* Serializes a JS value into an XML element.
*
* Arrays are expanded as repeated `<item>` children so decode can tell a
* single-key object apart from a single-element array. This is lossy for
* empty arrays (indistinguishable from null/undefined) and for objects that
* happen to have a property literally named "item".
*/
function encodeXmlElement(tag: string, value: unknown): string {
if (value === null || value === undefined) {
return `<${tag}/>`
}

if (Array.isArray(value)) {
if (value.length === 0) return `<${tag}/>`
const items = value.map((item) => encodeXmlElement('item', item)).join('')
return `<${tag}>${items}</${tag}>`
}

if (isPlainObject(value)) {
const keys = Object.keys(value)
if (keys.length === 0) return `<${tag}/>`
const inner = keys.map((key) => encodeXmlElement(key, value[key])).join('')
return `<${tag}>${inner}</${tag}>`
}

const text = xmlLeafToString(value)
if (text === '') return `<${tag}/>`
return `<${tag}>${escapeXmlText(text)}</${tag}>`
}

function stringifyXml(value: unknown): string {
return encodeXmlElement('root', value)
}

interface XmlNode {
tag: string
children: XmlNode[]
text: string
}

function parseXmlElement(input: string, start: number): { node: XmlNode; pos: number } {
let pos = start + 1 // consume '<'
const tagStart = pos
while (pos < input.length && !/[\s/>]/.test(input[pos]!)) pos += 1
const tag = input.slice(tagStart, pos)

while (pos < input.length && input[pos] !== '>' && !(input[pos] === '/' && input[pos + 1] === '>')) {
pos += 1
}

if (input[pos] === '/' && input[pos + 1] === '>') {
return { node: { tag, children: [], text: '' }, pos: pos + 2 }
}

pos += 1 // consume '>'
const node: XmlNode = { tag, children: [], text: '' }
let textBuffer = ''

while (pos < input.length) {
if (input.startsWith('</', pos)) {
const end = input.indexOf('>', pos)
pos = end === -1 ? input.length : end + 1
break
}
if (input[pos] === '<') {
if (input.startsWith('<!--', pos)) {
const end = input.indexOf('-->', pos)
pos = end === -1 ? input.length : end + 3
continue
}
const parsed = parseXmlElement(input, pos)
node.children.push(parsed.node)
pos = parsed.pos
continue
}
textBuffer += input[pos]
pos += 1
}

node.text = unescapeXmlText(textBuffer)
return { node, pos }
}

function xmlNodeToValue(node: XmlNode): unknown {
if (node.children.length === 0) {
return node.text === '' ? null : node.text
}

if (node.children.length > 1) {
const tags = new Set(node.children.map((child) => child.tag))
if (tags.size === 1) {
return node.children.map(xmlNodeToValue)
}
} else if (node.children[0]!.tag === 'item') {
return [xmlNodeToValue(node.children[0]!)]
}

const obj: Record<string, unknown> = {}
for (const child of node.children) {
const value = xmlNodeToValue(child)
if (Object.prototype.hasOwnProperty.call(obj, child.tag)) {
const existing = obj[child.tag]
obj[child.tag] = Array.isArray(existing) ? [...existing, value] : [existing, value]
} else {
obj[child.tag] = value
}
}
return obj
}

function parseXml(body: string): unknown {
let pos = 0
const skipWhitespace = () => {
while (pos < body.length && /\s/.test(body[pos]!)) pos += 1
}

skipWhitespace()
while (body.startsWith('<?', pos) || body.startsWith('<!', pos)) {
const end = body.indexOf('>', pos)
pos = end === -1 ? body.length : end + 1
skipWhitespace()
}

if (body[pos] !== '<') {
throw new SyntaxError('Invalid XML: expected an element')
}

const { node } = parseXmlElement(body, pos)
return xmlNodeToValue(node)
}

export const xmlCodec: Codec = {
name: 'xml',
contentTypes: ['application/xml', 'text/xml'],
encode: (value: unknown) => stringifyXml(value),
decode: (body: string) => parseXml(body),
}

// ─────────────────────────────────────────────────────────────────────────────
// TOON Codec (opt-in adapter for @toon-format/toon)
// ─────────────────────────────────────────────────────────────────────────────

/**
* Minimal shape of the `@toon-format/toon` package's `encode`/`decode`
* exports. Raffel never imports `@toon-format/toon` itself — the caller
* installs it and passes it in, same pattern as the zod/yup/joi validation
* adapters.
*/
export interface ToonEncoder {
encode: (value: unknown, options?: Record<string, unknown>) => string
decode: (input: string, options?: Record<string, unknown>) => unknown
}

export interface ToonCodecOptions {
/** Content types this codec should match on the Accept/Content-Type headers. */
contentTypes?: string[]
/** Options forwarded to `toon.encode()`. */
encodeOptions?: Record<string, unknown>
/** Options forwarded to `toon.decode()`. */
decodeOptions?: Record<string, unknown>
}

/**
* Creates a TOON (Token-Oriented Object Notation) codec for use with
* `resolveCodecs()`. Requires the optional peer dependency `@toon-format/toon`.
*
* @example
* ```ts
* import { encode, decode } from '@toon-format/toon'
* import { createToonCodec, resolveCodecs } from 'raffel'
*
* const codecs = resolveCodecs([createToonCodec({ encode, decode })])
* ```
*/
export function createToonCodec(toon: ToonEncoder, options: ToonCodecOptions = {}): Codec {
const contentTypes = options.contentTypes ?? ['application/toon', 'text/toon']
return {
name: 'toon',
contentTypes,
encode: (value: unknown) => toon.encode(value, options.encodeOptions),
decode: (body: string) => toon.decode(body, options.decodeOptions),
}
}

export const defaultCodecs: Codec[] = [jsonCodec, textCodec, csvCodec, xmlCodec]

export function resolveCodecs(codecs?: Codec[], fallback: Codec[] = defaultCodecs): Codec[] {
if (!codecs || codecs.length === 0) return fallback
Expand Down
4 changes: 2 additions & 2 deletions test/adapters/http.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ describe('HttpAdapter', () => {
const { status, body } = await request('/greet', {
method: 'POST',
body: { ok: true },
headers: { Accept: 'application/xml' },
headers: { Accept: 'application/pdf' },
})

expect(status).toBe(406)
Expand All @@ -200,7 +200,7 @@ describe('HttpAdapter', () => {
const { status, body } = await request('/greet', {
method: 'POST',
body: { ok: true },
headers: { 'Content-Type': 'application/xml' },
headers: { 'Content-Type': 'application/pdf' },
})

expect(status).toBe(415)
Expand Down
2 changes: 1 addition & 1 deletion test/adapters/jsonrpc.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,7 @@ describe('JSON-RPC 2.0 Adapter', () => {
try {
const response = await fetch(`http://localhost:${port}/`, {
method: 'POST',
headers: { 'Content-Type': 'application/xml' },
headers: { 'Content-Type': 'application/pdf' },
body: '{"jsonrpc":"2.0","method":"test","id":1}',
})

Expand Down
Loading
Loading