foldkit-media 0.3.1 → 0.4.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 (175) hide show
  1. package/README.md +65 -4
  2. package/dist/{asset-BLo8VWmd.d.mts → asset.d.ts} +10 -11
  3. package/dist/asset.d.ts.map +1 -0
  4. package/dist/asset.js +66 -0
  5. package/dist/asset.js.map +1 -0
  6. package/dist/browser/index.d.ts +15 -0
  7. package/dist/browser/index.d.ts.map +1 -0
  8. package/dist/browser/index.js +69 -0
  9. package/dist/browser/index.js.map +1 -0
  10. package/dist/browser/{index.d.mts → upload.d.ts} +5 -16
  11. package/dist/browser/upload.d.ts.map +1 -0
  12. package/dist/browser/upload.js +87 -0
  13. package/dist/browser/upload.js.map +1 -0
  14. package/dist/cloudflare/{index.d.mts → index.d.ts} +8 -6
  15. package/dist/cloudflare/index.d.ts.map +1 -0
  16. package/dist/cloudflare/{index.mjs → index.js} +35 -15
  17. package/dist/cloudflare/index.js.map +1 -0
  18. package/dist/describe.d.ts +32 -0
  19. package/dist/describe.d.ts.map +1 -0
  20. package/dist/describe.js +30 -0
  21. package/dist/describe.js.map +1 -0
  22. package/dist/format.d.ts +12 -0
  23. package/dist/format.d.ts.map +1 -0
  24. package/dist/{format-BCRTFU9j.mjs → format.js} +2 -2
  25. package/dist/format.js.map +1 -0
  26. package/dist/{icon-BGtxExTN.d.mts → icon.d.ts} +14 -17
  27. package/dist/icon.d.ts.map +1 -0
  28. package/dist/{icon-0A2dBtqj.mjs → icon.js} +2 -12
  29. package/dist/icon.js.map +1 -0
  30. package/dist/icons/{index.d.mts → index.d.ts} +2 -2
  31. package/dist/icons/index.d.ts.map +1 -0
  32. package/dist/icons/{index.mjs → index.js} +2 -2
  33. package/dist/icons/index.js.map +1 -0
  34. package/dist/index.d.ts +11 -0
  35. package/dist/index.js +10 -0
  36. package/dist/layout.d.ts +60 -0
  37. package/dist/layout.d.ts.map +1 -0
  38. package/dist/layout.js +72 -0
  39. package/dist/layout.js.map +1 -0
  40. package/dist/limits.d.ts +3 -0
  41. package/dist/limits.d.ts.map +1 -0
  42. package/dist/{limits-B4hHpyfE.mjs → limits.js} +2 -2
  43. package/dist/limits.js.map +1 -0
  44. package/dist/picture.d.ts +88 -0
  45. package/dist/picture.d.ts.map +1 -0
  46. package/dist/picture.js +113 -0
  47. package/dist/picture.js.map +1 -0
  48. package/dist/placeholder.d.ts +16 -0
  49. package/dist/placeholder.d.ts.map +1 -0
  50. package/dist/placeholder.js +38 -0
  51. package/dist/placeholder.js.map +1 -0
  52. package/dist/{provider-CB0nqu0m.d.mts → provider.d.ts} +16 -19
  53. package/dist/provider.d.ts.map +1 -0
  54. package/dist/provider.js +93 -0
  55. package/dist/provider.js.map +1 -0
  56. package/dist/server/admission.d.ts +31 -0
  57. package/dist/server/admission.d.ts.map +1 -0
  58. package/dist/server/admission.js +41 -0
  59. package/dist/server/admission.js.map +1 -0
  60. package/dist/server/api.d.ts +14 -0
  61. package/dist/server/api.d.ts.map +1 -0
  62. package/dist/server/api.js +21 -0
  63. package/dist/server/api.js.map +1 -0
  64. package/dist/server/diagnostics.d.ts +53 -0
  65. package/dist/server/diagnostics.d.ts.map +1 -0
  66. package/dist/server/diagnostics.js +50 -0
  67. package/dist/server/diagnostics.js.map +1 -0
  68. package/dist/server/errors.d.ts +24 -0
  69. package/dist/server/errors.d.ts.map +1 -0
  70. package/dist/{errors-BhEgXJ4m.mjs → server/errors.js} +2 -2
  71. package/dist/server/errors.js.map +1 -0
  72. package/dist/server/facts.d.ts +36 -0
  73. package/dist/server/facts.d.ts.map +1 -0
  74. package/dist/server/facts.js +126 -0
  75. package/dist/server/facts.js.map +1 -0
  76. package/dist/server/fetch.d.ts +29 -0
  77. package/dist/server/fetch.d.ts.map +1 -0
  78. package/dist/server/fetch.js +32 -0
  79. package/dist/server/fetch.js.map +1 -0
  80. package/dist/server/handlers.d.ts +48 -0
  81. package/dist/server/handlers.d.ts.map +1 -0
  82. package/dist/server/handlers.js +151 -0
  83. package/dist/server/handlers.js.map +1 -0
  84. package/dist/server/headers.d.ts +47 -0
  85. package/dist/server/headers.d.ts.map +1 -0
  86. package/dist/server/headers.js +134 -0
  87. package/dist/server/headers.js.map +1 -0
  88. package/dist/server/index.d.ts +13 -0
  89. package/dist/server/index.js +12 -0
  90. package/dist/server/materialize.d.ts +36 -0
  91. package/dist/server/materialize.d.ts.map +1 -0
  92. package/dist/server/materialize.js +62 -0
  93. package/dist/server/materialize.js.map +1 -0
  94. package/dist/{services-BZoK2VOY.d.mts → server/services.d.ts} +12 -12
  95. package/dist/server/services.d.ts.map +1 -0
  96. package/dist/{services-7B4hsQM7.mjs → server/services.js} +3 -3
  97. package/dist/server/services.js.map +1 -0
  98. package/dist/server/stores.d.ts +27 -0
  99. package/dist/server/stores.d.ts.map +1 -0
  100. package/dist/server/stores.js +62 -0
  101. package/dist/server/stores.js.map +1 -0
  102. package/dist/server/upload.d.ts +113 -0
  103. package/dist/server/upload.d.ts.map +1 -0
  104. package/dist/server/upload.js +185 -0
  105. package/dist/server/upload.js.map +1 -0
  106. package/dist/sharp/{index.d.mts → index.d.ts} +3 -3
  107. package/dist/sharp/index.d.ts.map +1 -0
  108. package/dist/sharp/{index.mjs → index.js} +11 -9
  109. package/dist/sharp/index.js.map +1 -0
  110. package/dist/unpic/{index.d.mts → index.d.ts} +5 -4
  111. package/dist/unpic/index.d.ts.map +1 -0
  112. package/dist/unpic/{index.mjs → index.js} +3 -3
  113. package/dist/unpic/index.js.map +1 -0
  114. package/dist/{variant-B-vyMmFB.d.mts → variant.d.ts} +15 -18
  115. package/dist/variant.d.ts.map +1 -0
  116. package/dist/variant.js +75 -0
  117. package/dist/variant.js.map +1 -0
  118. package/dist/vite/{index.d.mts → icons.d.ts} +1 -19
  119. package/dist/vite/icons.d.ts.map +1 -0
  120. package/dist/vite/{index.mjs → icons.js} +7 -168
  121. package/dist/vite/icons.js.map +1 -0
  122. package/dist/vite/images.d.ts +20 -0
  123. package/dist/vite/images.d.ts.map +1 -0
  124. package/dist/vite/images.js +167 -0
  125. package/dist/vite/images.js.map +1 -0
  126. package/dist/vite/index.d.ts +3 -0
  127. package/dist/vite/index.js +3 -0
  128. package/dist/widths.d.ts +22 -0
  129. package/dist/widths.d.ts.map +1 -0
  130. package/dist/{widths-qp3jshiF.mjs → widths.js} +2 -8
  131. package/dist/widths.js.map +1 -0
  132. package/package.json +22 -21
  133. package/dist/asset-BLo8VWmd.d.mts.map +0 -1
  134. package/dist/browser/index.d.mts.map +0 -1
  135. package/dist/browser/index.mjs +0 -150
  136. package/dist/browser/index.mjs.map +0 -1
  137. package/dist/cloudflare/index.d.mts.map +0 -1
  138. package/dist/cloudflare/index.mjs.map +0 -1
  139. package/dist/describe-BOgc0xbR.d.mts +0 -52
  140. package/dist/describe-BOgc0xbR.d.mts.map +0 -1
  141. package/dist/describe-C6sWA_8p.mjs +0 -171
  142. package/dist/describe-C6sWA_8p.mjs.map +0 -1
  143. package/dist/errors-BhEgXJ4m.mjs.map +0 -1
  144. package/dist/format-BCRTFU9j.mjs.map +0 -1
  145. package/dist/icon-0A2dBtqj.mjs.map +0 -1
  146. package/dist/icon-BGtxExTN.d.mts.map +0 -1
  147. package/dist/icons/index.d.mts.map +0 -1
  148. package/dist/icons/index.mjs.map +0 -1
  149. package/dist/index.d.mts +0 -157
  150. package/dist/index.d.mts.map +0 -1
  151. package/dist/index.mjs +0 -322
  152. package/dist/index.mjs.map +0 -1
  153. package/dist/limits-B4hHpyfE.mjs.map +0 -1
  154. package/dist/provider-CB0nqu0m.d.mts.map +0 -1
  155. package/dist/rolldown-runtime-BJohB4LM.mjs +0 -13
  156. package/dist/server/index.d.mts +0 -170
  157. package/dist/server/index.d.mts.map +0 -1
  158. package/dist/server/index.mjs +0 -231
  159. package/dist/server/index.mjs.map +0 -1
  160. package/dist/services-7B4hsQM7.mjs.map +0 -1
  161. package/dist/services-BZoK2VOY.d.mts.map +0 -1
  162. package/dist/sharp/index.d.mts.map +0 -1
  163. package/dist/sharp/index.mjs.map +0 -1
  164. package/dist/stores-CxraN3kt.mjs +0 -490
  165. package/dist/stores-CxraN3kt.mjs.map +0 -1
  166. package/dist/unpic/index.d.mts.map +0 -1
  167. package/dist/unpic/index.mjs.map +0 -1
  168. package/dist/upload-lVLMRJoC.d.mts +0 -160
  169. package/dist/upload-lVLMRJoC.d.mts.map +0 -1
  170. package/dist/variant-B-vyMmFB.d.mts.map +0 -1
  171. package/dist/vite/index.d.mts.map +0 -1
  172. package/dist/vite/index.mjs.map +0 -1
  173. package/dist/widths-qp3jshiF.mjs.map +0 -1
  174. package/dist/widths-upkgLdek.d.mts +0 -36
  175. package/dist/widths-upkgLdek.d.mts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.js","names":["Variant"],"sources":["../../src/server/api.ts"],"sourcesContent":["import { Schema } from 'effect'\nimport { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from 'effect/http-api'\nimport * as Variant from '../variant.js'\n\n/**\n * The media server's HTTP API: one route, a variant of an original named by\n * its content hash. The route takes its params as text, and the handler\n * decodes them with the space's Schema, the one `Provider.hosted` encodes\n * with, so a variant outside the space is refused before any work, and that\n * refusal, like every answer, carries the headers `headersFor` decides.\n */\nexport const MediaApi = HttpApi.make('foldkit-media').add(\n HttpApiGroup.make('images').add(\n HttpApiEndpoint.get('variant', Variant.PATH, {\n params: { hash: Schema.String, variant: Schema.String },\n success: HttpApiSchema.StreamUint8Array(),\n }),\n ),\n)\n"],"mappings":";;;;;;;;;;;AAWA,MAAa,WAAW,QAAQ,KAAK,eAAe,CAAC,CAAC,IACpD,aAAa,KAAK,QAAQ,CAAC,CAAC,IAC1B,gBAAgB,IAAI,WAAWA,UAAQ,MAAM;CAC3C,QAAQ;EAAE,MAAM,OAAO;EAAQ,SAAS,OAAO;CAAO;CACtD,SAAS,cAAc,iBAAiB;AAC1C,CAAC,CACH,CACF"}
@@ -0,0 +1,53 @@
1
+ import { Cause } from "effect";
2
+ import { Diagnostic } from "foldkit-surface";
3
+ /**
4
+ * A store that failed and was worked around: a read is taken as a miss and a
5
+ * write is dropped, since what it keeps (a variant, an edge copy, an
6
+ * original's facts) is made again when missed.
7
+ */
8
+ export interface StoreFailed extends Diagnostic {
9
+ readonly _tag: 'StoreFailed';
10
+ /** `variants` (the `Variants` store), `edge` (the Workers cache in front of it), `facts` (`factsOf`'s `cache`). */
11
+ readonly store: 'variants' | 'edge' | 'facts';
12
+ readonly operation: 'read' | 'write';
13
+ readonly key: string;
14
+ readonly cause: unknown;
15
+ }
16
+ /** A rate limiter that failed, so the request was admitted unlimited. */
17
+ export interface AdmissionFailed extends Diagnostic {
18
+ readonly _tag: 'AdmissionFailed';
19
+ /** `RateLimiter` (`admissionRateLimiter`) or `binding` (`admissionRateLimit`). */
20
+ readonly limiter: 'RateLimiter' | 'binding';
21
+ readonly client: string;
22
+ readonly cause: unknown;
23
+ }
24
+ /**
25
+ * An image the transformer could not transform, or the inspector could not
26
+ * read, answered `TransformFailed` with no cause. An inspection is most often
27
+ * a file that is no image, so it is a warning; a transform, of an original
28
+ * already taken in, is an error.
29
+ */
30
+ export interface ImageFailed extends Diagnostic {
31
+ readonly _tag: 'ImageFailed';
32
+ readonly step: 'transform' | 'inspect';
33
+ readonly cause: unknown;
34
+ }
35
+ /** The facts route answered `Unavailable`, whose reason the caller is not told. */
36
+ export interface FactsUnanswered extends Diagnostic {
37
+ readonly _tag: 'FactsUnanswered';
38
+ readonly url: string;
39
+ readonly reason: string;
40
+ }
41
+ /** A defect `serveFetch` answered 500, which its caller is told nothing of. */
42
+ export interface RequestDefect extends Diagnostic {
43
+ readonly _tag: 'RequestDefect';
44
+ readonly cause: Cause.Cause<unknown>;
45
+ }
46
+ /** Every diagnostic the media server reports. */
47
+ export type MediaDiagnostic = StoreFailed | AdmissionFailed | ImageFailed | FactsUnanswered | RequestDefect;
48
+ export declare const storeFailed: (facts: Pick<StoreFailed, 'store' | 'operation' | 'key' | 'cause'>) => StoreFailed;
49
+ export declare const admissionFailed: (facts: Pick<AdmissionFailed, 'limiter' | 'client' | 'cause'>) => AdmissionFailed;
50
+ export declare const imageFailed: (step: ImageFailed['step'], cause: unknown) => ImageFailed;
51
+ export declare const factsUnanswered: (url: string, reason: string) => FactsUnanswered;
52
+ export declare const requestDefect: (cause: Cause.Cause<unknown>) => RequestDefect;
53
+ //# sourceMappingURL=diagnostics.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diagnostics.d.ts","names":[],"sources":["../../src/server/diagnostics.ts"],"mappings":";;;;;;;iBAiBiB,oBAAoB;WAC1B;;WAEA;WACA;WACA;WACA;;;iBAIM,wBAAwB;WAC9B;;WAEA;WACA;WACA;;;;;;;;iBASM,oBAAoB;WAC1B;WACA;WACA;;;iBAIM,wBAAwB;WAC9B;WACA;WACA;;;iBAIM,sBAAsB;WAC5B;WACA,OAAO,MAAM;;;YAIZ,kBACR,cACA,kBACA,cACA,kBACA;qBAES,cAAW,OACf,KAAK,0DACX;qBAQU,kBAAe,OACnB,KAAK,qDACX;qBAQU,cAAW,MAAU,qBAAmB,mBAAmB;qBAS3D,kBAAe,aAAe,mBAAmB;qBASjD,gBAAa,OAAW,MAAM,mBAAiB"}
@@ -0,0 +1,50 @@
1
+ import { Cause } from "effect";
2
+ // src/server/diagnostics.ts
3
+ /**
4
+ * What the media server answers past without telling the caller why: a store
5
+ * or rate limiter that broke and was worked around, an image it could not
6
+ * transform or inspect, facts it could not read, and a defect answered 500.
7
+ * Each is reported through `Diagnostics.report`, so a host's log (a Worker's
8
+ * `wrangler tail`) shows it by default.
9
+ */
10
+ const source = "foldkit-media";
11
+ const storeFailed = (facts) => ({
12
+ _tag: "StoreFailed",
13
+ source,
14
+ level: "error",
15
+ message: `the ${facts.store} store failed a ${facts.operation} of ${facts.key} (${String(facts.cause)}), ${facts.operation === "read" ? "which was taken as a miss" : "which was dropped"}: the request was answered, and what it keeps is made again.`,
16
+ ...facts
17
+ });
18
+ const admissionFailed = (facts) => ({
19
+ _tag: "AdmissionFailed",
20
+ source,
21
+ level: "error",
22
+ message: `the ${facts.limiter === "binding" ? "rate limit binding" : "RateLimiter"} failed (${String(facts.cause)}), so ${facts.client} was admitted with no limit.`,
23
+ ...facts
24
+ });
25
+ const imageFailed = (step, cause) => ({
26
+ _tag: "ImageFailed",
27
+ source,
28
+ level: step === "inspect" ? "warning" : "error",
29
+ message: `Media.${step} failed (${String(cause)}), and was answered TransformFailed${step === "inspect" ? ": most often a file that is no image" : ""}.`,
30
+ step,
31
+ cause
32
+ });
33
+ const factsUnanswered = (url, reason) => ({
34
+ _tag: "FactsUnanswered",
35
+ source,
36
+ level: "warning",
37
+ message: `the facts of ${url} were answered Unavailable: ${reason}.`,
38
+ url,
39
+ reason
40
+ });
41
+ const requestDefect = (cause) => ({
42
+ _tag: "RequestDefect",
43
+ source,
44
+ level: "error",
45
+ message: `a media request failed on this side, and its caller was answered 500\n${Cause.pretty(cause)}`,
46
+ cause
47
+ });
48
+ export { admissionFailed, factsUnanswered, imageFailed, requestDefect, storeFailed };
49
+
50
+ //# sourceMappingURL=diagnostics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diagnostics.js","names":[],"sources":["../../src/server/diagnostics.ts"],"sourcesContent":["/**\n * What the media server answers past without telling the caller why: a store\n * or rate limiter that broke and was worked around, an image it could not\n * transform or inspect, facts it could not read, and a defect answered 500.\n * Each is reported through `Diagnostics.report`, so a host's log (a Worker's\n * `wrangler tail`) shows it by default.\n */\nimport { Cause } from 'effect'\nimport type { Diagnostic } from 'foldkit-surface'\n\nconst source = 'foldkit-media'\n\n/**\n * A store that failed and was worked around: a read is taken as a miss and a\n * write is dropped, since what it keeps (a variant, an edge copy, an\n * original's facts) is made again when missed.\n */\nexport interface StoreFailed extends Diagnostic {\n readonly _tag: 'StoreFailed'\n /** `variants` (the `Variants` store), `edge` (the Workers cache in front of it), `facts` (`factsOf`'s `cache`). */\n readonly store: 'variants' | 'edge' | 'facts'\n readonly operation: 'read' | 'write'\n readonly key: string\n readonly cause: unknown\n}\n\n/** A rate limiter that failed, so the request was admitted unlimited. */\nexport interface AdmissionFailed extends Diagnostic {\n readonly _tag: 'AdmissionFailed'\n /** `RateLimiter` (`admissionRateLimiter`) or `binding` (`admissionRateLimit`). */\n readonly limiter: 'RateLimiter' | 'binding'\n readonly client: string\n readonly cause: unknown\n}\n\n/**\n * An image the transformer could not transform, or the inspector could not\n * read, answered `TransformFailed` with no cause. An inspection is most often\n * a file that is no image, so it is a warning; a transform, of an original\n * already taken in, is an error.\n */\nexport interface ImageFailed extends Diagnostic {\n readonly _tag: 'ImageFailed'\n readonly step: 'transform' | 'inspect'\n readonly cause: unknown\n}\n\n/** The facts route answered `Unavailable`, whose reason the caller is not told. */\nexport interface FactsUnanswered extends Diagnostic {\n readonly _tag: 'FactsUnanswered'\n readonly url: string\n readonly reason: string\n}\n\n/** A defect `serveFetch` answered 500, which its caller is told nothing of. */\nexport interface RequestDefect extends Diagnostic {\n readonly _tag: 'RequestDefect'\n readonly cause: Cause.Cause<unknown>\n}\n\n/** Every diagnostic the media server reports. */\nexport type MediaDiagnostic =\n | StoreFailed\n | AdmissionFailed\n | ImageFailed\n | FactsUnanswered\n | RequestDefect\n\nexport const storeFailed = (\n facts: Pick<StoreFailed, 'store' | 'operation' | 'key' | 'cause'>,\n): StoreFailed => ({\n _tag: 'StoreFailed',\n source,\n level: 'error',\n message: `the ${facts.store} store failed a ${facts.operation} of ${facts.key} (${String(facts.cause)}), ${facts.operation === 'read' ? 'which was taken as a miss' : 'which was dropped'}: the request was answered, and what it keeps is made again.`,\n ...facts,\n})\n\nexport const admissionFailed = (\n facts: Pick<AdmissionFailed, 'limiter' | 'client' | 'cause'>,\n): AdmissionFailed => ({\n _tag: 'AdmissionFailed',\n source,\n level: 'error',\n message: `the ${facts.limiter === 'binding' ? 'rate limit binding' : 'RateLimiter'} failed (${String(facts.cause)}), so ${facts.client} was admitted with no limit.`,\n ...facts,\n})\n\nexport const imageFailed = (step: ImageFailed['step'], cause: unknown): ImageFailed => ({\n _tag: 'ImageFailed',\n source,\n level: step === 'inspect' ? 'warning' : 'error',\n message: `Media.${step} failed (${String(cause)}), and was answered TransformFailed${step === 'inspect' ? ': most often a file that is no image' : ''}.`,\n step,\n cause,\n})\n\nexport const factsUnanswered = (url: string, reason: string): FactsUnanswered => ({\n _tag: 'FactsUnanswered',\n source,\n level: 'warning',\n message: `the facts of ${url} were answered Unavailable: ${reason}.`,\n url,\n reason,\n})\n\nexport const requestDefect = (cause: Cause.Cause<unknown>): RequestDefect => ({\n _tag: 'RequestDefect',\n source,\n level: 'error',\n message: `a media request failed on this side, and its caller was answered 500\\n${Cause.pretty(cause)}`,\n cause,\n})\n"],"mappings":";;;;;;;;;AAUA,MAAM,SAAS;AA0Df,MAAa,eACX,WACiB;CACjB,MAAM;CACN;CACA,OAAO;CACP,SAAS,OAAO,MAAM,MAAM,kBAAkB,MAAM,UAAU,MAAM,MAAM,IAAI,IAAI,OAAO,MAAM,KAAK,EAAE,KAAK,MAAM,cAAc,SAAS,8BAA8B,oBAAoB;CAC1L,GAAG;AACL;AAEA,MAAa,mBACX,WACqB;CACrB,MAAM;CACN;CACA,OAAO;CACP,SAAS,OAAO,MAAM,YAAY,YAAY,uBAAuB,cAAc,WAAW,OAAO,MAAM,KAAK,EAAE,QAAQ,MAAM,OAAO;CACvI,GAAG;AACL;AAEA,MAAa,eAAe,MAA2B,WAAiC;CACtF,MAAM;CACN;CACA,OAAO,SAAS,YAAY,YAAY;CACxC,SAAS,SAAS,KAAK,WAAW,OAAO,KAAK,EAAE,qCAAqC,SAAS,YAAY,yCAAyC,GAAG;CACtJ;CACA;AACF;AAEA,MAAa,mBAAmB,KAAa,YAAqC;CAChF,MAAM;CACN;CACA,OAAO;CACP,SAAS,gBAAgB,IAAI,8BAA8B,OAAO;CAClE;CACA;AACF;AAEA,MAAa,iBAAiB,WAAgD;CAC5E,MAAM;CACN;CACA,OAAO;CACP,SAAS,yEAAyE,MAAM,OAAO,KAAK;CACpG;AACF"}
@@ -0,0 +1,24 @@
1
+ import { Schema } from "effect";
2
+ declare const OriginalNotFound_base: Schema.Class<OriginalNotFound, Schema.TaggedStruct<"OriginalNotFound", {
3
+ readonly hash: Schema.String;
4
+ }>, import("effect/Cause").YieldableError>;
5
+ /** No original is stored under this hash. */
6
+ export declare class OriginalNotFound extends OriginalNotFound_base {}
7
+ declare const OriginalTooLarge_base: Schema.Class<OriginalTooLarge, Schema.TaggedStruct<"OriginalTooLarge", {
8
+ readonly size: Schema.Number;
9
+ readonly limit: Schema.Number;
10
+ readonly unit: Schema.Literals<readonly ["bytes", "pixels"]>;
11
+ }>, import("effect/Cause").YieldableError>;
12
+ /** The original is larger than the server will read: in bytes, or in pixels once decoded. */
13
+ export declare class OriginalTooLarge extends OriginalTooLarge_base {}
14
+ declare const TransformFailed_base: Schema.Class<TransformFailed, Schema.TaggedStruct<"TransformFailed", {}>, import("effect/Cause").YieldableError>;
15
+ /**
16
+ * The transformer could not make the variant: the original is not an image it
17
+ * reads, or it failed. Its reason stays in the server's log, not the response.
18
+ */
19
+ export declare class TransformFailed extends TransformFailed_base {}
20
+ declare const QuotaExhausted_base: Schema.Class<QuotaExhausted, Schema.TaggedStruct<"QuotaExhausted", {}>, import("effect/Cause").YieldableError>;
21
+ /** The host's transformation allowance is spent; variants already made still serve. */
22
+ export declare class QuotaExhausted extends QuotaExhausted_base {}
23
+ export {};
24
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","names":[],"sources":["../../src/server/errors.ts"],"mappings":";;;;;qBAGa,yBAAyB;;;;;;;qBAOzB,yBAAyB;;;;;;qBAUzB,wBAAwB;;;qBAOxB,uBAAuB"}
@@ -15,6 +15,6 @@ var OriginalTooLarge = class extends Schema.TaggedError()("OriginalTooLarge", {
15
15
  var TransformFailed = class extends Schema.TaggedError()("TransformFailed", {}, { httpApiStatus: 502 }) {};
16
16
  /** The host's transformation allowance is spent; variants already made still serve. */
17
17
  var QuotaExhausted = class extends Schema.TaggedError()("QuotaExhausted", {}, { httpApiStatus: 503 }) {};
18
- export { TransformFailed as i, OriginalTooLarge as n, QuotaExhausted as r, OriginalNotFound as t };
18
+ export { OriginalNotFound, OriginalTooLarge, QuotaExhausted, TransformFailed };
19
19
 
20
- //# sourceMappingURL=errors-BhEgXJ4m.mjs.map
20
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../../src/server/errors.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** No original is stored under this hash. */\nexport class OriginalNotFound extends Schema.TaggedError<OriginalNotFound>()(\n 'OriginalNotFound',\n { hash: Schema.String },\n { httpApiStatus: 404 },\n) {}\n\n/** The original is larger than the server will read: in bytes, or in pixels once decoded. */\nexport class OriginalTooLarge extends Schema.TaggedError<OriginalTooLarge>()(\n 'OriginalTooLarge',\n { size: Schema.Number, limit: Schema.Number, unit: Schema.Literals(['bytes', 'pixels']) },\n { httpApiStatus: 413 },\n) {}\n\n/**\n * The transformer could not make the variant: the original is not an image it\n * reads, or it failed. Its reason stays in the server's log, not the response.\n */\nexport class TransformFailed extends Schema.TaggedError<TransformFailed>()(\n 'TransformFailed',\n {},\n { httpApiStatus: 502 },\n) {}\n\n/** The host's transformation allowance is spent; variants already made still serve. */\nexport class QuotaExhausted extends Schema.TaggedError<QuotaExhausted>()(\n 'QuotaExhausted',\n {},\n { httpApiStatus: 503 },\n) {}\n"],"mappings":";;;AAGA,IAAa,mBAAb,cAAsC,OAAO,YAA8B,CAAC,CAC1E,oBACA,EAAE,MAAM,OAAO,OAAO,GACtB,EAAE,eAAe,IAAI,CACvB,CAAC,CAAC,CAAC;;AAGH,IAAa,mBAAb,cAAsC,OAAO,YAA8B,CAAC,CAC1E,oBACA;CAAE,MAAM,OAAO;CAAQ,OAAO,OAAO;CAAQ,MAAM,OAAO,SAAS,CAAC,SAAS,QAAQ,CAAC;AAAE,GACxF,EAAE,eAAe,IAAI,CACvB,CAAC,CAAC,CAAC;;;;;AAMH,IAAa,kBAAb,cAAqC,OAAO,YAA6B,CAAC,CACxE,mBACA,CAAC,GACD,EAAE,eAAe,IAAI,CACvB,CAAC,CAAC,CAAC;;AAGH,IAAa,iBAAb,cAAoC,OAAO,YAA4B,CAAC,CACtE,kBACA,CAAC,GACD,EAAE,eAAe,IAAI,CACvB,CAAC,CAAC,CAAC"}
@@ -0,0 +1,36 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { ImageAsset } from "../asset.js";
3
+ import { Inspector } from "../describe.js";
4
+ import { KeyValueStore } from "effect/persistence";
5
+ declare const FactsUnavailable_base: Schema.Class<FactsUnavailable, Schema.TaggedStruct<"FactsUnavailable", {
6
+ readonly url: Schema.String;
7
+ readonly reason: Schema.String;
8
+ }>, import("effect/Cause").YieldableError>;
9
+ /** No facts could be read for the image at `url`; `reason` says why, for the build's report. */
10
+ export declare class FactsUnavailable extends FactsUnavailable_base {}
11
+ export interface FactsOptions {
12
+ /** The hosts an original may be read from, matched exactly: `cdn.example.com`, not a suffix. */
13
+ readonly allow: ReadonlyArray<string>;
14
+ /** The largest original read, in bytes, counted as it streams. */
15
+ readonly maxBytes?: number;
16
+ /**
17
+ * Facts kept by URL and revalidated with the original's `ETag`. A read that
18
+ * fails is a miss and a write that fails is dropped, each reported as
19
+ * `StoreFailed`.
20
+ */
21
+ readonly cache?: KeyValueStore.KeyValueStore;
22
+ /** How to fetch; the platform's `fetch` by default. */
23
+ readonly fetch?: (request: Request) => Promise<Response>;
24
+ }
25
+ /**
26
+ * The facts of an image a page names only by URL (a rich-text image, a CMS
27
+ * block), so it is drawn with its box and placeholder like any other: its
28
+ * original read from an allowed host and described (`describe`), with the
29
+ * URL as its key. Only `https` on a host in `allow`, at its default port, is read, and every
30
+ * redirect is checked again, so content cannot point the build at an
31
+ * internal address. Kept in `cache`, an unchanged original is asked for
32
+ * with its `ETag` and not read or inspected again.
33
+ */
34
+ export declare const factsOf: (url: string, options: FactsOptions) => Effect.Effect<ImageAsset, FactsUnavailable, Inspector>;
35
+ export {};
36
+ //# sourceMappingURL=facts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"facts.d.ts","names":[],"sources":["../../src/server/facts.ts"],"mappings":";;;;;;;;;qBASa,yBAAyB;iBAiBrB;;WAEN,OAAO;;WAEP;;;;;;WAMA,QAAQ,cAAc;;WAEtB,SAAS,SAAS,YAAY,QAAQ;;;;;;;;;;;qBAYpC,UAAO,aACP,SACF,iBACR,OAAO,OAAO,YAAY,kBAAkB"}
@@ -0,0 +1,126 @@
1
+ import { Effect, Option, Schema } from "effect";
2
+ import { ImageAsset } from "../asset.js";
3
+ import { describe } from "../describe.js";
4
+ import { nonNegativeInteger } from "../limits.js";
5
+ import { Diagnostics } from "foldkit-surface";
6
+ import { storeFailed } from "./diagnostics.js";
7
+ // src/server/facts.ts
8
+ /** No facts could be read for the image at `url`; `reason` says why, for the build's report. */
9
+ var FactsUnavailable = class extends Schema.TaggedError()("FactsUnavailable", {
10
+ url: Schema.String,
11
+ reason: Schema.String
12
+ }) {};
13
+ const Cached = Schema.Struct({
14
+ target: Schema.String,
15
+ etag: Schema.OptionFromNullOr(Schema.String),
16
+ asset: ImageAsset
17
+ });
18
+ const CachedJson = Schema.fromJsonString(Cached);
19
+ const MAX_REDIRECTS = 3;
20
+ const DEFAULT_MAX_BYTES = 20971520;
21
+ /**
22
+ * The facts of an image a page names only by URL (a rich-text image, a CMS
23
+ * block), so it is drawn with its box and placeholder like any other: its
24
+ * original read from an allowed host and described (`describe`), with the
25
+ * URL as its key. Only `https` on a host in `allow`, at its default port, is read, and every
26
+ * redirect is checked again, so content cannot point the build at an
27
+ * internal address. Kept in `cache`, an unchanged original is asked for
28
+ * with its `ETag` and not read or inspected again.
29
+ */
30
+ const factsOf = (url, options) => {
31
+ const unavailable = (reason) => new FactsUnavailable({
32
+ url,
33
+ reason
34
+ });
35
+ const fetchOne = options.fetch ?? ((request) => fetch(request));
36
+ const maxBytes = nonNegativeInteger("maxBytes", options.maxBytes ?? DEFAULT_MAX_BYTES);
37
+ const allowed = (target) => target.protocol === "https:" && target.port === "" && options.allow.includes(target.hostname);
38
+ const cacheKey = `facts/${url}`;
39
+ const readCached = Option.match(Option.fromNullishOr(options.cache), {
40
+ onNone: () => Effect.succeed(Option.none()),
41
+ onSome: (store) => store.get(cacheKey).pipe(Effect.map((text) => Option.flatMap(Option.fromNullishOr(text), Schema.decodeUnknownOption(CachedJson))), Effect.catch((cause) => Diagnostics.report(storeFailed({
42
+ store: "facts",
43
+ operation: "read",
44
+ key: cacheKey,
45
+ cause
46
+ })).pipe(Effect.as(Option.none()))))
47
+ });
48
+ const request = (cached) => Effect.tryPromise({
49
+ try: async () => {
50
+ let target = new URL(url);
51
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
52
+ if (!allowed(target)) return { refused: `${target.origin} is not an allowed host` };
53
+ const etag = Option.flatMap(cached, (entry) => entry.target === target.href ? entry.etag : Option.none());
54
+ const headers = Option.match(etag, {
55
+ onNone: () => ({}),
56
+ onSome: (tag) => ({ "if-none-match": tag })
57
+ });
58
+ const response = await fetchOne(new Request(target, {
59
+ headers,
60
+ redirect: "manual"
61
+ }));
62
+ const location = response.headers.get("location");
63
+ if (response.status < 300 || response.status >= 400 || response.status === 304 || location === null) return {
64
+ response,
65
+ target: target.href
66
+ };
67
+ target = new URL(location, target);
68
+ }
69
+ return { refused: `more than ${MAX_REDIRECTS} redirects` };
70
+ },
71
+ catch: (cause) => unavailable(`the fetch failed: ${String(cause)}`)
72
+ });
73
+ const bytesOf = (response) => Effect.tryPromise({
74
+ try: async () => {
75
+ const chunks = [];
76
+ let size = 0;
77
+ const reader = response.body?.getReader();
78
+ for (let read = await reader?.read(); read !== void 0 && !read.done; read = await reader?.read()) {
79
+ size += read.value.byteLength;
80
+ if (size > maxBytes) {
81
+ await reader?.cancel();
82
+ return;
83
+ }
84
+ chunks.push(read.value);
85
+ }
86
+ const bytes = new Uint8Array(size);
87
+ let at = 0;
88
+ for (const chunk of chunks) {
89
+ bytes.set(chunk, at);
90
+ at += chunk.byteLength;
91
+ }
92
+ return bytes;
93
+ },
94
+ catch: (cause) => unavailable(`the body could not be read: ${String(cause)}`)
95
+ });
96
+ return Effect.gen(function* () {
97
+ const cached = yield* readCached;
98
+ const answer = yield* request(cached);
99
+ if ("refused" in answer) return yield* unavailable(answer.refused);
100
+ const { response, target } = answer;
101
+ const unchanged = Option.filter(cached, (entry) => entry.target === target);
102
+ if (response.status === 304 && Option.isSome(unchanged)) return unchanged.value.asset;
103
+ if (response.status !== 200) return yield* unavailable(`the original answered ${response.status}`);
104
+ const bytes = yield* bytesOf(response);
105
+ if (bytes === void 0) return yield* unavailable(`the original is larger than ${maxBytes} bytes`);
106
+ const asset = yield* describe(url, bytes).pipe(Effect.mapError((error) => unavailable(`the original could not be inspected: ${error._tag}`)));
107
+ const store = options.cache;
108
+ if (store !== void 0) {
109
+ const entry = Schema.encodeSync(CachedJson)({
110
+ target,
111
+ etag: Option.fromNullishOr(response.headers.get("etag")),
112
+ asset
113
+ });
114
+ yield* store.set(cacheKey, entry).pipe(Effect.catch((cause) => Diagnostics.report(storeFailed({
115
+ store: "facts",
116
+ operation: "write",
117
+ key: cacheKey,
118
+ cause
119
+ }))));
120
+ }
121
+ return asset;
122
+ });
123
+ };
124
+ export { FactsUnavailable, factsOf };
125
+
126
+ //# sourceMappingURL=facts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"facts.js","names":[],"sources":["../../src/server/facts.ts"],"sourcesContent":["import { Effect, Option, Schema } from 'effect'\nimport type { KeyValueStore } from 'effect/persistence'\nimport { Diagnostics } from 'foldkit-surface'\nimport { ImageAsset } from '../asset.js'\nimport { describe, type Inspector } from '../describe.js'\nimport { nonNegativeInteger } from '../limits.js'\nimport { storeFailed } from './diagnostics.js'\n\n/** No facts could be read for the image at `url`; `reason` says why, for the build's report. */\nexport class FactsUnavailable extends Schema.TaggedError<FactsUnavailable>()('FactsUnavailable', {\n url: Schema.String,\n reason: Schema.String,\n}) {}\n\nconst Cached = Schema.Struct({\n target: Schema.String,\n etag: Schema.OptionFromNullOr(Schema.String),\n asset: ImageAsset,\n})\nconst CachedJson = Schema.fromJsonString(Cached)\n\n// A redirect chain longer than this is refused, not followed.\nconst MAX_REDIRECTS = 3\n\nconst DEFAULT_MAX_BYTES = 20 * 1024 * 1024\n\nexport interface FactsOptions {\n /** The hosts an original may be read from, matched exactly: `cdn.example.com`, not a suffix. */\n readonly allow: ReadonlyArray<string>\n /** The largest original read, in bytes, counted as it streams. */\n readonly maxBytes?: number\n /**\n * Facts kept by URL and revalidated with the original's `ETag`. A read that\n * fails is a miss and a write that fails is dropped, each reported as\n * `StoreFailed`.\n */\n readonly cache?: KeyValueStore.KeyValueStore\n /** How to fetch; the platform's `fetch` by default. */\n readonly fetch?: (request: Request) => Promise<Response>\n}\n\n/**\n * The facts of an image a page names only by URL (a rich-text image, a CMS\n * block), so it is drawn with its box and placeholder like any other: its\n * original read from an allowed host and described (`describe`), with the\n * URL as its key. Only `https` on a host in `allow`, at its default port, is read, and every\n * redirect is checked again, so content cannot point the build at an\n * internal address. Kept in `cache`, an unchanged original is asked for\n * with its `ETag` and not read or inspected again.\n */\nexport const factsOf = (\n url: string,\n options: FactsOptions,\n): Effect.Effect<ImageAsset, FactsUnavailable, Inspector> => {\n const unavailable = (reason: string) => new FactsUnavailable({ url, reason })\n const fetchOne = options.fetch ?? ((request: Request) => fetch(request))\n const maxBytes = nonNegativeInteger('maxBytes', options.maxBytes ?? DEFAULT_MAX_BYTES)\n // An allowed host on its own port alone: another port of it is another service.\n const allowed = (target: URL) =>\n target.protocol === 'https:' && target.port === '' && options.allow.includes(target.hostname)\n const cacheKey = `facts/${url}`\n\n const readCached = Option.match(Option.fromNullishOr(options.cache), {\n onNone: () => Effect.succeed(Option.none<typeof Cached.Type>()),\n onSome: store =>\n store.get(cacheKey).pipe(\n Effect.map(text =>\n Option.flatMap(Option.fromNullishOr(text), Schema.decodeUnknownOption(CachedJson)),\n ),\n Effect.catch(cause =>\n Diagnostics.report(\n storeFailed({ store: 'facts', operation: 'read', key: cacheKey, cause }),\n ).pipe(Effect.as(Option.none<typeof Cached.Type>())),\n ),\n ),\n })\n\n const request = (cached: Option.Option<typeof Cached.Type>) =>\n Effect.tryPromise({\n try: async () => {\n let target = new URL(url)\n for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {\n if (!allowed(target))\n return { refused: `${target.origin} is not an allowed host` } as const\n const etag = Option.flatMap(cached, entry =>\n entry.target === target.href ? entry.etag : Option.none(),\n )\n const headers = Option.match(etag, {\n onNone: () => ({}),\n onSome: tag => ({ 'if-none-match': tag }),\n })\n const response = await fetchOne(new Request(target, { headers, redirect: 'manual' }))\n const location = response.headers.get('location')\n if (\n response.status < 300 ||\n response.status >= 400 ||\n response.status === 304 ||\n location === null\n ) {\n return { response, target: target.href } as const\n }\n target = new URL(location, target)\n }\n return { refused: `more than ${MAX_REDIRECTS} redirects` } as const\n },\n catch: cause => unavailable(`the fetch failed: ${String(cause)}`),\n })\n\n // Counted as it streams: a missing or false Content-Length does not let a larger body through.\n const bytesOf = (response: Response) =>\n Effect.tryPromise({\n try: async () => {\n const chunks: Array<Uint8Array> = []\n let size = 0\n const reader = response.body?.getReader()\n for (\n let read = await reader?.read();\n read !== undefined && !read.done;\n read = await reader?.read()\n ) {\n size += read.value.byteLength\n if (size > maxBytes) {\n await reader?.cancel()\n return undefined\n }\n chunks.push(read.value)\n }\n const bytes = new Uint8Array(size)\n let at = 0\n for (const chunk of chunks) {\n bytes.set(chunk, at)\n at += chunk.byteLength\n }\n return bytes\n },\n catch: cause => unavailable(`the body could not be read: ${String(cause)}`),\n })\n\n return Effect.gen(function* () {\n const cached = yield* readCached\n const answer = yield* request(cached)\n if ('refused' in answer) return yield* unavailable(answer.refused)\n const { response, target } = answer\n const unchanged = Option.filter(cached, entry => entry.target === target)\n if (response.status === 304 && Option.isSome(unchanged)) return unchanged.value.asset\n if (response.status !== 200)\n return yield* unavailable(`the original answered ${response.status}`)\n const bytes = yield* bytesOf(response)\n if (bytes === undefined)\n return yield* unavailable(`the original is larger than ${maxBytes} bytes`)\n const asset = yield* describe(url, bytes).pipe(\n Effect.mapError(error => unavailable(`the original could not be inspected: ${error._tag}`)),\n )\n const store = options.cache\n if (store !== undefined) {\n const entry = Schema.encodeSync(CachedJson)({\n target,\n etag: Option.fromNullishOr(response.headers.get('etag')),\n asset,\n })\n yield* store\n .set(cacheKey, entry)\n .pipe(\n Effect.catch(cause =>\n Diagnostics.report(\n storeFailed({ store: 'facts', operation: 'write', key: cacheKey, cause }),\n ),\n ),\n )\n }\n return asset\n })\n}\n"],"mappings":";;;;;;;;AASA,IAAa,mBAAb,cAAsC,OAAO,YAA8B,CAAC,CAAC,oBAAoB;CAC/F,KAAK,OAAO;CACZ,QAAQ,OAAO;AACjB,CAAC,CAAC,CAAC,CAAC;AAEJ,MAAM,SAAS,OAAO,OAAO;CAC3B,QAAQ,OAAO;CACf,MAAM,OAAO,iBAAiB,OAAO,MAAM;CAC3C,OAAO;AACT,CAAC;AACD,MAAM,aAAa,OAAO,eAAe,MAAM;AAG/C,MAAM,gBAAgB;AAEtB,MAAM,oBAAoB;;;;;;;;;;AA0B1B,MAAa,WACX,KACA,YAC2D;CAC3D,MAAM,eAAe,WAAmB,IAAI,iBAAiB;EAAE;EAAK;CAAO,CAAC;CAC5E,MAAM,WAAW,QAAQ,WAAW,YAAqB,MAAM,OAAO;CACtE,MAAM,WAAW,mBAAmB,YAAY,QAAQ,YAAY,iBAAiB;CAErF,MAAM,WAAW,WACf,OAAO,aAAa,YAAY,OAAO,SAAS,MAAM,QAAQ,MAAM,SAAS,OAAO,QAAQ;CAC9F,MAAM,WAAW,SAAS;CAE1B,MAAM,aAAa,OAAO,MAAM,OAAO,cAAc,QAAQ,KAAK,GAAG;EACnE,cAAc,OAAO,QAAQ,OAAO,KAAyB,CAAC;EAC9D,SAAQ,UACN,MAAM,IAAI,QAAQ,CAAC,CAAC,KAClB,OAAO,KAAI,SACT,OAAO,QAAQ,OAAO,cAAc,IAAI,GAAG,OAAO,oBAAoB,UAAU,CAAC,CACnF,GACA,OAAO,OAAM,UACX,YAAY,OACV,YAAY;GAAE,OAAO;GAAS,WAAW;GAAQ,KAAK;GAAU;EAAM,CAAC,CACzE,CAAC,CAAC,KAAK,OAAO,GAAG,OAAO,KAAyB,CAAC,CAAC,CACrD,CACF;CACJ,CAAC;CAED,MAAM,WAAW,WACf,OAAO,WAAW;EAChB,KAAK,YAAY;GACf,IAAI,SAAS,IAAI,IAAI,GAAG;GACxB,KAAK,IAAI,MAAM,GAAG,OAAO,eAAe,OAAO;IAC7C,IAAI,CAAC,QAAQ,MAAM,GACjB,OAAO,EAAE,SAAS,GAAG,OAAO,OAAO,yBAAyB;IAC9D,MAAM,OAAO,OAAO,QAAQ,SAAQ,UAClC,MAAM,WAAW,OAAO,OAAO,MAAM,OAAO,OAAO,KAAK,CAC1D;IACA,MAAM,UAAU,OAAO,MAAM,MAAM;KACjC,eAAe,CAAC;KAChB,SAAQ,SAAQ,EAAE,iBAAiB,IAAI;IACzC,CAAC;IACD,MAAM,WAAW,MAAM,SAAS,IAAI,QAAQ,QAAQ;KAAE;KAAS,UAAU;IAAS,CAAC,CAAC;IACpF,MAAM,WAAW,SAAS,QAAQ,IAAI,UAAU;IAChD,IACE,SAAS,SAAS,OAClB,SAAS,UAAU,OACnB,SAAS,WAAW,OACpB,aAAa,MAEb,OAAO;KAAE;KAAU,QAAQ,OAAO;IAAK;IAEzC,SAAS,IAAI,IAAI,UAAU,MAAM;GACnC;GACA,OAAO,EAAE,SAAS,aAAa,cAAc,YAAY;EAC3D;EACA,QAAO,UAAS,YAAY,qBAAqB,OAAO,KAAK,GAAG;CAClE,CAAC;CAGH,MAAM,WAAW,aACf,OAAO,WAAW;EAChB,KAAK,YAAY;GACf,MAAM,SAA4B,CAAC;GACnC,IAAI,OAAO;GACX,MAAM,SAAS,SAAS,MAAM,UAAU;GACxC,KACE,IAAI,OAAO,MAAM,QAAQ,KAAK,GAC9B,SAAS,KAAA,KAAa,CAAC,KAAK,MAC5B,OAAO,MAAM,QAAQ,KAAK,GAC1B;IACA,QAAQ,KAAK,MAAM;IACnB,IAAI,OAAO,UAAU;KACnB,MAAM,QAAQ,OAAO;KACrB;IACF;IACA,OAAO,KAAK,KAAK,KAAK;GACxB;GACA,MAAM,QAAQ,IAAI,WAAW,IAAI;GACjC,IAAI,KAAK;GACT,KAAK,MAAM,SAAS,QAAQ;IAC1B,MAAM,IAAI,OAAO,EAAE;IACnB,MAAM,MAAM;GACd;GACA,OAAO;EACT;EACA,QAAO,UAAS,YAAY,+BAA+B,OAAO,KAAK,GAAG;CAC5E,CAAC;CAEH,OAAO,OAAO,IAAI,aAAa;EAC7B,MAAM,SAAS,OAAO;EACtB,MAAM,SAAS,OAAO,QAAQ,MAAM;EACpC,IAAI,aAAa,QAAQ,OAAO,OAAO,YAAY,OAAO,OAAO;EACjE,MAAM,EAAE,UAAU,WAAW;EAC7B,MAAM,YAAY,OAAO,OAAO,SAAQ,UAAS,MAAM,WAAW,MAAM;EACxE,IAAI,SAAS,WAAW,OAAO,OAAO,OAAO,SAAS,GAAG,OAAO,UAAU,MAAM;EAChF,IAAI,SAAS,WAAW,KACtB,OAAO,OAAO,YAAY,yBAAyB,SAAS,QAAQ;EACtE,MAAM,QAAQ,OAAO,QAAQ,QAAQ;EACrC,IAAI,UAAU,KAAA,GACZ,OAAO,OAAO,YAAY,+BAA+B,SAAS,OAAO;EAC3E,MAAM,QAAQ,OAAO,SAAS,KAAK,KAAK,CAAC,CAAC,KACxC,OAAO,UAAS,UAAS,YAAY,wCAAwC,MAAM,MAAM,CAAC,CAC5F;EACA,MAAM,QAAQ,QAAQ;EACtB,IAAI,UAAU,KAAA,GAAW;GACvB,MAAM,QAAQ,OAAO,WAAW,UAAU,CAAC,CAAC;IAC1C;IACA,MAAM,OAAO,cAAc,SAAS,QAAQ,IAAI,MAAM,CAAC;IACvD;GACF,CAAC;GACD,OAAO,MACJ,IAAI,UAAU,KAAK,CAAC,CACpB,KACC,OAAO,OAAM,UACX,YAAY,OACV,YAAY;IAAE,OAAO;IAAS,WAAW;IAAS,KAAK;IAAU;GAAM,CAAC,CAC1E,CACF,CACF;EACJ;EACA,OAAO;CACT,CAAC;AACH"}
@@ -0,0 +1,29 @@
1
+ import { Layer } from "effect";
2
+ import { Inspector } from "../describe.js";
3
+ import { Originals, Transformer, Variants } from "./services.js";
4
+ import { UploadOptions, UploadPolicy, Uploads } from "./upload.js";
5
+ import { Options } from "./handlers.js";
6
+ /** What `serveFetch` answers, each side's services built from the request's bindings. */
7
+ export interface FetchOptions<Env> {
8
+ /** `GET /_image/…`: the variants. A Worker request cannot wait on another's, so nothing coalesces. */
9
+ readonly images?: Omit<Options, 'coalesce'> & {
10
+ readonly layer: (env: Env) => Layer.Layer<Originals | Transformer | Variants, unknown>;
11
+ };
12
+ /** `POST /_media/upload` and `GET /_media/facts`: originals entering. */
13
+ readonly uploads?: UploadOptions & {
14
+ readonly layer: (env: Env) => Layer.Layer<Uploads | Inspector | UploadPolicy, unknown>;
15
+ };
16
+ /** Every path outside `/_image/` and `/_media/`: the application's own routes. A 404 when omitted. */
17
+ readonly otherwise?: (request: Request, env: Env) => Promise<Response>;
18
+ }
19
+ /**
20
+ * The media server as a Worker's fetch handler. It owns `/_image/` and
21
+ * `/_media/`: a route of either it was not given, another method (a
22
+ * preflight, which the upload route never answers), or another path under
23
+ * them is a 404, and everything else goes to `otherwise`. The services are
24
+ * built from each environment's bindings once and kept; a layer that fails
25
+ * to build answers a 500. When both layers give a `Diagnostics.Reporter`, a
26
+ * defect answered 500 on either side is reported to the uploads layer's.
27
+ */
28
+ export declare const serveFetch: <Env extends object>(options: FetchOptions<Env>) => ((request: Request, env: Env) => Promise<Response>);
29
+ //# sourceMappingURL=fetch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.d.ts","names":[],"sources":["../../src/server/fetch.ts"],"mappings":";;;;;;iBAWiB,aAAa;;WAEnB,SAAS,KAAK;aACZ,QAAQ,KAAK,QAAQ,MAAM,MAAM,YAAY,cAAc;;;WAG7D,UAAU;aACR,QAAQ,KAAK,QAAQ,MAAM,MAAM,UAAU,YAAY;;;WAGzD,aAAa,SAAS,SAAS,KAAK,QAAQ,QAAQ;;;;;;;;;;;qBAYlD,aAAc,oBAAkB,SAClC,aAAa,WACnB,SAAS,SAAS,KAAK,QAAQ,QAAQ"}
@@ -0,0 +1,32 @@
1
+ import { Layer } from "effect";
2
+ import * as Variant$1 from "../variant.js";
3
+ import { uploadLayer } from "./upload.js";
4
+ import { fetchOf, layer } from "./handlers.js";
5
+ // src/server/fetch.ts
6
+ const IMAGES = Variant$1.PATH.slice(0, Variant$1.PATH.indexOf(":"));
7
+ const UPLOADS = "/_media/";
8
+ /**
9
+ * The media server as a Worker's fetch handler. It owns `/_image/` and
10
+ * `/_media/`: a route of either it was not given, another method (a
11
+ * preflight, which the upload route never answers), or another path under
12
+ * them is a 404, and everything else goes to `otherwise`. The services are
13
+ * built from each environment's bindings once and kept; a layer that fails
14
+ * to build answers a 500. When both layers give a `Diagnostics.Reporter`, a
15
+ * defect answered 500 on either side is reported to the uploads layer's.
16
+ */
17
+ const serveFetch = (options) => {
18
+ const { images, uploads, otherwise } = options;
19
+ if (images === void 0 && uploads === void 0) throw new Error("serveFetch: give it `images`, `uploads`, or both");
20
+ const media = fetchOf((env) => Layer.mergeAll(images === void 0 ? Layer.empty : layer({
21
+ ...images,
22
+ coalesce: false
23
+ }).pipe(Layer.provideMerge(images.layer(env))), uploads === void 0 ? Layer.empty : uploadLayer(uploads).pipe(Layer.provideMerge(uploads.layer(env)))));
24
+ return (request, env) => {
25
+ const { pathname } = new URL(request.url);
26
+ if (pathname.startsWith(IMAGES) || pathname.startsWith(UPLOADS)) return media(request, env);
27
+ return otherwise === void 0 ? Promise.resolve(new Response(null, { status: 404 })) : otherwise(request, env);
28
+ };
29
+ };
30
+ export { serveFetch };
31
+
32
+ //# sourceMappingURL=fetch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.js","names":["Variant"],"sources":["../../src/server/fetch.ts"],"sourcesContent":["import { Layer } from 'effect'\nimport type { Inspector } from '../describe.js'\nimport * as Variant from '../variant.js'\nimport { fetchOf, layer, type Options } from './handlers.js'\nimport type { Originals, Transformer, Variants } from './services.js'\nimport { uploadLayer, type UploadOptions, type UploadPolicy, type Uploads } from './upload.js'\n\nconst IMAGES = Variant.PATH.slice(0, Variant.PATH.indexOf(':'))\nconst UPLOADS = '/_media/'\n\n/** What `serveFetch` answers, each side's services built from the request's bindings. */\nexport interface FetchOptions<Env> {\n /** `GET /_image/…`: the variants. A Worker request cannot wait on another's, so nothing coalesces. */\n readonly images?: Omit<Options, 'coalesce'> & {\n readonly layer: (env: Env) => Layer.Layer<Originals | Transformer | Variants, unknown>\n }\n /** `POST /_media/upload` and `GET /_media/facts`: originals entering. */\n readonly uploads?: UploadOptions & {\n readonly layer: (env: Env) => Layer.Layer<Uploads | Inspector | UploadPolicy, unknown>\n }\n /** Every path outside `/_image/` and `/_media/`: the application's own routes. A 404 when omitted. */\n readonly otherwise?: (request: Request, env: Env) => Promise<Response>\n}\n\n/**\n * The media server as a Worker's fetch handler. It owns `/_image/` and\n * `/_media/`: a route of either it was not given, another method (a\n * preflight, which the upload route never answers), or another path under\n * them is a 404, and everything else goes to `otherwise`. The services are\n * built from each environment's bindings once and kept; a layer that fails\n * to build answers a 500. When both layers give a `Diagnostics.Reporter`, a\n * defect answered 500 on either side is reported to the uploads layer's.\n */\nexport const serveFetch = <Env extends object>(\n options: FetchOptions<Env>,\n): ((request: Request, env: Env) => Promise<Response>) => {\n const { images, uploads, otherwise } = options\n if (images === undefined && uploads === undefined) {\n throw new Error('serveFetch: give it `images`, `uploads`, or both')\n }\n // Merged, not provided: a `Diagnostics.Reporter` in a layer reaches what\n // runs around the routes too, the report of a defect answered 500. One\n // build, so a layer both sides name is made once and shared. A service\n // both layers give reaches each side's routes from its own layer, and what\n // runs around them from the uploads layer, merged last.\n const media = fetchOf<Env>(env =>\n Layer.mergeAll(\n images === undefined\n ? Layer.empty\n : layer({ ...images, coalesce: false }).pipe(Layer.provideMerge(images.layer(env))),\n uploads === undefined\n ? Layer.empty\n : uploadLayer(uploads).pipe(Layer.provideMerge(uploads.layer(env))),\n ),\n )\n return (request, env) => {\n const { pathname } = new URL(request.url)\n if (pathname.startsWith(IMAGES) || pathname.startsWith(UPLOADS)) return media(request, env)\n return otherwise === undefined\n ? Promise.resolve(new Response(null, { status: 404 }))\n : otherwise(request, env)\n }\n}\n"],"mappings":";;;;;AAOA,MAAM,SAASA,UAAQ,KAAK,MAAM,GAAGA,UAAQ,KAAK,QAAQ,GAAG,CAAC;AAC9D,MAAM,UAAU;;;;;;;;;;AAyBhB,MAAa,cACX,YACwD;CACxD,MAAM,EAAE,QAAQ,SAAS,cAAc;CACvC,IAAI,WAAW,KAAA,KAAa,YAAY,KAAA,GACtC,MAAM,IAAI,MAAM,kDAAkD;CAOpE,MAAM,QAAQ,SAAa,QACzB,MAAM,SACJ,WAAW,KAAA,IACP,MAAM,QACN,MAAM;EAAE,GAAG;EAAQ,UAAU;CAAM,CAAC,CAAC,CAAC,KAAK,MAAM,aAAa,OAAO,MAAM,GAAG,CAAC,CAAC,GACpF,YAAY,KAAA,IACR,MAAM,QACN,YAAY,OAAO,CAAC,CAAC,KAAK,MAAM,aAAa,QAAQ,MAAM,GAAG,CAAC,CAAC,CACtE,CACF;CACA,QAAQ,SAAS,QAAQ;EACvB,MAAM,EAAE,aAAa,IAAI,IAAI,QAAQ,GAAG;EACxC,IAAI,SAAS,WAAW,MAAM,KAAK,SAAS,WAAW,OAAO,GAAG,OAAO,MAAM,SAAS,GAAG;EAC1F,OAAO,cAAc,KAAA,IACjB,QAAQ,QAAQ,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC,CAAC,IACnD,UAAU,SAAS,GAAG;CAC5B;AACF"}
@@ -0,0 +1,48 @@
1
+ import { Layer } from "effect";
2
+ import { Hosted } from "../provider.js";
3
+ import { Originals, Transformer, Variants } from "./services.js";
4
+ import { HttpRouter, HttpServer, HttpServerRequest } from "effect/http";
5
+ export interface Options {
6
+ /**
7
+ * The `Provider.hosted` the pages write URLs with: the server makes every
8
+ * variant of its space and nothing else. `Provider.hosted()` when omitted.
9
+ */
10
+ readonly provider?: Hosted;
11
+ /** The largest original read, in bytes; larger ones are a 413. */
12
+ readonly maxBytes?: number;
13
+ /**
14
+ * Concurrent misses for one variant share one transform and one write.
15
+ * Only where requests may wait on one another's work: on by default for
16
+ * `layer` (a Node server), off in `serveFetch`, since a Worker request
17
+ * cannot wake another's.
18
+ */
19
+ readonly coalesce?: boolean;
20
+ /**
21
+ * Who is asking, for `Admission`: by default Cloudflare's `CF-Connecting-IP`,
22
+ * else the connection's address. `X-Forwarded-For` is the client's to write,
23
+ * so read it here only behind a proxy that sets it.
24
+ */
25
+ readonly clientOf?: (request: HttpServerRequest.HttpServerRequest) => string;
26
+ }
27
+ /**
28
+ * The handlers of `MediaApi`'s one route. The path is decoded against the
29
+ * space; a variant kept is served as kept, and one the request already holds
30
+ * (`If-None-Match`) is a 304 before the store is read; otherwise the original
31
+ * is read, transformed, kept and served. Every answer, a refusal included,
32
+ * goes through `headersFor`, and a failure is never the original in the
33
+ * variant's place.
34
+ */
35
+ export declare const handlers: (options?: Options) => Layer.Layer<import("effect/http-api/HttpApiGroup").Service<"foldkit-media", "images">, never, Originals | Transformer | Variants>;
36
+ /**
37
+ * The media server as an Effect HTTP application: its route registered with
38
+ * the `HttpRouter`, needing `Originals`, `Transformer` and `Variants`.
39
+ */
40
+ export declare const layer: (options?: Options) => Layer.Layer<never, never, import("effect/FileSystem").FileSystem | import("effect/http/Etag").Generator | import("effect/http/HttpPlatform").HttpPlatform | HttpRouter.HttpRouter | Originals | import("effect/Path").Path | Transformer | Variants>;
41
+ /**
42
+ * A Worker's fetch handler over `app`, built from each environment's bindings
43
+ * once and kept, since a Worker hands every request the same bindings. A
44
+ * layer that fails to build answers a 500. With the router's logger off, a
45
+ * defect answered 500 is reported as `RequestDefect`.
46
+ */
47
+ export declare const fetchOf: <Env extends object>(app: (env: Env) => Layer.Layer<never, unknown, HttpRouter.HttpRouter | Layer.Success<typeof HttpServer.layerServices>>) => ((request: Request, env: Env) => Promise<Response>);
48
+ //# sourceMappingURL=handlers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handlers.d.ts","names":[],"sources":["../../src/server/handlers.ts"],"mappings":";;;;iBAiBiB;;;;;WAKN,WAAW;;WAEX;;;;;;;WAOA;;;;;;WAMA,YAAY,SAAS,kBAAkB;;;;;;;;;;qBA6BrC,WAAQ,UAAa,YAAO,MAAA,6CAAA,2CAAA,YAAA,cAAA;;;;;qBA4H5B,QAAK,UAAa,YAAO,MAAA,gDAAA,wCAAA,+CAAA,eAAA,WAAA,aAAA,kCAAA,OAAA,cAAA;;;;;;;qBAsBzB,UAAW,oBAAkB,MAEtC,KAAK,QACF,MAAM,sBAGT,WAAW,aAAa,MAAM,eAAe,WAAW,sBAEvD,SAAS,SAAS,KAAK,QAAQ,QAAQ"}