@crombolo/server 0.33.1 → 0.35.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/components.ts CHANGED
@@ -121,6 +121,9 @@ export async function checkComponents(options: {
121
121
  })
122
122
  }
123
123
 
124
+ for (const found of unawaitedMedia(source))
125
+ problems.push({ file: `${where}:${found.line}`, message: found.message })
126
+
124
127
  try {
125
128
  // A query does not bust Bun's module cache, so a path imported once in
126
129
  // this process answers from the registry. Harmless: the CLI checks each
@@ -156,6 +159,60 @@ export async function checkComponents(options: {
156
159
  }
157
160
  }
158
161
 
162
+ const MEDIA_CALL = /(\bawait\s+)?((?:[A-Za-z_$][\w$]*)(?:\??\.[A-Za-z_$][\w$]*)*)\.media\(/g
163
+
164
+ /** The index just past the parenthesis that closes the one opened before `from`. */
165
+ function closingParen(source: string, from: number): number {
166
+ let depth = 1
167
+ for (let at = from; at < source.length; at++) {
168
+ const c = source[at]
169
+ if (c === '(') depth += 1
170
+ else if (c === ')' && --depth === 0) return at + 1
171
+ }
172
+ return source.length
173
+ }
174
+
175
+ /**
176
+ * `media()` read as if it were not a promise (story 197): indexed, a property
177
+ * read off it, destructured or iterated without `await`. Without the type
178
+ * checker this is the check that catches a view written before media was read
179
+ * asynchronously. A promise passed on, or returned, is left alone. Pure.
180
+ */
181
+ export function unawaitedMedia(source: string): Array<{ line: number; message: string }> {
182
+ const out: Array<{ line: number; message: string }> = []
183
+ for (const match of source.matchAll(MEDIA_CALL)) {
184
+ if (match[1]) continue
185
+ const start = match.index ?? 0
186
+ const end = closingParen(source, start + match[0].length)
187
+ const call = source.slice(start, end)
188
+ const after = source.slice(end).trimStart()
189
+ const before = source.slice(Math.max(0, start - 200), start)
190
+ const synchronous =
191
+ /^(\[|\??\.(?!\.|then\b|catch\b|finally\b))/.test(after) ||
192
+ /\[[^\]=]*\]\s*=\s*$/.test(before) ||
193
+ /\bof\s+$/.test(before) ||
194
+ /\.\.\.\s*$/.test(before)
195
+ if (!synchronous) continue
196
+ out.push({
197
+ line: source.slice(0, start).split('\n').length,
198
+ message:
199
+ `${call} is read asynchronously: write (await ${call}) in an async component. ` +
200
+ 'Media is looked up as it is read, so it is awaited like any other promise.',
201
+ })
202
+ }
203
+ return out
204
+ }
205
+
206
+ /** The values read asynchronously since media left the page snapshot (story 197). */
207
+ const ASYNC_VALUE = /Promise<(?:MediaWithCrops|Link|PublishedContent|RawHtml|string)\b/
208
+
209
+ /** A compiler message about one of them, with the change to make. Pure. */
210
+ export function withAwaitHint(line: string): string {
211
+ return ASYNC_VALUE.test(line)
212
+ ? `${line} (media, rich text and link values are read asynchronously: await them in an async component)`
213
+ : line
214
+ }
215
+
159
216
  /**
160
217
  * `tsc --noEmit` with the site's own tsconfig, when the site has the compiler.
161
218
  *
@@ -187,6 +244,7 @@ async function checkTypes(siteDir: string): Promise<ComponentCheckReport['types'
187
244
  .split('\n')
188
245
  .map((line) => line.trim())
189
246
  .filter((line) => line.length > 0 && !/^Found \d+ error/.test(line))
247
+ .map(withAwaitHint)
190
248
  return { checked: true, problems: lines }
191
249
  }
192
250
 
package/src/config.ts CHANGED
@@ -262,6 +262,11 @@ export interface CromboloConfig {
262
262
  eventRetentionDays: number
263
263
  /** Where uploaded media files live; served at `/media/`. */
264
264
  mediaDir: string
265
+ /**
266
+ * The media cache's memory budget in megabytes (story 197): the media items
267
+ * used most recently are held up to about this much, the rest looked up again.
268
+ */
269
+ mediaCacheMegabytes?: number
265
270
  /**
266
271
  * Where the bytes of uploaded media actually go. Unset means the environment
267
272
  * decides (`CROMBOLO_MEDIA_STORE`), which defaults to `mediaDir` on this disk.
@@ -464,6 +469,7 @@ export const DEFAULTS = {
464
469
  schemaDir: 'schema',
465
470
  schemaRevision: '0',
466
471
  mediaDir: 'media',
472
+ mediaCacheMegabytes: 64,
467
473
  stylesheetsDir: 'css',
468
474
  logsDir: 'logs',
469
475
  scriptsDir: 'scripts',
@@ -630,6 +636,10 @@ export function loadConfig(
630
636
  DEFAULTS.eventRetentionDays,
631
637
  ),
632
638
  mediaDir: setting('CROMBOLO_MEDIA_DIR') ?? DEFAULTS.mediaDir,
639
+ mediaCacheMegabytes: positiveNumber(
640
+ setting('CROMBOLO_MEDIA_CACHE_MB'),
641
+ DEFAULTS.mediaCacheMegabytes,
642
+ ),
633
643
  mediaStore: undefined,
634
644
  logsDir: setting('CROMBOLO_LOGS_DIR') ?? DEFAULTS.logsDir,
635
645
  logLevel: parseLogLevel(setting('CROMBOLO_LOG_LEVEL')),
@@ -829,9 +839,15 @@ export function describeDatabase(
829
839
  }
830
840
  }
831
841
 
832
- export const VERSION = '0.33.1'
842
+ export const VERSION = '0.35.2'
833
843
 
834
844
  /** A whole number of seconds from the environment; undefined when unset or not one. */
845
+ /** A positive number from a setting, else the default. */
846
+ function positiveNumber(raw: string | undefined, fallback: number): number {
847
+ const value = Number(raw)
848
+ return raw !== undefined && raw !== '' && Number.isFinite(value) && value > 0 ? value : fallback
849
+ }
850
+
835
851
  function numberSetting(name: Parameters<typeof setting>[0]): number | undefined {
836
852
  const raw = setting(name)
837
853
  if (raw === undefined || raw.trim() === '') return undefined
@@ -6,7 +6,7 @@
6
6
  * its next tick. The command line wires the same sink without the live part.
7
7
  */
8
8
  import {
9
- type Actor,
9
+ actorMemberKey,
10
10
  actorName,
11
11
  actorNote,
12
12
  actorUserKey,
@@ -14,6 +14,7 @@ import {
14
14
  type DocumentEvent,
15
15
  type EventSink,
16
16
  liveEventsFor,
17
+ type MediaActor,
17
18
  type MediaEventSink,
18
19
  mediaAuditEntryFor,
19
20
  mediaWebhookFor,
@@ -38,11 +39,15 @@ const subjectOf = (event: DocumentEvent): string | null =>
38
39
  'key' in event ? event.key : 'parentKey' in event ? event.parentKey : null
39
40
 
40
41
  /** Who made a change, as the outbox keeps it: enough to name them and leave them out. */
41
- export const outboxActor = (actor: Actor) => ({
42
- kind: actor.kind,
43
- name: actorName(actor),
44
- userKey: actorUserKey(actor),
45
- })
42
+ export const outboxActor = (actor: MediaActor) => {
43
+ const memberKey = actorMemberKey(actor)
44
+ return {
45
+ kind: actor.kind,
46
+ name: actorName(actor),
47
+ userKey: actorUserKey(actor),
48
+ ...(memberKey ? { memberKey } : {}),
49
+ }
50
+ }
46
51
 
47
52
  export function createContentEventSink(options: ContentEventSinkOptions): EventSink {
48
53
  return {
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The Delivery API's media endpoints over the database (story 197): pages of a
3
+ * folder's children counted and ordered in SQL, items read through the media
4
+ * cache, so no request holds the library. docs/delivery-api.md, "Media".
5
+ */
6
+ import type { DeliveryMediaPort } from '@crombolo/api-delivery'
7
+ import { type Db, MediaListingRepository } from '@crombolo/data'
8
+ import type { MediaCache, PublishedMedia } from '@crombolo/render'
9
+
10
+ export function createDeliveryMediaPort(db: Db, media: MediaCache): DeliveryMediaPort {
11
+ const listing = new MediaListingRepository(db)
12
+ const inOrder = async (keys: readonly string[]) => {
13
+ const found = await media.byKeys(keys)
14
+ return keys.flatMap((key) => {
15
+ const item = found.get(key.toLowerCase())
16
+ return item ? [item] : []
17
+ })
18
+ }
19
+ return {
20
+ byKeys: inOrder,
21
+ async byPath(path) {
22
+ const node = await listing.byPath(path)
23
+ return node ? media.byKey(node.key) : undefined
24
+ },
25
+ async children(parent, query) {
26
+ const page = await listing.children({
27
+ parentId: parent === 'root' ? -1 : parent.id,
28
+ parentPath: parent === 'root' ? '-1' : parent.path,
29
+ mediaTypes: query.filters.filter((f) => f.kind === 'mediaType').map((f) => f.value),
30
+ names: query.filters.filter((f) => f.kind === 'name').map((f) => f.value),
31
+ sort:
32
+ query.sort && query.sort.field !== 'level'
33
+ ? { field: query.sort.field, ascending: query.sort.ascending }
34
+ : undefined,
35
+ skip: query.skip,
36
+ take: query.take,
37
+ readable: query.readable,
38
+ })
39
+ return { total: page.total, items: await inOrder(page.keys) }
40
+ },
41
+ async paths(items: readonly PublishedMedia[]) {
42
+ const ids = (item: PublishedMedia) =>
43
+ item.path
44
+ .split(',')
45
+ .map(Number)
46
+ .filter((id) => id > 0)
47
+ const names = await listing.names(items.flatMap(ids))
48
+ return new Map(
49
+ items.map((item) => [
50
+ item.id,
51
+ `/${ids(item)
52
+ .map((id) => (names.get(id) ?? '').toLowerCase())
53
+ .join('/')}/`,
54
+ ]),
55
+ )
56
+ },
57
+ }
58
+ }
@@ -0,0 +1,355 @@
1
+ /**
2
+ * What a photo says about itself, and taking it out (story 198). A member's
3
+ * upload carries EXIF from their phone — where it was taken, when, which way
4
+ * up — which is read here before the file is stored without it.
5
+ *
6
+ * The reader walks the TIFF structure EXIF is: IFD0 for the orientation, the
7
+ * EXIF IFD for the time taken, the GPS IFD for the location. The strippers
8
+ * drop every block a format keeps metadata in, leaving the pixels and the
9
+ * colour profile.
10
+ */
11
+
12
+ export interface ImageLocation {
13
+ latitude: number
14
+ longitude: number
15
+ /** Metres above sea level; negative below it. */
16
+ altitude?: number
17
+ }
18
+
19
+ export interface ExifFacts {
20
+ /** 1–8, as EXIF numbers them; 1 is upright. */
21
+ orientation?: number
22
+ /** `2026-10-28T09:15:00`, with the camera's offset when it wrote one. */
23
+ takenAt?: string
24
+ location?: ImageLocation
25
+ }
26
+
27
+ const TAG_ORIENTATION = 0x0112
28
+ const TAG_EXIF_IFD = 0x8769
29
+ const TAG_GPS_IFD = 0x8825
30
+ const TAG_TAKEN = 0x9003
31
+ const TAG_TAKEN_OFFSET = 0x9011
32
+ const TYPE_SIZES: Record<number, number> = { 1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 7: 1, 9: 4, 10: 8 }
33
+
34
+ const ascii = (bytes: Uint8Array, at: number, length: number) =>
35
+ String.fromCharCode(...bytes.subarray(at, at + length))
36
+
37
+ /** The facts a TIFF block of EXIF holds; empty for anything malformed. */
38
+ export function readExifTiff(tiff: Uint8Array): ExifFacts {
39
+ if (tiff.length < 8) return {}
40
+ const order = ascii(tiff, 0, 2)
41
+ if (order !== 'II' && order !== 'MM') return {}
42
+ const little = order === 'II'
43
+ const view = new DataView(tiff.buffer, tiff.byteOffset, tiff.byteLength)
44
+ const u16 = (at: number) => (at + 2 <= tiff.length ? view.getUint16(at, little) : 0)
45
+ const u32 = (at: number) => (at + 4 <= tiff.length ? view.getUint32(at, little) : 0)
46
+
47
+ type Entry = { type: number; count: number; at: number }
48
+ /** An IFD's entries by tag, each pointing at where its value lies. */
49
+ const ifd = (offset: number): Map<number, Entry> => {
50
+ const entries = new Map<number, Entry>()
51
+ if (offset <= 0 || offset + 2 > tiff.length) return entries
52
+ const count = Math.min(u16(offset), 512)
53
+ for (let i = 0; i < count; i++) {
54
+ const o = offset + 2 + i * 12
55
+ if (o + 12 > tiff.length) break
56
+ const type = u16(o + 2)
57
+ const n = u32(o + 4)
58
+ const size = (TYPE_SIZES[type] ?? 0) * n
59
+ entries.set(u16(o), { type, count: n, at: size <= 4 ? o + 8 : u32(o + 8) })
60
+ }
61
+ return entries
62
+ }
63
+ const text = (entry: Entry | undefined) => {
64
+ if (entry?.type !== 2 || entry.at + entry.count > tiff.length) return undefined
65
+ return ascii(tiff, entry.at, entry.count).replace(/\0.*$/s, '').trim() || undefined
66
+ }
67
+ const rational = (at: number) => {
68
+ const denominator = u32(at + 4)
69
+ return denominator === 0 ? Number.NaN : u32(at) / denominator
70
+ }
71
+ const rationals = (entry: Entry | undefined) => {
72
+ if (entry?.type !== 5 || entry.at + entry.count * 8 > tiff.length) return undefined
73
+ return Array.from({ length: entry.count }, (_, i) => rational(entry.at + i * 8))
74
+ }
75
+
76
+ const facts: ExifFacts = {}
77
+ const zero = ifd(u32(4))
78
+ const orientation = zero.get(TAG_ORIENTATION)
79
+ if (orientation?.type === 3) {
80
+ const value = u16(orientation.at)
81
+ if (value >= 1 && value <= 8) facts.orientation = value
82
+ }
83
+
84
+ const exif = ifd(zero.get(TAG_EXIF_IFD) ? u32((zero.get(TAG_EXIF_IFD) as Entry).at) : 0)
85
+ const taken = /^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2})$/.exec(
86
+ text(exif.get(TAG_TAKEN)) ?? '',
87
+ )
88
+ if (taken && taken[1] !== '0000') {
89
+ const offset = text(exif.get(TAG_TAKEN_OFFSET))
90
+ facts.takenAt = `${taken[1]}-${taken[2]}-${taken[3]}T${taken[4]}:${taken[5]}:${taken[6]}${
91
+ offset && /^[+-]\d{2}:\d{2}$/.test(offset) ? offset : ''
92
+ }`
93
+ }
94
+
95
+ const gps = ifd(zero.get(TAG_GPS_IFD) ? u32((zero.get(TAG_GPS_IFD) as Entry).at) : 0)
96
+ const degrees = (entry: Entry | undefined) => {
97
+ const parts = rationals(entry)
98
+ if (parts?.length !== 3 || parts.some((p) => !Number.isFinite(p))) return undefined
99
+ return (parts[0] as number) + (parts[1] as number) / 60 + (parts[2] as number) / 3600
100
+ }
101
+ const latitude = degrees(gps.get(2))
102
+ const longitude = degrees(gps.get(4))
103
+ if (latitude !== undefined && longitude !== undefined && latitude <= 90 && longitude <= 180) {
104
+ const round = (value: number) => Math.round(value * 1e7) / 1e7
105
+ const location: ImageLocation = {
106
+ latitude: round(text(gps.get(1)) === 'S' ? -latitude : latitude),
107
+ longitude: round(text(gps.get(3)) === 'W' ? -longitude : longitude),
108
+ }
109
+ const altitude = rationals(gps.get(6))?.[0]
110
+ if (altitude !== undefined && Number.isFinite(altitude)) {
111
+ const below = gps.get(5)
112
+ const sign = below && below.type === 1 && tiff[below.at] === 1 ? -1 : 1
113
+ location.altitude = Math.round(sign * altitude * 100) / 100
114
+ }
115
+ facts.location = location
116
+ }
117
+ return facts
118
+ }
119
+
120
+ const EXIF_HEADER = 'Exif\0\0'
121
+
122
+ /** The EXIF TIFF block a JPEG, PNG or WebP carries, if any. */
123
+ export function exifBlockOf(bytes: Uint8Array, format: string): Uint8Array | undefined {
124
+ if (format === 'jpeg') {
125
+ for (const segment of jpegSegments(bytes))
126
+ if (segment.marker === 0xe1 && ascii(bytes, segment.body, 6) === EXIF_HEADER)
127
+ return bytes.subarray(segment.body + 6, segment.end)
128
+ return undefined
129
+ }
130
+ if (format === 'png') {
131
+ for (const chunk of pngChunks(bytes))
132
+ if (chunk.type === 'eXIf') return bytes.subarray(chunk.data, chunk.data + chunk.length)
133
+ return undefined
134
+ }
135
+ if (format === 'webp') {
136
+ for (const chunk of riffChunks(bytes))
137
+ if (chunk.type === 'EXIF') {
138
+ const data = bytes.subarray(chunk.data, chunk.data + chunk.length)
139
+ return ascii(data, 0, 6) === EXIF_HEADER ? data.subarray(6) : data
140
+ }
141
+ }
142
+ return undefined
143
+ }
144
+
145
+ /** What a photo's EXIF says, read before it is stripped. */
146
+ export const readExif = (bytes: Uint8Array, format: string): ExifFacts => {
147
+ const block = exifBlockOf(bytes, format)
148
+ return block ? readExifTiff(block) : {}
149
+ }
150
+
151
+ // ------------------------------------------------------------------ JPEG
152
+
153
+ interface Segment {
154
+ marker: number
155
+ /** Where the segment starts, at its 0xFF. */
156
+ start: number
157
+ /** Where its body starts, after the length. */
158
+ body: number
159
+ end: number
160
+ }
161
+
162
+ /** A JPEG's marker segments up to the start of scan; the scan itself is not walked. */
163
+ function jpegSegments(bytes: Uint8Array): Segment[] {
164
+ const segments: Segment[] = []
165
+ let at = 2
166
+ while (at + 4 <= bytes.length && bytes[at] === 0xff) {
167
+ const marker = bytes[at + 1] as number
168
+ if (marker === 0xff) {
169
+ at += 1
170
+ continue
171
+ }
172
+ const length = ((bytes[at + 2] as number) << 8) | (bytes[at + 3] as number)
173
+ const end = Math.min(bytes.length, at + 2 + length)
174
+ segments.push({ marker, start: at, body: at + 4, end })
175
+ if (marker === 0xda) break
176
+ at = end
177
+ }
178
+ return segments
179
+ }
180
+
181
+ /**
182
+ * A JPEG without its metadata: every APPn segment but JFIF (APP0) and the
183
+ * colour profile (APP2 `ICC_PROFILE`), and every comment.
184
+ */
185
+ export function stripJpeg(bytes: Uint8Array): Uint8Array {
186
+ if (bytes[0] !== 0xff || bytes[1] !== 0xd8) throw new Error('Not a JPEG.')
187
+ const parts: Uint8Array[] = [bytes.subarray(0, 2)]
188
+ let rest = 2
189
+ for (const segment of jpegSegments(bytes)) {
190
+ if (segment.marker === 0xda) {
191
+ rest = segment.start
192
+ break
193
+ }
194
+ const app = segment.marker >= 0xe0 && segment.marker <= 0xef
195
+ const keep =
196
+ (!app && segment.marker !== 0xfe) ||
197
+ segment.marker === 0xe0 ||
198
+ (segment.marker === 0xe2 && ascii(bytes, segment.body, 12) === 'ICC_PROFILE\0')
199
+ if (keep) parts.push(bytes.subarray(segment.start, segment.end))
200
+ rest = segment.end
201
+ }
202
+ parts.push(bytes.subarray(rest))
203
+ return join(parts)
204
+ }
205
+
206
+ // ------------------------------------------------------------------- PNG
207
+
208
+ const PNG_KEEP = new Set([
209
+ 'IHDR',
210
+ 'PLTE',
211
+ 'IDAT',
212
+ 'IEND',
213
+ 'tRNS',
214
+ 'gAMA',
215
+ 'cHRM',
216
+ 'sRGB',
217
+ 'iCCP',
218
+ 'sBIT',
219
+ 'bKGD',
220
+ 'pHYs',
221
+ 'acTL',
222
+ 'fcTL',
223
+ 'fdAT',
224
+ ])
225
+
226
+ function pngChunks(bytes: Uint8Array) {
227
+ const chunks: Array<{ type: string; start: number; data: number; length: number; end: number }> =
228
+ []
229
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
230
+ let at = 8
231
+ while (at + 12 <= bytes.length) {
232
+ const length = view.getUint32(at)
233
+ const end = at + 12 + length
234
+ if (end > bytes.length) break
235
+ chunks.push({ type: ascii(bytes, at + 4, 4), start: at, data: at + 8, length, end })
236
+ at = end
237
+ }
238
+ return chunks
239
+ }
240
+
241
+ /** A PNG with only the chunks that draw it: no text, EXIF, time or anything unknown. */
242
+ export function stripPng(bytes: Uint8Array): Uint8Array {
243
+ const parts = [bytes.subarray(0, 8)]
244
+ for (const chunk of pngChunks(bytes))
245
+ if (PNG_KEEP.has(chunk.type)) parts.push(bytes.subarray(chunk.start, chunk.end))
246
+ return join(parts)
247
+ }
248
+
249
+ // ------------------------------------------------------------------ WebP
250
+
251
+ function riffChunks(bytes: Uint8Array) {
252
+ const chunks: Array<{ type: string; start: number; data: number; length: number; end: number }> =
253
+ []
254
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
255
+ let at = 12
256
+ while (at + 8 <= bytes.length) {
257
+ const length = view.getUint32(at + 4, true)
258
+ const end = Math.min(bytes.length, at + 8 + length + (length % 2))
259
+ chunks.push({ type: ascii(bytes, at, 4), start: at, data: at + 8, length, end })
260
+ at = end
261
+ }
262
+ return chunks
263
+ }
264
+
265
+ /** A WebP without its `EXIF` and `XMP ` chunks, its header's flags saying so. */
266
+ export function stripWebp(bytes: Uint8Array): Uint8Array {
267
+ const kept: Uint8Array[] = []
268
+ for (const chunk of riffChunks(bytes)) {
269
+ if (chunk.type === 'EXIF' || chunk.type === 'XMP ') continue
270
+ const part = bytes.slice(chunk.start, chunk.end)
271
+ // VP8X's flags: EXIF is bit 3, XMP bit 2.
272
+ if (chunk.type === 'VP8X' && part.length > 8) part[8] = (part[8] as number) & ~0x0c
273
+ kept.push(part)
274
+ }
275
+ const body = join(kept)
276
+ const head = new Uint8Array(12)
277
+ head.set(bytes.subarray(0, 12))
278
+ new DataView(head.buffer).setUint32(4, body.length + 4, true)
279
+ return join([head, body])
280
+ }
281
+
282
+ // ------------------------------------------------------------------- GIF
283
+
284
+ const NETSCAPE = new Set(['NETSCAPE2.0', 'ANIMEXTS1.0'])
285
+
286
+ /**
287
+ * A GIF without its comments and application blocks (XMP lives in one),
288
+ * keeping the frames, their timing and the loop count, so an animation stays
289
+ * one.
290
+ */
291
+ export function stripGif(bytes: Uint8Array): Uint8Array {
292
+ const head = ascii(bytes, 0, 6)
293
+ if (head !== 'GIF87a' && head !== 'GIF89a') throw new Error('Not a GIF.')
294
+ const table = (flags: number) => (flags & 0x80 ? 3 * 2 ** ((flags & 0x07) + 1) : 0)
295
+ /** The end of a run of sub-blocks starting at `at`. */
296
+ const subBlocks = (at: number) => {
297
+ while (at < bytes.length) {
298
+ const size = bytes[at] as number
299
+ at += 1 + size
300
+ if (size === 0) break
301
+ }
302
+ return at
303
+ }
304
+ let at = 13 + table(bytes[10] as number)
305
+ const parts = [bytes.subarray(0, at)]
306
+ while (at < bytes.length) {
307
+ const kind = bytes[at] as number
308
+ if (kind === 0x3b) {
309
+ parts.push(bytes.subarray(at, at + 1))
310
+ break
311
+ }
312
+ if (kind === 0x2c) {
313
+ const start = at
314
+ at += 10 + table(bytes[at + 9] as number)
315
+ at = subBlocks(at + 1)
316
+ parts.push(bytes.subarray(start, at))
317
+ } else if (kind === 0x21) {
318
+ const start = at
319
+ const label = bytes[at + 1] as number
320
+ const appId = label === 0xff ? ascii(bytes, at + 3, 11) : ''
321
+ at = subBlocks(at + 2)
322
+ const keep = label === 0xf9 || label === 0x01 || (label === 0xff && NETSCAPE.has(appId))
323
+ if (keep) parts.push(bytes.subarray(start, at))
324
+ } else throw new Error('The GIF could not be read.')
325
+ }
326
+ return join(parts)
327
+ }
328
+
329
+ // ------------------------------------------------------------- HEIF/AVIF
330
+
331
+ /** Whether an HEIF or AVIF file still holds an EXIF or XMP item, read from its header boxes. */
332
+ export function heifHasMetadata(bytes: Uint8Array): boolean {
333
+ const mdat = indexOf(bytes, 'mdat')
334
+ const header = bytes.subarray(0, mdat === -1 ? Math.min(bytes.length, 65536) : mdat)
335
+ return indexOf(header, 'Exif') !== -1 || indexOf(header, 'application/rdf+xml') !== -1
336
+ }
337
+
338
+ function indexOf(bytes: Uint8Array, text: string): number {
339
+ const needle = new TextEncoder().encode(text)
340
+ outer: for (let i = 0; i + needle.length <= bytes.length; i++) {
341
+ for (let j = 0; j < needle.length; j++) if (bytes[i + j] !== needle[j]) continue outer
342
+ return i
343
+ }
344
+ return -1
345
+ }
346
+
347
+ function join(parts: readonly Uint8Array[]): Uint8Array {
348
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))
349
+ let at = 0
350
+ for (const part of parts) {
351
+ out.set(part, at)
352
+ at += part.length
353
+ }
354
+ return out
355
+ }
package/src/imaging.ts CHANGED
@@ -10,6 +10,15 @@
10
10
  * and request, so each variant is computed once.
11
11
  */
12
12
  import { deflateSync, inflateSync } from 'node:zlib'
13
+ import {
14
+ heifHasMetadata,
15
+ type ImageLocation,
16
+ readExif,
17
+ stripGif,
18
+ stripJpeg,
19
+ stripPng,
20
+ stripWebp,
21
+ } from './image-metadata.ts'
13
22
  import type { MediaStore, StoredFile } from './media-store.ts'
14
23
 
15
24
  // --------------------------------------------------------------------- PNG
@@ -432,3 +441,92 @@ export function resizeQuery(options: {
432
441
  const query = params.toString()
433
442
  return query ? `?${query}` : ''
434
443
  }
444
+
445
+ // ------------------------------------------------------- a member's photo
446
+
447
+ /** What a member's image carried, handed to the bundle that took it (story 198). */
448
+ export interface MemberImageFacts {
449
+ width: number
450
+ height: number
451
+ location?: ImageLocation
452
+ /** When it was taken, as the camera said: `2026-10-28T09:15:00`, with an offset if it gave one. */
453
+ takenAt?: string
454
+ }
455
+
456
+ /** An image that cannot be stored without its metadata, so is not stored at all. */
457
+ export class ImageRefusedError extends Error {}
458
+
459
+ /** Turning a picture upright, as EXIF numbers its orientations: a rotation, then a mirror. */
460
+ const UPRIGHT: Record<number, { rotate?: number; flip?: boolean; flop?: boolean }> = {
461
+ 2: { flop: true },
462
+ 3: { rotate: 180 },
463
+ 4: { flip: true },
464
+ 5: { rotate: 90, flop: true },
465
+ 6: { rotate: 90 },
466
+ 7: { rotate: 270, flop: true },
467
+ 8: { rotate: 270 },
468
+ }
469
+
470
+ /**
471
+ * A member's image made safe to keep: turned the way its EXIF says is up, then
472
+ * re-encoded in its own format with every metadata block stripped, so nothing
473
+ * private is ever served. What the metadata said is returned beside it. A GIF
474
+ * keeps its frames and loses only its comments and application blocks. A
475
+ * format that cannot be re-encoded here, or that comes back still carrying
476
+ * metadata, is refused.
477
+ */
478
+ export async function prepareMemberImage(
479
+ bytes: Uint8Array,
480
+ format: string,
481
+ ): Promise<{ bytes: Uint8Array; facts: MemberImageFacts }> {
482
+ const exif = readExif(bytes, format)
483
+ const said = {
484
+ ...(exif.location ? { location: exif.location } : {}),
485
+ ...(exif.takenAt ? { takenAt: exif.takenAt } : {}),
486
+ }
487
+ try {
488
+ if (format === 'gif') {
489
+ const stripped = stripGif(bytes)
490
+ const { width, height } = await new Bun.Image(stripped).metadata()
491
+ return { bytes: stripped, facts: { width, height, ...said } }
492
+ }
493
+ let image = new Bun.Image(bytes, { autoOrient: false })
494
+ const upright = UPRIGHT[exif.orientation ?? 1]
495
+ if (upright?.rotate) image = image.rotate(upright.rotate)
496
+ if (upright?.flip) image = image.flip()
497
+ if (upright?.flop) image = image.flop()
498
+ let out: Uint8Array
499
+ switch (format) {
500
+ case 'jpeg':
501
+ out = stripJpeg(await image.jpeg({ quality: 90 }).bytes())
502
+ break
503
+ case 'png':
504
+ out = stripPng(await image.png().bytes())
505
+ break
506
+ case 'webp': {
507
+ const lossless = new TextDecoder().decode(bytes.subarray(12, 16)) === 'VP8L'
508
+ out = stripWebp(await image.webp(lossless ? { lossless: true } : { quality: 90 }).bytes())
509
+ break
510
+ }
511
+ case 'heic':
512
+ case 'avif':
513
+ out = await (format === 'heic'
514
+ ? image.heic({ quality: 90 })
515
+ : image.avif({ quality: 90 })
516
+ ).bytes()
517
+ if (heifHasMetadata(out)) throw new ImageRefusedError()
518
+ break
519
+ default:
520
+ throw new ImageRefusedError()
521
+ }
522
+ const { width, height } = await new Bun.Image(out).metadata()
523
+ return { bytes: out, facts: { width, height, ...said } }
524
+ } catch (error) {
525
+ const code = (error as { code?: string }).code
526
+ if (error instanceof ImageRefusedError || code === 'ERR_IMAGE_FORMAT_UNSUPPORTED')
527
+ throw new ImageRefusedError(
528
+ 'This kind of image cannot be prepared here, so it was not uploaded. Try a JPEG or PNG.',
529
+ )
530
+ throw new ImageRefusedError('The image could not be read, so it was not uploaded.')
531
+ }
532
+ }