@mindflight/mindbrain-personal-studio 0.6.1

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 (166) hide show
  1. package/.env.example +50 -0
  2. package/README.md +134 -0
  3. package/bin/mindbrain-studio.mjs +20 -0
  4. package/build/client/_app/immutable/assets/2.BXRKVU9n.css +1 -0
  5. package/build/client/_app/immutable/assets/2.BXRKVU9n.css.br +0 -0
  6. package/build/client/_app/immutable/assets/2.BXRKVU9n.css.gz +0 -0
  7. package/build/client/_app/immutable/chunks/-OSExkSk.js +2 -0
  8. package/build/client/_app/immutable/chunks/-OSExkSk.js.br +0 -0
  9. package/build/client/_app/immutable/chunks/-OSExkSk.js.gz +0 -0
  10. package/build/client/_app/immutable/chunks/BIHI7g3E.js +1 -0
  11. package/build/client/_app/immutable/chunks/BIHI7g3E.js.br +2 -0
  12. package/build/client/_app/immutable/chunks/BIHI7g3E.js.gz +0 -0
  13. package/build/client/_app/immutable/chunks/BJB7pSge.js +1 -0
  14. package/build/client/_app/immutable/chunks/BJB7pSge.js.br +0 -0
  15. package/build/client/_app/immutable/chunks/BJB7pSge.js.gz +0 -0
  16. package/build/client/_app/immutable/chunks/BNUkRZqg.js +1 -0
  17. package/build/client/_app/immutable/chunks/BNUkRZqg.js.br +0 -0
  18. package/build/client/_app/immutable/chunks/BNUkRZqg.js.gz +0 -0
  19. package/build/client/_app/immutable/chunks/BP2JbIUZ.js +1 -0
  20. package/build/client/_app/immutable/chunks/BP2JbIUZ.js.br +0 -0
  21. package/build/client/_app/immutable/chunks/BP2JbIUZ.js.gz +0 -0
  22. package/build/client/_app/immutable/chunks/BVrgUHq-.js +1 -0
  23. package/build/client/_app/immutable/chunks/BVrgUHq-.js.br +0 -0
  24. package/build/client/_app/immutable/chunks/BVrgUHq-.js.gz +0 -0
  25. package/build/client/_app/immutable/chunks/BmeSanva.js +1 -0
  26. package/build/client/_app/immutable/chunks/BmeSanva.js.br +0 -0
  27. package/build/client/_app/immutable/chunks/BmeSanva.js.gz +0 -0
  28. package/build/client/_app/immutable/chunks/BnkCgNCx.js +1 -0
  29. package/build/client/_app/immutable/chunks/BnkCgNCx.js.br +0 -0
  30. package/build/client/_app/immutable/chunks/BnkCgNCx.js.gz +0 -0
  31. package/build/client/_app/immutable/chunks/C5KYKPa8.js +311 -0
  32. package/build/client/_app/immutable/chunks/C5KYKPa8.js.br +0 -0
  33. package/build/client/_app/immutable/chunks/C5KYKPa8.js.gz +0 -0
  34. package/build/client/_app/immutable/chunks/CBDzfqXr.js +1 -0
  35. package/build/client/_app/immutable/chunks/CBDzfqXr.js.br +0 -0
  36. package/build/client/_app/immutable/chunks/CBDzfqXr.js.gz +0 -0
  37. package/build/client/_app/immutable/chunks/Cp9dXlPT.js +1 -0
  38. package/build/client/_app/immutable/chunks/Cp9dXlPT.js.br +0 -0
  39. package/build/client/_app/immutable/chunks/Cp9dXlPT.js.gz +0 -0
  40. package/build/client/_app/immutable/chunks/D0daF8Eh.js +2 -0
  41. package/build/client/_app/immutable/chunks/D0daF8Eh.js.br +0 -0
  42. package/build/client/_app/immutable/chunks/D0daF8Eh.js.gz +0 -0
  43. package/build/client/_app/immutable/chunks/D4SoBmS0.js +1 -0
  44. package/build/client/_app/immutable/chunks/D4SoBmS0.js.br +0 -0
  45. package/build/client/_app/immutable/chunks/D4SoBmS0.js.gz +0 -0
  46. package/build/client/_app/immutable/chunks/DpVrWha3.js +1 -0
  47. package/build/client/_app/immutable/chunks/DpVrWha3.js.br +0 -0
  48. package/build/client/_app/immutable/chunks/DpVrWha3.js.gz +0 -0
  49. package/build/client/_app/immutable/chunks/DyXQogav.js +1 -0
  50. package/build/client/_app/immutable/chunks/DyXQogav.js.br +0 -0
  51. package/build/client/_app/immutable/chunks/DyXQogav.js.gz +0 -0
  52. package/build/client/_app/immutable/chunks/Gs0cNFYG.js +1 -0
  53. package/build/client/_app/immutable/chunks/Gs0cNFYG.js.br +0 -0
  54. package/build/client/_app/immutable/chunks/Gs0cNFYG.js.gz +0 -0
  55. package/build/client/_app/immutable/chunks/NXeHtWpC.js +1 -0
  56. package/build/client/_app/immutable/chunks/NXeHtWpC.js.br +0 -0
  57. package/build/client/_app/immutable/chunks/NXeHtWpC.js.gz +0 -0
  58. package/build/client/_app/immutable/chunks/i0D5dc1Y.js +1 -0
  59. package/build/client/_app/immutable/chunks/i0D5dc1Y.js.br +0 -0
  60. package/build/client/_app/immutable/chunks/i0D5dc1Y.js.gz +0 -0
  61. package/build/client/_app/immutable/chunks/nnWk1BBo.js +1 -0
  62. package/build/client/_app/immutable/chunks/nnWk1BBo.js.br +0 -0
  63. package/build/client/_app/immutable/chunks/nnWk1BBo.js.gz +0 -0
  64. package/build/client/_app/immutable/entry/app.CVz6aYsT.js +2 -0
  65. package/build/client/_app/immutable/entry/app.CVz6aYsT.js.br +0 -0
  66. package/build/client/_app/immutable/entry/app.CVz6aYsT.js.gz +0 -0
  67. package/build/client/_app/immutable/entry/start.Bt5tVOz8.js +1 -0
  68. package/build/client/_app/immutable/entry/start.Bt5tVOz8.js.br +2 -0
  69. package/build/client/_app/immutable/entry/start.Bt5tVOz8.js.gz +0 -0
  70. package/build/client/_app/immutable/nodes/0.C2sXq0eH.js +1 -0
  71. package/build/client/_app/immutable/nodes/0.C2sXq0eH.js.br +0 -0
  72. package/build/client/_app/immutable/nodes/0.C2sXq0eH.js.gz +0 -0
  73. package/build/client/_app/immutable/nodes/1.BBtxY46Q.js +1 -0
  74. package/build/client/_app/immutable/nodes/1.BBtxY46Q.js.br +0 -0
  75. package/build/client/_app/immutable/nodes/1.BBtxY46Q.js.gz +0 -0
  76. package/build/client/_app/immutable/nodes/2.D0pSa9ko.js +9 -0
  77. package/build/client/_app/immutable/nodes/2.D0pSa9ko.js.br +0 -0
  78. package/build/client/_app/immutable/nodes/2.D0pSa9ko.js.gz +0 -0
  79. package/build/client/_app/version.json +1 -0
  80. package/build/client/_app/version.json.br +0 -0
  81. package/build/client/_app/version.json.gz +0 -0
  82. package/build/client/robots.txt +3 -0
  83. package/build/client/robots.txt.br +0 -0
  84. package/build/client/robots.txt.gz +0 -0
  85. package/build/env.js +70 -0
  86. package/build/env.js.map +1 -0
  87. package/build/handler.js +26 -0
  88. package/build/handler.js.map +1 -0
  89. package/build/index.js +149 -0
  90. package/build/index.js.map +1 -0
  91. package/build/server/chunks/chunks/edgeLinkModes.js-CfRqrZtd.js +50 -0
  92. package/build/server/chunks/chunks/edgeLinkModes.js-CfRqrZtd.js.map +1 -0
  93. package/build/server/chunks/chunks/environment.js-Bf8x1V_n.js +16 -0
  94. package/build/server/chunks/chunks/environment.js-Bf8x1V_n.js.map +1 -0
  95. package/build/server/chunks/chunks/exports.js-DFR3riS9.js +217 -0
  96. package/build/server/chunks/chunks/exports.js-DFR3riS9.js.map +1 -0
  97. package/build/server/chunks/chunks/false.js-CRHihH2U.js +4 -0
  98. package/build/server/chunks/chunks/false.js-CRHihH2U.js.map +1 -0
  99. package/build/server/chunks/chunks/graphRepository.js-D2DARfVY.js +280 -0
  100. package/build/server/chunks/chunks/graphRepository.js-D2DARfVY.js.map +1 -0
  101. package/build/server/chunks/chunks/internal.js-D8EA_he2.js +119 -0
  102. package/build/server/chunks/chunks/internal.js-D8EA_he2.js.map +1 -0
  103. package/build/server/chunks/chunks/mindbrainClient.js-BFAJqRSL.js +108 -0
  104. package/build/server/chunks/chunks/mindbrainClient.js-BFAJqRSL.js.map +1 -0
  105. package/build/server/chunks/chunks/ontologyInspect.js-Dm3l7KgF.js +13 -0
  106. package/build/server/chunks/chunks/ontologyInspect.js-Dm3l7KgF.js.map +1 -0
  107. package/build/server/chunks/chunks/render-context.js-CTu5Wkzp.js +475 -0
  108. package/build/server/chunks/chunks/render-context.js-CTu5Wkzp.js.map +1 -0
  109. package/build/server/chunks/chunks/renderer.js-DsOhU1UZ.js +1243 -0
  110. package/build/server/chunks/chunks/renderer.js-DsOhU1UZ.js.map +1 -0
  111. package/build/server/chunks/chunks/root.js-DCnlE3XY.js +2815 -0
  112. package/build/server/chunks/chunks/root.js-DCnlE3XY.js.map +1 -0
  113. package/build/server/chunks/chunks/shared-server.js-DaWdgxVh.js +11 -0
  114. package/build/server/chunks/chunks/shared-server.js-DaWdgxVh.js.map +1 -0
  115. package/build/server/chunks/chunks/shared.js-DuDDTJVi.js +1338 -0
  116. package/build/server/chunks/chunks/shared.js-DuDDTJVi.js.map +1 -0
  117. package/build/server/chunks/chunks/utils.js-DGYJFmnf.js +39 -0
  118. package/build/server/chunks/chunks/utils.js-DGYJFmnf.js.map +1 -0
  119. package/build/server/chunks/entries/endpoints/api/brain/_...path_/_server.ts.js-MgPpKBks.js +82 -0
  120. package/build/server/chunks/entries/endpoints/api/brain/_...path_/_server.ts.js-MgPpKBks.js.map +1 -0
  121. package/build/server/chunks/entries/endpoints/api/brain/health/_server.ts.js-DnJQNmWV.js +19 -0
  122. package/build/server/chunks/entries/endpoints/api/brain/health/_server.ts.js-DnJQNmWV.js.map +1 -0
  123. package/build/server/chunks/entries/endpoints/api/graph/_server.ts.js-Bxo7qHVz.js +37 -0
  124. package/build/server/chunks/entries/endpoints/api/graph/_server.ts.js-Bxo7qHVz.js.map +1 -0
  125. package/build/server/chunks/entries/endpoints/api/graph/count/_server.ts.js-BajaLnqp.js +37 -0
  126. package/build/server/chunks/entries/endpoints/api/graph/count/_server.ts.js-BajaLnqp.js.map +1 -0
  127. package/build/server/chunks/entries/endpoints/api/graph/ontologies/_server.ts.js-BFq2mbbX.js +146 -0
  128. package/build/server/chunks/entries/endpoints/api/graph/ontologies/_server.ts.js-BFq2mbbX.js.map +1 -0
  129. package/build/server/chunks/entries/endpoints/api/graph/schema-registry/_server.ts.js-Dyfsc-VA.js +154 -0
  130. package/build/server/chunks/entries/endpoints/api/graph/schema-registry/_server.ts.js-Dyfsc-VA.js.map +1 -0
  131. package/build/server/chunks/entries/endpoints/api/projections/catalog/_server.ts.js-Ds1RymA0.js +351 -0
  132. package/build/server/chunks/entries/endpoints/api/projections/catalog/_server.ts.js-Ds1RymA0.js.map +1 -0
  133. package/build/server/chunks/entries/fallbacks/error.svelte.js-B7V4yZjo.js +51 -0
  134. package/build/server/chunks/entries/fallbacks/error.svelte.js-B7V4yZjo.js.map +1 -0
  135. package/build/server/chunks/entries/pages/_layout.svelte.js-CoC9BAeH.js +15 -0
  136. package/build/server/chunks/entries/pages/_layout.svelte.js-CoC9BAeH.js.map +1 -0
  137. package/build/server/chunks/entries/pages/_page.svelte.js-DMEbD3K6.js +891 -0
  138. package/build/server/chunks/entries/pages/_page.svelte.js-DMEbD3K6.js.map +1 -0
  139. package/build/server/chunks/handler-BjXBCd1c.js +1698 -0
  140. package/build/server/chunks/handler-BjXBCd1c.js.map +1 -0
  141. package/build/server/chunks/index.js-BJYcV8V7.js +4183 -0
  142. package/build/server/chunks/index.js-BJYcV8V7.js.map +1 -0
  143. package/build/server/chunks/manifest.js-Ddaot0P4.js +91 -0
  144. package/build/server/chunks/manifest.js-Ddaot0P4.js.map +1 -0
  145. package/build/server/chunks/nodes/0.js-87v83UX9.js +9 -0
  146. package/build/server/chunks/nodes/0.js-87v83UX9.js.map +1 -0
  147. package/build/server/chunks/nodes/1.js-BRigw_9J.js +9 -0
  148. package/build/server/chunks/nodes/1.js-BRigw_9J.js.map +1 -0
  149. package/build/server/chunks/nodes/2.js-D9-B_qyX.js +9 -0
  150. package/build/server/chunks/nodes/2.js-D9-B_qyX.js.map +1 -0
  151. package/build/shims.js +33 -0
  152. package/build/shims.js.map +1 -0
  153. package/fixtures/minimal-graph.sqlite +0 -0
  154. package/package.json +81 -0
  155. package/scripts/backend-sqlite.mjs +190 -0
  156. package/scripts/build-serenity-v6-concept-review-pack.mjs +493 -0
  157. package/scripts/build-serenity-v6-review-pack.mjs +479 -0
  158. package/scripts/create-serenity-production-v6.mjs +627 -0
  159. package/scripts/dev-sqlite.mjs +86 -0
  160. package/scripts/export-serenity-v6-backup.mjs +178 -0
  161. package/scripts/import-serenity-v6-user-decisions.mjs +543 -0
  162. package/scripts/lib/sqlite-runtime.mjs +197 -0
  163. package/scripts/materialize-serenity-v6-snapshots.mjs +675 -0
  164. package/scripts/publish-npm.mjs +134 -0
  165. package/scripts/seed-immeuble-projections.mjs +169 -0
  166. package/scripts/studio-sqlite.mjs +74 -0
@@ -0,0 +1,1698 @@
1
+ import '../../shims.js';
2
+ import * as fs from 'node:fs';
3
+ import fs__default, { readdirSync, statSync, createReadStream } from 'node:fs';
4
+ import path, { resolve, sep, join, normalize } from 'node:path';
5
+ import process from 'node:process';
6
+ import http from 'node:http';
7
+ import { setImmediate } from 'node:timers';
8
+ import * as qs from 'node:querystring';
9
+ import { Readable } from 'node:stream';
10
+ import { S as SvelteKitError } from './chunks/shared.js-DuDDTJVi.js';
11
+ import { S as Server } from './index.js-BJYcV8V7.js';
12
+ import { m as manifest } from './manifest.js-Ddaot0P4.js';
13
+ import { env, dir, env_prefix } from '../../env.js';
14
+ import { format } from 'node:url';
15
+
16
+ function totalist(dir, callback, pre='') {
17
+ dir = resolve('.', dir);
18
+ let arr = readdirSync(dir);
19
+ let i=0, abs, stats;
20
+ for (; i < arr.length; i++) {
21
+ abs = join(dir, arr[i]);
22
+ stats = statSync(abs);
23
+ stats.isDirectory()
24
+ ? totalist(abs, callback, join(pre, arr[i]))
25
+ : callback(join(pre, arr[i]), abs, stats);
26
+ }
27
+ }
28
+
29
+ /**
30
+ * @typedef ParsedURL
31
+ * @type {import('.').ParsedURL}
32
+ */
33
+
34
+ /**
35
+ * @typedef Request
36
+ * @property {string} url
37
+ * @property {ParsedURL} _parsedUrl
38
+ */
39
+
40
+ /**
41
+ * @param {Request} req
42
+ * @returns {ParsedURL|void}
43
+ */
44
+ function parse$1(req) {
45
+ let raw = req.url;
46
+ if (raw == null) return;
47
+
48
+ let prev = req._parsedUrl;
49
+ if (prev && prev.raw === raw) return prev;
50
+
51
+ let pathname=raw, search='', query;
52
+
53
+ if (raw.length > 1) {
54
+ let idx = raw.indexOf('?', 1);
55
+
56
+ if (idx !== -1) {
57
+ search = raw.substring(idx);
58
+ pathname = raw.substring(0, idx);
59
+ if (search.length > 1) {
60
+ query = qs.parse(search.substring(1));
61
+ }
62
+ }
63
+ }
64
+
65
+ return req._parsedUrl = { pathname, search, query, raw };
66
+ }
67
+
68
+ const mimes = {
69
+ "3g2": "video/3gpp2",
70
+ "3gp": "video/3gpp",
71
+ "3gpp": "video/3gpp",
72
+ "3mf": "model/3mf",
73
+ "aac": "audio/aac",
74
+ "ac": "application/pkix-attr-cert",
75
+ "adp": "audio/adpcm",
76
+ "adts": "audio/aac",
77
+ "ai": "application/postscript",
78
+ "aml": "application/automationml-aml+xml",
79
+ "amlx": "application/automationml-amlx+zip",
80
+ "amr": "audio/amr",
81
+ "apng": "image/apng",
82
+ "appcache": "text/cache-manifest",
83
+ "appinstaller": "application/appinstaller",
84
+ "appx": "application/appx",
85
+ "appxbundle": "application/appxbundle",
86
+ "asc": "application/pgp-keys",
87
+ "atom": "application/atom+xml",
88
+ "atomcat": "application/atomcat+xml",
89
+ "atomdeleted": "application/atomdeleted+xml",
90
+ "atomsvc": "application/atomsvc+xml",
91
+ "au": "audio/basic",
92
+ "avci": "image/avci",
93
+ "avcs": "image/avcs",
94
+ "avif": "image/avif",
95
+ "aw": "application/applixware",
96
+ "bdoc": "application/bdoc",
97
+ "bin": "application/octet-stream",
98
+ "bmp": "image/bmp",
99
+ "bpk": "application/octet-stream",
100
+ "btf": "image/prs.btif",
101
+ "btif": "image/prs.btif",
102
+ "buffer": "application/octet-stream",
103
+ "ccxml": "application/ccxml+xml",
104
+ "cdfx": "application/cdfx+xml",
105
+ "cdmia": "application/cdmi-capability",
106
+ "cdmic": "application/cdmi-container",
107
+ "cdmid": "application/cdmi-domain",
108
+ "cdmio": "application/cdmi-object",
109
+ "cdmiq": "application/cdmi-queue",
110
+ "cer": "application/pkix-cert",
111
+ "cgm": "image/cgm",
112
+ "cjs": "application/node",
113
+ "class": "application/java-vm",
114
+ "coffee": "text/coffeescript",
115
+ "conf": "text/plain",
116
+ "cpl": "application/cpl+xml",
117
+ "cpt": "application/mac-compactpro",
118
+ "crl": "application/pkix-crl",
119
+ "css": "text/css",
120
+ "csv": "text/csv",
121
+ "cu": "application/cu-seeme",
122
+ "cwl": "application/cwl",
123
+ "cww": "application/prs.cww",
124
+ "davmount": "application/davmount+xml",
125
+ "dbk": "application/docbook+xml",
126
+ "deb": "application/octet-stream",
127
+ "def": "text/plain",
128
+ "deploy": "application/octet-stream",
129
+ "dib": "image/bmp",
130
+ "disposition-notification": "message/disposition-notification",
131
+ "dist": "application/octet-stream",
132
+ "distz": "application/octet-stream",
133
+ "dll": "application/octet-stream",
134
+ "dmg": "application/octet-stream",
135
+ "dms": "application/octet-stream",
136
+ "doc": "application/msword",
137
+ "dot": "application/msword",
138
+ "dpx": "image/dpx",
139
+ "drle": "image/dicom-rle",
140
+ "dsc": "text/prs.lines.tag",
141
+ "dssc": "application/dssc+der",
142
+ "dtd": "application/xml-dtd",
143
+ "dump": "application/octet-stream",
144
+ "dwd": "application/atsc-dwd+xml",
145
+ "ear": "application/java-archive",
146
+ "ecma": "application/ecmascript",
147
+ "elc": "application/octet-stream",
148
+ "emf": "image/emf",
149
+ "eml": "message/rfc822",
150
+ "emma": "application/emma+xml",
151
+ "emotionml": "application/emotionml+xml",
152
+ "eps": "application/postscript",
153
+ "epub": "application/epub+zip",
154
+ "exe": "application/octet-stream",
155
+ "exi": "application/exi",
156
+ "exp": "application/express",
157
+ "exr": "image/aces",
158
+ "ez": "application/andrew-inset",
159
+ "fdf": "application/fdf",
160
+ "fdt": "application/fdt+xml",
161
+ "fits": "image/fits",
162
+ "g3": "image/g3fax",
163
+ "gbr": "application/rpki-ghostbusters",
164
+ "geojson": "application/geo+json",
165
+ "gif": "image/gif",
166
+ "glb": "model/gltf-binary",
167
+ "gltf": "model/gltf+json",
168
+ "gml": "application/gml+xml",
169
+ "gpx": "application/gpx+xml",
170
+ "gram": "application/srgs",
171
+ "grxml": "application/srgs+xml",
172
+ "gxf": "application/gxf",
173
+ "gz": "application/gzip",
174
+ "h261": "video/h261",
175
+ "h263": "video/h263",
176
+ "h264": "video/h264",
177
+ "heic": "image/heic",
178
+ "heics": "image/heic-sequence",
179
+ "heif": "image/heif",
180
+ "heifs": "image/heif-sequence",
181
+ "hej2": "image/hej2k",
182
+ "held": "application/atsc-held+xml",
183
+ "hjson": "application/hjson",
184
+ "hlp": "application/winhlp",
185
+ "hqx": "application/mac-binhex40",
186
+ "hsj2": "image/hsj2",
187
+ "htm": "text/html",
188
+ "html": "text/html",
189
+ "ics": "text/calendar",
190
+ "ief": "image/ief",
191
+ "ifb": "text/calendar",
192
+ "iges": "model/iges",
193
+ "igs": "model/iges",
194
+ "img": "application/octet-stream",
195
+ "in": "text/plain",
196
+ "ini": "text/plain",
197
+ "ink": "application/inkml+xml",
198
+ "inkml": "application/inkml+xml",
199
+ "ipfix": "application/ipfix",
200
+ "iso": "application/octet-stream",
201
+ "its": "application/its+xml",
202
+ "jade": "text/jade",
203
+ "jar": "application/java-archive",
204
+ "jhc": "image/jphc",
205
+ "jls": "image/jls",
206
+ "jp2": "image/jp2",
207
+ "jpe": "image/jpeg",
208
+ "jpeg": "image/jpeg",
209
+ "jpf": "image/jpx",
210
+ "jpg": "image/jpeg",
211
+ "jpg2": "image/jp2",
212
+ "jpgm": "image/jpm",
213
+ "jpgv": "video/jpeg",
214
+ "jph": "image/jph",
215
+ "jpm": "image/jpm",
216
+ "jpx": "image/jpx",
217
+ "js": "text/javascript",
218
+ "json": "application/json",
219
+ "json5": "application/json5",
220
+ "jsonld": "application/ld+json",
221
+ "jsonml": "application/jsonml+json",
222
+ "jsx": "text/jsx",
223
+ "jt": "model/jt",
224
+ "jxr": "image/jxr",
225
+ "jxra": "image/jxra",
226
+ "jxrs": "image/jxrs",
227
+ "jxs": "image/jxs",
228
+ "jxsc": "image/jxsc",
229
+ "jxsi": "image/jxsi",
230
+ "jxss": "image/jxss",
231
+ "kar": "audio/midi",
232
+ "ktx": "image/ktx",
233
+ "ktx2": "image/ktx2",
234
+ "less": "text/less",
235
+ "lgr": "application/lgr+xml",
236
+ "list": "text/plain",
237
+ "litcoffee": "text/coffeescript",
238
+ "log": "text/plain",
239
+ "lostxml": "application/lost+xml",
240
+ "lrf": "application/octet-stream",
241
+ "m1v": "video/mpeg",
242
+ "m21": "application/mp21",
243
+ "m2a": "audio/mpeg",
244
+ "m2v": "video/mpeg",
245
+ "m3a": "audio/mpeg",
246
+ "m4a": "audio/mp4",
247
+ "m4p": "application/mp4",
248
+ "m4s": "video/iso.segment",
249
+ "ma": "application/mathematica",
250
+ "mads": "application/mads+xml",
251
+ "maei": "application/mmt-aei+xml",
252
+ "man": "text/troff",
253
+ "manifest": "text/cache-manifest",
254
+ "map": "application/json",
255
+ "mar": "application/octet-stream",
256
+ "markdown": "text/markdown",
257
+ "mathml": "application/mathml+xml",
258
+ "mb": "application/mathematica",
259
+ "mbox": "application/mbox",
260
+ "md": "text/markdown",
261
+ "mdx": "text/mdx",
262
+ "me": "text/troff",
263
+ "mesh": "model/mesh",
264
+ "meta4": "application/metalink4+xml",
265
+ "metalink": "application/metalink+xml",
266
+ "mets": "application/mets+xml",
267
+ "mft": "application/rpki-manifest",
268
+ "mid": "audio/midi",
269
+ "midi": "audio/midi",
270
+ "mime": "message/rfc822",
271
+ "mj2": "video/mj2",
272
+ "mjp2": "video/mj2",
273
+ "mjs": "text/javascript",
274
+ "mml": "text/mathml",
275
+ "mods": "application/mods+xml",
276
+ "mov": "video/quicktime",
277
+ "mp2": "audio/mpeg",
278
+ "mp21": "application/mp21",
279
+ "mp2a": "audio/mpeg",
280
+ "mp3": "audio/mpeg",
281
+ "mp4": "video/mp4",
282
+ "mp4a": "audio/mp4",
283
+ "mp4s": "application/mp4",
284
+ "mp4v": "video/mp4",
285
+ "mpd": "application/dash+xml",
286
+ "mpe": "video/mpeg",
287
+ "mpeg": "video/mpeg",
288
+ "mpf": "application/media-policy-dataset+xml",
289
+ "mpg": "video/mpeg",
290
+ "mpg4": "video/mp4",
291
+ "mpga": "audio/mpeg",
292
+ "mpp": "application/dash-patch+xml",
293
+ "mrc": "application/marc",
294
+ "mrcx": "application/marcxml+xml",
295
+ "ms": "text/troff",
296
+ "mscml": "application/mediaservercontrol+xml",
297
+ "msh": "model/mesh",
298
+ "msi": "application/octet-stream",
299
+ "msix": "application/msix",
300
+ "msixbundle": "application/msixbundle",
301
+ "msm": "application/octet-stream",
302
+ "msp": "application/octet-stream",
303
+ "mtl": "model/mtl",
304
+ "musd": "application/mmt-usd+xml",
305
+ "mxf": "application/mxf",
306
+ "mxmf": "audio/mobile-xmf",
307
+ "mxml": "application/xv+xml",
308
+ "n3": "text/n3",
309
+ "nb": "application/mathematica",
310
+ "nq": "application/n-quads",
311
+ "nt": "application/n-triples",
312
+ "obj": "model/obj",
313
+ "oda": "application/oda",
314
+ "oga": "audio/ogg",
315
+ "ogg": "audio/ogg",
316
+ "ogv": "video/ogg",
317
+ "ogx": "application/ogg",
318
+ "omdoc": "application/omdoc+xml",
319
+ "onepkg": "application/onenote",
320
+ "onetmp": "application/onenote",
321
+ "onetoc": "application/onenote",
322
+ "onetoc2": "application/onenote",
323
+ "opf": "application/oebps-package+xml",
324
+ "opus": "audio/ogg",
325
+ "otf": "font/otf",
326
+ "owl": "application/rdf+xml",
327
+ "oxps": "application/oxps",
328
+ "p10": "application/pkcs10",
329
+ "p7c": "application/pkcs7-mime",
330
+ "p7m": "application/pkcs7-mime",
331
+ "p7s": "application/pkcs7-signature",
332
+ "p8": "application/pkcs8",
333
+ "pdf": "application/pdf",
334
+ "pfr": "application/font-tdpfr",
335
+ "pgp": "application/pgp-encrypted",
336
+ "pkg": "application/octet-stream",
337
+ "pki": "application/pkixcmp",
338
+ "pkipath": "application/pkix-pkipath",
339
+ "pls": "application/pls+xml",
340
+ "png": "image/png",
341
+ "prc": "model/prc",
342
+ "prf": "application/pics-rules",
343
+ "provx": "application/provenance+xml",
344
+ "ps": "application/postscript",
345
+ "pskcxml": "application/pskc+xml",
346
+ "pti": "image/prs.pti",
347
+ "qt": "video/quicktime",
348
+ "raml": "application/raml+yaml",
349
+ "rapd": "application/route-apd+xml",
350
+ "rdf": "application/rdf+xml",
351
+ "relo": "application/p2p-overlay+xml",
352
+ "rif": "application/reginfo+xml",
353
+ "rl": "application/resource-lists+xml",
354
+ "rld": "application/resource-lists-diff+xml",
355
+ "rmi": "audio/midi",
356
+ "rnc": "application/relax-ng-compact-syntax",
357
+ "rng": "application/xml",
358
+ "roa": "application/rpki-roa",
359
+ "roff": "text/troff",
360
+ "rq": "application/sparql-query",
361
+ "rs": "application/rls-services+xml",
362
+ "rsat": "application/atsc-rsat+xml",
363
+ "rsd": "application/rsd+xml",
364
+ "rsheet": "application/urc-ressheet+xml",
365
+ "rss": "application/rss+xml",
366
+ "rtf": "text/rtf",
367
+ "rtx": "text/richtext",
368
+ "rusd": "application/route-usd+xml",
369
+ "s3m": "audio/s3m",
370
+ "sbml": "application/sbml+xml",
371
+ "scq": "application/scvp-cv-request",
372
+ "scs": "application/scvp-cv-response",
373
+ "sdp": "application/sdp",
374
+ "senmlx": "application/senml+xml",
375
+ "sensmlx": "application/sensml+xml",
376
+ "ser": "application/java-serialized-object",
377
+ "setpay": "application/set-payment-initiation",
378
+ "setreg": "application/set-registration-initiation",
379
+ "sgi": "image/sgi",
380
+ "sgm": "text/sgml",
381
+ "sgml": "text/sgml",
382
+ "shex": "text/shex",
383
+ "shf": "application/shf+xml",
384
+ "shtml": "text/html",
385
+ "sieve": "application/sieve",
386
+ "sig": "application/pgp-signature",
387
+ "sil": "audio/silk",
388
+ "silo": "model/mesh",
389
+ "siv": "application/sieve",
390
+ "slim": "text/slim",
391
+ "slm": "text/slim",
392
+ "sls": "application/route-s-tsid+xml",
393
+ "smi": "application/smil+xml",
394
+ "smil": "application/smil+xml",
395
+ "snd": "audio/basic",
396
+ "so": "application/octet-stream",
397
+ "spdx": "text/spdx",
398
+ "spp": "application/scvp-vp-response",
399
+ "spq": "application/scvp-vp-request",
400
+ "spx": "audio/ogg",
401
+ "sql": "application/sql",
402
+ "sru": "application/sru+xml",
403
+ "srx": "application/sparql-results+xml",
404
+ "ssdl": "application/ssdl+xml",
405
+ "ssml": "application/ssml+xml",
406
+ "stk": "application/hyperstudio",
407
+ "stl": "model/stl",
408
+ "stpx": "model/step+xml",
409
+ "stpxz": "model/step-xml+zip",
410
+ "stpz": "model/step+zip",
411
+ "styl": "text/stylus",
412
+ "stylus": "text/stylus",
413
+ "svg": "image/svg+xml",
414
+ "svgz": "image/svg+xml",
415
+ "swidtag": "application/swid+xml",
416
+ "t": "text/troff",
417
+ "t38": "image/t38",
418
+ "td": "application/urc-targetdesc+xml",
419
+ "tei": "application/tei+xml",
420
+ "teicorpus": "application/tei+xml",
421
+ "text": "text/plain",
422
+ "tfi": "application/thraud+xml",
423
+ "tfx": "image/tiff-fx",
424
+ "tif": "image/tiff",
425
+ "tiff": "image/tiff",
426
+ "toml": "application/toml",
427
+ "tr": "text/troff",
428
+ "trig": "application/trig",
429
+ "ts": "video/mp2t",
430
+ "tsd": "application/timestamped-data",
431
+ "tsv": "text/tab-separated-values",
432
+ "ttc": "font/collection",
433
+ "ttf": "font/ttf",
434
+ "ttl": "text/turtle",
435
+ "ttml": "application/ttml+xml",
436
+ "txt": "text/plain",
437
+ "u3d": "model/u3d",
438
+ "u8dsn": "message/global-delivery-status",
439
+ "u8hdr": "message/global-headers",
440
+ "u8mdn": "message/global-disposition-notification",
441
+ "u8msg": "message/global",
442
+ "ubj": "application/ubjson",
443
+ "uri": "text/uri-list",
444
+ "uris": "text/uri-list",
445
+ "urls": "text/uri-list",
446
+ "vcard": "text/vcard",
447
+ "vrml": "model/vrml",
448
+ "vtt": "text/vtt",
449
+ "vxml": "application/voicexml+xml",
450
+ "war": "application/java-archive",
451
+ "wasm": "application/wasm",
452
+ "wav": "audio/wav",
453
+ "weba": "audio/webm",
454
+ "webm": "video/webm",
455
+ "webmanifest": "application/manifest+json",
456
+ "webp": "image/webp",
457
+ "wgsl": "text/wgsl",
458
+ "wgt": "application/widget",
459
+ "wif": "application/watcherinfo+xml",
460
+ "wmf": "image/wmf",
461
+ "woff": "font/woff",
462
+ "woff2": "font/woff2",
463
+ "wrl": "model/vrml",
464
+ "wsdl": "application/wsdl+xml",
465
+ "wspolicy": "application/wspolicy+xml",
466
+ "x3d": "model/x3d+xml",
467
+ "x3db": "model/x3d+fastinfoset",
468
+ "x3dbz": "model/x3d+binary",
469
+ "x3dv": "model/x3d-vrml",
470
+ "x3dvz": "model/x3d+vrml",
471
+ "x3dz": "model/x3d+xml",
472
+ "xaml": "application/xaml+xml",
473
+ "xav": "application/xcap-att+xml",
474
+ "xca": "application/xcap-caps+xml",
475
+ "xcs": "application/calendar+xml",
476
+ "xdf": "application/xcap-diff+xml",
477
+ "xdssc": "application/dssc+xml",
478
+ "xel": "application/xcap-el+xml",
479
+ "xenc": "application/xenc+xml",
480
+ "xer": "application/patch-ops-error+xml",
481
+ "xfdf": "application/xfdf",
482
+ "xht": "application/xhtml+xml",
483
+ "xhtml": "application/xhtml+xml",
484
+ "xhvml": "application/xv+xml",
485
+ "xlf": "application/xliff+xml",
486
+ "xm": "audio/xm",
487
+ "xml": "text/xml",
488
+ "xns": "application/xcap-ns+xml",
489
+ "xop": "application/xop+xml",
490
+ "xpl": "application/xproc+xml",
491
+ "xsd": "application/xml",
492
+ "xsf": "application/prs.xsf+xml",
493
+ "xsl": "application/xml",
494
+ "xslt": "application/xml",
495
+ "xspf": "application/xspf+xml",
496
+ "xvm": "application/xv+xml",
497
+ "xvml": "application/xv+xml",
498
+ "yaml": "text/yaml",
499
+ "yang": "application/yang",
500
+ "yin": "application/yin+xml",
501
+ "yml": "text/yaml",
502
+ "zip": "application/zip"
503
+ };
504
+
505
+ function lookup(extn) {
506
+ let tmp = ('' + extn).trim().toLowerCase();
507
+ let idx = tmp.lastIndexOf('.');
508
+ return mimes[!~idx ? tmp : tmp.substring(++idx)];
509
+ }
510
+
511
+ const noop = () => {};
512
+
513
+ function isMatch(uri, arr) {
514
+ for (let i=0; i < arr.length; i++) {
515
+ if (arr[i].test(uri)) return true;
516
+ }
517
+ }
518
+
519
+ function toAssume(uri, extns) {
520
+ let i=0, x, len=uri.length - 1;
521
+ if (uri.charCodeAt(len) === 47) {
522
+ uri = uri.substring(0, len);
523
+ }
524
+
525
+ let arr=[], tmp=`${uri}/index`;
526
+ for (; i < extns.length; i++) {
527
+ x = extns[i] ? `.${extns[i]}` : '';
528
+ if (uri) arr.push(uri + x);
529
+ arr.push(tmp + x);
530
+ }
531
+
532
+ return arr;
533
+ }
534
+
535
+ function viaCache(cache, uri, extns) {
536
+ let i=0, data, arr=toAssume(uri, extns);
537
+ for (; i < arr.length; i++) {
538
+ if (data = cache[arr[i]]) return data;
539
+ }
540
+ }
541
+
542
+ function viaLocal(dir, isEtag, uri, extns) {
543
+ let i=0, arr=toAssume(uri, extns);
544
+ let abs, stats, name, headers;
545
+ for (; i < arr.length; i++) {
546
+ abs = normalize(
547
+ join(dir, name=arr[i])
548
+ );
549
+
550
+ if (abs.startsWith(dir) && fs.existsSync(abs)) {
551
+ stats = fs.statSync(abs);
552
+ if (stats.isDirectory()) continue;
553
+ headers = toHeaders(name, stats, isEtag);
554
+ headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store';
555
+ return { abs, stats, headers };
556
+ }
557
+ }
558
+ }
559
+
560
+ function is404(req, res) {
561
+ return (res.statusCode=404,res.end());
562
+ }
563
+
564
+ function send(req, res, file, stats, headers) {
565
+ let code=200, tmp, opts={};
566
+ headers = { ...headers };
567
+
568
+ for (let key in headers) {
569
+ tmp = res.getHeader(key);
570
+ if (tmp) headers[key] = tmp;
571
+ }
572
+
573
+ if (tmp = res.getHeader('content-type')) {
574
+ headers['Content-Type'] = tmp;
575
+ }
576
+
577
+ if (req.headers.range) {
578
+ code = 206;
579
+ let [x, y] = req.headers.range.replace('bytes=', '').split('-');
580
+ let end = opts.end = parseInt(y, 10) || stats.size - 1;
581
+ let start = opts.start = parseInt(x, 10) || 0;
582
+
583
+ if (end >= stats.size) {
584
+ end = stats.size - 1;
585
+ }
586
+
587
+ if (start >= stats.size) {
588
+ res.setHeader('Content-Range', `bytes */${stats.size}`);
589
+ res.statusCode = 416;
590
+ return res.end();
591
+ }
592
+
593
+ headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
594
+ headers['Content-Length'] = (end - start + 1);
595
+ headers['Accept-Ranges'] = 'bytes';
596
+ }
597
+
598
+ res.writeHead(code, headers);
599
+ fs.createReadStream(file, opts).pipe(res);
600
+ }
601
+
602
+ const ENCODING = {
603
+ '.br': 'br',
604
+ '.gz': 'gzip',
605
+ };
606
+
607
+ function toHeaders(name, stats, isEtag) {
608
+ let enc = ENCODING[name.slice(-3)];
609
+
610
+ let ctype = lookup(name.slice(0, enc && -3)) || '';
611
+ if (ctype === 'text/html') ctype += ';charset=utf-8';
612
+
613
+ let headers = {
614
+ 'Content-Length': stats.size,
615
+ 'Content-Type': ctype,
616
+ 'Last-Modified': stats.mtime.toUTCString(),
617
+ };
618
+
619
+ if (enc) headers['Content-Encoding'] = enc;
620
+ if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`;
621
+
622
+ return headers;
623
+ }
624
+
625
+ function sirv (dir, opts={}) {
626
+ dir = resolve(dir || '.');
627
+
628
+ let isNotFound = opts.onNoMatch || is404;
629
+ let setHeaders = opts.setHeaders || noop;
630
+
631
+ let extensions = opts.extensions || ['html', 'htm'];
632
+ let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz');
633
+ let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br');
634
+
635
+ const FILES = {};
636
+
637
+ let fallback = '/';
638
+ let isEtag = !!opts.etag;
639
+ let isSPA = !!opts.single;
640
+ if (typeof opts.single === 'string') {
641
+ let idx = opts.single.lastIndexOf('.');
642
+ fallback += !!~idx ? opts.single.substring(0, idx) : opts.single;
643
+ }
644
+
645
+ let ignores = [];
646
+ if (opts.ignores !== false) {
647
+ ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn
648
+ if (opts.dotfiles) ignores.push(/\/\.\w/);
649
+ else ignores.push(/\/\.well-known/);
650
+ [].concat(opts.ignores || []).forEach(x => {
651
+ ignores.push(new RegExp(x, 'i'));
652
+ });
653
+ }
654
+
655
+ let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
656
+ if (cc && opts.immutable) cc += ',immutable';
657
+ else if (cc && opts.maxAge === 0) cc += ',must-revalidate';
658
+
659
+ if (!opts.dev) {
660
+ totalist(dir, (name, abs, stats) => {
661
+ if (/\.well-known[\\+\/]/.test(name)) ; // keep
662
+ else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
663
+
664
+ let headers = toHeaders(name, stats, isEtag);
665
+ if (cc) headers['Cache-Control'] = cc;
666
+
667
+ FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers };
668
+ });
669
+ }
670
+
671
+ let lookup = opts.dev ? viaLocal.bind(0, dir + sep, isEtag) : viaCache.bind(0, FILES);
672
+
673
+ return function (req, res, next) {
674
+ let extns = [''];
675
+ let pathname = parse$1(req).pathname;
676
+ let val = req.headers['accept-encoding'] || '';
677
+ if (gzips && val.includes('gzip')) extns.unshift(...gzips);
678
+ if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots);
679
+ extns.push(...extensions); // [...br, ...gz, orig, ...exts]
680
+
681
+ if (pathname.indexOf('%') !== -1) {
682
+ try { pathname = decodeURI(pathname); }
683
+ catch (err) { /* malform uri */ }
684
+ }
685
+
686
+ let data = lookup(pathname, extns) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns);
687
+ if (!data) return next ? next() : isNotFound(req, res);
688
+
689
+ if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) {
690
+ res.writeHead(304);
691
+ return res.end();
692
+ }
693
+
694
+ if (gzips || brots) {
695
+ res.setHeader('Vary', 'Accept-Encoding');
696
+ }
697
+
698
+ setHeaders(res, pathname, data.stats);
699
+ send(req, res, data.abs, data.stats, data.headers);
700
+ };
701
+ }
702
+
703
+ /**
704
+ * @param {string|RegExp} input The route pattern
705
+ * @param {boolean} [loose] Allow open-ended matching. Ignored with `RegExp` input.
706
+ */
707
+ function parse(input, loose) {
708
+ if (input instanceof RegExp) return { keys:false, pattern:input };
709
+ var c, o, tmp, ext, keys=[], pattern='', arr = input.split('/');
710
+ arr[0] || arr.shift();
711
+
712
+ while (tmp = arr.shift()) {
713
+ c = tmp[0];
714
+ if (c === '*') {
715
+ keys.push(c);
716
+ pattern += tmp[1] === '?' ? '(?:/(.*))?' : '/(.*)';
717
+ } else if (c === ':') {
718
+ o = tmp.indexOf('?', 1);
719
+ ext = tmp.indexOf('.', 1);
720
+ keys.push( tmp.substring(1, !!~o ? o : !!~ext ? ext : tmp.length) );
721
+ pattern += !!~o && !~ext ? '(?:/([^/]+?))?' : '/([^/]+?)';
722
+ if (!!~ext) pattern += (!!~o ? '?' : '') + '\\' + tmp.substring(ext);
723
+ } else {
724
+ pattern += '/' + tmp;
725
+ }
726
+ }
727
+
728
+ return {
729
+ keys: keys,
730
+ pattern: new RegExp('^' + pattern + (loose ? '(?=$|\/)' : '\/?$'), 'i')
731
+ };
732
+ }
733
+
734
+ const MAP = {
735
+ "": 0,
736
+ GET: 1,
737
+ HEAD: 2,
738
+ PATCH: 3,
739
+ OPTIONS: 4,
740
+ CONNECT: 5,
741
+ DELETE: 6,
742
+ TRACE: 7,
743
+ POST: 8,
744
+ PUT: 9,
745
+ };
746
+
747
+ class Trouter {
748
+ constructor() {
749
+ this.routes = [];
750
+
751
+ this.all = this.add.bind(this, '');
752
+ this.get = this.add.bind(this, 'GET');
753
+ this.head = this.add.bind(this, 'HEAD');
754
+ this.patch = this.add.bind(this, 'PATCH');
755
+ this.options = this.add.bind(this, 'OPTIONS');
756
+ this.connect = this.add.bind(this, 'CONNECT');
757
+ this.delete = this.add.bind(this, 'DELETE');
758
+ this.trace = this.add.bind(this, 'TRACE');
759
+ this.post = this.add.bind(this, 'POST');
760
+ this.put = this.add.bind(this, 'PUT');
761
+ }
762
+
763
+ use(route, ...fns) {
764
+ let handlers = [].concat.apply([], fns);
765
+ let { keys, pattern } = parse(route, true);
766
+ this.routes.push({ keys, pattern, method: '', handlers, midx: MAP[''] });
767
+ return this;
768
+ }
769
+
770
+ add(method, route, ...fns) {
771
+ let { keys, pattern } = parse(route);
772
+ let handlers = [].concat.apply([], fns);
773
+ this.routes.push({ keys, pattern, method, handlers, midx: MAP[method] });
774
+ return this;
775
+ }
776
+
777
+ find(method, url) {
778
+ let midx = MAP[method];
779
+ let isHEAD = (midx === 2);
780
+ let i=0, j=0, k, tmp, arr=this.routes;
781
+ let matches=[], params={}, handlers=[];
782
+ for (; i < arr.length; i++) {
783
+ tmp = arr[i];
784
+ if (tmp.midx === midx || tmp.midx === 0 || (isHEAD && tmp.midx===1) ) {
785
+ if (tmp.keys === false) {
786
+ matches = tmp.pattern.exec(url);
787
+ if (matches === null) continue;
788
+ if (matches.groups !== void 0) for (k in matches.groups) params[k]=matches.groups[k];
789
+ tmp.handlers.length > 1 ? (handlers=handlers.concat(tmp.handlers)) : handlers.push(tmp.handlers[0]);
790
+ } else if (tmp.keys.length > 0) {
791
+ matches = tmp.pattern.exec(url);
792
+ if (matches === null) continue;
793
+ for (j=0; j < tmp.keys.length;) params[tmp.keys[j]]=matches[++j];
794
+ tmp.handlers.length > 1 ? (handlers=handlers.concat(tmp.handlers)) : handlers.push(tmp.handlers[0]);
795
+ } else if (tmp.pattern.test(url)) {
796
+ tmp.handlers.length > 1 ? (handlers=handlers.concat(tmp.handlers)) : handlers.push(tmp.handlers[0]);
797
+ }
798
+ } // else not a match
799
+ }
800
+
801
+ return { params, handlers };
802
+ }
803
+ }
804
+
805
+ function onError(err, req, res) {
806
+ let code = typeof err.status === 'number' && err.status;
807
+ code = res.statusCode = (code && code >= 100 ? code : 500);
808
+ if (typeof err === 'string' || Buffer.isBuffer(err)) res.end(err);
809
+ else res.end(err.message || http.STATUS_CODES[code]);
810
+ }
811
+
812
+ const mount = fn => fn instanceof Polka ? fn.attach : fn;
813
+
814
+ class Polka extends Trouter {
815
+ constructor(opts={}) {
816
+ super();
817
+ this.parse = parse$1;
818
+ this.server = opts.server;
819
+ this.handler = this.handler.bind(this);
820
+ this.onError = opts.onError || onError; // catch-all handler
821
+ this.onNoMatch = opts.onNoMatch || this.onError.bind(null, { status: 404 });
822
+ this.attach = (req, res) => setImmediate(this.handler, req, res);
823
+ }
824
+
825
+ use(base, ...fns) {
826
+ if (base === '/') {
827
+ super.use(base, fns.map(mount));
828
+ } else if (typeof base === 'function' || base instanceof Polka) {
829
+ super.use('/', [base, ...fns].map(mount));
830
+ } else {
831
+ super.use(base,
832
+ (req, _, next) => {
833
+ if (typeof base === 'string') {
834
+ let len = base.length;
835
+ base.startsWith('/') || len++;
836
+ req.url = req.url.substring(len) || '/';
837
+ req.path = req.path.substring(len) || '/';
838
+ } else {
839
+ req.url = req.url.replace(base, '') || '/';
840
+ req.path = req.path.replace(base, '') || '/';
841
+ }
842
+ if (req.url.charAt(0) !== '/') {
843
+ req.url = '/' + req.url;
844
+ }
845
+ next();
846
+ },
847
+ fns.map(mount),
848
+ (req, _, next) => {
849
+ req.path = req._parsedUrl.pathname;
850
+ req.url = req.path + req._parsedUrl.search;
851
+ next();
852
+ }
853
+ );
854
+ }
855
+ return this; // chainable
856
+ }
857
+
858
+ listen() {
859
+ (this.server = this.server || http.createServer()).on('request', this.attach);
860
+ this.server.listen.apply(this.server, arguments);
861
+ return this;
862
+ }
863
+
864
+ handler(req, res, next) {
865
+ let info = this.parse(req), path = info.pathname;
866
+ let obj = this.find(req.method, req.path=path);
867
+
868
+ req.url = path + info.search;
869
+ req.originalUrl = req.originalUrl || req.url;
870
+ req.query = info.query || {};
871
+ req.search = info.search;
872
+ req.params = obj.params;
873
+
874
+ if (path.length > 1 && path.indexOf('%', 1) !== -1) {
875
+ for (let k in req.params) {
876
+ try { req.params[k] = decodeURIComponent(req.params[k]); }
877
+ catch (e) { /* malform uri segment */ }
878
+ }
879
+ }
880
+
881
+ let i=0, arr=obj.handlers.concat(this.onNoMatch), len=arr.length;
882
+ let loop = async () => res.finished || (i < len) && arr[i++](req, res, next);
883
+ (next = next || (err => err ? this.onError(err, req, res, next) : loop().catch(next)))(); // init
884
+ }
885
+ }
886
+
887
+ function polka (opts) {
888
+ return new Polka(opts);
889
+ }
890
+
891
+ var defaultParseOptions = {
892
+ decodeValues: true,
893
+ map: false,
894
+ silent: false,
895
+ split: "auto", // auto = split strings but not arrays
896
+ };
897
+
898
+ function isForbiddenKey(key) {
899
+ return typeof key !== "string" || key in {};
900
+ }
901
+
902
+ function createNullObj() {
903
+ return Object.create(null);
904
+ }
905
+
906
+ function isNonEmptyString(str) {
907
+ return typeof str === "string" && !!str.trim();
908
+ }
909
+
910
+ function parseString(setCookieValue, options) {
911
+ var parts = setCookieValue.split(";").filter(isNonEmptyString);
912
+
913
+ var nameValuePairStr = parts.shift();
914
+ var parsed = parseNameValuePair(nameValuePairStr);
915
+ var name = parsed.name;
916
+ var value = parsed.value;
917
+
918
+ options = options
919
+ ? Object.assign({}, defaultParseOptions, options)
920
+ : defaultParseOptions;
921
+
922
+ if (isForbiddenKey(name)) {
923
+ return null;
924
+ }
925
+
926
+ try {
927
+ value = options.decodeValues ? decodeURIComponent(value) : value; // decode cookie value
928
+ } catch (e) {
929
+ console.error(
930
+ "set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.",
931
+ e
932
+ );
933
+ }
934
+
935
+ var cookie = createNullObj();
936
+ cookie.name = name;
937
+ cookie.value = value;
938
+
939
+ parts.forEach(function (part) {
940
+ var sides = part.split("=");
941
+ var key = sides.shift().trimLeft().toLowerCase();
942
+ if (isForbiddenKey(key)) {
943
+ return;
944
+ }
945
+ var value = sides.join("=");
946
+ if (key === "expires") {
947
+ cookie.expires = new Date(value);
948
+ } else if (key === "max-age") {
949
+ var n = parseInt(value, 10);
950
+ if (!Number.isNaN(n)) cookie.maxAge = n;
951
+ } else if (key === "secure") {
952
+ cookie.secure = true;
953
+ } else if (key === "httponly") {
954
+ cookie.httpOnly = true;
955
+ } else if (key === "samesite") {
956
+ cookie.sameSite = value;
957
+ } else if (key === "partitioned") {
958
+ cookie.partitioned = true;
959
+ } else if (key) {
960
+ cookie[key] = value;
961
+ }
962
+ });
963
+
964
+ return cookie;
965
+ }
966
+
967
+ function parseNameValuePair(nameValuePairStr) {
968
+ // Parses name-value-pair according to rfc6265bis draft
969
+
970
+ var name = "";
971
+ var value = "";
972
+ var nameValueArr = nameValuePairStr.split("=");
973
+ if (nameValueArr.length > 1) {
974
+ name = nameValueArr.shift();
975
+ value = nameValueArr.join("="); // everything after the first =, joined by a "=" if there was more than one part
976
+ } else {
977
+ value = nameValuePairStr;
978
+ }
979
+
980
+ return { name: name, value: value };
981
+ }
982
+
983
+ function parseSetCookie(input, options) {
984
+ options = options
985
+ ? Object.assign({}, defaultParseOptions, options)
986
+ : defaultParseOptions;
987
+
988
+ if (!input) {
989
+ if (!options.map) {
990
+ return [];
991
+ } else {
992
+ return createNullObj();
993
+ }
994
+ }
995
+
996
+ if (input.headers) {
997
+ if (typeof input.headers.getSetCookie === "function") {
998
+ // for fetch responses - they combine headers of the same type in the headers array,
999
+ // but getSetCookie returns an uncombined array
1000
+ input = input.headers.getSetCookie();
1001
+ } else if (input.headers["set-cookie"]) {
1002
+ // fast-path for node.js (which automatically normalizes header names to lower-case)
1003
+ input = input.headers["set-cookie"];
1004
+ } else {
1005
+ // slow-path for other environments - see #25
1006
+ var sch =
1007
+ input.headers[
1008
+ Object.keys(input.headers).find(function (key) {
1009
+ return key.toLowerCase() === "set-cookie";
1010
+ })
1011
+ ];
1012
+ // warn if called on a request-like object with a cookie header rather than a set-cookie header - see #34, 36
1013
+ if (!sch && input.headers.cookie && !options.silent) {
1014
+ console.warn(
1015
+ "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."
1016
+ );
1017
+ }
1018
+ input = sch;
1019
+ }
1020
+ }
1021
+
1022
+ var split = options.split;
1023
+ var isArray = Array.isArray(input);
1024
+
1025
+ if (split === "auto") {
1026
+ split = !isArray;
1027
+ }
1028
+
1029
+ if (!isArray) {
1030
+ input = [input];
1031
+ }
1032
+
1033
+ input = input.filter(isNonEmptyString);
1034
+
1035
+ if (split) {
1036
+ input = input.map(splitCookiesString).flat();
1037
+ }
1038
+
1039
+ if (!options.map) {
1040
+ return input
1041
+ .map(function (str) {
1042
+ return parseString(str, options);
1043
+ })
1044
+ .filter(Boolean);
1045
+ } else {
1046
+ var cookies = createNullObj();
1047
+ return input.reduce(function (cookies, str) {
1048
+ var cookie = parseString(str, options);
1049
+ if (cookie && !isForbiddenKey(cookie.name)) {
1050
+ cookies[cookie.name] = cookie;
1051
+ }
1052
+ return cookies;
1053
+ }, cookies);
1054
+ }
1055
+ }
1056
+
1057
+ /*
1058
+ Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
1059
+ that are within a single set-cookie field-value, such as in the Expires portion.
1060
+
1061
+ This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
1062
+ Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
1063
+ React Native's fetch does this for *every* header, including set-cookie.
1064
+
1065
+ Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
1066
+ Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
1067
+ */
1068
+ function splitCookiesString(cookiesString) {
1069
+ if (Array.isArray(cookiesString)) {
1070
+ return cookiesString;
1071
+ }
1072
+ if (typeof cookiesString !== "string") {
1073
+ return [];
1074
+ }
1075
+
1076
+ var cookiesStrings = [];
1077
+ var pos = 0;
1078
+ var start;
1079
+ var ch;
1080
+ var lastComma;
1081
+ var nextStart;
1082
+ var cookiesSeparatorFound;
1083
+
1084
+ function skipWhitespace() {
1085
+ while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
1086
+ pos += 1;
1087
+ }
1088
+ return pos < cookiesString.length;
1089
+ }
1090
+
1091
+ function notSpecialChar() {
1092
+ ch = cookiesString.charAt(pos);
1093
+
1094
+ return ch !== "=" && ch !== ";" && ch !== ",";
1095
+ }
1096
+
1097
+ while (pos < cookiesString.length) {
1098
+ start = pos;
1099
+ cookiesSeparatorFound = false;
1100
+
1101
+ while (skipWhitespace()) {
1102
+ ch = cookiesString.charAt(pos);
1103
+ if (ch === ",") {
1104
+ // ',' is a cookie separator if we have later first '=', not ';' or ','
1105
+ lastComma = pos;
1106
+ pos += 1;
1107
+
1108
+ skipWhitespace();
1109
+ nextStart = pos;
1110
+
1111
+ while (pos < cookiesString.length && notSpecialChar()) {
1112
+ pos += 1;
1113
+ }
1114
+
1115
+ // currently special character
1116
+ if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
1117
+ // we found cookies separator
1118
+ cookiesSeparatorFound = true;
1119
+ // pos is inside the next cookie, so back up and return it.
1120
+ pos = nextStart;
1121
+ cookiesStrings.push(cookiesString.substring(start, lastComma));
1122
+ start = pos;
1123
+ } else {
1124
+ // in param ',' or param separator ';',
1125
+ // we continue from that comma
1126
+ pos = lastComma + 1;
1127
+ }
1128
+ } else {
1129
+ pos += 1;
1130
+ }
1131
+ }
1132
+
1133
+ if (!cookiesSeparatorFound || pos >= cookiesString.length) {
1134
+ cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
1135
+ }
1136
+ }
1137
+
1138
+ return cookiesStrings;
1139
+ }
1140
+
1141
+ // named export for CJS
1142
+ parseSetCookie.parseSetCookie = parseSetCookie;
1143
+ // for backwards compatibility
1144
+ parseSetCookie.parse = parseSetCookie;
1145
+ parseSetCookie.parseString = parseString;
1146
+ parseSetCookie.splitCookiesString = splitCookiesString;
1147
+
1148
+ /**
1149
+ * @param {import('http').IncomingMessage} req
1150
+ * @param {number} [body_size_limit]
1151
+ */
1152
+ function get_raw_body(req, body_size_limit) {
1153
+ const h = req.headers;
1154
+
1155
+ if (!h['content-type']) {
1156
+ return null;
1157
+ }
1158
+
1159
+ const content_length = Number(h['content-length']);
1160
+
1161
+ // check if no request body
1162
+ if (
1163
+ (req.httpVersionMajor === 1 && isNaN(content_length) && h['transfer-encoding'] == null) ||
1164
+ content_length === 0
1165
+ ) {
1166
+ return null;
1167
+ }
1168
+
1169
+ if (req.destroyed) {
1170
+ const readable = new ReadableStream();
1171
+ void readable.cancel();
1172
+ return readable;
1173
+ }
1174
+
1175
+ let size = 0;
1176
+ let cancelled = false;
1177
+
1178
+ return new ReadableStream({
1179
+ start(controller) {
1180
+ if (body_size_limit !== undefined && content_length > body_size_limit) {
1181
+ let message = `Content-length of ${content_length} exceeds limit of ${body_size_limit} bytes.`;
1182
+
1183
+ if (body_size_limit === 0) {
1184
+ // https://github.com/sveltejs/kit/pull/11589
1185
+ // TODO this exists to aid migration — remove in a future version
1186
+ message += ' To disable body size limits, specify Infinity rather than 0.';
1187
+ }
1188
+
1189
+ const error = new SvelteKitError(413, 'Payload Too Large', message);
1190
+
1191
+ controller.error(error);
1192
+ return;
1193
+ }
1194
+
1195
+ req.on('error', (error) => {
1196
+ cancelled = true;
1197
+ controller.error(error);
1198
+ });
1199
+
1200
+ req.on('end', () => {
1201
+ if (cancelled) return;
1202
+ controller.close();
1203
+ });
1204
+
1205
+ req.on('data', (chunk) => {
1206
+ if (cancelled) return;
1207
+
1208
+ size += chunk.length;
1209
+ if (size > content_length) {
1210
+ cancelled = true;
1211
+
1212
+ const constraint = content_length ? 'content-length' : 'BODY_SIZE_LIMIT';
1213
+ const message = `request body size exceeded ${constraint} of ${content_length}`;
1214
+
1215
+ const error = new SvelteKitError(413, 'Payload Too Large', message);
1216
+ controller.error(error);
1217
+
1218
+ return;
1219
+ }
1220
+
1221
+ controller.enqueue(chunk);
1222
+
1223
+ if (controller.desiredSize === null || controller.desiredSize <= 0) {
1224
+ req.pause();
1225
+ }
1226
+ });
1227
+ },
1228
+
1229
+ pull() {
1230
+ req.resume();
1231
+ },
1232
+
1233
+ cancel(reason) {
1234
+ cancelled = true;
1235
+ req.destroy(reason);
1236
+ }
1237
+ });
1238
+ }
1239
+
1240
+ /**
1241
+ * @param {{
1242
+ * request: import('http').IncomingMessage;
1243
+ * base: string;
1244
+ * bodySizeLimit?: number;
1245
+ * }} options
1246
+ * @returns {Promise<Request>}
1247
+ */
1248
+ // TODO 3.0 make the signature synchronous?
1249
+ // eslint-disable-next-line @typescript-eslint/require-await
1250
+ async function getRequest({ request, base, bodySizeLimit }) {
1251
+ let headers = /** @type {Record<string, string>} */ (request.headers);
1252
+ if (request.httpVersionMajor >= 2) {
1253
+ // the Request constructor rejects headers with ':' in the name
1254
+ headers = Object.assign({}, headers);
1255
+ // https://www.rfc-editor.org/rfc/rfc9113.html#section-8.3.1-2.3.5
1256
+ if (headers[':authority']) {
1257
+ headers.host = headers[':authority'];
1258
+ }
1259
+ delete headers[':authority'];
1260
+ delete headers[':method'];
1261
+ delete headers[':path'];
1262
+ delete headers[':scheme'];
1263
+ }
1264
+
1265
+ // TODO: Whenever Node >=22 is minimum supported version, we can use `request.readableAborted`
1266
+ // @see https://github.com/nodejs/node/blob/5cf3c3e24c7257a0c6192ed8ef71efec8ddac22b/lib/internal/streams/readable.js#L1443-L1453
1267
+ const controller = new AbortController();
1268
+ let errored = false;
1269
+ let end_emitted = false;
1270
+ request.once('error', () => (errored = true));
1271
+ request.once('end', () => (end_emitted = true));
1272
+ request.once('close', () => {
1273
+ if ((errored || request.destroyed) && !end_emitted) {
1274
+ controller.abort();
1275
+ }
1276
+ });
1277
+
1278
+ return new Request(base + request.url, {
1279
+ // @ts-expect-error
1280
+ duplex: 'half',
1281
+ method: request.method,
1282
+ headers: Object.entries(headers),
1283
+ signal: controller.signal,
1284
+ body:
1285
+ request.method === 'GET' || request.method === 'HEAD'
1286
+ ? undefined
1287
+ : get_raw_body(request, bodySizeLimit)
1288
+ });
1289
+ }
1290
+
1291
+ /**
1292
+ * @param {import('http').ServerResponse} res
1293
+ * @param {Response} response
1294
+ * @returns {Promise<void>}
1295
+ */
1296
+ // TODO 3.0 make the signature synchronous?
1297
+ // eslint-disable-next-line @typescript-eslint/require-await
1298
+ async function setResponse(res, response) {
1299
+ for (const [key, value] of response.headers) {
1300
+ try {
1301
+ res.setHeader(
1302
+ key,
1303
+ key === 'set-cookie'
1304
+ ? splitCookiesString(
1305
+ // This is absurd but necessary, TODO: investigate why
1306
+ /** @type {string}*/ (response.headers.get(key))
1307
+ )
1308
+ : value
1309
+ );
1310
+ } catch (error) {
1311
+ res.getHeaderNames().forEach((name) => res.removeHeader(name));
1312
+ res.writeHead(500).end(String(error));
1313
+ return;
1314
+ }
1315
+ }
1316
+
1317
+ res.writeHead(response.status);
1318
+
1319
+ if (!response.body) {
1320
+ res.end();
1321
+ return;
1322
+ }
1323
+
1324
+ if (response.body.locked) {
1325
+ res.end(
1326
+ 'Fatal error: Response body is locked. ' +
1327
+ "This can happen when the response was already read (for example through 'response.json()' or 'response.text()')."
1328
+ );
1329
+ return;
1330
+ }
1331
+
1332
+ const reader = response.body.getReader();
1333
+
1334
+ if (res.destroyed) {
1335
+ void reader.cancel();
1336
+ return;
1337
+ }
1338
+
1339
+ const cancel = (/** @type {Error|undefined} */ error) => {
1340
+ res.off('close', cancel);
1341
+ res.off('error', cancel);
1342
+
1343
+ // If the reader has already been interrupted with an error earlier,
1344
+ // then it will appear here, it is useless, but it needs to be catch.
1345
+ reader.cancel(error).catch(() => {});
1346
+ if (error) res.destroy(error);
1347
+ };
1348
+
1349
+ res.on('close', cancel);
1350
+ res.on('error', cancel);
1351
+
1352
+ void next();
1353
+ async function next() {
1354
+ try {
1355
+ for (;;) {
1356
+ const { done, value } = await reader.read();
1357
+
1358
+ if (done) break;
1359
+
1360
+ if (!res.write(value)) {
1361
+ res.once('drain', next);
1362
+ return;
1363
+ }
1364
+ }
1365
+ res.end();
1366
+ } catch (error) {
1367
+ cancel(error instanceof Error ? error : new Error(String(error)));
1368
+ }
1369
+ }
1370
+ }
1371
+
1372
+ /**
1373
+ * Converts a file on disk to a readable stream
1374
+ * @param {string} file
1375
+ * @returns {ReadableStream}
1376
+ * @since 2.4.0
1377
+ */
1378
+ function createReadableStream(file) {
1379
+ return /** @type {ReadableStream} */ (Readable.toWeb(createReadStream(file)));
1380
+ }
1381
+
1382
+ /**
1383
+ * Parses the given value into number of bytes.
1384
+ *
1385
+ * @param {string} value - Size in bytes. Can also be specified with a unit suffix kilobytes (K), megabytes (M), or gigabytes (G).
1386
+ * @returns {number}
1387
+ */
1388
+ function parse_as_bytes(value) {
1389
+ const multiplier =
1390
+ {
1391
+ K: 1024,
1392
+ M: 1024 * 1024,
1393
+ G: 1024 * 1024 * 1024
1394
+ }[value[value.length - 1]?.toUpperCase()] ?? 1;
1395
+ return Number(multiplier != 1 ? value.substring(0, value.length - 1) : value) * multiplier;
1396
+ }
1397
+
1398
+ /**
1399
+ * Parses and validates an origin URL.
1400
+ *
1401
+ * @param {string | undefined} value - Origin URL with http:// or https:// protocol
1402
+ * @returns {string | undefined} The validated origin, or undefined if value is undefined
1403
+ * @throws {Error} If value is provided but invalid
1404
+ */
1405
+ function parse_origin(value) {
1406
+ if (value === undefined) {
1407
+ return undefined;
1408
+ }
1409
+
1410
+ const trimmed = value.trim();
1411
+
1412
+ let url;
1413
+ try {
1414
+ url = new URL(trimmed);
1415
+ } catch (error) {
1416
+ throw new Error(
1417
+ `Invalid ORIGIN: '${trimmed}'. ` +
1418
+ `ORIGIN must be a valid URL with http:// or https:// protocol. ` +
1419
+ `For example: 'http://localhost:3000' or 'https://my.site'`,
1420
+ { cause: error }
1421
+ );
1422
+ }
1423
+
1424
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
1425
+ throw new Error(
1426
+ `Invalid ORIGIN: '${trimmed}'. ` +
1427
+ `Only http:// and https:// protocols are supported. ` +
1428
+ `Received protocol: ${url.protocol}`
1429
+ );
1430
+ }
1431
+
1432
+ return url.origin;
1433
+ }
1434
+
1435
+ /**
1436
+ * Formats the address the server is listening on.
1437
+ *
1438
+ * @param {string | false} path
1439
+ * @param {string} host
1440
+ * @param {string | false} port
1441
+ * @param {import('node:net').AddressInfo | string | null} address
1442
+ * @returns {string}
1443
+ */
1444
+ function format_listening_address(path, host, port, address) {
1445
+ if (path) {
1446
+ return path;
1447
+ }
1448
+
1449
+ if (address && typeof address === 'object') {
1450
+ return format({
1451
+ protocol: 'http:',
1452
+ hostname: address.address,
1453
+ port: address.port
1454
+ });
1455
+ }
1456
+
1457
+ return format({
1458
+ protocol: 'http:',
1459
+ hostname: host,
1460
+ port: String(port)
1461
+ });
1462
+ }
1463
+
1464
+ const prerendered = new Set([]);
1465
+
1466
+ const server = new Server(manifest);
1467
+
1468
+ // parse_origin validates ORIGIN and throws descriptive errors for invalid values
1469
+ const origin = parse_origin(env('ORIGIN', undefined));
1470
+
1471
+ const xff_depth = parseInt(env('XFF_DEPTH', '1'));
1472
+ const address_header = env('ADDRESS_HEADER', '').toLowerCase();
1473
+ const protocol_header = env('PROTOCOL_HEADER', '').toLowerCase();
1474
+ const host_header = env('HOST_HEADER', '').toLowerCase();
1475
+ const port_header = env('PORT_HEADER', '').toLowerCase();
1476
+
1477
+ const body_size_limit = parse_as_bytes(env('BODY_SIZE_LIMIT', '512K'));
1478
+
1479
+ if (isNaN(body_size_limit)) {
1480
+ throw new Error(
1481
+ `Invalid BODY_SIZE_LIMIT: '${env('BODY_SIZE_LIMIT')}'. Please provide a numeric value.`
1482
+ );
1483
+ }
1484
+
1485
+ const asset_dir = `${dir}/client${""}`;
1486
+
1487
+ await server.init({
1488
+ env: /** @type {Record<string, string>} */ (process.env),
1489
+ read: (file) => createReadableStream(`${asset_dir}/${file}`)
1490
+ });
1491
+
1492
+ /**
1493
+ * @param {string} path
1494
+ * @param {boolean} client
1495
+ */
1496
+ function serve(path, client = false) {
1497
+ return fs__default.existsSync(path)
1498
+ ? sirv(path, {
1499
+ etag: true,
1500
+ gzip: true,
1501
+ brotli: true,
1502
+ setHeaders: client
1503
+ ? (res, pathname) => {
1504
+ // only apply to build directory, not e.g. version.json
1505
+ if (
1506
+ pathname.startsWith(`/${manifest.appPath}/immutable/`) &&
1507
+ res.statusCode === 200
1508
+ ) {
1509
+ res.setHeader('cache-control', 'public,max-age=31536000,immutable');
1510
+ }
1511
+ }
1512
+ : undefined
1513
+ })
1514
+ : undefined;
1515
+ }
1516
+
1517
+ // required because the static file server ignores trailing slashes
1518
+ /** @returns {import('polka').Middleware} */
1519
+ function serve_prerendered() {
1520
+ const handler = serve(path.join(dir, 'prerendered'));
1521
+
1522
+ return (req, res, next) => {
1523
+ let { pathname, search, query } = parse$1(req);
1524
+
1525
+ try {
1526
+ pathname = decodeURIComponent(pathname);
1527
+ } catch {
1528
+ // ignore invalid URI
1529
+ }
1530
+
1531
+ if (prerendered.has(pathname)) {
1532
+ return handler?.(req, res, next);
1533
+ }
1534
+
1535
+ // remove or add trailing slash as appropriate
1536
+ let location = pathname.at(-1) === '/' ? pathname.slice(0, -1) : pathname + '/';
1537
+ if (prerendered.has(location)) {
1538
+ if (query) location += search;
1539
+ res.writeHead(308, { location }).end();
1540
+ } else {
1541
+ void next();
1542
+ }
1543
+ };
1544
+ }
1545
+
1546
+ /** @type {import('polka').Middleware} */
1547
+ const ssr = async (req, res) => {
1548
+ /** @type {Request} */
1549
+ let request;
1550
+
1551
+ try {
1552
+ request = await getRequest({
1553
+ base: origin || get_origin(req.headers),
1554
+ request: req,
1555
+ bodySizeLimit: body_size_limit
1556
+ });
1557
+ } catch {
1558
+ res.statusCode = 400;
1559
+ res.end('Bad Request');
1560
+ return;
1561
+ }
1562
+
1563
+ const response = await server.respond(request, {
1564
+ platform: { req },
1565
+ getClientAddress: () => {
1566
+ if (address_header) {
1567
+ if (!(address_header in req.headers)) {
1568
+ throw new Error(
1569
+ `Address header was specified with ${
1570
+ env_prefix + 'ADDRESS_HEADER'
1571
+ }=${address_header} but is absent from request`
1572
+ );
1573
+ }
1574
+
1575
+ const value = /** @type {string} */ (req.headers[address_header]) || '';
1576
+
1577
+ if (address_header === 'x-forwarded-for') {
1578
+ const addresses = value.split(',');
1579
+
1580
+ if (xff_depth < 1) {
1581
+ throw new Error(`${env_prefix + 'XFF_DEPTH'} must be a positive integer`);
1582
+ }
1583
+
1584
+ if (xff_depth > addresses.length) {
1585
+ throw new Error(
1586
+ `${env_prefix + 'XFF_DEPTH'} is ${xff_depth}, but only found ${
1587
+ addresses.length
1588
+ } addresses`
1589
+ );
1590
+ }
1591
+ return addresses[addresses.length - xff_depth].trim();
1592
+ }
1593
+
1594
+ return value;
1595
+ }
1596
+
1597
+ return (
1598
+ req.connection?.remoteAddress ||
1599
+ // @ts-expect-error
1600
+ req.connection?.socket?.remoteAddress ||
1601
+ req.socket?.remoteAddress ||
1602
+ // @ts-expect-error
1603
+ req.info?.remoteAddress
1604
+ );
1605
+ }
1606
+ });
1607
+
1608
+ // Reverse proxies such as nginx buffer responses by default (ignoring
1609
+ // `cache-control`), which breaks streaming responses like server-sent events.
1610
+ // `X-Accel-Buffering: no` opts out of that buffering and is a no-op on proxies
1611
+ // that don't recognise it. See https://github.com/sveltejs/kit/issues/15790
1612
+ if (response.headers.get('content-type') === 'text/event-stream') {
1613
+ response.headers.set('x-accel-buffering', 'no');
1614
+ }
1615
+
1616
+ await setResponse(res, response);
1617
+ };
1618
+
1619
+ /** @param {import('polka').Middleware[]} handlers */
1620
+ function sequence(handlers) {
1621
+ /** @type {import('polka').Middleware} */
1622
+ return (req, res, next) => {
1623
+ /**
1624
+ * @param {number} i
1625
+ * @returns {ReturnType<import('polka').Middleware>}
1626
+ */
1627
+ function handle(i) {
1628
+ if (i < handlers.length) {
1629
+ return handlers[i](req, res, () => handle(i + 1));
1630
+ } else {
1631
+ return next();
1632
+ }
1633
+ }
1634
+
1635
+ return handle(0);
1636
+ };
1637
+ }
1638
+
1639
+ /**
1640
+ * @param {string} name
1641
+ * @param {string | string[] | undefined} value
1642
+ * @returns {string | undefined}
1643
+ */
1644
+ function normalise_header(name, value) {
1645
+ if (!name) return undefined;
1646
+ if (Array.isArray(value)) {
1647
+ if (value.length === 0) return undefined;
1648
+ if (value.length === 1) return value[0];
1649
+ throw new Error(
1650
+ `Multiple values provided for ${name} header where only one expected: ${value}`
1651
+ );
1652
+ }
1653
+ return value;
1654
+ }
1655
+
1656
+ /**
1657
+ * @param {import('http').IncomingHttpHeaders} headers
1658
+ * @returns {string}
1659
+ */
1660
+ function get_origin(headers) {
1661
+ const protocol = decodeURIComponent(
1662
+ normalise_header(protocol_header, headers[protocol_header]) || 'https'
1663
+ );
1664
+
1665
+ // this helps us avoid host injections through the protocol header
1666
+ if (protocol.includes(':')) {
1667
+ throw new Error(
1668
+ `The ${protocol_header} header specified ${protocol} which is an invalid because it includes \`:\`. It should only contain the protocol scheme (e.g. \`https\`)`
1669
+ );
1670
+ }
1671
+
1672
+ const host =
1673
+ normalise_header(host_header, headers[host_header]) ||
1674
+ normalise_header('host', headers['host']);
1675
+ if (!host) {
1676
+ const header_names = host_header ? `${host_header} or host headers` : 'host header';
1677
+ throw new Error(
1678
+ `Could not determine host. The request must have a value provided by the ${header_names}`
1679
+ );
1680
+ }
1681
+
1682
+ const port = normalise_header(port_header, headers[port_header]);
1683
+ if (port && isNaN(+port)) {
1684
+ throw new Error(
1685
+ `The ${port_header} header specified ${port} which is an invalid port because it is not a number. The value should only contain the port number (e.g. 443)`
1686
+ );
1687
+ }
1688
+
1689
+ return port ? `${protocol}://${host}:${port}` : `${protocol}://${host}`;
1690
+ }
1691
+
1692
+ const handler = sequence(
1693
+ /** @type {(import('sirv').RequestHandler | import('polka').Middleware)[]} */
1694
+ ([serve(path.join(dir, 'client'), true), serve_prerendered(), ssr].filter(Boolean))
1695
+ );
1696
+
1697
+ export { format_listening_address as f, handler as h, polka as p };
1698
+ //# sourceMappingURL=handler-BjXBCd1c.js.map