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,41 @@ 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 ( regex , ( ) => {
49
+ return `JSON.parse('${ escapedPatchedArrayJson } ')`
50
+ } )
51
+ writeFileSync ( fullPath , content , 'utf-8' )
52
+ console . log ( '✅ Patched service worker cached assets' )
53
+ }
54
+
55
+ async function addStaticAssetsInServiceWorker ( ) {
24
56
const manifest = [ ]
25
57
let size = 0
26
-
27
58
const addToManifest = ( filePath , url , s ) => {
28
59
const revision = getRevision ( filePath )
29
60
manifest . push ( { url, revision } )
@@ -35,7 +66,9 @@ function generatePrecacheManifest () {
35
66
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
67
staticFiles . filter ( staticMatch ) . forEach ( file => {
37
68
const stats = statSync ( file )
38
- addToManifest ( file , file . slice ( staticDir . length ) , stats . size )
69
+ // Normalize path separators for URLs
70
+ const url = file . slice ( staticDir . length ) . replace ( / \\ / g, '/' )
71
+ addToManifest ( file , url , stats . size )
39
72
} )
40
73
41
74
const pagesDir = join ( __dirname , '../pages' )
@@ -45,17 +78,60 @@ function generatePrecacheManifest () {
45
78
const pageMatch = f => precacheURLs . some ( url => fileToUrl ( f ) === url )
46
79
pagesFiles . filter ( pageMatch ) . forEach ( file => {
47
80
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
81
addToManifest ( file , fileToUrl ( file ) , stats . size )
53
82
} )
54
83
84
+ const nextStaticDir = join ( __dirname , '../.next/static' )
85
+ // Wait until folder is emitted
86
+ console . log ( '⏳ Waiting for .next/static to be emitted...' )
87
+ let folderRetries = 0
88
+ while ( ! existsSync ( nextStaticDir ) && folderRetries < 10 ) {
89
+ // eslint-disable-next-line no-await-in-loop
90
+ await new Promise ( resolve => setTimeout ( resolve , 500 ) )
91
+ folderRetries ++
92
+ }
93
+
94
+ if ( ! existsSync ( nextStaticDir ) ) {
95
+ // Still write the manifest with whatever was collected from public/ and pages/
96
+ const output = 'sw/precache-manifest.json'
97
+ writeFileSync ( output , JSON . stringify ( manifest , null , 2 ) )
98
+ console . warn (
99
+ `⚠️ .next/static not found. Created precache manifest at ${ output } with only public/ and pages/ assets.`
100
+ )
101
+ return
102
+ }
103
+ // Now watch for stabilization (files are emitted asynchronously)
104
+ let lastFileCount = 0
105
+ let stableCount = 0
106
+ const maxWaitMs = 60000
107
+ const startTime = Date . now ( )
108
+ while ( stableCount < 3 && ( Date . now ( ) - startTime ) < maxWaitMs ) {
109
+ const files = walkSync ( nextStaticDir )
110
+ if ( files . length === lastFileCount ) {
111
+ stableCount ++
112
+ } else {
113
+ stableCount = 0
114
+ lastFileCount = files . length
115
+ }
116
+ await new Promise ( resolve => setTimeout ( resolve , 500 ) )
117
+ }
118
+ // finally generate manifest
119
+ const nextStaticFiles = walkSync ( nextStaticDir )
120
+ nextStaticFiles . forEach ( file => {
121
+ const stats = statSync ( file )
122
+ // Normalize path separators for URLs
123
+ const url = `/_next/static${ file . slice ( nextStaticDir . length ) . replace ( / \\ / g, '/' ) } `
124
+ addToManifest ( file , url , stats . size )
125
+ } )
126
+ // write manifest
55
127
const output = 'sw/precache-manifest.json'
56
128
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 ) } .` )
129
+ console . log (
130
+ `✅ Created precache manifest at ${ output } . Cache will include ${ manifest . length } URLs with a size of ${ formatBytes ( size ) } .`
131
+ )
132
+ const data = readFileSync ( 'sw/precache-manifest.json' , 'utf-8' )
133
+ const manifestArray = JSON . parse ( data )
134
+ patchSwAssetsURL ( manifestArray )
59
135
}
60
136
61
- module . exports = { generatePrecacheManifest }
137
+ module . exports = { generateDummyPrecacheManifest , addStaticAssetsInServiceWorker }
0 commit comments