22
33/**
44 * Create a Worker that serves static assets
5- *
5+ *
66 * This example demonstrates how to:
77 * - Upload static assets to Cloudflare Workers
88 * - Create and deploy a Worker that serves those assets
9- *
9+ *
1010 * Docs:
1111 * - https://developers.cloudflare.com/workers/static-assets/direct-upload
1212 *
1717 *
1818 * Environment variables:
1919 * - CLOUDFLARE_API_TOKEN (required)
20- * - CLOUDFLARE_ACCOUNT_ID (required)
20+ * - CLOUDFLARE_ACCOUNT_ID (required)
2121 * - ASSETS_DIRECTORY (required)
2222 * - CLOUDFLARE_SUBDOMAIN (optional)
2323 *
@@ -99,11 +99,11 @@ const client = new Cloudflare({
9999 */
100100function createManifest ( directory : string ) : AssetManifest {
101101 const manifest : AssetManifest = { } ;
102-
102+
103103 function processDirectory ( currentDir : string , basePath = '' ) : void {
104104 try {
105105 const entries = fs . readdirSync ( currentDir , { withFileTypes : true } ) ;
106-
106+
107107 for ( const entry of entries ) {
108108 const fullPath = path . join ( currentDir , entry . name ) ;
109109 const relativePath = path . join ( basePath , entry . name ) ;
@@ -124,12 +124,12 @@ function createManifest(directory: string): AssetManifest {
124124
125125 // Normalize path separators to forward slashes
126126 const manifestPath = `/${ relativePath . replace ( / \\ / g, '/' ) } ` ;
127-
127+
128128 manifest [ manifestPath ] = {
129129 hash,
130130 size : fileContent . length ,
131131 } ;
132-
132+
133133 console . log ( `Added to manifest: ${ manifestPath } (${ fileContent . length } bytes)` ) ;
134134 } catch ( error ) {
135135 console . warn ( `Failed to process file ${ fullPath } :` , error ) ;
@@ -140,13 +140,13 @@ function createManifest(directory: string): AssetManifest {
140140 throw new Error ( `Failed to read directory ${ currentDir } : ${ error } ` ) ;
141141 }
142142 }
143-
143+
144144 processDirectory ( directory ) ;
145-
145+
146146 if ( Object . keys ( manifest ) . length === 0 ) {
147147 throw new Error ( `No files found in assets directory: ${ directory } ` ) ;
148148 }
149-
149+
150150 console . log ( `Created manifest with ${ Object . keys ( manifest ) . length } files` ) ;
151151 return manifest ;
152152}
@@ -201,26 +201,24 @@ export default {
201201async function createUploadPayloads (
202202 buckets : string [ ] [ ] ,
203203 manifest : AssetManifest ,
204- assetsDirectory : string
204+ assetsDirectory : string ,
205205) : Promise < UploadPayload [ ] > {
206206 const payloads : UploadPayload [ ] = [ ] ;
207-
207+
208208 for ( const bucket of buckets ) {
209209 const payload : UploadPayload = { } ;
210-
210+
211211 for ( const hash of bucket ) {
212212 // Find the file path for this hash
213- const manifestEntry = Object . entries ( manifest ) . find (
214- ( [ _ , data ] ) => data . hash === hash
215- ) ;
216-
213+ const manifestEntry = Object . entries ( manifest ) . find ( ( [ _ , data ] ) => data . hash === hash ) ;
214+
217215 if ( ! manifestEntry ) {
218216 throw new Error ( `Could not find file for hash: ${ hash } ` ) ;
219217 }
220-
218+
221219 const [ relativePath ] = manifestEntry ;
222220 const fullPath = path . join ( assetsDirectory , relativePath ) ;
223-
221+
224222 try {
225223 const fileContent = await readFile ( fullPath ) ;
226224 payload [ hash ] = fileContent . toString ( 'base64' ) ;
@@ -229,10 +227,10 @@ async function createUploadPayloads(
229227 throw new Error ( `Failed to read file ${ fullPath } : ${ error } ` ) ;
230228 }
231229 }
232-
230+
233231 payloads . push ( payload ) ;
234232 }
235-
233+
236234 return payloads ;
237235}
238236
@@ -242,16 +240,16 @@ async function createUploadPayloads(
242240async function uploadAssets (
243241 payloads : UploadPayload [ ] ,
244242 uploadJwt : string ,
245- accountId : string
243+ accountId : string ,
246244) : Promise < string > {
247245 let completionJwt : string | undefined ;
248-
246+
249247 console . log ( `Uploading ${ payloads . length } payload(s)...` ) ;
250-
248+
251249 for ( let i = 0 ; i < payloads . length ; i ++ ) {
252250 const payload = payloads [ i ] ! ;
253251 console . log ( `Uploading payload ${ i + 1 } /${ payloads . length } ...` ) ;
254-
252+
255253 try {
256254 const response = await client . workers . assets . upload . create (
257255 {
@@ -261,21 +259,21 @@ async function uploadAssets(
261259 } ,
262260 {
263261 headers : { Authorization : `Bearer ${ uploadJwt } ` } ,
264- }
262+ } ,
265263 ) ;
266-
264+
267265 if ( response ?. jwt ) {
268266 completionJwt = response . jwt ;
269267 }
270268 } catch ( error ) {
271269 throw new Error ( `Failed to upload payload ${ i + 1 } : ${ error } ` ) ;
272270 }
273271 }
274-
272+
275273 if ( ! completionJwt ) {
276274 throw new Error ( 'Upload completed but no completion JWT received' ) ;
277275 }
278-
276+
279277 console . log ( '✅ All assets uploaded successfully' ) ;
280278 return completionJwt ;
281279}
@@ -284,21 +282,23 @@ async function main(): Promise<void> {
284282 try {
285283 console . log ( '🚀 Starting Worker creation and deployment with static assets...' ) ;
286284 console . log ( `📁 Assets directory: ${ config . assetsDirectory } ` ) ;
287-
285+
288286 console . log ( '📝 Creating asset manifest...' ) ;
289287 const manifest = createManifest ( config . assetsDirectory ) ;
290288 const exampleFile = Object . keys ( manifest ) [ 0 ] ?. replace ( / ^ \/ / , '' ) || 'file.txt' ;
291289
292290 const scriptContent = generateWorkerScript ( exampleFile ) ;
293-
291+
294292 let worker ;
295293 try {
296294 worker = await client . workers . beta . workers . get ( config . workerName , {
297295 account_id : config . accountId ,
298296 } ) ;
299297 console . log ( `♻️ Worker ${ config . workerName } already exists. Using it.` ) ;
300298 } catch ( error ) {
301- if ( ! ( error instanceof Cloudflare . NotFoundError ) ) { throw error ; }
299+ if ( ! ( error instanceof Cloudflare . NotFoundError ) ) {
300+ throw error ;
301+ }
302302 console . log ( `✏️ Creating Worker ${ config . workerName } ...` ) ;
303303 worker = await client . workers . beta . workers . create ( {
304304 account_id : config . accountId ,
@@ -314,39 +314,28 @@ async function main(): Promise<void> {
314314
315315 console . log ( `⚙️ Worker id: ${ worker . id } ` ) ;
316316 console . log ( '🔄 Starting asset upload session...' ) ;
317-
318- const uploadResponse = await client . workers . scripts . assets . upload . create (
319- config . workerName ,
320- {
321- account_id : config . accountId ,
322- manifest,
323- }
324- ) ;
325-
317+
318+ const uploadResponse = await client . workers . scripts . assets . upload . create ( config . workerName , {
319+ account_id : config . accountId ,
320+ manifest,
321+ } ) ;
322+
326323 const { buckets, jwt : uploadJwt } = uploadResponse ;
327-
324+
328325 if ( ! uploadJwt || ! buckets ) {
329326 throw new Error ( 'Failed to start asset upload session' ) ;
330327 }
331-
328+
332329 let completionJwt : string ;
333-
330+
334331 if ( buckets . length === 0 ) {
335332 console . log ( '✅ No new assets to upload!' ) ;
336333 // Use the initial upload JWT as completion JWT when no uploads are needed
337334 completionJwt = uploadJwt ;
338335 } else {
339- const payloads = await createUploadPayloads (
340- buckets ,
341- manifest ,
342- config . assetsDirectory
343- ) ;
344-
345- completionJwt = await uploadAssets (
346- payloads ,
347- uploadJwt ,
348- config . accountId
349- ) ;
336+ const payloads = await createUploadPayloads ( buckets , manifest , config . assetsDirectory ) ;
337+
338+ completionJwt = await uploadAssets ( payloads , uploadJwt , config . accountId ) ;
350339 }
351340
352341 console . log ( '✏️ Creating Worker version...' ) ;
@@ -373,23 +362,23 @@ async function main(): Promise<void> {
373362 } ,
374363 ] ,
375364 } ) ;
376-
365+
377366 console . log ( '🚚 Creating Worker deployment...' ) ;
378-
367+
379368 // Create a deployment and point all traffic to the version we created
380369 await client . workers . scripts . deployments . create ( config . workerName , {
381370 account_id : config . accountId ,
382371 strategy : 'percentage' ,
383372 versions : [
384373 {
385- percentage : 100 ,
386- version_id : version . id ,
387- } ,
388- ] ,
374+ percentage : 100 ,
375+ version_id : version . id ,
376+ } ,
377+ ] ,
389378 } ) ;
390379
391380 console . log ( '✅ Deployment successful!' ) ;
392-
381+
393382 if ( config . subdomain ) {
394383 console . log ( `
395384🌍 Your Worker is live!
0 commit comments