1
1
const { createHash } = require ( 'crypto' )
2
- const { readdirSync, readFileSync, statSync, writeFileSync } = require ( 'fs' )
2
+ const { readdirSync, readFileSync, statSync, writeFileSync, existsSync , renameSync } = require ( 'fs' )
3
3
const { join } = require ( 'path' )
4
4
5
5
const getRevision = filePath => createHash ( 'md5' ) . update ( readFileSync ( filePath ) ) . digest ( 'hex' )
@@ -20,10 +20,67 @@ function formatBytes (bytes, decimals = 2) {
20
20
return `${ formattedSize } ${ sizes [ i ] } `
21
21
}
22
22
23
- function generatePrecacheManifest ( ) {
23
+ function escapeForSingleQuotedJsString ( str ) {
24
+ return str
25
+ . replace ( / \\ / g, '\\\\' )
26
+ . replace ( / ' / g, "\\'" )
27
+ . replace ( / \r / g, '\\r' )
28
+ . replace ( / \n / g, '\\n' )
29
+ . replace ( / \$ / g, '\\$' )
30
+ }
31
+
32
+ function generateDummyPrecacheManifest ( ) {
33
+ // A dummy manifest,to be easily referenced in the public/sw.js when patched
34
+ // This will be pathced with custom assets urls after Next builds
35
+ const manifest = [ {
36
+ url : '/dummy/path/test1.js' ,
37
+ revision : 'rev-123'
38
+ } ]
39
+
40
+ const output = join ( __dirname , 'precache-manifest.json' )
41
+ writeFileSync ( output , JSON . stringify ( manifest , null , 2 ) )
42
+
43
+ console . log ( `Created precache manifest at ${ output } .` )
44
+ }
45
+
46
+ function patchSwAssetsURL ( assetUrlsArray ) {
47
+ const fullPath = join ( __dirname , '../public/sw.js' )
48
+ let content = readFileSync ( fullPath , 'utf-8' )
49
+ const patchedArray = JSON . stringify ( assetUrlsArray )
50
+ const escapedPatchedArrayJson = escapeForSingleQuotedJsString ( patchedArray )
51
+
52
+ // Robust regex: matches JSON.parse('...') or JSON.parse("...") containing the dummy manifest
53
+ // Looks for the dummy manifest's url and revision keys as a marker
54
+ const regex = / J S O N \. p a r s e \( ( [ ' " ] ) \s * \[ \s * \{ \s * ( [ ' " ] ? ) u r l \2\s * : \s * ( [ ' " ] ) [ ^ \3] + \3\s * , \s * ( [ ' " ] ? ) r e v i s i o n \4\s * : \s * ( [ ' " ] ) [ ^ \5] + \5\s * \} \s * \] \s * \1\) /
55
+
56
+ if ( ! regex . test ( content ) ) {
57
+ console . warn ( '⚠️ No match found for precache manifest in sw.js. Service worker will NOT be patched.' )
58
+ return
59
+ }
60
+
61
+ content = content . replace ( regex , ( ) => {
62
+ return `JSON.parse('${ escapedPatchedArrayJson } ')`
63
+ } )
64
+
65
+ // Atomic write: write to temp file, then rename
66
+ const tempPath = fullPath + '.tmp'
67
+ try {
68
+ writeFileSync ( tempPath , content , 'utf-8' )
69
+ renameSync ( tempPath , fullPath )
70
+ console . log ( '✅ Patched service worker cached assets' )
71
+ } catch ( err ) {
72
+ console . error ( '❌ Failed to patch service worker:' , err )
73
+ // Clean up temp file if exists
74
+ if ( existsSync ( tempPath ) ) {
75
+ try { require ( 'fs' ) . unlinkSync ( tempPath ) } catch ( _ ) { }
76
+ }
77
+ throw err
78
+ }
79
+ }
80
+
81
+ async function addStaticAssetsInServiceWorker ( ) {
24
82
const manifest = [ ]
25
83
let size = 0
26
-
27
84
const addToManifest = ( filePath , url , s ) => {
28
85
const revision = getRevision ( filePath )
29
86
manifest . push ( { url, revision } )
@@ -35,7 +92,9 @@ function generatePrecacheManifest () {
35
92
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
93
staticFiles . filter ( staticMatch ) . forEach ( file => {
37
94
const stats = statSync ( file )
38
- addToManifest ( file , file . slice ( staticDir . length ) , stats . size )
95
+ // Normalize path separators for URLs
96
+ const url = file . slice ( staticDir . length ) . replace ( / \\ / g, '/' )
97
+ addToManifest ( file , url , stats . size )
39
98
} )
40
99
41
100
const pagesDir = join ( __dirname , '../pages' )
@@ -45,17 +104,67 @@ function generatePrecacheManifest () {
45
104
const pageMatch = f => precacheURLs . some ( url => fileToUrl ( f ) === url )
46
105
pagesFiles . filter ( pageMatch ) . forEach ( file => {
47
106
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
107
addToManifest ( file , fileToUrl ( file ) , stats . size )
53
108
} )
54
109
55
- const output = 'sw/precache-manifest.json'
56
- writeFileSync ( output , JSON . stringify ( manifest , null , 2 ) )
110
+ const nextStaticDir = join ( __dirname , '../.next/static' )
111
+ // Wait until folder is emitted
112
+ console . log ( '⏳ Waiting for .next/static to be emitted...' )
113
+ let folderRetries = 0
114
+ while ( ! existsSync ( nextStaticDir ) && folderRetries < 10 ) {
115
+ // eslint-disable-next-line no-await-in-loop
116
+ await new Promise ( resolve => setTimeout ( resolve , 500 ) )
117
+ folderRetries ++
118
+ }
57
119
58
- console . log ( `Created precache manifest at ${ output } . Cache will include ${ manifest . length } URLs with a size of ${ formatBytes ( size ) } .` )
120
+ if ( ! existsSync ( nextStaticDir ) ) {
121
+ // Still write the manifest with whatever was collected from public/ and pages/
122
+ const output = join ( __dirname , 'precache-manifest.json' )
123
+ writeFileSync ( output , JSON . stringify ( manifest , null , 2 ) )
124
+ console . warn (
125
+ `⚠️ .next/static not found. Created precache manifest at ${ output } with only public/ and pages/ assets.`
126
+ )
127
+ // Patch the service worker with the available manifest
128
+ patchSwAssetsURL ( manifest )
129
+ return manifest
130
+ }
131
+
132
+ function snapshot ( files ) {
133
+ return files . map ( f => `${ f } :${ statSync ( f ) . size } ` ) . join ( ',' )
134
+ }
135
+ // Now watch for stabilization (files are emitted asynchronously)
136
+ let lastSnapshot = ''
137
+ let stableCount = 0
138
+ const maxWaitMs = 60000
139
+ const startTime = Date . now ( )
140
+ while ( stableCount < 3 && ( Date . now ( ) - startTime ) < maxWaitMs ) {
141
+ const files = walkSync ( nextStaticDir )
142
+ const currentSnapshot = snapshot ( files )
143
+ if ( currentSnapshot === lastSnapshot ) {
144
+ stableCount ++
145
+ } else {
146
+ lastSnapshot = currentSnapshot
147
+ stableCount = 0
148
+ }
149
+ await new Promise ( resolve => setTimeout ( resolve , 500 ) )
150
+ }
151
+ // finally generate manifest
152
+ const nextStaticFiles = walkSync ( nextStaticDir )
153
+ nextStaticFiles . forEach ( file => {
154
+ const stats = statSync ( file )
155
+ // Normalize path separators for URLs
156
+ const url = `/_next/static${ file . slice ( nextStaticDir . length ) . replace ( / \\ / g, '/' ) } `
157
+ addToManifest ( file , url , stats . size )
158
+ } )
159
+ // write manifest
160
+ const output = join ( __dirname , 'precache-manifest.json' )
161
+ writeFileSync ( output , JSON . stringify ( manifest , null , 2 ) )
162
+ console . log (
163
+ `✅ Created precache manifest at ${ output } . Cache will include ${ manifest . length } URLs with a size of ${ formatBytes ( size ) } .`
164
+ )
165
+ const data = readFileSync ( output , 'utf-8' )
166
+ const manifestArray = JSON . parse ( data )
167
+ patchSwAssetsURL ( manifestArray )
59
168
}
60
169
61
- module . exports = { generatePrecacheManifest }
170
+ module . exports = { generateDummyPrecacheManifest , addStaticAssetsInServiceWorker }
0 commit comments