@serwist/next 9.5.8 → 9.5.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.config.mjs","names":[],"sources":["../src/lib/config/utils.ts","../src/index.config.ts"],"sourcesContent":["import { PHASE_DEVELOPMENT_SERVER, PHASE_PRODUCTION_BUILD } from \"next/constants.js\";\nimport type { NextConfigComplete } from \"next/dist/server/config-shared.js\";\n\nimport nextConfig = require(\"next/dist/server/config.js\");\n\nexport const loadNextConfig = (cwd: string, isDev: boolean): Promise<NextConfigComplete> => {\n const nextPhase = isDev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_BUILD;\n return nextConfig.default(nextPhase, cwd, {\n silent: false,\n });\n};\n\nexport const generateGlobPatterns = (distDir: string): string[] => [\n `${distDir}static/**/*.{js,css,html,ico,apng,png,avif,jpg,jpeg,jfif,pjpeg,pjp,gif,svg,webp,json,webmanifest}`,\n \"public/**/*\",\n];\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { rebasePath } from \"@serwist/build\";\nimport type { BuildOptions } from \"@serwist/cli\";\nimport { browserslistToEsbuild } from \"@serwist/utils\";\nimport browserslist from \"browserslist\";\nimport { MODERN_BROWSERSLIST_TARGET } from \"next/constants.js\";\nimport type { NextConfigComplete } from \"next/dist/server/config-shared.js\";\nimport type { SerwistOptions } from \"./lib/config/types.js\";\nimport { generateGlobPatterns, loadNextConfig } from \"./lib/config/utils.js\";\n\nconst _cwd = process.cwd();\nconst _isDev = process.env.NODE_ENV === \"development\";\n\n/**\n * Additional build context.\n */\nexport interface SerwistContext {\n /**\n * The current working directory.\n */\n cwd?: string;\n /**\n * Whether Serwist is in development mode. This option determines how Next.js configuration\n * is resolved. Note that it doesn't change how the service worker is built.\n */\n isDev?: boolean;\n}\n\nexport interface Serwist {\n /**\n * Integrates Serwist into your Next.js app.\n * @param options\n * @returns\n */\n (options: SerwistOptions, nextConfig?: NextConfigComplete, context?: SerwistContext): Promise<BuildOptions>;\n /**\n * Integrates Serwist into your Next.js app. Allows reading fully resolved Next.js configuration.\n * @param optionsFunction\n * @returns\n */\n withNextConfig: (\n optionsFunction: (nextConfig: NextConfigComplete) => Promise<SerwistOptions> | SerwistOptions,\n context?: SerwistContext,\n ) => Promise<BuildOptions>;\n}\n\nexport const serwist: Serwist = async (options, nextConfig, { cwd = _cwd, isDev = _isDev } = {}) => {\n if (!nextConfig) nextConfig = await loadNextConfig(cwd, isDev);\n const basePath = nextConfig.basePath || \"/\";\n let distDir = nextConfig.distDir;\n if (distDir[0] === \"/\") distDir = distDir.slice(1);\n if (distDir[distDir.length - 1] !== \"/\") distDir += \"/\";\n const distServerDir = `${distDir}server/`;\n const distAppDir = `${distServerDir}app/`;\n const distPagesDir = `${distServerDir}pages/`;\n const { precachePrerendered = true, globDirectory = cwd, ...cliOptions } = options;\n for (const file of [cliOptions.swDest, `${cliOptions.swDest}.map`]) {\n fs.rmSync(file, { force: true });\n }\n return {\n dontCacheBustURLsMatching: new RegExp(`^${distDir}static/`),\n disablePrecacheManifest: isDev,\n ...cliOptions,\n globDirectory,\n globPatterns: [\n ...(cliOptions.globPatterns ?? generateGlobPatterns(distDir)),\n ...(precachePrerendered ? [`${distServerDir}{app,pages}/**/*.html`] : []),\n ],\n globIgnores: [\n `${distAppDir}**/_not-found.html`,\n `${distAppDir}_global-error*`,\n `${distPagesDir}404.html`,\n `${distPagesDir}500.html`,\n ...(cliOptions.globIgnores ?? []),\n rebasePath({ baseDirectory: globDirectory, file: cliOptions.swSrc }),\n rebasePath({ baseDirectory: globDirectory, file: cliOptions.swDest }),\n rebasePath({ baseDirectory: globDirectory, file: `${cliOptions.swDest}.map` }),\n ],\n manifestTransforms: [\n ...(cliOptions.manifestTransforms ?? []),\n (manifestEntries) => {\n const manifest = manifestEntries.map((m) => {\n if (m.url.startsWith(distAppDir)) {\n // Keep the prefixing slash.\n m.url = m.url.slice(distAppDir.length - 1);\n }\n if (m.url.startsWith(distPagesDir)) {\n // Keep the prefixing slash.\n m.url = m.url.slice(distPagesDir.length - 1);\n }\n if (m.url.endsWith(\".html\")) {\n // trailingSlash: true && output: 'export'\n // or root index.html.\n // https://nextjs.org/docs/app/api-reference/config/next-config-js/trailingSlash\n // \"/abc/index.html\" -> \"/abc/\"\n // \"/index.html\" -> \"/\"\n if (m.url.endsWith(\"/index.html\")) {\n m.url = m.url.slice(0, m.url.lastIndexOf(\"/\") + 1);\n }\n // \"/xxx.html\" -> \"/xxx\"\n else {\n m.url = m.url.substring(0, m.url.lastIndexOf(\".\"));\n }\n m.url = path.posix.join(basePath, m.url);\n }\n // Replace all references to \"$(distDir)\" with \"$(assetPrefix)/_next/\".\n if (m.url.startsWith(distDir)) {\n m.url = `${nextConfig.assetPrefix ?? \"\"}/_next/${m.url.slice(distDir.length)}`;\n }\n // Replace all references to public/ with \"$(basePath)/\".\n if (m.url.startsWith(\"public/\")) {\n m.url = path.posix.join(basePath, m.url.slice(7));\n }\n return m;\n });\n return { manifest, warnings: [] };\n },\n ],\n esbuildOptions: {\n ...cliOptions.esbuildOptions,\n target: cliOptions.esbuildOptions?.target ?? browserslistToEsbuild(browserslist, cwd, MODERN_BROWSERSLIST_TARGET),\n },\n };\n};\n\nserwist.withNextConfig = async (optionsFunction, { cwd = _cwd, isDev = _isDev } = {}) => {\n const nextConfig = await loadNextConfig(cwd, isDev);\n return serwist(await optionsFunction(nextConfig), nextConfig, { cwd, isDev });\n};\n\nexport { generateGlobPatterns };\n\nexport type { SerwistOptions };\n"],"mappings":";;;;;;;;;MAGO,cAAA,8CAAA,EAAqB,6BAAA;AAE5B,MAAa,kBAAkB,KAAa,UAAgD;CAC1F,MAAM,YAAY,QAAQ,2BAA2B;AACrD,QAAO,WAAW,QAAQ,WAAW,KAAK,EACxC,QAAQ,OACT,CAAC;;AAGJ,MAAa,wBAAwB,YAA8B,CACjE,GAAG,QAAQ,oGACX,cACD;;;ACJD,MAAM,OAAO,QAAQ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C,SAAI,EAAE,IAAI,WAAW,WAAW,CAE9B,GAAE,MAAM,EAAE,IAAI,MAAM,WAAW,SAAS,EAAE;AAE5C,SAAI,EAAE,IAAI,WAAW,aAAa,CAEhC,GAAE,MAAM,EAAE,IAAI,MAAM,aAAa,SAAS,EAAE;AAE9C,SAAI,EAAE,IAAI,SAAS,QAAQ,EAAE;AAM3B,UAAI,EAAE,IAAI,SAAS,cAAc,CAC/B,GAAE,MAAM,EAAE,IAAI,MAAM,GAAG,EAAE,IAAI,YAAY,IAAI,GAAG,EAAE;UAIlD,GAAE,MAAM,EAAE,IAAI,UAAU,GAAG,EAAE,IAAI,YAAY,IAAI,CAAC;AAEpD,QAAE,MAAM,KAAK,MAAM,KAAK,UAAU,EAAE,IAAI;;AAG1C,SAAI,EAAE,IAAI,WAAW,QAAQ,CAC3B,GAAE,MAAM,GAAG,WAAW,eAAe,GAAG,SAAS,EAAE,IAAI,MAAM,QAAQ,OAAO;AAG9E,SAAI,EAAE,IAAI,WAAW,UAAU,CAC7B,GAAE,MAAM,KAAK,MAAM,KAAK,UAAU,EAAE,IAAI,MAAM,EAAE,CAAC;AAEnD,YAAO;MAEQ;IAAE,UAAU,EAAE;IAAE;IAEpC;EACD,gBAAgB;GACd,GAAG,WAAW;GACd,QAAQ,WAAW,gBAAgB,UAAU,sBAAsB,cAAc,KAAK,2BAA2B;GAClH;EACF;;AAGH,QAAQ,iBAAiB,OAAO,iBAAiB,EAAE,MAAM,MAAM,QAAQ,WAAW,EAAE,KAAK;CACvF,MAAM,aAAa,MAAM,eAAe,KAAK,MAAM;AACnD,QAAO,QAAQ,MAAM,gBAAgB,WAAW,EAAE,YAAY;EAAE;EAAK;EAAO,CAAC"}
1
+ {"version":3,"file":"index.config.mjs","names":["PHASE_DEVELOPMENT_SERVER","PHASE_PRODUCTION_BUILD","NextConfigComplete","nextConfig","loadNextConfig","cwd","isDev","Promise","nextPhase","default","silent","generateGlobPatterns","distDir","fs","path","rebasePath","BuildOptions","browserslistToEsbuild","browserslist","MODERN_BROWSERSLIST_TARGET","NextConfigComplete","SerwistOptions","generateGlobPatterns","loadNextConfig","_cwd","process","cwd","_isDev","env","NODE_ENV","SerwistContext","isDev","Serwist","options","nextConfig","context","Promise","withNextConfig","optionsFunction","serwist","basePath","distDir","slice","length","distServerDir","distAppDir","distPagesDir","precachePrerendered","globDirectory","cliOptions","file","swDest","rmSync","force","dontCacheBustURLsMatching","RegExp","disablePrecacheManifest","globPatterns","globIgnores","baseDirectory","swSrc","manifestTransforms","manifestEntries","manifest","map","m","url","startsWith","endsWith","lastIndexOf","substring","posix","join","assetPrefix","warnings","esbuildOptions","target"],"sources":["../src/lib/config/utils.ts","../src/index.config.ts"],"sourcesContent":["import { PHASE_DEVELOPMENT_SERVER, PHASE_PRODUCTION_BUILD } from \"next/constants.js\";\nimport type { NextConfigComplete } from \"next/dist/server/config-shared.js\";\n\nimport nextConfig = require(\"next/dist/server/config.js\");\n\nexport const loadNextConfig = (cwd: string, isDev: boolean): Promise<NextConfigComplete> => {\n const nextPhase = isDev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_BUILD;\n return nextConfig.default(nextPhase, cwd, {\n silent: false,\n });\n};\n\nexport const generateGlobPatterns = (distDir: string): string[] => [\n `${distDir}static/**/*.{js,css,html,ico,apng,png,avif,jpg,jpeg,jfif,pjpeg,pjp,gif,svg,webp,json,webmanifest}`,\n \"public/**/*\",\n];\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { rebasePath } from \"@serwist/build\";\nimport type { BuildOptions } from \"@serwist/cli\";\nimport { browserslistToEsbuild } from \"@serwist/utils\";\nimport browserslist from \"browserslist\";\nimport { MODERN_BROWSERSLIST_TARGET } from \"next/constants.js\";\nimport type { NextConfigComplete } from \"next/dist/server/config-shared.js\";\nimport type { SerwistOptions } from \"./lib/config/types.js\";\nimport { generateGlobPatterns, loadNextConfig } from \"./lib/config/utils.js\";\n\nconst _cwd = process.cwd();\nconst _isDev = process.env.NODE_ENV === \"development\";\n\n/**\n * Additional build context.\n */\nexport interface SerwistContext {\n /**\n * The current working directory.\n */\n cwd?: string;\n /**\n * Whether Serwist is in development mode. This option determines how Next.js configuration\n * is resolved. Note that it doesn't change how the service worker is built.\n */\n isDev?: boolean;\n}\n\nexport interface Serwist {\n /**\n * Integrates Serwist into your Next.js app.\n * @param options\n * @returns\n */\n (options: SerwistOptions, nextConfig?: NextConfigComplete, context?: SerwistContext): Promise<BuildOptions>;\n /**\n * Integrates Serwist into your Next.js app. Allows reading fully resolved Next.js configuration.\n * @param optionsFunction\n * @returns\n */\n withNextConfig: (\n optionsFunction: (nextConfig: NextConfigComplete) => Promise<SerwistOptions> | SerwistOptions,\n context?: SerwistContext,\n ) => Promise<BuildOptions>;\n}\n\nexport const serwist: Serwist = async (options, nextConfig, { cwd = _cwd, isDev = _isDev } = {}) => {\n if (!nextConfig) nextConfig = await loadNextConfig(cwd, isDev);\n const basePath = nextConfig.basePath || \"/\";\n let distDir = nextConfig.distDir;\n if (distDir[0] === \"/\") distDir = distDir.slice(1);\n if (distDir[distDir.length - 1] !== \"/\") distDir += \"/\";\n const distServerDir = `${distDir}server/`;\n const distAppDir = `${distServerDir}app/`;\n const distPagesDir = `${distServerDir}pages/`;\n const { precachePrerendered = true, globDirectory = cwd, ...cliOptions } = options;\n for (const file of [cliOptions.swDest, `${cliOptions.swDest}.map`]) {\n fs.rmSync(file, { force: true });\n }\n return {\n dontCacheBustURLsMatching: new RegExp(`^${distDir}static/`),\n disablePrecacheManifest: isDev,\n ...cliOptions,\n globDirectory,\n globPatterns: [\n ...(cliOptions.globPatterns ?? generateGlobPatterns(distDir)),\n ...(precachePrerendered ? [`${distServerDir}{app,pages}/**/*.html`] : []),\n ],\n globIgnores: [\n `${distAppDir}**/_not-found.html`,\n `${distAppDir}_global-error*`,\n `${distPagesDir}404.html`,\n `${distPagesDir}500.html`,\n ...(cliOptions.globIgnores ?? []),\n rebasePath({ baseDirectory: globDirectory, file: cliOptions.swSrc }),\n rebasePath({ baseDirectory: globDirectory, file: cliOptions.swDest }),\n rebasePath({ baseDirectory: globDirectory, file: `${cliOptions.swDest}.map` }),\n ],\n manifestTransforms: [\n ...(cliOptions.manifestTransforms ?? []),\n (manifestEntries) => {\n const manifest = manifestEntries.map((m) => {\n if (m.url.startsWith(distAppDir)) {\n // Keep the prefixing slash.\n m.url = m.url.slice(distAppDir.length - 1);\n }\n if (m.url.startsWith(distPagesDir)) {\n // Keep the prefixing slash.\n m.url = m.url.slice(distPagesDir.length - 1);\n }\n if (m.url.endsWith(\".html\")) {\n // trailingSlash: true && output: 'export'\n // or root index.html.\n // https://nextjs.org/docs/app/api-reference/config/next-config-js/trailingSlash\n // \"/abc/index.html\" -> \"/abc/\"\n // \"/index.html\" -> \"/\"\n if (m.url.endsWith(\"/index.html\")) {\n m.url = m.url.slice(0, m.url.lastIndexOf(\"/\") + 1);\n }\n // \"/xxx.html\" -> \"/xxx\"\n else {\n m.url = m.url.substring(0, m.url.lastIndexOf(\".\"));\n }\n m.url = path.posix.join(basePath, m.url);\n }\n // Replace all references to \"$(distDir)\" with \"$(assetPrefix)/_next/\".\n if (m.url.startsWith(distDir)) {\n m.url = `${nextConfig.assetPrefix ?? \"\"}/_next/${m.url.slice(distDir.length)}`;\n }\n // Replace all references to public/ with \"$(basePath)/\".\n if (m.url.startsWith(\"public/\")) {\n m.url = path.posix.join(basePath, m.url.slice(7));\n }\n return m;\n });\n return { manifest, warnings: [] };\n },\n ],\n esbuildOptions: {\n ...cliOptions.esbuildOptions,\n target: cliOptions.esbuildOptions?.target ?? browserslistToEsbuild(browserslist, cwd, MODERN_BROWSERSLIST_TARGET),\n },\n };\n};\n\nserwist.withNextConfig = async (optionsFunction, { cwd = _cwd, isDev = _isDev } = {}) => {\n const nextConfig = await loadNextConfig(cwd, isDev);\n return serwist(await optionsFunction(nextConfig), nextConfig, { cwd, isDev });\n};\n\nexport { generateGlobPatterns };\n\nexport type { SerwistOptions };\n"],"mappings":";;;;;;;;;MAG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,UAAU,EAAA;IAAI;IAEpC;EACDC,gBAAgB;GACd,GAAG1B,WAAW0B;GACdC,QAAQ3B,WAAW0B,gBAAgBC,UAAU3D,sBAAsBC,cAAcQ,KAAKP,2BAA0B;GAClH;EACD;;AAGHoB,QAAQF,iBAAiB,OAAOC,iBAAiB,EAAEZ,MAAMF,MAAMO,QAAQJ,WAAW,EAAE,KAAK;CACvF,MAAMO,aAAa,MAAMX,eAAeG,KAAKK,MAAM;AACnD,QAAOQ,QAAQ,MAAMD,gBAAgBJ,WAAW,EAAEA,YAAY;EAAER;EAAKK;EAAO,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["require","logger.info"],"sources":["../src/lib/find-first-truthy.ts","../src/lib/get-file-hash.ts","../src/lib/get-content-hash.ts","../src/lib/get-package-version.ts","../src/lib/load-tsconfig.ts","../src/lib/logger.ts","../src/lib/validator.ts","../src/index.ts"],"sourcesContent":["/**\n * Find the first truthy value in an array.\n * @param arr\n * @param fn\n * @returns\n */\nexport const findFirstTruthy = <T, U>(arr: T[], fn: (elm: T) => U) => {\n for (const i of arr) {\n const resolved = fn(i);\n if (resolved) {\n return resolved;\n }\n }\n return undefined;\n};\n","import crypto from \"node:crypto\";\nimport fs from \"node:fs\";\n\nexport const getFileHash = (file: fs.PathOrFileDescriptor) => crypto.createHash(\"md5\").update(fs.readFileSync(file)).digest(\"hex\");\n","import type fs from \"node:fs\";\n\nimport { getFileHash } from \"./get-file-hash.js\";\n\nexport const getContentHash = (file: fs.PathOrFileDescriptor, isDev: boolean) => {\n if (isDev) {\n return \"development\";\n }\n return getFileHash(file).slice(0, 16);\n};\n","import { createRequire } from \"node:module\";\n\nconst require = createRequire(import.meta.url);\n\n/**\n * Get a package's version\n * @param packageName\n * @returns\n */\nexport const getPackageVersion = (packageName: string): string | undefined => {\n try {\n return require(`${packageName}/package.json`).version;\n } catch {\n return undefined;\n }\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport type { TsConfigJson as TSConfigJSON } from \"type-fest\";\n\nimport { findFirstTruthy } from \"./find-first-truthy.js\";\n\nexport const loadTSConfig = (baseDir: string, relativeTSConfigPath: string | undefined): TSConfigJSON | undefined => {\n try {\n // Find tsconfig.json file\n const tsConfigPath = findFirstTruthy([relativeTSConfigPath ?? \"tsconfig.json\", \"jsconfig.json\"], (filePath) => {\n const resolvedPath = path.join(baseDir, filePath);\n return fs.existsSync(resolvedPath) ? resolvedPath : undefined;\n });\n if (!tsConfigPath) {\n return undefined;\n }\n // Read tsconfig.json file\n return JSON.parse(fs.readFileSync(tsConfigPath, \"utf-8\"));\n } catch {\n return undefined;\n }\n};\n","import { createRequire } from \"node:module\";\nimport { bold, green, red, white, yellow } from \"kolorist\";\nimport semver from \"semver\";\n\nconst require = createRequire(import.meta.url);\n\nconst LOGGING_SPACE_PREFIX = semver.gte(require(\"next/package.json\").version, \"16.0.0\") ? \"\" : \" \";\n\nexport type LoggingMethods = \"wait\" | \"error\" | \"warn\" | \"info\" | \"event\";\n\nconst prefixedLog = (prefixType: LoggingMethods, ...message: any[]) => {\n let prefix: string;\n let consoleMethod: keyof Console;\n\n switch (prefixType) {\n case \"wait\":\n prefix = `${white(bold(\"○\"))} (serwist)`;\n consoleMethod = \"log\";\n break;\n case \"error\":\n prefix = `${red(bold(\"X\"))} (serwist)`;\n consoleMethod = \"error\";\n break;\n case \"warn\":\n prefix = `${yellow(bold(\"⚠\"))} (serwist)`;\n consoleMethod = \"warn\";\n break;\n case \"info\":\n prefix = `${white(bold(\"○\"))} (serwist)`;\n consoleMethod = \"log\";\n break;\n case \"event\":\n prefix = `${green(bold(\"✓\"))} (serwist)`;\n consoleMethod = \"log\";\n break;\n }\n\n if ((message[0] === \"\" || message[0] === undefined) && message.length === 1) {\n message.shift();\n }\n\n // If there's no message, don't print the prefix but a new line\n if (message.length === 0) {\n console[consoleMethod](\"\");\n } else {\n console[consoleMethod](`${LOGGING_SPACE_PREFIX}${prefix}`, ...message);\n }\n};\n\nexport const wait = (...message: any[]) => prefixedLog(\"wait\", ...message);\n\nexport const error = (...message: any[]) => prefixedLog(\"error\", ...message);\n\nexport const warn = (...message: any[]) => prefixedLog(\"warn\", ...message);\n\nexport const info = (...message: any[]) => prefixedLog(\"info\", ...message);\n\nexport const event = (...message: any[]) => prefixedLog(\"event\", ...message);\n","import { SerwistConfigError, validationErrorMap } from \"@serwist/build/schema\";\nimport { z } from \"zod\";\nimport { injectManifestOptions } from \"./schema.js\";\nimport type { InjectManifestOptionsComplete } from \"./types.js\";\n\nexport const validateInjectManifestOptions = (input: unknown): InjectManifestOptionsComplete => {\n const result = injectManifestOptions.safeParse(input, {\n error: validationErrorMap,\n });\n if (!result.success) {\n throw new SerwistConfigError({ moduleName: \"@serwist/next\", message: z.prettifyError(result.error) });\n }\n return result.data;\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { InjectManifest } from \"@serwist/webpack-plugin\";\nimport { ChildCompilationPlugin, relativeToOutputPath } from \"@serwist/webpack-plugin/internal\";\nimport { globSync } from \"glob\";\nimport type { NextConfig } from \"next\";\nimport type { Compilation, Configuration, default as Webpack } from \"webpack\";\nimport type { ExcludeParams, SerwistNextOptions, SerwistNextOptionsKey } from \"./internal-types.js\";\nimport { getContentHash, getFileHash, loadTSConfig, logger } from \"./lib/index.js\";\nimport type { InjectManifestOptions, InjectManifestOptionsComplete } from \"./lib/types.js\";\nimport { validateInjectManifestOptions } from \"./lib/validator.js\";\n\nconst dirname = \"__dirname\" in globalThis ? __dirname : fileURLToPath(new URL(\".\", import.meta.url));\n\n/**\n * Integrates Serwist into your Next.js app.\n * @param userOptions\n * @returns\n */\nconst withSerwistInit = (userOptions: InjectManifestOptions): ((nextConfig?: NextConfig) => NextConfig) => {\n if (!process.env.SERWIST_SUPPRESS_TURBOPACK_WARNING && process.env.TURBOPACK && !userOptions.disable) {\n process.env.SERWIST_SUPPRESS_TURBOPACK_WARNING = \"1\";\n console.warn(\n `[@serwist/next] WARNING: You are using '@serwist/next' with \\`next dev --turbopack\\`, but it doesn't support Turbopack. Do one of the following:\n\n- Set \\`disable\\` to \\`process.env.NODE_ENV !== \"production\"\\`.\n\n- Use webpack by running \\`next dev --webpack\\` instead of \\`next dev --turbopack\\`.\n\n- Migrate to '@serwist/turbopack' which has experimental support for Turbopack. See https://serwist.pages.dev/docs/next/turbo for more information.\n\n- Migrate to configurator mode which has support for Turbopack. See https://serwist.pages.dev/docs/next/config for more information. \n\nFollow https://github.com/serwist/serwist/issues/54 for progress on Serwist + Turbopack. You can also suppress this warning by setting SERWIST_SUPPRESS_TURBOPACK_WARNING=1.\\n`,\n );\n }\n return (nextConfig = {}) => ({\n ...nextConfig,\n webpack(config: Configuration, options) {\n const webpack: typeof Webpack = options.webpack;\n const { dev } = options;\n\n const basePath = options.config.basePath || \"/\";\n\n const tsConfigJson = loadTSConfig(options.dir, nextConfig?.typescript?.tsconfigPath);\n\n const {\n cacheOnNavigation,\n disable,\n scope = basePath,\n swUrl,\n register,\n reloadOnOnline,\n globPublicPatterns,\n ...buildOptions\n } = validateInjectManifestOptions(userOptions);\n\n if (typeof nextConfig.webpack === \"function\") {\n config = nextConfig.webpack(config, options);\n }\n\n if (disable) {\n options.isServer && logger.info(\"Serwist is disabled.\");\n return config;\n }\n\n if (!config.plugins) {\n config.plugins = [];\n }\n\n const _sw = path.posix.join(basePath, swUrl);\n const _scope = path.posix.join(scope, \"/\");\n\n config.plugins.push(\n new webpack.DefinePlugin({\n \"self.__SERWIST_SW_ENTRY.sw\": `'${_sw}'`,\n \"self.__SERWIST_SW_ENTRY.scope\": `'${_scope}'`,\n \"self.__SERWIST_SW_ENTRY.cacheOnNavigation\": `${cacheOnNavigation}`,\n \"self.__SERWIST_SW_ENTRY.register\": `${register}`,\n \"self.__SERWIST_SW_ENTRY.reloadOnOnline\": `${reloadOnOnline}`,\n } satisfies Record<`${SerwistNextOptionsKey}.${Exclude<keyof SerwistNextOptions, \"swEntryWorker\">}`, string | undefined>),\n );\n\n const swEntryJs = path.join(dirname, \"sw-entry.mjs\");\n const entry = config.entry as () => Promise<Record<string, string[] | string>>;\n config.entry = async () => {\n const entries = await entry();\n if (entries[\"main.js\"] && !entries[\"main.js\"].includes(swEntryJs)) {\n if (Array.isArray(entries[\"main.js\"])) {\n entries[\"main.js\"].unshift(swEntryJs);\n } else if (typeof entries[\"main.js\"] === \"string\") {\n entries[\"main.js\"] = [swEntryJs, entries[\"main.js\"]];\n }\n }\n if (entries[\"main-app\"] && !entries[\"main-app\"].includes(swEntryJs)) {\n if (Array.isArray(entries[\"main-app\"])) {\n entries[\"main-app\"].unshift(swEntryJs);\n } else if (typeof entries[\"main-app\"] === \"string\") {\n entries[\"main-app\"] = [swEntryJs, entries[\"main-app\"]];\n }\n }\n return entries;\n };\n\n if (!options.isServer) {\n if (!register) {\n logger.info(\n \"The service worker will not be automatically registered, please call 'window.serwist.register()' in 'componentDidMount' or 'useEffect'.\",\n );\n\n if (!tsConfigJson?.compilerOptions?.types?.includes(\"@serwist/next/typings\")) {\n logger.info(\n \"You may also want to add '@serwist/next/typings' to your TypeScript/JavaScript configuration file at 'compilerOptions.types'.\",\n );\n }\n }\n\n const {\n swSrc: userSwSrc,\n swDest: userSwDest,\n additionalPrecacheEntries,\n exclude,\n manifestTransforms = [],\n ...otherBuildOptions\n } = buildOptions;\n\n let swSrc = userSwSrc;\n let swDest = userSwDest;\n\n // If these two paths are not absolute, they will be resolved from `compilation.options.output.path`,\n // which is `${options.dir}/${nextConfig.destDir}` for Next.js apps, rather than `${options.dir}`\n // as an user would expect.\n if (!path.isAbsolute(swSrc)) {\n swSrc = path.join(options.dir, swSrc);\n }\n if (!path.isAbsolute(swDest)) {\n swDest = path.join(options.dir, swDest);\n }\n\n const publicDir = path.resolve(options.dir, \"public\");\n const { dir: destDir, base: destBase } = path.parse(swDest);\n\n const cleanUpList = globSync([\"swe-worker-*.js\", \"swe-worker-*.js.map\", destBase, `${destBase}.map`], {\n absolute: true,\n nodir: true,\n follow: true,\n cwd: destDir,\n });\n\n for (const file of cleanUpList) {\n fs.rmSync(file, { force: true });\n }\n\n const shouldBuildSWEntryWorker = cacheOnNavigation;\n let swEntryPublicPath: string | undefined;\n let swEntryWorkerDest: string | undefined;\n\n if (shouldBuildSWEntryWorker) {\n const swEntryWorkerSrc = path.join(dirname, \"sw-entry-worker.mjs\");\n const swEntryName = `swe-worker-${getContentHash(swEntryWorkerSrc, dev)}.js`;\n swEntryPublicPath = path.posix.join(basePath, swEntryName);\n swEntryWorkerDest = path.join(destDir, swEntryName);\n config.plugins.push(\n new ChildCompilationPlugin({\n src: swEntryWorkerSrc,\n dest: swEntryWorkerDest,\n }),\n );\n }\n config.plugins.push(\n new webpack.DefinePlugin({\n \"self.__SERWIST_SW_ENTRY.swEntryWorker\": swEntryPublicPath && `'${swEntryPublicPath}'`,\n } satisfies Record<`${SerwistNextOptionsKey}.${Extract<keyof SerwistNextOptions, \"swEntryWorker\">}`, string | undefined>),\n );\n\n logger.event(`Bundling the service worker script with the URL '${_sw}' and the scope '${_scope}'...`);\n\n // Precache files in public folder\n let resolvedManifestEntries = additionalPrecacheEntries;\n\n if (!resolvedManifestEntries) {\n const publicScan = globSync(globPublicPatterns, {\n nodir: true,\n follow: true,\n cwd: publicDir,\n ignore: [\"swe-worker-*.js\", destBase, `${destBase}.map`],\n });\n resolvedManifestEntries = publicScan.map((f) => ({\n url: path.posix.join(basePath, f),\n revision: getFileHash(path.join(publicDir, f)),\n }));\n }\n\n const publicPath = config.output?.publicPath;\n\n config.plugins.push(\n new InjectManifest({\n swSrc,\n swDest,\n disablePrecacheManifest: dev,\n additionalPrecacheEntries: dev ? [] : resolvedManifestEntries,\n exclude: [\n ...exclude,\n ({ asset, compilation }: ExcludeParams) => {\n // Same as how `@serwist/webpack-plugin` does it. It is always\n // `relativeToOutputPath(compilation, originalSwDest)`.\n const swDestRelativeOutput = relativeToOutputPath(compilation, swDest);\n const swAsset = compilation.getAsset(swDestRelativeOutput);\n return (\n // We don't need the service worker to be cached.\n asset.name === swAsset?.name ||\n asset.name.startsWith(\"server/\") ||\n // This excludes all JSON files in the compilation directory by filtering\n // out paths that have slashes or don't end with `.json`. Only said files\n // match this criterion.\n /^[^/]*\\.json$/.test(asset.name) ||\n (dev && !asset.name.startsWith(\"static/runtime/\"))\n );\n },\n ],\n manifestTransforms: [\n ...manifestTransforms,\n async (manifestEntries, compilation) => {\n // This path always uses forward slashes, so it is safe to use it in the following string replace.\n const publicDirRelativeOutput = relativeToOutputPath(compilation as Compilation, publicDir);\n // `publicPath` is always `${assetPrefix}/_next/` for Next.js apps.\n const publicFilesPrefix = `${publicPath}${publicDirRelativeOutput}`;\n const manifest = manifestEntries.map((m) => {\n m.url = m.url.replace(\"/_next//static/image\", \"/_next/static/image\").replace(\"/_next//static/media\", \"/_next/static/media\");\n // We remove `${publicPath}/${publicDirRelativeOutput}` because `assetPrefix`\n // is not intended for files that are in the public directory and we also want\n // to remove `/_next/${publicDirRelativeOutput}` from the URL, since that is not how\n // we resolve files in the public directory.\n if (m.url.startsWith(publicFilesPrefix)) {\n m.url = path.posix.join(basePath, m.url.replace(publicFilesPrefix, \"\"));\n }\n m.url = m.url.replace(/\\[/g, \"%5B\").replace(/\\]/g, \"%5D\").replace(/@/g, \"%40\");\n return m;\n });\n return { manifest, warnings: [] };\n },\n ],\n ...otherBuildOptions,\n }),\n );\n }\n\n return config;\n },\n });\n};\n\nexport default withSerwistInit;\nexport { validateInjectManifestOptions };\nexport type { InjectManifestOptions as PluginOptions, InjectManifestOptionsComplete as PluginOptionsComplete };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAMA,MAAa,mBAAyB,KAAU,OAAsB;AACpE,MAAK,MAAM,KAAK,KAAK;EACnB,MAAM,WAAW,GAAG,EAAE;AACtB,MAAI,SACF,QAAO;;;;;ACPb,MAAa,eAAe,SAAkC,OAAO,WAAW,MAAM,CAAC,OAAO,GAAG,aAAa,KAAK,CAAC,CAAC,OAAO,MAAM;;;ACCl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,aAEE,MAAM,SAAS,SAAS,QACxB,MAAM,KAAK,WAAW,UAAU,IAIhC,gBAAgB,KAAK,MAAM,KAAK,IAC/B,OAAO,CAAC,MAAM,KAAK,WAAW,kBAAkB;OAGtD;KACD,oBAAoB,CAClB,GAAG,oBACH,OAAO,iBAAiB,gBAAgB;MAItC,MAAM,oBAAoB,GAAG,aAFG,qBAAqB,aAA4B,UAEhB;AAajE,aAAO;OAAE,UAZQ,gBAAgB,KAAK,MAAM;AAC1C,UAAE,MAAM,EAAE,IAAI,QAAQ,wBAAwB,sBAAsB,CAAC,QAAQ,wBAAwB,sBAAsB;AAK3H,YAAI,EAAE,IAAI,WAAW,kBAAkB,CACrC,GAAE,MAAM,KAAK,MAAM,KAAK,UAAU,EAAE,IAAI,QAAQ,mBAAmB,GAAG,CAAC;AAEzE,UAAE,MAAM,EAAE,IAAI,QAAQ,OAAO,MAAM,CAAC,QAAQ,OAAO,MAAM,CAAC,QAAQ,MAAM,MAAM;AAC9E,eAAO;SAEQ;OAAE,UAAU,EAAE;OAAE;OAEpC;KACD,GAAG;KACJ,CAAC,CACH;;AAGH,UAAO;;EAEV"}
1
+ {"version":3,"file":"index.mjs","names":["findFirstTruthy","arr","T","fn","elm","U","i","resolved","undefined","crypto","fs","getFileHash","file","PathOrFileDescriptor","createHash","update","readFileSync","digest","fs","getFileHash","getContentHash","file","PathOrFileDescriptor","isDev","slice","createRequire","require","import","meta","url","getPackageVersion","packageName","version","undefined","fs","path","TsConfigJson","TSConfigJSON","findFirstTruthy","loadTSConfig","baseDir","relativeTSConfigPath","tsConfigPath","filePath","resolvedPath","join","existsSync","undefined","JSON","parse","readFileSync","createRequire","bold","green","red","white","yellow","semver","require","import","meta","url","LOGGING_SPACE_PREFIX","gte","version","LoggingMethods","prefixedLog","prefixType","message","prefix","consoleMethod","Console","undefined","length","shift","console","wait","error","warn","info","event","SerwistConfigError","validationErrorMap","z","injectManifestOptions","InjectManifestOptionsComplete","validateInjectManifestOptions","input","result","safeParse","error","success","moduleName","message","prettifyError","data","fs","path","fileURLToPath","InjectManifest","ChildCompilationPlugin","relativeToOutputPath","globSync","NextConfig","Compilation","Configuration","default","Webpack","ExcludeParams","SerwistNextOptions","SerwistNextOptionsKey","getContentHash","getFileHash","loadTSConfig","logger","InjectManifestOptions","InjectManifestOptionsComplete","validateInjectManifestOptions","dirname","globalThis","__dirname","URL","import","meta","url","withSerwistInit","userOptions","nextConfig","process","env","SERWIST_SUPPRESS_TURBOPACK_WARNING","TURBOPACK","disable","console","warn","webpack","config","options","dev","basePath","tsConfigJson","dir","typescript","tsconfigPath","cacheOnNavigation","scope","swUrl","register","reloadOnOnline","globPublicPatterns","buildOptions","isServer","info","plugins","_sw","posix","join","_scope","push","DefinePlugin","Record","Exclude","swEntryJs","entry","Promise","entries","includes","Array","isArray","unshift","compilerOptions","types","swSrc","userSwSrc","swDest","userSwDest","additionalPrecacheEntries","exclude","manifestTransforms","otherBuildOptions","isAbsolute","publicDir","resolve","destDir","base","destBase","parse","cleanUpList","absolute","nodir","follow","cwd","file","rmSync","force","shouldBuildSWEntryWorker","swEntryPublicPath","swEntryWorkerDest","swEntryWorkerSrc","swEntryName","src","dest","Extract","event","resolvedManifestEntries","publicScan","ignore","map","f","revision","publicPath","output","disablePrecacheManifest","asset","compilation","swDestRelativeOutput","swAsset","getAsset","name","startsWith","test","manifestEntries","publicDirRelativeOutput","publicFilesPrefix","manifest","m","replace","warnings","PluginOptions","PluginOptionsComplete"],"sources":["../src/lib/find-first-truthy.ts","../src/lib/get-file-hash.ts","../src/lib/get-content-hash.ts","../src/lib/get-package-version.ts","../src/lib/load-tsconfig.ts","../src/lib/logger.ts","../src/lib/validator.ts","../src/index.ts"],"sourcesContent":["/**\n * Find the first truthy value in an array.\n * @param arr\n * @param fn\n * @returns\n */\nexport const findFirstTruthy = <T, U>(arr: T[], fn: (elm: T) => U) => {\n for (const i of arr) {\n const resolved = fn(i);\n if (resolved) {\n return resolved;\n }\n }\n return undefined;\n};\n","import crypto from \"node:crypto\";\nimport fs from \"node:fs\";\n\nexport const getFileHash = (file: fs.PathOrFileDescriptor) => crypto.createHash(\"md5\").update(fs.readFileSync(file)).digest(\"hex\");\n","import type fs from \"node:fs\";\n\nimport { getFileHash } from \"./get-file-hash.js\";\n\nexport const getContentHash = (file: fs.PathOrFileDescriptor, isDev: boolean) => {\n if (isDev) {\n return \"development\";\n }\n return getFileHash(file).slice(0, 16);\n};\n","import { createRequire } from \"node:module\";\n\nconst require = createRequire(import.meta.url);\n\n/**\n * Get a package's version\n * @param packageName\n * @returns\n */\nexport const getPackageVersion = (packageName: string): string | undefined => {\n try {\n return require(`${packageName}/package.json`).version;\n } catch {\n return undefined;\n }\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport type { TsConfigJson as TSConfigJSON } from \"type-fest\";\n\nimport { findFirstTruthy } from \"./find-first-truthy.js\";\n\nexport const loadTSConfig = (baseDir: string, relativeTSConfigPath: string | undefined): TSConfigJSON | undefined => {\n try {\n // Find tsconfig.json file\n const tsConfigPath = findFirstTruthy([relativeTSConfigPath ?? \"tsconfig.json\", \"jsconfig.json\"], (filePath) => {\n const resolvedPath = path.join(baseDir, filePath);\n return fs.existsSync(resolvedPath) ? resolvedPath : undefined;\n });\n if (!tsConfigPath) {\n return undefined;\n }\n // Read tsconfig.json file\n return JSON.parse(fs.readFileSync(tsConfigPath, \"utf-8\"));\n } catch {\n return undefined;\n }\n};\n","import { createRequire } from \"node:module\";\nimport { bold, green, red, white, yellow } from \"kolorist\";\nimport semver from \"semver\";\n\nconst require = createRequire(import.meta.url);\n\nconst LOGGING_SPACE_PREFIX = semver.gte(require(\"next/package.json\").version, \"16.0.0\") ? \"\" : \" \";\n\nexport type LoggingMethods = \"wait\" | \"error\" | \"warn\" | \"info\" | \"event\";\n\nconst prefixedLog = (prefixType: LoggingMethods, ...message: any[]) => {\n let prefix: string;\n let consoleMethod: keyof Console;\n\n switch (prefixType) {\n case \"wait\":\n prefix = `${white(bold(\"○\"))} (serwist)`;\n consoleMethod = \"log\";\n break;\n case \"error\":\n prefix = `${red(bold(\"X\"))} (serwist)`;\n consoleMethod = \"error\";\n break;\n case \"warn\":\n prefix = `${yellow(bold(\"⚠\"))} (serwist)`;\n consoleMethod = \"warn\";\n break;\n case \"info\":\n prefix = `${white(bold(\"○\"))} (serwist)`;\n consoleMethod = \"log\";\n break;\n case \"event\":\n prefix = `${green(bold(\"✓\"))} (serwist)`;\n consoleMethod = \"log\";\n break;\n }\n\n if ((message[0] === \"\" || message[0] === undefined) && message.length === 1) {\n message.shift();\n }\n\n // If there's no message, don't print the prefix but a new line\n if (message.length === 0) {\n console[consoleMethod](\"\");\n } else {\n console[consoleMethod](`${LOGGING_SPACE_PREFIX}${prefix}`, ...message);\n }\n};\n\nexport const wait = (...message: any[]) => prefixedLog(\"wait\", ...message);\n\nexport const error = (...message: any[]) => prefixedLog(\"error\", ...message);\n\nexport const warn = (...message: any[]) => prefixedLog(\"warn\", ...message);\n\nexport const info = (...message: any[]) => prefixedLog(\"info\", ...message);\n\nexport const event = (...message: any[]) => prefixedLog(\"event\", ...message);\n","import { SerwistConfigError, validationErrorMap } from \"@serwist/build/schema\";\nimport { z } from \"zod\";\nimport { injectManifestOptions } from \"./schema.js\";\nimport type { InjectManifestOptionsComplete } from \"./types.js\";\n\nexport const validateInjectManifestOptions = (input: unknown): InjectManifestOptionsComplete => {\n const result = injectManifestOptions.safeParse(input, {\n error: validationErrorMap,\n });\n if (!result.success) {\n throw new SerwistConfigError({ moduleName: \"@serwist/next\", message: z.prettifyError(result.error) });\n }\n return result.data;\n};\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { InjectManifest } from \"@serwist/webpack-plugin\";\nimport { ChildCompilationPlugin, relativeToOutputPath } from \"@serwist/webpack-plugin/internal\";\nimport { globSync } from \"glob\";\nimport type { NextConfig } from \"next\";\nimport type { Compilation, Configuration, default as Webpack } from \"webpack\";\nimport type { ExcludeParams, SerwistNextOptions, SerwistNextOptionsKey } from \"./internal-types.js\";\nimport { getContentHash, getFileHash, loadTSConfig, logger } from \"./lib/index.js\";\nimport type { InjectManifestOptions, InjectManifestOptionsComplete } from \"./lib/types.js\";\nimport { validateInjectManifestOptions } from \"./lib/validator.js\";\n\nconst dirname = \"__dirname\" in globalThis ? __dirname : fileURLToPath(new URL(\".\", import.meta.url));\n\n/**\n * Integrates Serwist into your Next.js app.\n * @param userOptions\n * @returns\n */\nconst withSerwistInit = (userOptions: InjectManifestOptions): ((nextConfig?: NextConfig) => NextConfig) => {\n if (!process.env.SERWIST_SUPPRESS_TURBOPACK_WARNING && process.env.TURBOPACK && !userOptions.disable) {\n process.env.SERWIST_SUPPRESS_TURBOPACK_WARNING = \"1\";\n console.warn(\n `[@serwist/next] WARNING: You are using '@serwist/next' with \\`next dev --turbopack\\`, but it doesn't support Turbopack. Do one of the following:\n\n- Set \\`disable\\` to \\`process.env.NODE_ENV !== \"production\"\\`.\n\n- Use webpack by running \\`next dev --webpack\\` instead of \\`next dev --turbopack\\`.\n\n- Migrate to '@serwist/turbopack' which has experimental support for Turbopack. See https://serwist.pages.dev/docs/next/turbo for more information.\n\n- Migrate to configurator mode which has support for Turbopack. See https://serwist.pages.dev/docs/next/config for more information. \n\nFollow https://github.com/serwist/serwist/issues/54 for progress on Serwist + Turbopack. You can also suppress this warning by setting SERWIST_SUPPRESS_TURBOPACK_WARNING=1.\\n`,\n );\n }\n return (nextConfig = {}) => ({\n ...nextConfig,\n webpack(config: Configuration, options) {\n const webpack: typeof Webpack = options.webpack;\n const { dev } = options;\n\n const basePath = options.config.basePath || \"/\";\n\n const tsConfigJson = loadTSConfig(options.dir, nextConfig?.typescript?.tsconfigPath);\n\n const {\n cacheOnNavigation,\n disable,\n scope = basePath,\n swUrl,\n register,\n reloadOnOnline,\n globPublicPatterns,\n ...buildOptions\n } = validateInjectManifestOptions(userOptions);\n\n if (typeof nextConfig.webpack === \"function\") {\n config = nextConfig.webpack(config, options);\n }\n\n if (disable) {\n options.isServer && logger.info(\"Serwist is disabled.\");\n return config;\n }\n\n if (!config.plugins) {\n config.plugins = [];\n }\n\n const _sw = path.posix.join(basePath, swUrl);\n const _scope = path.posix.join(scope, \"/\");\n\n config.plugins.push(\n new webpack.DefinePlugin({\n \"self.__SERWIST_SW_ENTRY.sw\": `'${_sw}'`,\n \"self.__SERWIST_SW_ENTRY.scope\": `'${_scope}'`,\n \"self.__SERWIST_SW_ENTRY.cacheOnNavigation\": `${cacheOnNavigation}`,\n \"self.__SERWIST_SW_ENTRY.register\": `${register}`,\n \"self.__SERWIST_SW_ENTRY.reloadOnOnline\": `${reloadOnOnline}`,\n } satisfies Record<`${SerwistNextOptionsKey}.${Exclude<keyof SerwistNextOptions, \"swEntryWorker\">}`, string | undefined>),\n );\n\n const swEntryJs = path.join(dirname, \"sw-entry.mjs\");\n const entry = config.entry as () => Promise<Record<string, string[] | string>>;\n config.entry = async () => {\n const entries = await entry();\n if (entries[\"main.js\"] && !entries[\"main.js\"].includes(swEntryJs)) {\n if (Array.isArray(entries[\"main.js\"])) {\n entries[\"main.js\"].unshift(swEntryJs);\n } else if (typeof entries[\"main.js\"] === \"string\") {\n entries[\"main.js\"] = [swEntryJs, entries[\"main.js\"]];\n }\n }\n if (entries[\"main-app\"] && !entries[\"main-app\"].includes(swEntryJs)) {\n if (Array.isArray(entries[\"main-app\"])) {\n entries[\"main-app\"].unshift(swEntryJs);\n } else if (typeof entries[\"main-app\"] === \"string\") {\n entries[\"main-app\"] = [swEntryJs, entries[\"main-app\"]];\n }\n }\n return entries;\n };\n\n if (!options.isServer) {\n if (!register) {\n logger.info(\n \"The service worker will not be automatically registered, please call 'window.serwist.register()' in 'componentDidMount' or 'useEffect'.\",\n );\n\n if (!tsConfigJson?.compilerOptions?.types?.includes(\"@serwist/next/typings\")) {\n logger.info(\n \"You may also want to add '@serwist/next/typings' to your TypeScript/JavaScript configuration file at 'compilerOptions.types'.\",\n );\n }\n }\n\n const {\n swSrc: userSwSrc,\n swDest: userSwDest,\n additionalPrecacheEntries,\n exclude,\n manifestTransforms = [],\n ...otherBuildOptions\n } = buildOptions;\n\n let swSrc = userSwSrc;\n let swDest = userSwDest;\n\n // If these two paths are not absolute, they will be resolved from `compilation.options.output.path`,\n // which is `${options.dir}/${nextConfig.destDir}` for Next.js apps, rather than `${options.dir}`\n // as an user would expect.\n if (!path.isAbsolute(swSrc)) {\n swSrc = path.join(options.dir, swSrc);\n }\n if (!path.isAbsolute(swDest)) {\n swDest = path.join(options.dir, swDest);\n }\n\n const publicDir = path.resolve(options.dir, \"public\");\n const { dir: destDir, base: destBase } = path.parse(swDest);\n\n const cleanUpList = globSync([\"swe-worker-*.js\", \"swe-worker-*.js.map\", destBase, `${destBase}.map`], {\n absolute: true,\n nodir: true,\n follow: true,\n cwd: destDir,\n });\n\n for (const file of cleanUpList) {\n fs.rmSync(file, { force: true });\n }\n\n const shouldBuildSWEntryWorker = cacheOnNavigation;\n let swEntryPublicPath: string | undefined;\n let swEntryWorkerDest: string | undefined;\n\n if (shouldBuildSWEntryWorker) {\n const swEntryWorkerSrc = path.join(dirname, \"sw-entry-worker.mjs\");\n const swEntryName = `swe-worker-${getContentHash(swEntryWorkerSrc, dev)}.js`;\n swEntryPublicPath = path.posix.join(basePath, swEntryName);\n swEntryWorkerDest = path.join(destDir, swEntryName);\n config.plugins.push(\n new ChildCompilationPlugin({\n src: swEntryWorkerSrc,\n dest: swEntryWorkerDest,\n }),\n );\n }\n config.plugins.push(\n new webpack.DefinePlugin({\n \"self.__SERWIST_SW_ENTRY.swEntryWorker\": swEntryPublicPath && `'${swEntryPublicPath}'`,\n } satisfies Record<`${SerwistNextOptionsKey}.${Extract<keyof SerwistNextOptions, \"swEntryWorker\">}`, string | undefined>),\n );\n\n logger.event(`Bundling the service worker script with the URL '${_sw}' and the scope '${_scope}'...`);\n\n // Precache files in public folder\n let resolvedManifestEntries = additionalPrecacheEntries;\n\n if (!resolvedManifestEntries) {\n const publicScan = globSync(globPublicPatterns, {\n nodir: true,\n follow: true,\n cwd: publicDir,\n ignore: [\"swe-worker-*.js\", destBase, `${destBase}.map`],\n });\n resolvedManifestEntries = publicScan.map((f) => ({\n url: path.posix.join(basePath, f),\n revision: getFileHash(path.join(publicDir, f)),\n }));\n }\n\n const publicPath = config.output?.publicPath;\n\n config.plugins.push(\n new InjectManifest({\n swSrc,\n swDest,\n disablePrecacheManifest: dev,\n additionalPrecacheEntries: dev ? [] : resolvedManifestEntries,\n exclude: [\n ...exclude,\n ({ asset, compilation }: ExcludeParams) => {\n // Same as how `@serwist/webpack-plugin` does it. It is always\n // `relativeToOutputPath(compilation, originalSwDest)`.\n const swDestRelativeOutput = relativeToOutputPath(compilation, swDest);\n const swAsset = compilation.getAsset(swDestRelativeOutput);\n return (\n // We don't need the service worker to be cached.\n asset.name === swAsset?.name ||\n asset.name.startsWith(\"server/\") ||\n // This excludes all JSON files in the compilation directory by filtering\n // out paths that have slashes or don't end with `.json`. Only said files\n // match this criterion.\n /^[^/]*\\.json$/.test(asset.name) ||\n (dev && !asset.name.startsWith(\"static/runtime/\"))\n );\n },\n ],\n manifestTransforms: [\n ...manifestTransforms,\n async (manifestEntries, compilation) => {\n // This path always uses forward slashes, so it is safe to use it in the following string replace.\n const publicDirRelativeOutput = relativeToOutputPath(compilation as Compilation, publicDir);\n // `publicPath` is always `${assetPrefix}/_next/` for Next.js apps.\n const publicFilesPrefix = `${publicPath}${publicDirRelativeOutput}`;\n const manifest = manifestEntries.map((m) => {\n m.url = m.url.replace(\"/_next//static/image\", \"/_next/static/image\").replace(\"/_next//static/media\", \"/_next/static/media\");\n // We remove `${publicPath}/${publicDirRelativeOutput}` because `assetPrefix`\n // is not intended for files that are in the public directory and we also want\n // to remove `/_next/${publicDirRelativeOutput}` from the URL, since that is not how\n // we resolve files in the public directory.\n if (m.url.startsWith(publicFilesPrefix)) {\n m.url = path.posix.join(basePath, m.url.replace(publicFilesPrefix, \"\"));\n }\n m.url = m.url.replace(/\\[/g, \"%5B\").replace(/\\]/g, \"%5D\").replace(/@/g, \"%40\");\n return m;\n });\n return { manifest, warnings: [] };\n },\n ],\n ...otherBuildOptions,\n }),\n );\n }\n\n return config;\n },\n });\n};\n\nexport default withSerwistInit;\nexport { validateInjectManifestOptions };\nexport type { InjectManifestOptions as PluginOptions, InjectManifestOptionsComplete as PluginOptionsComplete };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAMA,MAAaA,mBAAyBC,KAAUE,OAAsB;AACpE,MAAK,MAAMG,KAAKL,KAAK;EACnB,MAAMM,WAAWJ,GAAGG,EAAE;AACtB,MAAIC,SACF,QAAOA;;;;;ACPb,MAAaI,eAAeC,SAAkCH,OAAOK,WAAW,MAAM,CAACC,OAAOL,GAAGM,aAAaJ,KAAK,CAAC,CAACK,OAAO,MAAM;;;ACClI,MAAaG,kBAAkBC,MAA+BE,UAAmB;AAC/E,KAAIA,MACF,QAAO;AAET,QAAOJ,YAAYE,KAAK,CAACG,MAAM,GAAG,GAAG;;ACNvBC,cAAcE,OAAOC,KAAKC,IAAI;;;ACK9C,MAAaU,gBAAgBC,SAAiBC,yBAAuE;AACnH,KAAI;EAEF,MAAMC,eAAeJ,gBAAgB,CAACG,wBAAwB,iBAAiB,gBAAgB,GAAGE,aAAa;GAC7G,MAAMC,eAAeT,KAAKU,KAAKL,SAASG,SAAS;AACjD,UAAOT,GAAGY,WAAWF,aAAa,GAAGA,eAAeG,KAAAA;IACpD;AACF,MAAI,CAACL,aACH;AAGF,SAAOM,KAAKC,MAAMf,GAAGgB,aAAaR,cAAc,QAAQ,CAAC;SACnD;AACN;;;;;AChBJ,MAAMgB,UAAUP,cAAcQ,OAAOC,KAAKC,IAAI;AAE9C,MAAMC,uBAAuBL,OAAOM,IAAIL,QAAQ,oBAAoB,CAACM,SAAS,SAAS,GAAG,KAAK;AAI/F,MAAME,eAAeC,YAA4B,GAAGC,YAAmB;CACrE,IAAIC;CACJ,IAAIC;AAEJ,SAAQH,YAAR;EACE,KAAK;A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kBAAiB;OAGrD;KACDzC,oBAAoB,CAClB,GAAGA,oBACH,OAAO2C,iBAAiBP,gBAAgB;MAItC,MAAMS,oBAAoB,GAAGb,aAFG7G,qBAAqBiH,aAA4BjC,UAEhB;AAajE,aAAO;OAAE2C,UAZQH,gBAAgBd,KAAKkB,MAAM;AAC1CA,UAAErG,MAAMqG,EAAErG,IAAIsG,QAAQ,wBAAwB,sBAAsB,CAACA,QAAQ,wBAAwB,sBAAsB;AAK3H,YAAID,EAAErG,IAAI+F,WAAWI,kBAAkB,CACrCE,GAAErG,MAAM3B,KAAK0D,MAAMC,KAAKjB,UAAUsF,EAAErG,IAAIsG,QAAQH,mBAAmB,GAAG,CAAC;AAEzEE,UAAErG,MAAMqG,EAAErG,IAAIsG,QAAQ,OAAO,MAAM,CAACA,QAAQ,OAAO,MAAM,CAACA,QAAQ,MAAM,MAAM;AAC9E,eAAOD;SAEQ;OAAEE,UAAU,EAAA;OAAI;OAEpC;KACD,GAAGhD;KACJ,CACH,CAAC;;AAGH,UAAO3C;;EAEV"}
@@ -1,6 +1,8 @@
1
+ import { c } from "react/compiler-runtime";
1
2
  import { Serwist } from "@serwist/window";
2
3
  import { isCurrentPageOutOfScope } from "@serwist/window/internal";
3
4
  import { createContext, useContext, useEffect, useState } from "react";
5
+ import { jsx } from "react/jsx-runtime";
4
6
  //#region src/lib/context.ts
5
7
  const SerwistContext = createContext(null);
6
8
  const useSerwist = () => {
@@ -15,57 +17,120 @@ const useSerwist = () => {
15
17
  * @param options
16
18
  * @returns
17
19
  */
18
- function SerwistProvider({ swUrl, disable = false, register = true, cacheOnNavigation = true, reloadOnOnline = true, options, children }) {
19
- const [serwist] = useState(() => {
20
- if (typeof window === "undefined") return null;
21
- if (disable) return null;
22
- const scope = options?.scope || "/";
23
- if (!(window.serwist && window.serwist instanceof Serwist) && "serviceWorker" in navigator) {
24
- window.serwist = new Serwist(swUrl, {
25
- ...options,
26
- scope,
27
- type: options?.type || "module"
28
- });
29
- if (register && !isCurrentPageOutOfScope(scope)) window.serwist.register();
30
- }
31
- return window.serwist ?? null;
32
- });
33
- useEffect(() => {
34
- const cacheUrls = async (url) => {
35
- if (!window.navigator.onLine || !url) return;
36
- serwist?.messageSW({
37
- type: "CACHE_URLS",
38
- payload: { urlsToCache: [url] }
39
- });
20
+ function SerwistProvider(t0) {
21
+ const $ = c(19);
22
+ const { swUrl, disable: t1, register: t2, cacheOnNavigation: t3, reloadOnOnline: t4, options, children } = t0;
23
+ const disable = t1 === void 0 ? false : t1;
24
+ const register = t2 === void 0 ? true : t2;
25
+ const cacheOnNavigation = t3 === void 0 ? true : t3;
26
+ const reloadOnOnline = t4 === void 0 ? true : t4;
27
+ let t5;
28
+ if ($[0] !== disable || $[1] !== options || $[2] !== register || $[3] !== swUrl) {
29
+ t5 = () => {
30
+ if (typeof window === "undefined") return null;
31
+ if (disable) return null;
32
+ const scope = options?.scope || "/";
33
+ if (!(window.serwist && window.serwist instanceof Serwist) && "serviceWorker" in navigator) {
34
+ window.serwist = new Serwist(swUrl, {
35
+ ...options,
36
+ scope,
37
+ type: options?.type || "module"
38
+ });
39
+ if (register && !isCurrentPageOutOfScope(scope)) window.serwist.register();
40
+ }
41
+ return window.serwist ?? null;
40
42
  };
41
- const cacheCurrentPathname = () => cacheUrls(window.location.pathname);
42
- const pushState = history.pushState;
43
- const replaceState = history.replaceState;
44
- if (cacheOnNavigation) {
45
- history.pushState = (...args) => {
46
- pushState.apply(history, args);
47
- cacheUrls(args[2]);
43
+ $[0] = disable;
44
+ $[1] = options;
45
+ $[2] = register;
46
+ $[3] = swUrl;
47
+ $[4] = t5;
48
+ } else t5 = $[4];
49
+ const [serwist] = useState(t5);
50
+ let t6;
51
+ if ($[5] !== cacheOnNavigation || $[6] !== serwist) {
52
+ t6 = () => {
53
+ const cacheUrls = async (url) => {
54
+ if (!window.navigator.onLine || !url) return;
55
+ serwist?.messageSW({
56
+ type: "CACHE_URLS",
57
+ payload: { urlsToCache: [url] }
58
+ });
48
59
  };
49
- history.replaceState = (...args) => {
50
- replaceState.apply(history, args);
51
- cacheUrls(args[2]);
60
+ const cacheCurrentPathname = () => cacheUrls(window.location.pathname);
61
+ const pushState = history.pushState;
62
+ const replaceState = history.replaceState;
63
+ if (cacheOnNavigation) {
64
+ history.pushState = (...t7) => {
65
+ const args = t7;
66
+ pushState.apply(history, args);
67
+ cacheUrls(args[2]);
68
+ };
69
+ history.replaceState = (...t8) => {
70
+ const args_0 = t8;
71
+ replaceState.apply(history, args_0);
72
+ cacheUrls(args_0[2]);
73
+ };
74
+ window.addEventListener("online", cacheCurrentPathname);
75
+ }
76
+ return () => {
77
+ history.pushState = pushState;
78
+ history.replaceState = replaceState;
79
+ window.removeEventListener("online", cacheCurrentPathname);
52
80
  };
53
- window.addEventListener("online", cacheCurrentPathname);
54
- }
55
- return () => {
56
- history.pushState = pushState;
57
- history.replaceState = replaceState;
58
- window.removeEventListener("online", cacheCurrentPathname);
59
81
  };
60
- }, [serwist?.messageSW, cacheOnNavigation]);
61
- useEffect(() => {
62
- const reload = () => location.reload();
63
- if (reloadOnOnline) window.addEventListener("online", reload);
64
- return () => {
65
- window.removeEventListener("online", reload);
82
+ $[5] = cacheOnNavigation;
83
+ $[6] = serwist;
84
+ $[7] = t6;
85
+ } else t6 = $[7];
86
+ const t7 = serwist?.messageSW;
87
+ let t8;
88
+ if ($[8] !== cacheOnNavigation || $[9] !== t7) {
89
+ t8 = [t7, cacheOnNavigation];
90
+ $[8] = cacheOnNavigation;
91
+ $[9] = t7;
92
+ $[10] = t8;
93
+ } else t8 = $[10];
94
+ useEffect(t6, t8);
95
+ let t10;
96
+ let t9;
97
+ if ($[11] !== reloadOnOnline) {
98
+ t9 = () => {
99
+ const reload = _temp;
100
+ if (reloadOnOnline) window.addEventListener("online", reload);
101
+ return () => {
102
+ window.removeEventListener("online", reload);
103
+ };
66
104
  };
67
- }, [reloadOnOnline]);
68
- return <SerwistContext.Provider value={{ serwist }}>{children}</SerwistContext.Provider>;
105
+ t10 = [reloadOnOnline];
106
+ $[11] = reloadOnOnline;
107
+ $[12] = t10;
108
+ $[13] = t9;
109
+ } else {
110
+ t10 = $[12];
111
+ t9 = $[13];
112
+ }
113
+ useEffect(t9, t10);
114
+ let t11;
115
+ if ($[14] !== serwist) {
116
+ t11 = { serwist };
117
+ $[14] = serwist;
118
+ $[15] = t11;
119
+ } else t11 = $[15];
120
+ let t12;
121
+ if ($[16] !== children || $[17] !== t11) {
122
+ t12 = /* @__PURE__ */ jsx(SerwistContext.Provider, {
123
+ value: t11,
124
+ children
125
+ });
126
+ $[16] = children;
127
+ $[17] = t11;
128
+ $[18] = t12;
129
+ } else t12 = $[18];
130
+ return t12;
131
+ }
132
+ function _temp() {
133
+ return location.reload();
69
134
  }
70
135
  //#endregion
71
136
  export { SerwistProvider, useSerwist };
@@ -1 +1 @@
1
- {"version":3,"file":"index.react.mjs","names":[],"sources":["../src/lib/context.ts","../src/index.react.tsx"],"sourcesContent":["import type { Serwist } from \"@serwist/window\";\nimport { createContext, useContext } from \"react\";\n\nexport interface SerwistContextValues {\n serwist: Serwist | null;\n}\n\nexport const SerwistContext = createContext<SerwistContextValues>(null!);\n\nexport const useSerwist = () => {\n const context = useContext(SerwistContext);\n if (!context) {\n throw new Error(\"[useSerwist]: 'SerwistContext' is not available.\");\n }\n return context;\n};\n","import { Serwist } from \"@serwist/window\";\nimport { isCurrentPageOutOfScope } from \"@serwist/window/internal\";\nimport { type JSX, type ReactNode, useEffect, useState } from \"react\";\nimport { SerwistContext, useSerwist } from \"./lib/context.js\";\n\nexport interface SerwistProviderProps {\n swUrl: string;\n disable?: boolean;\n register?: boolean;\n cacheOnNavigation?: boolean;\n reloadOnOnline?: boolean;\n options?: RegistrationOptions;\n children?: ReactNode;\n}\n\ndeclare global {\n interface Window {\n serwist: Serwist;\n }\n}\n\n/**\n * `@serwist/window` provider for Next.js apps.\n * @param options\n * @returns\n */\nexport function SerwistProvider({\n swUrl,\n disable = false,\n register = true,\n cacheOnNavigation = true,\n reloadOnOnline = true,\n options,\n children,\n}: SerwistProviderProps): JSX.Element {\n const [serwist] = useState(() => {\n if (typeof window === \"undefined\") return null;\n if (disable) return null;\n const scope = options?.scope || \"/\";\n if (!(window.serwist && window.serwist instanceof Serwist) && \"serviceWorker\" in navigator) {\n window.serwist = new Serwist(swUrl, { ...options, scope, type: options?.type || \"module\" });\n if (register && !isCurrentPageOutOfScope(scope)) {\n void window.serwist.register();\n }\n }\n return window.serwist ?? null;\n });\n useEffect(() => {\n const cacheUrls = async (url?: string | URL | null | undefined) => {\n if (!window.navigator.onLine || !url) {\n return;\n }\n serwist?.messageSW({\n type: \"CACHE_URLS\",\n payload: { urlsToCache: [url] },\n });\n };\n const cacheCurrentPathname = () => cacheUrls(window.location.pathname);\n const pushState = history.pushState;\n const replaceState = history.replaceState;\n\n if (cacheOnNavigation) {\n history.pushState = (...args) => {\n pushState.apply(history, args);\n cacheUrls(args[2]);\n };\n history.replaceState = (...args) => {\n replaceState.apply(history, args);\n cacheUrls(args[2]);\n };\n window.addEventListener(\"online\", cacheCurrentPathname);\n }\n\n return () => {\n history.pushState = pushState;\n history.replaceState = replaceState;\n window.removeEventListener(\"online\", cacheCurrentPathname);\n };\n }, [serwist?.messageSW, cacheOnNavigation]);\n useEffect(() => {\n const reload = () => location.reload();\n if (reloadOnOnline) {\n window.addEventListener(\"online\", reload);\n }\n return () => {\n window.removeEventListener(\"online\", reload);\n };\n }, [reloadOnOnline]);\n return <SerwistContext.Provider value={{ serwist }}>{children}</SerwistContext.Provider>;\n}\n\nexport { useSerwist };\n"],"mappings":";;;;AAOA,MAAa,iBAAiB,cAAoC,KAAM;AAExE,MAAa,mBAAmB;CAC9B,MAAM,UAAU,WAAW,eAAe;AAC1C,KAAI,CAAC,QACH,OAAM,IAAI,MAAM,mDAAmD;AAErE,QAAO;;;;;;;;;ACYT,SAAgB,gBAAgB,EAC9B,OACA,UAAU,OACV,WAAW,MACX,oBAAoB,MACpB,iBAAiB,MACjB,SACA,YACoC;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G,SAAS,EAAE,eAAe"}
1
+ {"version":3,"file":"index.react.mjs","names":["Serwist","createContext","useContext","SerwistContextValues","serwist","SerwistContext","useSerwist","context","Error","Serwist","isCurrentPageOutOfScope","JSX","ReactNode","useEffect","useState","SerwistContext","useSerwist","SerwistProviderProps","swUrl","disable","register","cacheOnNavigation","reloadOnOnline","options","RegistrationOptions","children","global","Window","serwist","SerwistProvider","t0","$","_c","t1","t2","t3","t4","undefined","t5","window","scope","navigator","type","t6","cacheUrls","url","onLine","messageSW","payload","urlsToCache","cacheCurrentPathname","location","pathname","pushState","history","replaceState","t7","args","apply","t8","args_0","addEventListener","removeEventListener","t10","t9","reload","_temp","t11","t12"],"sources":["../src/lib/context.ts","../src/index.react.tsx"],"sourcesContent":["import type { Serwist } from \"@serwist/window\";\nimport { createContext, useContext } from \"react\";\n\nexport interface SerwistContextValues {\n serwist: Serwist | null;\n}\n\nexport const SerwistContext = createContext<SerwistContextValues>(null!);\n\nexport const useSerwist = () => {\n const context = useContext(SerwistContext);\n if (!context) {\n throw new Error(\"[useSerwist]: 'SerwistContext' is not available.\");\n }\n return context;\n};\n","import { Serwist } from \"@serwist/window\";\nimport { isCurrentPageOutOfScope } from \"@serwist/window/internal\";\nimport { type JSX, type ReactNode, useEffect, useState } from \"react\";\nimport { SerwistContext, useSerwist } from \"./lib/context.js\";\n\nexport interface SerwistProviderProps {\n swUrl: string;\n disable?: boolean;\n register?: boolean;\n cacheOnNavigation?: boolean;\n reloadOnOnline?: boolean;\n options?: RegistrationOptions;\n children?: ReactNode;\n}\n\ndeclare global {\n interface Window {\n serwist: Serwist;\n }\n}\n\n/**\n * `@serwist/window` provider for Next.js apps.\n * @param options\n * @returns\n */\nexport function SerwistProvider({\n swUrl,\n disable = false,\n register = true,\n cacheOnNavigation = true,\n reloadOnOnline = true,\n options,\n children,\n}: SerwistProviderProps): JSX.Element {\n const [serwist] = useState(() => {\n if (typeof window === \"undefined\") return null;\n if (disable) return null;\n const scope = options?.scope || \"/\";\n if (!(window.serwist && window.serwist instanceof Serwist) && \"serviceWorker\" in navigator) {\n window.serwist = new Serwist(swUrl, { ...options, scope, type: options?.type || \"module\" });\n if (register && !isCurrentPageOutOfScope(scope)) {\n void window.serwist.register();\n }\n }\n return window.serwist ?? null;\n });\n useEffect(() => {\n const cacheUrls = async (url?: string | URL | null | undefined) => {\n if (!window.navigator.onLine || !url) {\n return;\n }\n serwist?.messageSW({\n type: \"CACHE_URLS\",\n payload: { urlsToCache: [url] },\n });\n };\n const cacheCurrentPathname = () => cacheUrls(window.location.pathname);\n const pushState = history.pushState;\n const replaceState = history.replaceState;\n\n if (cacheOnNavigation) {\n history.pushState = (...args) => {\n pushState.apply(history, args);\n cacheUrls(args[2]);\n };\n history.replaceState = (...args) => {\n replaceState.apply(history, args);\n cacheUrls(args[2]);\n };\n window.addEventListener(\"online\", cacheCurrentPathname);\n }\n\n return () => {\n history.pushState = pushState;\n history.replaceState = replaceState;\n window.removeEventListener(\"online\", cacheCurrentPathname);\n };\n }, [serwist?.messageSW, cacheOnNavigation]);\n useEffect(() => {\n const reload = () => location.reload();\n if (reloadOnOnline) {\n window.addEventListener(\"online\", reload);\n }\n return () => {\n window.removeEventListener(\"online\", reload);\n };\n }, [reloadOnOnline]);\n return <SerwistContext.Provider value={{ serwist }}>{children}</SerwistContext.Provider>;\n}\n\nexport { useSerwist };\n"],"mappings":";;;;;;AAOA,MAAaK,iBAAiBJ,cAAoC,KAAM;AAExE,MAAaK,mBAAa;CACxB,MAAAC,UAAgBL,WAAWG,eAAe;AAC1C,KAAI,CAACE,QACH,OAAM,IAAIC,MAAM,mDAAmD;AACpE,QACMD;;;;;;;;;ACYT,SAAOsB,gBAAAC,IAAA;CAAA,MAAAC,IAAAC,EAAA,GAAA;CAAyB,MAAA,EAAAd,OAAAC,SAAAc,IAAAb,UAAAc,IAAAb,mBAAAc,IAAAb,gBAAAc,IAAAb,SAAAE,aAAAK;CAE9B,MAAAX,UAAAc,OAAAI,KAAAA,IAAA,QA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,IAAAqC;AAAA,KAAArC,EAAA,QAAAN,YAAAM,EAAA,QAAAoC,KAAA;AAA3CC,QAAA,oBAAA,eAAA,UAAA;GAAgC,OAAAD;GAAc1C;GAAmC,CAAA;AAAAM,IAAA,MAAAN;AAAAM,IAAA,MAAAoC;AAAApC,IAAA,MAAAqC;OAAAA,OAAArC,EAAA;AAAA,QAAjFqC;;AA9DF,SAAAF,QAAA;AAAA,QAsDkBf,SAAQc,QAAS"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.worker.mjs","names":[],"sources":["../src/index.worker.ts"],"sourcesContent":["import type { RuntimeCaching } from \"serwist\";\nimport { CacheFirst, ExpirationPlugin, NetworkFirst, NetworkOnly, RangeRequestsPlugin, StaleWhileRevalidate } from \"serwist\";\n\nexport const PAGES_CACHE_NAME = {\n rscPrefetch: \"pages-rsc-prefetch\",\n rsc: \"pages-rsc\",\n html: \"pages\",\n} as const;\n\n/**\n * The default, recommended list of caching strategies for applications\n * built with Next.js.\n *\n * @see https://serwist.pages.dev/docs/next/worker-exports#default-cache\n */\nexport const defaultCache: RuntimeCaching[] =\n process.env.NODE_ENV !== \"production\"\n ? [\n {\n matcher: /.*/i,\n handler: new NetworkOnly(),\n },\n ]\n : [\n {\n matcher: /^https:\\/\\/fonts\\.(?:gstatic)\\.com\\/.*/i,\n handler: new CacheFirst({\n cacheName: \"google-fonts-webfonts\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 4,\n maxAgeSeconds: 365 * 24 * 60 * 60, // 365 days\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n matcher: /^https:\\/\\/fonts\\.(?:googleapis)\\.com\\/.*/i,\n handler: new StaleWhileRevalidate({\n cacheName: \"google-fonts-stylesheets\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 4,\n maxAgeSeconds: 7 * 24 * 60 * 60, // 7 days\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n matcher: /\\.(?:eot|otf|ttc|ttf|woff|woff2|font.css)$/i,\n handler: new StaleWhileRevalidate({\n cacheName: \"static-font-assets\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 4,\n maxAgeSeconds: 7 * 24 * 60 * 60, // 7 days\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n matcher: /\\.(?:jpg|jpeg|gif|png|svg|ico|webp)$/i,\n handler: new StaleWhileRevalidate({\n cacheName: \"static-image-assets\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 64,\n maxAgeSeconds: 30 * 24 * 60 * 60, // 30 days\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n matcher: /\\/_next\\/static.+\\.js$/i,\n handler: new CacheFirst({\n cacheName: \"next-static-js-assets\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 64,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n matcher: /\\/_next\\/image\\?url=.+$/i,\n handler: new StaleWhileRevalidate({\n cacheName: \"next-image\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 64,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n matcher: /\\.(?:mp3|wav|ogg)$/i,\n handler: new CacheFirst({\n cacheName: \"static-audio-assets\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n maxAgeFrom: \"last-used\",\n }),\n new RangeRequestsPlugin(),\n ],\n }),\n },\n {\n matcher: /\\.(?:mp4|webm)$/i,\n handler: new CacheFirst({\n cacheName: \"static-video-assets\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n maxAgeFrom: \"last-used\",\n }),\n new RangeRequestsPlugin(),\n ],\n }),\n },\n {\n matcher: /\\.(?:js)$/i,\n handler: new StaleWhileRevalidate({\n cacheName: \"static-js-assets\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 48,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n matcher: /\\.(?:css|less)$/i,\n handler: new StaleWhileRevalidate({\n cacheName: \"static-style-assets\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n matcher: /\\/_next\\/data\\/.+\\/.+\\.json$/i,\n handler: new NetworkFirst({\n cacheName: \"next-data\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n matcher: /\\.(?:json|xml|csv)$/i,\n handler: new NetworkFirst({\n cacheName: \"static-data-assets\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n // Exclude /api/auth/* to fix auth callback\n // https://github.com/serwist/serwist/discussions/28\n matcher: /\\/api\\/auth\\/.*/,\n handler: new NetworkOnly({\n networkTimeoutSeconds: 10, // fallback to cache if API does not response within 10 seconds\n }),\n },\n {\n matcher: ({ sameOrigin, url: { pathname } }) => sameOrigin && pathname.startsWith(\"/api/\"),\n method: \"GET\",\n handler: new NetworkFirst({\n cacheName: \"apis\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 16,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n maxAgeFrom: \"last-used\",\n }),\n ],\n networkTimeoutSeconds: 10, // fallback to cache if API does not response within 10 seconds\n }),\n },\n {\n matcher: ({ request, url: { pathname }, sameOrigin }) =>\n request.headers.get(\"RSC\") === \"1\" && request.headers.get(\"Next-Router-Prefetch\") === \"1\" && sameOrigin && !pathname.startsWith(\"/api/\"),\n handler: new NetworkFirst({\n cacheName: PAGES_CACHE_NAME.rscPrefetch,\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n }),\n ],\n }),\n },\n {\n matcher: ({ request, url: { pathname }, sameOrigin }) => request.headers.get(\"RSC\") === \"1\" && sameOrigin && !pathname.startsWith(\"/api/\"),\n handler: new NetworkFirst({\n cacheName: PAGES_CACHE_NAME.rsc,\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n }),\n ],\n }),\n },\n {\n matcher: ({ request, url: { pathname }, sameOrigin }) =>\n request.headers.get(\"Content-Type\")?.includes(\"text/html\") && sameOrigin && !pathname.startsWith(\"/api/\"),\n handler: new NetworkFirst({\n cacheName: PAGES_CACHE_NAME.html,\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n }),\n ],\n }),\n },\n {\n matcher: ({ url: { pathname }, sameOrigin }) => sameOrigin && !pathname.startsWith(\"/api/\"),\n handler: new NetworkFirst({\n cacheName: \"others\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n }),\n ],\n }),\n },\n {\n matcher: ({ sameOrigin }) => !sameOrigin,\n handler: new NetworkFirst({\n cacheName: \"cross-origin\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 60 * 60, // 1 hour\n }),\n ],\n networkTimeoutSeconds: 10,\n }),\n },\n {\n matcher: /.*/i,\n method: \"GET\",\n handler: new NetworkOnly(),\n },\n ];\n"],"mappings":";;AAGA,MAAa,mBAAmB;CAC9B,aAAa;CACb,KAAK;CACL,MAAM;CACP;;;;;;;AAQD,MAAa,eACX,QAAQ,IAAI,aAAa,eACrB,CACE;CACE,SAAS;CACT,SAAS,IAAI,aAAa;CAC3B,CACF,GACD;CACE;EACE,SAAS;EACT,SAAS,IAAI,WAAW;GACtB,WAA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IAC1B,CAAC,CACH;GACF,CAAC;EACH;CACD;EACE,UAAU,EAAE,SAAS,KAAK,EAAE,YAAY,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,KAAK,OAAO,cAAc,CAAC,SAAS,WAAW,QAAQ;EAC1I,SAAS,IAAI,aAAa;GACxB,WAAW,iBAAiB;GAC5B,SAAS,CACP,IAAI,iBAAiB;IACnB,YAAY;IACZ,eAAe,OAAU;IAC1B,CAAC,CACH;GACF,CAAC;EACH;CACD;EACE,UAAU,EAAE,SAAS,KAAK,EAAE,YAAY,iBACtC,QAAQ,QAAQ,IAAI,eAAe,EAAE,SAAS,YAAY,IAAI,cAAc,CAAC,SAAS,WAAW,QAAQ;EAC3G,SAAS,IAAI,aAAa;GACxB,WAAW,iBAAiB;GAC5B,SAAS,CACP,IAAI,iBAAiB;IACnB,YAAY;IACZ,eAAe,OAAU;IAC1B,CAAC,CACH;GACF,CAAC;EACH;CACD;EACE,UAAU,EAAE,KAAK,EAAE,YAAY,iBAAiB,cAAc,CAAC,SAAS,WAAW,QAAQ;EAC3F,SAAS,IAAI,aAAa;GACxB,WAAW;GACX,SAAS,CACP,IAAI,iBAAiB;IACnB,YAAY;IACZ,eAAe,OAAU;IAC1B,CAAC,CACH;GACF,CAAC;EACH;CACD;EACE,UAAU,EAAE,iBAAiB,CAAC;EAC9B,SAAS,IAAI,aAAa;GACxB,WAAW;GACX,SAAS,CACP,IAAI,iBAAiB;IACnB,YAAY;IACZ,eAAe;IAChB,CAAC,CACH;GACD,uBAAuB;GACxB,CAAC;EACH;CACD;EACE,SAAS;EACT,QAAQ;EACR,SAAS,IAAI,aAAa;EAC3B;CACF"}
1
+ {"version":3,"file":"index.worker.mjs","names":["RuntimeCaching","CacheFirst","ExpirationPlugin","NetworkFirst","NetworkOnly","RangeRequestsPlugin","StaleWhileRevalidate","PAGES_CACHE_NAME","rscPrefetch","rsc","html","const","defaultCache","process","env","NODE_ENV","matcher","handler","cacheName","plugins","maxEntries","maxAgeSeconds","maxAgeFrom","networkTimeoutSeconds","sameOrigin","url","pathname","startsWith","method","request","headers","get","includes"],"sources":["../src/index.worker.ts"],"sourcesContent":["import type { RuntimeCaching } from \"serwist\";\nimport { CacheFirst, ExpirationPlugin, NetworkFirst, NetworkOnly, RangeRequestsPlugin, StaleWhileRevalidate } from \"serwist\";\n\nexport const PAGES_CACHE_NAME = {\n rscPrefetch: \"pages-rsc-prefetch\",\n rsc: \"pages-rsc\",\n html: \"pages\",\n} as const;\n\n/**\n * The default, recommended list of caching strategies for applications\n * built with Next.js.\n *\n * @see https://serwist.pages.dev/docs/next/worker-exports#default-cache\n */\nexport const defaultCache: RuntimeCaching[] =\n process.env.NODE_ENV !== \"production\"\n ? [\n {\n matcher: /.*/i,\n handler: new NetworkOnly(),\n },\n ]\n : [\n {\n matcher: /^https:\\/\\/fonts\\.(?:gstatic)\\.com\\/.*/i,\n handler: new CacheFirst({\n cacheName: \"google-fonts-webfonts\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 4,\n maxAgeSeconds: 365 * 24 * 60 * 60, // 365 days\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n matcher: /^https:\\/\\/fonts\\.(?:googleapis)\\.com\\/.*/i,\n handler: new StaleWhileRevalidate({\n cacheName: \"google-fonts-stylesheets\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 4,\n maxAgeSeconds: 7 * 24 * 60 * 60, // 7 days\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n matcher: /\\.(?:eot|otf|ttc|ttf|woff|woff2|font.css)$/i,\n handler: new StaleWhileRevalidate({\n cacheName: \"static-font-assets\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 4,\n maxAgeSeconds: 7 * 24 * 60 * 60, // 7 days\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n matcher: /\\.(?:jpg|jpeg|gif|png|svg|ico|webp)$/i,\n handler: new StaleWhileRevalidate({\n cacheName: \"static-image-assets\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 64,\n maxAgeSeconds: 30 * 24 * 60 * 60, // 30 days\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n matcher: /\\/_next\\/static.+\\.js$/i,\n handler: new CacheFirst({\n cacheName: \"next-static-js-assets\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 64,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n matcher: /\\/_next\\/image\\?url=.+$/i,\n handler: new StaleWhileRevalidate({\n cacheName: \"next-image\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 64,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n matcher: /\\.(?:mp3|wav|ogg)$/i,\n handler: new CacheFirst({\n cacheName: \"static-audio-assets\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n maxAgeFrom: \"last-used\",\n }),\n new RangeRequestsPlugin(),\n ],\n }),\n },\n {\n matcher: /\\.(?:mp4|webm)$/i,\n handler: new CacheFirst({\n cacheName: \"static-video-assets\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n maxAgeFrom: \"last-used\",\n }),\n new RangeRequestsPlugin(),\n ],\n }),\n },\n {\n matcher: /\\.(?:js)$/i,\n handler: new StaleWhileRevalidate({\n cacheName: \"static-js-assets\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 48,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n matcher: /\\.(?:css|less)$/i,\n handler: new StaleWhileRevalidate({\n cacheName: \"static-style-assets\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n matcher: /\\/_next\\/data\\/.+\\/.+\\.json$/i,\n handler: new NetworkFirst({\n cacheName: \"next-data\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n matcher: /\\.(?:json|xml|csv)$/i,\n handler: new NetworkFirst({\n cacheName: \"static-data-assets\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n maxAgeFrom: \"last-used\",\n }),\n ],\n }),\n },\n {\n // Exclude /api/auth/* to fix auth callback\n // https://github.com/serwist/serwist/discussions/28\n matcher: /\\/api\\/auth\\/.*/,\n handler: new NetworkOnly({\n networkTimeoutSeconds: 10, // fallback to cache if API does not response within 10 seconds\n }),\n },\n {\n matcher: ({ sameOrigin, url: { pathname } }) => sameOrigin && pathname.startsWith(\"/api/\"),\n method: \"GET\",\n handler: new NetworkFirst({\n cacheName: \"apis\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 16,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n maxAgeFrom: \"last-used\",\n }),\n ],\n networkTimeoutSeconds: 10, // fallback to cache if API does not response within 10 seconds\n }),\n },\n {\n matcher: ({ request, url: { pathname }, sameOrigin }) =>\n request.headers.get(\"RSC\") === \"1\" && request.headers.get(\"Next-Router-Prefetch\") === \"1\" && sameOrigin && !pathname.startsWith(\"/api/\"),\n handler: new NetworkFirst({\n cacheName: PAGES_CACHE_NAME.rscPrefetch,\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n }),\n ],\n }),\n },\n {\n matcher: ({ request, url: { pathname }, sameOrigin }) => request.headers.get(\"RSC\") === \"1\" && sameOrigin && !pathname.startsWith(\"/api/\"),\n handler: new NetworkFirst({\n cacheName: PAGES_CACHE_NAME.rsc,\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n }),\n ],\n }),\n },\n {\n matcher: ({ request, url: { pathname }, sameOrigin }) =>\n request.headers.get(\"Content-Type\")?.includes(\"text/html\") && sameOrigin && !pathname.startsWith(\"/api/\"),\n handler: new NetworkFirst({\n cacheName: PAGES_CACHE_NAME.html,\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n }),\n ],\n }),\n },\n {\n matcher: ({ url: { pathname }, sameOrigin }) => sameOrigin && !pathname.startsWith(\"/api/\"),\n handler: new NetworkFirst({\n cacheName: \"others\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 24 * 60 * 60, // 24 hours\n }),\n ],\n }),\n },\n {\n matcher: ({ sameOrigin }) => !sameOrigin,\n handler: new NetworkFirst({\n cacheName: \"cross-origin\",\n plugins: [\n new ExpirationPlugin({\n maxEntries: 32,\n maxAgeSeconds: 60 * 60, // 1 hour\n }),\n ],\n networkTimeoutSeconds: 10,\n }),\n },\n {\n matcher: /.*/i,\n method: \"GET\",\n handler: new NetworkOnly(),\n },\n ];\n"],"mappings":";;AAGA,MAAaO,mBAAmB;CAC9BC,aAAa;CACbC,KAAK;CACLC,MAAM;CACP;;;;;;;AAQD,MAAaE,eACXC,QAAQC,IAAIC,aAAa,eACrB,CACE;CACEC,SAAS;CACTC,SAAS,IAAIb,aAAY;CAC1B,CACF,GACD;CACE;EACEY,SAAS;EACTC,SAAS,IAAIhB,WAAW;GACtBiB,WAAW;GACXC,SAAS,CACP,IAAIjB,iBAAiB;IACnBkB,YAAY;IACZC,eAAe,MAAM,KAAK,KAAK;IAC/BC,YAAY;IACb,CAAC,CAAA;GAEL,CAAA;EACF;CACD;EACEN,SAAS;EACTC,SAAS,IAAIX,qBAAqB;GAChCY,WAAW;GACXC,SAAS,CACP,IAAIjB,iBAAiB;IACnBkB,YAAY;IACZC,eAAe,QA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AAA;EACF;CACD;EACEL,UAAU,EAAEa,SAASJ,KAAK,EAAEC,YAAYF,iBAAiBK,QAAQC,QAAQC,IAAI,MAAM,KAAK,OAAOP,cAAc,CAACE,SAASC,WAAW,QAAQ;EAC1IV,SAAS,IAAId,aAAa;GACxBe,WAAWX,iBAAiBE;GAC5BU,SAAS,CACP,IAAIjB,iBAAiB;IACnBkB,YAAY;IACZC,eAAe,OAAU;IAC1B,CAAC,CAAA;GAEL,CAAA;EACF;CACD;EACEL,UAAU,EAAEa,SAASJ,KAAK,EAAEC,YAAYF,iBACtCK,QAAQC,QAAQC,IAAI,eAAe,EAAEC,SAAS,YAAY,IAAIR,cAAc,CAACE,SAASC,WAAW,QAAQ;EAC3GV,SAAS,IAAId,aAAa;GACxBe,WAAWX,iBAAiBG;GAC5BS,SAAS,CACP,IAAIjB,iBAAiB;IACnBkB,YAAY;IACZC,eAAe,OAAU;IAC1B,CAAC,CAAA;GAEL,CAAA;EACF;CACD;EACEL,UAAU,EAAES,KAAK,EAAEC,YAAYF,iBAAiBA,cAAc,CAACE,SAASC,WAAW,QAAQ;EAC3FV,SAAS,IAAId,aAAa;GACxBe,WAAW;GACXC,SAAS,CACP,IAAIjB,iBAAiB;IACnBkB,YAAY;IACZC,eAAe,OAAU;IAC1B,CAAC,CAAA;GAEL,CAAA;EACF;CACD;EACEL,UAAU,EAAEQ,iBAAiB,CAACA;EAC9BP,SAAS,IAAId,aAAa;GACxBe,WAAW;GACXC,SAAS,CACP,IAAIjB,iBAAiB;IACnBkB,YAAY;IACZC,eAAe;IAChB,CAAC,CACH;GACDE,uBAAuB;GACxB,CAAA;EACF;CACD;EACEP,SAAS;EACTY,QAAQ;EACRX,SAAS,IAAIb,aAAY;EAC1B;CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"sw-entry-worker.mjs","names":[],"sources":["../src/sw-entry-worker.ts"],"sourcesContent":["declare const self: WorkerGlobalScope & typeof globalThis;\n\nexport type MessageType =\n | {\n type: \"__FRONTEND_NAV_CACHE__\";\n url: URL | string;\n }\n | {\n type: \"__START_URL_CACHE__\";\n url: URL | string;\n };\n\nself.onmessage = async (ev: MessageEvent<MessageType>) => {\n switch (ev.data.type) {\n case \"__START_URL_CACHE__\": {\n const url = ev.data.url;\n const response = await fetch(url);\n if (!response.redirected) {\n const startUrlCache = await caches.open(\"start-url\");\n return startUrlCache.put(url, response);\n }\n return Promise.resolve();\n }\n case \"__FRONTEND_NAV_CACHE__\": {\n const url = ev.data.url;\n const pagesCache = await caches.open(\"pages\");\n\n const isPageCached = !!(await pagesCache.match(url, {\n ignoreSearch: true,\n }));\n if (isPageCached) {\n return;\n }\n\n const page = await fetch(url);\n if (!page.ok) {\n return;\n }\n pagesCache.put(url, page.clone());\n\n return Promise.resolve();\n }\n default:\n return Promise.resolve();\n }\n};\n"],"mappings":";AAYA,KAAK,YAAY,OAAO,OAAkC;AACxD,SAAQ,GAAG,KAAK,MAAhB;EACE,KAAK,uBAAuB;GAC1B,MAAM,MAAM,GAAG,KAAK;GACpB,MAAM,WAAW,MAAM,MAAM,IAAI;AACjC,OAAI,CAAC,SAAS,WAEZ,SAAO,MADqB,OAAO,KAAK,YAAY,EAC/B,IAAI,KAAK,SAAS;AAEzC,UAAO,QAAQ,SAAS;;EAE1B,KAAK,0BAA0B;GAC7B,MAAM,MAAM,GAAG,KAAK;GACpB,MAAM,aAAa,MAAM,OAAO,KAAK,QAAQ;AAK7C,OAAI,CAHkB,CAAE,MAAM,WAAW,MAAM,KAAK,EAClD,cAAc,MACf,CAAC,CAEA;GAGF,MAAM,OAAO,MAAM,MAAM,IAAI;AAC7B,OAAI,CAAC,KAAK,GACR;AAEF,cAAW,IAAI,KAAK,KAAK,OAAO,CAAC;AAEjC,UAAO,QAAQ,SAAS;;EAE1B,QACE,QAAO,QAAQ,SAAS"}
1
+ {"version":3,"file":"sw-entry-worker.mjs","names":["self","WorkerGlobalScope","globalThis","MessageType","type","url","URL","onmessage","ev","MessageEvent","data","response","fetch","redirected","startUrlCache","caches","open","put","Promise","resolve","pagesCache","isPageCached","match","ignoreSearch","page","ok","clone"],"sources":["../src/sw-entry-worker.ts"],"sourcesContent":["declare const self: WorkerGlobalScope & typeof globalThis;\n\nexport type MessageType =\n | {\n type: \"__FRONTEND_NAV_CACHE__\";\n url: URL | string;\n }\n | {\n type: \"__START_URL_CACHE__\";\n url: URL | string;\n };\n\nself.onmessage = async (ev: MessageEvent<MessageType>) => {\n switch (ev.data.type) {\n case \"__START_URL_CACHE__\": {\n const url = ev.data.url;\n const response = await fetch(url);\n if (!response.redirected) {\n const startUrlCache = await caches.open(\"start-url\");\n return startUrlCache.put(url, response);\n }\n return Promise.resolve();\n }\n case \"__FRONTEND_NAV_CACHE__\": {\n const url = ev.data.url;\n const pagesCache = await caches.open(\"pages\");\n\n const isPageCached = !!(await pagesCache.match(url, {\n ignoreSearch: true,\n }));\n if (isPageCached) {\n return;\n }\n\n const page = await fetch(url);\n if (!page.ok) {\n return;\n }\n pagesCache.put(url, page.clone());\n\n return Promise.resolve();\n }\n default:\n return Promise.resolve();\n }\n};\n"],"mappings":";AAYAA,KAAKO,YAAY,OAAOC,OAAkC;AACxD,SAAQA,GAAGE,KAAKN,MAAhB;EACE,KAAK,uBAAuB;GAC1B,MAAMC,MAAMG,GAAGE,KAAKL;GACpB,MAAMM,WAAW,MAAMC,MAAMP,IAAI;AACjC,OAAI,CAACM,SAASE,WAEZ,SAAOC,MADqBC,OAAOC,KAAK,YAAY,EAC/BC,IAAIZ,KAAKM,SAAS;AAEzC,UAAOO,QAAQC,SAAS;;EAE1B,KAAK,0BAA0B;GAC7B,MAAMd,MAAMG,GAAGE,KAAKL;GACpB,MAAMe,aAAa,MAAML,OAAOC,KAAK,QAAQ;AAK7C,OAAIK,CAHkB,CAAE,MAAMD,WAAWE,MAAMjB,KAAK,EAClDkB,cAAc,MACf,CAAC,CAEA;GAGF,MAAMC,OAAO,MAAMZ,MAAMP,IAAI;AAC7B,OAAI,CAACmB,KAAKC,GACR;AAEFL,cAAWH,IAAIZ,KAAKmB,KAAKE,OAAO,CAAC;AAEjC,UAAOR,QAAQC,SAAS;;EAE1B,QACE,QAAOD,QAAQC,SAAS"}
@@ -1 +1 @@
1
- {"version":3,"file":"sw-entry.mjs","names":[],"sources":["../src/sw-entry.ts"],"sourcesContent":["import { Serwist } from \"@serwist/window\";\nimport { isCurrentPageOutOfScope } from \"@serwist/window/internal\";\n\nimport type { SerwistNextOptions } from \"./internal-types.js\";\nimport type { MessageType } from \"./sw-entry-worker.js\";\n\ndeclare global {\n interface Window {\n serwist: Serwist;\n }\n}\ndeclare const self: Window &\n typeof globalThis & {\n // Do not dereference this, use its attributes directly or assign them to other variables.\n // You should do the latter if you use an attribute multiple times.\n __SERWIST_SW_ENTRY: SerwistNextOptions;\n };\n\nif (typeof window !== \"undefined\" && \"serviceWorker\" in navigator && typeof caches !== \"undefined\") {\n const scope = self.__SERWIST_SW_ENTRY.scope;\n\n let swEntryWorker: Worker | undefined;\n\n if (self.__SERWIST_SW_ENTRY.swEntryWorker) {\n swEntryWorker = new Worker(self.__SERWIST_SW_ENTRY.swEntryWorker);\n }\n\n window.serwist = new Serwist(window.location.origin + self.__SERWIST_SW_ENTRY.sw, { scope });\n\n if (self.__SERWIST_SW_ENTRY.register && !isCurrentPageOutOfScope(scope)) {\n window.serwist.register();\n }\n\n if (self.__SERWIST_SW_ENTRY.cacheOnNavigation) {\n const cacheOnNavigation = async (url?: string | URL | null | undefined) => {\n if (!window.navigator.onLine || !url) {\n return;\n }\n swEntryWorker?.postMessage({\n type: \"__FRONTEND_NAV_CACHE__\",\n url,\n } satisfies MessageType);\n };\n\n const pushState = history.pushState;\n history.pushState = (...args) => {\n pushState.apply(history, args);\n cacheOnNavigation(args[2]);\n };\n\n const replaceState = history.replaceState;\n history.replaceState = (...args) => {\n replaceState.apply(history, args);\n cacheOnNavigation(args[2]);\n };\n\n window.addEventListener(\"online\", () => {\n cacheOnNavigation(window.location.pathname);\n });\n }\n\n if (self.__SERWIST_SW_ENTRY.reloadOnOnline) {\n window.addEventListener(\"online\", () => location.reload());\n }\n}\n"],"mappings":";;;AAkBA,IAAI,OAAO,WAAW,eAAe,mBAAmB,aAAa,OAAO,WAAW,aAAa;CAClG,MAAM,QAAQ,KAAK,mBAAmB;CAEtC,IAAI;AAEJ,KAAI,KAAK,mBAAmB,cAC1B,iBAAgB,IAAI,OAAO,KAAK,mBAAmB,cAAc;AAGnE,QAAO,UAAU,IAAI,QAAQ,OAAO,SAAS,SAAS,KAAK,mBAAmB,IAAI,EAAE,OAAO,CAAC;AAE5F,KAAI,KAAK,mBAAmB,YAAY,CAAC,wBAAwB,MAAM,CACrE,QAAO,QAAQ,UAAU;AAG3B,KAAI,KAAK,mBAAmB,mBAAmB;EAC7C,MAAM,oBAAoB,OAAO,QAA0C;AACzE,OAAI,CAAC,OAAO,UAAU,UAAU,CAAC,IAC/B;AAEF,kBAAe,YAAY;IACzB,MAAM;IACN;IACD,CAAuB;;EAG1B,MAAM,YAAY,QAAQ;AAC1B,UAAQ,aAAa,GAAG,SAAS;AAC/B,aAAU,MAAM,SAAS,KAAK;AAC9B,qBAAkB,KAAK,GAAG;;EAG5B,MAAM,eAAe,QAAQ;AAC7B,UAAQ,gBAAgB,GAAG,SAAS;AAClC,gBAAa,MAAM,SAAS,KAAK;AACjC,qBAAkB,KAAK,GAAG;;AAG5B,SAAO,iBAAiB,gBAAgB;AACtC,qBAAkB,OAAO,SAAS,SAAS;IAC3C;;AAGJ,KAAI,KAAK,mBAAmB,eAC1B,QAAO,iBAAiB,gBAAgB,SAAS,QAAQ,CAAC"}
1
+ {"version":3,"file":"sw-entry.mjs","names":["Serwist","isCurrentPageOutOfScope","SerwistNextOptions","MessageType","global","Window","serwist","self","globalThis","__SERWIST_SW_ENTRY","window","navigator","caches","scope","swEntryWorker","Worker","location","origin","sw","register","cacheOnNavigation","url","URL","onLine","postMessage","type","pushState","history","args","apply","replaceState","addEventListener","pathname","reloadOnOnline","reload"],"sources":["../src/sw-entry.ts"],"sourcesContent":["import { Serwist } from \"@serwist/window\";\nimport { isCurrentPageOutOfScope } from \"@serwist/window/internal\";\n\nimport type { SerwistNextOptions } from \"./internal-types.js\";\nimport type { MessageType } from \"./sw-entry-worker.js\";\n\ndeclare global {\n interface Window {\n serwist: Serwist;\n }\n}\ndeclare const self: Window &\n typeof globalThis & {\n // Do not dereference this, use its attributes directly or assign them to other variables.\n // You should do the latter if you use an attribute multiple times.\n __SERWIST_SW_ENTRY: SerwistNextOptions;\n };\n\nif (typeof window !== \"undefined\" && \"serviceWorker\" in navigator && typeof caches !== \"undefined\") {\n const scope = self.__SERWIST_SW_ENTRY.scope;\n\n let swEntryWorker: Worker | undefined;\n\n if (self.__SERWIST_SW_ENTRY.swEntryWorker) {\n swEntryWorker = new Worker(self.__SERWIST_SW_ENTRY.swEntryWorker);\n }\n\n window.serwist = new Serwist(window.location.origin + self.__SERWIST_SW_ENTRY.sw, { scope });\n\n if (self.__SERWIST_SW_ENTRY.register && !isCurrentPageOutOfScope(scope)) {\n window.serwist.register();\n }\n\n if (self.__SERWIST_SW_ENTRY.cacheOnNavigation) {\n const cacheOnNavigation = async (url?: string | URL | null | undefined) => {\n if (!window.navigator.onLine || !url) {\n return;\n }\n swEntryWorker?.postMessage({\n type: \"__FRONTEND_NAV_CACHE__\",\n url,\n } satisfies MessageType);\n };\n\n const pushState = history.pushState;\n history.pushState = (...args) => {\n pushState.apply(history, args);\n cacheOnNavigation(args[2]);\n };\n\n const replaceState = history.replaceState;\n history.replaceState = (...args) => {\n replaceState.apply(history, args);\n cacheOnNavigation(args[2]);\n };\n\n window.addEventListener(\"online\", () => {\n cacheOnNavigation(window.location.pathname);\n });\n }\n\n if (self.__SERWIST_SW_ENTRY.reloadOnOnline) {\n window.addEventListener(\"online\", () => location.reload());\n }\n}\n"],"mappings":";;;AAkBA,IAAI,OAAOU,WAAW,eAAe,mBAAmBC,aAAa,OAAOC,WAAW,aAAa;CAClG,MAAMC,QAAQN,KAAKE,mBAAmBI;CAEtC,IAAIC;AAEJ,KAAIP,KAAKE,mBAAmBK,cAC1BA,iBAAgB,IAAIC,OAAOR,KAAKE,mBAAmBK,cAAc;AAGnEJ,QAAOJ,UAAU,IAAIN,QAAQU,OAAOM,SAASC,SAASV,KAAKE,mBAAmBS,IAAI,EAAEL,OAAO,CAAC;AAE5F,KAAIN,KAAKE,mBAAmBU,YAAY,CAAClB,wBAAwBY,MAAM,CACrEH,QAAOJ,QAAQa,UAAU;AAG3B,KAAIZ,KAAKE,mBAAmBW,mBAAmB;EAC7C,MAAMA,oBAAoB,OAAOC,QAA0C;AACzE,OAAI,CAACX,OAAOC,UAAUY,UAAU,CAACF,IAC/B;AAEFP,kBAAeU,YAAY;IACzBC,MAAM;IACNJ;IACD,CAAuB;;EAG1B,MAAMK,YAAYC,QAAQD;AAC1BC,UAAQD,aAAa,GAAGE,SAAS;AAC/BF,aAAUG,MAAMF,SAASC,KAAK;AAC9BR,qBAAkBQ,KAAK,GAAG;;EAG5B,MAAME,eAAeH,QAAQG;AAC7BH,UAAQG,gBAAgB,GAAGF,SAAS;AAClCE,gBAAaD,MAAMF,SAASC,KAAK;AACjCR,qBAAkBQ,KAAK,GAAG;;AAG5BlB,SAAOqB,iBAAiB,gBAAgB;AACtCX,qBAAkBV,OAAOM,SAASgB,SAAS;IAC3C;;AAGJ,KAAIzB,KAAKE,mBAAmBwB,eAC1BvB,QAAOqB,iBAAiB,gBAAgBf,SAASkB,QAAQ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@serwist/next",
3
- "version": "9.5.8",
3
+ "version": "9.5.10",
4
4
  "type": "module",
5
5
  "description": "A module that integrates Serwist into your Next.js application.",
6
6
  "files": [
@@ -77,20 +77,23 @@
77
77
  },
78
78
  "dependencies": {
79
79
  "browserslist": "4.28.2",
80
- "glob": "10.5.0",
80
+ "glob": "13.0.6",
81
81
  "kolorist": "1.8.0",
82
82
  "semver": "7.7.4",
83
- "zod": "4.3.6",
84
- "@serwist/build": "9.5.8",
85
- "@serwist/utils": "9.5.8",
86
- "@serwist/webpack-plugin": "9.5.8",
87
- "@serwist/window": "9.5.8",
88
- "serwist": "9.5.8"
83
+ "zod": "4.4.1",
84
+ "@serwist/build": "9.5.10",
85
+ "@serwist/utils": "9.5.10",
86
+ "@serwist/webpack-plugin": "9.5.10",
87
+ "@serwist/window": "9.5.10",
88
+ "serwist": "9.5.10"
89
89
  },
90
90
  "devDependencies": {
91
+ "@rolldown/plugin-babel": "0.2.3",
91
92
  "@types/node": "25.6.0",
92
93
  "@types/react": "19.2.14",
93
94
  "@types/semver": "7.7.1",
95
+ "@vitejs/plugin-react": "6.0.1",
96
+ "babel-plugin-react-compiler": "1.0.0",
94
97
  "next": "16.2.4",
95
98
  "react": "19.2.5",
96
99
  "react-dom": "19.2.5",
@@ -98,13 +101,13 @@
98
101
  "type-fest": "5.6.0",
99
102
  "typescript": "6.0.3",
100
103
  "webpack": "5.106.2",
101
- "@serwist/cli": "9.5.8"
104
+ "@serwist/cli": "9.5.10"
102
105
  },
103
106
  "peerDependencies": {
104
107
  "next": ">=14.0.0",
105
108
  "react": ">=18.0.0",
106
109
  "typescript": ">=5.0.0",
107
- "@serwist/cli": "^9.5.8"
110
+ "@serwist/cli": "^9.5.10"
108
111
  },
109
112
  "peerDependenciesMeta": {
110
113
  "@serwist/cli": {