@yaks/blob 0.0.0-stage → 0.2.36

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 (172) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +946 -2
  3. package/_dist/accepts.d.ts +38 -0
  4. package/_dist/accepts.d.ts.map +1 -0
  5. package/_dist/artifact.d.ts +29 -0
  6. package/_dist/artifact.d.ts.map +1 -0
  7. package/_dist/attachment.d.ts +53 -0
  8. package/_dist/attachment.d.ts.map +1 -0
  9. package/_dist/backend.d.ts +20 -0
  10. package/_dist/backend.d.ts.map +1 -0
  11. package/_dist/broken.d.ts +24 -0
  12. package/_dist/broken.d.ts.map +1 -0
  13. package/_dist/browser.d.ts +27 -0
  14. package/_dist/browser.d.ts.map +1 -0
  15. package/_dist/compare.d.ts +4 -0
  16. package/_dist/compare.d.ts.map +1 -0
  17. package/_dist/content_type.d.ts +20 -0
  18. package/_dist/content_type.d.ts.map +1 -0
  19. package/_dist/graph.d.ts +13 -0
  20. package/_dist/graph.d.ts.map +1 -0
  21. package/_dist/hydrate.d.ts +36 -0
  22. package/_dist/hydrate.d.ts.map +1 -0
  23. package/_dist/identify.d.ts +7 -0
  24. package/_dist/identify.d.ts.map +1 -0
  25. package/_dist/image.d.ts +37 -0
  26. package/_dist/image.d.ts.map +1 -0
  27. package/_dist/keywords.d.ts +10 -0
  28. package/_dist/keywords.d.ts.map +1 -0
  29. package/_dist/mime.d.ts +2 -0
  30. package/_dist/mime.d.ts.map +1 -0
  31. package/_dist/mod.d.ts +97 -0
  32. package/_dist/mod.d.ts.map +1 -0
  33. package/_dist/object-put.d.ts +2 -0
  34. package/_dist/object-put.d.ts.map +1 -0
  35. package/_dist/object.d.ts +175 -0
  36. package/_dist/object.d.ts.map +1 -0
  37. package/_dist/parts.d.ts +91 -0
  38. package/_dist/parts.d.ts.map +1 -0
  39. package/_dist/plugin.d.ts +38 -0
  40. package/_dist/plugin.d.ts.map +1 -0
  41. package/_dist/png.d.ts +14 -0
  42. package/_dist/png.d.ts.map +1 -0
  43. package/_dist/props.d.ts +20 -0
  44. package/_dist/props.d.ts.map +1 -0
  45. package/_dist/representation.d.ts +17 -0
  46. package/_dist/representation.d.ts.map +1 -0
  47. package/_dist/representation_rules.d.ts +3 -0
  48. package/_dist/representation_rules.d.ts.map +1 -0
  49. package/_dist/routes.d.ts +65 -0
  50. package/_dist/routes.d.ts.map +1 -0
  51. package/_dist/serve.d.ts +29 -0
  52. package/_dist/serve.d.ts.map +1 -0
  53. package/_dist/sha256.d.ts +26 -0
  54. package/_dist/sha256.d.ts.map +1 -0
  55. package/_dist/sqlite.d.ts +57 -0
  56. package/_dist/sqlite.d.ts.map +1 -0
  57. package/_dist/store.d.ts +41 -0
  58. package/_dist/store.d.ts.map +1 -0
  59. package/_dist/stream.d.ts +91 -0
  60. package/_dist/stream.d.ts.map +1 -0
  61. package/_dist/upload.d.ts +114 -0
  62. package/_dist/upload.d.ts.map +1 -0
  63. package/_dist/value.d.ts +62 -0
  64. package/_dist/value.d.ts.map +1 -0
  65. package/_dist/vocab.d.ts +13 -0
  66. package/_dist/vocab.d.ts.map +1 -0
  67. package/accepts.js +76 -0
  68. package/accepts.js.map +1 -0
  69. package/accepts.ts +95 -0
  70. package/artifact.js +50 -0
  71. package/artifact.js.map +1 -0
  72. package/artifact.ts +93 -0
  73. package/attachment.js +190 -0
  74. package/attachment.js.map +1 -0
  75. package/attachment.ts +201 -0
  76. package/backend.js +37 -0
  77. package/backend.js.map +1 -0
  78. package/backend.ts +44 -0
  79. package/broken.js +278 -0
  80. package/broken.js.map +1 -0
  81. package/broken.ts +217 -0
  82. package/browser.js +124 -0
  83. package/browser.js.map +1 -0
  84. package/browser.ts +179 -0
  85. package/compare.js +82 -0
  86. package/compare.js.map +1 -0
  87. package/compare.ts +90 -0
  88. package/content_type.js +43 -0
  89. package/content_type.js.map +1 -0
  90. package/content_type.ts +58 -0
  91. package/deno.json +1 -0
  92. package/fixed.js +53 -0
  93. package/fixed.js.map +1 -0
  94. package/fixed.ts +61 -0
  95. package/graph.js +15 -0
  96. package/graph.js.map +1 -0
  97. package/graph.ts +22 -0
  98. package/hydrate.js +69 -0
  99. package/hydrate.js.map +1 -0
  100. package/hydrate.ts +72 -0
  101. package/identify.js +38 -0
  102. package/identify.js.map +1 -0
  103. package/identify.ts +50 -0
  104. package/image.js +111 -0
  105. package/image.js.map +1 -0
  106. package/image.ts +120 -0
  107. package/keywords.js +28 -0
  108. package/keywords.js.map +1 -0
  109. package/keywords.ts +28 -0
  110. package/meta/blob.vocab.json +17 -0
  111. package/mime.js +72 -0
  112. package/mime.js.map +1 -0
  113. package/mime.ts +73 -0
  114. package/mod.js +97 -0
  115. package/mod.js.map +1 -0
  116. package/mod.ts +115 -0
  117. package/object-put.js +90 -0
  118. package/object-put.js.map +1 -0
  119. package/object-put.ts +114 -0
  120. package/object.js +369 -0
  121. package/object.js.map +1 -0
  122. package/object.ts +592 -0
  123. package/package.json +84 -4
  124. package/parts.js +354 -0
  125. package/parts.js.map +1 -0
  126. package/parts.ts +423 -0
  127. package/plugin.js +158 -0
  128. package/plugin.js.map +1 -0
  129. package/plugin.ts +184 -0
  130. package/png.js +74 -0
  131. package/png.js.map +1 -0
  132. package/png.ts +58 -0
  133. package/props.js +32 -0
  134. package/props.js.map +1 -0
  135. package/props.ts +47 -0
  136. package/purge.js +65 -0
  137. package/purge.js.map +1 -0
  138. package/purge.ts +72 -0
  139. package/representation.js +34 -0
  140. package/representation.js.map +1 -0
  141. package/representation.ts +44 -0
  142. package/representation_rules.js +44 -0
  143. package/representation_rules.js.map +1 -0
  144. package/representation_rules.ts +57 -0
  145. package/routes.js +454 -0
  146. package/routes.js.map +1 -0
  147. package/routes.ts +575 -0
  148. package/serve.js +196 -0
  149. package/serve.js.map +1 -0
  150. package/serve.ts +242 -0
  151. package/sha256.js +185 -0
  152. package/sha256.js.map +1 -0
  153. package/sha256.ts +210 -0
  154. package/sqlite.js +201 -0
  155. package/sqlite.js.map +1 -0
  156. package/sqlite.ts +250 -0
  157. package/store.js +40 -0
  158. package/store.js.map +1 -0
  159. package/store.ts +93 -0
  160. package/stream.js +203 -0
  161. package/stream.js.map +1 -0
  162. package/stream.ts +256 -0
  163. package/upload.js +256 -0
  164. package/upload.js.map +1 -0
  165. package/upload.ts +404 -0
  166. package/value.js +234 -0
  167. package/value.js.map +1 -0
  168. package/value.ts +281 -0
  169. package/vocab.js +27 -0
  170. package/vocab.js.map +1 -0
  171. package/vocab.json +123 -0
  172. package/vocab.ts +32 -0
package/upload.js ADDED
@@ -0,0 +1,256 @@
1
+ // An upload's write half, without a request anywhere in it: bytes kept under
2
+ // their address and the rows that name them, held to what the store takes.
3
+ // The door (./routes.ts) is one way bytes arrive; a letter's attachments and
4
+ // a fetched document are others, and each keeps them through here.
5
+ //
6
+ // The bytes' own SHA-256 is the object's key and the content row's eid, so
7
+ // the same file sent twice is one object and one row. What the bytes are
8
+ // called and what they are sit on a second row, their use, addressed off the
9
+ // first (`useOf`): derived, so an upload finds its own row without reading
10
+ // for it, and the same file sent again is that row renamed. They stay apart
11
+ // because they are two things, and because a component may not point at its
12
+ // own entity.
13
+ //
14
+ // Which words the two rows speak is a store's to say (`Naming`). This
15
+ // package's own are `artifact` and `attachment` (`artifacts`).
16
+ //
17
+ // It is its own entry (`@yaks/blob/upload`), since reading a type off the
18
+ // bytes loads the file-type detector (./identify.ts).
19
+ import { line, sub } from "@yaks/query";
20
+ import { digest, token } from "@yaks/graph/sha256";
21
+ import { size as said } from "@yaks/fp";
22
+ import { fits, taken, takes } from "./accepts.js";
23
+ import { contentType } from "./identify.js";
24
+ import { sizeOf } from "./image.js";
25
+ import { representation, represents } from "./representation.js";
26
+ import { hashing, lengthOf, stage, TooMany } from "./stream.js";
27
+ let UNKNOWN = 'application/octet-stream';
28
+ /** The scope of a representation where a store names none. */ export let SCOPE = 'blob';
29
+ /** The eid of the use of the bytes at `sha`: the row saying what they are
30
+ * called and what they are. */ export let useOf = (sha)=>digest(`attachment:${sha}`);
31
+ let comp = (rows, eid, name)=>rows.find((r)=>r.entity.eid == eid)?.[name];
32
+ let text = (v)=>typeof v == 'string' ? v : '';
33
+ /** This package's words: an `artifact` at the address, and an `attachment`
34
+ * naming it. */ export let artifacts = {
35
+ rows: ({ sha, use, mime, name, bytes })=>[
36
+ {
37
+ entity: {
38
+ eid: sha
39
+ },
40
+ artifact: {
41
+ address: sha,
42
+ media_type: mime,
43
+ size: bytes
44
+ }
45
+ },
46
+ {
47
+ entity: {
48
+ eid: use
49
+ },
50
+ attachment: {
51
+ artifact: sha,
52
+ media_type: mime,
53
+ ...name ? {
54
+ name
55
+ } : {}
56
+ }
57
+ }
58
+ ],
59
+ said: (rows, { sha, use })=>{
60
+ let file = comp(rows, use, 'attachment');
61
+ let artifact = comp(rows, sha, 'artifact');
62
+ let was = file ?? artifact;
63
+ if (!was) return null;
64
+ let [eid, name] = file ? [
65
+ use,
66
+ 'attachment'
67
+ ] : [
68
+ sha,
69
+ 'artifact'
70
+ ];
71
+ return {
72
+ mime: text(was.media_type) || text(artifact?.media_type),
73
+ name: text(file?.name),
74
+ fix: (mime)=>[
75
+ {
76
+ entity: {
77
+ eid
78
+ },
79
+ [name]: {
80
+ media_type: mime
81
+ },
82
+ $was: {
83
+ [name]: {
84
+ media_type: token(was.media_type)
85
+ }
86
+ }
87
+ }
88
+ ]
89
+ };
90
+ },
91
+ names: (sha)=>line`.entity.eid=${sha} .artifact|.attachment.artifact=${sha}`
92
+ };
93
+ /** Bytes not taken: too many, of a type not taken, or past the store's room.
94
+ * `status` is the HTTP status a door answers, and `code` its word for it. */ export class Untaken extends Error {
95
+ status;
96
+ code;
97
+ constructor(status, code, says){
98
+ super(says);
99
+ this.name = 'Untaken';
100
+ this.status = status;
101
+ this.code = code;
102
+ }
103
+ }
104
+ /** Refused, when `bytes` bytes, or bytes read as `type`, are not taken.
105
+ *
106
+ * ```ts
107
+ * import { admit, Untaken } from '@yaks/blob/upload'
108
+ * import { memoryBlobs } from '@yaks/blob'
109
+ * import { assertThrows } from '@std/assert'
110
+ *
111
+ * let at = { store: memoryBlobs(), accepts: { maxLength: 4096, contentMediaType: 'image/*' } }
112
+ * admit(at, 4096, 'image/png')
113
+ * assertThrows(() => admit(at, 4097), Untaken, 'this app takes files of at most 4 KB')
114
+ * assertThrows(() => admit(at, 10, 'text/plain'), Untaken, 'this app takes image/*, and this file is text/plain')
115
+ * assertThrows(() => admit({ ...at, limit: 1024 }, 2048), Untaken, 'a file is at most 1 KB here')
116
+ * ```
117
+ */ export let admit = (at, bytes, type)=>{
118
+ if (at.limit != null && bytes > at.limit) {
119
+ throw new Untaken(413, 'too_large', `a file is at most ${said(at.limit)} here`);
120
+ }
121
+ if (!fits(at.accepts, bytes)) {
122
+ throw new Untaken(413, 'too_large', `this app takes files of at most ${said(at.accepts.maxLength)}`);
123
+ }
124
+ if (type != null && !takes(at.accepts, type)) {
125
+ throw new Untaken(415, 'unsupported_media_type', `this app takes ${taken(at.accepts)}, and this file is ${type}`);
126
+ }
127
+ };
128
+ /** Refused where the store has no room for `bytes` more at `sha`. Bytes it
129
+ * holds already count as the store counts them. */ export let roomFor = async (at, sha, bytes)=>{
130
+ let full = await at.room?.(sha, bytes);
131
+ if (full) throw new Untaken(413, 'space_full', full);
132
+ };
133
+ /**
134
+ * The rows that name the `bytes` bytes at `sha`, read off `head`: their first
135
+ * bytes, or all of them. A name or type the arrival leaves out is the one the
136
+ * store's rows already say (`read`), since the same file is the same file
137
+ * whatever a page had to call it the second time. The representation is
138
+ * among the rows, fixing the headers the bytes are served with.
139
+ */ export let described = async (read, at, sha, head, mime, name, bytes = head.byteLength)=>{
140
+ let naming = at.naming ?? artifacts;
141
+ let use = await useOf(sha);
142
+ if (!name || mime == UNKNOWN) {
143
+ let prior = naming.said(await read(line`.entity.eid=${use}`), {
144
+ sha,
145
+ use
146
+ });
147
+ name ||= prior?.name ?? '';
148
+ if (mime == UNKNOWN && prior?.mime) mime = prior.mime;
149
+ }
150
+ let type = await contentType(head, mime, bytes == head.byteLength);
151
+ let rep = representation(at.scope ?? SCOPE, sha, type, name);
152
+ let size = sizeOf(head);
153
+ let kept = {
154
+ sha,
155
+ use,
156
+ mime: rep.row.media_type,
157
+ name,
158
+ bytes,
159
+ ...size ? {
160
+ size
161
+ } : {}
162
+ };
163
+ return {
164
+ ...kept,
165
+ path: rep.path,
166
+ bundles: [
167
+ ...naming.rows(kept),
168
+ {
169
+ entity: {
170
+ eid: rep.eid
171
+ },
172
+ representation: rep.row
173
+ }
174
+ ]
175
+ };
176
+ };
177
+ /**
178
+ * Bytes kept under their address, held to what `at` takes, and the rows that
179
+ * name them, for the caller to write as whoever it decided is writing. A
180
+ * stream ({@link Put}) is kept as it arrives, never held whole (./stream.ts
181
+ * `stage`). Bytes not taken throw {@link Untaken} before any are kept at their
182
+ * address. `check` is asked of the rows before the bytes are kept, so
183
+ * whatever would refuse the write refuses the upload.
184
+ *
185
+ * The bytes land before their rows: a row naming nothing is what a reader
186
+ * sees, while bytes nobody has named yet are invisible until the same file
187
+ * arrives again and names them.
188
+ */ export let filed = async (read, at, bytes, mime, name, check)=>{
189
+ let called = (seen)=>typeof name == 'function' ? name(seen) : name;
190
+ if (at.expected && !(bytes instanceof Uint8Array) && at.store.publish) {
191
+ let { sha } = at.expected;
192
+ let publish = at.store.publish;
193
+ return await admitting(at, bytes, async (most)=>{
194
+ let { through, seen } = hashing(bytes.size, most);
195
+ return await publish(sha, {
196
+ stream: bytes.stream.pipeThrough(through),
197
+ size: bytes.size
198
+ }, async ()=>{
199
+ let got = await seen;
200
+ return await checked(read, at, got, mime, called(got), check);
201
+ });
202
+ });
203
+ }
204
+ let staged = await admitted(at, bytes);
205
+ try {
206
+ return await settled(read, at, staged, mime, called(staged), check);
207
+ } finally{
208
+ await staged.drop();
209
+ }
210
+ };
211
+ /** Bytes staged in `at`'s store as they arrive, refused with {@link Untaken}
212
+ * past the most it takes: before any are read where their length is said,
213
+ * and as they pass where it is not. The caller drops them. */ export let admitted = (at, bytes)=>admitting(at, bytes, (most)=>stage(at.store, bytes, most));
214
+ let admitting = async (at, bytes, save)=>{
215
+ let size = lengthOf(bytes);
216
+ if (size != null) admit(at, size);
217
+ if (size != null && at.expected && size != at.expected.bytes) throw changed();
218
+ let most = Math.min(at.limit ?? Infinity, at.accepts?.maxLength ?? Infinity);
219
+ try {
220
+ return await save(most);
221
+ } catch (e) {
222
+ if (e instanceof TooMany) admit(at, e.most + 1);
223
+ throw e;
224
+ }
225
+ };
226
+ let changed = ()=>new Untaken(400, 'upload_changed', 'The upload must match its SHA-256 and size.');
227
+ let checked = async (read, at, { sha, head, size }, mime, name, check, finish)=>{
228
+ if (at.expected && (at.expected.sha != sha || at.expected.bytes != size)) {
229
+ throw changed();
230
+ }
231
+ await roomFor(at, sha, size);
232
+ let file = await described(read, at, sha, head, mime, name, size);
233
+ admit(at, size, file.mime);
234
+ if (finish) file = await finish(file);
235
+ await check?.(file.bundles);
236
+ return file;
237
+ };
238
+ /** {@link filed}, for bytes already staged: the caller drops them. */ export let settled = async (read, at, staged, mime, name, check, finish)=>{
239
+ let file = await checked(read, at, staged, mime, name, check, finish);
240
+ await staged.keep();
241
+ return file;
242
+ };
243
+ /**
244
+ * The representation `eid` of the bytes at `sha`, read off the store in one
245
+ * query, while it is served: none for one of another scope, one that does
246
+ * not address these bytes, or bytes no row names any more. A representation
247
+ * outlives the rows naming its bytes, and a copy of them may be left in a
248
+ * cache or a bucket, so a deleted upload stops here.
249
+ */ export let servable = async (read, at, sha, eid)=>{
250
+ let names = (at.naming ?? artifacts).names(sha);
251
+ let rows = await read(line`.entity.eid=${eid} .representation|${sub(names)}`);
252
+ let rep = rows.find((r)=>r.entity.eid == eid)?.representation;
253
+ return rows.some((r)=>r.entity.eid != eid) ? servedRepresentation(at.scope ?? SCOPE, sha, eid, rep) : null;
254
+ };
255
+ /** Check a representation already read from the upload's store. */ export let servedRepresentation = (scope, sha, eid, rep)=>rep && rep.scope == scope && rep.address == sha && represents(eid, rep) ? rep : null;
256
+ //# sourceMappingURL=upload.js.map
package/upload.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload.js","sources":["./upload.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,2EAA2E;AAC3E,6EAA6E;AAC7E,mEAAmE;AACnE,EAAE;AACF,2EAA2E;AAC3E,yEAAyE;AACzE,6EAA6E;AAC7E,2EAA2E;AAC3E,4EAA4E;AAC5E,4EAA4E;AAC5E,cAAc;AACd,EAAE;AACF,sEAAsE;AACtE,+DAA+D;AAC/D,EAAE;AACF,0EAA0E;AAC1E,sDAAsD;AAEtD,SAAqB,IAAI,EAAE,GAAG,2BAAgC;AAE9D,SAAS,MAAM,EAAE,KAAK,kCAAuC;AAC7D,SAAS,QAAQ,IAAI,wBAA6B;AAClD,SAAuB,IAAI,EAAE,KAAK,EAAE,KAAK,uBAAsB;AAC/D,SAAS,WAAW,wBAAuB;AAC3C,SAAoB,MAAM,qBAAoB;AAC9C,SAEE,cAAc,EACd,UAAU,8BACgB;AAE5B,SACE,OAAO,EACP,QAAQ,EAGR,KAAK,EAEL,OAAO,sBACW;AAEpB,IAAI,UAAU;AAEd,4DAA4D,GAC5D,OAAO,IAAI,QAAQ,OAAM;AAEzB;6BAC6B,GAC7B,OAAO,IAAI,QAAQ,CAAC,MAAiC,OAAO,CAAC,WAAW,EAAE,KAAK,EAAC;AAqChF,IAAI,OAAO,CAAC,MAAgB,KAAa,OACvC,KAAK,IAAI,CAAC,CAAC,IAAM,EAAE,MAAM,CAAC,GAAG,IAAI,MAAM,CAAC,KAAK;AAE/C,IAAI,OAAO,CAAC,IAAe,OAAO,KAAK,WAAW,IAAI;AAEtD;cACc,GACd,OAAO,IAAI,YAAoB;EAC7B,MAAM,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,GAAK;MACzC;QACE,QAAQ;UAAE,KAAK;QAAI;QACnB,UAAU;UAAE,SAAS;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AM,CAAC,GAAG,IAAI,MAAM;EAGjD,OAAO,KAAK,IAAI,CAAC,CAAC,IAAM,EAAE,MAAM,CAAC,GAAG,IAAI,OACpC,qBAAqB,GAAG,KAAK,IAAI,OAAO,KAAK,KAAK,OAClD;AACN,EAAC;AAED,iEAAiE,GACjE,OAAO,IAAI,uBAAuB,CAChC,OACA,KACA,KACA,MAEA,OAAO,IAAI,KAAK,IAAI,SAAS,IAAI,OAAO,IAAI,OAAO,WAAW,KAAK,OAC/D,MACA,KAAI"}
package/upload.ts ADDED
@@ -0,0 +1,404 @@
1
+ // An upload's write half, without a request anywhere in it: bytes kept under
2
+ // their address and the rows that name them, held to what the store takes.
3
+ // The door (./routes.ts) is one way bytes arrive; a letter's attachments and
4
+ // a fetched document are others, and each keeps them through here.
5
+ //
6
+ // The bytes' own SHA-256 is the object's key and the content row's eid, so
7
+ // the same file sent twice is one object and one row. What the bytes are
8
+ // called and what they are sit on a second row, their use, addressed off the
9
+ // first (`useOf`): derived, so an upload finds its own row without reading
10
+ // for it, and the same file sent again is that row renamed. They stay apart
11
+ // because they are two things, and because a component may not point at its
12
+ // own entity.
13
+ //
14
+ // Which words the two rows speak is a store's to say (`Naming`). This
15
+ // package's own are `artifact` and `attachment` (`artifacts`).
16
+ //
17
+ // It is its own entry (`@yaks/blob/upload`), since reading a type off the
18
+ // bytes loads the file-type detector (./identify.ts).
19
+
20
+ import { type Built, line, sub } from '@yaks/query'
21
+ import type { Bundle, Comp, Reads } from 'jsr:@yaks/graph@0.2.36'
22
+ import { digest, token } from '@yaks/graph/sha256'
23
+ import { size as said } from '@yaks/fp'
24
+ import { type Accepts, fits, taken, takes } from './accepts.js'
25
+ import { contentType } from './identify.js'
26
+ import { type Size, sizeOf } from './image.js'
27
+ import {
28
+ type Representation,
29
+ representation,
30
+ represents,
31
+ } from './representation.js'
32
+ import type { Blobs } from './store.ts'
33
+ import {
34
+ hashing,
35
+ lengthOf,
36
+ type Put,
37
+ type Seen,
38
+ stage,
39
+ type Staged,
40
+ TooMany,
41
+ } from './stream.js'
42
+
43
+ let UNKNOWN = 'application/octet-stream'
44
+
45
+ /** The scope of a representation where a store names none. */
46
+ export let SCOPE = 'blob'
47
+
48
+ /** The eid of the use of the bytes at `sha`: the row saying what they are
49
+ * called and what they are. */
50
+ export let useOf = (sha: string): Promise<string> => digest(`attachment:${sha}`)
51
+
52
+ /** Kept bytes, as the rows that name them are made from: their address, the
53
+ * eid of their use, their media type and name, how many there are, and what
54
+ * a picture measures. */
55
+ export type Kept = {
56
+ sha: string
57
+ use: string
58
+ mime: string
59
+ name: string
60
+ bytes: number
61
+ size?: Size
62
+ }
63
+
64
+ /** What a store's rows say the bytes at `sha` are: their media type and
65
+ * name, and the patch that corrects the type once it is read off them. */
66
+ export type Said = {
67
+ mime: string
68
+ name: string
69
+ fix: (mime: string) => Bundle[]
70
+ }
71
+
72
+ /** How a store's words name kept bytes. */
73
+ export type Naming = {
74
+ /** The content row and the use. The use is a patch, so an arrival that
75
+ * names nothing keeps the name the first one gave. */
76
+ rows: (kept: Kept) => Bundle[]
77
+ /** What rows read at the use and the content say of the bytes, or null
78
+ * where none names them. */
79
+ said: (rows: Bundle[], at: { sha: string; use: string }) => Said | null
80
+ /** Find a named use when no canonical use exists at the content address. */
81
+ current?: (read: Read, sha: string) => Promise<Said | null>
82
+ /** The query for the rows still naming the bytes at `sha`. While one
83
+ * answers, the bytes are served. */
84
+ names: (sha: string) => Built
85
+ }
86
+
87
+ let comp = (rows: Bundle[], eid: string, name: string) =>
88
+ rows.find((r) => r.entity.eid == eid)?.[name] as Comp | undefined
89
+
90
+ let text = (v: unknown) => typeof v == 'string' ? v : ''
91
+
92
+ /** This package's words: an `artifact` at the address, and an `attachment`
93
+ * naming it. */
94
+ export let artifacts: Naming = {
95
+ rows: ({ sha, use, mime, name, bytes }) => [
96
+ {
97
+ entity: { eid: sha },
98
+ artifact: { address: sha, media_type: mime, size: bytes },
99
+ },
100
+ {
101
+ entity: { eid: use },
102
+ attachment: { artifact: sha, media_type: mime, ...name ? { name } : {} },
103
+ },
104
+ ],
105
+ said: (rows, { sha, use }) => {
106
+ let file = comp(rows, use, 'attachment')
107
+ let artifact = comp(rows, sha, 'artifact')
108
+ let was = file ?? artifact
109
+ if (!was) return null
110
+ let [eid, name] = file ? [use, 'attachment'] : [sha, 'artifact']
111
+ return {
112
+ mime: text(was.media_type) || text(artifact?.media_type),
113
+ name: text(file?.name),
114
+ fix: (mime) => [{
115
+ entity: { eid },
116
+ [name]: { media_type: mime },
117
+ $was: { [name]: { media_type: token(was.media_type) } },
118
+ }],
119
+ }
120
+ },
121
+ names: (sha) =>
122
+ line`.entity.eid=${sha} .artifact|.attachment.artifact=${sha}`,
123
+ }
124
+
125
+ /** Where bytes are kept and what is taken there. */
126
+ export type Upload = {
127
+ /** where the bytes go, under their address */
128
+ store: Blobs
129
+ /** the representations' scope: an app's eid, where one host serves many
130
+ * (default {@link SCOPE}) */
131
+ scope?: string
132
+ /** what is taken: a size, and types read off the bytes */
133
+ accepts?: Accepts
134
+ /** the most bytes one object may be */
135
+ limit?: number
136
+ /** The file a caller committed to sending, checked before it is kept. */
137
+ expected?: { sha: string; bytes: number }
138
+ /** Why the store has no room for `bytes` more at `sha`, its ceiling's
139
+ * refusal, or nothing where they fit. */
140
+ room?: (sha: string, bytes: number) => string | Promise<string>
141
+ /** the words the rows speak (default {@link artifacts}) */
142
+ naming?: Naming
143
+ }
144
+
145
+ /** Bytes not taken: too many, of a type not taken, or past the store's room.
146
+ * `status` is the HTTP status a door answers, and `code` its word for it. */
147
+ export class Untaken extends Error {
148
+ status: number
149
+ code: string
150
+ constructor(status: number, code: string, says: string) {
151
+ super(says)
152
+ this.name = 'Untaken'
153
+ this.status = status
154
+ this.code = code
155
+ }
156
+ }
157
+
158
+ /** Refused, when `bytes` bytes, or bytes read as `type`, are not taken.
159
+ *
160
+ * ```ts
161
+ * import { admit, Untaken } from '@yaks/blob/upload'
162
+ * import { memoryBlobs } from '@yaks/blob'
163
+ * import { assertThrows } from '@std/assert'
164
+ *
165
+ * let at = { store: memoryBlobs(), accepts: { maxLength: 4096, contentMediaType: 'image/*' } }
166
+ * admit(at, 4096, 'image/png')
167
+ * assertThrows(() => admit(at, 4097), Untaken, 'this app takes files of at most 4 KB')
168
+ * assertThrows(() => admit(at, 10, 'text/plain'), Untaken, 'this app takes image/*, and this file is text/plain')
169
+ * assertThrows(() => admit({ ...at, limit: 1024 }, 2048), Untaken, 'a file is at most 1 KB here')
170
+ * ```
171
+ */
172
+ export let admit = (at: Upload, bytes: number, type?: string): void => {
173
+ if (at.limit != null && bytes > at.limit) {
174
+ throw new Untaken(
175
+ 413,
176
+ 'too_large',
177
+ `a file is at most ${said(at.limit)} here`,
178
+ )
179
+ }
180
+ if (!fits(at.accepts, bytes)) {
181
+ throw new Untaken(
182
+ 413,
183
+ 'too_large',
184
+ `this app takes files of at most ${said(at.accepts!.maxLength!)}`,
185
+ )
186
+ }
187
+ if (type != null && !takes(at.accepts, type)) {
188
+ throw new Untaken(
189
+ 415,
190
+ 'unsupported_media_type',
191
+ `this app takes ${taken(at.accepts)}, and this file is ${type}`,
192
+ )
193
+ }
194
+ }
195
+
196
+ /** Refused where the store has no room for `bytes` more at `sha`. Bytes it
197
+ * holds already count as the store counts them. */
198
+ export let roomFor = async (
199
+ at: Upload,
200
+ sha: string,
201
+ bytes: number,
202
+ ): Promise<void> => {
203
+ let full = await at.room?.(sha, bytes)
204
+ if (full) throw new Untaken(413, 'space_full', full)
205
+ }
206
+
207
+ /** Kept bytes, and the rows that name them. */
208
+ export type File = Kept & {
209
+ /** the representation's address beneath a door: `<sha>/<eid>` */
210
+ path: string
211
+ bundles: Bundle[]
212
+ }
213
+
214
+ /** How the rows a store holds are read: a query line, its rows. */
215
+ export type Read = Reads<Bundle[] | Promise<Bundle[]>, []>
216
+
217
+ /** A name supplied up front or learned as the upload's bytes pass. */
218
+ export type UploadName = string | ((seen: Seen) => string)
219
+
220
+ /**
221
+ * The rows that name the `bytes` bytes at `sha`, read off `head`: their first
222
+ * bytes, or all of them. A name or type the arrival leaves out is the one the
223
+ * store's rows already say (`read`), since the same file is the same file
224
+ * whatever a page had to call it the second time. The representation is
225
+ * among the rows, fixing the headers the bytes are served with.
226
+ */
227
+ export let described = async (
228
+ read: Read,
229
+ at: Upload,
230
+ sha: string,
231
+ head: Uint8Array,
232
+ mime: string,
233
+ name: string,
234
+ bytes: number = head.byteLength,
235
+ ): Promise<File> => {
236
+ let naming = at.naming ?? artifacts
237
+ let use = await useOf(sha)
238
+ if (!name || mime == UNKNOWN) {
239
+ let prior = naming.said(await read(line`.entity.eid=${use}`), { sha, use })
240
+ name ||= prior?.name ?? ''
241
+ if (mime == UNKNOWN && prior?.mime) mime = prior.mime
242
+ }
243
+ let type = await contentType(head, mime, bytes == head.byteLength)
244
+ let rep = representation(at.scope ?? SCOPE, sha, type, name)
245
+ let size = sizeOf(head)
246
+ let kept: Kept = {
247
+ sha,
248
+ use,
249
+ mime: rep.row.media_type,
250
+ name,
251
+ bytes,
252
+ ...size ? { size } : {},
253
+ }
254
+ return {
255
+ ...kept,
256
+ path: rep.path,
257
+ bundles: [...naming.rows(kept), {
258
+ entity: { eid: rep.eid },
259
+ representation: rep.row,
260
+ }],
261
+ }
262
+ }
263
+
264
+ /**
265
+ * Bytes kept under their address, held to what `at` takes, and the rows that
266
+ * name them, for the caller to write as whoever it decided is writing. A
267
+ * stream ({@link Put}) is kept as it arrives, never held whole (./stream.ts
268
+ * `stage`). Bytes not taken throw {@link Untaken} before any are kept at their
269
+ * address. `check` is asked of the rows before the bytes are kept, so
270
+ * whatever would refuse the write refuses the upload.
271
+ *
272
+ * The bytes land before their rows: a row naming nothing is what a reader
273
+ * sees, while bytes nobody has named yet are invisible until the same file
274
+ * arrives again and names them.
275
+ */
276
+ export let filed = async (
277
+ read: Read,
278
+ at: Upload,
279
+ bytes: Put,
280
+ mime: string,
281
+ name: UploadName,
282
+ check?: (rows: Bundle[]) => unknown,
283
+ ): Promise<File> => {
284
+ let called = (seen: Seen) => typeof name == 'function' ? name(seen) : name
285
+ if (at.expected && !(bytes instanceof Uint8Array) && at.store.publish) {
286
+ let { sha } = at.expected
287
+ let publish = at.store.publish
288
+ return await admitting(at, bytes, async (most) => {
289
+ let { through, seen } = hashing(bytes.size, most)
290
+ return await publish(sha, {
291
+ stream: bytes.stream.pipeThrough(through),
292
+ size: bytes.size,
293
+ }, async () => {
294
+ let got = await seen
295
+ return await checked(read, at, got, mime, called(got), check)
296
+ })
297
+ })
298
+ }
299
+ let staged = await admitted(at, bytes)
300
+ try {
301
+ return await settled(read, at, staged, mime, called(staged), check)
302
+ } finally {
303
+ await staged.drop()
304
+ }
305
+ }
306
+
307
+ /** Bytes staged in `at`'s store as they arrive, refused with {@link Untaken}
308
+ * past the most it takes: before any are read where their length is said,
309
+ * and as they pass where it is not. The caller drops them. */
310
+ export let admitted = (at: Upload, bytes: Put): Promise<Staged> =>
311
+ admitting(at, bytes, (most) => stage(at.store, bytes, most))
312
+
313
+ let admitting = async <T>(
314
+ at: Upload,
315
+ bytes: Put,
316
+ save: (most: number) => Promise<T>,
317
+ ): Promise<T> => {
318
+ let size = lengthOf(bytes)
319
+ if (size != null) admit(at, size)
320
+ if (size != null && at.expected && size != at.expected.bytes) throw changed()
321
+ let most = Math.min(at.limit ?? Infinity, at.accepts?.maxLength ?? Infinity)
322
+ try {
323
+ return await save(most)
324
+ } catch (e) {
325
+ if (e instanceof TooMany) admit(at, e.most + 1)
326
+ throw e
327
+ }
328
+ }
329
+
330
+ let changed = () =>
331
+ new Untaken(
332
+ 400,
333
+ 'upload_changed',
334
+ 'The upload must match its SHA-256 and size.',
335
+ )
336
+
337
+ let checked = async (
338
+ read: Read,
339
+ at: Upload,
340
+ { sha, head, size }: Seen,
341
+ mime: string,
342
+ name: string,
343
+ check?: (rows: Bundle[]) => unknown,
344
+ finish?: (file: File) => File | Promise<File>,
345
+ ): Promise<File> => {
346
+ if (at.expected && (at.expected.sha != sha || at.expected.bytes != size)) {
347
+ throw changed()
348
+ }
349
+ await roomFor(at, sha, size)
350
+ let file = await described(read, at, sha, head, mime, name, size)
351
+ admit(at, size, file.mime)
352
+ if (finish) file = await finish(file)
353
+ await check?.(file.bundles)
354
+ return file
355
+ }
356
+
357
+ /** {@link filed}, for bytes already staged: the caller drops them. */
358
+ export let settled = async (
359
+ read: Read,
360
+ at: Upload,
361
+ staged: Staged,
362
+ mime: string,
363
+ name: string,
364
+ check?: (rows: Bundle[]) => unknown,
365
+ finish?: (file: File) => File | Promise<File>,
366
+ ): Promise<File> => {
367
+ let file = await checked(read, at, staged, mime, name, check, finish)
368
+ await staged.keep()
369
+ return file
370
+ }
371
+
372
+ /**
373
+ * The representation `eid` of the bytes at `sha`, read off the store in one
374
+ * query, while it is served: none for one of another scope, one that does
375
+ * not address these bytes, or bytes no row names any more. A representation
376
+ * outlives the rows naming its bytes, and a copy of them may be left in a
377
+ * cache or a bucket, so a deleted upload stops here.
378
+ */
379
+ export let servable = async (
380
+ read: Read,
381
+ at: Pick<Upload, 'scope' | 'naming'>,
382
+ sha: string,
383
+ eid: string,
384
+ ): Promise<Representation | null> => {
385
+ let names = (at.naming ?? artifacts).names(sha)
386
+ let rows = await read(line`.entity.eid=${eid} .representation|${sub(names)}`)
387
+ let rep = rows.find((r) => r.entity.eid == eid)?.representation as
388
+ | Representation
389
+ | undefined
390
+ return rows.some((r) => r.entity.eid != eid)
391
+ ? servedRepresentation(at.scope ?? SCOPE, sha, eid, rep)
392
+ : null
393
+ }
394
+
395
+ /** Check a representation already read from the upload's store. */
396
+ export let servedRepresentation = (
397
+ scope: string,
398
+ sha: string,
399
+ eid: string,
400
+ rep: Representation | undefined,
401
+ ): Representation | null =>
402
+ rep && rep.scope == scope && rep.address == sha && represents(eid, rep)
403
+ ? rep
404
+ : null