-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
190 lines (177 loc) · 6.68 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
// export * as apis from './apis'
export const apis = {
'apis.do': {
icon: '🚀',
type: 'core',
description: 'Hypermedia-driven API Directory',
endpoints: {
'List Categories': '/api',
'Get Category': '/:type',
'Search APIs': '/search/:term',
},
examples: {
'Get Utilities': '/utilities',
'Search for Data': '/search/data',
},
},
'esbuild.do': {
icon: '⚡️',
type: 'code',
description: 'ESBuild as a Service',
endpoints: {
'Build from URL': '/:url',
'Build from POST': 'POST /builds',
'List Previous Builds': '/builds',
},
examples: {
'Build Package': 'https://esbuild.do/pkg.do/lodash',
'Build Generated Worker': 'https://esbuild.do/worker.do/cube/x=5/x^3',
'Build Gist': 'https://gist.githubusercontent.com/nathanclevenger/05c566c2452de53caa20a32cd12fbbca/raw/0c8ef49c00d3614b04c1228f279c556c96ef14b8/index.js',
}
},
'gist.do': {
icon: '🛠',
type: 'code',
description: 'Abstract Syntax Tree Parser',
endpoints: {
deployWorker: '/:gist',
invokeWorker: 'https://gist.gist.do',
},
examples: {
publish: 'https://gist.do/28a6b4bfde485b704a2fcc9b6c874e79',
invokeWorker: 'https://28a6b4bfde485b704a2fcc9b6c874e79.gist.do',
publishAPI: 'https://gist.do/api/nathanclevenger/28a6b4bfde485b704a2fcc9b6c874e79',
publishWorker: 'https://gist.do/worker/nathanclevenger/28a6b4bfde485b704a2fcc9b6c874e79',
}
},
'pkg.do': {
icon: '📦',
type: 'code',
description: 'Simple Package Bundle CDN',
endpoints: {
getPackage: '/:package',
},
examples: {
getAPIs: '/apis.do',
getLodash: '/lodash-es',
getVersion: '/[email protected]',
},
},
'syntax.do': {
icon: '⚡️',
type: 'code',
description: 'Abstract Syntax Tree Parser',
endpoints: {
parseScript: '/:code',
parseModule: '/:url',
},
examples: {
parseScript: 'https://syntax.do/x=x+3',
parseGist: 'https://syntax.do/gist.githubusercontent.com/nathanclevenger/05c566c2452de53caa20a32cd12fbbca/raw/203017cdae58f14d72a242627a1e10e986444a2f/index.js',
},
},
'worker.do': {
icon: '👌',
type: 'code',
description: 'Generate Worker from any JavaScriptFunction',
endpoints: {
buildCode: '/:name/:args/:code',
buildFile: '/:name/:args/:url',
},
examples: {
workerFromScript: 'https://worker.do/cube/number=5/5^3',
workerFromGist: 'https://worker.do/math/number=5/gist.githubusercontent.com/nathanclevenger/05c566c2452de53caa20a32cd12fbbca/raw/203017cdae58f14d72a242627a1e10e986444a2f/index.js',
},
},
}
export const getAPI = (req, opts) => {
const { origin, hostname, pathname } = new URL(req.url)
const domain = opts?.api ?? hostname.split('.').slice(-2).join('.')
const knownAPI = apis[domain]
const endpoints = Object.fromEntries(Object.entries(knownAPI?.endpoints)
.map(([name, endpoint]) => ([name, endpoint.startsWith('https://') ? endpoint : origin + endpoint])))
const examples = Object.fromEntries(Object.entries(knownAPI?.endpoints)
.map(([name, endpoint]) => ([name, endpoint.startsWith('https://') ? endpoint : origin + endpoint])))
const gettingStarted = knownAPI?.gettingStarted ?? [
`If you don't already have a JSON Viewer Browser Extension, get that first:`,
`https://extensions.do`,
]
const api = {
icon: knownAPI?.icon ?? opts?.icon ?? '🚀',
name: opts?.name ?? domain,
description: knownAPI?.description ?? opts?.description ?? 'Hypermedia-driven API Directory',
url: origin + '/api',
type: 'https://apis.do/' + (knownAPI?.type ?? opts?.type ?? 'api'),
endpoints,
site: origin,
login: opts?.login ?? opts?.noLogin ? undefined : origin + '/login',
signup: opts?.signup ?? opts?.noSignup ? undefined : origin + '/signup',
subscribe: opts?.subscribe ?? opts?.noSubscribe ? undefined : origin + '/subscribe',
repo: opts?.repo ?? 'https://github.com/drivly/' + domain,
}
return { api, gettingStarted, examples }
}
export const fetchJSON = (...args) => fetch(...args).then(res => res.json()).catch(({name,message}) => ({ error: {name,message}}))
export const json = data => new Response(JSON.stringify(data, null, 2), { headers: { 'content-type': 'application/json; charset=utf-8' }})
export const err = ({name,message,stack}) => ({ error: {name,message,stack}})
export const api = func => ({
fetch: async (req, env) => {
let api = getAPI(req)
let result = await func(req).catch(err)
return {api, result}
}
})
export const categories = Object.entries(apis).reduce((acc, [name,item]) => {
acc[item.type] = acc[item.type] || []
acc[item.type].push({name,...item})
}, {})
// https://github.com/kwhitley/itty-router-extras
export const Router = (options = {}) => {
const { stack = false } = options
return new Proxy(BaseRouter(options), {
get: (obj, prop) => (...args) =>
prop === 'handle'
? obj[prop](...args).catch(err => error(
err.status || 500,
{
status: err.status || 500,
error: err.message,
stack: stack && err.stack || undefined
},
))
: obj[prop](...args)
})
}
// https://github.com/kwhitley/itty-router
function BaseRouter({ base = '', routes = [] } = {}) {
return {
__proto__: new Proxy({}, {
get: (target, prop, receiver) => (route, ...handlers) =>
routes.push([
prop.toUpperCase(),
RegExp(`^${(base + route)
.replace(/(\/?)\*/g, '($1.*)?') // trailing wildcard
.replace(/(\/$)|((?<=\/)\/)/, '') // remove trailing slash or double slash from joins
.replace(/:(\w+)(\?)?(\.)?/g, '$2(?<$1>[^/]+)$2$3') // named params
.replace(/\.(?=[\w(])/, '\\.') // dot in path
.replace(/\)\.\?\(([^\[]+)\[\^/g, '?)\\.?($1(?<=\\.)[^\\.') // optional image format
}/*$`),
handlers,
]) && receiver
}),
routes,
async handle (request, ...args) {
let response, match, url = new URL(request.url)
request.query = Object.fromEntries(url.searchParams)
for (let [method, route, handlers] of routes) {
if ((method === request.method || method === 'ALL') && (match = url.pathname.match(route))) {
request.params = match.groups
for (let handler of handlers) {
if ((response = await handler(request.proxy || request, ...args)) !== undefined) return response
}
}
}
}
}
}
// export default { apis, json, api, err, categories, Router, fetchJSON, getAPI }