Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 | 42x 42x 42x 42x 131x 254x 7x 85x 85x 85x 85x 73x 85x 85x 85x 73x 73x 70x 69x 69x 85x 67x 67x 67x 2x 67x 67x 1x 41x 47x 47x 47x 46x 46x 113x 113x 111x 3x 108x 5x 103x 103x 113x 113x 113x 41x 62x | import type { AssemblyStatus } from './alphalib/types/assemblyStatus.ts'
import type { InterpolatableRobotUploadHandleInstructionsInput } from './alphalib/types/robots/upload-handle.ts'
import type { StoredAsset } from './alphalib/types/storageAsset.ts'
import type { CreateAssemblyOptions, Transloadit } from './Transloadit.ts'
import { createHash } from 'node:crypto'
import { createReadStream } from 'node:fs'
import debug from 'debug'
import { z } from 'zod'
import { ApiError } from './ApiError.ts'
import { storedAssetSchema } from './alphalib/types/storageAsset.ts'
import InconsistentResponseError from './InconsistentResponseError.ts'
/**
* Verified Storage metadata that can be saved and passed directly to an image renderer.
* Width and height reflect EXIF auto-orientation, matching Storage preview delivery.
*/
export interface StoredImageReceipt extends Readonly<StoredAsset> {
/** Legacy catalog spelling; new server receipts use has_alpha. */
readonly hasAlpha?: boolean
readonly height: number
readonly md5hash: string
readonly width: number
}
/** Shared SDK/CLI opt-in for server extraction; rendering remains a separate choice. */
export const storageImagePlaceholderSchema = z.enum(['blur', 'empty'])
/** One explicit destination, with the existing Assembly upload and polling controls. */
export interface StoreImageOptions
extends Pick<
CreateAssemblyOptions,
'chunkSize' | 'onAssemblyProgress' | 'onUploadProgress' | 'signal' | 'timeout'
> {
/** Complete relative Storage filename. Directories and interpolation expressions are rejected. */
path: string
/** Explicit opt-in replacement of an existing path; defaults to false. */
overwrite?: boolean
/** Request a server ThumbHash. Successful extraction adds metadata usage of 20% of the file bytes. */
placeholder?: z.infer<typeof storageImagePlaceholderSchema>
/** Observe verified metadata. Not awaited; sync and async observer errors cannot undo a write. */
onReceipt?: (
receipt: StoredImageReceipt,
input: StoredImageExpectation,
assemblyId: string | undefined,
) => void | Promise<void>
}
/** Trusted upload facts used to correlate a stored result with an application-owned upload. */
export interface StoredImageExpectation {
path: string
size: number
md5hash: string
}
/** Recovers one original's receipt without re-uploading or trusting notification payloads. */
export interface GetStoredImageReceiptOptions {
assemblyId: string
expected: StoredImageExpectation
}
const positiveIntegerSchema = z.number().int().positive().max(Number.MAX_SAFE_INTEGER)
const receiptRequestSchema = z.object({
assemblyId: z.string().regex(/^[A-Za-z0-9_-]+$/),
expected: z.object({
path: z.string(),
size: positiveIntegerSchema,
md5hash: z.string().regex(/^[a-f0-9]{32}$/),
}),
})
const completedImageSchema = z.object({
ok: z.literal('ASSEMBLY_COMPLETED'),
results: z.object({
':original': z.tuple([
storedAssetSchema.extend({
md5hash: storedAssetSchema.shape.md5hash.unwrap(),
height: positiveIntegerSchema,
width: positiveIntegerSchema,
size: positiveIntegerSchema,
}),
]),
}),
})
function validateDestination(path: string): void {
if (
typeof path !== 'string' ||
path.trim() !== path ||
Buffer.byteLength(path) > 1024 ||
path.normalize('NFC') !== path ||
/[\p{Cc}\p{Cs}\\|]/u.test(path) ||
path.includes('${') ||
path.split('/').some((segment) => segment.trim() === '' || segment === '.' || segment === '..')
) {
throw new TypeError('Storage path must be a complete relative filename without interpolation')
}
}
/** Stores one original without overwriting; receipt validation occurs after the Storage write. */
export async function storeImage(
client: Transloadit,
filePath: string,
options: StoreImageOptions,
): Promise<StoredImageReceipt> {
const {
path,
chunkSize,
onAssemblyProgress,
onUploadProgress,
onReceipt,
overwrite,
signal,
timeout,
} = options
validateDestination(path)
const placeholder = storageImagePlaceholderSchema.optional().parse(options.placeholder, {
path: ['placeholder'],
})
Iif (overwrite !== undefined && typeof overwrite !== 'boolean')
throw new TypeError('overwrite must be a boolean')
signal?.throwIfAborted()
const checksum = createHash('md5')
let size = 0
for await (const chunk of createReadStream(filePath, { signal })) {
checksum.update(chunk)
size += chunk.length
}
if (size === 0) throw new Error('Cannot store an empty image')
const md5hash = checksum.digest('hex')
signal?.throwIfAborted()
const assembly = await client.createAssembly({
chunkSize,
files: { image: filePath },
onAssemblyProgress,
onUploadProgress,
params: {
steps: {
...(placeholder === 'blur'
? {
':original': {
robot: '/upload/handle',
output_meta: { thumbhash: true },
} satisfies InterpolatableRobotUploadHandleInstructionsInput,
}
: {}),
stored: {
robot: '/transloadit/store',
use: ':original',
path,
conflict_strategy: overwrite === true ? 'overwrite' : 'error',
},
},
},
signal,
timeout,
waitForCompletion: true,
})
const input = { path, size, md5hash }
// API2 can watermark uploads before Robots run; this exact write's result describes stored bytes.
const receipt = validateReceipt(assembly, input, true)
const observerFailed = (): void => {
debug('transloadit:warn')('Ignored onReceipt observer failure after a completed Storage write')
}
try {
// Neither a stalled observer nor its rejection may hide a successfully stored receipt.
void Promise.resolve(onReceipt?.({ ...receipt }, input, assembly.assembly_id)).catch(
observerFailed,
)
} catch {
observerFailed()
}
return receipt
}
/** Fetches authoritative Assembly status and applies the same validation as a local image store. */
export async function getStoredImageReceipt(
client: Transloadit,
options: GetStoredImageReceiptOptions,
): Promise<StoredImageReceipt> {
const { assemblyId, expected } = receiptRequestSchema.parse(options)
validateDestination(expected.path)
const assembly = await client.getAssembly(assemblyId)
Iif (assembly.assembly_id !== assemblyId) {
throw new InconsistentResponseError('The response did not match the requested Assembly', {
cause: { assemblyId },
})
}
return validateReceipt(assembly, expected)
}
function validateReceipt(
assembly: AssemblyStatus,
expected: StoredImageExpectation,
acceptTransformed = false,
): StoredImageReceipt {
const { path, size, md5hash } = expected
if (typeof assembly.error === 'string') throw new ApiError({ body: assembly })
if (assembly.ok === 'ASSEMBLY_CANCELED') {
throw new InconsistentResponseError('The Storage Assembly ended with ASSEMBLY_CANCELED', {
cause: { assemblyId: assembly.assembly_id },
})
}
if (
assembly.ok === 'ASSEMBLY_UPLOADING' ||
assembly.ok === 'ASSEMBLY_EXECUTING' ||
assembly.ok === 'ASSEMBLY_REPLAYING'
) {
throw new InconsistentResponseError(`The Storage Assembly is not complete (${assembly.ok})`, {
cause: { assemblyId: assembly.assembly_id },
})
}
const parsed = completedImageSchema.safeParse(assembly)
const result = parsed.success ? parsed.data.results[':original'][0] : undefined
const originals = assembly.results?.[':original']
const receiptCheck = {
originalCount: Array.isArray(originals) ? originals.length : 0,
metadataValid: parsed.success,
pathMatches: result === undefined ? undefined : result.path === path,
sizeMatches: result === undefined ? undefined : result.size === size,
md5Matches: result === undefined ? undefined : result.md5hash === md5hash,
}
if (
result === undefined ||
result.path !== path ||
(!acceptTransformed && (!receiptCheck.sizeMatches || !receiptCheck.md5Matches))
) {
throw new InconsistentResponseError(
'The Assembly did not return a matching Storage image receipt',
{
cause: { assemblyId: assembly.assembly_id, receiptCheck },
},
)
}
return result
}
|