1
1
const { createHash } = require ( 'crypto' )
2
- const { readdirSync, readFileSync, statSync, writeFileSync } = require ( 'fs' )
3
- const { join } = require ( 'path' )
2
+ const { readdirSync, readFileSync, statSync, writeFileSync, existsSync } = require ( 'fs' )
3
+ const { join, resolve } = require ( 'path' )
4
4
5
5
const getRevision = filePath => createHash ( 'md5' ) . update ( readFileSync ( filePath ) ) . digest ( 'hex' )
6
6
const walkSync = dir => readdirSync ( dir , { withFileTypes : true } ) . flatMap ( file =>
@@ -20,10 +20,42 @@ function formatBytes (bytes, decimals = 2) {
20
20
return `${ formattedSize } ${ sizes [ i ] } `
21
21
}
22
22
23
- function generatePrecacheManifest ( ) {
23
+ function generateDummyPrecacheManifest ( ) {
24
+ // A dummy manifest,to be easily referenced in the public/sw.js when patched
25
+ // This will be pathced with custom assets urls after Next builds
26
+ const manifest = [ {
27
+ url : '/dummy/path/test1.js' ,
28
+ revision : 'rev-123'
29
+ } ]
30
+
31
+ const output = 'sw/precache-manifest.json'
32
+ writeFileSync ( output , JSON . stringify ( manifest , null , 2 ) )
33
+
34
+ console . log ( `Created precache manifest at ${ output } .` )
35
+ }
36
+
37
+ function patchSwAssetsURL ( assetUrlsArray ) {
38
+ const fullPath = resolve ( 'public/sw.js' )
39
+ let content = readFileSync ( fullPath , 'utf-8' )
40
+ const patchedArray = JSON . stringify ( assetUrlsArray )
41
+ const escapedPatchedArrayJson = patchedArray . replace ( / " / g, '\\"' )
42
+ const regex = / J S O N \. p a r s e \( \s * ' \[ \{ " u r l " : " \/ d u m m y \/ p a t h \/ t e s t 1 \. j s " , " r e v i s i o n " : " r e v - 1 2 3 " \} \] ' \s * \) /
43
+ if ( ! regex . test ( content ) ) {
44
+ console . warn ( '⚠️ No match found for precache manifest in sw.js' )
45
+ return
46
+ }
47
+
48
+ content = content . replace (
49
+ regex ,
50
+ `JSON.parse("${ escapedPatchedArrayJson } ")`
51
+ )
52
+ writeFileSync ( fullPath , content , 'utf-8' )
53
+ console . log ( '✅ Patched service worker cached assets' )
54
+ }
55
+
56
+ async function addStaticAssetsInServiceWorker ( ) {
24
57
const manifest = [ ]
25
58
let size = 0
26
-
27
59
const addToManifest = ( filePath , url , s ) => {
28
60
const revision = getRevision ( filePath )
29
61
manifest . push ( { url, revision } )
@@ -35,7 +67,9 @@ function generatePrecacheManifest () {
35
67
const staticMatch = f => [ / \. ( g i f | j p e ? g | i c o | p n g | t t f | w o f f | w o f f 2 ) $ / ] . some ( m => m . test ( f ) )
36
68
staticFiles . filter ( staticMatch ) . forEach ( file => {
37
69
const stats = statSync ( file )
38
- addToManifest ( file , file . slice ( staticDir . length ) , stats . size )
70
+ // Normalize path separators for URLs
71
+ const url = file . slice ( staticDir . length ) . replace ( / \\ / g, '/' )
72
+ addToManifest ( file , url , stats . size )
39
73
} )
40
74
41
75
const pagesDir = join ( __dirname , '../pages' )
@@ -45,17 +79,60 @@ function generatePrecacheManifest () {
45
79
const pageMatch = f => precacheURLs . some ( url => fileToUrl ( f ) === url )
46
80
pagesFiles . filter ( pageMatch ) . forEach ( file => {
47
81
const stats = statSync ( file )
48
- // This is not ideal since dependencies of the pages may have changed
49
- // but we would still generate the same revision ...
50
- // The ideal solution would be to create a revision from the file generated by webpack
51
- // in .next/server/pages but the file may not exist yet when we run this script
52
82
addToManifest ( file , fileToUrl ( file ) , stats . size )
53
83
} )
54
84
85
+ const nextStaticDir = join ( __dirname , '../.next/static' )
86
+ // Wait until folder is emitted
87
+ console . log ( '⏳ Waiting for .next/static to be emitted...' )
88
+ let folderRetries = 0
89
+ while ( ! existsSync ( nextStaticDir ) && folderRetries < 10 ) {
90
+ // eslint-disable-next-line no-await-in-loop
91
+ await new Promise ( resolve => setTimeout ( resolve , 500 ) )
92
+ folderRetries ++
93
+ }
94
+
95
+ if ( ! existsSync ( nextStaticDir ) ) {
96
+ // Still write the manifest with whatever was collected from public/ and pages/
97
+ const output = 'sw/precache-manifest.json'
98
+ writeFileSync ( output , JSON . stringify ( manifest , null , 2 ) )
99
+ console . warn (
100
+ `⚠️ .next/static not found. Created precache manifest at ${ output } with only public/ and pages/ assets.`
101
+ )
102
+ return
103
+ }
104
+ // Now watch for stabilization (files are emitted asynchronously)
105
+ let lastFileCount = 0
106
+ let stableCount = 0
107
+ const maxWaitMs = 60000
108
+ const startTime = Date . now ( )
109
+ while ( stableCount < 3 && ( Date . now ( ) - startTime ) < maxWaitMs ) {
110
+ const files = walkSync ( nextStaticDir )
111
+ if ( files . length === lastFileCount ) {
112
+ stableCount ++
113
+ } else {
114
+ stableCount = 0
115
+ lastFileCount = files . length
116
+ }
117
+ await new Promise ( resolve => setTimeout ( resolve , 500 ) )
118
+ }
119
+ // finally generate manifest
120
+ const nextStaticFiles = walkSync ( nextStaticDir )
121
+ nextStaticFiles . forEach ( file => {
122
+ const stats = statSync ( file )
123
+ // Normalize path separators for URLs
124
+ const url = `/_next/static${ file . slice ( nextStaticDir . length ) . replace ( / \\ / g, '/' ) } `
125
+ addToManifest ( file , url , stats . size )
126
+ } )
127
+ // write manifest
55
128
const output = 'sw/precache-manifest.json'
56
129
writeFileSync ( output , JSON . stringify ( manifest , null , 2 ) )
57
-
58
- console . log ( `Created precache manifest at ${ output } . Cache will include ${ manifest . length } URLs with a size of ${ formatBytes ( size ) } .` )
130
+ console . log (
131
+ `✅ Created precache manifest at ${ output } . Cache will include ${ manifest . length } URLs with a size of ${ formatBytes ( size ) } .`
132
+ )
133
+ const data = readFileSync ( 'sw/precache-manifest.json' , 'utf-8' )
134
+ const manifestArray = JSON . parse ( data )
135
+ patchSwAssetsURL ( manifestArray )
59
136
}
60
137
61
- module . exports = { generatePrecacheManifest }
138
+ module . exports = { generateDummyPrecacheManifest , addStaticAssetsInServiceWorker }
0 commit comments