@aponiajs/compression 0.0.0-stage → 1.0.0-beta.64

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/README.md CHANGED
@@ -1,3 +1,115 @@
1
- # Temporary Holding Version
1
+ # @aponiajs/compression
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Brotli and gzip response compression for AponiaJS, with a size threshold and
4
+ safe skips.
5
+
6
+ ```bash
7
+ bun add @aponiajs/compression@alpha
8
+ ```
9
+
10
+ ## Use it
11
+
12
+ ### Register the module
13
+
14
+ ```ts
15
+ import { Module } from "@aponiajs/common";
16
+ import { CompressionModule } from "@aponiajs/compression";
17
+
18
+ @Module({
19
+ imports: [CompressionModule.forRoot()],
20
+ })
21
+ export class AppModule {}
22
+ ```
23
+
24
+ ### Use it in a controller
25
+
26
+ ```ts
27
+ import { Controller, Get } from "@aponiajs/common";
28
+
29
+ @Controller("reports")
30
+ export class ReportsController {
31
+ @Get()
32
+ read() {
33
+ return { rows: Array.from({ length: 200 }, (_, index) => ({ id: index })) };
34
+ }
35
+ }
36
+ ```
37
+
38
+ No service is injected; this package contributes a policy/endpoint. The policy
39
+ negotiates `Accept-Encoding`, preferring Brotli when both encodings are
40
+ accepted, and leaves responses under the threshold untouched. A compressible
41
+ body above `thresholdBytes` answers with `content-encoding` and an appended
42
+ `vary: Accept-Encoding`.
43
+
44
+ ### Async registration
45
+
46
+ `CompressionModule.forRootAsync` accepts a factory, a class, or an existing
47
+ provider, and a factory may answer a Promise:
48
+
49
+ ```ts
50
+ CompressionModule.forRootAsync({
51
+ useFactory: async () => ({ thresholdBytes: 2_048 }),
52
+ });
53
+ ```
54
+
55
+ ```ts
56
+ import { Injectable } from "@aponiajs/common";
57
+
58
+ @Injectable()
59
+ class CompressionSettings {
60
+ create() {
61
+ return { thresholdBytes: 2_048 };
62
+ }
63
+ }
64
+
65
+ CompressionModule.forRootAsync({ useClass: CompressionSettings });
66
+ ```
67
+
68
+ ```ts
69
+ @Module({ providers: [CompressionSettings], exports: [CompressionSettings] })
70
+ class CompressionSettingsModule {}
71
+
72
+ CompressionModule.forRootAsync({
73
+ imports: [CompressionSettingsModule],
74
+ useExisting: CompressionSettings,
75
+ });
76
+ ```
77
+
78
+ ## Options
79
+
80
+ | Option | Default | Meaning |
81
+ | ---------------- | ---------------- | --------------------------------------- |
82
+ | `thresholdBytes` | `1024` | Minimum body size before compression. |
83
+ | `encodings` | `["br", "gzip"]` | Offered encodings, in preference order. |
84
+ | `key` | `compression` | Module identity. |
85
+
86
+ ## Behavior
87
+
88
+ - Only compressible types are compressed: `text/*`, JSON, JavaScript, XML, and
89
+ SVG.
90
+ - `HEAD`, `204`, `206`, and `304` responses are skipped.
91
+ - A response that already carries `content-encoding` is skipped.
92
+ - `Vary: Accept-Encoding` is appended, preserving existing values.
93
+ - A `Response` object keeps its status and headers; a string or object response
94
+ leaves through the same status.
95
+ - Brotli and gzip are asynchronous, so compression does not block the event
96
+ loop while it runs.
97
+
98
+ This package compresses responses; it does not decompress requests, cache
99
+ compressed bodies, or negotiate content beyond `Accept-Encoding`.
100
+
101
+ ## Bootstrap
102
+
103
+ ```ts
104
+ import { AponiaFactory } from "@aponiajs/platform-elysia";
105
+ import { AppModule } from "./app.module.ts";
106
+
107
+ const application = await AponiaFactory.create(AppModule);
108
+ await application.listen(Number(Bun.env.PORT ?? 3000));
109
+ ```
110
+
111
+ ## Documentation
112
+
113
+ - [Published packages](../../docs/reference/packages.md)
114
+ - [AponiaJS architecture](../../docs/build/architecture-and-style.md)
115
+ - [npm](https://www.npmjs.com/package/@aponiajs/compression)
@@ -0,0 +1,41 @@
1
+ import { DynamicModule, ModuleAsyncOptions } from "@aponiajs/common";
2
+ /** Options a compression registration accepts. */
3
+ interface CompressionModuleOptions {
4
+ /** The minimum body size in bytes; defaults to 1 KiB. */
5
+ readonly thresholdBytes?: number;
6
+ /** The encodings offered, in preference order; defaults to `["br", "gzip"]`. */
7
+ readonly encodings?: readonly ("br" | "gzip")[];
8
+ /** The plugin module identity; defaults to `compression`. */
9
+ readonly key?: string;
10
+ }
11
+ /** The registration options a factory supplies. */
12
+ type CompressionModuleAsyncOptions = ModuleAsyncOptions<CompressionModuleOptions> & {
13
+ readonly key?: string;
14
+ };
15
+ /** Contributes the encoding-aware compression policy. */
16
+ export declare class CompressionModule {
17
+ /**
18
+ * Builds a compression registration.
19
+ *
20
+ * @param options - Threshold, encodings, and module key.
21
+ * @returns The module registration an application imports.
22
+ * @throws An `AponiaError` with `INVALID_COMPRESSION_OPTIONS` when an option is invalid.
23
+ */
24
+ static forRoot(options?: CompressionModuleOptions): DynamicModule;
25
+ /**
26
+ * Builds a compression registration whose options a factory resolves.
27
+ *
28
+ * @param options - The imports, injected tokens, factory, key, and extra providers.
29
+ * @returns The module registration an application imports.
30
+ */
31
+ static forRootAsync(options: ModuleAsyncOptions<CompressionModuleOptions> & {
32
+ readonly key?: string;
33
+ }): DynamicModule;
34
+ /**
35
+ * Builds a compression registration.
36
+ *
37
+ * @deprecated Use {@link CompressionModule.forRoot}; retained for the beta line.
38
+ */
39
+ static register(options?: CompressionModuleOptions): DynamicModule;
40
+ }
41
+ export type { CompressionModuleAsyncOptions, CompressionModuleOptions };
package/dist/index.mjs ADDED
@@ -0,0 +1,142 @@
1
+ import { AponiaError, Module, createToken, dynamicModule, moduleOptionsProviders, provideHttpPolicyAsync, provideValue, requirePlatformCapabilities } from "@aponiajs/common";
2
+ import { brotliCompress, gzip } from "node:zlib";
3
+ import { promisify } from "node:util";
4
+ // src/policy/compression.policy.ts
5
+ const brotli = promisify(brotliCompress);
6
+ const gzipAsync = promisify(gzip);
7
+ const defaultThresholdBytes = 1024;
8
+ /** Validates one registration and answers the policy it builds. */
9
+ function resolveCompressionOptions(options) {
10
+ const thresholdBytes = options.thresholdBytes ?? defaultThresholdBytes;
11
+ const encodings = options.encodings ?? ["br", "gzip"];
12
+ const issues = [];
13
+ if (!Number.isInteger(thresholdBytes) || thresholdBytes < 0) issues.push("thresholdBytes must be a non-negative integer");
14
+ if (!Array.isArray(encodings) || encodings.length === 0 || encodings.some((encoding) => encoding !== "br" && encoding !== "gzip")) issues.push("encodings must be a non-empty array of \"br\" or \"gzip\"");
15
+ if (issues.length > 0) throw new AponiaError("INVALID_COMPRESSION_OPTIONS", `The compression registration is invalid: ${issues.join("; ")}.`, { issues: Object.freeze(issues) });
16
+ return Object.freeze({
17
+ thresholdBytes,
18
+ encodings: Object.freeze([...new Set(encodings)])
19
+ });
20
+ }
21
+ /**
22
+ * Builds the neutral response policy one registration contributes.
23
+ *
24
+ * The policy transforms a `Response`, so it runs on every platform through the
25
+ * shared pipeline rather than mounting a runtime plugin.
26
+ */
27
+ function buildCompressionPolicy(options) {
28
+ return {
29
+ name: "compression",
30
+ async onResponse(request, response) {
31
+ return await compressResponse(response, request, options) ?? response;
32
+ }
33
+ };
34
+ }
35
+ async function compressResponse(response, request, options) {
36
+ if (request.method === "HEAD") return;
37
+ if (response.status === 204 || response.status === 206 || response.status === 304) return;
38
+ if (response.body === null) return;
39
+ if (response.headers.has("content-encoding")) return;
40
+ const contentType = response.headers.get("content-type");
41
+ if (contentType !== null && contentType.startsWith("text/event-stream")) return;
42
+ if (contentType !== null && !isCompressible(contentType)) return;
43
+ const encoding = selectEncoding(request.headers.get("accept-encoding"), options);
44
+ if (encoding === void 0) return;
45
+ const declaredLength = response.headers.get("content-length");
46
+ if (declaredLength !== null && Number(declaredLength) < options.thresholdBytes) return;
47
+ const payload = new Uint8Array(await response.clone().arrayBuffer());
48
+ if (payload.byteLength < options.thresholdBytes) return;
49
+ const compressed = await compress(payload, encoding);
50
+ const headers = new Headers(response.headers);
51
+ headers.set("content-encoding", encoding);
52
+ headers.set("content-length", String(compressed.byteLength));
53
+ headers.set("vary", appendVary(headers.get("vary") ?? void 0, "accept-encoding"));
54
+ return new Response(compressed, {
55
+ status: response.status,
56
+ statusText: response.statusText,
57
+ headers
58
+ });
59
+ }
60
+ function isCompressible(contentType) {
61
+ const type = contentType.toLowerCase();
62
+ return type.startsWith("text/") || type.includes("application/json") || type.includes("+json") || type.includes("application/javascript") || type.includes("application/xml") || type.includes("image/svg+xml");
63
+ }
64
+ function selectEncoding(acceptEncoding, options) {
65
+ if (acceptEncoding === null) return;
66
+ const accepted = /* @__PURE__ */ new Map();
67
+ for (const part of acceptEncoding.split(",")) {
68
+ const [name, ...parameters] = part.trim().toLowerCase().split(";");
69
+ if (name === void 0 || name === "") continue;
70
+ const quality = parameters.find((parameter) => parameter.trim().startsWith("q="));
71
+ const q = quality === void 0 ? 1 : Number(quality.trim().slice(2));
72
+ accepted.set(name, Number.isFinite(q) ? q : 0);
73
+ }
74
+ for (const encoding of options.encodings) if ((accepted.get(encoding) ?? accepted.get("*") ?? 0) > 0) return encoding;
75
+ }
76
+ function appendVary(current, value) {
77
+ const normalized = Array.isArray(current) ? current.join(", ") : current === void 0 ? "" : String(current);
78
+ const parts = new Set(normalized.split(",").map((part) => part.trim().toLowerCase()).filter((part) => part !== ""));
79
+ parts.add(value);
80
+ return [...parts].join(", ");
81
+ }
82
+ async function compress(payload, encoding) {
83
+ const buffer = await (encoding === "br" ? brotli(payload) : gzipAsync(payload));
84
+ return new Uint8Array(buffer);
85
+ }
86
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/decorate.js
87
+ function __decorate(decorators, target, key, desc) {
88
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
89
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
90
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
91
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
92
+ }
93
+ // src/module/compression.module.ts
94
+ var _CompressionModule;
95
+ const defaultKey = "compression";
96
+ const COMPRESSION_RESOLVED = createToken("aponia.plugin.compression.resolved");
97
+ let CompressionModule = _CompressionModule = class CompressionModule {
98
+ /**
99
+ * Builds a compression registration.
100
+ *
101
+ * @param options - Threshold, encodings, and module key.
102
+ * @returns The module registration an application imports.
103
+ * @throws An `AponiaError` with `INVALID_COMPRESSION_OPTIONS` when an option is invalid.
104
+ */
105
+ static forRoot(options = {}) {
106
+ return registration([provideValue(COMPRESSION_RESOLVED, resolveCompressionOptions(options))], options.key ?? defaultKey);
107
+ }
108
+ /**
109
+ * Builds a compression registration whose options a factory resolves.
110
+ *
111
+ * @param options - The imports, injected tokens, factory, key, and extra providers.
112
+ * @returns The module registration an application imports.
113
+ */
114
+ static forRootAsync(options) {
115
+ return registration(moduleOptionsProviders(COMPRESSION_RESOLVED, options, (resolved) => resolveCompressionOptions(resolved)), options.key ?? defaultKey, options.imports, options.extraProviders);
116
+ }
117
+ /**
118
+ * Builds a compression registration.
119
+ *
120
+ * @deprecated Use {@link CompressionModule.forRoot}; retained for the beta line.
121
+ */
122
+ static register(options = {}) {
123
+ return _CompressionModule.forRoot(options);
124
+ }
125
+ };
126
+ CompressionModule = _CompressionModule = __decorate([Module({})], CompressionModule);
127
+ function registration(resolvedProviders, key, imports = [], extraProviders = []) {
128
+ return dynamicModule({
129
+ module: CompressionModule,
130
+ id: `CompressionModule[${key}]`,
131
+ instanceId: Symbol.for(`aponia.compression:${key}`),
132
+ imports,
133
+ providers: [
134
+ ...resolvedProviders,
135
+ provideHttpPolicyAsync([COMPRESSION_RESOLVED], (resolved) => buildCompressionPolicy(resolved)),
136
+ requirePlatformCapabilities("compression", ["http"]),
137
+ ...extraProviders
138
+ ],
139
+ exports: []
140
+ });
141
+ }
142
+ export { CompressionModule };
package/llms.txt ADDED
@@ -0,0 +1,24 @@
1
+ # @aponiajs/compression
2
+
3
+ > Brotli and gzip response compression for an AponiaJS application, with a size threshold, encoding negotiation, and safe skips.
4
+
5
+ ## What this package exports
6
+
7
+ - `CompressionModule.forRoot({ thresholdBytes?, encodings?, key? })`: the registration an application imports; `register` is the deprecated beta alias.
8
+ - `CompressionModuleOptions`: the public contract.
9
+
10
+ ## Behavior a consumer can rely on
11
+
12
+ - `Accept-Encoding` is negotiated; Brotli is preferred when both are accepted.
13
+ - Only `text/*`, JSON, JavaScript, XML, and SVG responses are compressed.
14
+ - Responses below `thresholdBytes` and bodyless statuses are skipped.
15
+ - Already-encoded responses are skipped.
16
+ - `Vary: Accept-Encoding` is appended, preserving existing values.
17
+ - Brotli and gzip run asynchronously.
18
+ - An invalid option fails the boot with `INVALID_COMPRESSION_OPTIONS` and a frozen issue list.
19
+
20
+ ## Documentation
21
+
22
+ - [Package README](./README.md)
23
+ - [Published packages](../../docs/reference/packages.md)
24
+ - [npm](https://www.npmjs.com/package/@aponiajs/compression)
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@aponiajs/compression",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0-beta.64",
4
+ "description": "Brotli and gzip response compression for an Aponia application, with a size threshold.",
5
+ "keywords": [
6
+ "aponia",
7
+ "aponiajs",
8
+ "brotli",
9
+ "bun",
10
+ "compression",
11
+ "elysia",
12
+ "gzip",
13
+ "typescript"
14
+ ],
15
+ "homepage": "https://github.com/aponiajs/aponiajs#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/aponiajs/aponiajs/issues"
18
+ },
19
+ "license": "MIT",
20
+ "author": "AponiaJS contributors",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/aponiajs/aponiajs.git",
24
+ "directory": "packages/compression"
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "llms.txt"
29
+ ],
30
+ "type": "module",
31
+ "exports": {
32
+ ".": "./dist/index.mjs",
33
+ "./package.json": "./package.json"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "scripts": {
39
+ "build": "bunx --bun vp pack",
40
+ "dev": "bunx --bun vp pack --watch",
41
+ "test": "bun test",
42
+ "test:vite-plus": "vp test",
43
+ "check": "bunx --bun vp check",
44
+ "prepublishOnly": "bun run build"
45
+ },
46
+ "dependencies": {
47
+ "@aponiajs/common": "1.0.0-beta.64"
48
+ },
49
+ "devDependencies": {
50
+ "@aponiajs/core": "1.0.0-beta.64",
51
+ "@aponiajs/platform-elysia": "1.0.0-beta.64",
52
+ "@aponiajs/platform-h3": "1.0.0-beta.64",
53
+ "@aponiajs/platform-hono": "1.0.0-beta.64",
54
+ "@aponiajs/serverless": "1.0.0-beta.64",
55
+ "elysia": "2.0.0-rc.4"
56
+ },
57
+ "engines": {
58
+ "bun": ">=1.4.4"
59
+ }
60
+ }