starpro-plugin-sdk 1.0.1 → 1.1.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.
@@ -0,0 +1,413 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/build/index.ts
31
+ var build_exports = {};
32
+ __export(build_exports, {
33
+ buildStarProPlugin: () => buildStarProPlugin,
34
+ discoverRoutes: () => discoverRoutes,
35
+ starproEsbuildPlugin: () => starproEsbuildPlugin
36
+ });
37
+ module.exports = __toCommonJS(build_exports);
38
+ var fs = __toESM(require("fs"));
39
+ var path = __toESM(require("path"));
40
+ function walkDir(dir, fileList = []) {
41
+ if (!fs.existsSync(dir)) return fileList;
42
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
43
+ for (const entry of entries) {
44
+ const fullPath = path.join(dir, entry.name);
45
+ if (entry.isDirectory()) {
46
+ walkDir(fullPath, fileList);
47
+ } else if (entry.isFile()) {
48
+ fileList.push(fullPath);
49
+ }
50
+ }
51
+ return fileList;
52
+ }
53
+ function discoverRoutes(appDir, options = {}) {
54
+ const { stripRouteGroups = true } = options;
55
+ const allFiles = walkDir(appDir);
56
+ const pageFiles = [];
57
+ let layoutFile = null;
58
+ for (const fullPath of allFiles) {
59
+ const rel = path.relative(appDir, fullPath).replace(/\\/g, "/");
60
+ if (/^(\([^)]+\)\/)?layout\.(tsx|jsx|js|ts)$/.test(rel) && !layoutFile) {
61
+ layoutFile = fullPath;
62
+ }
63
+ if (!/(^|\/)(page|index)\.(tsx|jsx|js|ts)$/.test(rel)) {
64
+ continue;
65
+ }
66
+ let cleaned = rel.replace(/\/(page|index)\.(tsx|jsx|js|ts)$/, "").replace(/^(page|index)\.(tsx|jsx|js|ts)$/, "");
67
+ if (stripRouteGroups) {
68
+ cleaned = cleaned.split("/").filter((part) => !/^\([^)]+\)$/.test(part)).join("/");
69
+ }
70
+ cleaned = cleaned.replace(/\[\.\.\.([^\]]+)\]/g, "*$1").replace(/\[([^\]]+)\]/g, ":$1");
71
+ let routePath = cleaned ? cleaned.startsWith("/") ? cleaned : `/${cleaned}` : "/";
72
+ let label = void 0;
73
+ const isDynamic = routePath.includes(":") || routePath.includes("*");
74
+ if (!isDynamic && routePath !== "/") {
75
+ const last = routePath.split("/").pop() || "";
76
+ label = last.split(/[-_]+/).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
77
+ if (label) {
78
+ label = label.replace(/\bWater Waste Water\b/gi, "Water & Wastewater");
79
+ }
80
+ }
81
+ pageFiles.push({
82
+ filePath: fullPath,
83
+ routePath,
84
+ label
85
+ });
86
+ }
87
+ pageFiles.sort((a, b) => {
88
+ if (a.routePath === "/") return -1;
89
+ if (b.routePath === "/") return 1;
90
+ const aDyn = a.routePath.includes(":") || a.routePath.includes("*");
91
+ const bDyn = b.routePath.includes(":") || b.routePath.includes("*");
92
+ if (aDyn && !bDyn) return 1;
93
+ if (!aDyn && bDyn) return -1;
94
+ return a.routePath.localeCompare(b.routePath);
95
+ });
96
+ return { routes: pageFiles, layoutFile };
97
+ }
98
+ function starproEsbuildPlugin(options = {}) {
99
+ const cwd = options.cwd || process.cwd();
100
+ const mockNext = options.mockNext !== false;
101
+ const stripRouteGroups = options.stripRouteGroups !== false;
102
+ let appDir = options.appDir;
103
+ if (!appDir) {
104
+ const candidates = [
105
+ path.join(cwd, "src/app"),
106
+ path.join(cwd, "app"),
107
+ path.join(cwd, "src/pages"),
108
+ path.join(cwd, "pages")
109
+ ];
110
+ for (const cand of candidates) {
111
+ if (fs.existsSync(cand)) {
112
+ appDir = cand;
113
+ break;
114
+ }
115
+ }
116
+ }
117
+ return {
118
+ name: "starpro-plugin-bundler",
119
+ setup(build) {
120
+ build.onResolve({ filter: /^starpro:routes$/ }, (args) => ({
121
+ path: args.path,
122
+ namespace: "starpro-routes-virtual"
123
+ }));
124
+ build.onLoad(
125
+ { filter: /.*/, namespace: "starpro-routes-virtual" },
126
+ () => {
127
+ if (!appDir || !fs.existsSync(appDir)) {
128
+ return {
129
+ contents: `
130
+ export const routes = [];
131
+ export const layout = undefined;
132
+ export default routes;
133
+ `,
134
+ loader: "ts"
135
+ };
136
+ }
137
+ const { routes, layoutFile } = discoverRoutes(appDir, {
138
+ stripRouteGroups
139
+ });
140
+ const importLines = [];
141
+ const routeObjects = [];
142
+ routes.forEach((r, idx) => {
143
+ const varName = `Page_${idx}`;
144
+ const normalizedPath = r.filePath.replace(/\\/g, "/");
145
+ importLines.push(`import ${varName} from ${JSON.stringify(normalizedPath)};`);
146
+ routeObjects.push(`{
147
+ path: ${JSON.stringify(r.routePath)},
148
+ component: ${varName},
149
+ label: ${r.label ? JSON.stringify(r.label) : "undefined"},
150
+ exact: ${r.routePath === "/"}
151
+ }`);
152
+ });
153
+ let layoutImport = "export const layout = undefined;";
154
+ if (layoutFile) {
155
+ const normLayout = layoutFile.replace(/\\/g, "/");
156
+ importLines.push(`import LayoutComponent from ${JSON.stringify(normLayout)};`);
157
+ layoutImport = "export const layout = LayoutComponent;";
158
+ }
159
+ const defaultRoute = routes.find((r) => r.routePath !== "/" && !r.routePath.includes(":"))?.routePath || (routes.length > 0 ? routes[0].routePath : "/");
160
+ const contents = `
161
+ ${importLines.join("\n")}
162
+
163
+ export const routes = [
164
+ ${routeObjects.join(",\n")}
165
+ ];
166
+
167
+ ${layoutImport}
168
+ export const defaultRoute = ${JSON.stringify(defaultRoute)};
169
+ export default routes;
170
+ `;
171
+ return {
172
+ contents,
173
+ loader: "tsx",
174
+ resolveDir: cwd
175
+ };
176
+ }
177
+ );
178
+ if (mockNext) {
179
+ build.onResolve({ filter: /^next\/navigation$/ }, (args) => ({
180
+ path: args.path,
181
+ namespace: "starpro-mock-nav"
182
+ }));
183
+ build.onLoad(
184
+ { filter: /.*/, namespace: "starpro-mock-nav" },
185
+ () => ({
186
+ contents: `
187
+ import React from 'react';
188
+ import {
189
+ starproRouter,
190
+ useStarProPathname,
191
+ useStarProSearchParams,
192
+ useStarProParams,
193
+ } from 'starpro-plugin-sdk';
194
+
195
+ export const useRouter = () => ({
196
+ push: (url) => starproRouter.push(url),
197
+ replace: (url) => starproRouter.replace(url),
198
+ back: () => starproRouter.back(),
199
+ forward: () => starproRouter.forward(),
200
+ refresh: () => {},
201
+ prefetch: () => {},
202
+ });
203
+
204
+ export const usePathname = useStarProPathname;
205
+ export const useSearchParams = useStarProSearchParams;
206
+ export const useParams = useStarProParams;
207
+ export const useSelectedLayoutSegment = () => null;
208
+ export const useSelectedLayoutSegments = () => [];
209
+
210
+ export const redirect = (url) => {
211
+ starproRouter.replace(url);
212
+ const err = new Error('NEXT_REDIRECT');
213
+ err.digest = 'NEXT_REDIRECT;replace;' + url + ';307;';
214
+ err.url = url;
215
+ err.isStarProRedirect = true;
216
+ throw err;
217
+ };
218
+
219
+ export const notFound = () => {};
220
+ export default { useRouter, usePathname, useSearchParams, useParams, redirect, notFound };
221
+ `,
222
+ loader: "tsx",
223
+ resolveDir: cwd
224
+ })
225
+ );
226
+ build.onResolve({ filter: /^next\/link$/ }, (args) => ({
227
+ path: args.path,
228
+ namespace: "starpro-mock-link"
229
+ }));
230
+ build.onLoad(
231
+ { filter: /.*/, namespace: "starpro-mock-link" },
232
+ () => ({
233
+ contents: `
234
+ import React, { forwardRef } from 'react';
235
+ import { starproRouter } from 'starpro-plugin-sdk';
236
+
237
+ export const Link = forwardRef((props, ref) => {
238
+ const { href, children, onClick, ...rest } = props;
239
+ const targetHref = typeof href === 'object' && href !== null ? (href.pathname || '#') : (href || '#');
240
+ return React.createElement('a', {
241
+ ...rest,
242
+ ref,
243
+ href: targetHref,
244
+ onClick: (e) => {
245
+ if (onClick) onClick(e);
246
+ if (targetHref.startsWith('http://') || targetHref.startsWith('https://')) {
247
+ return;
248
+ }
249
+ e.preventDefault();
250
+ starproRouter.push(targetHref);
251
+ }
252
+ }, children);
253
+ });
254
+ export default Link;
255
+ `,
256
+ loader: "tsx",
257
+ resolveDir: cwd
258
+ })
259
+ );
260
+ build.onResolve({ filter: /^next\/image$/ }, (args) => ({
261
+ path: args.path,
262
+ namespace: "starpro-mock-image"
263
+ }));
264
+ build.onLoad(
265
+ { filter: /.*/, namespace: "starpro-mock-image" },
266
+ () => ({
267
+ contents: `
268
+ import React from 'react';
269
+ export default function Image(props) {
270
+ const { src, alt, ...rest } = props;
271
+ const targetSrc = typeof src === 'object' && src !== null ? (src.src || '') : src;
272
+ return React.createElement('img', { ...rest, src: targetSrc, alt: alt || '' });
273
+ }
274
+ `,
275
+ loader: "tsx",
276
+ resolveDir: cwd
277
+ })
278
+ );
279
+ build.onResolve({ filter: /^next\/router$/ }, (args) => ({
280
+ path: args.path,
281
+ namespace: "starpro-mock-pages-router"
282
+ }));
283
+ build.onLoad(
284
+ { filter: /.*/, namespace: "starpro-mock-pages-router" },
285
+ () => ({
286
+ contents: `
287
+ import { starproRouter } from 'starpro-plugin-sdk';
288
+ export const useRouter = () => ({
289
+ push: (url) => starproRouter.push(url),
290
+ replace: (url) => starproRouter.replace(url),
291
+ pathname: starproRouter.getState().pathname,
292
+ query: Object.fromEntries(starproRouter.getState().searchParams.entries()),
293
+ asPath: starproRouter.getState().url,
294
+ });
295
+ export default { useRouter };
296
+ `,
297
+ loader: "ts",
298
+ resolveDir: cwd
299
+ })
300
+ );
301
+ }
302
+ }
303
+ };
304
+ }
305
+ function loadProjectEnv(cwd, mode) {
306
+ const envFiles = [
307
+ `.env.${mode}.local`,
308
+ `.env.local`,
309
+ `.env.${mode}`,
310
+ `.env`
311
+ ];
312
+ const envMap = {};
313
+ for (const file of envFiles) {
314
+ const fullPath = path.resolve(cwd, file);
315
+ if (fs.existsSync(fullPath)) {
316
+ try {
317
+ const lines = fs.readFileSync(fullPath, "utf-8").split("\n");
318
+ for (const line of lines) {
319
+ const trimmed = line.trim();
320
+ if (!trimmed || trimmed.startsWith("#")) continue;
321
+ const idx = trimmed.indexOf("=");
322
+ if (idx !== -1) {
323
+ const key = trimmed.slice(0, idx).trim();
324
+ let val = trimmed.slice(idx + 1).trim();
325
+ if (val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'")) {
326
+ val = val.slice(1, -1);
327
+ }
328
+ if (!(key in envMap)) {
329
+ envMap[key] = val;
330
+ }
331
+ }
332
+ }
333
+ } catch (e) {
334
+ }
335
+ }
336
+ }
337
+ return envMap;
338
+ }
339
+ async function buildStarProPlugin(options = {}) {
340
+ const cwd = options.cwd || process.cwd();
341
+ const envMode = options.env || process.env.NODE_ENV || "production";
342
+ const entry = options.entry || (fs.existsSync(path.join(cwd, "src/plugin-entry.tsx")) ? "src/plugin-entry.tsx" : "src/plugin-entry.ts");
343
+ const outFile = options.out || "public/plugin.js";
344
+ const minify = options.minify !== false;
345
+ let esbuild;
346
+ try {
347
+ esbuild = require("esbuild");
348
+ } catch (e) {
349
+ console.error(
350
+ "\u274C [StarPro Build] 'esbuild' is required. Please install it with: npm install -D esbuild"
351
+ );
352
+ throw e;
353
+ }
354
+ const envVars = loadProjectEnv(cwd, envMode);
355
+ const apiUrl = process.env.NEXT_PUBLIC_API_URL || envVars["NEXT_PUBLIC_API_URL"] || "";
356
+ console.log(
357
+ `\u{1F4E6} [StarPro Plugin SDK] Building ${entry} -> ${outFile} (mode: ${envMode})`
358
+ );
359
+ const defineRecord = {
360
+ "process.env.NODE_ENV": JSON.stringify(envMode),
361
+ "process.env.NEXT_PUBLIC_API_URL": JSON.stringify(apiUrl),
362
+ ...options.define
363
+ };
364
+ for (const [k, v] of Object.entries(envVars)) {
365
+ if (k.startsWith("NEXT_PUBLIC_") && !(`process.env.${k}` in defineRecord)) {
366
+ defineRecord[`process.env.${k}`] = JSON.stringify(v);
367
+ }
368
+ }
369
+ const targetNodeModules = path.resolve(cwd, "node_modules");
370
+ const alias = {};
371
+ if (fs.existsSync(path.join(targetNodeModules, "react"))) {
372
+ alias["react"] = path.join(targetNodeModules, "react");
373
+ }
374
+ if (fs.existsSync(path.join(targetNodeModules, "react-dom"))) {
375
+ alias["react-dom"] = path.join(targetNodeModules, "react-dom");
376
+ }
377
+ if (fs.existsSync(path.join(targetNodeModules, "react/jsx-runtime"))) {
378
+ alias["react/jsx-runtime"] = path.join(targetNodeModules, "react/jsx-runtime");
379
+ }
380
+ const plugins = [
381
+ starproEsbuildPlugin({
382
+ appDir: options.appDir,
383
+ cwd,
384
+ mockNext: options.mockNext,
385
+ stripRouteGroups: options.stripRouteGroups
386
+ }),
387
+ ...options.plugins || []
388
+ ];
389
+ try {
390
+ const result = await esbuild.build({
391
+ entryPoints: [entry],
392
+ bundle: true,
393
+ minify,
394
+ format: "iife",
395
+ jsx: "automatic",
396
+ outfile: outFile,
397
+ alias,
398
+ define: defineRecord,
399
+ plugins
400
+ });
401
+ console.log(`\u2705 [StarPro Plugin SDK] Successfully built ${outFile}!`);
402
+ return result;
403
+ } catch (err) {
404
+ console.error("\u274C [StarPro Plugin SDK] Build failed:", err);
405
+ throw err;
406
+ }
407
+ }
408
+ // Annotate the CommonJS export names for ESM import in node:
409
+ 0 && (module.exports = {
410
+ buildStarProPlugin,
411
+ discoverRoutes,
412
+ starproEsbuildPlugin
413
+ });