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.
package/dist/index.js ADDED
@@ -0,0 +1,725 @@
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/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ StarProPluginWrapper: () => StarProPluginWrapper,
34
+ StarProRedirectBoundary: () => StarProRedirectBoundary,
35
+ StarProRouter: () => StarProRouter,
36
+ StarProRouterView: () => StarProRouterView,
37
+ autoRoutesFromGlob: () => autoRoutesFromGlob,
38
+ createStarProApp: () => createStarProApp,
39
+ defineStarProApp: () => defineStarProApp,
40
+ defineStarProPlugin: () => defineStarProPlugin,
41
+ isStarProPlugin: () => isStarProPlugin,
42
+ matchRoute: () => matchRoute,
43
+ setupStarProAuthBridge: () => setupStarProAuthBridge,
44
+ starproRouter: () => starproRouter,
45
+ useStarProAuth: () => useStarProAuth,
46
+ useStarProParams: () => useStarProParams,
47
+ useStarProPathname: () => useStarProPathname,
48
+ useStarProRouter: () => useStarProRouter,
49
+ useStarProSearchParams: () => useStarProSearchParams
50
+ });
51
+ module.exports = __toCommonJS(index_exports);
52
+
53
+ // src/bridge.ts
54
+ function setupStarProAuthBridge(payload) {
55
+ if (typeof window === "undefined") return;
56
+ const { accessToken, refreshToken, user } = payload || {};
57
+ if (!accessToken) return;
58
+ console.log("\u26A1 [StarPro Plugin SDK] Auto-syncing auth tokens across storage & HTTP clients...");
59
+ const tokenKeys = ["accessToken", "access_token", "token", "starpro_token", "authToken"];
60
+ tokenKeys.forEach((key) => {
61
+ try {
62
+ localStorage.setItem(key, accessToken);
63
+ sessionStorage.setItem(key, accessToken);
64
+ } catch (e) {
65
+ }
66
+ });
67
+ if (refreshToken) {
68
+ try {
69
+ localStorage.setItem("refreshToken", refreshToken);
70
+ localStorage.setItem("refresh_token", refreshToken);
71
+ sessionStorage.setItem("refreshToken", refreshToken);
72
+ } catch (e) {
73
+ }
74
+ }
75
+ if (user) {
76
+ try {
77
+ localStorage.setItem("user", JSON.stringify(user));
78
+ localStorage.setItem("user_email", user.email || "");
79
+ } catch (e) {
80
+ }
81
+ }
82
+ try {
83
+ localStorage.setItem("is_starpro_plugin", "true");
84
+ sessionStorage.setItem("is_starpro_plugin", "true");
85
+ } catch (e) {
86
+ }
87
+ if (window.axios) {
88
+ try {
89
+ window.axios.defaults.headers.common["Authorization"] = `Bearer ${accessToken}`;
90
+ } catch (e) {
91
+ }
92
+ }
93
+ if (typeof window.fetch === "function") {
94
+ const originalFetch = window.fetch;
95
+ window.fetch = function(input, init) {
96
+ const options = init || {};
97
+ options.headers = options.headers || {};
98
+ if (options.headers instanceof Headers) {
99
+ if (!options.headers.has("Authorization")) {
100
+ options.headers.set("Authorization", `Bearer ${accessToken}`);
101
+ }
102
+ } else if (Array.isArray(options.headers)) {
103
+ const hasAuth = options.headers.some(([k]) => k.toLowerCase() === "authorization");
104
+ if (!hasAuth) {
105
+ options.headers.push(["Authorization", `Bearer ${accessToken}`]);
106
+ }
107
+ } else {
108
+ const headersRecord = options.headers;
109
+ if (!headersRecord["Authorization"] && !headersRecord["authorization"]) {
110
+ headersRecord["Authorization"] = `Bearer ${accessToken}`;
111
+ }
112
+ }
113
+ return originalFetch.call(this, input, options);
114
+ };
115
+ }
116
+ }
117
+ function isStarProPlugin() {
118
+ if (typeof window === "undefined") return false;
119
+ return localStorage.getItem("is_starpro_plugin") === "true" || sessionStorage.getItem("is_starpro_plugin") === "true" || Boolean(window.StarProPlugins);
120
+ }
121
+
122
+ // src/define-plugin.ts
123
+ function defineStarProPlugin(options) {
124
+ if (typeof window === "undefined") return;
125
+ const {
126
+ pluginId = "default",
127
+ onMount,
128
+ onUnmount,
129
+ autoInjectAuth = true
130
+ } = options;
131
+ window.StarProPlugins = window.StarProPlugins || {};
132
+ const pluginModule = {
133
+ mount: function(container, payload) {
134
+ const targetElement = typeof container === "string" ? document.getElementById(container) : container;
135
+ if (!targetElement) {
136
+ console.error(
137
+ `[StarPro Plugin: ${pluginId}] Target container element not found!`
138
+ );
139
+ return;
140
+ }
141
+ if (autoInjectAuth) {
142
+ setupStarProAuthBridge(payload);
143
+ }
144
+ let cleanup = void 0;
145
+ if (typeof onMount === "function") {
146
+ cleanup = onMount(targetElement, payload);
147
+ }
148
+ return function unmount() {
149
+ if (typeof cleanup === "function") {
150
+ try {
151
+ cleanup();
152
+ } catch (err) {
153
+ console.warn(`[StarPro Plugin: ${pluginId}] Error in cleanup:`, err);
154
+ }
155
+ }
156
+ if (typeof onUnmount === "function") {
157
+ try {
158
+ onUnmount();
159
+ } catch (err) {
160
+ console.warn(
161
+ `[StarPro Plugin: ${pluginId}] Error in onUnmount:`,
162
+ err
163
+ );
164
+ }
165
+ }
166
+ targetElement.innerHTML = "";
167
+ };
168
+ }
169
+ };
170
+ window.StarProPlugins[pluginId] = pluginModule;
171
+ window.StarProPlugins["default"] = pluginModule;
172
+ window.mountStarProPlugin = pluginModule.mount;
173
+ console.log(`\u2713 [StarPro Plugin SDK] Registered plugin "${pluginId}"`);
174
+ }
175
+
176
+ // src/define-app.tsx
177
+ var import_client = require("react-dom/client");
178
+
179
+ // src/react.tsx
180
+ var import_react2 = require("react");
181
+
182
+ // src/router.tsx
183
+ var import_react = __toESM(require("react"));
184
+ var import_jsx_runtime = require("react/jsx-runtime");
185
+ function matchRoute(pattern, pathname) {
186
+ const cleanPattern = pattern.length > 1 && pattern.endsWith("/") ? pattern.slice(0, -1) : pattern;
187
+ const cleanPath = pathname.length > 1 && pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
188
+ if (cleanPattern === cleanPath) {
189
+ return { matched: true, params: {} };
190
+ }
191
+ const paramNames = [];
192
+ const regexPattern = cleanPattern.replace(/\[\.\.\.([^\]]+)\]/g, (_, name) => {
193
+ paramNames.push(name);
194
+ return "(.*)";
195
+ }).replace(/\[([^\]]+)\]/g, (_, name) => {
196
+ paramNames.push(name);
197
+ return "([^/]+)";
198
+ }).replace(/:([a-zA-Z0-9_]+)/g, (_, name) => {
199
+ paramNames.push(name);
200
+ return "([^/]+)";
201
+ }).replace(/\*([a-zA-Z0-9_]*)/g, (_, name) => {
202
+ paramNames.push(name || "wildcard");
203
+ return "(.*)";
204
+ });
205
+ const regex = new RegExp(`^${regexPattern}$`);
206
+ const match = cleanPath.match(regex);
207
+ if (!match) {
208
+ return { matched: false, params: {} };
209
+ }
210
+ const params = {};
211
+ paramNames.forEach((name, index) => {
212
+ params[name] = decodeURIComponent(match[index + 1] || "");
213
+ });
214
+ return { matched: true, params };
215
+ }
216
+ var StarProRouter = class {
217
+ constructor(initialUrl = "/") {
218
+ this.currentUrl = "/";
219
+ this.history = ["/"];
220
+ this.listeners = /* @__PURE__ */ new Set();
221
+ this.routes = [];
222
+ this.notifyScheduled = false;
223
+ this.currentUrl = initialUrl;
224
+ this.history = [initialUrl];
225
+ }
226
+ setRoutes(routes) {
227
+ this.routes = routes;
228
+ this.notify();
229
+ }
230
+ getRoutes() {
231
+ return this.routes;
232
+ }
233
+ getState() {
234
+ const [pathPart, searchPart] = (this.currentUrl || "/").split("?");
235
+ const pathname = pathPart || "/";
236
+ const searchParams = new URLSearchParams(searchPart || "");
237
+ let params = {};
238
+ for (const r of this.routes) {
239
+ const match = matchRoute(r.path, pathname);
240
+ if (match.matched) {
241
+ params = match.params;
242
+ break;
243
+ }
244
+ }
245
+ return {
246
+ url: this.currentUrl,
247
+ pathname,
248
+ searchParams,
249
+ params,
250
+ history: [...this.history]
251
+ };
252
+ }
253
+ getPathname() {
254
+ return this.getState().pathname;
255
+ }
256
+ getSearchParams() {
257
+ return this.getState().searchParams;
258
+ }
259
+ getParams() {
260
+ return this.getState().params;
261
+ }
262
+ subscribe(listener) {
263
+ this.listeners.add(listener);
264
+ return () => {
265
+ this.listeners.delete(listener);
266
+ };
267
+ }
268
+ /**
269
+ * Asynchronously notifies listeners on the next microtask tick.
270
+ * This completely prevents React warnings when navigating or redirecting
271
+ * during a component's render lifecycle.
272
+ */
273
+ notify() {
274
+ if (this.notifyScheduled) return;
275
+ this.notifyScheduled = true;
276
+ Promise.resolve().then(() => {
277
+ this.notifyScheduled = false;
278
+ const state = this.getState();
279
+ this.listeners.forEach((fn) => {
280
+ try {
281
+ fn(state);
282
+ } catch (err) {
283
+ console.error("[StarPro Router] Listener error:", err);
284
+ }
285
+ });
286
+ });
287
+ }
288
+ push(url) {
289
+ if (!url || url === this.currentUrl) return;
290
+ this.currentUrl = url;
291
+ this.history.push(url);
292
+ this.notify();
293
+ }
294
+ replace(url) {
295
+ if (!url) return;
296
+ this.currentUrl = url;
297
+ if (this.history.length > 0) {
298
+ this.history[this.history.length - 1] = url;
299
+ } else {
300
+ this.history.push(url);
301
+ }
302
+ this.notify();
303
+ }
304
+ redirect(url) {
305
+ this.replace(url);
306
+ }
307
+ back() {
308
+ if (this.history.length > 1) {
309
+ this.history.pop();
310
+ this.currentUrl = this.history[this.history.length - 1];
311
+ this.notify();
312
+ }
313
+ }
314
+ forward() {
315
+ }
316
+ };
317
+ var starproRouter = new StarProRouter("/");
318
+ function useStarProRouter() {
319
+ const [state, setState] = (0, import_react.useState)(
320
+ () => starproRouter.getState()
321
+ );
322
+ (0, import_react.useEffect)(() => {
323
+ return starproRouter.subscribe(setState);
324
+ }, []);
325
+ return {
326
+ ...state,
327
+ push: (url) => starproRouter.push(url),
328
+ replace: (url) => starproRouter.replace(url),
329
+ redirect: (url) => starproRouter.replace(url),
330
+ back: () => starproRouter.back(),
331
+ forward: () => starproRouter.forward()
332
+ };
333
+ }
334
+ function useStarProPathname() {
335
+ const [pathname, setPathname] = (0, import_react.useState)(
336
+ () => starproRouter.getState().pathname
337
+ );
338
+ (0, import_react.useEffect)(() => {
339
+ return starproRouter.subscribe((s) => setPathname(s.pathname));
340
+ }, []);
341
+ return pathname;
342
+ }
343
+ function useStarProSearchParams() {
344
+ const [searchParams, setSearchParams] = (0, import_react.useState)(
345
+ () => starproRouter.getState().searchParams
346
+ );
347
+ (0, import_react.useEffect)(() => {
348
+ return starproRouter.subscribe((s) => setSearchParams(s.searchParams));
349
+ }, []);
350
+ return searchParams;
351
+ }
352
+ function useStarProParams() {
353
+ const [params, setParams] = (0, import_react.useState)(
354
+ () => starproRouter.getState().params
355
+ );
356
+ (0, import_react.useEffect)(() => {
357
+ return starproRouter.subscribe((s) => setParams(s.params));
358
+ }, []);
359
+ return params;
360
+ }
361
+ function autoRoutesFromGlob(modules, options = {}) {
362
+ const routes = [];
363
+ const { stripGroups = true } = options;
364
+ for (const [rawPath, moduleExports] of Object.entries(modules)) {
365
+ let routePath = rawPath.replace(/^[./]+/, "").replace(/^src\//, "").replace(/^(app|pages)\//, "").replace(/\/page\.(tsx|jsx|js|ts)$/, "").replace(/\/index\.(tsx|jsx|js|ts)$/, "").replace(/^page\.(tsx|jsx|js|ts)$/, "").replace(/^index\.(tsx|jsx|js|ts)$/, "");
366
+ if (stripGroups) {
367
+ routePath = routePath.split("/").filter((segment) => !/^\([^)]+\)$/.test(segment)).join("/");
368
+ }
369
+ routePath = routePath.replace(/\[\.\.\.([^\]]+)\]/g, "*$1").replace(/\[([^\]]+)\]/g, ":$1");
370
+ if (!routePath.startsWith("/")) {
371
+ routePath = "/" + routePath;
372
+ }
373
+ if (routePath === "") {
374
+ routePath = "/";
375
+ }
376
+ const Component = moduleExports?.default || moduleExports;
377
+ if (!Component) continue;
378
+ let label = void 0;
379
+ const isDynamic = routePath.includes(":") || routePath.includes("*");
380
+ if (!isDynamic && routePath !== "/") {
381
+ const lastSegment = routePath.split("/").pop() || "";
382
+ label = lastSegment.split(/[-_]+/).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
383
+ if (label) {
384
+ label = label.replace(/\bWater Waste Water\b/gi, "Water & Wastewater");
385
+ }
386
+ }
387
+ routes.push({
388
+ path: routePath,
389
+ component: Component,
390
+ label,
391
+ exact: routePath === "/"
392
+ });
393
+ }
394
+ return routes.sort((a, b) => {
395
+ if (a.path === "/") return -1;
396
+ if (b.path === "/") return 1;
397
+ const aDyn = a.path.includes(":") || a.path.includes("*");
398
+ const bDyn = b.path.includes(":") || b.path.includes("*");
399
+ if (aDyn && !bDyn) return 1;
400
+ if (!aDyn && bDyn) return -1;
401
+ return a.path.localeCompare(b.path);
402
+ });
403
+ }
404
+ var StarProRedirectBoundary = class extends import_react.default.Component {
405
+ constructor(props) {
406
+ super(props);
407
+ this.state = { hasError: false };
408
+ }
409
+ static getDerivedStateFromError(error) {
410
+ if (error?.isStarProRedirect || error?.message === "NEXT_REDIRECT" || typeof error?.digest === "string" && error.digest.startsWith("NEXT_REDIRECT")) {
411
+ return { hasError: true };
412
+ }
413
+ return { hasError: false };
414
+ }
415
+ componentDidCatch(error) {
416
+ if (error?.isStarProRedirect || error?.message === "NEXT_REDIRECT" || typeof error?.digest === "string" && error.digest.startsWith("NEXT_REDIRECT")) {
417
+ const targetUrl = error.url || (typeof error.digest === "string" ? error.digest.split(";")[2] : null);
418
+ if (targetUrl) {
419
+ starproRouter.replace(targetUrl);
420
+ }
421
+ Promise.resolve().then(() => {
422
+ this.setState({ hasError: false });
423
+ });
424
+ return;
425
+ }
426
+ console.error("[StarPro Router] Page render error:", error);
427
+ }
428
+ render() {
429
+ if (this.state.hasError) {
430
+ return this.props.fallback || null;
431
+ }
432
+ return this.props.children;
433
+ }
434
+ };
435
+ var StarProRouterView = ({
436
+ routes,
437
+ defaultRoute,
438
+ payload,
439
+ layout: CustomLayout,
440
+ title,
441
+ badge,
442
+ showNav,
443
+ themeColor = "#059669",
444
+ // emerald
445
+ fallback
446
+ }) => {
447
+ const [routeState, setRouteState] = (0, import_react.useState)(
448
+ () => starproRouter.getState()
449
+ );
450
+ (0, import_react.useEffect)(() => {
451
+ starproRouter.setRoutes(routes);
452
+ const current = starproRouter.getState().pathname;
453
+ const hasExactRoot = routes.some((r) => r.path === "/" || r.path === "");
454
+ if (current === "/" || current === "") {
455
+ if (defaultRoute) {
456
+ starproRouter.replace(defaultRoute);
457
+ } else if (!hasExactRoot && routes.length > 0) {
458
+ const first = routes.find((r) => r.path !== "/" && !r.path.includes(":"));
459
+ if (first) {
460
+ starproRouter.replace(first.path);
461
+ }
462
+ }
463
+ }
464
+ return starproRouter.subscribe(setRouteState);
465
+ }, [routes, defaultRoute]);
466
+ const { pathname, searchParams, params } = routeState;
467
+ const navTabs = routes.filter((r) => Boolean(r.label));
468
+ const shouldShowNav = showNav !== void 0 ? showNav : !CustomLayout && navTabs.length > 0;
469
+ let MatchedComponent = null;
470
+ for (const r of routes) {
471
+ const match = matchRoute(r.path, pathname);
472
+ if (match.matched) {
473
+ MatchedComponent = r.component;
474
+ break;
475
+ }
476
+ }
477
+ const activeTab = navTabs.find((tab) => {
478
+ if (tab.path === pathname) return true;
479
+ if (tab.path !== "/" && pathname.startsWith(tab.path)) return true;
480
+ return false;
481
+ });
482
+ const pageContent = MatchedComponent ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
483
+ MatchedComponent,
484
+ {
485
+ params,
486
+ searchParams,
487
+ payload
488
+ }
489
+ ) : fallback ? fallback : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "p-8 text-center border border-dashed border-zinc-300 dark:border-zinc-700 rounded-xl my-4", children: [
490
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("h3", { className: "text-base font-semibold text-zinc-800 dark:text-zinc-200", children: [
491
+ "Page Not Found (",
492
+ pathname,
493
+ ")"
494
+ ] }),
495
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "text-sm text-zinc-500 mt-1", children: "Rute ini belum didaftarkan di StarPro plugin router." }),
496
+ defaultRoute && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
497
+ "button",
498
+ {
499
+ type: "button",
500
+ onClick: () => starproRouter.push(defaultRoute),
501
+ style: { backgroundColor: themeColor },
502
+ className: "mt-4 px-4 py-2 text-xs font-medium text-white rounded-lg cursor-pointer",
503
+ children: "Kembali ke Beranda"
504
+ }
505
+ )
506
+ ] });
507
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "starpro-universal-router-view w-full min-h-screen text-zinc-900 dark:text-zinc-100", children: [
508
+ shouldShowNav && navTabs.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "sticky top-0 z-30 mb-6 border-b border-zinc-200 bg-white/95 pb-3 pt-2 backdrop-blur dark:border-zinc-800 dark:bg-zinc-900/95", children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex flex-wrap items-center justify-between gap-3", children: [
509
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "flex items-center gap-2.5", children: [
510
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
511
+ "span",
512
+ {
513
+ style: { backgroundColor: themeColor },
514
+ className: "flex h-8 w-8 items-center justify-center rounded-lg font-bold text-white shadow-xs text-xs",
515
+ children: badge || "PRO"
516
+ }
517
+ ),
518
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [
519
+ title && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
520
+ "div",
521
+ {
522
+ style: { color: themeColor },
523
+ className: "text-xs font-semibold tracking-wider uppercase",
524
+ children: title
525
+ }
526
+ ),
527
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "text-xs text-zinc-500 dark:text-zinc-400", children: pathname })
528
+ ] })
529
+ ] }),
530
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "flex flex-wrap items-center gap-1 rounded-xl bg-zinc-100 p-1 dark:bg-zinc-800", children: navTabs.map((tab) => {
531
+ const isActive = activeTab?.path === tab.path;
532
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
533
+ "button",
534
+ {
535
+ type: "button",
536
+ onClick: () => starproRouter.push(tab.path),
537
+ className: `flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium transition-all duration-150 cursor-pointer ${isActive ? "bg-white text-emerald-600 shadow-xs dark:bg-zinc-900 dark:text-emerald-400" : "text-zinc-600 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100"}`,
538
+ children: [
539
+ tab.icon && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: tab.icon }),
540
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: tab.label })
541
+ ]
542
+ },
543
+ tab.path
544
+ );
545
+ }) })
546
+ ] }) }),
547
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "starpro-page-container", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StarProRedirectBoundary, { fallback, children: CustomLayout ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
548
+ CustomLayout,
549
+ {
550
+ params,
551
+ searchParams,
552
+ payload,
553
+ children: pageContent
554
+ }
555
+ ) : pageContent }) })
556
+ ] });
557
+ };
558
+
559
+ // src/react.tsx
560
+ var import_jsx_runtime2 = require("react/jsx-runtime");
561
+ function useStarProAuth() {
562
+ const [authState, setAuthState] = (0, import_react2.useState)(() => {
563
+ if (typeof window === "undefined") {
564
+ return {
565
+ accessToken: null,
566
+ refreshToken: null,
567
+ user: null,
568
+ isPlugin: false,
569
+ isLoading: true
570
+ };
571
+ }
572
+ const token = localStorage.getItem("accessToken") || localStorage.getItem("token");
573
+ const refresh = localStorage.getItem("refreshToken");
574
+ let userObj = null;
575
+ try {
576
+ const storedUser = localStorage.getItem("user");
577
+ if (storedUser) userObj = JSON.parse(storedUser);
578
+ } catch (e) {
579
+ }
580
+ return {
581
+ accessToken: token,
582
+ refreshToken: refresh,
583
+ user: userObj,
584
+ isPlugin: isStarProPlugin(),
585
+ isLoading: false
586
+ };
587
+ });
588
+ return authState;
589
+ }
590
+ var StarProPluginWrapper = ({
591
+ payload,
592
+ children,
593
+ banner = true
594
+ }) => {
595
+ const user = payload?.user;
596
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "starpro-plugin-root", children: [
597
+ banner && user && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
598
+ "div",
599
+ {
600
+ style: {
601
+ background: "#f0fdf4",
602
+ border: "1px solid #bbf7d0",
603
+ color: "#166534",
604
+ padding: "8px 14px",
605
+ fontSize: "12px",
606
+ borderRadius: "8px",
607
+ marginBottom: "16px",
608
+ display: "flex",
609
+ justifyContent: "space-between",
610
+ alignItems: "center",
611
+ fontFamily: "system-ui, -apple-system, sans-serif"
612
+ },
613
+ children: [
614
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { children: [
615
+ "\u2713 Terhubung ke StarPro sebagai: ",
616
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("strong", { children: user.name || user.email })
617
+ ] }),
618
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { style: { fontSize: "11px", opacity: 0.8 }, children: "Login Otomatis Aktif" })
619
+ ]
620
+ }
621
+ ),
622
+ children
623
+ ] });
624
+ };
625
+
626
+ // src/define-app.tsx
627
+ var import_jsx_runtime3 = require("react/jsx-runtime");
628
+ function defineStarProApp(options = {}) {
629
+ const {
630
+ pluginId = "default",
631
+ defaultRoute,
632
+ component: RootComponent,
633
+ layout: CustomLayout,
634
+ title,
635
+ badge,
636
+ themeColor,
637
+ showNav,
638
+ autoInjectAuth = true,
639
+ banner = true,
640
+ fallback,
641
+ render: customRender
642
+ } = options;
643
+ let resolvedRoutes = options.routes || [];
644
+ if (resolvedRoutes.length === 0 && typeof window !== "undefined") {
645
+ if (window.__STARPRO_ROUTES__ && Array.isArray(window.__STARPRO_ROUTES__)) {
646
+ resolvedRoutes = window.__STARPRO_ROUTES__;
647
+ } else {
648
+ try {
649
+ const virtualModule = require("starpro:routes");
650
+ if (virtualModule) {
651
+ resolvedRoutes = virtualModule.default || virtualModule.routes || virtualModule;
652
+ }
653
+ } catch (e) {
654
+ }
655
+ }
656
+ }
657
+ defineStarProPlugin({
658
+ pluginId,
659
+ autoInjectAuth,
660
+ onMount: (container, payload) => {
661
+ let contentNode;
662
+ if (RootComponent) {
663
+ contentNode = /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(RootComponent, { payload });
664
+ } else {
665
+ contentNode = /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
666
+ StarProRouterView,
667
+ {
668
+ routes: resolvedRoutes,
669
+ defaultRoute,
670
+ payload,
671
+ layout: CustomLayout,
672
+ title,
673
+ badge,
674
+ showNav,
675
+ themeColor,
676
+ fallback
677
+ }
678
+ );
679
+ }
680
+ const appTree = /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(StarProPluginWrapper, { payload, banner, children: contentNode });
681
+ if (typeof customRender === "function") {
682
+ const cleanup = customRender(appTree, container);
683
+ return () => {
684
+ if (typeof cleanup === "function") {
685
+ try {
686
+ cleanup();
687
+ } catch (e) {
688
+ }
689
+ }
690
+ container.innerHTML = "";
691
+ };
692
+ }
693
+ const root = (0, import_client.createRoot)(container);
694
+ root.render(appTree);
695
+ return () => {
696
+ try {
697
+ root.unmount();
698
+ } catch (e) {
699
+ }
700
+ container.innerHTML = "";
701
+ };
702
+ }
703
+ });
704
+ }
705
+ var createStarProApp = defineStarProApp;
706
+ // Annotate the CommonJS export names for ESM import in node:
707
+ 0 && (module.exports = {
708
+ StarProPluginWrapper,
709
+ StarProRedirectBoundary,
710
+ StarProRouter,
711
+ StarProRouterView,
712
+ autoRoutesFromGlob,
713
+ createStarProApp,
714
+ defineStarProApp,
715
+ defineStarProPlugin,
716
+ isStarProPlugin,
717
+ matchRoute,
718
+ setupStarProAuthBridge,
719
+ starproRouter,
720
+ useStarProAuth,
721
+ useStarProParams,
722
+ useStarProPathname,
723
+ useStarProRouter,
724
+ useStarProSearchParams
725
+ });