@velajs/cloudflare 1.30.0 → 1.32.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.
Files changed (118) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/README.md +407 -77
  3. package/dist/bindings.js +93 -0
  4. package/dist/bindings.js.map +1 -0
  5. package/dist/cloudflare-application-CXDy9C1R.d.ts +199 -0
  6. package/dist/cloudflare-application.js +15 -34
  7. package/dist/cloudflare-application.js.map +1 -1
  8. package/dist/cloudflare-factory-CuFNUJJD.d.ts +241 -0
  9. package/dist/cloudflare-factory.js +227 -38
  10. package/dist/cloudflare-factory.js.map +1 -1
  11. package/dist/diagnostics.js +18 -0
  12. package/dist/diagnostics.js.map +1 -0
  13. package/dist/durable-object/boot.js +76 -0
  14. package/dist/durable-object/boot.js.map +1 -0
  15. package/dist/durable-object/host-dispatch.js +134 -0
  16. package/dist/durable-object/host-dispatch.js.map +1 -0
  17. package/dist/durable-object/host-methods.js +47 -0
  18. package/dist/durable-object/host-methods.js.map +1 -0
  19. package/dist/durable-object/tokens.js +17 -0
  20. package/dist/durable-object/tokens.js.map +1 -0
  21. package/dist/durable-object/vela-durable-object.js +121 -0
  22. package/dist/durable-object/vela-durable-object.js.map +1 -0
  23. package/dist/durable-objects.d.ts +136 -10
  24. package/dist/durable-objects.js +3 -1
  25. package/dist/email/email-dispatch.js +65 -0
  26. package/dist/email/email-dispatch.js.map +1 -0
  27. package/dist/email/on-email.js +57 -0
  28. package/dist/email/on-email.js.map +1 -0
  29. package/dist/email.d.ts +51 -0
  30. package/dist/email.js +3 -0
  31. package/dist/entrypoint/vela-entrypoint.js +160 -0
  32. package/dist/entrypoint/vela-entrypoint.js.map +1 -0
  33. package/dist/entrypoints.d.ts +93 -0
  34. package/dist/entrypoints.js +2 -0
  35. package/dist/host/host-invoker.js +276 -0
  36. package/dist/host/host-invoker.js.map +1 -0
  37. package/dist/host/host-members.js +73 -0
  38. package/dist/host/host-members.js.map +1 -0
  39. package/dist/host-members-DECj_4yz.d.ts +13 -0
  40. package/dist/index.d.ts +211 -445
  41. package/dist/index.js +8 -13
  42. package/dist/{nonce.durable-object-Ci9AGssY.d.ts → nonce.durable-object-Bg1e0BMD.d.ts} +1 -11
  43. package/dist/platform.js +22 -0
  44. package/dist/platform.js.map +1 -0
  45. package/dist/queue/cloudflare-queues.js +7 -7
  46. package/dist/queue/cloudflare-queues.js.map +1 -1
  47. package/dist/rate-limit/cloudflare-rate-limit.store.js +66 -27
  48. package/dist/rate-limit/cloudflare-rate-limit.store.js.map +1 -1
  49. package/dist/root-module.js +19 -0
  50. package/dist/root-module.js.map +1 -0
  51. package/dist/rpc/entrypoint-error.js +145 -0
  52. package/dist/rpc/entrypoint-error.js.map +1 -0
  53. package/dist/schedule-diagnostics.js +8 -15
  54. package/dist/schedule-diagnostics.js.map +1 -1
  55. package/dist/services/kv-cache.store.js +33 -7
  56. package/dist/services/kv-cache.store.js.map +1 -1
  57. package/dist/storage/r2-storage.js +30 -0
  58. package/dist/storage/r2-storage.js.map +1 -0
  59. package/dist/storage.d.ts +28 -0
  60. package/dist/storage.js +2 -0
  61. package/dist/tail/on-tail.js +46 -0
  62. package/dist/tail/on-tail.js.map +1 -0
  63. package/dist/tail/tail-dispatch.js +67 -0
  64. package/dist/tail/tail-dispatch.js.map +1 -0
  65. package/dist/tail.d.ts +39 -0
  66. package/dist/tail.js +2 -0
  67. package/dist/testing.d.ts +148 -0
  68. package/dist/testing.js +188 -0
  69. package/dist/testing.js.map +1 -0
  70. package/dist/websocket/binding-gateways.js +33 -0
  71. package/dist/websocket/binding-gateways.js.map +1 -0
  72. package/dist/websocket/cf-room-registry.js +3 -1
  73. package/dist/websocket/cf-room-registry.js.map +1 -1
  74. package/dist/websocket/do-bootstrap.js +64 -40
  75. package/dist/websocket/do-bootstrap.js.map +1 -1
  76. package/dist/websocket/do-live.js +49 -90
  77. package/dist/websocket/do-live.js.map +1 -1
  78. package/dist/websocket/do-state.js.map +1 -1
  79. package/dist/websocket/live-driver.js +149 -0
  80. package/dist/websocket/live-driver.js.map +1 -0
  81. package/dist/websocket/room-id.js +11 -1
  82. package/dist/websocket/room-id.js.map +1 -1
  83. package/dist/websocket/websocket.durable-object.js +51 -18
  84. package/dist/websocket/websocket.durable-object.js.map +1 -1
  85. package/dist/websocket/worker-transport.js +80 -0
  86. package/dist/websocket/worker-transport.js.map +1 -0
  87. package/dist/worker-events.js +49 -0
  88. package/dist/worker-events.js.map +1 -0
  89. package/dist/workflow/vela-workflow.js +104 -0
  90. package/dist/workflow/vela-workflow.js.map +1 -0
  91. package/dist/workflows.d.ts +82 -0
  92. package/dist/workflows.js +2 -0
  93. package/package.json +39 -6
  94. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js +0 -9
  95. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js +0 -6
  96. package/dist/_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js +0 -8
  97. package/dist/storage/r2-storage.driver.js +0 -67
  98. package/dist/storage/r2-storage.driver.js.map +0 -1
  99. package/dist/storage/storage-key-claim.js +0 -74
  100. package/dist/storage/storage-key-claim.js.map +0 -1
  101. package/dist/storage/storage-manager.service.js +0 -38
  102. package/dist/storage/storage-manager.service.js.map +0 -1
  103. package/dist/storage/storage.controller.js +0 -64
  104. package/dist/storage/storage.controller.js.map +0 -1
  105. package/dist/storage/storage.module.js +0 -25
  106. package/dist/storage/storage.module.js.map +0 -1
  107. package/dist/storage/storage.service.js +0 -64
  108. package/dist/storage/storage.service.js.map +0 -1
  109. package/dist/storage/storage.tokens.js +0 -7
  110. package/dist/storage/storage.tokens.js.map +0 -1
  111. package/dist/websocket/broadcast.js +0 -32
  112. package/dist/websocket/broadcast.js.map +0 -1
  113. package/dist/websocket/cloudflare-websocket.module.js +0 -25
  114. package/dist/websocket/cloudflare-websocket.module.js.map +0 -1
  115. package/dist/websocket/websocket-routing.js +0 -133
  116. package/dist/websocket/websocket-routing.js.map +0 -1
  117. package/dist/websocket/ws-server-holder.js +0 -38
  118. package/dist/websocket/ws-server-holder.js.map +0 -1
@@ -1,74 +0,0 @@
1
- //#region src/storage/storage-key-claim.ts
2
- /** R2-compatible object-key claim bound. Keeps decode work predictably small. */
3
- const MAX_STORAGE_KEY_BYTES = 1024;
4
- const BASE64URL_RE = /^[A-Za-z0-9_-]+$/;
5
- const ROOT_TOKEN_PATTERNS = {
6
- date: "\\d{4}-\\d{2}-\\d{2}",
7
- year: "\\d{4}",
8
- month: "(?:0[1-9]|1[0-2])",
9
- day: "(?:0[1-9]|[12]\\d|3[01])",
10
- uuid: "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}"
11
- };
12
- /** Encode an object key as an opaque, canonical base64url query claim. */
13
- function encodeStorageKeyClaim(key) {
14
- const bytes = new TextEncoder().encode(key);
15
- if (bytes.byteLength === 0 || bytes.byteLength > MAX_STORAGE_KEY_BYTES) throw new Error(`Storage key must be 1–${MAX_STORAGE_KEY_BYTES} UTF-8 bytes`);
16
- let binary = "";
17
- for (const byte of bytes) binary += String.fromCharCode(byte);
18
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
19
- }
20
- /** Decode exactly one canonical base64url layer. Malformed/non-UTF-8 claims return undefined. */
21
- function decodeStorageKeyClaim(claim) {
22
- try {
23
- if (claim.length === 0 || claim.length > Math.ceil(MAX_STORAGE_KEY_BYTES * 4 / 3) || !BASE64URL_RE.test(claim) || claim.length % 4 === 1) return;
24
- const base64 = claim.replace(/-/g, "+").replace(/_/g, "/");
25
- const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
26
- const binary = atob(padded);
27
- const bytes = new Uint8Array(new ArrayBuffer(binary.length));
28
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
29
- if (bytes.byteLength === 0 || bytes.byteLength > MAX_STORAGE_KEY_BYTES) return void 0;
30
- const decoded = new TextDecoder("utf-8", {
31
- fatal: true,
32
- ignoreBOM: false
33
- }).decode(bytes);
34
- return encodeStorageKeyClaim(decoded) === claim ? decoded : void 0;
35
- } catch {
36
- return;
37
- }
38
- }
39
- function isDotSegment(segment) {
40
- let decoded = segment;
41
- for (let i = 0; i < 2; i++) {
42
- if (decoded === "" || decoded === "." || decoded === "..") return true;
43
- try {
44
- const next = decodeURIComponent(decoded);
45
- if (next === decoded) break;
46
- decoded = next;
47
- } catch {
48
- break;
49
- }
50
- }
51
- return decoded === "" || decoded === "." || decoded === "..";
52
- }
53
- function rootSegmentPattern(segment) {
54
- let pattern = "";
55
- let cursor = 0;
56
- for (const match of segment.matchAll(/\{(date|year|month|day|uuid)\}/g)) {
57
- pattern += segment.slice(cursor, match.index).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
58
- pattern += ROOT_TOKEN_PATTERNS[match[1]];
59
- cursor = match.index + match[0].length;
60
- }
61
- pattern += segment.slice(cursor).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
62
- return pattern;
63
- }
64
- /** Assert a canonical key is beneath a static or templated configured root. */
65
- function isStorageKeyWithinRoot(key, root) {
66
- const segments = (root ?? "").split(/[/\\]+/).filter((segment) => !isDotSegment(segment));
67
- if (segments.length === 0) return key.length > 0;
68
- const rootPattern = segments.map(rootSegmentPattern).join("/");
69
- return new RegExp(`^(?:${rootPattern})(?:/|$)`).test(key);
70
- }
71
- //#endregion
72
- export { MAX_STORAGE_KEY_BYTES, decodeStorageKeyClaim, encodeStorageKeyClaim, isStorageKeyWithinRoot };
73
-
74
- //# sourceMappingURL=storage-key-claim.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"storage-key-claim.js","names":[],"sources":["../../src/storage/storage-key-claim.ts"],"sourcesContent":["/** R2-compatible object-key claim bound. Keeps decode work predictably small. */\nexport const MAX_STORAGE_KEY_BYTES = 1024;\n\nconst BASE64URL_RE = /^[A-Za-z0-9_-]+$/;\nconst ROOT_TOKEN_PATTERNS: Record<string, string> = {\n date: '\\\\d{4}-\\\\d{2}-\\\\d{2}',\n year: '\\\\d{4}',\n month: '(?:0[1-9]|1[0-2])',\n day: '(?:0[1-9]|[12]\\\\d|3[01])',\n uuid: '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}',\n};\n\n/** Encode an object key as an opaque, canonical base64url query claim. */\nexport function encodeStorageKeyClaim(key: string): string {\n const bytes = new TextEncoder().encode(key);\n if (bytes.byteLength === 0 || bytes.byteLength > MAX_STORAGE_KEY_BYTES) {\n throw new Error(`Storage key must be 1–${MAX_STORAGE_KEY_BYTES} UTF-8 bytes`);\n }\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n/** Decode exactly one canonical base64url layer. Malformed/non-UTF-8 claims return undefined. */\nexport function decodeStorageKeyClaim(claim: string): string | undefined {\n try {\n if (\n claim.length === 0 ||\n claim.length > Math.ceil((MAX_STORAGE_KEY_BYTES * 4) / 3) ||\n !BASE64URL_RE.test(claim) ||\n claim.length % 4 === 1\n ) {\n return undefined;\n }\n const base64 = claim.replace(/-/g, '+').replace(/_/g, '/');\n const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);\n const binary = atob(padded);\n const bytes = new Uint8Array(new ArrayBuffer(binary.length));\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n if (bytes.byteLength === 0 || bytes.byteLength > MAX_STORAGE_KEY_BYTES) return undefined;\n const decoded = new TextDecoder('utf-8', { fatal: true, ignoreBOM: false }).decode(bytes);\n return encodeStorageKeyClaim(decoded) === claim ? decoded : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction isDotSegment(segment: string): boolean {\n let decoded = segment;\n for (let i = 0; i < 2; i++) {\n if (decoded === '' || decoded === '.' || decoded === '..') return true;\n try {\n const next = decodeURIComponent(decoded);\n if (next === decoded) break;\n decoded = next;\n } catch {\n break;\n }\n }\n return decoded === '' || decoded === '.' || decoded === '..';\n}\n\nfunction rootSegmentPattern(segment: string): string {\n let pattern = '';\n let cursor = 0;\n for (const match of segment.matchAll(/\\{(date|year|month|day|uuid)\\}/g)) {\n pattern += segment.slice(cursor, match.index).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n pattern += ROOT_TOKEN_PATTERNS[match[1]!]!;\n cursor = match.index! + match[0].length;\n }\n pattern += segment.slice(cursor).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return pattern;\n}\n\n/** Assert a canonical key is beneath a static or templated configured root. */\nexport function isStorageKeyWithinRoot(key: string, root: string | undefined): boolean {\n const segments = (root ?? '').split(/[/\\\\]+/).filter((segment) => !isDotSegment(segment));\n if (segments.length === 0) return key.length > 0;\n const rootPattern = segments.map(rootSegmentPattern).join('/');\n return new RegExp(`^(?:${rootPattern})(?:/|$)`).test(key);\n}\n"],"mappings":";;AACA,MAAa,wBAAwB;AAErC,MAAM,eAAe;AACrB,MAAM,sBAA8C;CAClD,MAAM;CACN,MAAM;CACN,OAAO;CACP,KAAK;CACL,MAAM;AACR;;AAGA,SAAgB,sBAAsB,KAAqB;CACzD,MAAM,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,GAAG;CAC1C,IAAI,MAAM,eAAe,KAAK,MAAM,aAAa,uBAC/C,MAAM,IAAI,MAAM,yBAAyB,sBAAsB,aAAa;CAE9E,IAAI,SAAS;CACb,KAAK,MAAM,QAAQ,OAAO,UAAU,OAAO,aAAa,IAAI;CAC5D,OAAO,KAAK,MAAM,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,EAAE;AAC/E;;AAGA,SAAgB,sBAAsB,OAAmC;CACvE,IAAI;EACF,IACE,MAAM,WAAW,K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;CACnC;CACA,WAAW,QAAQ,MAAM,MAAM,CAAC,CAAC,QAAQ,uBAAuB,MAAM;CACtE,OAAO;AACT;;AAGA,SAAgB,uBAAuB,KAAa,MAAmC;CACrF,MAAM,YAAY,QAAQ,GAAA,CAAI,MAAM,QAAQ,CAAC,CAAC,QAAQ,YAAY,CAAC,aAAa,OAAO,CAAC;CACxF,IAAI,SAAS,WAAW,GAAG,OAAO,IAAI,SAAS;CAC/C,MAAM,cAAc,SAAS,IAAI,kBAAkB,CAAC,CAAC,KAAK,GAAG;CAC7D,OAAO,IAAI,OAAO,OAAO,YAAY,SAAS,CAAC,CAAC,KAAK,GAAG;AAC1D"}
@@ -1,38 +0,0 @@
1
- import { STORAGE_OPTIONS } from "./storage.tokens.js";
2
- import { R2StorageDriver } from "./r2-storage.driver.js";
3
- import __decorateMetadata from "../_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js";
4
- import __decorateParam from "../_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js";
5
- import __decorate from "../_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js";
6
- import { Inject, Injectable } from "@velajs/vela";
7
- //#region src/storage/storage-manager.service.ts
8
- let StorageManagerService = class StorageManagerService {
9
- options;
10
- constructor(options) {
11
- this.options = options;
12
- }
13
- hasDisk(disk) {
14
- return this.options.disks.some((d) => d.disk === disk);
15
- }
16
- getDiskConfig(disk) {
17
- const config = this.options.disks.find((d) => d.disk === disk);
18
- if (!config) throw new Error(`Storage disk "${disk}" is not configured.`);
19
- return config;
20
- }
21
- getDriver(disk) {
22
- const config = this.getDiskConfig(disk);
23
- return new R2StorageDriver({
24
- disk,
25
- bucket: config.bucket,
26
- secret: this.options.secret
27
- });
28
- }
29
- };
30
- StorageManagerService = __decorate([
31
- Injectable(),
32
- __decorateParam(0, Inject(STORAGE_OPTIONS)),
33
- __decorateMetadata("design:paramtypes", [Object])
34
- ], StorageManagerService);
35
- //#endregion
36
- export { StorageManagerService };
37
-
38
- //# sourceMappingURL=storage-manager.service.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"storage-manager.service.js","names":[],"sources":["../../src/storage/storage-manager.service.ts"],"sourcesContent":["import { Inject, Injectable } from '@velajs/vela';\nimport { R2StorageDriver } from './r2-storage.driver';\nimport { STORAGE_OPTIONS } from './storage.tokens';\nimport type { DiskConfig, StorageModuleOptions } from './storage.types';\n\n@Injectable()\nexport class StorageManagerService {\n constructor(@Inject(STORAGE_OPTIONS) private readonly options: StorageModuleOptions) {}\n\n hasDisk(disk: string): boolean {\n return this.options.disks.some((d) => d.disk === disk);\n }\n\n getDiskConfig(disk: string): DiskConfig {\n const config = this.options.disks.find((d) => d.disk === disk);\n if (!config) throw new Error(`Storage disk \"${disk}\" is not configured.`);\n return config;\n }\n\n getDriver(disk: string): R2StorageDriver {\n const config = this.getDiskConfig(disk);\n return new R2StorageDriver({ disk, bucket: config.bucket, secret: this.options.secret });\n }\n}\n"],"mappings":";;;;;;;AAMO,IAAM,wBAAN,MAAM,sBAAsB;CACqB;CAAtD,YAAY,SAAyE;EAA/B,KAAA,UAAA;CAAgC;CAEtF,QAAQ,MAAuB;EAC7B,OAAO,KAAK,QAAQ,MAAM,MAAM,MAAM,EAAE,SAAS,IAAI;CACvD;CAEA,cAAc,MAA0B;EACtC,MAAM,SAAS,KAAK,QAAQ,MAAM,MAAM,MAAM,EAAE,SAAS,IAAI;EAC7D,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,iBAAiB,KAAK,qBAAqB;EACxE,OAAO;CACT;CAEA,UAAU,MAA+B;EACvC,MAAM,SAAS,KAAK,cAAc,IAAI;EACtC,OAAO,IAAI,gBAAgB;GAAE;GAAM,QAAQ,OAAO;GAAQ,QAAQ,KAAK,QAAQ;EAAO,CAAC;CACzF;AACF;;CAlBC,WAAW;CAEG,gBAAA,GAAA,OAAO,eAAe,CAAA"}
@@ -1,64 +0,0 @@
1
- import { STORAGE_OPTIONS } from "./storage.tokens.js";
2
- import { decodeStorageKeyClaim, isStorageKeyWithinRoot } from "./storage-key-claim.js";
3
- import __decorateMetadata from "../_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js";
4
- import __decorateParam from "../_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js";
5
- import __decorate from "../_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js";
6
- import { StorageManagerService } from "./storage-manager.service.js";
7
- import { Controller, Get, Inject, Req } from "@velajs/vela";
8
- import { joinStoragePath } from "@velajs/vela/storage";
9
- import { STORAGE_SIGNED_URL_PURPOSE, verifySignedUrl } from "@velajs/vela/security";
10
- //#region src/storage/storage.controller.ts
11
- let StorageController = class StorageController {
12
- manager;
13
- options;
14
- constructor(manager, options) {
15
- this.manager = manager;
16
- this.options = options;
17
- }
18
- async download(c) {
19
- const secret = this.options.secret;
20
- if (!secret) return new Response("Storage signing is not configured", { status: 500 });
21
- if (!await verifySignedUrl(c.req.url, secret, {
22
- method: c.req.method,
23
- purpose: STORAGE_SIGNED_URL_PURPOSE
24
- })) return new Response("Invalid or expired URL", { status: 403 });
25
- const url = new URL(c.req.url);
26
- if (url.searchParams.get("method") !== "GET") return new Response("URL is not scoped for reads", { status: 403 });
27
- const disk = c.req.param("disk");
28
- if (!disk || !this.manager.hasDisk(disk)) return new Response("Unknown disk", { status: 404 });
29
- const claim = url.searchParams.get("key");
30
- const decoded = claim ? decodeStorageKeyClaim(claim) : void 0;
31
- if (!decoded) return new Response("Malformed storage key claim", { status: 400 });
32
- const fullPath = joinStoragePath(void 0, decoded);
33
- if (fullPath !== decoded) return new Response("Invalid storage key", { status: 403 });
34
- if (!isStorageKeyWithinRoot(fullPath, this.manager.getDiskConfig(disk).root)) return new Response("Storage key is outside the configured root", { status: 403 });
35
- try {
36
- const result = await this.manager.getDriver(disk).download(fullPath);
37
- const filename = fullPath.split("/").at(-1) || "download";
38
- return new Response(result.toStream(), { headers: {
39
- "content-type": result.contentType || "application/octet-stream",
40
- "content-disposition": `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`,
41
- "x-content-type-options": "nosniff"
42
- } });
43
- } catch {
44
- return new Response("Not found", { status: 404 });
45
- }
46
- }
47
- };
48
- __decorate([
49
- Get("/:disk"),
50
- __decorateParam(0, Req()),
51
- __decorateMetadata("design:type", Function),
52
- __decorateMetadata("design:paramtypes", [Object]),
53
- __decorateMetadata("design:returntype", Promise)
54
- ], StorageController.prototype, "download", null);
55
- StorageController = __decorate([
56
- Controller("storage"),
57
- __decorateParam(0, Inject(StorageManagerService)),
58
- __decorateParam(1, Inject(STORAGE_OPTIONS)),
59
- __decorateMetadata("design:paramtypes", [typeof StorageManagerService === "undefined" ? Object : StorageManagerService, Object])
60
- ], StorageController);
61
- //#endregion
62
- export { StorageController };
63
-
64
- //# sourceMappingURL=storage.controller.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"storage.controller.js","names":[],"sources":["../../src/storage/storage.controller.ts"],"sourcesContent":["import { Controller, Get, Inject, Req } from '@velajs/vela';\nimport { joinStoragePath } from '@velajs/vela/storage';\nimport { STORAGE_SIGNED_URL_PURPOSE, verifySignedUrl } from '@velajs/vela/security';\nimport type { Context } from 'hono';\nimport { STORAGE_OPTIONS } from './storage.tokens';\nimport type { StorageModuleOptions } from './storage.types';\nimport { StorageManagerService } from './storage-manager.service';\nimport { decodeStorageKeyClaim, isStorageKeyWithinRoot } from './storage-key-claim';\n\n/**\n * Presign-proxy: serves objects for HMAC-signed URLs produced by\n * `StorageService.url()`. R2 has no native presign, so a signed URL points here;\n * this route verifies the signature (+expiry) before streaming the object.\n * The FULL object key (root already applied at sign time) is carried as an\n * opaque base64url query claim. The signature is verified before the claim is\n * decoded exactly once and checked against the configured disk root.\n */\n@Controller('storage')\nexport class StorageController {\n constructor(\n @Inject(StorageManagerService) private readonly manager: StorageManagerService,\n @Inject(STORAGE_OPTIONS) private readonly options: StorageModuleOptions,\n ) {}\n\n @Get('/:disk')\n async download(@Req() c: Context): Promise<Response> {\n const secret = this.options.secret;\n if (!secret) return new Response('Storage signing is not configured', { status: 500 });\n\n // Verify the complete path/query capability before inspecting the disk or\n // decoding attacker-controlled claims.\n if (\n !(await verifySignedUrl(c.req.url, secret, {\n method: c.req.method,\n purpose: STORAGE_SIGNED_URL_PURPOSE,\n }))\n ) {\n return new Response('Invalid or expired URL', { status: 403 });\n }\n\n // Enforce the signed `method` scope: this proxy only serves reads, so a URL\n // scoped to PUT/DELETE/HEAD must NOT be honored as a GET (it would over-grant\n // read access relative to the token's intended scope). The param is part of\n // the signed payload, so it is trustworthy once the signature verifies.\n const url = new URL(c.req.url);\n if (url.searchParams.get('method') !== 'GET') {\n return new Response('URL is not scoped for reads', { status: 403 });\n }\n\n const disk = c.req.param('disk');\n if (!disk || !this.manager.hasDisk(disk)) return new Response('Unknown disk', { status: 404 });\n\n const claim = url.searchParams.get('key');\n const decoded = claim ? decodeStorageKeyClaim(claim) : undefined;\n if (!decoded) return new Response('Malformed storage key claim', { status: 400 });\n\n // Canonicalize after the one decode. Signed direct-driver callers cannot\n // smuggle dot segments or non-canonical aliases into the proxy contract.\n const fullPath = joinStoragePath(undefined, decoded);\n if (fullPath !== decoded) return new Response('Invalid storage key', { status: 403 });\n\n if (!isStorageKeyWithinRoot(fullPath, this.manager.getDiskConfig(disk).root)) {\n return new Response('Storage key is outside the configured root', { status: 403 });\n }\n\n try {\n const result = await this.manager.getDriver(disk).download(fullPath);\n const filename = fullPath.split('/').at(-1) || 'download';\n return new Response(result.toStream(), {\n headers: {\n 'content-type': result.contentType || 'application/octet-stream',\n // Objects are untrusted user content. The authenticated API origin\n // never renders them inline (especially HTML/SVG), even when the\n // stored Content-Type is attacker controlled.\n 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`,\n 'x-content-type-options': 'nosniff',\n },\n });\n } catch {\n return new Response('Not found', { status: 404 });\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAkBO,IAAM,oBAAN,MAAM,kBAAkB;CAEqB;C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AAC,GAAG,EAAE,KAAK;GAC/C,OAAO,IAAI,SAAS,OAAO,SAAS,GAAG,EACrC,SAAS;IACP,gBAAgB,OAAO,eAAe;IAItC,uBAAuB,gCAAgC,mBAAmB,QAAQ;IAClF,0BAA0B;GAC5B,EACF,CAAC;EACH,QAAQ;GACN,OAAO,IAAI,SAAS,aAAa,EAAE,QAAQ,IAAI,CAAC;EAClD;CACF;AACF;;CA1DG,IAAI,QAAQ;CACG,gBAAA,GAAA,IAAI,CAAA;;;;;;CARrB,WAAW,SAAS;CAGhB,gBAAA,GAAA,OAAO,qBAAqB,CAAA;CAC5B,gBAAA,GAAA,OAAO,eAAe,CAAA"}
@@ -1,25 +0,0 @@
1
- import { STORAGE_OPTIONS } from "./storage.tokens.js";
2
- import __decorate from "../_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js";
3
- import { StorageManagerService } from "./storage-manager.service.js";
4
- import { StorageController } from "./storage.controller.js";
5
- import { StorageService } from "./storage.service.js";
6
- import { ConfigurableModuleBuilder, Module } from "@velajs/vela";
7
- //#region src/storage/storage.module.ts
8
- const { ConfigurableModuleClass } = new ConfigurableModuleBuilder({
9
- moduleName: "Storage",
10
- optionsInjectionToken: STORAGE_OPTIONS
11
- }).build();
12
- let StorageModule = class StorageModule extends ConfigurableModuleClass {};
13
- StorageModule = __decorate([Module({
14
- providers: [StorageManagerService, StorageService],
15
- controllers: [StorageController],
16
- exports: [
17
- StorageService,
18
- StorageManagerService,
19
- STORAGE_OPTIONS
20
- ]
21
- })], StorageModule);
22
- //#endregion
23
- export { StorageModule };
24
-
25
- //# sourceMappingURL=storage.module.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"storage.module.js","names":[],"sources":["../../src/storage/storage.module.ts"],"sourcesContent":["import { ConfigurableModuleBuilder, Module } from '@velajs/vela';\nimport { StorageController } from './storage.controller';\nimport { StorageManagerService } from './storage-manager.service';\nimport { StorageService } from './storage.service';\nimport { STORAGE_OPTIONS } from './storage.tokens';\nimport type { StorageModuleOptions } from './storage.types';\n\nconst { ConfigurableModuleClass } = new ConfigurableModuleBuilder<StorageModuleOptions>({\n moduleName: 'Storage',\n optionsInjectionToken: STORAGE_OPTIONS,\n}).build();\n\n@Module({\n providers: [StorageManagerService, StorageService],\n controllers: [StorageController],\n exports: [StorageService, StorageManagerService, STORAGE_OPTIONS],\n})\nexport class StorageModule extends ConfigurableModuleClass {}\n"],"mappings":";;;;;;;AAOA,MAAM,EAAE,4BAA4B,IAAI,0BAAgD;CACtF,YAAY;CACZ,uBAAuB;AACzB,CAAC,CAAC,CAAC,MAAM;AAOF,IAAM,gBAAN,MAAM,sBAAsB,wBAAwB,CAAC;AAL3D,gBAAA,WAAA,CAAA,OAAO;CACN,WAAW,CAAC,uBAAuB,cAAc;CACjD,aAAa,CAAC,iBAAiB;CAC/B,SAAS;EAAC;EAAgB;EAAuB;CAAe;AAClE,CAAC,CAAA,GAAA,aAAA"}
@@ -1,64 +0,0 @@
1
- import { STORAGE_OPTIONS } from "./storage.tokens.js";
2
- import __decorateMetadata from "../_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateMetadata.js";
3
- import __decorateParam from "../_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorateParam.js";
4
- import __decorate from "../_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js";
5
- import { StorageManagerService } from "./storage-manager.service.js";
6
- import { Inject, Injectable } from "@velajs/vela";
7
- import { joinStoragePath } from "@velajs/vela/storage";
8
- //#region src/storage/storage.service.ts
9
- const DEFAULT_PRESIGN = {
10
- defaultExpiry: 3600,
11
- maxExpiry: 86400
12
- };
13
- let StorageService = class StorageService {
14
- options;
15
- manager;
16
- constructor(options, manager) {
17
- this.options = options;
18
- this.manager = manager;
19
- }
20
- put(relativePath, body, options = {}, disk) {
21
- const name = this.resolveDisk(disk);
22
- return this.manager.getDriver(name).upload(body, this.fullPath(relativePath, name), options);
23
- }
24
- get(relativePath, disk) {
25
- const name = this.resolveDisk(disk);
26
- return this.manager.getDriver(name).download(this.fullPath(relativePath, name));
27
- }
28
- delete(relativePath, disk) {
29
- const name = this.resolveDisk(disk);
30
- return this.manager.getDriver(name).delete(this.fullPath(relativePath, name));
31
- }
32
- exists(relativePath, disk) {
33
- const name = this.resolveDisk(disk);
34
- return this.manager.getDriver(name).exists(this.fullPath(relativePath, name));
35
- }
36
- url(relativePath, method = "GET", expiresIn, disk) {
37
- const name = this.resolveDisk(disk);
38
- return this.manager.getDriver(name).getPresignedUrl(this.fullPath(relativePath, name), method, this.validateExpiry(expiresIn));
39
- }
40
- resolveDisk(disk) {
41
- const name = disk ?? this.options.defaultDisk;
42
- if (!this.manager.hasDisk(name)) throw new Error(`Storage disk "${name}" is not configured.`);
43
- return name;
44
- }
45
- fullPath(relativePath, disk) {
46
- return joinStoragePath(this.manager.getDiskConfig(disk).root, relativePath);
47
- }
48
- validateExpiry(expiresIn) {
49
- const cfg = this.options.presignedUrl ?? DEFAULT_PRESIGN;
50
- const value = expiresIn ?? cfg.defaultExpiry;
51
- if (!Number.isSafeInteger(value) || value < 1 || value > cfg.maxExpiry) throw new Error(`Presigned URL expiry ${value}s is out of range (1–${cfg.maxExpiry}s).`);
52
- return value;
53
- }
54
- };
55
- StorageService = __decorate([
56
- Injectable(),
57
- __decorateParam(0, Inject(STORAGE_OPTIONS)),
58
- __decorateParam(1, Inject(StorageManagerService)),
59
- __decorateMetadata("design:paramtypes", [Object, typeof StorageManagerService === "undefined" ? Object : StorageManagerService])
60
- ], StorageService);
61
- //#endregion
62
- export { StorageService };
63
-
64
- //# sourceMappingURL=storage.service.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"storage.service.js","names":[],"sources":["../../src/storage/storage.service.ts"],"sourcesContent":["import { Inject, Injectable } from '@velajs/vela';\nimport {\n joinStoragePath,\n type DownloadResult,\n type PresignedUrlResult,\n type PresignMethod,\n type StorageBody,\n type UploadOptions,\n type UploadResult,\n} from '@velajs/vela/storage';\nimport { StorageManagerService } from './storage-manager.service';\nimport { STORAGE_OPTIONS } from './storage.tokens';\nimport type { StorageModuleOptions } from './storage.types';\n\nconst DEFAULT_PRESIGN = { defaultExpiry: 3600, maxExpiry: 86400 };\n\n/**\n * Multi-disk storage facade. Applies each disk's (templated) root, resolves the\n * driver, and validates presign expiry. Injectable anywhere via `StorageService`.\n */\n@Injectable()\nexport class StorageService {\n constructor(\n @Inject(STORAGE_OPTIONS) private readonly options: StorageModuleOptions,\n @Inject(StorageManagerService) private readonly manager: StorageManagerService,\n ) {}\n\n put(\n relativePath: string,\n body: StorageBody,\n options: UploadOptions = {},\n disk?: string,\n ): Promise<UploadResult> {\n const name = this.resolveDisk(disk);\n return this.manager.getDriver(name).upload(body, this.fullPath(relativePath, name), options);\n }\n\n get(relativePath: string, disk?: string): Promise<DownloadResult> {\n const name = this.resolveDisk(disk);\n return this.manager.getDriver(name).download(this.fullPath(relativePath, name));\n }\n\n delete(relativePath: string, disk?: string): Promise<void> {\n const name = this.resolveDisk(disk);\n return this.manager.getDriver(name).delete(this.fullPath(relativePath, name));\n }\n\n exists(relativePath: string, disk?: string): Promise<boolean> {\n const name = this.resolveDisk(disk);\n return this.manager.getDriver(name).exists(this.fullPath(relativePath, name));\n }\n\n url(\n relativePath: string,\n method: PresignMethod = 'GET',\n expiresIn?: number,\n disk?: string,\n ): Promise<PresignedUrlResult> {\n const name = this.resolveDisk(disk);\n return this.manager\n .getDriver(name)\n .getPresignedUrl(this.fullPath(relativePath, name), method, this.validateExpiry(expiresIn));\n }\n\n private resolveDisk(disk?: string): string {\n const name = disk ?? this.options.defaultDisk;\n if (!this.manager.hasDisk(name)) throw new Error(`Storage disk \"${name}\" is not configured.`);\n return name;\n }\n\n private fullPath(relativePath: string, disk: string): string {\n return joinStoragePath(this.manager.getDiskConfig(disk).root, relativePath);\n }\n\n private validateExpiry(expiresIn?: number): number {\n const cfg = this.options.presignedUrl ?? DEFAULT_PRESIGN;\n const value = expiresIn ?? cfg.defaultExpiry;\n // `Number.isSafeInteger` rejects NaN/fractional/infinite values — otherwise\n // `NaN < 1 || NaN > max` is false,\n // NaN slips through, signUrl omits `expires`, and the URL never expires.\n if (!Number.isSafeInteger(value) || value < 1 || value > cfg.maxExpiry) {\n throw new Error(`Presigned URL expiry ${value}s is out of range (1–${cfg.maxExpiry}s).`);\n }\n return value;\n }\n}\n"],"mappings":";;;;;;;;AAcA,MAAM,kBAAkB;CAAE,eAAe;CAAM,WAAW;AAAM;AAOzD,IAAM,iBAAN,MAAM,eAAe;CAEkB;CACM;CAFlD,YACE,SACA,SACA;EAF0C,KAAA,UAAA;EACM,KAAA,UAAA;CAC/C;CAEH,IACE,cACA,MACA,UAAyB,CAAC,GAC1B,MACuB;EACvB,MAAM,OAAO,KAAK,YAAY,IAAI;EAClC,OAAO,KAAK,QAAQ,UAAU,IAAI,CAAC,CAAC,OAAO,MAAM,KAAK,SAAS,cAAc,IAAI,GAAG,OAAO;CAC7F;CAEA,IAAI,cAAsB,MAAwC;EAChE,MAAM,OAAO,KAAK,YAAY,IAAI;EAClC,OAAO,KAAK,QAAQ,UAAU,IAAI,CAAC,CAAC,SAAS,KAAK,SAAS,cAAc,IAAI,CAAC;CAChF;CAEA,OAAO,cAAsB,MAA8B;EACzD,MAAM,OAAO,KAAK,YAAY,IAAI;EAClC,OAAO,KAAK,QAAQ,UAAU,IAAI,CAAC,CAAC,OAAO,KAAK,SAAS,cAAc,IAAI,CAAC;CAC9E;CAEA,OAAO,cAAsB,MAAiC;EAC5D,MAAM,OAAO,KAAK,YAAY,IAAI;EAClC,OAAO,KAAK,QAAQ,UAAU,IAAI,CAAC,CAAC,OAAO,KAAK,SAAS,cAAc,IAAI,CAAC;CAC9E;CAEA,IACE,cACA,SAAwB,OACxB,WACA,MAC6B;EAC7B,MAAM,OAAO,KAAK,YAAY,IAAI;EAClC,OAAO,KAAK,QACT,UAAU,IAAI,CAAC,CACf,gBAAgB,KAAK,SAAS,cAAc,IAAI,GAAG,QAAQ,KAAK,eAAe,SAAS,CAAC;CAC9F;CAEA,YAAoB,MAAuB;EACzC,MAAM,OAAO,QAAQ,KAAK,QAAQ;EAClC,IAAI,CAAC,KAAK,QAAQ,QAAQ,IAAI,GAAG,MAAM,IAAI,MAAM,iBAAiB,KAAK,qBAAqB;EAC5F,OAAO;CACT;CAEA,SAAiB,cAAsB,MAAsB;EAC3D,OAAO,gBAAgB,KAAK,QAAQ,cAAc,IAAI,CAAC,CAAC,MAAM,YAAY;CAC5E;CAEA,eAAuB,WAA4B;EACjD,MAAM,MAAM,KAAK,QAAQ,gBAAgB;EACzC,MAAM,QAAQ,aAAa,IAAI;EAI/B,IAAI,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ,KAAK,QAAQ,IAAI,WAC3D,MAAM,IAAI,MAAM,wBAAwB,MAAM,uBAAuB,IAAI,UAAU,IAAI;EAEzF,OAAO;CACT;AACF;;CAjEC,WAAW;CAGP,gBAAA,GAAA,OAAO,eAAe,CAAA;CACtB,gBAAA,GAAA,OAAO,qBAAqB,CAAA"}
@@ -1,7 +0,0 @@
1
- import { InjectionToken } from "@velajs/vela";
2
- //#region src/storage/storage.tokens.ts
3
- const STORAGE_OPTIONS = new InjectionToken("STORAGE_OPTIONS");
4
- //#endregion
5
- export { STORAGE_OPTIONS };
6
-
7
- //# sourceMappingURL=storage.tokens.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"storage.tokens.js","names":[],"sources":["../../src/storage/storage.tokens.ts"],"sourcesContent":["import { InjectionToken } from '@velajs/vela';\nimport type { StorageModuleOptions } from './storage.types';\n\nexport const STORAGE_OPTIONS = new InjectionToken<StorageModuleOptions>('STORAGE_OPTIONS');\n"],"mappings":";;AAGA,MAAa,kBAAkB,IAAI,eAAqC,iBAAiB"}
@@ -1,32 +0,0 @@
1
- import { roomToDurableId } from "./room-id.js";
2
- import { DEFAULT_WS_MAX_FRAME_BYTES, assertBroadcastCommandFits, resolveMaxFrameBytes } from "@velajs/vela/websocket";
3
- //#region src/websocket/broadcast.ts
4
- /**
5
- * Push to a room from a Worker HTTP handler / cron / queue consumer (server-
6
- * initiated emit). Resolves the room's Durable Object and calls its `broadcast`
7
- * RPC method — the same canonical room→DO mapping the upgrade route uses, so it
8
- * always reaches the DO holding those sockets.
9
- *
10
- * @example
11
- * ```ts
12
- * // In a controller — ns from the typed Worker environment
13
- * await broadcastToRoom(ns, '/orgs/:orgId/ws', `org:${id}`, 'order.created', order);
14
- * ```
15
- */
16
- async function broadcastToRoom(ns, gatewayPath, room, event, data, options) {
17
- const cmd = {
18
- rooms: [room],
19
- exceptIds: options?.exceptIds,
20
- frame: JSON.stringify({
21
- event,
22
- data
23
- })
24
- };
25
- const maxFrameBytes = resolveMaxFrameBytes({ maxFrameBytes: options?.maxFrameBytes ?? DEFAULT_WS_MAX_FRAME_BYTES });
26
- assertBroadcastCommandFits(cmd, maxFrameBytes);
27
- await ns.get(roomToDurableId(ns, gatewayPath, room)).broadcast(cmd);
28
- }
29
- //#endregion
30
- export { broadcastToRoom };
31
-
32
- //# sourceMappingURL=broadcast.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"broadcast.js","names":[],"sources":["../../src/websocket/broadcast.ts"],"sourcesContent":["import {\n assertBroadcastCommandFits,\n DEFAULT_WS_MAX_FRAME_BYTES,\n resolveMaxFrameBytes,\n} from '@velajs/vela/websocket';\nimport type { BroadcastCommand } from '@velajs/vela/websocket';\nimport { roomToDurableId } from './room-id';\n\nexport interface WsBroadcastStub {\n broadcast(cmd: BroadcastCommand): Promise<void>;\n}\n\nexport interface BroadcastNamespace {\n idFromName(name: string): DurableObjectId;\n get(id: DurableObjectId): WsBroadcastStub;\n}\n\n/**\n * Push to a room from a Worker HTTP handler / cron / queue consumer (server-\n * initiated emit). Resolves the room's Durable Object and calls its `broadcast`\n * RPC method — the same canonical room→DO mapping the upgrade route uses, so it\n * always reaches the DO holding those sockets.\n *\n * @example\n * ```ts\n * // In a controller — ns from the typed Worker environment\n * await broadcastToRoom(ns, '/orgs/:orgId/ws', `org:${id}`, 'order.created', order);\n * ```\n */\nexport async function broadcastToRoom(\n ns: BroadcastNamespace,\n gatewayPath: string,\n room: string,\n event: string,\n data?: unknown,\n options?: { exceptIds?: string[]; maxFrameBytes?: number },\n): Promise<void> {\n const cmd: BroadcastCommand = {\n rooms: [room],\n exceptIds: options?.exceptIds,\n frame: JSON.stringify({ event, data }),\n };\n const maxFrameBytes = resolveMaxFrameBytes({\n maxFrameBytes: options?.maxFrameBytes ?? DEFAULT_WS_MAX_FRAME_BYTES,\n });\n assertBroadcastCommandFits(cmd, maxFrameBytes);\n const stub = ns.get(roomToDurableId(ns, gatewayPath, room));\n await stub.broadcast(cmd);\n}\n"],"mappings":";;;;;;;;;;;;;;;AA6BA,eAAsB,gBACpB,IACA,aACA,MACA,OACA,MACA,SACe;CACf,MAAM,MAAwB;EAC5B,OAAO,CAAC,IAAI;EACZ,WAAW,SAAS;EACpB,OAAO,KAAK,UAAU;GAAE;GAAO;EAAK,CAAC;CACvC;CACA,MAAM,gBAAgB,qBAAqB,EACzC,eAAe,SAAS,iBAAiB,2BAC3C,CAAC;CACD,2BAA2B,KAAK,aAAa;CAE7C,MADa,GAAG,IAAI,gBAAgB,IAAI,aAAa,IAAI,CAChD,CAAC,CAAC,UAAU,GAAG;AAC1B"}
@@ -1,25 +0,0 @@
1
- import { WsServerHolder } from "./ws-server-holder.js";
2
- import { defineProvider } from "@velajs/vela";
3
- import { WS_SERVER, WsDispatcher } from "@velajs/vela/websocket";
4
- //#region src/websocket/cloudflare-websocket.module.ts
5
- /**
6
- * Cloudflare counterpart to the core `WebSocketModule.forRoot()`. Import this in
7
- * your `AppModule` instead: it provides the gateway dispatcher plus a late-bound
8
- * `WS_SERVER` (`WsServerHolder`) that the WebSocket Durable Object wires to a
9
- * ctx-backed server per instance. `useClass` ensures a fresh holder per DI
10
- * container so colocated DO instances never share a server.
11
- */
12
- var CloudflareWebSocketModule = class CloudflareWebSocketModule {
13
- static forRoot() {
14
- const providers = [defineProvider(WS_SERVER, { useClass: WsServerHolder }), WsDispatcher];
15
- return {
16
- module: CloudflareWebSocketModule,
17
- providers,
18
- exports: [WS_SERVER, WsDispatcher]
19
- };
20
- }
21
- };
22
- //#endregion
23
- export { CloudflareWebSocketModule };
24
-
25
- //# sourceMappingURL=cloudflare-websocket.module.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"cloudflare-websocket.module.js","names":[],"sources":["../../src/websocket/cloudflare-websocket.module.ts"],"sourcesContent":["import { defineProvider, type DynamicModule } from '@velajs/vela';\nimport { WsDispatcher, WS_SERVER } from '@velajs/vela/websocket';\nimport { WsServerHolder } from './ws-server-holder';\n\n/**\n * Cloudflare counterpart to the core `WebSocketModule.forRoot()`. Import this in\n * your `AppModule` instead: it provides the gateway dispatcher plus a late-bound\n * `WS_SERVER` (`WsServerHolder`) that the WebSocket Durable Object wires to a\n * ctx-backed server per instance. `useClass` ensures a fresh holder per DI\n * container so colocated DO instances never share a server.\n */\nexport class CloudflareWebSocketModule {\n static forRoot(): DynamicModule {\n const providers = [defineProvider(WS_SERVER, { useClass: WsServerHolder }), WsDispatcher];\n\n return {\n module: CloudflareWebSocketModule,\n providers,\n exports: [WS_SERVER, WsDispatcher],\n };\n }\n}\n"],"mappings":";;;;;;;;;;;AAWA,IAAa,4BAAb,MAAa,0BAA0B;CACrC,OAAO,UAAyB;EAC9B,MAAM,YAAY,CAAC,eAAe,WAAW,EAAE,UAAU,eAAe,CAAC,GAAG,YAAY;EAExF,OAAO;GACL,QAAQ;GACR;GACA,SAAS,CAAC,WAAW,YAAY;EACnC;CACF;AACF"}
@@ -1,133 +0,0 @@
1
- import { durableObjectRoomName } from "./room-id.js";
2
- import { getMetadata, getTrustedRequestIdentity } from "@velajs/vela/module-kit";
3
- import { WS_GATEWAY_METADATA, createWebSocketUpgradeGate, resolveGatewayRoomId, resolveGatewayRoomParam, resolveMaxFrameBytes } from "@velajs/vela/websocket";
4
- //#region src/websocket/websocket-routing.ts
5
- const MAX_IDENTITY_FIELD_BYTES = 2048;
6
- const encoder = new TextEncoder();
7
- function isIdentityField(value) {
8
- return typeof value === "string" && value.length > 0 && !value.includes("\r") && !value.includes("\n") && encoder.encode(value).byteLength <= MAX_IDENTITY_FIELD_BYTES;
9
- }
10
- /** `null` means an identity was present but violated the transport contract. */
11
- function accessIdentity(c) {
12
- const value = getTrustedRequestIdentity(c.req.raw);
13
- if (!value) return void 0;
14
- const { principal, tenantId, expiresAtMs } = value;
15
- if (!isIdentityField(principal.issuer) || !isIdentityField(principal.subject) || !isIdentityField(tenantId) || typeof expiresAtMs !== "number" || !Number.isSafeInteger(expiresAtMs) || expiresAtMs <= 0) return null;
16
- return {
17
- principal,
18
- tenantId,
19
- expiresAtMs
20
- };
21
- }
22
- /** `null` means two independently verified identities disagree. */
23
- function combineIdentities(requestIdentity, upgradeIdentity) {
24
- if (!requestIdentity && !upgradeIdentity) return void 0;
25
- if (!requestIdentity) return upgradeIdentity;
26
- if (!upgradeIdentity) return requestIdentity;
27
- if (requestIdentity.principal.issuer !== upgradeIdentity.principal.issuer || requestIdentity.principal.subject !== upgradeIdentity.principal.subject || requestIdentity.principal.principalType !== upgradeIdentity.principal.principalType || requestIdentity.tenantId !== upgradeIdentity.tenantId) return null;
28
- return {
29
- principal: { ...upgradeIdentity.principal },
30
- tenantId: upgradeIdentity.tenantId,
31
- expiresAtMs: Math.min(requestIdentity.expiresAtMs, upgradeIdentity.expiresAtMs)
32
- };
33
- }
34
- /** An instance's constructor is the class token its module registered. */
35
- function isClass(value) {
36
- return typeof value === "function";
37
- }
38
- /**
39
- * Read `@WebSocketGateway({ path, binding })` off a resolved instance (CF-hosted
40
- * gateways only). The application container names the module that declares the
41
- * gateway when exactly one module registers it.
42
- */
43
- function collectWsGatewayRoutes(instance, container) {
44
- const options = getMetadata(WS_GATEWAY_METADATA, instance.constructor);
45
- if (!options?.path || !options?.binding) return [];
46
- resolveGatewayRoomParam(options);
47
- resolveMaxFrameBytes(options);
48
- const gateway = instance.constructor;
49
- const owners = isClass(gateway) ? container.getOwnerModuleIds(gateway) : [];
50
- return [{
51
- path: options.path,
52
- binding: options.binding,
53
- options: { ...options },
54
- ...owners.length === 1 ? { moduleId: owners[0] } : {}
55
- }];
56
- }
57
- /**
58
- * Registers the upgrade routes on the Worker's Hono app. Each route validates
59
- * the `Upgrade` header, authenticates through the gateway's authenticator
60
- * (resolved once from `container`, the application's DI container), resolves
61
- * the room's Durable Object, and forwards the raw request — injecting
62
- * spoof-safe `x-vela-*` headers the DO reads. The DO returns the `101` with the
63
- * client socket.
64
- */
65
- function registerWebSocketRoutes(hono, routes, container) {
66
- for (const route of routes) {
67
- const authenticate = createWebSocketUpgradeGate(container, route);
68
- hono.get(route.path, async (c) => {
69
- if (c.req.header("upgrade")?.toLowerCase() !== "websocket") return c.text("Expected WebSocket upgrade", 426);
70
- const headers = new Headers(c.req.raw.headers);
71
- headers.delete("x-vela-room");
72
- headers.delete("x-vela-path");
73
- headers.delete("x-vela-user");
74
- headers.delete("x-vela-expires-at");
75
- headers.delete("x-vela-expires-at-ms");
76
- headers.delete("x-vela-issuer");
77
- headers.delete("x-vela-subject");
78
- headers.delete("x-vela-principal-type");
79
- headers.delete("x-vela-tenant");
80
- const sanitizedRequest = new Request(c.req.raw, { headers });
81
- let roomId;
82
- try {
83
- roomId = resolveGatewayRoomId(route.options, (name) => c.req.param(name));
84
- } catch {
85
- return c.text("Invalid WebSocket room", 400);
86
- }
87
- const upgrade = await authenticate(sanitizedRequest, roomId);
88
- if (upgrade === false) return c.text("WebSocket upgrade forbidden", 403);
89
- const requestIdentity = accessIdentity(c);
90
- if (requestIdentity === null) return c.text("Invalid WebSocket identity", 403);
91
- const identity = combineIdentities(requestIdentity, upgrade.identity);
92
- if (identity === null) return c.text("Conflicting WebSocket identities", 403);
93
- if (identity && identity.expiresAtMs <= Date.now()) return c.text("WebSocket identity expired", 403);
94
- const forwardHeaders = new Headers(upgrade.request.headers);
95
- forwardHeaders.set("x-vela-room", roomId);
96
- forwardHeaders.set("x-vela-path", route.path);
97
- if (identity) {
98
- forwardHeaders.set("x-vela-user", identity.principal.subject);
99
- forwardHeaders.set("x-vela-issuer", identity.principal.issuer);
100
- forwardHeaders.set("x-vela-subject", identity.principal.subject);
101
- forwardHeaders.set("x-vela-principal-type", identity.principal.principalType);
102
- forwardHeaders.set("x-vela-tenant", identity.tenantId);
103
- forwardHeaders.set("x-vela-expires-at-ms", String(identity.expiresAtMs));
104
- }
105
- return forwardToRoom(c.env, route.binding, route.path, roomId, new Request(upgrade.request, { headers: forwardHeaders }));
106
- });
107
- }
108
- }
109
- /**
110
- * Gateway metadata contains a runtime binding name, so the native type is
111
- * erased. Validate only the operations consumed here and their observable
112
- * results; never assert that an arbitrary value implements a native namespace.
113
- */
114
- async function forwardToRoom(env, binding, path, room, request) {
115
- if (typeof env !== "object" || env === null) throw new Error("Worker environment is missing");
116
- const namespace = Reflect.get(env, binding);
117
- if (typeof namespace !== "object" || namespace === null) return new Response(`Durable Object binding '${binding}' is not configured`, { status: 500 });
118
- const idFromName = Reflect.get(namespace, "idFromName");
119
- const get = Reflect.get(namespace, "get");
120
- if (typeof idFromName !== "function" || typeof get !== "function") throw new Error("Invalid Durable Object namespace");
121
- const id = Reflect.apply(idFromName, namespace, [durableObjectRoomName(path, room)]);
122
- const stub = Reflect.apply(get, namespace, [id]);
123
- if (typeof stub !== "object" || stub === null) throw new Error("Invalid Durable Object stub");
124
- const fetch = Reflect.get(stub, "fetch");
125
- if (typeof fetch !== "function") throw new Error("Durable Object stub has no fetch operation");
126
- const response = await Reflect.apply(fetch, stub, [request]);
127
- if (!(response instanceof Response)) throw new Error("Durable Object returned an invalid response");
128
- return response;
129
- }
130
- //#endregion
131
- export { collectWsGatewayRoutes, registerWebSocketRoutes };
132
-
133
- //# sourceMappingURL=websocket-routing.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"websocket-routing.js","names":[],"sources":["../../src/websocket/websocket-routing.ts"],"sourcesContent":["import type { Type, VelaContext as Context, VelaHono as Hono } from '@velajs/vela';\nimport type { Container } from '@velajs/vela/module-kit';\nimport { getMetadata, getTrustedRequestIdentity } from '@velajs/vela/module-kit';\nimport {\n createWebSocketUpgradeGate,\n resolveGatewayRoomId,\n resolveGatewayRoomParam,\n resolveMaxFrameBytes,\n WS_GATEWAY_METADATA,\n type WebSocketGatewayOptions,\n type WebSocketUpgradeIdentity,\n} from '@velajs/vela/websocket';\nimport { durableObjectRoomName } from './room-id';\n\nexport interface WsGatewayRoute {\n path: string;\n binding: string;\n options: WebSocketGatewayOptions;\n /** Container module that declares the gateway; its authenticator resolves from here. */\n moduleId?: string;\n}\n\nconst MAX_IDENTITY_FIELD_BYTES = 2048;\nconst encoder = new TextEncoder();\n\ntype PrincipalType = 'user' | 'service';\n\ninterface ForwardedIdentity extends WebSocketUpgradeIdentity {\n principal: {\n issuer: string;\n subject: string;\n principalType: PrincipalType;\n };\n tenantId: string;\n expiresAtMs: number;\n}\n\nfunction isIdentityField(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n value.length > 0 &&\n !value.includes('\\r') &&\n !value.includes('\\n') &&\n encoder.encode(value).byteLength <= MAX_IDENTITY_FIELD_BYTES\n );\n}\n\n/** `null` means an identity was present but violated the transport contract. */\nfunction accessIdentity(c: Context): ForwardedIdentity | null | undefined {\n const value = getTrustedRequestIdentity(c.req.raw);\n if (!value) return undefined;\n const { principal, tenantId, expiresAtMs } = value;\n if (\n !isIdentityField(principal.issuer) ||\n !isIdentityField(principal.subject) ||\n !isIdentityField(tenantId) ||\n typeof expiresAtMs !== 'number' ||\n !Number.isSafeInteger(expiresAtMs) ||\n expiresAtMs <= 0\n )\n return null;\n return { principal, tenantId, expiresAtMs };\n}\n\n/** `null` means two independently verified identities disagree. */\nfunction combineIdentities(\n requestIdentity: ForwardedIdentity | undefined,\n upgradeIdentity: WebSocketUpgradeIdentity | undefined,\n): ForwardedIdentity | null | undefined {\n if (!requestIdentity && !upgradeIdentity) return undefined;\n if (!requestIdentity) return upgradeIdentity;\n if (!upgradeIdentity) return requestIdentity;\n if (\n requestIdentity.principal.issuer !== upgradeIdentity.principal.issuer ||\n requestIdentity.principal.subject !== upgradeIdentity.principal.subject ||\n requestIdentity.principal.principalType !== upgradeIdentity.principal.principalType ||\n requestIdentity.tenantId !== upgradeIdentity.tenantId\n ) {\n return null;\n }\n return {\n principal: { ...upgradeIdentity.principal },\n tenantId: upgradeIdentity.tenantId,\n expiresAtMs: Math.min(requestIdentity.expiresAtMs, upgradeIdentity.expiresAtMs),\n };\n}\n\n/** An instance's constructor is the class token its module registered. */\nfunction isClass(value: unknown): value is Type {\n return typeof value === 'function';\n}\n\n/**\n * Read `@WebSocketGateway({ path, binding })` off a resolved instance (CF-hosted\n * gateways only). The application container names the module that declares the\n * gateway when exactly one module registers it.\n */\nexport function collectWsGatewayRoutes(instance: object, container: Container): WsGatewayRoute[] {\n // Decorator metadata is the framework's explicit reflection boundary.\n const options = getMetadata<WebSocketGatewayOptions>(WS_GATEWAY_METADATA, instance.constructor);\n if (!options?.path || !options?.binding) return [];\n resolveGatewayRoomParam(options);\n resolveMaxFrameBytes(options);\n const gateway: unknown = instance.constructor;\n const owners = isClass(gateway) ? container.getOwnerModuleIds(gateway) : [];\n return [\n {\n path: options.path,\n binding: options.binding,\n options: { ...options },\n ...(owners.length === 1 ? { moduleId: owners[0] } : {}),\n },\n ];\n}\n\n/**\n * Registers the upgrade routes on the Worker's Hono app. Each route validates\n * the `Upgrade` header, authenticates through the gateway's authenticator\n * (resolved once from `container`, the application's DI container), resolves\n * the room's Durable Object, and forwards the raw request — injecting\n * spoof-safe `x-vela-*` headers the DO reads. The DO returns the `101` with the\n * client socket.\n */\nexport function registerWebSocketRoutes(\n hono: Hono,\n routes: WsGatewayRoute[],\n container: Container,\n): void {\n for (const route of routes) {\n const authenticate = createWebSocketUpgradeGate(container, route);\n hono.get(route.path, async (c: Context) => {\n if (c.req.header('upgrade')?.toLowerCase() !== 'websocket') {\n return c.text('Expected WebSocket upgrade', 426);\n }\n\n // Internal transport headers are never application credentials. Remove\n // client-supplied values before even the pre-allocation authorization\n // hook sees the request, then populate trusted values below.\n const headers = new Headers(c.req.raw.headers);\n headers.delete('x-vela-room');\n headers.delete('x-vela-path');\n headers.delete('x-vela-user');\n headers.delete('x-vela-expires-at');\n headers.delete('x-vela-expires-at-ms');\n headers.delete('x-vela-issuer');\n headers.delete('x-vela-subject');\n headers.delete('x-vela-principal-type');\n headers.delete('x-vela-tenant');\n const sanitizedRequest = new Request(c.req.raw, { headers });\n\n let roomId: string;\n try {\n roomId = resolveGatewayRoomId(route.options, (name) => c.req.param(name));\n } catch {\n return c.text('Invalid WebSocket room', 400);\n }\n\n // Origin, application authorization, and ticket/cookie authentication\n // all complete before the gateway Durable Object id is resolved.\n const upgrade = await authenticate(sanitizedRequest, roomId);\n if (upgrade === false) return c.text('WebSocket upgrade forbidden', 403);\n\n const requestIdentity = accessIdentity(c);\n if (requestIdentity === null) return c.text('Invalid WebSocket identity', 403);\n const identity = combineIdentities(requestIdentity, upgrade.identity);\n if (identity === null) return c.text('Conflicting WebSocket identities', 403);\n if (identity && identity.expiresAtMs <= Date.now()) {\n return c.text('WebSocket identity expired', 403);\n }\n\n // Populate the ticket-free forwarding request with trusted server values.\n const forwardHeaders = new Headers(upgrade.request.headers);\n forwardHeaders.set('x-vela-room', roomId);\n forwardHeaders.set('x-vela-path', route.path);\n if (identity) {\n forwardHeaders.set('x-vela-user', identity.principal.subject);\n forwardHeaders.set('x-vela-issuer', identity.principal.issuer);\n forwardHeaders.set('x-vela-subject', identity.principal.subject);\n forwardHeaders.set('x-vela-principal-type', identity.principal.principalType);\n forwardHeaders.set('x-vela-tenant', identity.tenantId);\n forwardHeaders.set('x-vela-expires-at-ms', String(identity.expiresAtMs));\n }\n\n return forwardToRoom(\n c.env,\n route.binding,\n route.path,\n roomId,\n new Request(upgrade.request, { headers: forwardHeaders }),\n );\n });\n }\n}\n\n/**\n * Gateway metadata contains a runtime binding name, so the native type is\n * erased. Validate only the operations consumed here and their observable\n * results; never assert that an arbitrary value implements a native namespace.\n */\nasync function forwardToRoom(\n env: unknown,\n binding: string,\n path: string,\n room: string,\n request: Request,\n): Promise<Response> {\n if (typeof env !== 'object' || env === null) throw new Error('Worker environment is missing');\n const namespace: unknown = Reflect.get(env, binding);\n if (typeof namespace !== 'object' || namespace === null) {\n return new Response(`Durable Object binding '${binding}' is not configured`, { status: 500 });\n }\n const idFromName: unknown = Reflect.get(namespace, 'idFromName');\n const get: unknown = Reflect.get(namespace, 'get');\n if (typeof idFromName !== 'function' || typeof get !== 'function') {\n throw new Error('Invalid Durable Object namespace');\n }\n const id: unknown = Reflect.apply(idFromName, namespace, [durableObjectRoomName(path, room)]);\n const stub: unknown = Reflect.apply(get, namespace, [id]);\n if (typeof stub !== 'object' || stub === null) throw new Error('Invalid Durable Object stub');\n const fetch: unknown = Reflect.get(stub, 'fetch');\n if (typeof fetch !== 'function') throw new Error('Durable Object stub has no fetch operation');\n const response: unknown = await Reflect.apply(fetch, stub, [request]);\n if (!(response instanceof Response))\n throw new Error('Durable Object returned an invalid response');\n return response;\n}\n"],"mappings":";;;;AAsBA,MAAM,2BAA2B;AACjC,MAAM,UAAU,IAAI,YAAY;AAchC,SAAS,gBAAgB,OAAiC;CACxD,OACE,OAAO,UAAU,YACjB,MAAM,SAAS,KACf,CAAC,MAAM,SAAS,IAAI,KACpB,CAAC,MAAM,SAAS,IAAI,KACpB,QAAQ,OAAO,KAAK,CAAC,CAAC,cAAc;AAExC;;AAGA,SAAS,eAAe,GAAkD;CACxE,MAAM,QAAQ,0BAA0B,EAAE,IAAI,GAAG;CACjD,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,MAAM,EAAE,WAAW,UAAU,gBAAgB;CAC7C,IACE,CAAC,gBAAgB,UAAU,MAAM,KACjC,CAAC,gBAAgB,UAAU,OAAO,KAClC,CAAC,gBAAgB,QAAQ,KACzB,OAAO,gBAAgB,YACvB,CAAC,OAAO,cAAc,WAAW,KACjC,eAAe,GAEf,O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_runtime@0.150.0/helpers/esm/decorate.js";
2
- import { Injectable } from "@velajs/vela";
3
- import { resolveMaxFrameBytes } from "@velajs/vela/websocket";
4
- //#region src/websocket/ws-server-holder.ts
5
- let WsServerHolder = class WsServerHolder {
6
- target;
7
- maxFrameBytes;
8
- setTarget(server) {
9
- this.target = server;
10
- if (this.maxFrameBytes !== void 0) server.setOutboundFrameLimit?.(this.maxFrameBytes);
11
- }
12
- setOutboundFrameLimit(maxFrameBytes) {
13
- const resolved = resolveMaxFrameBytes({ maxFrameBytes });
14
- this.maxFrameBytes = this.maxFrameBytes === void 0 ? resolved : Math.max(this.maxFrameBytes, resolved);
15
- this.target?.setOutboundFrameLimit?.(this.maxFrameBytes);
16
- }
17
- get resolved() {
18
- if (!this.target) throw new Error("WebSocket server is only available inside a WebSocket Durable Object. To push from a Worker HTTP handler, use broadcastToRoom(namespace, gatewayPath, room, ...).");
19
- return this.target;
20
- }
21
- emit(event, data) {
22
- return this.resolved.emit(event, data);
23
- }
24
- to(room) {
25
- return this.resolved.to(room);
26
- }
27
- in(room) {
28
- return this.resolved.in(room);
29
- }
30
- except(room) {
31
- return this.resolved.except(room);
32
- }
33
- };
34
- WsServerHolder = __decorate([Injectable()], WsServerHolder);
35
- //#endregion
36
- export { WsServerHolder };
37
-
38
- //# sourceMappingURL=ws-server-holder.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ws-server-holder.js","names":[],"sources":["../../src/websocket/ws-server-holder.ts"],"sourcesContent":["import { Injectable } from '@velajs/vela';\nimport { resolveMaxFrameBytes } from '@velajs/vela/websocket';\nimport type { BroadcastOperator, WsServer } from '@velajs/vela/websocket';\n\n/**\n * Late-bound `WsServer`. Provided as `WS_SERVER` (one per DI container, i.e. per\n * Durable Object instance), then pointed at the ctx-backed server once the DO\n * builds. Gateways inject it via `@WebSocketServer()`; it throws if used before\n * a runtime binds it (e.g. from the stateless Worker isolate).\n */\n@Injectable()\nexport class WsServerHolder implements WsServer {\n private target?: WsServer;\n private maxFrameBytes?: number;\n\n setTarget(server: WsServer): void {\n this.target = server;\n if (this.maxFrameBytes !== undefined) server.setOutboundFrameLimit?.(this.maxFrameBytes);\n }\n\n setOutboundFrameLimit(maxFrameBytes: number): void {\n const resolved = resolveMaxFrameBytes({ maxFrameBytes });\n this.maxFrameBytes =\n this.maxFrameBytes === undefined ? resolved : Math.max(this.maxFrameBytes, resolved);\n this.target?.setOutboundFrameLimit?.(this.maxFrameBytes);\n }\n\n private get resolved(): WsServer {\n if (!this.target) {\n throw new Error(\n 'WebSocket server is only available inside a WebSocket Durable Object. To ' +\n 'push from a Worker HTTP handler, use broadcastToRoom(namespace, gatewayPath, room, ...).',\n );\n }\n return this.target;\n }\n\n emit(event: string, data?: unknown): void | Promise<void> {\n return this.resolved.emit(event, data);\n }\n to(room: string): BroadcastOperator {\n return this.resolved.to(room);\n }\n in(room: string): BroadcastOperator {\n return this.resolved.in(room);\n }\n except(room: string): BroadcastOperator {\n return this.resolved.except(room);\n }\n}\n"],"mappings":";;;;AAWO,IAAM,iBAAN,MAAM,eAAmC;CAC9C;CACA;CAEA,UAAU,QAAwB;EAChC,KAAK,SAAS;EACd,IAAI,KAAK,kBAAkB,KAAA,GAAW,OAAO,wBAAwB,KAAK,aAAa;CACzF;CAEA,sBAAsB,eAA6B;EACjD,MAAM,WAAW,qBAAqB,EAAE,cAAc,CAAC;EACvD,KAAK,gBACH,KAAK,kBAAkB,KAAA,IAAY,WAAW,KAAK,IAAI,KAAK,eAAe,QAAQ;EACrF,KAAK,QAAQ,wBAAwB,KAAK,aAAa;CACzD;CAEA,IAAY,WAAqB;EAC/B,IAAI,CAAC,KAAK,QACR,MAAM,IAAI,MACR,mKAEF;EAEF,OAAO,KAAK;CACd;CAEA,KAAK,OAAe,MAAsC;EACxD,OAAO,KAAK,SAAS,KAAK,OAAO,IAAI;CACvC;CACA,GAAG,MAAiC;EAClC,OAAO,KAAK,SAAS,GAAG,IAAI;CAC9B;CACA,GAAG,MAAiC;EAClC,OAAO,KAAK,SAAS,GAAG,IAAI;CAC9B;CACA,OAAO,MAAiC;EACtC,OAAO,KAAK,SAAS,OAAO,IAAI;CAClC;AACF;AAvCC,iBAAA,WAAA,CAAA,WAAW,CAAA,GAAA,cAAA"}