yedra 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,18 @@
1
+ Copyright 2024 WeMakeFuture AG
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ this software and associated documentation files (the “Software”), to deal in
5
+ the Software without restriction, including without limitation the rights to
6
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7
+ the Software, and to permit persons to whom the Software is furnished to do so,
8
+ subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,326 @@
1
+ # @wemakefuture/y
2
+
3
+ ## Table Of Contents
4
+
5
+ - [Introduction](#introduction)
6
+ - [Getting Started](#getting-started)
7
+ - [Endpoints](#endpoints)
8
+ - [Apps](#apps)
9
+ - [Error Handling](#error-handling)
10
+ - [Schemas](#schemas)
11
+ - [HTTP Client](#http-client)
12
+ - [Paths](#paths)
13
+ - [Changelog](#changelog)
14
+
15
+ ## Introduction
16
+
17
+ y is a simple web framework for TypeScript. It includes a validation library
18
+ similar to Zod, and a simple route system similar to express. y is very
19
+ opinionated and not suitable for all use cases, e.g. since it doesn't provide
20
+ good support for custom middleware or data formats other than JSON.
21
+
22
+ Instead, it makes it easy to build well-documented software: y supports
23
+ automatic generation of OpenAPI documentation for all endpoints. This includes
24
+ generating JSON schemas for all request and response bodies that are specified
25
+ using y schemas.
26
+
27
+ ## Getting Started
28
+
29
+ First, install y with your favorite package manager:
30
+
31
+ ```bash
32
+ npm install @wemakefuture/y
33
+ yarn add @wemakefuture/y
34
+ bun add @wemakefuture/y
35
+ ```
36
+
37
+ Then, create your first endpoint in `src/routes/up.ts`:
38
+
39
+ ```ts
40
+ import { y } from "@wemakefuture/y";
41
+
42
+ export default y.endpoint("/up", {
43
+ summary: "Get server status.",
44
+ method: "GET",
45
+ query: y.object({}),
46
+ headers: y.object({}),
47
+ req: y.object({}),
48
+ res: y.object({ message: y.string() }),
49
+ do(req) {
50
+ return {
51
+ body: {
52
+ message: "Healthy.",
53
+ },
54
+ };
55
+ },
56
+ });
57
+ ```
58
+
59
+ And add this to `src/index.ts`:
60
+
61
+ ```ts
62
+ import { y } from "@wemakefuture/y";
63
+
64
+ y.app(`${__dirname}/routes`).then((app) => {
65
+ app.listen(3000);
66
+ });
67
+ ```
68
+
69
+ This starts a server with all endpoints in `src/routes` and listens on
70
+ port 3000.
71
+
72
+ ## Endpoints
73
+
74
+ The core construct of y is the `endpoint`. Endpoints are created like this:
75
+
76
+ ```ts
77
+ import { y } from "@wemakefuture/y";
78
+
79
+ export default y.endpoint("/up", {
80
+ summary: "Get server status.",
81
+ description:
82
+ "Returns a 200 status code if the server is running, otherwise a 502.",
83
+ method: "GET",
84
+ query: y.object({}),
85
+ headers: y.object({}),
86
+ req: y.object({}),
87
+ res: y.object({
88
+ message: y.string(),
89
+ }),
90
+ do(req) {
91
+ if (isHealthy()) {
92
+ return {
93
+ status: 200,
94
+ body: {
95
+ message: "Healthy.",
96
+ },
97
+ };
98
+ }
99
+ return {
100
+ status: 502,
101
+ body: {
102
+ message: "Not healthy.",
103
+ },
104
+ };
105
+ },
106
+ });
107
+ ```
108
+
109
+ This is a lot, so let's break it down:
110
+
111
+ 1. `/up` is the HTTP endpoint [path](#paths).
112
+ 2. `summary` is a simple summary of the endpoint. This will appear as the title
113
+ in the OpenAPI documentation.
114
+ 3. `description` is an optional longer description that will appear after
115
+ expanding the OpenAPI documentation for this endpoint.
116
+ 4. `method` is the HTTP method used to access the endpoint. Options are `GET`,
117
+ `POST`, `PUT`, and `DELETE`.
118
+ 5. `query` is the schema for the query parameters.
119
+ 6. `headers` is the schema for the HTTP headers.
120
+ 7. `req` is the schema for the request body. This should be empty for `GET` and
121
+ `POST`.
122
+ 8. `res` is the schema for the response body.
123
+ 9. `do` is the function that will actually be executed. It can be either sync or
124
+ async, and must return a response body, and optionally status codes and
125
+ headers.
126
+
127
+ Schemas are described in more detail [here](#schemas). In more complex
128
+ endpoints, [error handling](#error-handling) is also an important topic.
129
+
130
+ Inside the `do` function, the request data can be accessed using the `req`
131
+ parameter.
132
+
133
+ 1. `req.body` is the validated request body, matching the schema specified for
134
+ the endpoint.
135
+ 2. `req.headers` is just like `req.query`, but for headers.
136
+ 3. `req.http` is a request-specific HTTP client, which is described in detail
137
+ [here](#http-client).
138
+ 4. `req.log` is a request-specific logger. Currently, the logger isn't used for
139
+ anything and just prints everything to the console, but that will change in
140
+ the future.
141
+ 5. `req.params` are the parameters extracted from the path. Unfortunately, they
142
+ are not type-checked statically.
143
+ 6. `req.query` is the typed object containing all query parameters. If the query
144
+ parameters do not match the schema specified for the endpoint, an error is
145
+ raised.
146
+ 7. `req.url` is the HTTP path, so it does not include the hostname, and starts
147
+ with `/`.
148
+
149
+ ## Apps
150
+
151
+ Endpoints are always part of an entire application. With y, you create an
152
+ application like this:
153
+
154
+ ```ts
155
+ const app = await y.app(`${__dirname}/routes`);
156
+ ```
157
+
158
+ This will automatically find all endpoints in the provided directory. Right now,
159
+ all `.ts` and `.js` files are loaded, except for any `.test.ts`, `.schema.ts`,
160
+ `.util.ts`, `.d.ts`, `.test.js`, `.schema.js`, or `.util.js` files. Only the
161
+ default export is considered as an endpoint, so every endpoint will need to be
162
+ put into its own file. The `routes` path should be absolute. There is currently
163
+ no way to add endpoints manually to an application.
164
+
165
+ Once the application is created, it can be started like this:
166
+
167
+ ```ts
168
+ const context = app.listen(3000);
169
+ ```
170
+
171
+ This starts an HTTP server and listens on port 3000. The `context` that is
172
+ returned can be used for stopping the server again:
173
+
174
+ ```ts
175
+ await context.stop();
176
+ ```
177
+
178
+ This stops the server, but still continues to serve all current connections.
179
+ Once every connection is closed, the method returns.
180
+
181
+ Apps can also be used to generate OpenAPI documentation:
182
+
183
+ ```ts
184
+ const docs = app.docs({
185
+ info: {
186
+ title: "My title.",
187
+ description: "My description.",
188
+ version: "1.0.0",
189
+ },
190
+ servers: [
191
+ {
192
+ url: "prod.example.com",
193
+ description: "The production server.",
194
+ },
195
+ ],
196
+ });
197
+ console.log(docs);
198
+ ```
199
+
200
+ ## Schemas
201
+
202
+ To make y mostly typesafe, query parameters, headers, and the request and
203
+ response bodies are specified using schemas. If you have worked with Zod,
204
+ schemas should be very familiar.
205
+
206
+ There is a large number of functions that create a schema. Some of them take
207
+ subschemas, others can be configured using methods called on the schemas. In all
208
+ cases, the schema itself is immutable, and modifying functions like
209
+ `.optional()` always create a new schema instead of modifying the existing one.
210
+ The schemas should be very self-explanatory in general, and contain
211
+ documentation comments. The best way to learn is to try them! Here is a list of
212
+ all schemas:
213
+
214
+ - y.array
215
+ - y.boolean
216
+ - y.date
217
+ - y.enum
218
+ - y.intersection
219
+ - y.number
220
+ - y.object
221
+ - y.record
222
+ - y.string
223
+ - y.undefined
224
+ - y.union
225
+ - y.unknown
226
+
227
+ These are the same names as the schemas in Zod. Some schemas, like `z.any` in
228
+ Zod, won't be added to y, since using any leads to lots of type unsafety.
229
+ Instead, use `y.unknown` and use explicit type-checking.
230
+
231
+ There is also the more general `y.BodyType`. All of the above schemas are
232
+ subclasses of `y.BodyType`, but there are also:
233
+
234
+ - y.raw, which accepts any raw buffer with the specified content type
235
+ - y.either, which works just like y.union, except it may also contain a y.raw
236
+
237
+ Schemas can be passed to [endpoints](./endpoints.md) for validation, but you can
238
+ use them to validate things yourself, too. You can do that with the `y.parse`
239
+ function. It takes an unknown value and returns a typed and parsed value, or
240
+ throws a `y.ValiationError`.
241
+
242
+ If you need to use the type of a `y.BodyType`, you can do this using
243
+ `y.Typeof<typeof bodyType>`. In this case, `typeof bodyType` is the TypeScript
244
+ type of the schema itself, and `y.Typeof` turns that into the parsed type.
245
+
246
+ ## Error Handling
247
+
248
+ It is generally possible to return any status code from an endpoint, including
249
+ status codes that indicate failure. However, it is often simpler to just throw
250
+ an error, especially in nested method calls. To reduce boilerplate code
251
+ associated with catching these errors, y automatically handles errors derived
252
+ from `y.HttpError`, and returns their message and status code as an HTTP
253
+ response. There are some predefined error classes:
254
+
255
+ - `y.BadRequestError`
256
+ - `y.UnauthorizedError`
257
+ - `y.PaymentRequiredError`
258
+ - `y.ForbiddenError`
259
+ - `y.NotFoundError`
260
+ - `y.ConflictError`
261
+
262
+ If any other error is thrown inside an endpoint and not caught, y will
263
+ automatically return a 500 response, with the message `Internal Server Error`.
264
+ This is supposed to prevent accidental leakage of sensitive information.
265
+
266
+ ## HTTP Client
267
+
268
+ y contains a small embedded HTTP client that directly interfaces with the
269
+ logger. It is similar to Axios, but based on `fetch`. You can access the HTTP
270
+ client using `req.http`, the methods are fairly self-explanatory.
271
+
272
+ ## Paths
273
+
274
+ HTTP paths are used for specifying how the endpoint can be reached. They always
275
+ start with `/`, and can contain multiple segments, each separated using `/` from
276
+ the others. Segments can only contain lower-case letters, digits and hyphens.
277
+ Segments can be optional, in which case they are followed by `?`. Optional
278
+ segments must be at the end of the path, i.e. they may not be followed by
279
+ non-optional segments. Segments can also be parameters, in which case they are
280
+ preceded by `:`. This means they can match any segment.
281
+
282
+ All of these rules are checked automatically once creating the path. If you want
283
+ to check a path programmatically, you can use `y.validatePath`, which checks the
284
+ path and throws an exception if it is invalid.
285
+
286
+ The path parameters can be accessed inside [endpoints](./endpoints.md) using
287
+ `req.params`.
288
+
289
+ ## Changelog
290
+
291
+ y generally tries to follow a semantic versioning model. Right now, y is
292
+ pre-1.0, so breaking changes can occur on every minor release.
293
+
294
+ - 0.8.0 - Removed `identity` encoding, changed error field to `errorMessage`
295
+ - 0.7.3 - Changed `accept-encoding` for `y.Http` to `identity` to prevent memory leak
296
+ - 0.7.2 - Added time and connection count to connection log
297
+ - 0.7.1 - Made headers on test service methods optional
298
+ - 0.7.0 - Added test service and env parser
299
+ - 0.6.7 - Fixed failed 0.6.6 release
300
+ - 0.6.6 - Made `request` method of `y.Http` public
301
+ - 0.6.5 - Fixed crash when validation error occurs
302
+ - 0.6.4 - Added changelog and custom category option for endpoints
303
+ - 0.6.3 - Updated documentation and fixed NodeJS compatibility
304
+ - 0.6.2 - Fixed auto-importing of utility files
305
+ - 0.6.1 - Fixed auto-import error
306
+ - 0.6.0 - Replaced `y.router` with `y.app`, removed CLI completely
307
+ - 0.5.0 - Removed need for `y fix`
308
+ - 0.4.1 - Updated `y init` command
309
+ - 0.4.0 - Added listen context to correctly terminate server
310
+ - 0.3.11 - Added basic way to stop server after `y.listen`
311
+ - 0.3.10 - Improved OpenAPI generation
312
+ - 0.3.9 - Fixed parsing of empty JSON body
313
+ - 0.3.8 - Fixed incorrect NPM version
314
+ - 0.3.7 - Added `y doc` command
315
+ - 0.3.6 - Added `req.http` client
316
+ - 0.3.5 - Added log on each request
317
+ - 0.3.4 - Fixed endpoint result schema
318
+ - 0.3.3 - Fixed `y.either` export status
319
+ - 0.3.2 - Added `y.either`
320
+ - 0.3.1 - Fixed request body parsing
321
+ - 0.3.0 - Added `y.raw`
322
+ - 0.2.1 - Fix for `y fix` command
323
+ - 0.2.0 - Added NodeJS support and CLI interface
324
+ - 0.1.2 - Fixed y.number() minimum and maximum checks
325
+ - 0.1.1 - Added test cases, documentation and license
326
+ - 0.1.0 - Initial release
@@ -0,0 +1,2 @@
1
+ import * as y from './lib';
2
+ export { y };
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.y = void 0;
4
+ const y = require("./lib");
5
+ exports.y = y;
package/dist/lib.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ export { type EndpointOptions, type EndpointRequest, type EndpointResponse, endpoint, } from './routing/endpoint';
2
+ export { HttpError, BadRequestError, UnauthorizedError, PaymentRequiredError, ForbiddenError, NotFoundError, ConflictError, } from './routing/errors';
3
+ export { type Context } from './routing/listen';
4
+ export { Log } from './routing/log';
5
+ export { type Endpoint, app } from './routing/app';
6
+ export declare const validatePath: (path: string) => void;
7
+ export { TestService } from './routing/test';
8
+ export { parseEnv } from './routing/env';
9
+ export { route } from './routing/route';
10
+ export { array } from './validation/array';
11
+ export { boolean } from './validation/boolean';
12
+ export { date } from './validation/date';
13
+ export { _enum as enum } from './validation/enum';
14
+ export { ValidationError } from './validation/error';
15
+ export { intersection } from './validation/intersection';
16
+ export { number } from './validation/number';
17
+ export { object } from './validation/object';
18
+ export { record } from './validation/record';
19
+ export { Schema } from './validation/schema';
20
+ export { BodyType, type Typeof } from './validation/body';
21
+ export { raw } from './validation/raw';
22
+ export { none } from './validation/none';
23
+ export { either } from './validation/either';
24
+ export { HttpResponse, HttpRequestError, Http } from './routing/http';
25
+ export { string } from './validation/string';
26
+ export { _undefined as undefined } from './validation/undefined';
27
+ export { union } from './validation/union';
28
+ export { unknown } from './validation/unknown';
package/dist/lib.js ADDED
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.unknown = exports.union = exports.undefined = exports.string = exports.Http = exports.HttpRequestError = exports.HttpResponse = exports.either = exports.none = exports.raw = exports.BodyType = exports.Schema = exports.record = exports.object = exports.number = exports.intersection = exports.ValidationError = exports.enum = exports.date = exports.boolean = exports.array = exports.route = exports.parseEnv = exports.TestService = exports.validatePath = exports.app = exports.Log = exports.ConflictError = exports.NotFoundError = exports.ForbiddenError = exports.PaymentRequiredError = exports.UnauthorizedError = exports.BadRequestError = exports.HttpError = exports.endpoint = void 0;
4
+ const path_1 = require("./routing/path");
5
+ // routing
6
+ var endpoint_1 = require("./routing/endpoint");
7
+ Object.defineProperty(exports, "endpoint", { enumerable: true, get: function () { return endpoint_1.endpoint; } });
8
+ var errors_1 = require("./routing/errors");
9
+ Object.defineProperty(exports, "HttpError", { enumerable: true, get: function () { return errors_1.HttpError; } });
10
+ Object.defineProperty(exports, "BadRequestError", { enumerable: true, get: function () { return errors_1.BadRequestError; } });
11
+ Object.defineProperty(exports, "UnauthorizedError", { enumerable: true, get: function () { return errors_1.UnauthorizedError; } });
12
+ Object.defineProperty(exports, "PaymentRequiredError", { enumerable: true, get: function () { return errors_1.PaymentRequiredError; } });
13
+ Object.defineProperty(exports, "ForbiddenError", { enumerable: true, get: function () { return errors_1.ForbiddenError; } });
14
+ Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return errors_1.NotFoundError; } });
15
+ Object.defineProperty(exports, "ConflictError", { enumerable: true, get: function () { return errors_1.ConflictError; } });
16
+ var log_1 = require("./routing/log");
17
+ Object.defineProperty(exports, "Log", { enumerable: true, get: function () { return log_1.Log; } });
18
+ var app_1 = require("./routing/app");
19
+ Object.defineProperty(exports, "app", { enumerable: true, get: function () { return app_1.app; } });
20
+ const validatePath = (path) => {
21
+ new path_1.Path(path);
22
+ };
23
+ exports.validatePath = validatePath;
24
+ var test_1 = require("./routing/test");
25
+ Object.defineProperty(exports, "TestService", { enumerable: true, get: function () { return test_1.TestService; } });
26
+ var env_1 = require("./routing/env");
27
+ Object.defineProperty(exports, "parseEnv", { enumerable: true, get: function () { return env_1.parseEnv; } });
28
+ var route_1 = require("./routing/route");
29
+ Object.defineProperty(exports, "route", { enumerable: true, get: function () { return route_1.route; } });
30
+ // validation
31
+ var array_1 = require("./validation/array");
32
+ Object.defineProperty(exports, "array", { enumerable: true, get: function () { return array_1.array; } });
33
+ var boolean_1 = require("./validation/boolean");
34
+ Object.defineProperty(exports, "boolean", { enumerable: true, get: function () { return boolean_1.boolean; } });
35
+ var date_1 = require("./validation/date");
36
+ Object.defineProperty(exports, "date", { enumerable: true, get: function () { return date_1.date; } });
37
+ var enum_1 = require("./validation/enum");
38
+ Object.defineProperty(exports, "enum", { enumerable: true, get: function () { return enum_1._enum; } });
39
+ var error_1 = require("./validation/error");
40
+ Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return error_1.ValidationError; } });
41
+ var intersection_1 = require("./validation/intersection");
42
+ Object.defineProperty(exports, "intersection", { enumerable: true, get: function () { return intersection_1.intersection; } });
43
+ var number_1 = require("./validation/number");
44
+ Object.defineProperty(exports, "number", { enumerable: true, get: function () { return number_1.number; } });
45
+ var object_1 = require("./validation/object");
46
+ Object.defineProperty(exports, "object", { enumerable: true, get: function () { return object_1.object; } });
47
+ var record_1 = require("./validation/record");
48
+ Object.defineProperty(exports, "record", { enumerable: true, get: function () { return record_1.record; } });
49
+ var schema_1 = require("./validation/schema");
50
+ Object.defineProperty(exports, "Schema", { enumerable: true, get: function () { return schema_1.Schema; } });
51
+ var body_1 = require("./validation/body");
52
+ Object.defineProperty(exports, "BodyType", { enumerable: true, get: function () { return body_1.BodyType; } });
53
+ var raw_1 = require("./validation/raw");
54
+ Object.defineProperty(exports, "raw", { enumerable: true, get: function () { return raw_1.raw; } });
55
+ var none_1 = require("./validation/none");
56
+ Object.defineProperty(exports, "none", { enumerable: true, get: function () { return none_1.none; } });
57
+ var either_1 = require("./validation/either");
58
+ Object.defineProperty(exports, "either", { enumerable: true, get: function () { return either_1.either; } });
59
+ var http_1 = require("./routing/http");
60
+ Object.defineProperty(exports, "HttpResponse", { enumerable: true, get: function () { return http_1.HttpResponse; } });
61
+ Object.defineProperty(exports, "HttpRequestError", { enumerable: true, get: function () { return http_1.HttpRequestError; } });
62
+ Object.defineProperty(exports, "Http", { enumerable: true, get: function () { return http_1.Http; } });
63
+ var string_1 = require("./validation/string");
64
+ Object.defineProperty(exports, "string", { enumerable: true, get: function () { return string_1.string; } });
65
+ var undefined_1 = require("./validation/undefined");
66
+ Object.defineProperty(exports, "undefined", { enumerable: true, get: function () { return undefined_1._undefined; } });
67
+ var union_1 = require("./validation/union");
68
+ Object.defineProperty(exports, "union", { enumerable: true, get: function () { return union_1.union; } });
69
+ var unknown_1 = require("./validation/unknown");
70
+ Object.defineProperty(exports, "unknown", { enumerable: true, get: function () { return unknown_1.unknown; } });
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "yedra",
3
+ "version": "0.9.0",
4
+ "repository": "github:0codekit/yedra",
5
+ "main": "dist/index.js",
6
+ "devDependencies": {
7
+ "@biomejs/biome": "^1.8.3",
8
+ "@types/bun": "^1.1.6",
9
+ "@types/node": "^20.14.10",
10
+ "typescript": "^5.5.3"
11
+ },
12
+ "bugs": "https://github.com/0codekit/yedra/issues",
13
+ "contributors": ["Justus Zorn <jzorn@wemakefuture.com>"],
14
+ "description": "A TypeScript web framework with OpenAPI generation.",
15
+ "keywords": ["typescript", "web", "http", "schema", "validation", "openapi"],
16
+ "license": "MIT",
17
+ "files": ["./dist/*"],
18
+ "scripts": {
19
+ "check": "biome check src/*"
20
+ },
21
+ "types": "dist/index.d.ts",
22
+ "dependencies": {
23
+ "glob": "^10.4.5"
24
+ }
25
+ }