@onruntime/next-sitemap 0.6.2 → 0.8.0

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.
package/dist/index.cjs CHANGED
@@ -1,5 +1,204 @@
1
1
  'use strict';
2
2
 
3
+ var fs = require('fs');
4
+ var path = require('path');
5
+ var childProcess = require('child_process');
6
+ var url = require('url');
7
+
8
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
9
+ function _interopNamespace(e) {
10
+ if (e && e.__esModule) return e;
11
+ var n = Object.create(null);
12
+ if (e) {
13
+ Object.keys(e).forEach(function (k) {
14
+ if (k !== 'default') {
15
+ var d = Object.getOwnPropertyDescriptor(e, k);
16
+ Object.defineProperty(n, k, d.get ? d : {
17
+ enumerable: true,
18
+ get: function () { return e[k]; }
19
+ });
20
+ }
21
+ });
22
+ }
23
+ n.default = e;
24
+ return Object.freeze(n);
25
+ }
26
+
27
+ var childProcess__namespace = /*#__PURE__*/_interopNamespace(childProcess);
28
+
29
+ // src/shared.ts
30
+ var JS_EXTENSIONS = /* @__PURE__ */ new Set([
31
+ ".js",
32
+ ".cjs",
33
+ ".mjs",
34
+ ".jsx",
35
+ ".ts",
36
+ ".cts",
37
+ ".mts",
38
+ ".tsx",
39
+ ".json",
40
+ ".node"
41
+ ]);
42
+ var NO_STATIC_PARAMS = "NO_STATIC_PARAMS";
43
+ var spawnProcess = childProcess__namespace.spawn;
44
+ var __dirname$1 = path.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));
45
+ var paramsCache = /* @__PURE__ */ new Map();
46
+ var isDev = process.env.NODE_ENV === "development";
47
+ async function executeWorker(directory, fileKey, debug) {
48
+ const absolutePath = path.join(directory, fileKey.replace("./", ""));
49
+ const projectRoot = process.cwd();
50
+ const distRoot = path.join(__dirname$1, "..");
51
+ const workerPath = path.join(distRoot, "worker.cjs");
52
+ const loaderPath = path.join(distRoot, "loader.js");
53
+ if (debug) {
54
+ console.log(`[next-sitemap] Worker path: ${workerPath}`);
55
+ console.log(`[next-sitemap] Worker exists: ${fs.existsSync(workerPath)}`);
56
+ console.log(`[next-sitemap] Loader path: ${loaderPath}`);
57
+ console.log(`[next-sitemap] Loader exists: ${fs.existsSync(loaderPath)}`);
58
+ }
59
+ return new Promise((resolve) => {
60
+ const nodePath = [
61
+ path.join(projectRoot, "node_modules"),
62
+ path.join(__dirname$1, "..", "node_modules")
63
+ ].join(path.delimiter);
64
+ const importFlag = ["--import", loaderPath];
65
+ const args = [...importFlag, workerPath, absolutePath, projectRoot];
66
+ const child = spawnProcess("node", args, {
67
+ cwd: projectRoot,
68
+ stdio: ["ignore", "pipe", "pipe"],
69
+ env: { ...process.env, NODE_PATH: nodePath }
70
+ });
71
+ let stdout = "";
72
+ let stderr = "";
73
+ child.stdout.on("data", (data) => {
74
+ stdout += data.toString();
75
+ });
76
+ child.stderr.on("data", (data) => {
77
+ stderr += data.toString();
78
+ });
79
+ child.on("close", (code) => {
80
+ if (debug && stderr) {
81
+ console.warn(`[next-sitemap] Worker stderr: ${stderr}`);
82
+ }
83
+ if (code !== 0 && code !== null) {
84
+ if (debug) console.warn(`[next-sitemap] Worker exited with code ${code}`);
85
+ resolve(null);
86
+ return;
87
+ }
88
+ try {
89
+ const lines = stdout.trim().split("\n");
90
+ const result = JSON.parse(lines[lines.length - 1]);
91
+ if (result.success) {
92
+ resolve(result.params);
93
+ } else {
94
+ if (result.error !== NO_STATIC_PARAMS && debug) {
95
+ console.warn(`[next-sitemap] Worker error: ${result.error}`);
96
+ }
97
+ resolve(null);
98
+ }
99
+ } catch {
100
+ if (debug) console.warn(`[next-sitemap] Failed to parse worker output: ${stdout}`);
101
+ resolve(null);
102
+ }
103
+ });
104
+ child.on("error", (err) => {
105
+ if (debug) console.warn(`[next-sitemap] Failed to spawn worker: ${err.message}`);
106
+ resolve(null);
107
+ });
108
+ });
109
+ }
110
+ async function getRouteParams(route, directory, debug) {
111
+ const cacheKey = route.fileKey;
112
+ if (paramsCache.has(cacheKey)) {
113
+ return paramsCache.get(cacheKey);
114
+ }
115
+ if (debug) {
116
+ console.log(`[next-sitemap] ${route.pathname}: executing static params via worker`);
117
+ }
118
+ const params = await executeWorker(directory, route.fileKey, debug);
119
+ paramsCache.set(cacheKey, params);
120
+ if (debug && params) {
121
+ console.log(`[next-sitemap] ${route.pathname}: got ${params.length} params`);
122
+ }
123
+ return params;
124
+ }
125
+ async function generateAllPaths(routes, directory, debug) {
126
+ const staticPaths = ["/"];
127
+ const dynamicRoutes = [];
128
+ for (const route of routes) {
129
+ if (route.dynamicSegments.length === 0) {
130
+ if (route.pathname !== "/") {
131
+ staticPaths.push(route.pathname);
132
+ }
133
+ } else {
134
+ dynamicRoutes.push(route);
135
+ }
136
+ }
137
+ const startTime = isDev ? Date.now() : 0;
138
+ if (isDev && dynamicRoutes.length > 0) {
139
+ console.log(`[next-sitemap] Generating sitemap for ${dynamicRoutes.length} dynamic routes (dev only, instant in production)...`);
140
+ }
141
+ const dynamicResults = await Promise.all(
142
+ dynamicRoutes.map(async (route) => {
143
+ const params = await getRouteParams(route, directory, debug);
144
+ if (!params || params.length === 0) {
145
+ if (debug) {
146
+ console.warn(`[next-sitemap] Skipping dynamic route ${route.pathname}: no static params or empty result.`);
147
+ }
148
+ return [];
149
+ }
150
+ const paths = [];
151
+ for (const param of params) {
152
+ let path = route.pathname;
153
+ let valid = true;
154
+ for (const segment of route.dynamicSegments) {
155
+ const value = param[segment];
156
+ if (value === void 0) {
157
+ if (debug) {
158
+ console.warn(`[next-sitemap] ${route.pathname}: missing param "${segment}" in`, param);
159
+ }
160
+ valid = false;
161
+ break;
162
+ }
163
+ path = path.replace(`[${segment}]`, value);
164
+ }
165
+ if (valid) paths.push(path);
166
+ }
167
+ return paths;
168
+ })
169
+ );
170
+ const allPaths = new Set(staticPaths);
171
+ for (const paths of dynamicResults) {
172
+ for (const path of paths) {
173
+ allPaths.add(path);
174
+ }
175
+ }
176
+ if (isDev && dynamicRoutes.length > 0) {
177
+ const elapsed = Date.now() - startTime;
178
+ console.log(`[next-sitemap] Done! Found ${allPaths.size} total URLs in ${elapsed}ms.`);
179
+ }
180
+ return Array.from(allPaths);
181
+ }
182
+ function pathsToEntries(paths, config) {
183
+ const { baseUrl, locales = [], defaultLocale, exclude, priority, changeFreq } = config;
184
+ return paths.filter((pathname) => !shouldExclude(pathname, exclude)).map((pathname) => {
185
+ const entry = {
186
+ url: buildUrl(baseUrl, pathname, defaultLocale, defaultLocale),
187
+ lastModified: /* @__PURE__ */ new Date(),
188
+ changeFrequency: getChangeFreq(pathname, changeFreq),
189
+ priority: getPriority(pathname, priority)
190
+ };
191
+ if (locales.length > 0) {
192
+ entry.alternates = {
193
+ languages: Object.fromEntries(
194
+ locales.map((locale) => [locale, buildUrl(baseUrl, pathname, locale, defaultLocale)])
195
+ )
196
+ };
197
+ }
198
+ return entry;
199
+ });
200
+ }
201
+
3
202
  // src/index.ts
4
203
  function calculateDepthPriority(pathname) {
5
204
  if (pathname === "/") return 1;
@@ -47,7 +246,8 @@ function buildUrl(baseUrl, pathname, locale, defaultLocale) {
47
246
  }
48
247
  return `${baseUrl}/${locale}${normalizedPath}`;
49
248
  }
50
- function generateSitemapXml(entries) {
249
+ function generateSitemapXml(entries, options) {
250
+ const { poweredBy = true } = options || {};
51
251
  const hasAlternates = entries.some((e) => e.alternates?.languages);
52
252
  const xmlns = hasAlternates ? 'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"' : 'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"';
53
253
  const urlEntries = entries.map((entry) => {
@@ -71,13 +271,14 @@ function generateSitemapXml(entries) {
71
271
  ${parts.join("\n")}
72
272
  </url>`;
73
273
  }).join("\n");
74
- return `<?xml version="1.0" encoding="UTF-8"?>
274
+ const comment = poweredBy ? "\n<!-- Powered by @onruntime/next-sitemap -->" : "";
275
+ return `<?xml version="1.0" encoding="UTF-8"?>${comment}
75
276
  <urlset ${xmlns}>
76
277
  ${urlEntries}
77
278
  </urlset>`;
78
279
  }
79
280
  function generateSitemapIndexXml(baseUrl, sitemapCount, options) {
80
- const { sitemapPattern = "/sitemap-{id}.xml", additionalSitemaps = [] } = options || {};
281
+ const { sitemapPattern = "/sitemap-{id}.xml", additionalSitemaps = [], poweredBy = true } = options || {};
81
282
  const now = (/* @__PURE__ */ new Date()).toISOString();
82
283
  const paginatedEntries = Array.from({ length: sitemapCount }, (_, i) => {
83
284
  const loc = `${baseUrl}${sitemapPattern.replace("{id}", String(i))}`;
@@ -94,17 +295,26 @@ function generateSitemapIndexXml(baseUrl, sitemapCount, options) {
94
295
  </sitemap>`;
95
296
  });
96
297
  const allEntries = [...paginatedEntries, ...additionalEntries].join("\n");
97
- return `<?xml version="1.0" encoding="UTF-8"?>
298
+ const comment = poweredBy ? "\n<!-- Powered by @onruntime/next-sitemap -->" : "";
299
+ return `<?xml version="1.0" encoding="UTF-8"?>${comment}
98
300
  <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
99
301
  ${allEntries}
100
302
  </sitemapindex>`;
101
303
  }
102
304
 
305
+ exports.JS_EXTENSIONS = JS_EXTENSIONS;
306
+ exports.NO_STATIC_PARAMS = NO_STATIC_PARAMS;
103
307
  exports.buildUrl = buildUrl;
104
308
  exports.calculateDepthPriority = calculateDepthPriority;
309
+ exports.executeWorker = executeWorker;
310
+ exports.generateAllPaths = generateAllPaths;
105
311
  exports.generateSitemapIndexXml = generateSitemapIndexXml;
106
312
  exports.generateSitemapXml = generateSitemapXml;
107
313
  exports.getChangeFreq = getChangeFreq;
108
314
  exports.getPriority = getPriority;
315
+ exports.getRouteParams = getRouteParams;
316
+ exports.isDev = isDev;
109
317
  exports.normalizePath = normalizePath;
318
+ exports.paramsCache = paramsCache;
319
+ exports.pathsToEntries = pathsToEntries;
110
320
  exports.shouldExclude = shouldExclude;
package/dist/index.d.cts CHANGED
@@ -1,4 +1,54 @@
1
+ /**
2
+ * Shared utilities, constants, and types for the sitemap package
3
+ */
4
+
5
+ /**
6
+ * File extensions that Node.js/jiti can actually process.
7
+ * Any other extension will be mocked as an empty module.
8
+ */
9
+ declare const JS_EXTENSIONS: Set<string>;
10
+ /**
11
+ * Special error code when a page doesn't export generateStaticParams or getStaticPaths
12
+ */
13
+ declare const NO_STATIC_PARAMS = "NO_STATIC_PARAMS";
14
+ /**
15
+ * Worker result types
16
+ */
17
+ interface WorkerSuccess {
18
+ success: true;
19
+ params: Record<string, string>[];
20
+ }
21
+ interface WorkerFailure {
22
+ success: false;
23
+ error: string;
24
+ }
25
+ type WorkerOutput = WorkerSuccess | WorkerFailure;
26
+ declare const paramsCache: Map<string, Record<string, string>[] | null>;
27
+ declare const isDev: boolean;
28
+ interface RouteInfo$1 {
29
+ pathname: string;
30
+ dynamicSegments: string[];
31
+ fileKey: string;
32
+ }
33
+ /**
34
+ * Execute worker via child process to get static params
35
+ */
36
+ declare function executeWorker(directory: string, fileKey: string, debug: boolean): Promise<Record<string, string>[] | null>;
37
+ /**
38
+ * Get params for a dynamic route (with caching)
39
+ */
40
+ declare function getRouteParams(route: RouteInfo$1, directory: string, debug: boolean): Promise<Record<string, string>[] | null>;
41
+ /**
42
+ * Generate all URL paths from routes (parallel execution for dynamic routes)
43
+ */
44
+ declare function generateAllPaths(routes: RouteInfo$1[], directory: string, debug: boolean): Promise<string[]>;
45
+ /**
46
+ * Convert paths to sitemap entries
47
+ */
48
+ declare function pathsToEntries(paths: string[], config: SitemapConfig): SitemapEntry[];
49
+
1
50
  type ChangeFrequency = "always" | "hourly" | "daily" | "weekly" | "monthly" | "yearly" | "never";
51
+
2
52
  interface SitemapConfig {
3
53
  /**
4
54
  * Base URL of the site (e.g., "https://example.com")
@@ -51,6 +101,16 @@ interface SitemapConfig {
51
101
  * @example additionalSitemaps: ["/products-sitemap.xml", "/blog-sitemap.xml"]
52
102
  */
53
103
  additionalSitemaps?: string[];
104
+ /**
105
+ * Enable debug logging to diagnose issues with route discovery
106
+ * @default false
107
+ */
108
+ debug?: boolean;
109
+ /**
110
+ * Include "Powered by @onruntime/next-sitemap" comment in generated XML
111
+ * @default true
112
+ */
113
+ poweredBy?: boolean;
54
114
  }
55
115
  interface SitemapEntry {
56
116
  url: string;
@@ -98,13 +158,16 @@ declare function buildUrl(baseUrl: string, pathname: string, locale?: string, de
98
158
  /**
99
159
  * Generate sitemap XML from entries
100
160
  */
101
- declare function generateSitemapXml(entries: SitemapEntry[]): string;
161
+ declare function generateSitemapXml(entries: SitemapEntry[], options?: {
162
+ poweredBy?: boolean;
163
+ }): string;
102
164
  /**
103
165
  * Generate sitemap index XML
104
166
  */
105
167
  declare function generateSitemapIndexXml(baseUrl: string, sitemapCount: number, options?: {
106
168
  sitemapPattern?: string;
107
169
  additionalSitemaps?: string[];
170
+ poweredBy?: boolean;
108
171
  }): string;
109
172
 
110
- export { type ChangeFrequency, type PageModule, type RouteInfo, type SitemapConfig, type SitemapEntry, buildUrl, calculateDepthPriority, generateSitemapIndexXml, generateSitemapXml, getChangeFreq, getPriority, normalizePath, shouldExclude };
173
+ export { type ChangeFrequency, JS_EXTENSIONS, NO_STATIC_PARAMS, type PageModule, type RouteInfo, type SitemapConfig, type SitemapEntry, type WorkerFailure, type WorkerOutput, type WorkerSuccess, buildUrl, calculateDepthPriority, executeWorker, generateAllPaths, generateSitemapIndexXml, generateSitemapXml, getChangeFreq, getPriority, getRouteParams, isDev, normalizePath, paramsCache, pathsToEntries, shouldExclude };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,54 @@
1
+ /**
2
+ * Shared utilities, constants, and types for the sitemap package
3
+ */
4
+
5
+ /**
6
+ * File extensions that Node.js/jiti can actually process.
7
+ * Any other extension will be mocked as an empty module.
8
+ */
9
+ declare const JS_EXTENSIONS: Set<string>;
10
+ /**
11
+ * Special error code when a page doesn't export generateStaticParams or getStaticPaths
12
+ */
13
+ declare const NO_STATIC_PARAMS = "NO_STATIC_PARAMS";
14
+ /**
15
+ * Worker result types
16
+ */
17
+ interface WorkerSuccess {
18
+ success: true;
19
+ params: Record<string, string>[];
20
+ }
21
+ interface WorkerFailure {
22
+ success: false;
23
+ error: string;
24
+ }
25
+ type WorkerOutput = WorkerSuccess | WorkerFailure;
26
+ declare const paramsCache: Map<string, Record<string, string>[] | null>;
27
+ declare const isDev: boolean;
28
+ interface RouteInfo$1 {
29
+ pathname: string;
30
+ dynamicSegments: string[];
31
+ fileKey: string;
32
+ }
33
+ /**
34
+ * Execute worker via child process to get static params
35
+ */
36
+ declare function executeWorker(directory: string, fileKey: string, debug: boolean): Promise<Record<string, string>[] | null>;
37
+ /**
38
+ * Get params for a dynamic route (with caching)
39
+ */
40
+ declare function getRouteParams(route: RouteInfo$1, directory: string, debug: boolean): Promise<Record<string, string>[] | null>;
41
+ /**
42
+ * Generate all URL paths from routes (parallel execution for dynamic routes)
43
+ */
44
+ declare function generateAllPaths(routes: RouteInfo$1[], directory: string, debug: boolean): Promise<string[]>;
45
+ /**
46
+ * Convert paths to sitemap entries
47
+ */
48
+ declare function pathsToEntries(paths: string[], config: SitemapConfig): SitemapEntry[];
49
+
1
50
  type ChangeFrequency = "always" | "hourly" | "daily" | "weekly" | "monthly" | "yearly" | "never";
51
+
2
52
  interface SitemapConfig {
3
53
  /**
4
54
  * Base URL of the site (e.g., "https://example.com")
@@ -51,6 +101,16 @@ interface SitemapConfig {
51
101
  * @example additionalSitemaps: ["/products-sitemap.xml", "/blog-sitemap.xml"]
52
102
  */
53
103
  additionalSitemaps?: string[];
104
+ /**
105
+ * Enable debug logging to diagnose issues with route discovery
106
+ * @default false
107
+ */
108
+ debug?: boolean;
109
+ /**
110
+ * Include "Powered by @onruntime/next-sitemap" comment in generated XML
111
+ * @default true
112
+ */
113
+ poweredBy?: boolean;
54
114
  }
55
115
  interface SitemapEntry {
56
116
  url: string;
@@ -98,13 +158,16 @@ declare function buildUrl(baseUrl: string, pathname: string, locale?: string, de
98
158
  /**
99
159
  * Generate sitemap XML from entries
100
160
  */
101
- declare function generateSitemapXml(entries: SitemapEntry[]): string;
161
+ declare function generateSitemapXml(entries: SitemapEntry[], options?: {
162
+ poweredBy?: boolean;
163
+ }): string;
102
164
  /**
103
165
  * Generate sitemap index XML
104
166
  */
105
167
  declare function generateSitemapIndexXml(baseUrl: string, sitemapCount: number, options?: {
106
168
  sitemapPattern?: string;
107
169
  additionalSitemaps?: string[];
170
+ poweredBy?: boolean;
108
171
  }): string;
109
172
 
110
- export { type ChangeFrequency, type PageModule, type RouteInfo, type SitemapConfig, type SitemapEntry, buildUrl, calculateDepthPriority, generateSitemapIndexXml, generateSitemapXml, getChangeFreq, getPriority, normalizePath, shouldExclude };
173
+ export { type ChangeFrequency, JS_EXTENSIONS, NO_STATIC_PARAMS, type PageModule, type RouteInfo, type SitemapConfig, type SitemapEntry, type WorkerFailure, type WorkerOutput, type WorkerSuccess, buildUrl, calculateDepthPriority, executeWorker, generateAllPaths, generateSitemapIndexXml, generateSitemapXml, getChangeFreq, getPriority, getRouteParams, isDev, normalizePath, paramsCache, pathsToEntries, shouldExclude };
package/dist/index.js CHANGED
@@ -1,3 +1,181 @@
1
+ import { existsSync } from 'fs';
2
+ import { dirname, join, delimiter } from 'path';
3
+ import * as childProcess from 'child_process';
4
+ import { fileURLToPath } from 'url';
5
+
6
+ // src/shared.ts
7
+ var JS_EXTENSIONS = /* @__PURE__ */ new Set([
8
+ ".js",
9
+ ".cjs",
10
+ ".mjs",
11
+ ".jsx",
12
+ ".ts",
13
+ ".cts",
14
+ ".mts",
15
+ ".tsx",
16
+ ".json",
17
+ ".node"
18
+ ]);
19
+ var NO_STATIC_PARAMS = "NO_STATIC_PARAMS";
20
+ var spawnProcess = childProcess.spawn;
21
+ var __dirname$1 = dirname(fileURLToPath(import.meta.url));
22
+ var paramsCache = /* @__PURE__ */ new Map();
23
+ var isDev = process.env.NODE_ENV === "development";
24
+ async function executeWorker(directory, fileKey, debug) {
25
+ const absolutePath = join(directory, fileKey.replace("./", ""));
26
+ const projectRoot = process.cwd();
27
+ const distRoot = join(__dirname$1, "..");
28
+ const workerPath = join(distRoot, "worker.cjs");
29
+ const loaderPath = join(distRoot, "loader.js");
30
+ if (debug) {
31
+ console.log(`[next-sitemap] Worker path: ${workerPath}`);
32
+ console.log(`[next-sitemap] Worker exists: ${existsSync(workerPath)}`);
33
+ console.log(`[next-sitemap] Loader path: ${loaderPath}`);
34
+ console.log(`[next-sitemap] Loader exists: ${existsSync(loaderPath)}`);
35
+ }
36
+ return new Promise((resolve) => {
37
+ const nodePath = [
38
+ join(projectRoot, "node_modules"),
39
+ join(__dirname$1, "..", "node_modules")
40
+ ].join(delimiter);
41
+ const importFlag = ["--import", loaderPath];
42
+ const args = [...importFlag, workerPath, absolutePath, projectRoot];
43
+ const child = spawnProcess("node", args, {
44
+ cwd: projectRoot,
45
+ stdio: ["ignore", "pipe", "pipe"],
46
+ env: { ...process.env, NODE_PATH: nodePath }
47
+ });
48
+ let stdout = "";
49
+ let stderr = "";
50
+ child.stdout.on("data", (data) => {
51
+ stdout += data.toString();
52
+ });
53
+ child.stderr.on("data", (data) => {
54
+ stderr += data.toString();
55
+ });
56
+ child.on("close", (code) => {
57
+ if (debug && stderr) {
58
+ console.warn(`[next-sitemap] Worker stderr: ${stderr}`);
59
+ }
60
+ if (code !== 0 && code !== null) {
61
+ if (debug) console.warn(`[next-sitemap] Worker exited with code ${code}`);
62
+ resolve(null);
63
+ return;
64
+ }
65
+ try {
66
+ const lines = stdout.trim().split("\n");
67
+ const result = JSON.parse(lines[lines.length - 1]);
68
+ if (result.success) {
69
+ resolve(result.params);
70
+ } else {
71
+ if (result.error !== NO_STATIC_PARAMS && debug) {
72
+ console.warn(`[next-sitemap] Worker error: ${result.error}`);
73
+ }
74
+ resolve(null);
75
+ }
76
+ } catch {
77
+ if (debug) console.warn(`[next-sitemap] Failed to parse worker output: ${stdout}`);
78
+ resolve(null);
79
+ }
80
+ });
81
+ child.on("error", (err) => {
82
+ if (debug) console.warn(`[next-sitemap] Failed to spawn worker: ${err.message}`);
83
+ resolve(null);
84
+ });
85
+ });
86
+ }
87
+ async function getRouteParams(route, directory, debug) {
88
+ const cacheKey = route.fileKey;
89
+ if (paramsCache.has(cacheKey)) {
90
+ return paramsCache.get(cacheKey);
91
+ }
92
+ if (debug) {
93
+ console.log(`[next-sitemap] ${route.pathname}: executing static params via worker`);
94
+ }
95
+ const params = await executeWorker(directory, route.fileKey, debug);
96
+ paramsCache.set(cacheKey, params);
97
+ if (debug && params) {
98
+ console.log(`[next-sitemap] ${route.pathname}: got ${params.length} params`);
99
+ }
100
+ return params;
101
+ }
102
+ async function generateAllPaths(routes, directory, debug) {
103
+ const staticPaths = ["/"];
104
+ const dynamicRoutes = [];
105
+ for (const route of routes) {
106
+ if (route.dynamicSegments.length === 0) {
107
+ if (route.pathname !== "/") {
108
+ staticPaths.push(route.pathname);
109
+ }
110
+ } else {
111
+ dynamicRoutes.push(route);
112
+ }
113
+ }
114
+ const startTime = isDev ? Date.now() : 0;
115
+ if (isDev && dynamicRoutes.length > 0) {
116
+ console.log(`[next-sitemap] Generating sitemap for ${dynamicRoutes.length} dynamic routes (dev only, instant in production)...`);
117
+ }
118
+ const dynamicResults = await Promise.all(
119
+ dynamicRoutes.map(async (route) => {
120
+ const params = await getRouteParams(route, directory, debug);
121
+ if (!params || params.length === 0) {
122
+ if (debug) {
123
+ console.warn(`[next-sitemap] Skipping dynamic route ${route.pathname}: no static params or empty result.`);
124
+ }
125
+ return [];
126
+ }
127
+ const paths = [];
128
+ for (const param of params) {
129
+ let path = route.pathname;
130
+ let valid = true;
131
+ for (const segment of route.dynamicSegments) {
132
+ const value = param[segment];
133
+ if (value === void 0) {
134
+ if (debug) {
135
+ console.warn(`[next-sitemap] ${route.pathname}: missing param "${segment}" in`, param);
136
+ }
137
+ valid = false;
138
+ break;
139
+ }
140
+ path = path.replace(`[${segment}]`, value);
141
+ }
142
+ if (valid) paths.push(path);
143
+ }
144
+ return paths;
145
+ })
146
+ );
147
+ const allPaths = new Set(staticPaths);
148
+ for (const paths of dynamicResults) {
149
+ for (const path of paths) {
150
+ allPaths.add(path);
151
+ }
152
+ }
153
+ if (isDev && dynamicRoutes.length > 0) {
154
+ const elapsed = Date.now() - startTime;
155
+ console.log(`[next-sitemap] Done! Found ${allPaths.size} total URLs in ${elapsed}ms.`);
156
+ }
157
+ return Array.from(allPaths);
158
+ }
159
+ function pathsToEntries(paths, config) {
160
+ const { baseUrl, locales = [], defaultLocale, exclude, priority, changeFreq } = config;
161
+ return paths.filter((pathname) => !shouldExclude(pathname, exclude)).map((pathname) => {
162
+ const entry = {
163
+ url: buildUrl(baseUrl, pathname, defaultLocale, defaultLocale),
164
+ lastModified: /* @__PURE__ */ new Date(),
165
+ changeFrequency: getChangeFreq(pathname, changeFreq),
166
+ priority: getPriority(pathname, priority)
167
+ };
168
+ if (locales.length > 0) {
169
+ entry.alternates = {
170
+ languages: Object.fromEntries(
171
+ locales.map((locale) => [locale, buildUrl(baseUrl, pathname, locale, defaultLocale)])
172
+ )
173
+ };
174
+ }
175
+ return entry;
176
+ });
177
+ }
178
+
1
179
  // src/index.ts
2
180
  function calculateDepthPriority(pathname) {
3
181
  if (pathname === "/") return 1;
@@ -45,7 +223,8 @@ function buildUrl(baseUrl, pathname, locale, defaultLocale) {
45
223
  }
46
224
  return `${baseUrl}/${locale}${normalizedPath}`;
47
225
  }
48
- function generateSitemapXml(entries) {
226
+ function generateSitemapXml(entries, options) {
227
+ const { poweredBy = true } = options || {};
49
228
  const hasAlternates = entries.some((e) => e.alternates?.languages);
50
229
  const xmlns = hasAlternates ? 'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"' : 'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"';
51
230
  const urlEntries = entries.map((entry) => {
@@ -69,13 +248,14 @@ function generateSitemapXml(entries) {
69
248
  ${parts.join("\n")}
70
249
  </url>`;
71
250
  }).join("\n");
72
- return `<?xml version="1.0" encoding="UTF-8"?>
251
+ const comment = poweredBy ? "\n<!-- Powered by @onruntime/next-sitemap -->" : "";
252
+ return `<?xml version="1.0" encoding="UTF-8"?>${comment}
73
253
  <urlset ${xmlns}>
74
254
  ${urlEntries}
75
255
  </urlset>`;
76
256
  }
77
257
  function generateSitemapIndexXml(baseUrl, sitemapCount, options) {
78
- const { sitemapPattern = "/sitemap-{id}.xml", additionalSitemaps = [] } = options || {};
258
+ const { sitemapPattern = "/sitemap-{id}.xml", additionalSitemaps = [], poweredBy = true } = options || {};
79
259
  const now = (/* @__PURE__ */ new Date()).toISOString();
80
260
  const paginatedEntries = Array.from({ length: sitemapCount }, (_, i) => {
81
261
  const loc = `${baseUrl}${sitemapPattern.replace("{id}", String(i))}`;
@@ -92,10 +272,11 @@ function generateSitemapIndexXml(baseUrl, sitemapCount, options) {
92
272
  </sitemap>`;
93
273
  });
94
274
  const allEntries = [...paginatedEntries, ...additionalEntries].join("\n");
95
- return `<?xml version="1.0" encoding="UTF-8"?>
275
+ const comment = poweredBy ? "\n<!-- Powered by @onruntime/next-sitemap -->" : "";
276
+ return `<?xml version="1.0" encoding="UTF-8"?>${comment}
96
277
  <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
97
278
  ${allEntries}
98
279
  </sitemapindex>`;
99
280
  }
100
281
 
101
- export { buildUrl, calculateDepthPriority, generateSitemapIndexXml, generateSitemapXml, getChangeFreq, getPriority, normalizePath, shouldExclude };
282
+ export { JS_EXTENSIONS, NO_STATIC_PARAMS, buildUrl, calculateDepthPriority, executeWorker, generateAllPaths, generateSitemapIndexXml, generateSitemapXml, getChangeFreq, getPriority, getRouteParams, isDev, normalizePath, paramsCache, pathsToEntries, shouldExclude };