Skip to content
Source
Sign inSign up
samwillis/neon-durable-streams
Open History to see the last commit

path.ts

30 lines1.4 KB

1import { StreamError } from './errors.js'
2​
3export function validateSchema(schema: string): string {
4 if (!/^[a-z_][a-z0-9_]{0,62}$/.test(schema) || schema.startsWith('pg_') || ['public', 'information_schema'].includes(schema)) {
5 throw new TypeError('Use a dedicated schema with a lower-case ASCII identifier of at most 63 bytes')
6 }
7 return `"${schema}"`
8}
9​
10export function normalizeBasePath(basePath: string): string {
11 if (!/^\/(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+$/.test(basePath)) throw new TypeError('Invalid basePath')
12 return basePath
14​
15/** Reject ambiguous encodings instead of aliasing two stream URLs. */
16export function streamPath(url: URL, basePath: string): string | null {
17 if (!url.pathname.startsWith(`${basePath}/`)) return null
18 const raw = url.pathname.slice(basePath.length + 1)
19 const parts = raw.split('/')
20 const decoded = parts.map((part) => {
21 let value: string
22 try { value = decodeURIComponent(part) } catch { throw new StreamError(400, 'INVALID_PATH', 'Invalid stream path') }
23 if (!value || value === '.' || value === '..' || /[/\\\u0000-\u001f\u007f]/.test(value) || /%[0-9a-f]{2}/i.test(value)) {
24 throw new StreamError(400, 'INVALID_PATH', 'Ambiguous stream path')
25 }
26 return value
27 }).join('/')
28 if (Buffer.byteLength(decoded) > 2048) throw new StreamError(414, 'PATH_TOO_LONG', 'Stream path is too long')
29 return decoded