create-fullstack-scaffold 0.4.2 → 0.4.4

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.
Files changed (156) hide show
  1. package/dist/cli/index.js +513 -122
  2. package/dist/cli/index.js.map +1 -1
  3. package/package.json +1 -1
  4. package/template/dist/cli/index.js +237 -94
  5. package/template/dist/cli/index.js.map +1 -1
  6. package/template/dist/client/admin.html +15 -10
  7. package/template/dist/client/assets/App-BpFUIC-5.js +114 -0
  8. package/template/dist/client/assets/{CartPage-DESSHkaG.js → CartPage-DgDZP-R5.js} +2 -2
  9. package/template/dist/client/assets/{CategoriesPage-DqLZ_Mom.js → CategoriesPage-fuYNiSmE.js} +2 -2
  10. package/template/dist/client/assets/ContentDetailPage-BvvFU1Mr.js +1 -0
  11. package/template/dist/client/assets/ContentListPage-ShPxo6WG.js +1 -0
  12. package/template/dist/client/assets/DashboardPage-C1rZzZo4.js +11 -0
  13. package/template/dist/client/assets/{DeveloperDashboardPage-Cum7zFwO.js → DeveloperDashboardPage-_WtmbVoA.js} +2 -2
  14. package/template/dist/client/assets/{EmptyState-BK7ttK8D.js → EmptyState-DEyOQjbY.js} +1 -1
  15. package/template/dist/client/assets/LoadingSpinner-BcHjaM1m.js +6 -0
  16. package/template/dist/client/assets/LoginPage-CjeQqDdO.js +1 -0
  17. package/template/dist/client/assets/LogoutOutlined-ColFAHdd.js +1 -0
  18. package/template/dist/client/assets/NotificationPage-DRkEv02s.js +1 -0
  19. package/template/dist/client/assets/OrdersPage-7I3vPWLP.js +11 -0
  20. package/template/dist/client/assets/{PluginDetailPage-Br24YS4P.js → PluginDetailPage-CWyxdVCg.js} +3 -13
  21. package/template/dist/client/assets/PluginsPage-DRgWLeJT.js +6 -0
  22. package/template/dist/client/assets/ProfilePage-2FFkaii8.js +16 -0
  23. package/template/dist/client/assets/PublishPage-DW7yvROx.js +1 -0
  24. package/template/dist/client/assets/{RegisterPage-rPFG4Sry.js → RegisterPage-Dvaf9b0e.js} +2 -2
  25. package/template/dist/client/assets/SaveOutlined-CLQ2tsSY.js +2 -0
  26. package/template/dist/client/assets/{SearchPage-DQl1U5Uy.js → SearchPage-DvnEyswS.js} +2 -2
  27. package/template/dist/client/assets/{SettingsPage-DaYE80wj.js → SettingsPage-IrU-L9Zr.js} +2 -2
  28. package/template/dist/client/assets/{StatusBadge-BJ3W2Zc7.js → StatusBadge-CG7wVqpu.js} +1 -1
  29. package/template/dist/client/assets/{TodoPage-zC5wWNBa.js → TodoPage-B7D-bl65.js} +3 -3
  30. package/template/dist/client/assets/TopicsPage-CYCNr-mn.js +6 -0
  31. package/template/dist/client/assets/{WebSocketPage-B4NLdz1w.js → WebSocketPage-CGEg6QJE.js} +2 -2
  32. package/template/dist/client/assets/{activity-B94BUAsD.js → activity-CgTz9Mrd.js} +1 -1
  33. package/template/dist/client/assets/admin-D2iHWNOg.js +1 -0
  34. package/template/dist/client/assets/api-request-DIJocPxr.js +356 -0
  35. package/template/dist/client/assets/{arrow-left-H5JH0iU1.js → arrow-left-DtLQ3tTk.js} +1 -1
  36. package/template/dist/client/assets/{chevron-down-DwRh_wjD.js → chevron-down-CpIAV_yr.js} +1 -1
  37. package/template/dist/client/assets/{chevron-right-CpIWaqAL.js → chevron-right-CnU7oPQs.js} +1 -1
  38. package/template/dist/client/assets/{circle-check-big-CSElLscG.js → circle-check-big-CrZdwS75.js} +1 -1
  39. package/template/dist/client/assets/{circle-x-CYxr4RAw.js → circle-x-CvN9r3fW.js} +1 -1
  40. package/template/dist/client/assets/{clock-BseUJ7ex.js → clock-CTeSZBiH.js} +1 -1
  41. package/template/dist/client/assets/{download-BsGC_Xhq.js → download-OSVfVuNV.js} +1 -1
  42. package/template/dist/client/assets/{external-link-UTDzdjq8.js → external-link-fBsuHMby.js} +1 -1
  43. package/template/dist/client/assets/{eye-nR10ui7i.js → eye-CwlZZEsj.js} +1 -1
  44. package/template/dist/client/assets/index-09IqiOaE.css +1 -0
  45. package/template/dist/client/assets/index-B3CRby6r.js +51 -0
  46. package/template/dist/client/assets/index-CC_zy73y.js +17 -0
  47. package/template/dist/client/assets/main-Cn4IDo2I.js +92 -0
  48. package/template/dist/client/assets/merchant-DDDN9bMu.js +40 -0
  49. package/template/dist/client/assets/{message-square-CwWGL-Bh.js → message-square-BRaZfgbJ.js} +1 -1
  50. package/template/dist/client/assets/pluginStore-DDsWJPe6.js +1 -0
  51. package/template/dist/client/assets/{plus-pZld_nUL.js → plus-DDZfPiDJ.js} +1 -1
  52. package/template/dist/client/assets/sse-client-DGQ072hl.js +64 -0
  53. package/template/dist/client/assets/star-C7tO6w4H.js +11 -0
  54. package/template/dist/client/assets/{tag-DsiUPF90.js → tag-DBfpQDuJ.js} +1 -1
  55. package/template/dist/client/assets/tenant-CizbLaLJ.js +1 -0
  56. package/template/dist/client/assets/{trash-2-DRblNbnA.js → trash-2-BP7fkd5b.js} +1 -1
  57. package/template/dist/client/assets/{triangle-alert-D1CLh-Vd.js → triangle-alert-CrOQEdJ2.js} +1 -1
  58. package/template/dist/client/assets/{wifi-BwXjnCqI.js → wifi-CwYSE0J4.js} +1 -1
  59. package/template/dist/client/assets/{x-BH2rJdFq.js → x-t615pnNR.js} +1 -1
  60. package/template/dist/client/content/index.html +5 -4
  61. package/template/dist/client/index.html +4 -3
  62. package/template/dist/client/merchant.html +18 -0
  63. package/template/dist/client/notifications/index.html +6 -5
  64. package/template/dist/client/tenant.html +18 -0
  65. package/template/dist/client/todos/index.html +6 -5
  66. package/template/dist/client/websocket/index.html +6 -5
  67. package/template/dist/cloudflare/chunk-HX7DVRDX.js +1 -0
  68. package/template/dist/cloudflare/{chunk-QBHAPWIA.js → chunk-IXJL2LE4.js} +1 -1
  69. package/template/dist/cloudflare/chunk-Q34AN3RF.js +14 -0
  70. package/template/dist/cloudflare/{chunk-BHPTQ4K2.js → chunk-ZAMVL4EG.js} +2 -2
  71. package/template/dist/cloudflare/cloudflare.js +35 -29
  72. package/template/dist/cloudflare/db-4AQOSFAX.js +1 -0
  73. package/template/dist/cloudflare/{migrator-2ZYYKNI5.js → migrator-TEPBVUFO.js} +1 -1
  74. package/template/dist/cloudflare/permission-service-impl-RE7NPW3Q.js +1 -0
  75. package/template/dist/cloudflare/schema-DVEMT3X2.js +1 -0
  76. package/template/dist/cloudflare/test-setup-Z2RYE5B4.js +265 -0
  77. package/template/dist/server/chunk-27SIJSPF.js +1 -0
  78. package/template/dist/server/chunk-37QNGBQU.js +1 -0
  79. package/template/dist/server/chunk-FIY4CGJJ.js +1 -0
  80. package/template/dist/server/chunk-HZUDBIT4.js +1 -0
  81. package/template/dist/server/chunk-I6OBDFDU.js +1 -0
  82. package/template/dist/server/chunk-JHNYLNG7.js +1 -0
  83. package/template/dist/server/chunk-MDOVVKKD.js +1 -0
  84. package/template/dist/server/chunk-NSOCT7E5.js +1 -0
  85. package/template/dist/server/chunk-OU5IGVVO.js +1 -0
  86. package/template/dist/server/chunk-OYCBNRMK.js +1 -0
  87. package/template/dist/server/chunk-P2RJNNGD.js +1 -0
  88. package/template/dist/server/chunk-UMAQLNPE.js +1 -0
  89. package/template/dist/server/chunk-XZZTSRSN.js +1 -0
  90. package/template/dist/server/content-service-5QVHDR5X.js +1 -0
  91. package/template/dist/server/db-FLI5L5DD.js +1 -0
  92. package/template/dist/server/dispute-service-E2FCYUEM.js +1 -0
  93. package/template/dist/server/init-72JXJV3I.js +46 -0
  94. package/template/dist/server/init-FWYXSKPX.js +46 -0
  95. package/template/dist/server/node.js +34 -28
  96. package/template/dist/server/order-service-TKGG5S5K.js +1 -0
  97. package/template/dist/server/permission-service-impl-M3AKEYNY.js +1 -0
  98. package/template/dist/server/schema-V4UG7HMU.js +1 -0
  99. package/template/dist/server/tenant-service-JG6UUWXQ.js +1 -0
  100. package/template/dist/server/tenant-service-XJWZSEDX.js +1 -0
  101. package/template/dist/{cloudflare/test-setup-NMZJZLRV.js → server/test-setup-VFOPBGYM.js} +83 -2
  102. package/template/dist/server/ticket-service-3RSW7V2Z.js +1 -0
  103. package/template/dist/server/todo-service-S6BGIO7D.js +1 -0
  104. package/template/package.json +1 -1
  105. package/template/src/client/App.tsx +3 -1
  106. package/template/src/client/pages/ContentListPage.tsx +36 -4
  107. package/template/src/client/pages/PluginsPage.tsx +112 -20
  108. package/template/src/client/pages/TodoPage.tsx +9 -1
  109. package/template/src/client/preset-ui-config.ts +79 -2
  110. package/template/src/merchant/pages/DisputesPage.tsx +11 -11
  111. package/template/src/merchant/pages/OrdersPage.tsx +4 -3
  112. package/template/src/merchant/pages/ProductsPage.tsx +2 -2
  113. package/template/src/merchant/stores/merchantStore.ts +11 -6
  114. package/template/src/server/db/init.ts +5 -253
  115. package/template/src/server/module-content/routes/topics-routes.ts +250 -0
  116. package/template/src/server/module-content/services/content-service.ts +1 -1
  117. package/template/src/server/module-plugin/services/plugin-seed-service.ts +623 -0
  118. package/template/src/server/module-tenant/routes/tenant-routes.ts +2 -2
  119. package/template/src/server/module-tenant/services/tenant-service.ts +63 -17
  120. package/template/src/server/module-todos/services/todo-service.ts +1 -1
  121. package/template/src/shared/modules/merchant/index.ts +9 -0
  122. package/template/src/shared/modules/merchant/schemas.ts +37 -0
  123. package/template/src/shared/modules/tenant/index.ts +2 -0
  124. package/template/src/shared/schemas/index.ts +27 -0
  125. package/template/src/tenant/layouts/Header.tsx +1 -1
  126. package/template/src/tenant/layouts/Sidebar.tsx +1 -1
  127. package/template/src/tenant/pages/SettingsPage.tsx +4 -8
  128. package/template/src/tenant/stores/tenantStore.ts +41 -302
  129. package/template/tsconfig.json +1 -0
  130. package/template/tsup.config.ts +11 -3
  131. package/template/dist/client/assets/ContentDetailPage-DdltMANL.js +0 -1
  132. package/template/dist/client/assets/ContentListPage-B63sUB6N.js +0 -1
  133. package/template/dist/client/assets/DashboardPage-tUMilc7Z.js +0 -11
  134. package/template/dist/client/assets/LoadingSpinner-DVYOLSRM.js +0 -6
  135. package/template/dist/client/assets/LoginPage-g9mSLIMC.js +0 -6
  136. package/template/dist/client/assets/NotificationPage-COTzp-HD.js +0 -1
  137. package/template/dist/client/assets/OrdersPage-BsPh4oEI.js +0 -11
  138. package/template/dist/client/assets/PluginsPage-BNtAe_yo.js +0 -6
  139. package/template/dist/client/assets/ProfilePage-dL_iSuZN.js +0 -16
  140. package/template/dist/client/assets/PublishPage-D96FnbLA.js +0 -1
  141. package/template/dist/client/assets/TopicsPage-DyLjZa4D.js +0 -6
  142. package/template/dist/client/assets/admin-Bh1vfz_L.js +0 -486
  143. package/template/dist/client/assets/index-1bA-ixFv.js +0 -114
  144. package/template/dist/client/assets/index-CWh3vXC_.css +0 -1
  145. package/template/dist/client/assets/main-DHnArIp_.js +0 -82
  146. package/template/dist/client/assets/pluginStore-XQfsm3iR.js +0 -1
  147. package/template/dist/client/content/content-1/index.html +0 -18
  148. package/template/dist/client/content/content-13/index.html +0 -18
  149. package/template/dist/client/content/content-14/index.html +0 -18
  150. package/template/dist/client/content/content-15/index.html +0 -18
  151. package/template/dist/client/content/content-19/index.html +0 -18
  152. package/template/dist/client/content/content-2/index.html +0 -18
  153. package/template/dist/client/content/content-20/index.html +0 -18
  154. package/template/dist/cloudflare/chunk-YY6FRMAQ.js +0 -14
  155. package/template/dist/cloudflare/db-7J42RQ3T.js +0 -1
  156. package/template/dist/cloudflare/permission-service-impl-TGXVSSSA.js +0 -1
@@ -1,44 +1,50 @@
1
- import {b as b$1,a,c as c$5}from'./chunk-FMFYN7XK.js';import {d as d$2,e as e$1,t,n,o,p,q as q$1,r,m as m$1,b as b$2,c as c$1,f as f$3,g as g$2,h as h$2,i,j as j$2,k as k$2,l as l$1,a as a$2}from'./chunk-QA3BGGM3.js';import {b as b$3,c as c$2,d as d$3,e as e$2,f as f$1,g as g$1,h as h$1,j,k,l,m as m$2,n as n$1,o as o$1,p as p$1,r as r$1,s as s$1,t as t$1,u,v,w,I,A,B as B$1,C as C$1,D as D$1,E,F,G,y,x,H as H$1}from'./chunk-XM6RLKK6.js';import {d as d$1,a as a$1,c as c$4}from'./chunk-JCPOP4XL.js';import {e,h,g,b,N,H,c as c$3,f as f$2,I as I$1,j as j$1,k as k$1,s as s$2,J,a as a$3,L as L$1}from'./chunk-BDLK3LCW.js';import {c as c$6}from'./chunk-5J6HXUF6.js';import {serve}from'@hono/node-server';import {serveStatic}from'@hono/node-server/serve-static';import {resolve,extname,join}from'path';import {existsSync,readFileSync}from'fs';import {WebSocketServer}from'ws';import {z,createRoute,OpenAPIHono}from'@hono/zod-openapi';import {HTTPException}from'hono/http-exception';import {ZodError}from'zod';import {cors}from'hono/cors';import xi from'jsonwebtoken';import {getCookie,setCookie}from'hono/cookie';import {timingSafeEqual,randomUUID,createHmac}from'crypto';import {desc,eq,and,gte,lte}from'drizzle-orm';import {stat,readFile,writeFile,unlink,mkdir}from'fs/promises';import Ja from'bcryptjs';e();e();h();var V=class e extends Error{code;statusCode;details;cause;logLevel;timestamp;constructor(t){super(t.message),this.name="AppError",this.code=t.code,this.statusCode=t.statusCode,this.details=t.details,this.cause=t.cause,this.logLevel=t.logLevel??"warn",this.timestamp=new Date().toISOString(),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor);}toJSON(){return {success:false,error:this.message,code:this.code,status:this.statusCode,details:this.details,timestamp:this.timestamp}}static isAppError(t){return t instanceof e}},$e=class extends V{constructor(t,r){super({code:"VALIDATION_ERROR",message:t,statusCode:400,details:r,logLevel:"info"}),this.name="ValidationError";}},He=class e extends V{constructor(t="Unauthorized",r="UNAUTHORIZED"){super({code:r,message:t,statusCode:401,logLevel:"warn"}),this.name="AuthenticationError";}static tokenExpired(){return new e("Token has expired","TOKEN_EXPIRED")}static tokenInvalid(){return new e("Invalid token","TOKEN_INVALID")}static tokenMissing(){return new e("Authentication token is required","TOKEN_MISSING")}},ie=class e extends V{constructor(t="Forbidden",r){super({code:"FORBIDDEN",message:t,statusCode:403,details:r,logLevel:"warn"}),this.name="AuthorizationError";}static permissionDenied(t){return new e(t?`Permission denied: ${t}`:"Permission denied",t?[{message:`Missing required permission: ${t}`}]:void 0)}static insufficientRole(t,r){return new e("Insufficient role privileges",t&&r?[{message:`Role '${t}' does not meet required role '${r}'`}]:void 0)}},f=class e extends V{constructor(t,r){super({code:"NOT_FOUND",message:r?`${t} not found: ${r}`:`${t} not found`,statusCode:404,logLevel:"info"}),this.name="NotFoundError";}static user(t){return new e("User",t)}static order(t){return new e("Order",t)}static dispute(t){return new e("Dispute",t)}static ticket(t){return new e("Ticket",t)}};var me=class e extends V{constructor(t,r="BUSINESS_ERROR",o){super({code:r,message:t,statusCode:422,details:o,logLevel:"info"}),this.name="BusinessError";}static invalidState(t,r){return new e("Invalid state transition","INVALID_STATE",[{message:`Current state '${t}' is not valid. Expected one of: ${r.join(", ")}`}])}static operationNotAllowed(t){return new e(`Operation not allowed: ${t}`,"OPERATION_NOT_ALLOWED")}};function ts(e){let t;try{t=b$1();}catch{return}let r;try{r=e.getOpenAPIDocument({openapi:"3.0.0",info:{title:"API",version:"1.0.0"}});}catch{return}let o=r.paths;if(!o)return;let n=new Set;for(let[i,a]of Object.entries(o)){if(!a)continue;let u=a.get;if(!u?.responses)continue;let p=u.responses[200]?.content;if(!p)continue;let T="websocket"in p,P="text/event-stream"in p;if(T){let O=i.startsWith("/")?i:`/${i}`;n.has(O)||(t.handleWS(O),n.add(O));}if(P){let O=i.startsWith("/")?i:`/${i}`;n.has(O)||(t.handleSSE(O),n.add(O));}}}var Ri={origin:process.env.NODE_ENV==="production"?process.env.CORS_ORIGIN?.split(",")||[]:["http://localhost:5173","http://localhost:3010"],credentials:true,allowMethods:["GET","POST","PUT","PATCH","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization"]};function fr(e={}){let t={...Ri,...e};return cors(t)}h();var wi={logRequests:true,logResponses:true,logErrors:true,excludePaths:["/health"]};function gr(e={}){let t={...wi,...e},r=f$2("api");return async(o,n)=>{let{req:i}=o,a=new URL(i.url).pathname;if(t.excludePaths?.some(l=>a.startsWith(l)))return n();let u=Date.now();if(t.logRequests){let l={method:i.method,path:a,userAgent:i.header("user-agent")};r.info(l,"Request started");}try{if(await n(),t.logResponses){let l=Date.now()-u,p={method:i.method,path:a,status:o.res?.status,duration:`${l}ms`};r.info(p,"Request completed");}}catch(l){if(t.logErrors){let p=Date.now()-u,T={method:i.method,path:a,error:l instanceof Error?l.message:"Unknown error",duration:`${p}ms`};r.error(T,"Request failed");}throw l}}}h();var Ei={includeStackTrace:false,logErrors:true};function bi(e){return e.issues.map(t=>({field:t.path.join("."),message:t.message,code:t.code}))}function yr(e,t,r){let o={success:false,error:t,status:e};return r&&(o.details=r),o}function Sr(e={}){let t={...Ei,...e},r=f$2("api");return async(o,n)=>{try{await n();}catch(i){if(o.res.headers.set("Content-Type","application/json"),V.isAppError(i)){if(t.logErrors){let l={errorType:i.name,code:i.code,message:i.message,status:i.statusCode,path:o.req.path,method:o.req.method};r.warn(l,i.message);}return o.json(yr(i.statusCode,i.message,i.details),i.statusCode)}if(i instanceof ZodError){let l=bi(i);if(t.logErrors){let p={errorType:"ZodError",errors:l,path:o.req.path,method:o.req.method};r.warn(p,"Validation error");}return o.json(yr(400,"Validation failed",l),400)}if(i instanceof HTTPException){if(t.logErrors){let T={errorType:"HTTPException",error:i.message,status:i.status,path:o.req.path,method:o.req.method,cause:i.cause};r.warn(T,"HTTP exception");}let l=i.status||500,p=i.message||"Internal server error";return o.json(yr(l,p),l)}if(t.logErrors){let l={errorType:"UnknownError",error:i instanceof Error?i.message:"Unknown error",stack:i instanceof Error?i.stack:void 0,path:o.req.path,method:o.req.method};r.error(l,"Unhandled error");}let u={success:false,error:i instanceof Error?i.message:"Internal server error",status:500};return t.includeStackTrace&&i instanceof Error&&i.stack&&(u.stack=i.stack),o.json(u,500)}}}h();var ft="dev-secret-key-change-in-production",rs=process.env.AUTH_SECRET_KEY||ft;rs===ft&&process.env.NODE_ENV==="production"&&console.error(`\u26A0\uFE0F SECURITY WARNING: AUTH_SECRET_KEY is using the default value in production!
1
+ import {b as b$6,c as c$4,d as d$4,e as e$5,f as f$2,h as h$5}from'./chunk-P2RJNNGD.js';import {l as l$1,d as d$5,e as e$6,f as f$3,g as g$4,h as h$6,i,j as j$1,b as b$8,a as a$2,k as k$3}from'./chunk-XZZTSRSN.js';import {e as e$1,b as b$1,g as g$3,d as d$6,c as c$7,f as f$7,a as a$7}from'./chunk-MDOVVKKD.js';import {a as a$6}from'./chunk-NSOCT7E5.js';import {b as b$2,a as a$3,c as c$9}from'./chunk-FMFYN7XK.js';import {d as d$1,e as e$2,t,n as n$1,o as o$1,p as p$2,q as q$2,r as r$1,m as m$1,b as b$3,c as c$1,f as f$6,g as g$6,h as h$7,i as i$1,j as j$2,k as k$1,l as l$2,a as a$4}from'./chunk-37QNGBQU.js';import {j,k,l,m,n,o,p as p$1,q as q$1,r,h as h$2,g as g$5,c as c$5,b as b$7,e as e$7,f as f$4,d as d$7,a as a$1}from'./chunk-OU5IGVVO.js';import {b as b$4,c as c$2,d as d$2,e as e$3,f,g as g$1,h as h$3}from'./chunk-HZUDBIT4.js';import {b as b$5,c as c$3,d as d$3,e as e$4,f as f$1,g as g$2,h as h$4}from'./chunk-JHNYLNG7.js';import'./chunk-I6OBDFDU.js';import'./chunk-FIY4CGJJ.js';import {d,c as c$8,a as a$5}from'./chunk-JCPOP4XL.js';import {a}from'./chunk-UMAQLNPE.js';import {e,h as h$1,g,b,c as c$6,f as f$5,i as i$2,j as j$3,l as l$3,a as a$8}from'./chunk-OYCBNRMK.js';import {J,k as k$2,z as z$2,C,F,G,D,E}from'./chunk-27SIJSPF.js';import {c as c$a}from'./chunk-5J6HXUF6.js';import {serve}from'@hono/node-server';import {serveStatic}from'@hono/node-server/serve-static';import {resolve}from'path';import {existsSync,readFileSync}from'fs';import {WebSocketServer}from'ws';import {z as z$1,createRoute,OpenAPIHono}from'@hono/zod-openapi';import {HTTPException}from'hono/http-exception';import {ZodError}from'zod';import {cors}from'hono/cors';import fp from'jsonwebtoken';import {getCookie,setCookie}from'hono/cookie';import {randomUUID}from'crypto';import {desc,eq,and,gte,lte,or,asc,like,sql}from'drizzle-orm';import An,{hashSync,compareSync}from'bcryptjs';e();e();h$1();function Qs(e){let t;try{t=b$2();}catch{return}let r;try{r=e.getOpenAPIDocument({openapi:"3.0.0",info:{title:"API",version:"1.0.0"}});}catch{return}let o=r.paths;if(!o)return;let n=new Set;for(let[i,u]of Object.entries(o)){if(!u)continue;let d=u.get;if(!d?.responses)continue;let m=d.responses[200]?.content;if(!m)continue;let R="websocket"in m,v="text/event-stream"in m;if(R){let P=i.startsWith("/")?i:`/${i}`;n.has(P)||(t.handleWS(P),n.add(P));}if(v){let P=i.startsWith("/")?i:`/${i}`;n.has(P)||(t.handleSSE(P),n.add(P));}}}var up={origin:process.env.NODE_ENV==="production"?process.env.CORS_ORIGIN?.split(",")||[]:["http://localhost:5173","http://localhost:3010"],credentials:true,allowMethods:["GET","POST","PUT","PATCH","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization"]};function Io(e={}){let t={...up,...e};return cors(t)}h$1();var dp={logRequests:true,logResponses:true,logErrors:true,excludePaths:["/health"]};function ko(e={}){let t={...dp,...e},r=f$5("api");return async(o,n)=>{let{req:i}=o,u=new URL(i.url).pathname;if(t.excludePaths?.some(l=>u.startsWith(l)))return n();let d=Date.now();if(t.logRequests){let l={method:i.method,path:u,userAgent:i.header("user-agent")};r.info(l,"Request started");}try{if(await n(),t.logResponses){let l=Date.now()-d,m={method:i.method,path:u,status:o.res?.status,duration:`${l}ms`};r.info(m,"Request completed");}}catch(l){if(t.logErrors){let m=Date.now()-d,R={method:i.method,path:u,error:l instanceof Error?l.message:"Unknown error",duration:`${m}ms`};r.error(R,"Request failed");}throw l}}}h$1();var gp={includeStackTrace:false,logErrors:true};function hp(e){return e.issues.map(t=>({field:t.path.join("."),message:t.message,code:t.code}))}function Uo(e,t,r){let o={success:false,error:t,status:e};return r&&(o.details=r),o}function jo(e={}){let t={...gp,...e},r=f$5("api");return async(o,n)=>{try{await n();}catch(i){if(o.res.headers.set("Content-Type","application/json"),a$7.isAppError(i)){if(t.logErrors){let l={errorType:i.name,code:i.code,message:i.message,status:i.statusCode,path:o.req.path,method:o.req.method};r.warn(l,i.message);}return o.json(Uo(i.statusCode,i.message,i.details),i.statusCode)}if(i instanceof ZodError){let l=hp(i);if(t.logErrors){let m={errorType:"ZodError",errors:l,path:o.req.path,method:o.req.method};r.warn(m,"Validation error");}return o.json(Uo(400,"Validation failed",l),400)}if(i instanceof HTTPException){if(t.logErrors){let R={errorType:"HTTPException",error:i.message,status:i.status,path:o.req.path,method:o.req.method,cause:i.cause};r.warn(R,"HTTP exception");}let l=i.status||500,m=i.message||"Internal server error";return o.json(Uo(l,m),l)}if(t.logErrors){let l={errorType:"UnknownError",error:i instanceof Error?i.message:"Unknown error",stack:i instanceof Error?i.stack:void 0,path:o.req.path,method:o.req.method};r.error(l,"Unhandled error");}let d={success:false,error:i instanceof Error?i.message:"Internal server error",status:500};return t.includeStackTrace&&i instanceof Error&&i.stack&&(d.stack=i.stack),o.json(d,500)}}}h$1();var nr="dev-secret-key-change-in-production",Js=process.env.AUTH_SECRET_KEY||nr;Js===nr&&process.env.NODE_ENV==="production"&&console.error(`\u26A0\uFE0F SECURITY WARNING: AUTH_SECRET_KEY is using the default value in production!
2
2
  Please set a strong AUTH_SECRET_KEY environment variable.
3
- Dev tokens should NEVER be used in production.`);var os=()=>process.env.ENABLE_DEV_TOKENS==="true"?true:!(process.env.ENABLE_DEV_TOKENS==="false"||process.env.NODE_ENV==="production");os()&&console.warn("\u26A0\uFE0F WARNING: Dev tokens are ENABLED. Do not use in production!");function Ci(e){return !e||!e.startsWith("Bearer ")?null:e.slice(7)}function Ai(e){return e==="admin-token"||e==="super-admin-token"?{id:"super-admin-1",username:"superadmin",email:"superadmin@example.com",role:"super_admin",permissions:a$2("super_admin")}:e==="customer-service-token"?{id:"customer-service-1",username:"customerservice",email:"cs@example.com",role:"customer_service",permissions:a$2("customer_service")}:e==="user-token"?{id:"user-1",username:"user",email:"user@example.com",role:"user",permissions:a$2("user")}:e.startsWith("test-super-admin-")?{id:e,username:`superadmin-${e}`,email:`superadmin-${e}@example.com`,role:"super_admin",permissions:a$2("super_admin")}:e.startsWith("test-customer-service-")?{id:e,username:`cs-${e}`,email:`cs-${e}@example.com`,role:"customer_service",permissions:a$2("customer_service")}:e.startsWith("test-user-")?{id:e,username:`user-${e}`,email:`user-${e}@example.com`,role:"user",permissions:a$2("user")}:null}function Ii(e,t){if(t===ft&&os()){let r=Ai(e);if(r)return f$2("auth").warn({userId:r.id,role:r.role},"DEV TOKEN USED - This should not appear in production!"),r}if(t!==ft)try{let r=xi.verify(e,t);return {id:r.userId,username:r.username,email:r.email,role:r.role,permissions:a$2(r.role)}}catch{return null}return null}function m(e={}){let t=e.secretKey??rs,r=f$2("auth");return async(o,n)=>{let i=o.req.header("Authorization"),a=Ci(i);if(!a)throw r.warn({path:o.req.path,method:o.req.method},"Missing auth token"),He.tokenMissing();let u=Ii(a,t);if(!u)throw r.warn({path:o.req.path,method:o.req.method},"Invalid auth token"),He.tokenInvalid();if(r.info({userId:u.id,role:u.role,path:o.req.path},"User authenticated"),e.requiredRole){let l={super_admin:3,customer_service:2,user:1},p=l[u.role],T=l[e.requiredRole];if(p<T)throw r.warn({path:o.req.path,method:o.req.method,userRole:u.role,requiredRole:e.requiredRole},"Insufficient role"),ie.insufficientRole(u.role,e.requiredRole)}if(e.requiredPermissions&&e.requiredPermissions.length>0){let{permissionService:l}=await import('./permission-service-impl-7GOJPMMF.js');for(let p of e.requiredPermissions)if(!await l.hasPermission(u.id,p,u.role))throw r.warn({path:o.req.path,method:o.req.method,userId:u.id,requiredPermission:p},"Insufficient permission"),ie.permissionDenied(p)}o.set("authUser",u),await n();}}var ns=1e3,Oi=300*1e3,Y=new Map;function Di(){let e=Date.now();for(let[t,r]of Y)e-r.createdAt>Oi&&Y.delete(t);if(Y.size>ns){let r=[...Y.entries()].sort((o,n)=>o[1].createdAt-n[1].createdAt).slice(0,Y.size-ns);for(let[o]of r)Y.delete(o);}}function Rr(e={}){let{skipPaths:t=["/api/captcha","/api/verify-captcha","/api/admin/login","/api/admin/register"],maxRequests:r=10,windowMs:o=6e4}=e;return async(n,i)=>{if(process.env.NODE_ENV==="test")return i();Di();let a=n.req.path;if(t.some(T=>a.startsWith(T)))return i();let u=getCookie(n,"session_id")||ki();getCookie(n,"session_id")||setCookie(n,"session_id",u,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"Strict",maxAge:86400});let l=Date.now(),p=Y.get(u)||{verified:false,requestCount:0,windowStart:l,createdAt:l};return l-p.windowStart>o&&(p.requestCount=0,p.windowStart=l),p.requestCount++,Y.set(u,p),p.verified&&p.verifiedAt&&l-p.verifiedAt<3e5?i():p.requestCount>r?n.json({success:false,error:"\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u5B8C\u6210\u9A8C\u8BC1\u7801\u9A8C\u8BC1",needCaptcha:true},429):qi(n)?n.json({success:false,error:"\u68C0\u6D4B\u5230\u53EF\u7591\u884C\u4E3A\uFF0C\u8BF7\u5B8C\u6210\u9A8C\u8BC1\u7801\u9A8C\u8BC1",needCaptcha:true},403):i()}}function ki(){return randomUUID()}function qi(e){let t=e.req.header("User-Agent")||"";return !!(!t||t.length<10||t.includes("bot")||t.includes("crawler"))}function wr(e){let t=Y.get(e);t&&(t.verified=true,t.verifiedAt=Date.now(),t.requestCount=0,t.windowStart=Date.now(),Y.set(e,t));}var Ni=[{id:"1",username:"superadmin",email:"superadmin@example.com",role:"super_admin",status:"active",avatar:"https://api.dicebear.com/7.x/avataaars/svg?seed=superadmin",createdAt:"2024-01-01T00:00:00Z",updatedAt:"2024-01-01T00:00:00Z"},{id:"2",username:"customerservice",email:"customerservice@example.com",role:"customer_service",status:"active",avatar:"https://api.dicebear.com/7.x/avataaars/svg?seed=customerservice",createdAt:"2024-01-02T00:00:00Z",updatedAt:"2024-01-02T00:00:00Z"},{id:"3",username:"user1",email:"user1@example.com",role:"user",status:"active",avatar:"https://api.dicebear.com/7.x/avataaars/svg?seed=user1",createdAt:"2024-01-03T00:00:00Z",updatedAt:"2024-01-03T00:00:00Z"}];function M(e){return e.get("authUser")}function ae(){return Ni}h();g.api();var gt=new Map,is=Date.now();function ji(){let e=Date.now();if(!(e-is<6e4)){is=e;for(let[t,r]of gt)r.resetAt<=e&&gt.delete(t);}}function Ae(e={}){let t=e.windowMs??6e4,r=e.max??100,o=e.message??"Too many requests";return async(n,i)=>{if(process.env.NODE_ENV==="test")return i();ji();let a=n.req.header("x-forwarded-for")?.split(",")[0]?.trim()||n.req.header("x-real-ip")||"unknown",u=Date.now(),l=gt.get(a);if(l&&l.resetAt>u&&l.count>=r)return n.header("Retry-After",String(Math.ceil((l.resetAt-u)/1e3))),n.json({success:false,error:o},429);!l||l.resetAt<=u?gt.set(a,{count:1,resetAt:u+t}):l.count++,await i();}}var Ie=Ae({windowMs:15*6e4,max:5,message:"Too many attempts, please try again later"}),as=Ae({windowMs:6e4,max:20,message:"Too many upload requests, please slow down"});Ae({windowMs:6e4,max:100});b();function Ge(){let e=new Map,t=new Map,r=new Map,o=new Map,n=(l,p=[],T="notification")=>{let P=JSON.stringify(l),O=`event: ${T}
4
- data: ${P}
3
+ Dev tokens should NEVER be used in production.`);var Ys=()=>process.env.ENABLE_DEV_TOKENS==="true"?true:!(process.env.ENABLE_DEV_TOKENS==="false"||process.env.NODE_ENV==="production");Ys()&&console.warn("\u26A0\uFE0F WARNING: Dev tokens are ENABLED. Do not use in production!");function yp(e){return !e||!e.startsWith("Bearer ")?null:e.slice(7)}function Sp(e){return e==="admin-token"||e==="super-admin-token"?{id:"super-admin-1",username:"superadmin",email:"superadmin@example.com",role:"super_admin",permissions:a$4("super_admin")}:e==="customer-service-token"?{id:"customer-service-1",username:"customerservice",email:"cs@example.com",role:"customer_service",permissions:a$4("customer_service")}:e==="user-token"?{id:"user-1",username:"user",email:"user@example.com",role:"user",permissions:a$4("user")}:e.startsWith("test-super-admin-")?{id:e,username:`superadmin-${e}`,email:`superadmin-${e}@example.com`,role:"super_admin",permissions:a$4("super_admin")}:e.startsWith("test-customer-service-")?{id:e,username:`cs-${e}`,email:`cs-${e}@example.com`,role:"customer_service",permissions:a$4("customer_service")}:e.startsWith("test-user-")?{id:e,username:`user-${e}`,email:`user-${e}@example.com`,role:"user",permissions:a$4("user")}:null}function wp(e,t){if(t===nr&&Ys()){let r=Sp(e);if(r)return f$5("auth").warn({userId:r.id,role:r.role},"DEV TOKEN USED - This should not appear in production!"),r}if(t!==nr)try{let r=fp.verify(e,t);return {id:r.userId,username:r.username,email:r.email,role:r.role,permissions:a$4(r.role)}}catch{return null}return null}function h(e={}){let t=e.secretKey??Js,r=f$5("auth");return async(o,n)=>{let i=o.req.header("Authorization"),u=yp(i);if(!u)throw r.warn({path:o.req.path,method:o.req.method},"Missing auth token"),c$7.tokenMissing();let d=wp(u,t);if(!d)throw r.warn({path:o.req.path,method:o.req.method},"Invalid auth token"),c$7.tokenInvalid();if(r.info({userId:d.id,role:d.role,path:o.req.path},"User authenticated"),e.requiredRole){let l={super_admin:3,customer_service:2,user:1},m=l[d.role],R=l[e.requiredRole];if(m<R)throw r.warn({path:o.req.path,method:o.req.method,userRole:d.role,requiredRole:e.requiredRole},"Insufficient role"),d$6.insufficientRole(d.role,e.requiredRole)}if(e.requiredPermissions&&e.requiredPermissions.length>0){let{permissionService:l}=await import('./permission-service-impl-M3AKEYNY.js');for(let m of e.requiredPermissions)if(!await l.hasPermission(d.id,m,d.role))throw r.warn({path:o.req.path,method:o.req.method,userId:d.id,requiredPermission:m},"Insufficient permission"),d$6.permissionDenied(m)}o.set("authUser",d),await n();}}var Xs=1e3,bp=300*1e3,he=new Map;function xp(){let e=Date.now();for(let[t,r]of he)e-r.createdAt>bp&&he.delete(t);if(he.size>Xs){let r=[...he.entries()].sort((o,n)=>o[1].createdAt-n[1].createdAt).slice(0,he.size-Xs);for(let[o]of r)he.delete(o);}}function qo(e={}){let{skipPaths:t=["/api/captcha","/api/verify-captcha","/api/admin/login","/api/admin/register"],maxRequests:r=10,windowMs:o=6e4,forceEnabled:n=false}=e;return async(i,u)=>{if(!n&&process.env.NODE_ENV==="test")return u();xp();let l=i.req.path;if(t.some(P=>l.startsWith(P)))return u();let m=getCookie(i,"session_id")||Cp();getCookie(i,"session_id")||setCookie(i,"session_id",m,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"Strict",maxAge:86400});let R=Date.now(),v=he.get(m)||{verified:false,requestCount:0,windowStart:R,createdAt:R};return R-v.windowStart>o&&(v.requestCount=0,v.windowStart=R),v.requestCount++,he.set(m,v),v.verified&&v.verifiedAt&&R-v.verifiedAt<3e5?u():v.requestCount>r?i.json({success:false,error:"\u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u5B8C\u6210\u9A8C\u8BC1\u7801\u9A8C\u8BC1",needCaptcha:true},429):Tp(i,n)?i.json({success:false,error:"\u68C0\u6D4B\u5230\u53EF\u7591\u884C\u4E3A\uFF0C\u8BF7\u5B8C\u6210\u9A8C\u8BC1\u7801\u9A8C\u8BC1",needCaptcha:true},403):u()}}function Cp(){return randomUUID()}function Tp(e,t=false){if(!t&&(process.env.NODE_ENV==="test"||process.env.NODE_ENV==="development"))return false;let r=e.req.header("User-Agent")||"";return !!(!r||r.length<10||r.toLowerCase().includes("bot")||r.toLowerCase().includes("crawler"))}function Do(e){let t=he.get(e);t&&(t.verified=true,t.verifiedAt=Date.now(),t.requestCount=0,t.windowStart=Date.now(),he.set(e,t));}var Pp=[{id:"1",username:"superadmin",email:"superadmin@example.com",role:"super_admin",status:"active",avatar:"https://api.dicebear.com/7.x/avataaars/svg?seed=superadmin",createdAt:"2024-01-01T00:00:00Z",updatedAt:"2024-01-01T00:00:00Z"},{id:"2",username:"customerservice",email:"customerservice@example.com",role:"customer_service",status:"active",avatar:"https://api.dicebear.com/7.x/avataaars/svg?seed=customerservice",createdAt:"2024-01-02T00:00:00Z",updatedAt:"2024-01-02T00:00:00Z"},{id:"3",username:"user1",email:"user1@example.com",role:"user",status:"active",avatar:"https://api.dicebear.com/7.x/avataaars/svg?seed=user1",createdAt:"2024-01-03T00:00:00Z",updatedAt:"2024-01-03T00:00:00Z"}],Ap=new Map([["super-admin-token","1"],["customer-service-token","2"],["user-token","3"]]),Ep=new Map;function L(e){return e.get("authUser")}function Ae(){return Pp}function ei(){return Ap}function Oo(){return Ep}h$1();g.api();var sr=new Map,ti=Date.now();function Ip(){let e=Date.now();if(!(e-ti<6e4)){ti=e;for(let[t,r]of sr)r.resetAt<=e&&sr.delete(t);}}function Ze(e={}){let t=e.windowMs??6e4,r=e.max??100,o=e.message??"Too many requests";return async(n,i)=>{if(process.env.NODE_ENV==="test")return i();Ip();let u=n.req.header("x-forwarded-for")?.split(",")[0]?.trim()||n.req.header("x-real-ip")||"unknown",d=Date.now(),l=sr.get(u);if(l&&l.resetAt>d&&l.count>=r)return n.header("Retry-After",String(Math.ceil((l.resetAt-d)/1e3))),n.json({success:false,error:o},429);!l||l.resetAt<=d?sr.set(u,{count:1,resetAt:d+t}):l.count++,await i();}}var Xe=Ze({windowMs:15*6e4,max:5,message:"Too many attempts, please try again later"}),ri=Ze({windowMs:6e4,max:20,message:"Too many upload requests, please slow down"});Ze({windowMs:6e4,max:100});b();function xt(){let e=new Map,t=new Map,r=new Map,o=new Map,n=(l,m=[],R="notification")=>{let v=JSON.stringify(l),P=`event: ${R}
4
+ data: ${v}
5
5
 
6
- `;for(let[G,cr]of e)if(!p.includes(G))try{cr.send({type:T,payload:l});}catch{e.delete(G);}for(let[G,cr]of t)if(!p.includes(G))try{cr.send(O);}catch{t.delete(G);}};return {wsClients:e,sseClients:t,broadcast:n,handleWSMessage:(l,p)=>{let T=e.get(l);if(T){if(typeof p=="object"&&p!==null&&"method"in p&&"id"in p){let P=p,O=r.get(P.method);if(O)try{let G=O(P.params,l);T.send({id:P.id,result:G});}catch(G){T.send({id:P.id,error:G instanceof Error?G.message:"Unknown error"});}else T.send({id:P.id,error:`Unknown method: ${P.method}`});return}if(typeof p=="object"&&p!==null&&"type"in p){let P=p,O=o.get(P.type);O&&O(P.payload,l,n);}}},registerRPCHandler:(l,p)=>{r.set(l,p);},registerEventHandler:(l,p)=>{o.set(l,p);}}}function vr(e){return {path:e,get adapter(){return c$5.adapter},registerRPC(t,r){let o=(n,i)=>r(n,i);c$5.registerRPC(t,o);},registerEvent(t,r){let o=(n,i)=>{r(n,i);};c$5.registerEvent(t,o);},broadcast(t,r,o){c$5.broadcast(t,r,o);}}}function Ke(){return typeof globalThis<"u"&&globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():randomUUID()}var Er=class{id;ws;constructor(t){this.id=Ke(),this.ws=t;}send(t){this.ws.readyState===1&&this.ws.send(JSON.stringify(t));}close(){this.ws.close();}},yt=class{platform={name:"node",isCloudflare:false,isNode:true};core;wsPaths=new Set;ssePaths=new Set;_connections=new Map;constructor(){this.core=Ge();}handleWS(t){this.wsPaths.add(t);}handleSSE(t){this.ssePaths.add(t);}getWSConnections(){return this._connections}getSSEConnections(){return this.core.sseClients}broadcast(t,r,o=[]){this.core.broadcast(r,o,t);}registerRPC(t,r){this.core.registerRPCHandler(t,r);}registerEvent(t,r){this.core.registerEventHandler(t,(o,n,i)=>{r(o,n);});}hasWSPath(t){return this.wsPaths.has(t)}hasSSEPath(t){return this.ssePaths.has(t)}handleConnection(t){let r=new Er(t);return t.on("message",o=>{try{let n=JSON.parse(o.toString());this.core.handleWSMessage(r.id,n);}catch{}}),t.on("close",()=>{this._connections.delete(r.id),this.core.wsClients.delete(r.id);}),this._connections.set(r.id,r),this.core.wsClients.set(r.id,r),r.send({type:"connected",payload:{timestamp:Date.now()}}),r}get connections(){return this._connections}get size(){return this._connections.size}handleSSERequest(){let t=Ke(),r=new ReadableStream({start:o=>{this.core.sseClients.set(t,{id:t,send:i=>{try{o.enqueue(new TextEncoder().encode(i));}catch{this.core.sseClients.delete(t);}}});let n=`event: connected
6
+ `;for(let[_,ue]of e)if(!m.includes(_))try{ue.send({type:R,payload:l});}catch{e.delete(_);}for(let[_,ue]of t)if(!m.includes(_))try{ue.send(P);}catch{t.delete(_);}};return {wsClients:e,sseClients:t,broadcast:n,handleWSMessage:(l,m)=>{let R=e.get(l);if(R){if(typeof m=="object"&&m!==null&&"method"in m&&"id"in m){let v=m,P=r.get(v.method);if(P)try{let _=P(v.params,l);R.send({id:v.id,result:_});}catch(_){R.send({id:v.id,error:_ instanceof Error?_.message:"Unknown error"});}else R.send({id:v.id,error:`Unknown method: ${v.method}`});return}if(typeof m=="object"&&m!==null&&"type"in m){let v=m,P=o.get(v.type);P&&P(v.payload,l,n);}}},registerRPCHandler:(l,m)=>{r.set(l,m);},registerEventHandler:(l,m)=>{o.set(l,m);}}}function Mo(e){return {path:e,get adapter(){return c$9.adapter},registerRPC(t,r){let o=(n,i)=>r(n,i);c$9.registerRPC(t,o);},registerEvent(t,r){let o=(n,i)=>{r(n,i);};c$9.registerEvent(t,o);},broadcast(t,r,o){c$9.broadcast(t,r,o);}}}var Lo=class{id;ws;constructor(t){this.id=a$6(),this.ws=t;}send(t){this.ws.readyState===1&&this.ws.send(JSON.stringify(t));}close(){this.ws.close();}},ir=class{platform={name:"node",isCloudflare:false,isNode:true};core;wsPaths=new Set;ssePaths=new Set;_connections=new Map;constructor(){this.core=xt();}handleWS(t){this.wsPaths.add(t);}handleSSE(t){this.ssePaths.add(t);}getWSConnections(){return this._connections}getSSEConnections(){return this.core.sseClients}broadcast(t,r,o=[]){this.core.broadcast(r,o,t);}registerRPC(t,r){this.core.registerRPCHandler(t,r);}registerEvent(t,r){this.core.registerEventHandler(t,(o,n,i)=>{r(o,n);});}hasWSPath(t){return this.wsPaths.has(t)}hasSSEPath(t){return this.ssePaths.has(t)}handleConnection(t){let r=new Lo(t);return t.on("message",o=>{try{let n=JSON.parse(o.toString());this.core.handleWSMessage(r.id,n);}catch{}}),t.on("close",()=>{this._connections.delete(r.id),this.core.wsClients.delete(r.id);}),this._connections.set(r.id,r),this.core.wsClients.set(r.id,r),r.send({type:"connected",payload:{timestamp:Date.now()}}),r}get connections(){return this._connections}get size(){return this._connections.size}handleSSERequest(){let t=a$6(),r=new ReadableStream({start:o=>{this.core.sseClients.set(t,{id:t,send:i=>{try{o.enqueue(new TextEncoder().encode(i));}catch{this.core.sseClients.delete(t);}}});let n=`event: connected
7
7
  data: ${JSON.stringify({timestamp:Date.now()})}
8
8
 
9
- `;o.enqueue(new TextEncoder().encode(n));},cancel:()=>{this.core.sseClients.delete(t);}});return new Response(r,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}},Tr=null;function br(){return Tr||(Tr=new yt),Tr}var St=null,Rt=null;function cs(e){St=e,Rt=null;}function _i(){return a$3&&St?.REALTIME_DO?{async broadcast(e,t){let r=St.REALTIME_DO.idFromName("global");await St.REALTIME_DO.get(r).fetch(new Request("https://internal/broadcast",{method:"POST",body:JSON.stringify({event:e,data:t})}));}}:{async broadcast(e,t){let{getRuntimeAdapter:r}=await import('./runtime-HBG2YPJ4.js');r().broadcast(e,t);}}}function Li(){return Rt||(Rt=_i()),Rt}var Ye=new Proxy({},{get(e,t){let r=Li();return Reflect.get(r,t,r)}});function ds(){return async(e,t)=>{let r=e.env;r&&cs(r),await t();}}N();H();d$1();var xr=class{async create(t){let o=await(await I$1()).insert(s$2).values({...t,createdAt:new Date}).returning();return c$4(o[0])}async getAll(t=50,r=0){return (await(await I$1()).select().from(s$2).orderBy(desc(s$2.createdAt)).limit(t).offset(r)).map(c$4)}async getByUserId(t,r=50){return (await(await I$1()).select().from(s$2).where(eq(s$2.userId,t)).orderBy(desc(s$2.createdAt)).limit(r)).map(c$4)}async getByResource(t,r){let o=await I$1(),n=[eq(s$2.resourceType,t)];return r&&n.push(eq(s$2.resourceId,r)),(await o.select().from(s$2).where(and(...n)).orderBy(desc(s$2.createdAt))).map(c$4)}async search(t){let r=await I$1(),o=[];return t.userId&&o.push(eq(s$2.userId,t.userId)),t.action&&o.push(eq(s$2.action,t.action)),t.resourceType&&o.push(eq(s$2.resourceType,t.resourceType)),t.startDate&&o.push(gte(s$2.createdAt,t.startDate)),t.endDate&&o.push(lte(s$2.createdAt,t.endDate)),(await r.select().from(s$2).where(o.length>0?and(...o):void 0).orderBy(desc(s$2.createdAt))).map(c$4)}async deleteOlderThan(t){let r=await I$1(),o=new Date;return o.setDate(o.getDate()-t),(await r.delete(s$2).where(lte(s$2.createdAt,o)).returning()).length}},Ue=new xr;h();var C={USER:"user",ROLE:"role",PERMISSION:"permission",CONTENT:"content",ROUTE:"route",ORDER:"order",TICKET:"ticket",DISPUTE:"dispute",FILE:"file",CHAT:"chat",NOTIFICATION:"notification",CAPTCHA:"captcha"},ls={users:C.USER,roles:C.ROLE,permissions:C.PERMISSION,contents:C.CONTENT,routes:C.ROUTE,orders:C.ORDER,tickets:C.TICKET,disputes:C.DISPUTE,files:C.FILE,chats:C.CHAT,notifications:C.NOTIFICATION,captchas:C.CAPTCHA},D={CREATE:"create",UPDATE:"update",DELETE:"delete",ASSIGN:"assign",REVOKE:"revoke"};var he=g.api();function ms(){return async(e,t)=>{let r=Date.now(),o=e.req.path,n=e.req.method;await t();let i=Date.now()-r,a=e.res.status;if(he.info({path:o,method:n,status:a,duration:i},"Audit log middleware checking"),!o.startsWith("/api/")||o.startsWith("/api/permissions/")){he.info({path:o},"Skipping: not API or public API");return}if(!["POST","PUT","DELETE","PATCH"].includes(n)){he.info({method:n},"Skipping: not write operation");return}if(a<200||a>=300){he.info({status:a},"Skipping: not successful operation");return}let u=M(e);if(!u){he.info({path:o},"Skipping: no user");return}let l=D.CREATE;n==="POST"?l=D.CREATE:n==="PUT"||n==="PATCH"?l=D.UPDATE:n==="DELETE"&&(l=D.DELETE);let p=o.split("/").filter(Boolean),T="user";if(p.length>=2){let P=p[1];T=ls[P]||"unknown";}try{await Ue.create({id:`audit_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,userId:u.id,action:l,resourceType:T,resourceId:p.length>=3?p[2]:null,oldValue:null,newValue:null,ipAddress:e.req.header("x-forwarded-for")||e.req.header("x-real-ip")||null,userAgent:e.req.header("user-agent")||null}),he.info({userId:u.id,action:l,resourceType:T,path:o,method:n,status:a,duration:i},"Audit log created");}catch(P){he.error({error:P,path:o,method:n},"Failed to create audit log");}}}h();N();H();d$1();b();var Yi=["image/jpeg","image/png","image/gif","image/webp","application/pdf","text/plain","text/csv","application/json","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.wordprocessingml.document"],Zi=[".jpg",".jpeg",".png",".gif",".webp",".pdf",".txt",".csv",".json",".xlsx",".docx"],vt=null;function Et(){if(vt)return vt;let e=process.env.FILE_STORAGE_PATH||join(process.cwd(),"uploads"),t=process.env.FILE_TEMP_PATH||join(e,"temp"),r=parseInt(process.env.FILE_TEMP_TTL||"3600000",10),o=parseInt(process.env.FILE_PRIVATE_URL_EXPIRY||"3600",10),n=process.env.FILE_SECRET_KEY||(process.env.NODE_ENV==="test"?"test-secret-key":void 0);if(!n)throw new Error("FILE_SECRET_KEY environment variable is required in production");return vt={baseDir:e,tempDir:t,tempFileTTL:r,privateUrlExpiry:o,secretKey:n},vt}function Ar(e,t){let r=Et();return {uploadDir:join(r.baseDir,e),maxFileSize:10*1024*1024,allowedMimeTypes:Yi,allowedExtensions:Zi}}async function Ji(e){existsSync(e)||await mkdir(e,{recursive:true});}function Ir(e,t){if(e.size>t.maxFileSize)return {valid:false,error:`File size exceeds maximum allowed size of ${t.maxFileSize} bytes`};if(!t.allowedMimeTypes.includes(e.type))return {valid:false,error:`File type "${e.type}" is not allowed`};let r=extname(e.name).toLowerCase();return t.allowedExtensions.includes(r)?{valid:true}:{valid:false,error:`File extension "${r}" is not allowed`}}async function bt(e,t,r){if(a$3)throw new Error("Local file storage is not supported in Cloudflare environment. Use R2 or other cloud storage.");let o=Ar(e),n=Ir(t,o);if(!n.valid)throw new Error(n.error);await Ji(o.uploadDir);let i=extname(t.name).toLowerCase(),a=`${randomUUID()}${i}`,u=join(o.uploadDir,a);return await writeFile(u,Buffer.from(t.data)),{filename:a,originalName:t.name,mimeType:t.type,size:t.size,path:u,extension:i}}async function Pr(e){if(a$3)throw new Error("Local file storage is not supported in Cloudflare environment.");if(!existsSync(e))throw new Error("File not found");return readFile(e)}async function Ur(e){if(a$3)throw new Error("Local file storage is not supported in Cloudflare environment.");try{return existsSync(e)&&await unlink(e),!0}catch{return false}}function xt(e,t){let r=Et();return join(r.baseDir,e,t)}function Or(e,t,r){return r?`${r}/files/public/${e}/${t}`:`/files/public/${e}/${t}`}function hs(e,t,r){let o=Et(),n=`${e}:${t}:${r}`;return createHmac("sha256",o.secretKey).update(n).digest("hex")}function Dr(e,t,r,o){let n=hs(e,t,r);try{let i=Buffer.from(o,"hex"),a=Buffer.from(n,"hex");return i.length===a.length&&timingSafeEqual(i,a)}catch{return false}}function fs(e,t,r,o){let n=Et(),i=Math.floor(Date.now()/1e3)+(r||n.privateUrlExpiry),a=hs(e,t,i);return {url:o?`${o}/files/private/${e}/${t}?expiry=${i}&signature=${a}`:`/files/private/${e}/${t}?expiry=${i}&signature=${a}`,expiry:i}}async function Oe(e,t){let r=xt(e,t);if(!existsSync(r))return null;try{let o=await stat(r),n=extname(t).toLowerCase(),i={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".pdf":"application/pdf",".txt":"text/plain",".csv":"text/csv",".json":"application/json",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};return {size:o.size,mimeType:i[n]||"application/octet-stream",lastModified:o.mtime}}catch{return null}}function Z(e){return `"${e.replace(/^[+\-=@\t\r]/,"'$&").replace(/"/g,'""')}"`}var gs="todos";async function Ss(){return (await(await I$1()).select().from(j$1).orderBy(desc(j$1.createdAt))).map(r=>({id:r.id,title:r.title,description:r.description??void 0,status:r.status,createdAt:a$1(r.createdAt),updatedAt:a$1(r.updatedAt)}))}async function Je(e){let o=(await(await I$1()).select().from(j$1).where(eq(j$1.id,e)))[0];return o?{id:o.id,title:o.title,description:o.description??void 0,status:o.status,createdAt:a$1(o.createdAt),updatedAt:a$1(o.updatedAt)}:null}async function Rs(e){let t=await I$1(),r=new Date,n=(await t.insert(j$1).values({title:e.title,description:e.description??null,status:"pending",createdAt:r,updatedAt:r}).returning())[0];return {id:n.id,title:n.title,description:n.description??void 0,status:n.status,createdAt:a$1(n.createdAt),updatedAt:a$1(n.updatedAt)}}async function ws(e,t){let r=await I$1(),n={updatedAt:new Date};t.title!==void 0&&t.title!==null&&(n.title=t.title),t.description!==void 0&&t.description!==null&&(n.description=t.description),t.status!==void 0&&t.status!==null&&(n.status=t.status);let i=await r.update(j$1).set(n).where(eq(j$1.id,e)).returning();if(i.length===0)return null;let a=i[0];return {id:a.id,title:a.title,description:a.description??void 0,status:a.status,createdAt:a$1(a.createdAt),updatedAt:a$1(a.updatedAt)}}async function vs(e){let t=await I$1(),r=await t.select().from(k$1).where(eq(k$1.todoId,e));for(let n of r)await Ur(n.path);return (await t.delete(j$1).where(eq(j$1.id,e)).returning()).length>0}async function Ts(e,t,r){let o=await I$1(),n=Ar(gs),i=Ir(t,n);if(!i.valid)throw new Error(i.error);let a=await bt(gs,t),u=new Date,p=(await o.insert(k$1).values({todoId:e,fileName:a.filename,originalName:a.originalName,mimeType:a.mimeType,size:a.size,path:a.path,uploadedBy:r??null,createdAt:u}).returning())[0];return {id:p.id,todoId:p.todoId,fileName:p.fileName,originalName:p.originalName,mimeType:p.mimeType,size:p.size,path:p.path,uploadedBy:p.uploadedBy??void 0,createdAt:a$1(p.createdAt)}}async function kr(e){return (await(await I$1()).select().from(k$1).where(eq(k$1.todoId,e)).orderBy(desc(k$1.createdAt))).map(o=>({id:o.id,todoId:o.todoId,fileName:o.fileName,originalName:o.originalName,mimeType:o.mimeType,size:o.size,path:o.path,uploadedBy:o.uploadedBy??void 0,createdAt:a$1(o.createdAt)}))}async function Es(e){let t=await Je(e);if(!t)return null;let r=await kr(e);return {...t,attachments:r}}async function bs(e){let t=await I$1(),r=await t.select().from(k$1).where(eq(k$1.id,e));if(r.length===0)return false;let o=r[0];return await Ur(o.path),await t.delete(k$1).where(eq(k$1.id,e)),true}var Ct=e=>z.object({success:z.literal(true),data:e,timestamp:z.string()}),Qi=z.object({field:z.string().optional(),message:z.string(),code:z.string().optional()}),At=z.object({success:z.literal(false),error:z.string(),code:z.string().optional(),status:z.number().optional(),details:z.array(Qi).optional(),timestamp:z.string().optional()});var Nr=z.object({rpc:z.object({echo:z.object({in:z.object({message:z.string()}),out:z.object({message:z.string(),timestamp:z.number()})}),ping:z.object({in:z.object({}),out:z.object({pong:z.boolean(),timestamp:z.number()})})}),events:z.object({notification:z.object({title:z.string(),body:z.string(),timestamp:z.number()}),broadcast:z.object({message:z.string(),timestamp:z.number()}),connected:z.object({timestamp:z.number()}),disconnected:z.object({timestamp:z.number()})})}),jr=z.object({connectedClients:z.number()});var ge=z.object({namespace:z.string(),filename:z.string()}),Xe=z.object({expiry:z.string().transform(Number),signature:z.string()}),Mr=z.object({url:z.string()}),_r=z.object({url:z.string(),expiry:z.number()}),It=z.object({namespace:z.string(),filename:z.string(),isPrivate:z.boolean().nullish().default(false),expirySeconds:z.number().nullish()}),Pt=z.union([Mr,_r]);z.object({});var Ut=z.object({filename:z.string(),originalName:z.string(),mimeType:z.string(),size:z.number(),url:z.string()}),Ot=z.object({file:z.instanceof(File),namespace:z.string().nullish().default("uploads")});var Dt=z.enum(["pending","in_progress","completed"]),ce=z.object({id:z.number().int().positive(),title:z.string().min(1,"Title is required").max(200,"Title too long"),description:z.string().max(1e3,"Description too long").nullish(),status:Dt,createdAt:z.string().datetime(),updatedAt:z.string().datetime()}),kt=z.object({title:z.string().min(1,"Title is required").max(200,"Title too long"),description:z.string().max(1e3,"Description too long").nullish()}),qt=z.object({title:z.string().min(1,"Title is required").max(200,"Title too long").nullish(),description:z.string().max(1e3,"Description too long").nullish(),status:Dt.nullish()});z.object({id:z.coerce.number().int().positive()});var Nt=z.object({id:z.number()}),Qe=z.object({id:z.number().int().positive(),todoId:z.number().int().positive(),fileName:z.string(),originalName:z.string(),mimeType:z.string(),size:z.number().int().positive(),path:z.string(),uploadedBy:z.string().nullish(),createdAt:z.string().datetime()}),et=z.array(Qe),jt=ce.extend({attachments:et}),Mt=z.object({file:z.file().openapi({type:"string",format:"binary"})}),_t=z.object({id:z.number()});var tt=z.enum(["info","warning","success","error"]),B=z.object({id:z.string().uuid(),type:tt,title:z.string().min(1).max(200),message:z.string().max(2e3),read:z.boolean().default(false),createdAt:z.string().datetime()}),Lt=z.object({type:tt,title:z.string().min(1,"Title is required").max(200,"Title too long"),message:z.string().min(1,"Message is required").max(2e3,"Message too long")});z.object({unreadOnly:z.coerce.boolean().nullish().default(false),limit:z.coerce.number().int().min(1).max(100).nullish().default(20),cursor:z.string().nullish()});z.object({event:z.enum(["notification","ping","connected"]),data:z.union([B,z.object({timestamp:z.number()})])});var Lr=z.object({count:z.number()}),De=z.object({events:z.object({notification:B,"unread-count":Lr,ping:z.object({timestamp:z.number()}),connected:z.object({timestamp:z.number()})})}),ye=z.object({count:z.number()}),Ft=z.object({id:z.string()}),Fr=z.array(B),zr=z.object({count:z.number()}),Br=z.object({type:tt.nullish().default("info")});function d(e){return {success:true,data:e,timestamp:new Date().toISOString()}}function L(e){return {success:true,data:e,timestamp:new Date().toISOString()}}function c(e,t){return {content:{"application/json":{schema:Ct(e)}},description:t}}function s(e){return {content:{"application/json":{schema:At}},description:e}}function Ps(e,t){return c(z.object({items:z.array(e),nextCursor:z.string().optional()}),t)}var oa=z.object({id:z.string()}),Us={params:oa};function zt(e){return {body:{content:{"application/json":{schema:e}}}}}var na=z.array(ce),ia=createRoute({method:"get",path:"/todos",tags:["todos"],responses:{200:c(na,"List all todos"),500:s("Internal server error")}}),aa=createRoute({method:"get",path:"/todos/{id}",tags:["todos"],request:{params:z.object({id:z.coerce.number().int().positive()})},responses:{200:c(ce,"Get a todo by ID"),404:s("Todo not found")}}),ca=createRoute({method:"post",path:"/todos",tags:["todos"],security:[{Bearer:[]}],middleware:[m()],request:{body:{content:{"application/json":{schema:kt}}}},responses:{201:c(ce,"Create a new todo"),400:s("Invalid input")}}),da=createRoute({method:"put",path:"/todos/{id}",tags:["todos"],security:[{Bearer:[]}],middleware:[m()],request:{params:z.object({id:z.coerce.number().int().positive()}),body:{content:{"application/json":{schema:qt}}}},responses:{200:c(ce,"Update a todo"),404:s("Todo not found")}}),pa=createRoute({method:"delete",path:"/todos/{id}",tags:["todos"],security:[{Bearer:[]}],middleware:[m()],request:{params:z.object({id:z.coerce.number().int().positive()})},responses:{200:c(Nt,"Delete a todo"),404:s("Todo not found")}}),ua=createRoute({method:"post",path:"/todos/{id}/attachments",tags:["todos"],security:[{Bearer:[]}],middleware:[m()],request:{params:z.object({id:z.coerce.number().int().positive()}),body:{required:true,content:{"multipart/form-data":{schema:Mt}}}},responses:{201:c(Qe,"File uploaded successfully"),404:s("Todo not found"),400:s("Invalid file or file too large")}}),la=createRoute({method:"get",path:"/todos/{id}/attachments",tags:["todos"],security:[{Bearer:[]}],middleware:[m()],request:{params:z.object({id:z.coerce.number().int().positive()})},responses:{200:c(et,"List attachments"),404:s("Todo not found")}}),ma=createRoute({method:"get",path:"/todos/{id}/with-attachments",tags:["todos"],security:[{Bearer:[]}],middleware:[m()],request:{params:z.object({id:z.coerce.number().int().positive()})},responses:{200:c(jt,"Get todo with attachments"),404:s("Todo not found")}}),ha=createRoute({method:"delete",path:"/todos/{todoId}/attachments/{attachmentId}",tags:["todos"],security:[{Bearer:[]}],middleware:[m()],request:{params:z.object({todoId:z.coerce.number().int().positive(),attachmentId:z.coerce.number().int().positive()})},responses:{200:c(_t,"Attachment deleted"),404:s("Attachment not found")}}),Os=new OpenAPIHono().openapi(ia,async e=>{let t=await Ss();return e.json(d(t),200)}).openapi(aa,async e=>{let{id:t}=e.req.valid("param"),r=await Je(t);if(!r)throw new f("Todo",String(t));return e.json(d(r),200)}).openapi(ca,async e=>{let t=e.req.valid("json"),r=await Rs(t);return e.json(L(r),201)}).openapi(da,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=await ws(t,r);if(!o)throw new f("Todo",String(t));return e.json(d(o),200)}).openapi(pa,async e=>{let{id:t}=e.req.valid("param");if(!await vs(t))throw new f("Todo",String(t));return e.json(d({id:t}),200)}).openapi(ua,async e=>{let{id:t}=e.req.valid("param");if(!await Je(t))throw new f("Todo",String(t));let n=e.req.valid("form").file;if(!n||!(n instanceof File))throw new $e("No file uploaded");let i=M(e),a=await n.arrayBuffer();try{let u=await Ts(t,{name:n.name,type:n.type,size:n.size,data:a},i?.id);return e.json(L(u),201)}catch(u){throw new $e(u.message)}}).openapi(la,async e=>{let{id:t}=e.req.valid("param");if(!await Je(t))throw new f("Todo",String(t));let o=await kr(t);return e.json(d(o),200)}).openapi(ma,async e=>{let{id:t}=e.req.valid("param"),r=await Es(t);if(!r)throw new f("Todo",String(t));return e.json(d(r),200)}).openapi(ha,async e=>{let{attachmentId:t}=e.req.valid("param");if(!await bs(t))throw new f("Attachment",String(t));return e.json(d({id:t}),200)}).doc("/docs",{openapi:"3.0.0",info:{version:"1.0.0",title:"Todo API"}});var ga=createRoute({method:"get",path:"/permissions/roles",tags:["permissions"],responses:{200:c(d$2.array(),"Get all roles")}}),ya=createRoute({method:"get",path:"/permissions",tags:["permissions"],responses:{200:c(e$1.array(),"Get all permissions")}}),Sa=createRoute({method:"get",path:"/permissions/me",tags:["permissions"],security:[{Bearer:[]}],middleware:[m()],responses:{200:c(f$3,"Get current user permissions"),401:s("Unauthorized")}}),Ra=createRoute({method:"get",path:"/permissions/menu-config",tags:["permissions"],responses:{200:c(g$2,"Get menu configuration")}}),wa=createRoute({method:"get",path:"/permissions/page-permissions",tags:["permissions"],responses:{200:c(h$2,"Get page permissions configuration")}}),va=createRoute({method:"get",path:"/permissions/categories",tags:["permissions"],responses:{200:c(i,"Get permission categories")}}),Ta=createRoute({method:"get",path:"/permissions/role-labels",tags:["permissions"],responses:{200:c(j$2,"Get role labels")}}),Ea=createRoute({method:"get",path:"/permissions/permission-labels",tags:["permissions"],responses:{200:c(k$2,"Get permission labels")}}),ba=createRoute({method:"get",path:"/permissions/my-menu",tags:["permissions"],security:[{Bearer:[]}],middleware:[m()],responses:{200:c(g$2,"Get user menu configuration"),401:s("Unauthorized")}}),xa=createRoute({method:"get",path:"/permissions/init",tags:["permissions"],security:[{Bearer:[]}],middleware:[m()],responses:{200:c(l$1,"Get permission initialization data"),401:s("Unauthorized")}}),Ds=new OpenAPIHono().openapi(ga,async e=>{let t$1=await t.getAllRoles();return e.json(d(t$1),200)}).openapi(ya,async e=>{let t$1=await t.getAllPermissions();return e.json(d(t$1),200)}).openapi(Sa,async e=>{let t$1=M(e),o=(await t.getUserPermissions(t$1.id,t$1.role)).map(n=>n.code);return e.json(d({userId:t$1.id,role:t$1.role,permissions:o}),200)}).openapi(Ra,async e=>{let t=n();return e.json(d(t),200)}).openapi(wa,async e=>{let t=o();return e.json(d(t),200)}).openapi(va,async e=>{let t=p();return e.json(d(t),200)}).openapi(Ta,async e=>{let t=q$1();return e.json(d(t),200)}).openapi(Ea,async e=>{let t=r();return e.json(d(t),200)}).openapi(ba,async e=>{let t$1=M(e),r=await t.getUserMenuConfig(t$1.id,t$1.role);return e.json(d(r),200)}).openapi(xa,async e=>{let t$1=M(e),[r,o,n]=await Promise.all([t.getUserPermissions(t$1.id,t$1.role),t.getUserMenuConfig(t$1.id,t$1.role),t.getUserPagePermissions(t$1.id,t$1.role)]),i=r.map(a=>a.code);return e.json(d({permissions:i,menuConfig:o,pagePermissions:n,role:t$1.role}),200)});var ks=z.union([z.string(),z.date(),z.null()]).transform(e=>e instanceof Date?e.toISOString():e===null?new Date().toISOString():e),ot=z.object({id:z.string(),code:z.string(),name:z.string(),label:z.string(),description:z.string().optional().nullable(),isSystem:z.boolean().nullable(),isActive:z.boolean().nullable(),sortOrder:z.number().nullable(),createdAt:ks,updatedAt:ks}),qs=z.object({code:z.string().min(1),name:z.string().min(1),label:z.string().min(1),description:z.string().nullish(),sortOrder:z.number().nullish()}),Ns=z.object({name:z.string().nullish(),label:z.string().nullish(),description:z.string().nullish(),sortOrder:z.number().nullish(),isActive:z.boolean().nullish()}),js=z.object({permissionIds:z.array(z.string())}),Wr=z.object({});var Ca={"user:create":["user:view"],"user:edit":["user:view"],"user:delete":["user:view"],"content:create":["content:view"],"content:edit":["content:view"],"content:delete":["content:view"],"order:process":["order:view"],"order:cancel":["order:view"],"order:complete":["order:view"],"ticket:reply":["ticket:view"],"ticket:close":["ticket:view"],"data:export":["user:view"],"system:settings":["system:logs"]};function Ms(e){let t=[];for(let r of e){let o=Ca[r];if(o){let n=o.filter(i=>!e.includes(i));n.length>0&&t.push(`\u6743\u9650 "${r}" \u9700\u8981\u4EE5\u4E0B\u6743\u9650: ${n.join(", ")}`);}}return {valid:t.length===0,errors:t}}var Ia=ot.extend({permissions:z.array(z.string())}),Pa=createRoute({method:"get",path:"/roles",tags:["roles"],security:[{Bearer:[]}],middleware:[m({requiredRole:"super_admin"})],responses:{200:c(ot.array(),"Get all roles"),401:s("Unauthorized"),403:s("Forbidden")}}),Ua=createRoute({method:"get",path:"/roles/:id",tags:["roles"],security:[{Bearer:[]}],middleware:[m({requiredRole:"super_admin"})],request:{params:z.object({id:z.string()})},responses:{200:c(Ia,"Get role by ID"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Role not found")}}),Oa=createRoute({method:"post",path:"/roles",tags:["roles"],security:[{Bearer:[]}],middleware:[m({requiredRole:"super_admin"})],request:{body:{content:{"application/json":{schema:qs}}}},responses:{200:c(ot,"Role created"),401:s("Unauthorized"),403:s("Forbidden"),400:s("Invalid request")}}),Da=createRoute({method:"put",path:"/roles/:id",tags:["roles"],security:[{Bearer:[]}],middleware:[m({requiredRole:"super_admin"})],request:{params:z.object({id:z.string()}),body:{content:{"application/json":{schema:Ns}}}},responses:{200:c(ot,"Role updated"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Role not found")}}),ka=createRoute({method:"delete",path:"/roles/:id",tags:["roles"],security:[{Bearer:[]}],middleware:[m({requiredRole:"super_admin"})],request:{params:z.object({id:z.string()})},responses:{200:c(Wr,"Role deleted"),401:s("Unauthorized"),403:s("Forbidden"),400:s("Cannot delete system role")}}),qa=createRoute({method:"put",path:"/roles/:id/permissions",tags:["roles"],security:[{Bearer:[]}],middleware:[m({requiredRole:"super_admin"})],request:{params:z.object({id:z.string()}),body:{content:{"application/json":{schema:js}}}},responses:{200:c(Wr,"Role permissions updated"),400:s("Permission dependency validation failed"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Role not found")}}),_s=new OpenAPIHono().openapi(Pa,async e=>{let t=await m$1.getAll();return e.json(d(t),200)}).openapi(Ua,async e=>{let{id:t$1}=e.req.valid("param"),r=await m$1.getById(t$1);if(!r)return e.json({success:false,error:"Role not found"},404);let o=await t.getRolePermissions(t$1);return e.json(d({...r,permissions:o.map(n=>n.code)}),200)}).openapi(Oa,async e=>{let t=e.req.valid("json"),r=await m$1.create({id:`role_${Date.now()}`,...t,sortOrder:t.sortOrder??0});return e.json(d(r),200)}).openapi(Da,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=Object.fromEntries(Object.entries(r).filter(([i,a])=>a!=null)),n=await m$1.update(t,o);return n?e.json(d(n),200):e.json({success:false,error:"Role not found"},404)}).openapi(ka,async e=>{let{id:t}=e.req.valid("param");return await m$1.delete(t)?e.json(d({}),200):e.json({success:false,error:"Cannot delete system role or role not found"},400)}).openapi(qa,async e=>{let{id:t$1}=e.req.valid("param"),{permissionIds:r}=e.req.valid("json"),o=await m$1.getById(t$1);if(!o)return e.json({success:false,error:"Role not found"},404);if(o.code==="super_admin")return e.json({success:false,error:"Cannot modify super admin permissions"},403);let n=Ms(r);if(!n.valid)return e.json({success:false,error:"\u6743\u9650\u4F9D\u8D56\u6821\u9A8C\u5931\u8D25",details:n.errors.map(p=>({message:p}))},400);let a=(await Promise.all(r.map(p=>t.getByCode(p)))).filter(p=>p!==void 0).map(p=>p.id),l=(await t.getRolePermissions(t$1)).map(p=>p.id);for(let p of l)a.includes(p)||await t.revokePermissionFromRole(t$1,p);for(let p of a)l.includes(p)||await t.assignPermissionToRole(t$1,p);return e.json(d({}),200)});var $r=z.enum(Object.values(C)),Hr=z.enum(Object.values(D)),Vr=z.object({id:z.string(),userId:z.string(),action:Hr,resourceType:$r,resourceId:z.string().nullable(),oldValue:z.string().nullable(),newValue:z.string().nullable(),ipAddress:z.string().nullable(),userAgent:z.string().nullable(),createdAt:z.union([z.string(),z.date()]).transform(e=>e instanceof Date?e.toISOString():e)});var ja=createRoute({method:"get",path:"/audit-logs",tags:["audit-logs"],security:[{Bearer:[]}],middleware:[m()],request:{query:z.object({limit:z.string().optional(),offset:z.string().optional(),userId:z.string().optional(),action:Hr.optional(),resourceType:$r.optional()})},responses:{200:c(Vr.array(),"Get audit logs"),401:s("Unauthorized")}}),Ma=createRoute({method:"get",path:"/audit-logs/:id",tags:["audit-logs"],security:[{Bearer:[]}],middleware:[m()],request:{params:z.object({id:z.string()})},responses:{200:c(Vr,"Get audit log by ID"),404:s("Audit log not found"),401:s("Unauthorized")}}),Fs=new OpenAPIHono().openapi(ja,async e=>{let t=e.req.valid("query"),r=t.limit?parseInt(t.limit):50,o=t.offset?parseInt(t.offset):0;if(t.userId||t.action||t.resourceType){let i=await Ue.search({userId:t.userId,action:t.action,resourceType:t.resourceType});return e.json(d(i.slice(o,o+r)),200)}let n=await Ue.getAll(r,o);return e.json(d(n),200)}).openapi(Ma,async e=>{let{id:t}=e.req.valid("param"),o=(await Ue.getAll(1e3,0)).find(n=>n.id===t);return o?e.json(d(o),200):e.json({success:false,error:"Audit log not found"},404)});h();var de=[];function Bt(e){let t=[...de];e.unreadOnly&&(t=t.filter(a=>!a.read)),t.sort((a,u)=>new Date(u.createdAt).getTime()-new Date(a.createdAt).getTime());let r=e.limit??20,o=0;if(e.cursor){let a=t.findIndex(u=>u.id===e.cursor);a!==-1&&(o=a+1);}let n=t.slice(o,o+r),i=n.length===r?n[n.length-1]?.id:void 0;return {data:n,nextCursor:i}}function zs(e){return de.find(t=>t.id===e)}function _a(e){let t={id:Ke(),type:e.type,title:e.title,message:e.message,read:false,createdAt:new Date().toISOString()};return de.unshift(t),t}async function Wt(e){let t=_a(e);try{await Ye.broadcast("notification",t);}catch(r){g.module("notification").debug({error:String(r)},"Broadcast failed");}return t}function $t(e){let t=de.find(r=>r.id===e);return t&&(t.read=true),t}function Ht(){let e=0;return de.forEach(t=>{t.read||(t.read=true,e++);}),e}function Bs(e){let t=de.findIndex(r=>r.id===e);return t!==-1?(de.splice(t,1),true):false}function st(){return de.filter(e=>!e.read).length}var Fa=createRoute({method:"get",path:"/notifications/stream",tags:["notifications"],responses:{200:{content:{"text/event-stream":{schema:De}},description:"SSE stream for notifications"},500:s("Internal server error")}}),za=createRoute({method:"get",path:"/notifications",tags:["notifications"],request:{query:z.object({unreadOnly:z.string().optional(),limit:z.string().optional(),cursor:z.string().optional()})},responses:{200:Ps(B,"List notifications"),500:s("Internal server error")}}),Ba=createRoute({method:"get",path:"/notifications/unread-count",tags:["notifications"],responses:{200:c(ye,"Get unread count"),500:s("Internal server error")}}),Wa=createRoute({method:"get",path:"/notifications/{id}",tags:["notifications"],request:{params:z.object({id:z.string()})},responses:{200:c(B,"Get notification by ID"),404:s("Notification not found")}}),$a=createRoute({method:"post",path:"/notifications",tags:["notifications"],request:{body:{content:{"application/json":{schema:Lt}}}},responses:{201:c(B,"Create notification"),400:s("Invalid input")}}),Ha=createRoute({method:"patch",path:"/notifications/read-all",tags:["notifications"],responses:{200:c(ye,"Mark all as read"),500:s("Internal server error")}}),Va=createRoute({method:"patch",path:"/notifications/{id}/read",tags:["notifications"],request:{params:z.object({id:z.string()})},responses:{200:c(B,"Mark as read"),404:s("Notification not found")}}),Ga=createRoute({method:"delete",path:"/notifications/{id}",tags:["notifications"],request:{params:z.object({id:z.string()})},responses:{200:c(Ft,"Delete notification"),404:s("Notification not found")}}),$s=new OpenAPIHono().openapi(Fa,async e=>{let t=e.env;if(t?.REALTIME_DO){let o=t.REALTIME_DO.idFromName("global"),n=t.REALTIME_DO.get(o),i=new Request(e.req.url,{method:e.req.method,headers:e.req.raw.headers});return n.fetch(i)}let r=b$1();return r.handleSSERequest?await r.handleSSERequest():e.json({success:false,error:"SSE not supported"},500)}).openapi(za,async e=>{let t=e.req.valid("query"),r=Bt({unreadOnly:t.unreadOnly==="true",limit:t.limit?parseInt(t.limit):20,cursor:t.cursor});return e.json(d({items:r.data,nextCursor:r.nextCursor}),200)}).openapi(Ba,async e=>{let t=st();return e.json(d({count:t}),200)}).openapi(Wa,async e=>{let{id:t}=e.req.valid("param"),r=zs(t);if(!r)throw new f("Notification",t);return e.json(d(r),200)}).openapi($a,async e=>{let t=e.req.valid("json"),r=await Wt(t);return e.json(L(r),201)}).openapi(Ha,async e=>{let t=Ht();return e.json(d({count:t}),200)}).openapi(Va,async e=>{let{id:t}=e.req.valid("param"),r=$t(t);if(!r)throw new f("Notification",t);return e.json(d(r),200)}).openapi(Ga,async e=>{let{id:t}=e.req.valid("param");if(!Bs(t))throw new f("Notification",t);return e.json(d({id:t}),200)});var Vt=vr("/chat/ws");Vt.registerRPC("echo",e=>({message:e.message,timestamp:Date.now()}));Vt.registerRPC("ping",()=>({pong:true,timestamp:Date.now()}));Vt.registerEvent("broadcast",(e,t)=>{Vt.broadcast("broadcast",e,[t]);});var Ya=createRoute({method:"get",path:"/chat/ws/status",tags:["chat"],responses:{200:c(jr,"Get WebSocket status")}}),Za=createRoute({method:"get",path:"/chat/ws",tags:["chat"],responses:{200:{content:{websocket:{schema:Nr}},description:"WebSocket endpoint for chat"}}}),Vs=new OpenAPIHono().openapi(Ya,async e=>e.json(d({connectedClients:0}))).openapi(Za,async e=>{let t=b$1();return t.handleWebSocketRequest?t.handleWebSocketRequest(e.req.raw):new Response("WebSocket not supported",{status:500})});N();H();d$1();async function Ks(){let e=await J();if(e&&"execute"in e){let o=await e.execute("SELECT COUNT(*) as count FROM todos"),n=await e.execute("SELECT COUNT(*) as count FROM todos WHERE status = 'pending'"),i=await e.execute("SELECT COUNT(*) as count FROM todos WHERE status = 'completed'"),a=u=>{let l=u[0];return typeof l?.count=="number"?l.count:0};return {totalTodos:a(o.rows),pendingTodos:a(n.rows),completedTodos:a(i.rows),lastUpdated:new Date().toISOString()}}let r=await(await I$1()).select().from(j$1);return {totalTodos:r.length,pendingTodos:r.filter(o=>o.status==="pending").length,completedTodos:r.filter(o=>o.status==="completed").length,lastUpdated:new Date().toISOString()}}async function Ys(){try{return await(await I$1()).select().from(j$1).limit(1),{database:"connected",timestamp:new Date().toISOString()}}catch{return {database:"disconnected",timestamp:new Date().toISOString()}}}async function Zs(){return {deletedCount:(await(await I$1()).delete(j$1).returning()).length}}async function Js(e=10){return (await(await I$1()).select().from(j$1).orderBy(desc(j$1.updatedAt)).limit(e)).map(o=>({id:o.id,title:o.title,status:o.status,updatedAt:a$1(o.updatedAt)}))}var Xa="$2b$10$9iWkIfjDcJ7Kv4wHSb8ONONnrlfGb6rcfiJlZuuY4G2xQMG78DBbm";async function Gt(e){let r=ae().find(n=>n.username===e.username);if(!r||!await Ja.compare(e.password,Xa))throw new Error("Invalid credentials");let o;return r.role==="super_admin"?o=`test-super-admin-${r.id}`:r.role==="customer_service"?o=`test-customer-service-${r.id}`:o=`test-user-${r.id}`,{user:{id:r.id,username:r.username,email:r.email,role:r.role,avatar:r.avatar,permissions:a$2(r.role)},token:o}}async function Kt(e){let t=ae();if(t.find(n=>n.username===e.username||n.email===e.email))throw new Error("User already exists");let o={id:String(t.length+1),username:e.username,email:e.email,role:"user",status:"active",avatar:`https://api.dicebear.com/7.x/avataaars/svg?seed=${e.username}`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return t.push(o),o}async function Xs(){return ae()}async function Qs(e){return ae().find(r=>r.id===e)||null}async function en(e,t){let r=ae(),o=r.findIndex(a=>a.id===e);if(o===-1)throw new Error("User not found");let n=Object.fromEntries(Object.entries(t).filter(([a,u])=>u!=null)),i={...r[o],...n,updatedAt:new Date().toISOString()};return r[o]=i,i}async function tn(e){let t=ae(),r=t.findIndex(o=>o.id===e);if(r===-1)throw new Error("User not found");t.splice(r,1);}async function rn(e){let t=ae();if(t.find(n=>n.username===e.username||n.email===e.email))throw new Error("User with this username or email already exists");let o={id:`user-${Date.now()}`,username:e.username,email:e.email,role:e.role,status:e.status||"active",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return t.push(o),o}async function Yt(){return (await(await I$1()).select().from(j$1).orderBy(desc(j$1.createdAt))).map(r=>({id:r.id,title:r.title,completed:r.status==="completed",createdAt:a$1(r.createdAt)}))}var Gr=new Map,Kr=new Map;async function on(e){if(Gr.has(e))return Gr.get(e);let t=await fetch(`https://api.dicebear.com/7.x/avataaars/png?seed=${e}`);if(!t.ok)return null;let o={data:await t.blob(),contentType:"image/png"};return Gr.set(e,o),o}async function sn(e){if(Kr.has(e))return Kr.get(e);let r={home:'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l9-6 6 6 6-6 9 9 6-6-9-9z"></path><path d="M9 21l6-6 6 6-6 9 9 6-6 9-9z"></path></svg>',settings:'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 3 3 3 3 3 0 0 6.3 6.3A1.65 1.65 0 0 3 3 3 3 3 0 0 6.3 6.3a1.65 1.65 0 0 3 3 3 3 3 0 0 6.3 6.3z"></path></svg>',user:'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0 1-3 1H4a4 4 0 0 0 1 3v2"></path><circle cx="12" cy="7" r="4"></circle><path d="M16 11.37A4 4 0 1 1.8 2.44L8 2.44A4 4 0 1 1.8 2z"></path></svg>',bell:'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8A6 6 0 0 0 6 6c0 1.1.9 2.1 2.1-2 2.1-.9.9-.9 2.1-2 2.1A6 6 0 0 0 6-6 7-9l1-1.1c.7-.7 1.9-2 2.1-.9-.9-.9-2.1-2-2.1A6 6 0 0 0-6 6-7 9l-1 1.1c-.7.7-1.9 2-2.1.9.9.9 2.1 2 2.1z"></path><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2z"></path><line x1="15" y1="12"></line><line x1="15" y1="9"></line></svg>'}[e];return r?(Kr.set(e,r),r):null}var nn=z.object({totalTodos:z.number(),pendingTodos:z.number(),completedTodos:z.number(),lastUpdated:z.string()}),an=z.object({database:z.enum(["connected","disconnected"]),timestamp:z.string()}),Qa=z.object({id:z.number(),title:z.string(),status:z.string(),updatedAt:z.string()}),cn=z.array(Qa),nt=z.object({id:z.string(),username:z.string(),email:z.string(),role:b$2,avatar:z.string().nullish(),permissions:z.array(c$1)}),Zt=z.object({username:z.string().min(1),password:z.string().min(6)}),Jt=z.object({user:nt,token:z.string()}),Xt=z.object({username:z.string().min(1),email:z.string().email(),password:z.string().min(6)}),se=z.object({id:z.string(),username:z.string(),email:z.string(),role:b$2,status:z.enum(["active","inactive","locked"]),avatar:z.string().nullish(),createdAt:z.string(),updatedAt:z.string()}),dn=z.array(se),pn=z.object({username:z.string().nullish(),email:z.string().email().nullish(),role:b$2.nullish(),status:z.enum(["active","inactive","locked"]).nullish()}),un=z.object({username:z.string().min(1),email:z.string().email(),password:z.string().min(6),role:b$2,status:z.enum(["active","inactive","locked"]).nullish().default("active")}),ln=z.object({deletedCount:z.number()}),Qt=z.object({}),mn=z.object({token:z.string(),downloadUrl:z.string(),expiresIn:z.number()});var tc=createRoute({method:"get",path:"/admin/me",tags:["admin"],security:[{Bearer:[]}],middleware:[m()],responses:{200:c(nt,"Get current authenticated user"),401:s("Unauthorized")}}),rc=createRoute({method:"post",path:"/admin/login",tags:["admin"],middleware:[Ie],request:{body:{content:{"application/json":{schema:Zt}}}},responses:{200:c(Jt,"Login successful"),401:s("Invalid credentials")}}),oc=createRoute({method:"post",path:"/admin/register",tags:["admin"],middleware:[Ie],request:{body:{content:{"application/json":{schema:Xt}}}},responses:{201:c(se,"User registered"),400:s("User already exists")}}),hn=new OpenAPIHono().openapi(tc,async e=>{let t=M(e);return e.json(d(t),200)}).openapi(rc,async e=>{try{let t=e.req.valid("json"),r=await Gt(t);return e.json(d(r),200)}catch{return e.json({success:false,error:"Invalid credentials"},401)}}).openapi(oc,async e=>{let t=e.req.valid("json"),r=await Kt(t);return e.json(d(r),201)});var nc=createRoute({method:"get",path:"/admin/users",tags:["admin"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["user:view"]})],responses:{200:c(dn,"Get user list"),401:s("Unauthorized"),403:s("Forbidden")}}),ic=createRoute({method:"get",path:"/admin/users/:id",tags:["admin"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["user:view"]})],request:{params:z.object({id:z.string()})},responses:{200:c(se,"Get user"),401:s("Unauthorized"),403:s("Forbidden"),404:s("User not found")}}),ac=createRoute({method:"put",path:"/admin/users/:id",tags:["admin"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["user:edit"]})],request:{params:z.object({id:z.string()}),body:{content:{"application/json":{schema:pn}}}},responses:{200:c(se,"User updated"),401:s("Unauthorized"),403:s("Forbidden"),404:s("User not found")}}),cc=createRoute({method:"delete",path:"/admin/users/:id",tags:["admin"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["user:delete"]})],request:{params:z.object({id:z.string()})},responses:{200:c(Qt,"User deleted"),401:s("Unauthorized"),403:s("Forbidden"),404:s("User not found")}}),dc=createRoute({method:"post",path:"/admin/users",tags:["admin"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["user:create"]})],request:{body:{content:{"application/json":{schema:un}}}},responses:{200:c(se,"User created"),401:s("Unauthorized"),403:s("Forbidden"),400:s("Invalid request")}}),fn=new OpenAPIHono().openapi(nc,async e=>{let t=await Xs();return e.json(d(t),200)}).openapi(ic,async e=>{let{id:t}=e.req.valid("param"),r=await Qs(t);return r?e.json(d(r),200):e.json({success:false,error:"User not found"},404)}).openapi(ac,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=await en(t,r);return e.json(d(o),200)}).openapi(cc,async e=>{let{id:t}=e.req.valid("param");return await tn(t),e.json(d({}),200)}).openapi(dc,async e=>{let t=e.req.valid("json"),r=await rn(t);return e.json(d(r),200)});h();var uc=createRoute({method:"get",path:"/admin/notifications",tags:["notifications"],security:[{Bearer:[]}],middleware:[m()],request:{query:z.object({unreadOnly:z.string().optional(),limit:z.string().optional()})},responses:{200:c(Fr,"Get notifications"),401:s("Unauthorized")}}),lc=createRoute({method:"get",path:"/admin/notifications/unread-count",tags:["notifications"],security:[{Bearer:[]}],middleware:[m()],responses:{200:c(ye,"Get unread count"),401:s("Unauthorized")}}),mc=createRoute({method:"put",path:"/admin/notifications/:id/read",tags:["notifications"],security:[{Bearer:[]}],middleware:[m()],request:{params:z.object({id:z.string()})},responses:{200:c(Qt,"Notification marked as read"),401:s("Unauthorized"),404:s("Notification not found")}}),hc=createRoute({method:"put",path:"/admin/notifications/read-all",tags:["notifications"],security:[{Bearer:[]}],middleware:[m()],responses:{200:c(zr,"All notifications marked as read"),401:s("Unauthorized")}}),fc=createRoute({method:"post",path:"/admin/notifications/test",tags:["notifications"],security:[{Bearer:[]}],middleware:[m({requiredRole:"super_admin"})],request:{body:{content:{"application/json":{schema:Br}}}},responses:{200:c(B,"Test notification sent"),401:s("Unauthorized"),403:s("Forbidden")}}),gc=createRoute({method:"get",path:"/admin/notifications/stream",tags:["notifications"],security:[{Bearer:[]}],middleware:[m()],responses:{200:{content:{"text/event-stream":{schema:De}},description:"SSE stream for admin notifications"},401:s("Unauthorized")}}),gn=new OpenAPIHono().openapi(uc,async e=>{let{unreadOnly:t,limit:r}=e.req.valid("query"),o=Bt({unreadOnly:t==="true",limit:r?parseInt(r,10):20});return e.json(d(o.data),200)}).openapi(lc,async e=>{let t=st();return e.json(d({count:t}),200)}).openapi(mc,async e=>{let{id:t}=e.req.valid("param");if(!$t(t))throw new f("Notification",t);try{let o=st();await Ye.broadcast("unread-count",{count:o});}catch(o){g.module("notification").debug({error:String(o)},"Broadcast failed");}return e.json(d({}),200)}).openapi(hc,async e=>{let t=Ht();try{await Ye.broadcast("unread-count",{count:0});}catch(r){g.module("notification").debug({error:String(r)},"Broadcast failed");}return e.json(d({count:t}),200)}).openapi(fc,async e=>{let{type:t}=e.req.valid("json"),r=await Wt({type:t??"info",title:t==="warning"?"\u8B66\u544A\u901A\u77E5":t==="error"?"\u9519\u8BEF\u901A\u77E5":t==="success"?"\u6210\u529F\u901A\u77E5":"\u7CFB\u7EDF\u901A\u77E5",message:t==="warning"?"\u8FD9\u662F\u4E00\u6761\u8B66\u544A\u901A\u77E5\uFF0C\u8BF7\u6CE8\u610F\uFF01":t==="error"?"\u8FD9\u662F\u4E00\u6761\u9519\u8BEF\u901A\u77E5\uFF0C\u8BF7\u7ACB\u5373\u5904\u7406\uFF01":t==="success"?"\u64CD\u4F5C\u6210\u529F\u5B8C\u6210\uFF01":"\u8FD9\u662F\u4E00\u6761\u666E\u901A\u4FE1\u606F\u901A\u77E5"});return e.json(d(r),200)}).openapi(gc,async e=>{let t=e.env;if(t?.REALTIME_DO){let n=t.REALTIME_DO.idFromName("global"),i=t.REALTIME_DO.get(n),a=new Request(e.req.url,{method:e.req.method,headers:e.req.raw.headers});return i.fetch(a)}let{getRuntimeAdapter:r}=await import('./runtime-HBG2YPJ4.js'),o=r();return o.handleSSERequest?await o.handleSSERequest():e.json({success:false,error:"SSE not supported"},500)});var Sc=createRoute({method:"get",path:"/admin/avatar/:id",tags:["media"],security:[{Bearer:[]}],middleware:[m()],request:{params:z.object({id:z.string()})},responses:{200:{content:{"image/png":{schema:z.any().openapi({type:"string",format:"binary"})},"image/jpeg":{schema:z.any().openapi({type:"string",format:"binary"})}},description:"User avatar image"},401:s("Unauthorized"),404:s("Avatar not found")}}),Rc=createRoute({method:"get",path:"/admin/icon/:name",tags:["media"],security:[{Bearer:[]}],middleware:[m()],request:{params:z.object({name:z.string()})},responses:{200:{content:{"image/svg+xml":{schema:z.string()}},description:"SVG icon"},401:s("Unauthorized"),404:s("Icon not found")}}),Sn=new OpenAPIHono().openapi(Sc,async e=>{let{id:t}=e.req.valid("param"),r=await on(t);return r?new Response(r.data,{headers:{"Content-Type":r.contentType}}):e.json({success:false,error:"Avatar not found"},404)}).openapi(Rc,async e=>{let{name:t}=e.req.valid("param"),r=await sn(t);return r?new Response(r,{headers:{"Content-Type":"image/svg+xml"}}):e.json({success:false,error:"Icon not found"},404)});var ct=new Map,vc=()=>{let e=Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15);return ct.set(e,{createdAt:Date.now(),expiresIn:6e4}),setTimeout(()=>ct.delete(e),6e4),e},Tc=e=>{let t=ct.get(e);return t?Date.now()-t.createdAt>t.expiresIn?(ct.delete(e),false):true:false},Ec=e=>{let t=Tc(e);return t&&ct.delete(e),t},bc=createRoute({method:"get",path:"/admin/todos/export",tags:["export"],security:[{Bearer:[]}],middleware:[m()],responses:{200:{content:{"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":{schema:z.any().openapi({type:"string",format:"binary"})},"text/csv":{schema:z.string()}},description:"Export todos as Excel or CSV"},401:s("Unauthorized")}}),xc=createRoute({method:"post",path:"/admin/todos/export/token",tags:["export"],security:[{Bearer:[]}],middleware:[m()],responses:{200:c(mn,"Generate a temporary download token"),401:s("Unauthorized")}}),Cc=createRoute({method:"get",path:"/admin/todos/export/download/:token",tags:["export"],request:{params:z.object({token:z.string()})},responses:{200:{content:{"text/csv":{schema:z.string()}},description:"Download CSV with temporary token"},403:s("Invalid or expired token")}}),Ac=createRoute({method:"get",path:"/admin/todos/export/stream",tags:["export"],security:[{Bearer:[]}],middleware:[m()],responses:{200:{content:{"text/csv":{schema:z.string()}},description:"Stream export todos as CSV (for large datasets)"},401:s("Unauthorized")}}),Rn=new OpenAPIHono().openapi(bc,async e=>{let t=await Yt(),r=new TextEncoder,o=new ReadableStream({async start(n){n.enqueue(r.encode(`id,title,completed,created_at
10
- `));for(let i of t){let a=`${Z(String(i.id))},${Z(i.title)},${i.completed},${Z(i.createdAt)}
11
- `;n.enqueue(r.encode(a)),await new Promise(u=>setTimeout(u,100));}n.close();}});return new Response(o,{headers:{"Content-Type":"text/csv","Content-Disposition":'attachment; filename="todos.csv"',"Cache-Control":"no-cache","X-Accel-Buffering":"no"}})}).openapi(xc,async e=>{let t=vc(),r=`/api/admin/todos/export/download/${t}`;return e.json(d({token:t,downloadUrl:r,expiresIn:6e4}),200)}).openapi(Cc,async e=>{let{token:t}=e.req.valid("param");if(!Ec(t))return e.json({success:false,error:"Invalid or expired token"},403);let r=await Yt(),o=new TextEncoder,n=new ReadableStream({async start(i){i.enqueue(o.encode(`id,title,completed,created_at
12
- `));for(let a of r){let u=`${Z(String(a.id))},${Z(a.title)},${a.completed},${Z(a.createdAt)}
13
- `;i.enqueue(o.encode(u)),await new Promise(l=>setTimeout(l,100));}i.close();}});return new Response(n,{headers:{"Content-Type":"text/csv","Content-Disposition":'attachment; filename="todos.csv"',"Cache-Control":"no-cache","X-Accel-Buffering":"no"}})}).openapi(Ac,async e=>{let t=await Yt(),r=new TextEncoder,o=new ReadableStream({async start(n){n.enqueue(r.encode(`id,title,completed,created_at
14
- `));for(let i=0;i<t.length;i++){let a=t[i],u=`${Z(String(a.id))},${Z(a.title)},${a.completed},${Z(a.createdAt)}
15
- `;n.enqueue(r.encode(u)),await new Promise(l=>setTimeout(l,300));}n.close();}});return new Response(o,{headers:{"Content-Type":"text/csv","Content-Disposition":'attachment; filename="todos-stream.csv"',"Cache-Control":"no-cache","X-Accel-Buffering":"no"}})});var Pc=createRoute({method:"get",path:"/admin/stats",tags:["admin"],security:[{Bearer:[]}],middleware:[m({requiredRole:"super_admin"})],responses:{200:c(nn,"Get system statistics"),401:s("Unauthorized"),403:s("Forbidden")}}),Uc=createRoute({method:"get",path:"/admin/health",tags:["admin"],security:[{Bearer:[]}],middleware:[m({requiredRole:"super_admin"})],responses:{200:c(an,"Get system health"),401:s("Unauthorized"),403:s("Forbidden")}}),Oc=createRoute({method:"get",path:"/admin/activity",tags:["admin"],security:[{Bearer:[]}],middleware:[m({requiredRole:"super_admin"})],request:{query:z.object({limit:z.string().optional()})},responses:{200:c(cn,"Get recent activity"),401:s("Unauthorized"),403:s("Forbidden")}}),Dc=createRoute({method:"delete",path:"/admin/todos/all",tags:["admin"],security:[{Bearer:[]}],middleware:[m({requiredRole:"super_admin"})],responses:{200:c(ln,"All todos cleared"),401:s("Unauthorized"),403:s("Forbidden")}}),vn=new OpenAPIHono().openapi(Pc,async e=>{let t=await Ks();return e.json(d(t),200)}).openapi(Uc,async e=>{let t=await Ys();return e.json(d(t),200)}).openapi(Oc,async e=>{let{limit:t}=e.req.valid("query"),r=t?parseInt(t,10):10,o=await Js(r);return e.json(d(o),200)}).openapi(Dc,async e=>{let t=await Zs();return e.json(d(t),200)});var qc=new OpenAPIHono().route("/",hn).route("/",fn),Nc=qc.route("/",gn).route("/",Sn),jc=Nc.route("/",Rn).route("/",vn),Tn=jc;var _c=createRoute({method:"post",path:"/auth/login",tags:["auth"],middleware:[Ie],request:{body:{content:{"application/json":{schema:Zt}}}},responses:{200:c(Jt,"Login successful"),401:s("Invalid credentials")}}),Lc=createRoute({method:"post",path:"/auth/register",tags:["auth"],middleware:[Ie],request:{body:{content:{"application/json":{schema:Xt}}}},responses:{201:c(se,"User registered"),400:s("User already exists")}}),Fc=createRoute({method:"get",path:"/auth/me",tags:["auth"],security:[{Bearer:[]}],middleware:[m()],responses:{200:c(nt,"Get current authenticated user"),401:s("Unauthorized")}}),En=new OpenAPIHono().openapi(_c,async e=>{try{let t=e.req.valid("json"),r=await Gt(t);return e.json(d(r),200)}catch{return e.json({success:false,error:"Invalid credentials"},401)}}).openapi(Lc,async e=>{try{let t=e.req.valid("json"),r=await Kt(t);return e.json(d(r),201)}catch{return e.json({success:false,error:"User already exists"},400)}}).openapi(Fc,async e=>{let t=M(e);return e.json(d(t),200)});var Re=new Map;function Jr(){Bc();let e=Math.random().toString(36).substring(2)+Date.now().toString(36),t=Math.random().toString(36).substring(2,7).toUpperCase();Re.set(e,{code:t,createdAt:Date.now(),attempts:0});let r=zc(t);return {id:e,image:r}}function Xr(e,t){let r=Re.get(e);if(!r)return false;if(Date.now()-r.createdAt>3e5||r.attempts>=3)return Re.delete(e),false;r.attempts++;let o=r.code.toUpperCase()===t.toUpperCase();return o&&Re.delete(e),o}function zc(e){let n=e.split("").map((u,l)=>{let p=30+l*30,T=35+Math.random()*10-5,P=(Math.random()-.5)*40,O=Math.random()*360;return `<text
16
- x="${p}"
17
- y="${T}"
9
+ `;o.enqueue(new TextEncoder().encode(n));},cancel:()=>{this.core.sseClients.delete(t);}});return new Response(r,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}},No=null;function zo(){return No||(No=new ir),No}var ar=null,cr=null;function oi(e){ar=e,cr=null;}function kp(){return a$8&&ar?.REALTIME_DO?{async broadcast(e,t){let r=ar.REALTIME_DO.idFromName("global");await ar.REALTIME_DO.get(r).fetch(new Request("https://internal/broadcast",{method:"POST",body:JSON.stringify({event:e,data:t})}));}}:{async broadcast(e,t){let{getRuntimeAdapter:r}=await import('./runtime-HBG2YPJ4.js');r().broadcast(e,t);}}}function Up(){return cr||(cr=kp()),cr}var Ct=new Proxy({},{get(e,t){let r=Up();return Reflect.get(r,t,r)}});function ni(){return async(e,t)=>{let r=e.env;r&&oi(r),await t();}}a();J();d();var Bo=class{async create(t){let o=await(await i$2()).insert(k$2).values({...t,createdAt:new Date}).returning();return c$8(o[0])}async getAll(t=50,r=0){return (await(await i$2()).select().from(k$2).orderBy(desc(k$2.createdAt)).limit(t).offset(r)).map(c$8)}async getByUserId(t,r=50){return (await(await i$2()).select().from(k$2).where(eq(k$2.userId,t)).orderBy(desc(k$2.createdAt)).limit(r)).map(c$8)}async getByResource(t,r){let o=await i$2(),n=[eq(k$2.resourceType,t)];return r&&n.push(eq(k$2.resourceId,r)),(await o.select().from(k$2).where(and(...n)).orderBy(desc(k$2.createdAt))).map(c$8)}async search(t){let r=await i$2(),o=[];return t.userId&&o.push(eq(k$2.userId,t.userId)),t.action&&o.push(eq(k$2.action,t.action)),t.resourceType&&o.push(eq(k$2.resourceType,t.resourceType)),t.startDate&&o.push(gte(k$2.createdAt,t.startDate)),t.endDate&&o.push(lte(k$2.createdAt,t.endDate)),(await r.select().from(k$2).where(o.length>0?and(...o):void 0).orderBy(desc(k$2.createdAt))).map(c$8)}async deleteOlderThan(t){let r=await i$2(),o=new Date;return o.setDate(o.getDate()-t),(await r.delete(k$2).where(lte(k$2.createdAt,o)).returning()).length}},tt=new Bo;h$1();var q={USER:"user",ROLE:"role",PERMISSION:"permission",CONTENT:"content",ROUTE:"route",ORDER:"order",TICKET:"ticket",DISPUTE:"dispute",FILE:"file",CHAT:"chat",NOTIFICATION:"notification",CAPTCHA:"captcha"},ai={users:q.USER,roles:q.ROLE,permissions:q.PERMISSION,contents:q.CONTENT,routes:q.ROUTE,orders:q.ORDER,tickets:q.TICKET,disputes:q.DISPUTE,files:q.FILE,chats:q.CHAT,notifications:q.NOTIFICATION,captchas:q.CAPTCHA},H={CREATE:"create",UPDATE:"update",DELETE:"delete",ASSIGN:"assign",REVOKE:"revoke"};var Me=g.api();function ci(){return async(e,t)=>{let r=Date.now(),o=e.req.path,n=e.req.method;await t();let i=Date.now()-r,u=e.res.status;if(Me.info({path:o,method:n,status:u,duration:i},"Audit log middleware checking"),!o.startsWith("/api/")||o.startsWith("/api/permissions/")){Me.info({path:o},"Skipping: not API or public API");return}if(!["POST","PUT","DELETE","PATCH"].includes(n)){Me.info({method:n},"Skipping: not write operation");return}if(u<200||u>=300){Me.info({status:u},"Skipping: not successful operation");return}let d=L(e);if(!d){Me.info({path:o},"Skipping: no user");return}let l=H.CREATE;n==="POST"?l=H.CREATE:n==="PUT"||n==="PATCH"?l=H.UPDATE:n==="DELETE"&&(l=H.DELETE);let m=o.split("/").filter(Boolean),R="user";if(m.length>=2){let v=m[1];R=ai[v]||"unknown";}try{await tt.create({id:`audit_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,userId:d.id,action:l,resourceType:R,resourceId:m.length>=3?m[2]:null,oldValue:null,newValue:null,ipAddress:e.req.header("x-forwarded-for")||e.req.header("x-real-ip")||null,userAgent:e.req.header("user-agent")||null}),Me.info({userId:d.id,action:l,resourceType:R,path:o,method:n,status:u,duration:i},"Audit log created");}catch(v){Me.error({error:v,path:o,method:n},"Failed to create audit log");}}}h$1();var ur=e=>z$1.object({success:z$1.literal(true),data:e,timestamp:z$1.string()}),qp=z$1.object({field:z$1.string().optional(),message:z$1.string(),code:z$1.string().optional()}),dr=z$1.object({success:z$1.literal(false),error:z$1.string(),code:z$1.string().optional(),status:z$1.number().optional(),details:z$1.array(qp).optional(),timestamp:z$1.string().optional()});var Fo=z$1.object({rpc:z$1.object({echo:z$1.object({in:z$1.object({message:z$1.string()}),out:z$1.object({message:z$1.string(),timestamp:z$1.number()})}),ping:z$1.object({in:z$1.object({}),out:z$1.object({pong:z$1.boolean(),timestamp:z$1.number()})})}),events:z$1.object({notification:z$1.object({title:z$1.string(),body:z$1.string(),timestamp:z$1.number()}),broadcast:z$1.object({message:z$1.string(),timestamp:z$1.number()}),connected:z$1.object({timestamp:z$1.number()}),disconnected:z$1.object({timestamp:z$1.number()})})}),Ho=z$1.object({connectedClients:z$1.number()});var Ne=z$1.object({namespace:z$1.string(),filename:z$1.string()}),Tt=z$1.object({expiry:z$1.string().transform(Number),signature:z$1.string()}),Wo=z$1.object({url:z$1.string()}),$o=z$1.object({url:z$1.string(),expiry:z$1.number()}),lr=z$1.object({namespace:z$1.string(),filename:z$1.string(),isPrivate:z$1.boolean().nullish().default(false),expirySeconds:z$1.number().nullish()}),mr=z$1.union([Wo,$o]);z$1.object({});var gr=z$1.object({filename:z$1.string(),originalName:z$1.string(),mimeType:z$1.string(),size:z$1.number(),url:z$1.string()}),hr=z$1.object({file:z$1.instanceof(File),namespace:z$1.string().nullish().default("uploads")});var fr=z$1.enum(["pending","in_progress","completed"]),Ee=z$1.object({id:z$1.number().int().positive(),title:z$1.string().min(1,"Title is required").max(200,"Title too long"),description:z$1.string().max(1e3,"Description too long").nullish(),status:fr,createdAt:z$1.string().datetime(),updatedAt:z$1.string().datetime()}),yr=z$1.object({title:z$1.string().min(1,"Title is required").max(200,"Title too long"),description:z$1.string().max(1e3,"Description too long").nullish()}),Sr=z$1.object({title:z$1.string().min(1,"Title is required").max(200,"Title too long").nullish(),description:z$1.string().max(1e3,"Description too long").nullish(),status:fr.nullish()});z$1.object({id:z$1.coerce.number().int().positive()});var wr=z$1.object({id:z$1.number()}),Pt=z$1.object({id:z$1.number().int().positive(),todoId:z$1.number().int().positive(),fileName:z$1.string(),originalName:z$1.string(),mimeType:z$1.string(),size:z$1.number().int().positive(),path:z$1.string(),uploadedBy:z$1.string().nullish(),createdAt:z$1.string().datetime()}),At=z$1.array(Pt),Rr=Ee.extend({attachments:At}),vr=z$1.object({file:z$1.file().openapi({type:"string",format:"binary"})}),br=z$1.object({id:z$1.number()});var Et=z$1.enum(["info","warning","success","error"]),ce=z$1.object({id:z$1.string().uuid(),type:Et,title:z$1.string().min(1).max(200),message:z$1.string().max(2e3),read:z$1.boolean().default(false),createdAt:z$1.string().datetime()}),xr=z$1.object({type:Et,title:z$1.string().min(1,"Title is required").max(200,"Title too long"),message:z$1.string().min(1,"Message is required").max(2e3,"Message too long")});z$1.object({unreadOnly:z$1.coerce.boolean().nullish().default(false),limit:z$1.coerce.number().int().min(1).max(100).nullish().default(20),cursor:z$1.string().nullish()});z$1.object({event:z$1.enum(["notification","ping","connected"]),data:z$1.union([ce,z$1.object({timestamp:z$1.number()})])});var Vo=z$1.object({count:z$1.number()}),rt=z$1.object({events:z$1.object({notification:ce,"unread-count":Vo,ping:z$1.object({timestamp:z$1.number()}),connected:z$1.object({timestamp:z$1.number()})})}),Le=z$1.object({count:z$1.number()}),Cr=z$1.object({id:z$1.string()}),Go=z$1.array(ce),Ko=z$1.object({count:z$1.number()}),Qo=z$1.object({type:Et.nullish().default("info")});var It=z$1.object({id:z$1.string(),username:z$1.string(),email:z$1.string().email(),role:z$1.string(),createdAt:z$1.string().datetime()}),Tr=z$1.object({account:z$1.string().nullish(),email:z$1.string().email().nullish(),password:z$1.string().min(6)}).refine(e=>e.account||e.email,{message:"Either account or email is required",path:["account"]}),Pr=z$1.object({username:z$1.string().min(3).max(50),email:z$1.string().email(),password:z$1.string().min(6).max(100)}),kt=z$1.object({token:z$1.string(),profile:It});z$1.object({id:z$1.string(),username:z$1.string(),email:z$1.string().email(),bio:z$1.string().optional().nullable(),joinDate:z$1.string(),stats:z$1.object({posts:z$1.number(),followers:z$1.number(),following:z$1.number()})});var Ut=z$1.enum(["pending","approved","rejected"]),Z=z$1.object({id:z$1.string(),name:z$1.string().min(1).max(200),slug:z$1.string().min(1).max(200),description:z$1.string().max(2e3),readme:z$1.string().nullish(),authorId:z$1.string(),authorName:z$1.string(),repositoryUrl:z$1.string().url().nullish(),homepageUrl:z$1.string().url().nullish(),npmPackage:z$1.string().nullish(),license:z$1.string().nullish(),version:z$1.string(),status:Ut,downloadCount:z$1.number().int().nonnegative().default(0),viewCount:z$1.number().int().nonnegative().default(0),featured:z$1.boolean().default(false),screenshotUrl:z$1.string().nullish(),siteUrls:z$1.array(z$1.string().url()).nullish(),tags:z$1.array(z$1.string()).nullish(),commands:z$1.array(z$1.object({name:z$1.string(),description:z$1.string().nullish()})).nullish(),rejectReason:z$1.string().nullish(),createdAt:z$1.number(),updatedAt:z$1.number()}),jt=z$1.object({name:z$1.string().min(1).max(200),slug:z$1.string().min(1).max(200).regex(/^[a-z0-9-]+$/),description:z$1.string().min(1).max(2e3),repositoryUrl:z$1.string().url().nullish(),homepageUrl:z$1.string().url().nullish(),npmPackage:z$1.string().nullish(),license:z$1.string().nullish(),tags:z$1.array(z$1.string()).nullish(),siteUrls:z$1.array(z$1.string().url()).nullish(),commands:z$1.array(z$1.object({name:z$1.string(),description:z$1.string().nullish()})).nullish()}),Ar=jt.partial(),Jo=z$1.enum(["pending","approved","rejected"]),Er=z$1.object({id:z$1.string(),pluginId:z$1.string(),version:z$1.string(),changelog:z$1.string().nullish(),packageUrl:z$1.string().nullish(),fileSize:z$1.number().nullish(),checksum:z$1.string().nullish(),status:Jo,publishedAt:z$1.number()}),Ie=z$1.object({id:z$1.string(),name:z$1.string(),slug:z$1.string(),description:z$1.string().nullish(),icon:z$1.string().nullish(),sortOrder:z$1.number().int().default(0)}),qt=z$1.object({id:z$1.string(),pluginId:z$1.string(),userId:z$1.string(),userName:z$1.string(),rating:z$1.number().int().min(1).max(5),title:z$1.string().nullish(),content:z$1.string().nullish(),createdAt:z$1.number()}),Ir=z$1.object({rating:z$1.number().int().min(1).max(5),title:z$1.string().max(200).nullish(),content:z$1.string().max(2e3).nullish()}),kr=z$1.object({totalPlugins:z$1.number(),totalDownloads:z$1.number(),totalDevelopers:z$1.number(),totalCategories:z$1.number()}),ot=z$1.object({plugins:z$1.array(Z),total:z$1.number(),page:z$1.number(),limit:z$1.number()}),Yo=Z.extend({avgRating:z$1.number().nullish(),reviewCount:z$1.number().nullish()}),Ur=z$1.object({totalPlugins:z$1.number(),pendingPlugins:z$1.number(),totalDownloads:z$1.number(),totalDevelopers:z$1.number(),totalCategories:z$1.number(),recentSubmissions:z$1.array(Yo).nullish()}),jr=z$1.object({page:z$1.coerce.number().int().positive().default(1),limit:z$1.coerce.number().int().positive().max(100).default(20),search:z$1.string().nullish(),status:Ut.nullish(),category:z$1.string().nullish(),sort:z$1.enum(["newest","popular","downloads","name"]).default("newest"),featured:z$1.coerce.boolean().nullish()}),K=z$1.object({slug:z$1.string().min(1)}),qr=z$1.object({q:z$1.string().min(1),page:z$1.coerce.number().int().positive().default(1),limit:z$1.coerce.number().int().positive().max(100).default(20),category:z$1.string().nullish()}),ze=z$1.object({slug:z$1.string()}),Dr=z$1.object({slug:z$1.string(),reviewId:z$1.string()}),Or=z$1.object({id:z$1.string()}),Mr=z$1.object({slug:z$1.string()}),Nr=z$1.object({page:z$1.coerce.number().int().positive().default(1),limit:z$1.coerce.number().int().positive().max(100).default(20)}),Dt=z$1.object({plugins:z$1.array(Z),total:z$1.number(),page:z$1.number(),limit:z$1.number()}),Lr=z$1.object({page:z$1.coerce.number().int().positive().default(1),limit:z$1.coerce.number().int().positive().max(100).default(20)}),zr=z$1.object({page:z$1.coerce.number().int().positive().default(1),limit:z$1.coerce.number().int().positive().max(100).default(20),status:Ut.nullish()}),Br=z$1.object({reason:z$1.string().min(1)}),_r=z$1.object({slugs:z$1.array(z$1.string()).min(1)}),Fr=z$1.object({slugs:z$1.array(z$1.string()).min(1),reason:z$1.string().min(1)}),Ot=z$1.object({count:z$1.number()}),Hr=z$1.object({name:z$1.string().min(1),slug:z$1.string().min(1),description:z$1.string().nullish(),icon:z$1.string().nullish()}),Wr=z$1.object({name:z$1.string().nullish(),slug:z$1.string().nullish(),description:z$1.string().nullish(),icon:z$1.string().nullish(),sortOrder:z$1.number().int().nullish()}),Mt=z$1.object({id:z$1.string()}),$r=z$1.object({id:z$1.string()});var gi=z$1.object({label:z$1.string(),value:z$1.string(),trend:z$1.number()}),Zo=z$1.object({month:z$1.string(),value:z$1.number()}),hi=z$1.enum(["Active","Pending","Inactive"]),fi=z$1.object({id:z$1.number(),user:z$1.string(),action:z$1.string(),date:z$1.string(),status:hi}),Xo=z$1.object({stats:z$1.array(gi),revenue:z$1.array(Zo),userGrowth:z$1.array(Zo),activity:z$1.array(fi)});var Vr=z$1.object({id:z$1.number(),name:z$1.string(),variant:z$1.string(),price:z$1.number(),quantity:z$1.number(),color:z$1.string()}),yi=z$1.object({subtotal:z$1.number(),shipping:z$1.number(),tax:z$1.number(),total:z$1.number(),totalItems:z$1.number()}),en=z$1.object({items:z$1.array(Vr),summary:yi}),tn=z$1.object({id:z$1.number(),name:z$1.string(),variant:z$1.string(),price:z$1.number(),quantity:z$1.number().min(1).default(1),color:z$1.string()});z$1.object({id:z$1.string()});var Gr=z$1.enum(["pending","processing","completed","cancelled","disputed"]),ee=z$1.object({id:z$1.string(),orderNo:z$1.string(),customerName:z$1.string(),customerEmail:z$1.string(),productName:z$1.string(),amount:z$1.number(),status:Gr,createdAt:z$1.string(),updatedAt:z$1.string()}),rn=z$1.object({customerName:z$1.string(),customerEmail:z$1.string().email(),productName:z$1.string(),amount:z$1.number().positive()}),on=z$1.object({status:Gr.nullish()}),nn=z$1.array(ee),sn=z$1.object({status:Gr.nullish(),customerName:z$1.string().nullish(),limit:z$1.coerce.number().int().positive().max(100).default(20),offset:z$1.coerce.number().int().min(0).default(0)}),an=z$1.object({message:z$1.string()});z$1.object({orderId:z$1.string()});z$1.object({orderId:z$1.string(),reason:z$1.string().nullish()});var cn=z$1.object({removedId:z$1.string()}),Si=z$1.object({name:z$1.string(),color:z$1.string()}),wi=z$1.enum(["processing","shipped","delivered","cancelled"]),Ri=z$1.object({id:z$1.string(),date:z$1.string(),status:wi,products:z$1.array(Si),total:z$1.number()}),pn=z$1.array(Ri);var vi=z$1.enum(["hot","unanswered","solved"]),bi=z$1.object({label:z$1.string(),color:z$1.string()}),xi=z$1.object({name:z$1.string(),initials:z$1.string()}),Ci=z$1.object({id:z$1.string(),title:z$1.string(),excerpt:z$1.string(),votes:z$1.number(),replyCount:z$1.number(),viewCount:z$1.number(),status:vi,tags:z$1.array(bi),author:xi,createdAt:z$1.string()}),Kr=z$1.array(Ci),Ti=z$1.object({topics:z$1.number(),replies:z$1.number(),likes:z$1.number()}),Pi=z$1.enum(["topic","reply","like"]),Ai=z$1.object({id:z$1.string(),type:Pi,text:z$1.string(),target:z$1.string(),time:z$1.string()}),un=z$1.object({stats:Ti,activity:z$1.array(Ai)});var Nt=z$1.enum(["active","suspended","trial"]),nt=z$1.enum(["free","starter","pro","enterprise"]),Lt=z$1.record(z$1.string(),z$1.unknown()).nullable(),dn=z$1.object({id:z$1.number().int().positive(),name:z$1.string().min(1).max(200),slug:z$1.string().min(1).max(100).regex(/^[a-z0-9-]+$/),status:Nt,plan:nt,maxUsers:z$1.number().int().min(1).max(1e3),settings:Lt,createdAt:z$1.string().datetime(),updatedAt:z$1.string().datetime()});z$1.object({name:z$1.string().min(1).max(200),slug:z$1.string().min(1).max(100).regex(/^[a-z0-9-]+$/),plan:nt.default("free"),maxUsers:z$1.number().int().min(1).max(1e3).default(5),settings:Lt});z$1.object({name:z$1.string().min(1).max(200).nullish(),status:Nt.nullish(),plan:nt.nullish(),maxUsers:z$1.number().int().min(1).max(1e3).nullish(),settings:Lt.nullish()});z$1.object({id:z$1.coerce.number().int().positive()});z$1.object({slug:z$1.string()});z$1.object({items:z$1.array(dn),total:z$1.number(),page:z$1.number(),pageSize:z$1.number()});z$1.object({id:z$1.number()});z$1.object({status:Nt.nullish(),plan:nt.nullish(),page:z$1.coerce.number().int().positive().default(1),pageSize:z$1.coerce.number().int().positive().max(100).default(20)});var ln=z$1.enum(["refund","product_quality","service_quality","delivery","other"]),mn=z$1.enum(["pending","investigating","resolved","rejected"]),fe=z$1.object({id:z$1.string(),disputeNo:z$1.string(),orderId:z$1.string(),orderNo:z$1.string(),customerName:z$1.string(),customerEmail:z$1.string(),type:ln,status:mn,description:z$1.string(),resolution:z$1.string().nullish(),amount:z$1.number(),createdAt:z$1.string(),updatedAt:z$1.string(),resolvedAt:z$1.string().nullish(),resolvedBy:z$1.string().nullish()}),gn=z$1.object({orderId:z$1.string(),orderNo:z$1.string(),customerName:z$1.string(),customerEmail:z$1.string().email(),type:ln,description:z$1.string(),amount:z$1.number().positive()}),hn=z$1.object({status:mn.nullish(),resolution:z$1.string().nullish()}),fn=z$1.object({resolution:z$1.string(),resolvedBy:z$1.string()}),yn=z$1.array(fe),Oi=z$1.object({message:z$1.string()});var Sn=z$1.object({id:z$1.string(),name:z$1.string().min(1).max(200),description:z$1.string().max(1e3),price:z$1.number().positive(),status:z$1.enum(["active","inactive","out_of_stock"]),stock:z$1.number().int().min(0),imageUrl:z$1.string().url().nullable(),createdAt:z$1.string().datetime(),updatedAt:z$1.string().datetime()});z$1.object({name:z$1.string().min(1).max(200),description:z$1.string().max(1e3),price:z$1.number().positive(),status:z$1.enum(["active","inactive","out_of_stock"]).default("active"),stock:z$1.number().int().min(0).default(0),imageUrl:z$1.string().url().nullable()});z$1.object({name:z$1.string().min(1).max(200).optional(),description:z$1.string().max(1e3).optional(),price:z$1.number().positive().optional(),status:z$1.enum(["active","inactive","out_of_stock"]).optional(),stock:z$1.number().int().min(0).optional(),imageUrl:z$1.string().url().nullable().optional()});z$1.array(Sn);function p(e){return {success:true,data:e,timestamp:new Date().toISOString()}}function z(e){return {success:true,data:e,timestamp:new Date().toISOString()}}function c(e,t){return {content:{"application/json":{schema:ur(e)}},description:t}}function s(e){return {content:{"application/json":{schema:dr}},description:e}}function zi(e,t){return c(z$1.object({items:z$1.array(e),nextCursor:z$1.string().optional()}),t)}var Bp=z$1.object({id:z$1.string()}),Bi={params:Bp};function Qr(e){return {body:{content:{"application/json":{schema:e}}}}}var Fp=z$1.array(Ee),Hp=createRoute({method:"get",path:"/todos",tags:["todos"],responses:{200:c(Fp,"List all todos"),500:s("Internal server error")}}),Wp=createRoute({method:"get",path:"/todos/{id}",tags:["todos"],request:{params:z$1.object({id:z$1.coerce.number().int().positive()})},responses:{200:c(Ee,"Get a todo by ID"),404:s("Todo not found")}}),$p=createRoute({method:"post",path:"/todos",tags:["todos"],security:[{Bearer:[]}],middleware:[h()],request:{body:{content:{"application/json":{schema:yr}}}},responses:{201:c(Ee,"Create a new todo"),400:s("Invalid input")}}),Vp=createRoute({method:"put",path:"/todos/{id}",tags:["todos"],security:[{Bearer:[]}],middleware:[h()],request:{params:z$1.object({id:z$1.coerce.number().int().positive()}),body:{content:{"application/json":{schema:Sr}}}},responses:{200:c(Ee,"Update a todo"),404:s("Todo not found")}}),Gp=createRoute({method:"delete",path:"/todos/{id}",tags:["todos"],security:[{Bearer:[]}],middleware:[h()],request:{params:z$1.object({id:z$1.coerce.number().int().positive()})},responses:{200:c(wr,"Delete a todo"),404:s("Todo not found")}}),Kp=createRoute({method:"post",path:"/todos/{id}/attachments",tags:["todos"],security:[{Bearer:[]}],middleware:[h()],request:{params:z$1.object({id:z$1.coerce.number().int().positive()}),body:{required:true,content:{"multipart/form-data":{schema:vr}}}},responses:{201:c(Pt,"File uploaded successfully"),404:s("Todo not found"),400:s("Invalid file or file too large")}}),Qp=createRoute({method:"get",path:"/todos/{id}/attachments",tags:["todos"],security:[{Bearer:[]}],middleware:[h()],request:{params:z$1.object({id:z$1.coerce.number().int().positive()})},responses:{200:c(At,"List attachments"),404:s("Todo not found")}}),Jp=createRoute({method:"get",path:"/todos/{id}/with-attachments",tags:["todos"],security:[{Bearer:[]}],middleware:[h()],request:{params:z$1.object({id:z$1.coerce.number().int().positive()})},responses:{200:c(Rr,"Get todo with attachments"),404:s("Todo not found")}}),Yp=createRoute({method:"delete",path:"/todos/{todoId}/attachments/{attachmentId}",tags:["todos"],security:[{Bearer:[]}],middleware:[h()],request:{params:z$1.object({todoId:z$1.coerce.number().int().positive(),attachmentId:z$1.coerce.number().int().positive()})},responses:{200:c(br,"Attachment deleted"),404:s("Attachment not found")}}),_i=new OpenAPIHono().openapi(Hp,async e=>{let t=await j();return e.json(p(t),200)}).openapi(Wp,async e=>{let{id:t}=e.req.valid("param"),r=await k(t);if(!r)throw new e$1("Todo",String(t));return e.json(p(r),200)}).openapi($p,async e=>{let t=e.req.valid("json"),r=await l(t);return e.json(z(r),201)}).openapi(Vp,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=await m(t,r);if(!o)throw new e$1("Todo",String(t));return e.json(p(o),200)}).openapi(Gp,async e=>{let{id:t}=e.req.valid("param");if(!await n(t))throw new e$1("Todo",String(t));return e.json(p({id:t}),200)}).openapi(Kp,async e=>{let{id:t}=e.req.valid("param");if(!await k(t))throw new e$1("Todo",String(t));let n=e.req.valid("form").file;if(!n||!(n instanceof File))throw new b$1("No file uploaded");let i=L(e),u=await n.arrayBuffer();try{let d=await o(t,{name:n.name,type:n.type,size:n.size,data:u},i?.id);return e.json(z(d),201)}catch(d){throw new b$1(d.message)}}).openapi(Qp,async e=>{let{id:t}=e.req.valid("param");if(!await k(t))throw new e$1("Todo",String(t));let o=await p$1(t);return e.json(p(o),200)}).openapi(Jp,async e=>{let{id:t}=e.req.valid("param"),r=await q$1(t);if(!r)throw new e$1("Todo",String(t));return e.json(p(r),200)}).openapi(Yp,async e=>{let{attachmentId:t}=e.req.valid("param");if(!await r(t))throw new e$1("Attachment",String(t));return e.json(p({id:t}),200)}).doc("/docs",{openapi:"3.0.0",info:{version:"1.0.0",title:"Todo API"}});var Xp=createRoute({method:"get",path:"/permissions/roles",tags:["permissions"],responses:{200:c(d$1.array(),"Get all roles")}}),eu=createRoute({method:"get",path:"/permissions",tags:["permissions"],responses:{200:c(e$2.array(),"Get all permissions")}}),tu=createRoute({method:"get",path:"/permissions/me",tags:["permissions"],security:[{Bearer:[]}],middleware:[h()],responses:{200:c(f$6,"Get current user permissions"),401:s("Unauthorized")}}),ru=createRoute({method:"get",path:"/permissions/menu-config",tags:["permissions"],responses:{200:c(g$6,"Get menu configuration")}}),ou=createRoute({method:"get",path:"/permissions/page-permissions",tags:["permissions"],responses:{200:c(h$7,"Get page permissions configuration")}}),nu=createRoute({method:"get",path:"/permissions/categories",tags:["permissions"],responses:{200:c(i$1,"Get permission categories")}}),su=createRoute({method:"get",path:"/permissions/role-labels",tags:["permissions"],responses:{200:c(j$2,"Get role labels")}}),iu=createRoute({method:"get",path:"/permissions/permission-labels",tags:["permissions"],responses:{200:c(k$1,"Get permission labels")}}),au=createRoute({method:"get",path:"/permissions/my-menu",tags:["permissions"],security:[{Bearer:[]}],middleware:[h()],responses:{200:c(g$6,"Get user menu configuration"),401:s("Unauthorized")}}),cu=createRoute({method:"get",path:"/permissions/init",tags:["permissions"],security:[{Bearer:[]}],middleware:[h()],responses:{200:c(l$2,"Get permission initialization data"),401:s("Unauthorized")}}),Fi=new OpenAPIHono().openapi(Xp,async e=>{let t$1=await t.getAllRoles();return e.json(p(t$1),200)}).openapi(eu,async e=>{let t$1=await t.getAllPermissions();return e.json(p(t$1),200)}).openapi(tu,async e=>{let t$1=L(e),o=(await t.getUserPermissions(t$1.id,t$1.role)).map(n=>n.code);return e.json(p({userId:t$1.id,role:t$1.role,permissions:o}),200)}).openapi(ru,async e=>{let t=n$1();return e.json(p(t),200)}).openapi(ou,async e=>{let t=o$1();return e.json(p(t),200)}).openapi(nu,async e=>{let t=p$2();return e.json(p(t),200)}).openapi(su,async e=>{let t=q$2();return e.json(p(t),200)}).openapi(iu,async e=>{let t=r$1();return e.json(p(t),200)}).openapi(au,async e=>{let t$1=L(e),r=await t.getUserMenuConfig(t$1.id,t$1.role);return e.json(p(r),200)}).openapi(cu,async e=>{let t$1=L(e),[r,o,n]=await Promise.all([t.getUserPermissions(t$1.id,t$1.role),t.getUserMenuConfig(t$1.id,t$1.role),t.getUserPagePermissions(t$1.id,t$1.role)]),i=r.map(u=>u.code);return e.json(p({permissions:i,menuConfig:o,pagePermissions:n,role:t$1.role}),200)});var Hi=z$1.union([z$1.string(),z$1.date(),z$1.null()]).transform(e=>e instanceof Date?e.toISOString():e===null?new Date().toISOString():e),Bt=z$1.object({id:z$1.string(),code:z$1.string(),name:z$1.string(),label:z$1.string(),description:z$1.string().optional().nullable(),isSystem:z$1.boolean().nullable(),isActive:z$1.boolean().nullable(),sortOrder:z$1.number().nullable(),createdAt:Hi,updatedAt:Hi}),Wi=z$1.object({code:z$1.string().min(1),name:z$1.string().min(1),label:z$1.string().min(1),description:z$1.string().nullish(),sortOrder:z$1.number().nullish()}),$i=z$1.object({name:z$1.string().nullish(),label:z$1.string().nullish(),description:z$1.string().nullish(),sortOrder:z$1.number().nullish(),isActive:z$1.boolean().nullish()}),Vi=z$1.object({permissionIds:z$1.array(z$1.string())}),wn=z$1.object({});var pu={"user:create":["user:view"],"user:edit":["user:view"],"user:delete":["user:view"],"content:create":["content:view"],"content:edit":["content:view"],"content:delete":["content:view"],"order:process":["order:view"],"order:cancel":["order:view"],"order:complete":["order:view"],"ticket:reply":["ticket:view"],"ticket:close":["ticket:view"],"data:export":["user:view"],"system:settings":["system:logs"]};function Gi(e){let t=[];for(let r of e){let o=pu[r];if(o){let n=o.filter(i=>!e.includes(i));n.length>0&&t.push(`\u6743\u9650 "${r}" \u9700\u8981\u4EE5\u4E0B\u6743\u9650: ${n.join(", ")}`);}}return {valid:t.length===0,errors:t}}var du=Bt.extend({permissions:z$1.array(z$1.string())}),lu=createRoute({method:"get",path:"/roles",tags:["roles"],security:[{Bearer:[]}],middleware:[h({requiredRole:"super_admin"})],responses:{200:c(Bt.array(),"Get all roles"),401:s("Unauthorized"),403:s("Forbidden")}}),mu=createRoute({method:"get",path:"/roles/:id",tags:["roles"],security:[{Bearer:[]}],middleware:[h({requiredRole:"super_admin"})],request:{params:z$1.object({id:z$1.string()})},responses:{200:c(du,"Get role by ID"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Role not found")}}),gu=createRoute({method:"post",path:"/roles",tags:["roles"],security:[{Bearer:[]}],middleware:[h({requiredRole:"super_admin"})],request:{body:{content:{"application/json":{schema:Wi}}}},responses:{200:c(Bt,"Role created"),401:s("Unauthorized"),403:s("Forbidden"),400:s("Invalid request")}}),hu=createRoute({method:"put",path:"/roles/:id",tags:["roles"],security:[{Bearer:[]}],middleware:[h({requiredRole:"super_admin"})],request:{params:z$1.object({id:z$1.string()}),body:{content:{"application/json":{schema:$i}}}},responses:{200:c(Bt,"Role updated"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Role not found")}}),fu=createRoute({method:"delete",path:"/roles/:id",tags:["roles"],security:[{Bearer:[]}],middleware:[h({requiredRole:"super_admin"})],request:{params:z$1.object({id:z$1.string()})},responses:{200:c(wn,"Role deleted"),401:s("Unauthorized"),403:s("Forbidden"),400:s("Cannot delete system role")}}),yu=createRoute({method:"put",path:"/roles/:id/permissions",tags:["roles"],security:[{Bearer:[]}],middleware:[h({requiredRole:"super_admin"})],request:{params:z$1.object({id:z$1.string()}),body:{content:{"application/json":{schema:Vi}}}},responses:{200:c(wn,"Role permissions updated"),400:s("Permission dependency validation failed"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Role not found")}}),Ki=new OpenAPIHono().openapi(lu,async e=>{let t=await m$1.getAll();return e.json(p(t),200)}).openapi(mu,async e=>{let{id:t$1}=e.req.valid("param"),r=await m$1.getById(t$1);if(!r)return e.json({success:false,error:"Role not found"},404);let o=await t.getRolePermissions(t$1);return e.json(p({...r,permissions:o.map(n=>n.code)}),200)}).openapi(gu,async e=>{let t=e.req.valid("json"),r=await m$1.create({id:`role_${Date.now()}`,...t,sortOrder:t.sortOrder??0});return e.json(p(r),200)}).openapi(hu,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=Object.fromEntries(Object.entries(r).filter(([i,u])=>u!=null)),n=await m$1.update(t,o);return n?e.json(p(n),200):e.json({success:false,error:"Role not found"},404)}).openapi(fu,async e=>{let{id:t}=e.req.valid("param");return await m$1.delete(t)?e.json(p({}),200):e.json({success:false,error:"Cannot delete system role or role not found"},400)}).openapi(yu,async e=>{let{id:t$1}=e.req.valid("param"),{permissionIds:r}=e.req.valid("json"),o=await m$1.getById(t$1);if(!o)return e.json({success:false,error:"Role not found"},404);if(o.code==="super_admin")return e.json({success:false,error:"Cannot modify super admin permissions"},403);let n=Gi(r);if(!n.valid)return e.json({success:false,error:"\u6743\u9650\u4F9D\u8D56\u6821\u9A8C\u5931\u8D25",details:n.errors.map(m=>({message:m}))},400);let u=(await Promise.all(r.map(m=>t.getByCode(m)))).filter(m=>m!==void 0).map(m=>m.id),l=(await t.getRolePermissions(t$1)).map(m=>m.id);for(let m of l)u.includes(m)||await t.revokePermissionFromRole(t$1,m);for(let m of u)l.includes(m)||await t.assignPermissionToRole(t$1,m);return e.json(p({}),200)});var Rn=z$1.enum(Object.values(q)),vn=z$1.enum(Object.values(H)),bn=z$1.object({id:z$1.string(),userId:z$1.string(),action:vn,resourceType:Rn,resourceId:z$1.string().nullable(),oldValue:z$1.string().nullable(),newValue:z$1.string().nullable(),ipAddress:z$1.string().nullable(),userAgent:z$1.string().nullable(),createdAt:z$1.union([z$1.string(),z$1.date()]).transform(e=>e instanceof Date?e.toISOString():e)});var wu=createRoute({method:"get",path:"/audit-logs",tags:["audit-logs"],security:[{Bearer:[]}],middleware:[h()],request:{query:z$1.object({limit:z$1.string().optional(),offset:z$1.string().optional(),userId:z$1.string().optional(),action:vn.optional(),resourceType:Rn.optional()})},responses:{200:c(bn.array(),"Get audit logs"),401:s("Unauthorized")}}),Ru=createRoute({method:"get",path:"/audit-logs/:id",tags:["audit-logs"],security:[{Bearer:[]}],middleware:[h()],request:{params:z$1.object({id:z$1.string()})},responses:{200:c(bn,"Get audit log by ID"),404:s("Audit log not found"),401:s("Unauthorized")}}),Ji=new OpenAPIHono().openapi(wu,async e=>{let t=e.req.valid("query"),r=t.limit?parseInt(t.limit):50,o=t.offset?parseInt(t.offset):0;if(t.userId||t.action||t.resourceType){let i=await tt.search({userId:t.userId,action:t.action,resourceType:t.resourceType});return e.json(p(i.slice(o,o+r)),200)}let n=await tt.getAll(r,o);return e.json(p(n),200)}).openapi(Ru,async e=>{let{id:t}=e.req.valid("param"),o=(await tt.getAll(1e3,0)).find(n=>n.id===t);return o?e.json(p(o),200):e.json({success:false,error:"Audit log not found"},404)});h$1();var ke=[];function Jr(e){let t=[...ke];e.unreadOnly&&(t=t.filter(u=>!u.read)),t.sort((u,d)=>new Date(d.createdAt).getTime()-new Date(u.createdAt).getTime());let r=e.limit??20,o=0;if(e.cursor){let u=t.findIndex(d=>d.id===e.cursor);u!==-1&&(o=u+1);}let n=t.slice(o,o+r),i=n.length===r?n[n.length-1]?.id:void 0;return {data:n,nextCursor:i}}function Yi(e){return ke.find(t=>t.id===e)}function vu(e){let t={id:a$6(),type:e.type,title:e.title,message:e.message,read:false,createdAt:new Date().toISOString()};return ke.unshift(t),t}async function Yr(e){let t=vu(e);try{await Ct.broadcast("notification",t);}catch(r){g.module("notification").debug({error:String(r)},"Broadcast failed");}return t}function Zr(e){let t=ke.find(r=>r.id===e);return t&&(t.read=true),t}function Xr(){let e=0;return ke.forEach(t=>{t.read||(t.read=true,e++);}),e}function Zi(e){let t=ke.findIndex(r=>r.id===e);return t!==-1?(ke.splice(t,1),true):false}function _t(){return ke.filter(e=>!e.read).length}function ea(){let e=new ReadableStream({start(t){let r=new TextEncoder,o=()=>{t.enqueue(r.encode(`event: ping
10
+ data: {"timestamp":${Date.now()}}
11
+
12
+ `));};o();let n=setInterval(o,3e4);setTimeout(()=>{clearInterval(n),t.close();},3e5);}});return new Response(e,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}var xu=createRoute({method:"get",path:"/notifications/stream",tags:["notifications"],responses:{200:{content:{"text/event-stream":{schema:rt}},description:"SSE stream for notifications"},500:s("Internal server error")}}),Cu=createRoute({method:"get",path:"/notifications",tags:["notifications"],request:{query:z$1.object({unreadOnly:z$1.string().optional(),limit:z$1.string().optional(),cursor:z$1.string().optional()})},responses:{200:zi(ce,"List notifications"),500:s("Internal server error")}}),Tu=createRoute({method:"get",path:"/notifications/unread-count",tags:["notifications"],responses:{200:c(Le,"Get unread count"),500:s("Internal server error")}}),Pu=createRoute({method:"get",path:"/notifications/{id}",tags:["notifications"],request:{params:z$1.object({id:z$1.string()})},responses:{200:c(ce,"Get notification by ID"),404:s("Notification not found")}}),Au=createRoute({method:"post",path:"/notifications",tags:["notifications"],request:{body:{content:{"application/json":{schema:xr}}}},responses:{201:c(ce,"Create notification"),400:s("Invalid input")}}),Eu=createRoute({method:"patch",path:"/notifications/read-all",tags:["notifications"],responses:{200:c(Le,"Mark all as read"),500:s("Internal server error")}}),Iu=createRoute({method:"patch",path:"/notifications/{id}/read",tags:["notifications"],request:{params:z$1.object({id:z$1.string()})},responses:{200:c(ce,"Mark as read"),404:s("Notification not found")}}),ku=createRoute({method:"delete",path:"/notifications/{id}",tags:["notifications"],request:{params:z$1.object({id:z$1.string()})},responses:{200:c(Cr,"Delete notification"),404:s("Notification not found")}}),ta=new OpenAPIHono().openapi(xu,async e=>{let t=e.env;if(t?.REALTIME_DO){let r=t.REALTIME_DO.idFromName("global"),o=t.REALTIME_DO.get(r),n=new Request(e.req.url,{method:e.req.method,headers:e.req.raw.headers});return o.fetch(n)}try{let r=b$2();if(r.handleSSERequest)return await r.handleSSERequest()}catch{return ea()}return ea()}).openapi(Cu,async e=>{let t=e.req.valid("query"),r=Jr({unreadOnly:t.unreadOnly==="true",limit:t.limit?parseInt(t.limit):20,cursor:t.cursor});return e.json(p({items:r.data,nextCursor:r.nextCursor}),200)}).openapi(Tu,async e=>{let t=_t();return e.json(p({count:t}),200)}).openapi(Pu,async e=>{let{id:t}=e.req.valid("param"),r=Yi(t);if(!r)throw new e$1("Notification",t);return e.json(p(r),200)}).openapi(Au,async e=>{let t=e.req.valid("json"),r=await Yr(t);return e.json(z(r),201)}).openapi(Eu,async e=>{let t=Xr();return e.json(p({count:t}),200)}).openapi(Iu,async e=>{let{id:t}=e.req.valid("param"),r=Zr(t);if(!r)throw new e$1("Notification",t);return e.json(p(r),200)}).openapi(ku,async e=>{let{id:t}=e.req.valid("param");if(!Zi(t))throw new e$1("Notification",t);return e.json(p({id:t}),200)});var eo=Mo("/chat/ws");eo.registerRPC("echo",e=>({message:e.message,timestamp:Date.now()}));eo.registerRPC("ping",()=>({pong:true,timestamp:Date.now()}));eo.registerEvent("broadcast",(e,t)=>{eo.broadcast("broadcast",e,[t]);});var ju=createRoute({method:"get",path:"/chat/ws/status",tags:["chat"],responses:{200:c(Ho,"Get WebSocket status")}}),qu=createRoute({method:"get",path:"/chat/ws",tags:["chat"],responses:{200:{content:{websocket:{schema:Fo}},description:"WebSocket endpoint for chat"}}}),oa=new OpenAPIHono().openapi(ju,async e=>e.json(p({connectedClients:0}))).openapi(qu,async e=>{let t=b$2();return t.handleWebSocketRequest?t.handleWebSocketRequest(e.req.raw):new Response("WebSocket not supported",{status:500})});a();d();var xn=null,Cn=false;async function Ft(){if(Cn)return xn;try{return xn=(await import('./schema-V4UG7HMU.js')).todos??null,Cn=!0,xn}catch{return Cn=true,null}}async function sa(){let e=await j$3();if(e&&"execute"in e){let n=await e.execute("SELECT COUNT(*) as count FROM todos"),i=await e.execute("SELECT COUNT(*) as count FROM todos WHERE status = 'pending'"),u=await e.execute("SELECT COUNT(*) as count FROM todos WHERE status = 'completed'"),d=l=>{let m=l[0];return typeof m?.count=="number"?m.count:0};return {totalTodos:d(n.rows),pendingTodos:d(i.rows),completedTodos:d(u.rows),lastUpdated:new Date().toISOString()}}let t=await Ft();if(!t)return {totalTodos:0,pendingTodos:0,completedTodos:0,lastUpdated:new Date().toISOString()};let o=await(await i$2()).select().from(t);return {totalTodos:o.length,pendingTodos:o.filter(n=>n.status==="pending").length,completedTodos:o.filter(n=>n.status==="completed").length,lastUpdated:new Date().toISOString()}}async function ia(){try{let e=await Ft();return e?(await(await i$2()).select().from(e).limit(1),{database:"connected",timestamp:new Date().toISOString()}):{database:"disconnected",timestamp:new Date().toISOString()}}catch{return {database:"disconnected",timestamp:new Date().toISOString()}}}async function aa(){let e=await Ft();return e?{deletedCount:(await(await i$2()).delete(e).returning()).length}:{deletedCount:0}}async function ca(e=10){let t=await Ft();return t?(await(await i$2()).select().from(t).orderBy(desc(t.updatedAt)).limit(e)).map(n=>({id:n.id,title:n.title,status:n.status,updatedAt:a$5(n.updatedAt)})):[]}var Du="$2b$10$9iWkIfjDcJ7Kv4wHSb8ONONnrlfGb6rcfiJlZuuY4G2xQMG78DBbm";async function to(e){let r=Ae().find(l=>l.username===e.username);if(!r)throw new Error("Invalid credentials");let n=Oo().get(r.id);if(!(n?await An.compare(e.password,n):await An.compare(e.password,Du)))throw new Error("Invalid credentials");let u=ei(),d;for(let[l,m]of u)if(m===r.id){d=l;break}return d||(d=`test-token-${r.id}-${Date.now()}`,u.set(d,r.id)),{user:{id:r.id,username:r.username,email:r.email,role:r.role,avatar:r.avatar,permissions:a$4(r.role)},token:d}}async function ro(e){let t=Ae();if(t.find(i=>i.username===e.username||i.email===e.email))throw new Error("User already exists");let o=await An.hash(e.password,10),n={id:String(t.length+1),username:e.username,email:e.email,role:"user",status:"active",avatar:`https://api.dicebear.com/7.x/avataaars/svg?seed=${e.username}`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return t.push(n),Oo().set(n.id,o),n}async function pa(){return Ae()}async function ua(e){return Ae().find(r=>r.id===e)||null}async function da(e,t){let r=Ae(),o=r.findIndex(u=>u.id===e);if(o===-1)throw new Error("User not found");let n=Object.fromEntries(Object.entries(t).filter(([u,d])=>d!=null)),i={...r[o],...n,updatedAt:new Date().toISOString()};return r[o]=i,i}async function la(e){let t=Ae(),r=t.findIndex(o=>o.id===e);if(r===-1)throw new Error("User not found");t.splice(r,1);}async function ma(e){let t=Ae();if(t.find(n=>n.username===e.username||n.email===e.email))throw new Error("User with this username or email already exists");let o={id:`user-${Date.now()}`,username:e.username,email:e.email,role:e.role,status:e.status||"active",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return t.push(o),o}async function oo(){let e=await Ft();return e?(await(await i$2()).select().from(e).orderBy(desc(e.createdAt))).map(o=>({id:o.id,title:o.title,completed:o.status==="completed",createdAt:a$5(o.createdAt)})):[]}var Tn=new Map,Pn=new Map;async function ga(e){if(Tn.has(e))return Tn.get(e);let t=await fetch(`https://api.dicebear.com/7.x/avataaars/png?seed=${e}`);if(!t.ok)return null;let o={data:await t.blob(),contentType:"image/png"};return Tn.set(e,o),o}async function ha(e){if(Pn.has(e))return Pn.get(e);let r={home:'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l9-6 6 6 6-6 9 9 6-6-9-9z"></path><path d="M9 21l6-6 6 6-6 9 9 6-6 9-9z"></path></svg>',settings:'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 3 3 3 3 3 0 0 6.3 6.3A1.65 1.65 0 0 3 3 3 3 3 0 0 6.3 6.3a1.65 1.65 0 0 3 3 3 3 3 0 0 6.3 6.3z"></path></svg>',user:'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0 1-3 1H4a4 4 0 0 0 1 3v2"></path><circle cx="12" cy="7" r="4"></circle><path d="M16 11.37A4 4 0 1 1.8 2.44L8 2.44A4 4 0 1 1.8 2z"></path></svg>',bell:'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8A6 6 0 0 0 6 6c0 1.1.9 2.1 2.1-2 2.1-.9.9-.9 2.1-2 2.1A6 6 0 0 0 6-6 7-9l1-1.1c.7-.7 1.9-2 2.1-.9-.9-.9-2.1-2-2.1A6 6 0 0 0-6 6-7 9l-1 1.1c-.7.7-1.9 2-2.1.9.9.9 2.1 2 2.1z"></path><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2z"></path><line x1="15" y1="12"></line><line x1="15" y1="9"></line></svg>'}[e];return r?(Pn.set(e,r),r):null}var fa=z$1.object({totalTodos:z$1.number(),pendingTodos:z$1.number(),completedTodos:z$1.number(),lastUpdated:z$1.string()}),ya=z$1.object({database:z$1.enum(["connected","disconnected"]),timestamp:z$1.string()}),Ou=z$1.object({id:z$1.number(),title:z$1.string(),status:z$1.string(),updatedAt:z$1.string()}),Sa=z$1.array(Ou),Ht=z$1.object({id:z$1.string(),username:z$1.string(),email:z$1.string(),role:b$3,avatar:z$1.string().nullish(),permissions:z$1.array(c$1)}),no=z$1.object({username:z$1.string().min(1),password:z$1.string().min(6)}),so=z$1.object({user:Ht,token:z$1.string()}),io=z$1.object({username:z$1.string().min(1),email:z$1.string().email(),password:z$1.string().min(6)}),xe=z$1.object({id:z$1.string(),username:z$1.string(),email:z$1.string(),role:b$3,status:z$1.enum(["active","inactive","locked"]),avatar:z$1.string().nullish(),createdAt:z$1.string(),updatedAt:z$1.string()}),wa=z$1.array(xe),Ra=z$1.object({username:z$1.string().nullish(),email:z$1.string().email().nullish(),role:b$3.nullish(),status:z$1.enum(["active","inactive","locked"]).nullish()}),va=z$1.object({username:z$1.string().min(1),email:z$1.string().email(),password:z$1.string().min(6),role:b$3,status:z$1.enum(["active","inactive","locked"]).nullish().default("active")}),ba=z$1.object({deletedCount:z$1.number()}),ao=z$1.object({}),xa=z$1.object({token:z$1.string(),downloadUrl:z$1.string(),expiresIn:z$1.number()});var Nu=createRoute({method:"get",path:"/admin/me",tags:["admin"],security:[{Bearer:[]}],middleware:[h()],responses:{200:c(Ht,"Get current authenticated user"),401:s("Unauthorized")}}),Lu=createRoute({method:"post",path:"/admin/login",tags:["admin"],middleware:[Xe],request:{body:{content:{"application/json":{schema:no}}}},responses:{200:c(so,"Login successful"),401:s("Invalid credentials")}}),zu=createRoute({method:"post",path:"/admin/register",tags:["admin"],middleware:[Xe],request:{body:{content:{"application/json":{schema:io}}}},responses:{201:c(xe,"User registered"),400:s("User already exists")}}),Ca=new OpenAPIHono().openapi(Nu,async e=>{let t=L(e);return e.json(p(t),200)}).openapi(Lu,async e=>{try{let t=e.req.valid("json"),r=await to(t);return e.json(p(r),200)}catch{return e.json({success:false,error:"Invalid credentials"},401)}}).openapi(zu,async e=>{let t=e.req.valid("json"),r=await ro(t);return e.json(p(r),201)});var _u=createRoute({method:"get",path:"/admin/users",tags:["admin"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["user:view"]})],responses:{200:c(wa,"Get user list"),401:s("Unauthorized"),403:s("Forbidden")}}),Fu=createRoute({method:"get",path:"/admin/users/:id",tags:["admin"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["user:view"]})],request:{params:z$1.object({id:z$1.string()})},responses:{200:c(xe,"Get user"),401:s("Unauthorized"),403:s("Forbidden"),404:s("User not found")}}),Hu=createRoute({method:"put",path:"/admin/users/:id",tags:["admin"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["user:edit"]})],request:{params:z$1.object({id:z$1.string()}),body:{content:{"application/json":{schema:Ra}}}},responses:{200:c(xe,"User updated"),401:s("Unauthorized"),403:s("Forbidden"),404:s("User not found")}}),Wu=createRoute({method:"delete",path:"/admin/users/:id",tags:["admin"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["user:delete"]})],request:{params:z$1.object({id:z$1.string()})},responses:{200:c(ao,"User deleted"),401:s("Unauthorized"),403:s("Forbidden"),404:s("User not found")}}),$u=createRoute({method:"post",path:"/admin/users",tags:["admin"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["user:create"]})],request:{body:{content:{"application/json":{schema:va}}}},responses:{200:c(xe,"User created"),401:s("Unauthorized"),403:s("Forbidden"),400:s("Invalid request")}}),Ta=new OpenAPIHono().openapi(_u,async e=>{let t=await pa();return e.json(p(t),200)}).openapi(Fu,async e=>{let{id:t}=e.req.valid("param"),r=await ua(t);return r?e.json(p(r),200):e.json({success:false,error:"User not found"},404)}).openapi(Hu,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=await da(t,r);return e.json(p(o),200)}).openapi(Wu,async e=>{let{id:t}=e.req.valid("param");return await la(t),e.json(p({}),200)}).openapi($u,async e=>{let t=e.req.valid("json"),r=await ma(t);return e.json(p(r),200)});h$1();function Pa(){let e=new ReadableStream({start(t){let r=new TextEncoder,o=()=>{t.enqueue(r.encode(`event: ping
13
+ data: {"timestamp":${Date.now()}}
14
+
15
+ `));};o();let n=setInterval(o,3e4);setTimeout(()=>{clearInterval(n),t.close();},3e5);}});return new Response(e,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}var Gu=createRoute({method:"get",path:"/admin/notifications",tags:["notifications"],security:[{Bearer:[]}],middleware:[h()],request:{query:z$1.object({unreadOnly:z$1.string().optional(),limit:z$1.string().optional()})},responses:{200:c(Go,"Get notifications"),401:s("Unauthorized")}}),Ku=createRoute({method:"get",path:"/admin/notifications/unread-count",tags:["notifications"],security:[{Bearer:[]}],middleware:[h()],responses:{200:c(Le,"Get unread count"),401:s("Unauthorized")}}),Qu=createRoute({method:"put",path:"/admin/notifications/:id/read",tags:["notifications"],security:[{Bearer:[]}],middleware:[h()],request:{params:z$1.object({id:z$1.string()})},responses:{200:c(ao,"Notification marked as read"),401:s("Unauthorized"),404:s("Notification not found")}}),Ju=createRoute({method:"put",path:"/admin/notifications/read-all",tags:["notifications"],security:[{Bearer:[]}],middleware:[h()],responses:{200:c(Ko,"All notifications marked as read"),401:s("Unauthorized")}}),Yu=createRoute({method:"post",path:"/admin/notifications/test",tags:["notifications"],security:[{Bearer:[]}],middleware:[h({requiredRole:"super_admin"})],request:{body:{content:{"application/json":{schema:Qo}}}},responses:{200:c(ce,"Test notification sent"),401:s("Unauthorized"),403:s("Forbidden")}}),Zu=createRoute({method:"get",path:"/admin/notifications/stream",tags:["notifications"],security:[{Bearer:[]}],middleware:[h()],responses:{200:{content:{"text/event-stream":{schema:rt}},description:"SSE stream for admin notifications"},401:s("Unauthorized")}}),Aa=new OpenAPIHono().openapi(Gu,async e=>{let{unreadOnly:t,limit:r}=e.req.valid("query"),o=Jr({unreadOnly:t==="true",limit:r?parseInt(r,10):20});return e.json(p(o.data),200)}).openapi(Ku,async e=>{let t=_t();return e.json(p({count:t}),200)}).openapi(Qu,async e=>{let{id:t}=e.req.valid("param");if(!Zr(t))throw new e$1("Notification",t);try{let o=_t();await Ct.broadcast("unread-count",{count:o});}catch(o){g.module("notification").debug({error:String(o)},"Broadcast failed");}return e.json(p({}),200)}).openapi(Ju,async e=>{let t=Xr();try{await Ct.broadcast("unread-count",{count:0});}catch(r){g.module("notification").debug({error:String(r)},"Broadcast failed");}return e.json(p({count:t}),200)}).openapi(Yu,async e=>{let{type:t}=e.req.valid("json"),r=await Yr({type:t??"info",title:t==="warning"?"\u8B66\u544A\u901A\u77E5":t==="error"?"\u9519\u8BEF\u901A\u77E5":t==="success"?"\u6210\u529F\u901A\u77E5":"\u7CFB\u7EDF\u901A\u77E5",message:t==="warning"?"\u8FD9\u662F\u4E00\u6761\u8B66\u544A\u901A\u77E5\uFF0C\u8BF7\u6CE8\u610F\uFF01":t==="error"?"\u8FD9\u662F\u4E00\u6761\u9519\u8BEF\u901A\u77E5\uFF0C\u8BF7\u7ACB\u5373\u5904\u7406\uFF01":t==="success"?"\u64CD\u4F5C\u6210\u529F\u5B8C\u6210\uFF01":"\u8FD9\u662F\u4E00\u6761\u666E\u901A\u4FE1\u606F\u901A\u77E5"});return e.json(p(r),200)}).openapi(Zu,async e=>{let t=e.env;if(t?.REALTIME_DO){let r=t.REALTIME_DO.idFromName("global"),o=t.REALTIME_DO.get(r),n=new Request(e.req.url,{method:e.req.method,headers:e.req.raw.headers});return o.fetch(n)}try{let{getRuntimeAdapter:r}=await import('./runtime-HBG2YPJ4.js'),o=r();if(o.handleSSERequest)return await o.handleSSERequest()}catch{return Pa()}return Pa()});var ed=createRoute({method:"get",path:"/admin/avatar/:id",tags:["media"],security:[{Bearer:[]}],middleware:[h()],request:{params:z$1.object({id:z$1.string()})},responses:{200:{content:{"image/png":{schema:z$1.any().openapi({type:"string",format:"binary"})},"image/jpeg":{schema:z$1.any().openapi({type:"string",format:"binary"})}},description:"User avatar image"},401:s("Unauthorized"),404:s("Avatar not found")}}),td=createRoute({method:"get",path:"/admin/icon/:name",tags:["media"],security:[{Bearer:[]}],middleware:[h()],request:{params:z$1.object({name:z$1.string()})},responses:{200:{content:{"image/svg+xml":{schema:z$1.string()}},description:"SVG icon"},401:s("Unauthorized"),404:s("Icon not found")}}),Ia=new OpenAPIHono().openapi(ed,async e=>{let{id:t}=e.req.valid("param"),r=await ga(t);return r?new Response(r.data,{headers:{"Content-Type":r.contentType}}):e.json({success:false,error:"Avatar not found"},404)}).openapi(td,async e=>{let{name:t}=e.req.valid("param"),r=await ha(t);return r?new Response(r,{headers:{"Content-Type":"image/svg+xml"}}):e.json({success:false,error:"Icon not found"},404)});var Vt=new Map,od=()=>{let e=Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15);return Vt.set(e,{createdAt:Date.now(),expiresIn:6e4}),setTimeout(()=>Vt.delete(e),6e4),e},nd=e=>{let t=Vt.get(e);return t?Date.now()-t.createdAt>t.expiresIn?(Vt.delete(e),false):true:false},sd=e=>{let t=nd(e);return t&&Vt.delete(e),t},id=createRoute({method:"get",path:"/admin/todos/export",tags:["export"],security:[{Bearer:[]}],middleware:[h()],responses:{200:{content:{"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":{schema:z$1.any().openapi({type:"string",format:"binary"})},"text/csv":{schema:z$1.string()}},description:"Export todos as Excel or CSV"},401:s("Unauthorized")}}),ad=createRoute({method:"post",path:"/admin/todos/export/token",tags:["export"],security:[{Bearer:[]}],middleware:[h()],responses:{200:c(xa,"Generate a temporary download token"),401:s("Unauthorized")}}),cd=createRoute({method:"get",path:"/admin/todos/export/download/:token",tags:["export"],request:{params:z$1.object({token:z$1.string()})},responses:{200:{content:{"text/csv":{schema:z$1.string()}},description:"Download CSV with temporary token"},403:s("Invalid or expired token")}}),pd=createRoute({method:"get",path:"/admin/todos/export/stream",tags:["export"],security:[{Bearer:[]}],middleware:[h()],responses:{200:{content:{"text/csv":{schema:z$1.string()}},description:"Stream export todos as CSV (for large datasets)"},401:s("Unauthorized")}}),ka=new OpenAPIHono().openapi(id,async e=>{let t=await oo(),r=new TextEncoder,o=new ReadableStream({async start(n){n.enqueue(r.encode(`id,title,completed,created_at
16
+ `));for(let i of t){let u=`${h$2(String(i.id))},${h$2(i.title)},${i.completed},${h$2(i.createdAt)}
17
+ `;n.enqueue(r.encode(u)),await new Promise(d=>setTimeout(d,100));}n.close();}});return new Response(o,{headers:{"Content-Type":"text/csv","Content-Disposition":'attachment; filename="todos.csv"',"Cache-Control":"no-cache","X-Accel-Buffering":"no"}})}).openapi(ad,async e=>{let t=od(),r=`/api/admin/todos/export/download/${t}`;return e.json(p({token:t,downloadUrl:r,expiresIn:6e4}),200)}).openapi(cd,async e=>{let{token:t}=e.req.valid("param");if(!sd(t))return e.json({success:false,error:"Invalid or expired token"},403);let r=await oo(),o=new TextEncoder,n=new ReadableStream({async start(i){i.enqueue(o.encode(`id,title,completed,created_at
18
+ `));for(let u of r){let d=`${h$2(String(u.id))},${h$2(u.title)},${u.completed},${h$2(u.createdAt)}
19
+ `;i.enqueue(o.encode(d)),await new Promise(l=>setTimeout(l,100));}i.close();}});return new Response(n,{headers:{"Content-Type":"text/csv","Content-Disposition":'attachment; filename="todos.csv"',"Cache-Control":"no-cache","X-Accel-Buffering":"no"}})}).openapi(pd,async e=>{let t=await oo(),r=new TextEncoder,o=new ReadableStream({async start(n){n.enqueue(r.encode(`id,title,completed,created_at
20
+ `));for(let i=0;i<t.length;i++){let u=t[i],d=`${h$2(String(u.id))},${h$2(u.title)},${u.completed},${h$2(u.createdAt)}
21
+ `;n.enqueue(r.encode(d)),await new Promise(l=>setTimeout(l,300));}n.close();}});return new Response(o,{headers:{"Content-Type":"text/csv","Content-Disposition":'attachment; filename="todos-stream.csv"',"Cache-Control":"no-cache","X-Accel-Buffering":"no"}})});var dd=createRoute({method:"get",path:"/admin/stats",tags:["admin"],security:[{Bearer:[]}],middleware:[h({requiredRole:"super_admin"})],responses:{200:c(fa,"Get system statistics"),401:s("Unauthorized"),403:s("Forbidden")}}),ld=createRoute({method:"get",path:"/admin/health",tags:["admin"],security:[{Bearer:[]}],middleware:[h({requiredRole:"super_admin"})],responses:{200:c(ya,"Get system health"),401:s("Unauthorized"),403:s("Forbidden")}}),md=createRoute({method:"get",path:"/admin/activity",tags:["admin"],security:[{Bearer:[]}],middleware:[h({requiredRole:"super_admin"})],request:{query:z$1.object({limit:z$1.string().optional()})},responses:{200:c(Sa,"Get recent activity"),401:s("Unauthorized"),403:s("Forbidden")}}),gd=createRoute({method:"delete",path:"/admin/todos/all",tags:["admin"],security:[{Bearer:[]}],middleware:[h({requiredRole:"super_admin"})],responses:{200:c(ba,"All todos cleared"),401:s("Unauthorized"),403:s("Forbidden")}}),ja=new OpenAPIHono().openapi(dd,async e=>{let t=await sa();return e.json(p(t),200)}).openapi(ld,async e=>{let t=await ia();return e.json(p(t),200)}).openapi(md,async e=>{let{limit:t}=e.req.valid("query"),r=t?parseInt(t,10):10,o=await ca(r);return e.json(p(o),200)}).openapi(gd,async e=>{let t=await aa();return e.json(p(t),200)});var fd=new OpenAPIHono().route("/",Ca).route("/",Ta),yd=fd.route("/",Aa).route("/",Ia),Sd=yd.route("/",ka).route("/",ja),qa=Sd;var Rd=createRoute({method:"post",path:"/auth/login",tags:["auth"],middleware:[Xe],request:{body:{content:{"application/json":{schema:no}}}},responses:{200:c(so,"Login successful"),401:s("Invalid credentials")}}),vd=createRoute({method:"post",path:"/auth/register",tags:["auth"],middleware:[Xe],request:{body:{content:{"application/json":{schema:io}}}},responses:{201:c(xe,"User registered"),400:s("User already exists")}}),bd=createRoute({method:"get",path:"/auth/me",tags:["auth"],security:[{Bearer:[]}],middleware:[h()],responses:{200:c(Ht,"Get current authenticated user"),401:s("Unauthorized")}}),Da=new OpenAPIHono().openapi(Rd,async e=>{try{let t=e.req.valid("json"),r=await to(t);return e.json(p(r),200)}catch{return e.json({success:false,error:"Invalid credentials"},401)}}).openapi(vd,async e=>{try{let t=e.req.valid("json"),r=await ro(t);return e.json(p(r),201)}catch{return e.json({success:false,error:"User already exists"},400)}}).openapi(bd,async e=>{let t=L(e);return e.json(p(t),200)});var _e=new Map;function kn(){Cd();let e=Math.random().toString(36).substring(2)+Date.now().toString(36),t=Math.random().toString(36).substring(2,7).toUpperCase();_e.set(e,{code:t,createdAt:Date.now(),attempts:0});let r=xd(t);return {id:e,image:r}}function Un(e,t){let r=_e.get(e);if(!r)return false;if(Date.now()-r.createdAt>3e5||r.attempts>=3)return _e.delete(e),false;r.attempts++;let o=r.code.toUpperCase()===t.toUpperCase();return o&&_e.delete(e),o}function xd(e){let n=e.split("").map((d,l)=>{let m=30+l*30,R=35+Math.random()*10-5,v=(Math.random()-.5)*40,P=Math.random()*360;return `<text
22
+ x="${m}"
23
+ y="${R}"
18
24
  font-family="Arial, sans-serif"
19
25
  font-size="40"
20
26
  font-weight="bold"
21
- fill="hsl(${O}, 70%, 30%)"
22
- transform="rotate(${P} ${p} ${T})"
23
- >${u}</text>`}).join(""),i=Array.from({length:50},()=>{let u=Math.random()*200,l=Math.random()*60,p=Math.random()*2;return `<circle cx="${u}" cy="${l}" r="${p}" fill="rgba(${Math.random()*255}, ${Math.random()*255}, ${Math.random()*255}, 0.5)" />`}).join(""),a=Array.from({length:5},()=>{let u=Math.random()*200,l=Math.random()*60,p=Math.random()*200,T=Math.random()*60;return `<line x1="${u}" y1="${l}" x2="${p}" y2="${T}" stroke="rgba(${Math.random()*255}, ${Math.random()*255}, ${Math.random()*255}, 0.3)" stroke-width="1" />`}).join("");return `data:image/svg+xml;base64,${Buffer.from(`
27
+ fill="hsl(${P}, 70%, 30%)"
28
+ transform="rotate(${v} ${m} ${R})"
29
+ >${d}</text>`}).join(""),i=Array.from({length:50},()=>{let d=Math.random()*200,l=Math.random()*60,m=Math.random()*2;return `<circle cx="${d}" cy="${l}" r="${m}" fill="rgba(${Math.random()*255}, ${Math.random()*255}, ${Math.random()*255}, 0.5)" />`}).join(""),u=Array.from({length:5},()=>{let d=Math.random()*200,l=Math.random()*60,m=Math.random()*200,R=Math.random()*60;return `<line x1="${d}" y1="${l}" x2="${m}" y2="${R}" stroke="rgba(${Math.random()*255}, ${Math.random()*255}, ${Math.random()*255}, 0.3)" stroke-width="1" />`}).join("");return `data:image/svg+xml;base64,${Buffer.from(`
24
30
  <svg xmlns="http://www.w3.org/2000/svg" width="200" height="60">
25
31
  <rect width="100%" height="100%" fill="#f0f0f0" />
26
32
  ${i}
27
- ${a}
33
+ ${u}
28
34
  ${n}
29
35
  </svg>
30
- `).toString("base64")}`}function Bc(){let e=Date.now();for(let[t,r]of Re.entries())e-r.createdAt>3e5&&Re.delete(t);}var bn=z.object({id:z.string(),image:z.string()}),xn=z.object({id:z.string(),code:z.string()}),Cn=z.object({message:z.string()});var Hc=createRoute({method:"get",path:"/captcha",tags:["captcha"],responses:{200:c(bn,"Get captcha")}}),Vc=createRoute({method:"post",path:"/verify-captcha",tags:["captcha"],request:{body:{content:{"application/json":{schema:xn}}}},responses:{200:c(Cn,"Captcha verified"),400:s("Invalid captcha")}}),In=new OpenAPIHono().openapi(Hc,e=>{let{id:t,image:r}=Jr();return e.json(d({id:t,image:r}),200)}).openapi(Vc,async e=>{let{id:t,code:r}=e.req.valid("json");if(Xr(t,r)){let n=getCookie(e,"session_id");return n&&wr(n),e.json(d({message:"\u9A8C\u8BC1\u6210\u529F"}),200)}else return e.json({success:false,error:"\u9A8C\u8BC1\u7801\u9519\u8BEF\u6216\u5DF2\u8FC7\u671F"},400)});var Qr=z.enum(["pending","processing","completed","cancelled","disputed"]),W=z.object({id:z.string(),orderNo:z.string(),customerName:z.string(),customerEmail:z.string(),productName:z.string(),amount:z.number(),status:Qr,createdAt:z.string(),updatedAt:z.string()}),Pn=z.object({customerName:z.string(),customerEmail:z.string().email(),productName:z.string(),amount:z.number().positive()}),Un=z.object({status:Qr.nullish()}),On=z.array(W),Dn=z.object({status:Qr.nullish(),customerName:z.string().nullish(),limit:z.coerce.number().int().positive().max(100).default(20),offset:z.coerce.number().int().min(0).default(0)}),kn=z.object({message:z.string()});z.object({orderId:z.string()});z.object({orderId:z.string(),reason:z.string().nullish()});var Kc=createRoute({method:"get",path:"/orders",tags:["orders"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["order:view"]})],request:{query:Dn},responses:{200:c(On,"List all orders"),401:s("Unauthorized"),403:s("Forbidden"),500:s("Internal server error")}}),Yc=createRoute({method:"get",path:"/orders/{id}",tags:["orders"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["order:view"]})],request:{params:W.pick({id:true})},responses:{200:c(W,"Get order by id"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Order not found"),500:s("Internal server error")}}),Zc=createRoute({method:"post",path:"/orders",tags:["orders"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["order:create"]})],request:{body:{content:{"application/json":{schema:Pn}}}},responses:{201:c(W,"Create order"),401:s("Unauthorized"),403:s("Forbidden"),400:s("Invalid input"),500:s("Internal server error")}}),Jc=createRoute({method:"put",path:"/orders/{id}",tags:["orders"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["order:edit"]})],request:{params:W.pick({id:true}),body:{content:{"application/json":{schema:Un}}}},responses:{200:c(W,"Update order"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Order not found"),400:s("Invalid input"),500:s("Internal server error")}}),Xc=createRoute({method:"delete",path:"/orders/{id}",tags:["orders"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["order:delete"]})],request:{params:W.pick({id:true})},responses:{200:c(kn,"Order deleted"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Order not found"),500:s("Internal server error")}}),Qc=createRoute({method:"put",path:"/orders/{id}/process",tags:["orders"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["order:process"]})],request:{params:W.pick({id:true})},responses:{200:c(W,"Order processed"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Order not found"),400:s("Cannot process order"),500:s("Internal server error")}}),ed=createRoute({method:"put",path:"/orders/{id}/cancel",tags:["orders"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["order:process"]})],request:{params:W.pick({id:true})},responses:{200:c(W,"Order cancelled"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Order not found"),400:s("Cannot cancel order"),500:s("Internal server error")}}),qn=new OpenAPIHono().openapi(Kc,async e=>{let{status:t,customerName:r,limit:o,offset:n}=e.req.valid("query"),i=await b$3({status:t??void 0,customerName:r??void 0});return e.json(d(i.slice(n,n+o)),200)}).openapi(Yc,async e=>{let{id:t}=e.req.valid("param"),r=await c$2(t);if(!r)throw new f("Order",t);return e.json(d(r),200)}).openapi(Zc,async e=>{let t=e.req.valid("json"),r=await d$3(t);return e.json(L(r),201)}).openapi(Jc,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=await e$2(t,r);if(!o)throw new f("Order",t);return e.json(d(o),200)}).openapi(Xc,async e=>{let{id:t}=e.req.valid("param");if((await f$1(t)).message==="\u8BA2\u5355\u4E0D\u5B58\u5728")throw new f("Order",t);return e.json(d({message:"Deleted successfully"}),200)}).openapi(Qc,async e=>{let{id:t}=e.req.valid("param"),r=await g$1(t);if(!r)throw new f("Order",t);return e.json(d(r),200)}).openapi(ed,async e=>{let{id:t}=e.req.valid("param"),r=await h$1(t);if(!r)throw new f("Order",t);return e.json(d(r),200)});var Nn=z.enum(["open","in_progress","waiting_customer","resolved","closed"]),jn=z.enum(["low","medium","high","urgent"]),Mn=z.enum(["technical","billing","feature_request","bug_report","general"]),td=z.object({id:z.string(),ticketId:z.string(),content:z.string(),author:z.string(),isCustomer:z.boolean(),createdAt:z.string()}),$=z.object({id:z.string(),ticketNo:z.string(),customerName:z.string(),customerEmail:z.string(),subject:z.string(),description:z.string(),status:Nn,priority:jn,category:Mn,assignedTo:z.string().nullish(),createdAt:z.string(),updatedAt:z.string(),replies:z.array(td)}),_n=z.object({customerName:z.string(),customerEmail:z.string().email(),subject:z.string(),description:z.string(),category:Mn,priority:jn}),Ln=z.object({status:Nn.nullish(),assignedTo:z.string().nullish()}),Fn=z.object({content:z.string(),author:z.string()}),zn=z.array($),Bn=z.object({message:z.string()});var od=createRoute({method:"get",path:"/tickets",tags:["tickets"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["ticket:view"]})],request:{query:z.object({limit:z.coerce.number().int().positive().max(100).default(20),offset:z.coerce.number().int().min(0).default(0)})},responses:{200:c(zn,"List all tickets"),401:s("Unauthorized"),403:s("Forbidden"),500:s("Internal server error")}}),sd=createRoute({method:"get",path:"/tickets/{id}",tags:["tickets"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["ticket:view"]})],request:{params:$.pick({id:true})},responses:{200:c($,"Get ticket by id"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Ticket not found"),500:s("Internal server error")}}),nd=createRoute({method:"post",path:"/tickets",tags:["tickets"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["ticket:create"]})],request:{body:{content:{"application/json":{schema:_n}}}},responses:{201:c($,"Create ticket"),401:s("Unauthorized"),403:s("Forbidden"),400:s("Invalid input"),500:s("Internal server error")}}),id=createRoute({method:"put",path:"/tickets/{id}",tags:["tickets"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["ticket:edit"]})],request:{params:$.pick({id:true}),body:{content:{"application/json":{schema:Ln}}}},responses:{200:c($,"Update ticket"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Ticket not found"),400:s("Invalid input"),500:s("Internal server error")}}),ad=createRoute({method:"delete",path:"/tickets/{id}",tags:["tickets"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["ticket:delete"]})],request:{params:$.pick({id:true})},responses:{200:c(Bn,"Ticket deleted"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Ticket not found"),500:s("Internal server error")}}),cd=createRoute({method:"post",path:"/tickets/{id}/reply",tags:["tickets"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["ticket:reply"]})],request:{params:$.pick({id:true}),body:{content:{"application/json":{schema:Fn}}}},responses:{200:c($,"Ticket replied"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Ticket not found"),400:s("Cannot reply ticket"),500:s("Internal server error")}}),dd=createRoute({method:"put",path:"/tickets/{id}/close",tags:["tickets"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["ticket:close"]})],request:{params:$.pick({id:true})},responses:{200:c($,"Ticket closed"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Ticket not found"),400:s("Cannot close ticket"),500:s("Internal server error")}}),Wn=new OpenAPIHono().openapi(od,async e=>{let{limit:t,offset:r}=e.req.valid("query"),o=await j();return e.json(d(o.slice(r,r+t)),200)}).openapi(sd,async e=>{let{id:t}=e.req.valid("param"),r=await k(t);if(!r)throw new f("Ticket",t);return e.json(d(r),200)}).openapi(nd,async e=>{let t=e.req.valid("json"),r=await l(t);return e.json(L(r),201)}).openapi(id,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=await m$2(t,r);if(!o)throw new f("Ticket",t);return e.json(d(o),200)}).openapi(ad,async e=>{let{id:t}=e.req.valid("param");if((await n$1(t)).message==="\u5DE5\u5355\u4E0D\u5B58\u5728")throw new f("Ticket",t);return e.json(d({message:"Deleted successfully"}),200)}).openapi(cd,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=await o$1(t,r);if(!o)throw new f("Ticket",t);return e.json(d(o),200)}).openapi(dd,async e=>{let{id:t}=e.req.valid("param"),r=await p$1(t);if(!r)throw new f("Ticket",t);return e.json(d(r),200)});var $n=z.enum(["refund","product_quality","service_quality","delivery","other"]),Hn=z.enum(["pending","investigating","resolved","rejected"]),ee=z.object({id:z.string(),disputeNo:z.string(),orderId:z.string(),orderNo:z.string(),customerName:z.string(),customerEmail:z.string(),type:$n,status:Hn,description:z.string(),resolution:z.string().nullish(),amount:z.number(),createdAt:z.string(),updatedAt:z.string(),resolvedAt:z.string().nullish(),resolvedBy:z.string().nullish()}),Vn=z.object({orderId:z.string(),orderNo:z.string(),customerName:z.string(),customerEmail:z.string().email(),type:$n,description:z.string(),amount:z.number().positive()}),Gn=z.object({status:Hn.nullish(),resolution:z.string().nullish()}),Kn=z.object({resolution:z.string(),resolvedBy:z.string()}),Yn=z.array(ee);z.object({message:z.string()});var ud=createRoute({method:"get",path:"/disputes",tags:["disputes"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["dispute:view"]})],request:{query:z.object({limit:z.coerce.number().int().positive().max(100).default(20),offset:z.coerce.number().int().min(0).default(0)})},responses:{200:c(Yn,"List all disputes"),401:s("Unauthorized"),403:s("Forbidden")}}),ld=createRoute({method:"get",path:"/disputes/{id}",tags:["disputes"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["dispute:view"]})],request:{params:ee.pick({id:true})},responses:{200:c(ee,"Get dispute by id"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Dispute not found")}}),md=createRoute({method:"post",path:"/disputes",tags:["disputes"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["dispute:create"]})],request:zt(Vn),responses:{201:c(ee,"Create dispute"),401:s("Unauthorized"),403:s("Forbidden")}}),hd=createRoute({method:"put",path:"/disputes/{id}",tags:["disputes"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["dispute:edit"]})],request:{params:ee.pick({id:true}),...zt(Gn)},responses:{200:c(ee,"Update dispute"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Dispute not found")}}),fd=createRoute({method:"delete",path:"/disputes/{id}",tags:["disputes"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["dispute:delete"]})],request:Us,responses:{200:c(ee,"Delete dispute"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Dispute not found")}}),gd=createRoute({method:"put",path:"/disputes/{id}/resolve",tags:["disputes"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["dispute:resolve"]})],request:{params:ee.pick({id:true}),...zt(Kn)},responses:{200:c(ee,"Dispute resolved"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Dispute not found"),422:s("Cannot resolve dispute in current state")}}),Zn=new OpenAPIHono().openapi(ud,async e=>{let{limit:t,offset:r}=e.req.valid("query"),o=await r$1();return e.json(d(o.slice(r,r+t)),200)}).openapi(ld,async e=>{let{id:t}=e.req.valid("param"),r=await s$1(t);if(!r)throw f.dispute(t);return e.json(d(r),200)}).openapi(md,async e=>{let t=e.req.valid("json"),r=await t$1(t);return e.json(L(r),201)}).openapi(hd,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=await u(t,r);if(!o)throw f.dispute(t);return e.json(d(o),200)}).openapi(fd,async e=>{let{id:t}=e.req.valid("param");if(!(await v(t)).success)throw f.dispute(t);return e.json(d({message:"Deleted successfully"}),200)}).openapi(gd,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=await w(t,r);if(!o)throw new me("Cannot resolve dispute in current state");return e.json(d(o),200)});I();var dt=z.enum(["article","announcement","tutorial","news","policy"]),Jn=z.enum(["draft","published","archived"]),q=z.object({id:z.string(),title:z.string(),content:z.string(),category:dt,status:Jn,author:z.string(),tags:z.array(z.string()),viewCount:z.number(),likeCount:z.number(),createdAt:z.string(),updatedAt:z.string(),publishedAt:z.string().nullish()}),Xn=z.object({title:z.string(),content:z.string(),category:dt,tags:z.array(z.string()).nullish()}),Qn=z.object({title:z.string().nullish(),content:z.string().nullish(),category:dt.nullish(),tags:z.array(z.string()).nullish(),status:Jn.nullish()}),ei=z.array(q),ti=z.object({message:z.string()});var Sd=createRoute({method:"get",path:"/contents",tags:["contents"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["content:view"]})],request:{query:z.object({limit:z.coerce.number().int().positive().max(100).default(20),offset:z.coerce.number().int().min(0).default(0)})},responses:{200:c(ei,"List all contents")}}),Rd=createRoute({method:"get",path:"/contents/{id}",tags:["contents"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["content:view"]})],request:{params:q.pick({id:true})},responses:{200:c(q,"Get content by id"),404:s("Content not found")}}),wd=createRoute({method:"post",path:"/contents",tags:["contents"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["content:create"]})],request:{body:{content:{"application/json":{schema:Xn}}}},responses:{201:c(q,"Create content"),400:s("Invalid input")}}),vd=createRoute({method:"put",path:"/contents/{id}",tags:["contents"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["content:edit"]})],request:{params:q.pick({id:true}),body:{content:{"application/json":{schema:Qn}}}},responses:{200:c(q,"Update content"),404:s("Content not found"),400:s("Invalid input")}}),Td=createRoute({method:"delete",path:"/contents/{id}",tags:["contents"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["content:delete"]})],request:{params:q.pick({id:true})},responses:{200:c(ti,"Content deleted"),404:s("Content not found")}}),Ed=createRoute({method:"put",path:"/contents/{id}/publish",tags:["contents"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["content:edit"]})],request:{params:q.pick({id:true})},responses:{200:c(q,"Content published"),404:s("Content not found"),422:s("Content cannot be published")}}),bd=createRoute({method:"put",path:"/contents/{id}/archive",tags:["contents"],security:[{Bearer:[]}],middleware:[m({requiredPermissions:["content:edit"]})],request:{params:q.pick({id:true})},responses:{200:c(q,"Content archived"),404:s("Content not found"),422:s("Content cannot be archived")}}),ri=new OpenAPIHono().openapi(Sd,async e=>{let{limit:t,offset:r}=e.req.valid("query"),o=await A();return e.json(d(o.slice(r,r+t)),200)}).openapi(Rd,async e=>{let{id:t}=e.req.valid("param"),r=await B$1(t);if(!r)throw new f("Content",t);return e.json(d(r),200)}).openapi(wd,async e=>{let t=e.req.valid("json"),r=await C$1(t);return e.json(L(r),201)}).openapi(vd,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=await D$1(t,r);if(!o)throw new f("Content",t);return e.json(d(o),200)}).openapi(Td,async e=>{let{id:t}=e.req.valid("param");if(!(await E(t)).success)throw new f("Content",t);return e.json(d({message:"Deleted successfully"}),200)}).openapi(Ed,async e=>{let{id:t}=e.req.valid("param"),r=await F(t);if(!r)throw new me("Content cannot be published (must be in draft state)");return e.json(d(r),200)}).openapi(bd,async e=>{let{id:t}=e.req.valid("param"),r=await G(t);if(!r)throw new me("Content cannot be archived (must be in published state)");return e.json(d(r),200)});I();var Cd=createRoute({method:"get",path:"/public/contents",tags:["public-contents"],request:{query:z.object({category:dt.optional(),search:z.string().optional(),limit:z.coerce.number().int().positive().max(50).default(20),offset:z.coerce.number().int().min(0).default(0)})},responses:{200:c(z.array(q),"List published contents")}}),Ad=createRoute({method:"get",path:"/public/contents/{id}",tags:["public-contents"],request:{params:q.pick({id:true})},responses:{200:c(q,"Get published content"),404:s("Content not found")}}),si=new OpenAPIHono().openapi(Cd,async e=>{let{category:t,search:r,limit:o,offset:n}=e.req.valid("query"),a=(await A({status:"published",category:t,search:r})).slice(n,n+o);return e.json(d(a),200)}).openapi(Ad,async e=>{let{id:t}=e.req.valid("param"),r=await B$1(t);if(!r||r.status!=="published")throw new f("Content",t);return e.json(d(r),200)});var ni=z.any(),Pd=createRoute({method:"get",path:"/public/{namespace}/{filename}",tags:["files"],request:{params:ge},responses:{200:{description:"File content",content:{"application/octet-stream":{schema:ni}}},404:s("File not found")}}),Ud=createRoute({method:"get",path:"/private/{namespace}/{filename}",tags:["files"],request:{params:ge,query:Xe},responses:{200:{description:"File content",content:{"application/octet-stream":{schema:ni}}},403:s("Invalid or expired signature"),404:s("File not found")}}),Od=createRoute({method:"post",path:"/generate-url",tags:["files"],request:{body:{content:{"application/json":{schema:It}}}},responses:{200:c(Pt,"URL generated successfully"),400:s("Invalid request"),404:s("File not found")}}),Dd=createRoute({method:"head",path:"/public/{namespace}/{filename}",tags:["files"],request:{params:ge},responses:{200:{description:"File exists",content:{"application/octet-stream":{schema:z.null()}}},404:s("File not found")}}),kd=createRoute({method:"head",path:"/private/{namespace}/{filename}",tags:["files"],request:{params:ge,query:Xe},responses:{200:{description:"File exists",content:{"application/octet-stream":{schema:z.null()}}},403:s("Invalid or expired signature"),404:s("File not found")}}),qd=createRoute({method:"post",path:"/upload",tags:["files"],middleware:[as],request:{body:{content:{"multipart/form-data":{schema:Ot}}}},responses:{200:c(Ut,"File uploaded successfully"),400:s("Invalid file or upload failed")}}),or=new OpenAPIHono().openapi(Pd,async e=>{let{namespace:t,filename:r}=e.req.valid("param"),o=await Oe(t,r);if(!o)throw new f("File",`${t}/${r}`);let n=xt(t,r),i=await Pr(n);return e.header("Content-Type",o.mimeType),e.header("Content-Length",o.size.toString()),e.header("Content-Disposition",`inline; filename="${r}"`),e.header("Cache-Control","public, max-age=31536000"),e.header("Last-Modified",o.lastModified.toUTCString()),e.body(i)}).openapi(Ud,async e=>{let{namespace:t,filename:r}=e.req.valid("param"),{expiry:o,signature:n}=e.req.valid("query");if(Math.floor(Date.now()/1e3)>o)throw new ie("URL has expired");if(!Dr(t,r,o,n))throw new ie("Invalid signature");let a=await Oe(t,r);if(!a)throw new f("File",`${t}/${r}`);let u=xt(t,r),l=await Pr(u);return e.header("Content-Type",a.mimeType),e.header("Content-Length",a.size.toString()),e.header("Content-Disposition",`inline; filename="${r}"`),e.header("Cache-Control","private, no-store"),e.body(l)}).openapi(Od,async e=>{let{namespace:t,filename:r,isPrivate:o,expirySeconds:n}=e.req.valid("json");if(!await Oe(t,r))throw new f("File",`${t}/${r}`);let a=process.env.PUBLIC_URL||"";if(o){let{url:l,expiry:p}=fs(t,r,n??void 0,a);return e.json(d({url:l,expiry:p}),200)}let u=Or(t,r,a);return e.json(d({url:u}),200)}).openapi(Dd,async e=>{let{namespace:t,filename:r}=e.req.valid("param"),o=await Oe(t,r);if(!o)throw new f("File",`${t}/${r}`);return e.header("Content-Type",o.mimeType),e.header("Content-Length",o.size.toString()),e.header("Last-Modified",o.lastModified.toUTCString()),e.body(null,200)}).openapi(kd,async e=>{let{namespace:t,filename:r}=e.req.valid("param"),{expiry:o,signature:n}=e.req.valid("query");if(Math.floor(Date.now()/1e3)>o)return e.json({success:false,error:"URL has expired"},403);if(!Dr(t,r,o,n))return e.json({success:false,error:"Invalid signature"},403);let a=await Oe(t,r);if(!a)throw new f("File",`${t}/${r}`);return e.header("Content-Type",a.mimeType),e.header("Content-Length",a.size.toString()),e.body(null,200)}).openapi(qd,async e=>{let t=await e.req.parseBody(),r=t.file;if(!r||!(r instanceof File))return e.json({success:false,error:"No file provided"},400);let o=typeof t.namespace=="string"?t.namespace:"uploads",n=await r.arrayBuffer(),i=await bt(o,{name:r.name,type:r.type,size:r.size,data:n}),a=Or(o,i.filename);return e.json(d({filename:i.filename,originalName:i.originalName,mimeType:i.mimeType,size:i.size,url:a}),200)});var Nd=Ae({windowMs:6e4,max:100,message:"Too many requests"}),ai=new OpenAPIHono().use("*",Nd).route("/api",En).route("/api",Vs).route("/api",$s).route("/api",Os).route("/api",si),ci=new OpenAPIHono().route("/api",qn).route("/api",Wn).route("/api",Zn).route("/api",ri).route("/api",or).route("/api",In).route("/api",Ds).route("/api",_s).route("/api",Fs).route("/api",Tn);function di(e={}){let t=new OpenAPIHono().use("*",Sr()).use("*",gr()).use("*",fr()).use("*",ds()).use("/api/*",ms()).use("/api/admin/*",Rr({maxRequests:20,windowMs:6e4})).route("/",ai).route("/",ci).route("/files",or).get("/health",async r=>{try{let{getDb:o}=await import('./db-RGXG7SDI.js');return await o(),r.json({status:"ok",timestamp:new Date().toISOString(),db:"connected"})}catch{return r.json({status:"ok",timestamp:new Date().toISOString(),db:"not configured"})}}).post("/api/__test__/cleanup",async r=>{try{let{cleanupTestDatabase:o}=await import('./test-setup-FHJYAGH7.js');return await o(),r.json({success:!0,message:"Database cleaned up"})}catch(o){return console.error("Error during database cleanup:",o),r.json({success:false,message:"Failed to cleanup database"},500)}});return ts(t),t.onError((r,o)=>{let n=f$2("api");if(o.res.headers.set("Content-Type","application/json"),V.isAppError(r))return o.json({success:false,error:r.message,status:r.statusCode,details:r.details},r.statusCode);if(r instanceof HTTPException)return o.json({success:false,error:r.message,status:r.status},r.status);if(r instanceof ZodError){let i=r.issues.map(a=>({field:a.path.join("."),message:a.message}));return o.json({success:false,error:"Validation failed",status:400,details:i},400)}return n.error({err:r,path:o.req.path},"Unhandled error"),o.json({success:false,error:r.message||"Internal server error",status:500},500)}),t}N();var Ld=["/","/todos","/content","/notifications","/websocket"],Fd=["/content/"];function pi(e){if(Ld.includes(e))return true;for(let t of Fd)if(e.startsWith(t))return true;return false}function so(e){return `isr:${e==="/"?"/index":e.replace(/\/$/,"")}`}var no=class{cache=new Map;timer=null;constructor(){this.timer=setInterval(()=>this.cleanup(),6e4),this.timer&&typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref();}cleanup(){let t=Date.now();for(let[r,o]of this.cache)t>o.revalidateAt+6e4&&this.cache.delete(r);}async get(t){return this.cache.get(t)??null}async set(t,r,o){let n=Date.now();this.cache.set(t,{html:r,createdAt:n,revalidateAt:n+o.maxAge*1e3});}async purge(t){this.cache.delete(t);}async purgePattern(t){let r=new RegExp("^"+t.replace(/\*/g,".*")+"$");for(let o of this.cache.keys())r.test(o)&&this.cache.delete(o);}destroy(){this.timer&&(clearInterval(this.timer),this.timer=null),this.cache.clear();}},io=class{cache=null;origin="https://isr.local";async getCache(){return this.cache||(this.cache=await caches.open("isr-pages")),this.cache}toUrl(t){return `${this.origin}${t.replace(/^isr:/,"")}`}async get(t){let r=await this.getCache(),o=this.toUrl(t),n=await r.match(o);if(!n)return null;let i=await n.text(),a=Number(n.headers.get("x-isr-created-at")||"0"),u=Number(n.headers.get("x-isr-revalidate-at")||"0");return {html:i,createdAt:a,revalidateAt:u}}async set(t,r,o){let n=await this.getCache(),i=this.toUrl(t),a=Date.now(),u=new Response(r,{headers:{"Content-Type":"text/html;charset=UTF-8","x-isr-created-at":String(a),"x-isr-revalidate-at":String(a+o.maxAge*1e3),"x-isr-max-age":String(o.maxAge),"x-isr-stale-while-revalidate":String(o.staleWhileRevalidate),"Cache-Control":`public, max-age=${o.maxAge}, s-maxage=${o.maxAge}, stale-while-revalidate=${o.staleWhileRevalidate}`}});await n.put(i,u);}async purge(t){let r=await this.getCache(),o=this.toUrl(t);await r.delete(o);}async purgePattern(t){let r=await this.getCache(),o=new RegExp("^"+t.replace(/\*/g,".*")+"$"),n=[];for(let i of n){let u=`isr:${new URL(i.url).pathname}`;o.test(u)&&await r.delete(i);}}};function ui(e){let t=60,r=300,n=typeof caches<"u"&&typeof caches.open=="function"?new io:new no;return {async lookup(i){let a=so(i),u=await n.get(a);if(!u)return {status:"miss",html:null};let l=Date.now(),p=u.revalidateAt+r*1e3;return l<=u.revalidateAt?{status:"fresh",html:u.html,entry:u}:l<=p?{status:"stale",html:u.html,entry:u}:{status:"miss",html:null}},async store(i,a,u){let l=so(i),p={maxAge:u?.maxAge??t,staleWhileRevalidate:u?.staleWhileRevalidate??r};await n.set(l,a,p);},async purge(i){let a=so(i);await n.purge(a);},async purgePattern(i){await n.purgePattern(i);},getStore(){return n}}}var zd=[{path:"/",pattern:/^\/$/,meta:{title:"Todo List - Biomimic App",description:"A full-stack application template with React and Hono"}},{path:"/todos",pattern:/^\/todos$/,meta:{title:"Todo List - Biomimic App",description:"Manage your todos with real-time updates"}},{path:"/notifications",pattern:/^\/notifications$/,meta:{title:"Notifications - Biomimic App",description:"Real-time notifications via Server-Sent Events"}},{path:"/websocket",pattern:/^\/websocket$/,meta:{title:"WebSocket Demo - Biomimic App",description:"Type-safe WebSocket communication demo"}},{path:"/content",pattern:/^\/content$/,meta:{title:"\u5185\u5BB9\u4E2D\u5FC3 - Biomimic App",description:"Content management with categories and search"}},{path:"/content/:id",pattern:/^\/content\/([^/]+)$/,meta:{title:"\u5185\u5BB9\u8BE6\u60C5 - Biomimic App",description:"View content details"},loader:async e=>{try{let r=await(I(),c$6(H$1)).getContentById(e.id);if(r)return {__meta:{title:`${r.title} - Biomimic App`,description:r.content?.substring(0,160)||"View content details"},content:r}}catch{}return {}}}];function Bd(e){for(let t of zd){let r=e.match(t.pattern);if(r){let o={};return t.path==="/content/:id"&&r[1]&&(o.id=r[1]),{route:t,params:o}}}return null}async function ao(e,t){let r=Bd(e);if(!r)return $d();let{route:o,params:n}=r,i={...o.meta},a={};if(o.loader)try{let l=await o.loader(n);l.__meta&&(i={...i,...l.__meta},delete l.__meta),a=l;}catch{}return {html:Wd({title:i.title,description:i.description,ogType:i.ogType||"website",data:a,pathname:e}),status:200,headers:{"Content-Type":"text/html;charset=UTF-8","X-ISR-Rendered":"true"}}}function Wd(e){let r=JSON.stringify(e.data).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return `<!DOCTYPE html>
36
+ `).toString("base64")}`}function Cd(){let e=Date.now();for(let[t,r]of _e.entries())e-r.createdAt>3e5&&_e.delete(t);}var Oa=z$1.object({id:z$1.string(),image:z$1.string()}),Ma=z$1.object({id:z$1.string(),code:z$1.string()}),Na=z$1.object({message:z$1.string()});var Ad=createRoute({method:"get",path:"/captcha",tags:["captcha"],responses:{200:c(Oa,"Get captcha")}}),Ed=createRoute({method:"post",path:"/verify-captcha",tags:["captcha"],request:{body:{content:{"application/json":{schema:Ma}}}},responses:{200:c(Na,"Captcha verified"),400:s("Invalid captcha")}}),za=new OpenAPIHono().openapi(Ad,e=>{let{id:t,image:r}=kn();return e.json(p({id:t,image:r}),200)}).openapi(Ed,async e=>{let{id:t,code:r}=e.req.valid("json");if(Un(t,r)){let n=getCookie(e,"session_id");return n&&Do(n),e.json(p({message:"\u9A8C\u8BC1\u6210\u529F"}),200)}else return e.json({success:false,error:"\u9A8C\u8BC1\u7801\u9519\u8BEF\u6216\u5DF2\u8FC7\u671F"},400)});var kd=createRoute({method:"get",path:"/orders",tags:["orders"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["order:view"]})],request:{query:sn},responses:{200:c(nn,"List all orders"),401:s("Unauthorized"),403:s("Forbidden"),500:s("Internal server error")}}),Ud=createRoute({method:"get",path:"/orders/{id}",tags:["orders"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["order:view"]})],request:{params:ee.pick({id:true})},responses:{200:c(ee,"Get order by id"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Order not found"),500:s("Internal server error")}}),jd=createRoute({method:"post",path:"/orders",tags:["orders"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["order:create"]})],request:{body:{content:{"application/json":{schema:rn}}}},responses:{201:c(ee,"Create order"),401:s("Unauthorized"),403:s("Forbidden"),400:s("Invalid input"),500:s("Internal server error")}}),qd=createRoute({method:"put",path:"/orders/{id}",tags:["orders"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["order:edit"]})],request:{params:ee.pick({id:true}),body:{content:{"application/json":{schema:on}}}},responses:{200:c(ee,"Update order"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Order not found"),400:s("Invalid input"),500:s("Internal server error")}}),Dd=createRoute({method:"delete",path:"/orders/{id}",tags:["orders"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["order:delete"]})],request:{params:ee.pick({id:true})},responses:{200:c(an,"Order deleted"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Order not found"),500:s("Internal server error")}}),Od=createRoute({method:"put",path:"/orders/{id}/process",tags:["orders"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["order:process"]})],request:{params:ee.pick({id:true})},responses:{200:c(ee,"Order processed"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Order not found"),400:s("Cannot process order"),500:s("Internal server error")}}),Md=createRoute({method:"put",path:"/orders/{id}/cancel",tags:["orders"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["order:process"]})],request:{params:ee.pick({id:true})},responses:{200:c(ee,"Order cancelled"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Order not found"),400:s("Cannot cancel order"),500:s("Internal server error")}}),Ba=new OpenAPIHono().openapi(kd,async e=>{let{status:t,customerName:r,limit:o,offset:n}=e.req.valid("query"),i=await b$4({status:t??void 0,customerName:r??void 0});return e.json(p(i.slice(n,n+o)),200)}).openapi(Ud,async e=>{let{id:t}=e.req.valid("param"),r=await c$2(t);if(!r)throw new e$1("Order",t);return e.json(p(r),200)}).openapi(jd,async e=>{let t=e.req.valid("json"),r=await d$2(t);return e.json(z(r),201)}).openapi(qd,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=await e$3(t,r);if(!o)throw new e$1("Order",t);return e.json(p(o),200)}).openapi(Dd,async e=>{let{id:t}=e.req.valid("param");if((await f(t)).message==="\u8BA2\u5355\u4E0D\u5B58\u5728")throw new e$1("Order",t);return e.json(p({message:"Deleted successfully"}),200)}).openapi(Od,async e=>{let{id:t}=e.req.valid("param"),r=await g$1(t);if(!r)throw new e$1("Order",t);return e.json(p(r),200)}).openapi(Md,async e=>{let{id:t}=e.req.valid("param"),r=await h$3(t);if(!r)throw new e$1("Order",t);return e.json(p(r),200)});var _a=z$1.enum(["open","in_progress","waiting_customer","resolved","closed"]),Fa=z$1.enum(["low","medium","high","urgent"]),Ha=z$1.enum(["technical","billing","feature_request","bug_report","general"]),Nd=z$1.object({id:z$1.string(),ticketId:z$1.string(),content:z$1.string(),author:z$1.string(),isCustomer:z$1.boolean(),createdAt:z$1.string()}),pe=z$1.object({id:z$1.string(),ticketNo:z$1.string(),customerName:z$1.string(),customerEmail:z$1.string(),subject:z$1.string(),description:z$1.string(),status:_a,priority:Fa,category:Ha,assignedTo:z$1.string().nullish(),createdAt:z$1.string(),updatedAt:z$1.string(),replies:z$1.array(Nd)}),Wa=z$1.object({customerName:z$1.string(),customerEmail:z$1.string().email(),subject:z$1.string(),description:z$1.string(),category:Ha,priority:Fa}),$a=z$1.object({status:_a.nullish(),assignedTo:z$1.string().nullish()}),Va=z$1.object({content:z$1.string(),author:z$1.string()}),Ga=z$1.array(pe),Ka=z$1.object({message:z$1.string()});var zd=createRoute({method:"get",path:"/tickets",tags:["tickets"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["ticket:view"]})],request:{query:z$1.object({limit:z$1.coerce.number().int().positive().max(100).default(20),offset:z$1.coerce.number().int().min(0).default(0)})},responses:{200:c(Ga,"List all tickets"),401:s("Unauthorized"),403:s("Forbidden"),500:s("Internal server error")}}),Bd=createRoute({method:"get",path:"/tickets/{id}",tags:["tickets"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["ticket:view"]})],request:{params:pe.pick({id:true})},responses:{200:c(pe,"Get ticket by id"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Ticket not found"),500:s("Internal server error")}}),_d=createRoute({method:"post",path:"/tickets",tags:["tickets"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["ticket:create"]})],request:{body:{content:{"application/json":{schema:Wa}}}},responses:{201:c(pe,"Create ticket"),401:s("Unauthorized"),403:s("Forbidden"),400:s("Invalid input"),500:s("Internal server error")}}),Fd=createRoute({method:"put",path:"/tickets/{id}",tags:["tickets"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["ticket:edit"]})],request:{params:pe.pick({id:true}),body:{content:{"application/json":{schema:$a}}}},responses:{200:c(pe,"Update ticket"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Ticket not found"),400:s("Invalid input"),500:s("Internal server error")}}),Hd=createRoute({method:"delete",path:"/tickets/{id}",tags:["tickets"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["ticket:delete"]})],request:{params:pe.pick({id:true})},responses:{200:c(Ka,"Ticket deleted"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Ticket not found"),500:s("Internal server error")}}),Wd=createRoute({method:"post",path:"/tickets/{id}/reply",tags:["tickets"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["ticket:reply"]})],request:{params:pe.pick({id:true}),body:{content:{"application/json":{schema:Va}}}},responses:{200:c(pe,"Ticket replied"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Ticket not found"),400:s("Cannot reply ticket"),500:s("Internal server error")}}),$d=createRoute({method:"put",path:"/tickets/{id}/close",tags:["tickets"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["ticket:close"]})],request:{params:pe.pick({id:true})},responses:{200:c(pe,"Ticket closed"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Ticket not found"),400:s("Cannot close ticket"),500:s("Internal server error")}}),Qa=new OpenAPIHono().openapi(zd,async e=>{let{limit:t,offset:r}=e.req.valid("query"),o=await b$5();return e.json(p(o.slice(r,r+t)),200)}).openapi(Bd,async e=>{let{id:t}=e.req.valid("param"),r=await c$3(t);if(!r)throw new e$1("Ticket",t);return e.json(p(r),200)}).openapi(_d,async e=>{let t=e.req.valid("json"),r=await d$3(t);return e.json(z(r),201)}).openapi(Fd,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=await e$4(t,r);if(!o)throw new e$1("Ticket",t);return e.json(p(o),200)}).openapi(Hd,async e=>{let{id:t}=e.req.valid("param");if((await f$1(t)).message==="\u5DE5\u5355\u4E0D\u5B58\u5728")throw new e$1("Ticket",t);return e.json(p({message:"Deleted successfully"}),200)}).openapi(Wd,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=await g$2(t,r);if(!o)throw new e$1("Ticket",t);return e.json(p(o),200)}).openapi($d,async e=>{let{id:t}=e.req.valid("param"),r=await h$4(t);if(!r)throw new e$1("Ticket",t);return e.json(p(r),200)});var Gd=createRoute({method:"get",path:"/disputes",tags:["disputes"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["dispute:view"]})],request:{query:z$1.object({limit:z$1.coerce.number().int().positive().max(100).default(20),offset:z$1.coerce.number().int().min(0).default(0)})},responses:{200:c(yn,"List all disputes"),401:s("Unauthorized"),403:s("Forbidden")}}),Kd=createRoute({method:"get",path:"/disputes/{id}",tags:["disputes"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["dispute:view"]})],request:{params:fe.pick({id:true})},responses:{200:c(fe,"Get dispute by id"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Dispute not found")}}),Qd=createRoute({method:"post",path:"/disputes",tags:["disputes"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["dispute:create"]})],request:Qr(gn),responses:{201:c(fe,"Create dispute"),401:s("Unauthorized"),403:s("Forbidden")}}),Jd=createRoute({method:"put",path:"/disputes/{id}",tags:["disputes"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["dispute:edit"]})],request:{params:fe.pick({id:true}),...Qr(hn)},responses:{200:c(fe,"Update dispute"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Dispute not found")}}),Yd=createRoute({method:"delete",path:"/disputes/{id}",tags:["disputes"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["dispute:delete"]})],request:Bi,responses:{200:c(Oi,"Delete dispute"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Dispute not found")}}),Zd=createRoute({method:"put",path:"/disputes/{id}/resolve",tags:["disputes"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["dispute:resolve"]})],request:{params:fe.pick({id:true}),...Qr(fn)},responses:{200:c(fe,"Dispute resolved"),401:s("Unauthorized"),403:s("Forbidden"),404:s("Dispute not found"),422:s("Cannot resolve dispute in current state")}}),Ja=new OpenAPIHono().openapi(Gd,async e=>{let{limit:t,offset:r}=e.req.valid("query"),o=await b$6();return e.json(p(o.slice(r,r+t)),200)}).openapi(Kd,async e=>{let{id:t}=e.req.valid("param"),r=await c$4(t);if(!r)throw e$1.dispute(t);return e.json(p(r),200)}).openapi(Qd,async e=>{let t=e.req.valid("json"),r=await d$4(t);return e.json(z(r),201)}).openapi(Jd,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=await e$5(t,r);if(!o)throw e$1.dispute(t);return e.json(p(o),200)}).openapi(Yd,async e=>{let{id:t}=e.req.valid("param");if(!(await f$2(t)).success)throw e$1.dispute(t);return e.json(p({message:"Deleted successfully"}),200)}).openapi(Zd,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=await h$5(t,r);if(!o)throw new g$3("Cannot resolve dispute in current state");return e.json(p(o),200)});l$1();var Gt=z$1.enum(["article","announcement","tutorial","news","policy"]),Ya=z$1.enum(["draft","published","archived"]),$=z$1.object({id:z$1.string(),title:z$1.string(),content:z$1.string(),category:Gt,status:Ya,author:z$1.string(),tags:z$1.array(z$1.string()),viewCount:z$1.number(),likeCount:z$1.number(),createdAt:z$1.string(),updatedAt:z$1.string(),publishedAt:z$1.string().nullish()}),Za=z$1.object({title:z$1.string(),content:z$1.string(),category:Gt,tags:z$1.array(z$1.string()).nullish()}),Xa=z$1.object({title:z$1.string().nullish(),content:z$1.string().nullish(),category:Gt.nullish(),tags:z$1.array(z$1.string()).nullish(),status:Ya.nullish()}),ec=z$1.array($),tc=z$1.object({message:z$1.string()});var el=createRoute({method:"get",path:"/contents",tags:["contents"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["content:view"]})],request:{query:z$1.object({limit:z$1.coerce.number().int().positive().max(100).default(20),offset:z$1.coerce.number().int().min(0).default(0)})},responses:{200:c(ec,"List all contents")}}),tl=createRoute({method:"get",path:"/contents/{id}",tags:["contents"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["content:view"]})],request:{params:$.pick({id:true})},responses:{200:c($,"Get content by id"),404:s("Content not found")}}),rl=createRoute({method:"post",path:"/contents",tags:["contents"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["content:create"]})],request:{body:{content:{"application/json":{schema:Za}}}},responses:{201:c($,"Create content"),400:s("Invalid input")}}),ol=createRoute({method:"put",path:"/contents/{id}",tags:["contents"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["content:edit"]})],request:{params:$.pick({id:true}),body:{content:{"application/json":{schema:Xa}}}},responses:{200:c($,"Update content"),404:s("Content not found"),400:s("Invalid input")}}),nl=createRoute({method:"delete",path:"/contents/{id}",tags:["contents"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["content:delete"]})],request:{params:$.pick({id:true})},responses:{200:c(tc,"Content deleted"),404:s("Content not found")}}),sl=createRoute({method:"put",path:"/contents/{id}/publish",tags:["contents"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["content:edit"]})],request:{params:$.pick({id:true})},responses:{200:c($,"Content published"),404:s("Content not found"),422:s("Content cannot be published")}}),il=createRoute({method:"put",path:"/contents/{id}/archive",tags:["contents"],security:[{Bearer:[]}],middleware:[h({requiredPermissions:["content:edit"]})],request:{params:$.pick({id:true})},responses:{200:c($,"Content archived"),404:s("Content not found"),422:s("Content cannot be archived")}}),rc=new OpenAPIHono().openapi(el,async e=>{let{limit:t,offset:r}=e.req.valid("query"),o=await d$5();return e.json(p(o.slice(r,r+t)),200)}).openapi(tl,async e=>{let{id:t}=e.req.valid("param"),r=await e$6(t);if(!r)throw new e$1("Content",t);return e.json(p(r),200)}).openapi(rl,async e=>{let t=e.req.valid("json"),r=await f$3(t);return e.json(z(r),201)}).openapi(ol,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=await g$4(t,r);if(!o)throw new e$1("Content",t);return e.json(p(o),200)}).openapi(nl,async e=>{let{id:t}=e.req.valid("param");if(!(await h$6(t)).success)throw new e$1("Content",t);return e.json(p({message:"Deleted successfully"}),200)}).openapi(sl,async e=>{let{id:t}=e.req.valid("param"),r=await i(t);if(!r)throw new g$3("Content cannot be published (must be in draft state)");return e.json(p(r),200)}).openapi(il,async e=>{let{id:t}=e.req.valid("param"),r=await j$1(t);if(!r)throw new g$3("Content cannot be archived (must be in published state)");return e.json(p(r),200)});l$1();var cl=createRoute({method:"get",path:"/public/contents",tags:["public-contents"],request:{query:z$1.object({category:Gt.optional(),search:z$1.string().optional(),limit:z$1.coerce.number().int().positive().max(50).default(20),offset:z$1.coerce.number().int().min(0).default(0)})},responses:{200:c(z$1.array($),"List published contents")}}),pl=createRoute({method:"get",path:"/public/contents/{id}",tags:["public-contents"],request:{params:$.pick({id:true})},responses:{200:c($,"Get published content"),404:s("Content not found")}}),nc=new OpenAPIHono().openapi(cl,async e=>{let{category:t,search:r,limit:o,offset:n}=e.req.valid("query"),u=(await d$5({status:"published",category:t,search:r})).slice(n,n+o);return e.json(p(u),200)}).openapi(pl,async e=>{let{id:t}=e.req.valid("param"),r=await e$6(t);if(!r||r.status!=="published")throw new e$1("Content",t);return e.json(p(r),200)});var sc=z$1.any(),dl=createRoute({method:"get",path:"/public/{namespace}/{filename}",tags:["files"],request:{params:Ne},responses:{200:{description:"File content",content:{"application/octet-stream":{schema:sc}}},404:s("File not found")}}),ll=createRoute({method:"get",path:"/private/{namespace}/{filename}",tags:["files"],request:{params:Ne,query:Tt},responses:{200:{description:"File content",content:{"application/octet-stream":{schema:sc}}},403:s("Invalid or expired signature"),404:s("File not found")}}),ml=createRoute({method:"post",path:"/generate-url",tags:["files"],request:{body:{content:{"application/json":{schema:lr}}}},responses:{200:c(mr,"URL generated successfully"),400:s("Invalid request"),404:s("File not found")}}),gl=createRoute({method:"head",path:"/public/{namespace}/{filename}",tags:["files"],request:{params:Ne},responses:{200:{description:"File exists",content:{"application/octet-stream":{schema:z$1.null()}}},404:s("File not found")}}),hl=createRoute({method:"head",path:"/private/{namespace}/{filename}",tags:["files"],request:{params:Ne,query:Tt},responses:{200:{description:"File exists",content:{"application/octet-stream":{schema:z$1.null()}}},403:s("Invalid or expired signature"),404:s("File not found")}}),fl=createRoute({method:"post",path:"/upload",tags:["files"],middleware:[ri],request:{body:{content:{"multipart/form-data":{schema:hr}}}},responses:{200:c(gr,"File uploaded successfully"),400:s("Invalid file or upload failed")}}),lo=new OpenAPIHono().openapi(dl,async e=>{let{namespace:t,filename:r}=e.req.valid("param"),o=await g$5(t,r);if(!o)throw new e$1("File",`${t}/${r}`);let n=c$5(t,r),i=await b$7(n);return e.header("Content-Type",o.mimeType),e.header("Content-Length",o.size.toString()),e.header("Content-Disposition",`inline; filename="${r}"`),e.header("Cache-Control","public, max-age=31536000"),e.header("Last-Modified",o.lastModified.toUTCString()),e.body(i)}).openapi(ll,async e=>{let{namespace:t,filename:r}=e.req.valid("param"),{expiry:o,signature:n}=e.req.valid("query");if(Math.floor(Date.now()/1e3)>o)throw new d$6("URL has expired");if(!e$7(t,r,o,n))throw new d$6("Invalid signature");let u=await g$5(t,r);if(!u)throw new e$1("File",`${t}/${r}`);let d=c$5(t,r),l=await b$7(d);return e.header("Content-Type",u.mimeType),e.header("Content-Length",u.size.toString()),e.header("Content-Disposition",`inline; filename="${r}"`),e.header("Cache-Control","private, no-store"),e.body(l)}).openapi(ml,async e=>{let{namespace:t,filename:r,isPrivate:o,expirySeconds:n}=e.req.valid("json");if(!await g$5(t,r))throw new e$1("File",`${t}/${r}`);let u=process.env.PUBLIC_URL||"";if(o){let{url:l,expiry:m}=f$4(t,r,n??void 0,u);return e.json(p({url:l,expiry:m}),200)}let d=d$7(t,r,u);return e.json(p({url:d}),200)}).openapi(gl,async e=>{let{namespace:t,filename:r}=e.req.valid("param"),o=await g$5(t,r);if(!o)throw new e$1("File",`${t}/${r}`);return e.header("Content-Type",o.mimeType),e.header("Content-Length",o.size.toString()),e.header("Last-Modified",o.lastModified.toUTCString()),e.body(null,200)}).openapi(hl,async e=>{let{namespace:t,filename:r}=e.req.valid("param"),{expiry:o,signature:n}=e.req.valid("query");if(Math.floor(Date.now()/1e3)>o)return e.json({success:false,error:"URL has expired"},403);if(!e$7(t,r,o,n))return e.json({success:false,error:"Invalid signature"},403);let u=await g$5(t,r);if(!u)throw new e$1("File",`${t}/${r}`);return e.header("Content-Type",u.mimeType),e.header("Content-Length",u.size.toString()),e.body(null,200)}).openapi(fl,async e=>{let t=await e.req.parseBody(),r=t.file;if(!r||!(r instanceof File))return e.json({success:false,error:"No file provided"},400);let o=typeof t.namespace=="string"?t.namespace:"uploads",n=await r.arrayBuffer(),i=await a$1(o,{name:r.name,type:r.type,size:r.size,data:n}),u=d$7(o,i.filename);return e.json(p({filename:i.filename,originalName:i.originalName,mimeType:i.mimeType,size:i.size,url:u}),200)});a();J();d();function Mn(e){return {id:e.id,username:e.username,email:e.email,role:e.role,createdAt:a$5(e.createdAt)}}async function ac(e){let t=await i$2(),r=await t.select().from(z$2).where(or(eq(z$2.email,e.email),eq(z$2.username,e.username)));if(r.length>0){let l=r[0].email===e.email?"email":"username";throw f$7.duplicateEntry(l,e[l]??"")}let o=a$6(),n=`ak_${a$6()}`,i=hashSync(e.password,10),u=new Date;await t.insert(z$2).values({id:o,username:e.username,email:e.email,passwordHash:i,apiKey:n,createdAt:u,updatedAt:u});let d=await t.select().from(z$2).where(eq(z$2.id,o));return {profile:Mn(d[0])}}async function cc(e){let t=await i$2(),r=e.account||e.email;if(!r)throw new c$7("Account or email is required");let o=await t.select().from(z$2).where(or(eq(z$2.email,r),eq(z$2.username,r)));if(o.length===0)throw new c$7("Invalid credentials");let n=o[0];if(!compareSync(e.password,n.passwordHash))throw new c$7("Invalid credentials");return {profile:Mn(n)}}async function pc(e){let r=await(await i$2()).select().from(z$2).where(eq(z$2.id,e));return r.length===0?null:Mn(r[0])}var bl=process.env.AUTH_SECRET_KEY||"dev-secret-key-change-in-production";function uc(e){return fp.sign({userId:e.id,username:e.username,email:e.email,role:e.role},bl,{expiresIn:"7d"})}var xl=createRoute({method:"post",path:"/auth/register",tags:["auth"],request:{body:{content:{"application/json":{schema:Pr}}}},responses:{201:c(kt,"Register a new developer"),409:s("Email or username already exists"),400:s("Invalid input")}}),Cl=createRoute({method:"post",path:"/auth/login",tags:["auth"],request:{body:{content:{"application/json":{schema:Tr}}}},responses:{200:c(kt,"Login and get token"),401:s("Invalid credentials"),400:s("Invalid input")}}),Tl=createRoute({method:"get",path:"/auth/verify",tags:["auth"],responses:{200:c(It,"Verify token and get profile"),401:s("Unauthorized")}}),dc=new OpenAPIHono().openapi(xl,async e=>{let t=e.req.valid("json"),{profile:r}=await ac(t),o=uc(r);return e.json(z({token:o,profile:r}),201)}).openapi(Cl,async e=>{let t=e.req.valid("json"),{profile:r}=await cc(t),o=uc(r);return e.json(p({token:o,profile:r}),200)}).openapi(Tl,async e=>{let t=e.get("authUser"),r=await pc(t.id);if(!r)throw new b$1("Developer profile not found");return e.json(p(r),200)});a();J();function mo(e){if(e)try{return JSON.parse(e)}catch{return}}function $e(e){return e==null?null:JSON.stringify(e)}function V(e){return {id:e.id,name:e.name,slug:e.slug,description:e.description??"",readme:e.readme??void 0,authorId:e.authorId,authorName:e.authorName,repositoryUrl:e.repositoryUrl??void 0,homepageUrl:e.homepageUrl??void 0,npmPackage:e.npmPackage??void 0,license:e.license??void 0,version:e.version,status:e.status,downloadCount:e.downloadCount,viewCount:e.viewCount,featured:e.featured,screenshotUrl:e.screenshotUrl??void 0,siteUrls:mo(e.siteUrls),tags:mo(e.tags),commands:mo(e.commands),rejectReason:e.rejectReason??void 0,createdAt:e.createdAt.getTime(),updatedAt:e.updatedAt.getTime()}}async function lc(e){let t=await i$2();if((await t.select().from(C).where(eq(C.slug,e.slug))).length>0)throw new f$7(`Plugin with slug '${e.slug}' already exists`);let o=a$6(),n=new Date,i=await t.insert(C).values({id:o,name:e.name,slug:e.slug,description:e.description,readme:e.readme??null,authorId:e.authorId,authorName:e.authorName,repositoryUrl:e.repositoryUrl??null,homepageUrl:e.homepageUrl??null,npmPackage:e.npmPackage??null,license:e.license??null,version:"0.0.1",status:"pending",screenshotUrl:e.screenshotUrl??null,siteUrls:$e(e.siteUrls),tags:$e(e.tags),commands:$e(e.commands),createdAt:n,updatedAt:n}).returning();return V(i[0])}async function mc(e,t,r){let o=await i$2(),n=await o.select().from(C).where(eq(C.slug,e));if(n.length===0)throw new e$1("Plugin",e);if(n[0].authorId!==r)throw new d$6("Only the plugin author can update this plugin");let u={updatedAt:new Date};t.name!==void 0&&(u.name=t.name),t.description!==void 0&&(u.description=t.description),t.readme!==void 0&&(u.readme=t.readme),t.repositoryUrl!==void 0&&(u.repositoryUrl=t.repositoryUrl),t.homepageUrl!==void 0&&(u.homepageUrl=t.homepageUrl),t.npmPackage!==void 0&&(u.npmPackage=t.npmPackage),t.license!==void 0&&(u.license=t.license),t.screenshotUrl!==void 0&&(u.screenshotUrl=t.screenshotUrl),t.siteUrls!==void 0&&(u.siteUrls=$e(t.siteUrls)),t.tags!==void 0&&(u.tags=$e(t.tags)),t.commands!==void 0&&(u.commands=$e(t.commands));let d=await o.update(C).set(u).where(eq(C.slug,e)).returning();return V(d[0])}async function gc(e,t){let r=await i$2(),o=await r.select().from(C).where(eq(C.slug,e));if(o.length===0)throw new e$1("Plugin",e);if(o[0].authorId!==t)throw new d$6("Only the plugin author can delete this plugin");await r.delete(C).where(eq(C.slug,e));}async function hc(e){let t=await i$2(),r=await t.select().from(C).where(eq(C.slug,e));if(r.length===0)throw new e$1("Plugin",e);await t.update(C).set({downloadCount:r[0].downloadCount+1,updatedAt:new Date}).where(eq(C.slug,e));}a();J();function El(e){return {id:e.id,pluginId:e.pluginId,version:e.version,changelog:e.changelog??void 0,packageUrl:e.packageUrl??void 0,fileSize:e.fileSize??void 0,checksum:e.checksum??void 0,status:e.status,publishedAt:e.publishedAt.getTime()}}function Il(e){return {id:e.id,name:e.name,slug:e.slug,description:e.description??void 0,icon:e.icon??void 0,sortOrder:e.sortOrder}}async function kl(e,t=""){try{let r=await j$3();if(!r||!("execute"in r))return 0;let o=t?`SELECT COUNT(*) as count FROM ${e} WHERE ${t}`:`SELECT COUNT(*) as count FROM ${e}`;return (await r.execute(o)).rows[0]?.count??0}catch{return 0}}async function yc(e={}){try{let t=await i$2(),r=e.page??1,o=e.limit??20,n=(r-1)*o,i=[];e.status?i.push(eq(C.status,e.status)):i.push(eq(C.status,"approved")),e.featured!==void 0&&e.featured!==null&&i.push(eq(C.featured,e.featured));let u=i.length>1?and(...i):i[0],d;switch(e.sort){case "popular":d=desc(C.viewCount);break;case "downloads":d=desc(C.downloadCount);break;case "name":d=asc(C.name);break;default:d=desc(C.createdAt);}let l=await t.select().from(C).where(u).orderBy(d).limit(o).offset(n),m=await kl("plugins",e.status?`status = '${e.status}'`:"status = 'approved'");return {plugins:l.map(V),total:m,page:r,limit:o}}catch{return {plugins:[],total:0,page:e.page??1,limit:e.limit??20}}}async function Sc(e,t={}){try{let r=await i$2(),o=t.page??1,n=t.limit??20,i=(o-1)*n,u=`%${e}%`,d=[eq(C.status,"approved"),or(like(C.name,u),like(C.description,u),like(C.tags,u),like(C.authorName,u))];if(t.category){let P=await r.select().from(F).where(eq(F.slug,t.category));if(P.length>0){let _=await r.select().from(G).where(eq(G.categoryId,P[0].id));if(_.length>0){let ue=_.map(Zt=>Zt.pluginId);d.push(sql`${C.id} IN (${sql.join(ue.map(Zt=>sql`${Zt}`),sql`, `)})`);}}}let l=and(...d),m=await r.select().from(C).where(l).orderBy(desc(C.downloadCount)).limit(n).offset(i),R=await j$3(),v=0;if(R&&"execute"in R)try{let P=e.replace(/'/g,"''");v=(await R.execute(`SELECT COUNT(*) as count FROM plugins WHERE status = 'approved' AND (name LIKE '%${P}%' OR description LIKE '%${P}%' OR tags LIKE '%${P}%' OR author_name LIKE '%${P}%')`)).rows[0]?.count??0;}catch{v=0;}return {plugins:m.map(V),total:v,page:o,limit:n}}catch{return {plugins:[],total:0,page:t.page??1,limit:t.limit??20}}}async function Qt(e){try{let t=await i$2(),r=await t.select().from(C).where(eq(C.slug,e));if(r.length===0)throw new e$1("Plugin",e);try{await t.update(C).set({viewCount:r[0].viewCount+1}).where(eq(C.slug,e));}catch{}return V(r[0])}catch(t){throw e$1&&t instanceof e$1?t:new e$1("Plugin",e)}}async function wc(e){try{return (await(await i$2()).select().from(D).where(eq(D.pluginId,e)).orderBy(desc(D.publishedAt))).map(El)}catch{return []}}async function Rc(){try{return (await(await i$2()).select().from(F).orderBy(asc(F.sortOrder))).map(Il)}catch{return []}}async function vc(e,t={}){try{let r=await i$2(),o=t.page??1,n=t.limit??20,i=(o-1)*n,u=await r.select().from(F).where(eq(F.slug,e));if(u.length===0)throw new e$1("Category",e);let d=u[0].id,m=(await r.select().from(G).where(eq(G.categoryId,d))).map(ue=>ue.pluginId);if(m.length===0)return {plugins:[],total:0,page:o,limit:n};let R=and(eq(C.status,"approved"),sql`${C.id} IN (${sql.join(m.map(ue=>sql`${ue}`),sql`, `)})`),v=await r.select().from(C).where(R).orderBy(desc(C.downloadCount)).limit(n).offset(i),P=await j$3(),_=0;if(P&&"execute"in P)try{let ue=m.map(sp=>`'${sp}'`).join(",");_=(await P.execute(`SELECT COUNT(*) as count FROM plugins WHERE status = 'approved' AND id IN (${ue})`)).rows[0]?.count??0;}catch{_=0;}return {plugins:v.map(V),total:_,page:o,limit:n}}catch(r){if(e$1&&r instanceof e$1)throw r;return {plugins:[],total:0,page:t.page??1,limit:t.limit??20}}}async function bc(e){try{return (await(await i$2()).select().from(C).where(eq(C.authorId,e)).orderBy(desc(C.createdAt))).map(V)}catch{return []}}async function xc(){try{let e=await j$3();if(!e||!("execute"in e))return {totalPlugins:0,totalDownloads:0,totalDevelopers:0,totalCategories:0};let[t,r,o,n]=await Promise.all([e.execute("SELECT COUNT(*) as count FROM plugins WHERE status = 'approved'"),e.execute("SELECT COALESCE(SUM(download_count), 0) as total FROM plugins"),e.execute("SELECT COUNT(DISTINCT author_id) as count FROM plugins"),e.execute("SELECT COUNT(*) as count FROM plugin_categories")]);return {totalPlugins:t.rows[0]?.count??0,totalDownloads:r.rows[0]?.total??0,totalDevelopers:o.rows[0]?.count??0,totalCategories:n.rows[0]?.count??0}}catch{return {totalPlugins:0,totalDownloads:0,totalDevelopers:0,totalCategories:0}}}a();J();function Cc(e){return {id:e.id,pluginId:e.pluginId,userId:e.userId,userName:e.userName,rating:e.rating,title:e.title??void 0,content:e.content??void 0,createdAt:e.createdAt.getTime()}}async function Tc(e){let t=await i$2();if((await t.select().from(C).where(eq(C.id,e.pluginId))).length===0)throw new e$1("Plugin",e.pluginId);if((await t.select().from(E).where(and(eq(E.pluginId,e.pluginId),eq(E.userId,e.userId)))).length>0)throw new f$7("You have already reviewed this plugin");let n=a$6(),i=new Date,u=await t.insert(E).values({id:n,pluginId:e.pluginId,userId:e.userId,userName:e.userName,rating:e.rating,title:e.title??null,content:e.content??null,createdAt:i}).returning();return Cc(u[0])}async function Pc(e){return (await(await i$2()).select().from(E).where(eq(E.pluginId,e)).orderBy(E.createdAt)).map(Cc)}async function Ac(e,t){let r=await i$2(),o=await r.select().from(E).where(eq(E.id,e));if(o.length===0)throw new e$1("Review",e);if(o[0].userId!==t)throw new d$6("Only the review author can delete this review");await r.delete(E).where(eq(E.id,e));}var Ol=createRoute({method:"get",path:"/plugins",tags:["plugins"],request:{query:jr},responses:{200:c(ot,"List plugins")}}),Ml=createRoute({method:"get",path:"/plugins/search",tags:["plugins"],request:{query:qr},responses:{200:c(ot,"Search plugins")}}),Nl=createRoute({method:"get",path:"/plugins/{slug}",tags:["plugins"],request:{params:K},responses:{200:c(Z,"Get plugin by slug"),404:s("Plugin not found")}}),Ll=createRoute({method:"get",path:"/plugins/{slug}/versions",tags:["plugins"],request:{params:K},responses:{200:c(z$1.array(Er),"List plugin versions"),404:s("Plugin not found")}}),zl=createRoute({method:"post",path:"/plugins",tags:["plugins"],security:[{Bearer:[]}],request:{body:{content:{"application/json":{schema:jt}}}},responses:{201:c(Z,"Create plugin"),400:s("Invalid input"),409:s("Plugin slug already exists")}}),Bl=createRoute({method:"put",path:"/plugins/{slug}",tags:["plugins"],security:[{Bearer:[]}],request:{params:K,body:{content:{"application/json":{schema:Ar}}}},responses:{200:c(Z,"Update plugin"),404:s("Plugin not found"),403:s("Forbidden")}}),_l=createRoute({method:"delete",path:"/plugins/{slug}",tags:["plugins"],security:[{Bearer:[]}],request:{params:K},responses:{200:c(ze,"Delete plugin"),404:s("Plugin not found"),403:s("Forbidden")}}),Fl=createRoute({method:"post",path:"/plugins/{slug}/reviews",tags:["plugins"],security:[{Bearer:[]}],request:{params:K,body:{content:{"application/json":{schema:Ir}}}},responses:{201:c(qt,"Submit review"),404:s("Plugin not found"),409:s("Already reviewed")}}),Hl=createRoute({method:"get",path:"/plugins/{slug}/reviews",tags:["plugins"],request:{params:K},responses:{200:c(z$1.array(qt),"List reviews")}}),Wl=createRoute({method:"delete",path:"/plugins/{slug}/reviews/{reviewId}",tags:["plugins"],security:[{Bearer:[]}],request:{params:Dr},responses:{200:c(Or,"Review deleted"),404:s("Review not found"),403:s("Forbidden")}}),$l=createRoute({method:"post",path:"/plugins/{slug}/install",tags:["plugins"],request:{params:K},responses:{200:c(ze,"Install tracked"),404:s("Plugin not found")}}),Vl=createRoute({method:"get",path:"/categories",tags:["plugins"],responses:{200:c(z$1.array(Ie),"List categories")}}),Gl=createRoute({method:"get",path:"/categories/{slug}/plugins",tags:["plugins"],request:{params:Mr,query:Nr},responses:{200:c(ot,"Plugins by category"),404:s("Category not found")}}),Kl=createRoute({method:"get",path:"/stats",tags:["plugins"],responses:{200:c(kr,"Marketplace stats")}}),Ql=createRoute({method:"get",path:"/plugins/mine",tags:["plugins"],security:[{Bearer:[]}],responses:{200:c(z$1.array(Z),"My plugins")}}),Ec=new OpenAPIHono().openapi(Ql,async e=>{let t=L(e);if(!t)return e.json({success:false,error:"Unauthorized"},401);try{let r=await bc(t.id);return e.json(p(r),200)}catch{return e.json(p([]),200)}}).openapi(Ol,async e=>{let t=e.req.valid("query");try{let r=await yc({page:t.page,limit:t.limit,status:t.status,sort:t.sort,featured:t.featured});return e.json(p(r),200)}catch{return e.json(p({plugins:[],total:0,page:1,limit:20}),200)}}).openapi(Ml,async e=>{let{q:t,page:r,limit:o,category:n}=e.req.valid("query");try{let i=await Sc(t,{page:r,limit:o,category:n});return e.json(p(i),200)}catch{return e.json(p({plugins:[],total:0,page:1,limit:20}),200)}}).openapi(Nl,async e=>{let{slug:t}=e.req.valid("param");try{let r=await Qt(t);return e.json(p(r),200)}catch{return e.json({success:false,error:"Plugin not found"},404)}}).openapi(Ll,async e=>{let{slug:t}=e.req.valid("param");try{let r=await Qt(t),o=await wc(r.id);return e.json(p(o),200)}catch{return e.json(p([]),200)}}).openapi(zl,async e=>{let t=e.req.valid("json"),r=L(e),o=await lc({...t,authorId:r.id,authorName:r.username});return e.json(z(o),201)}).openapi(Bl,async e=>{let{slug:t}=e.req.valid("param"),r=e.req.valid("json"),o=L(e),n=await mc(t,r,o.id);return e.json(p(n),200)}).openapi(_l,async e=>{let{slug:t}=e.req.valid("param"),r=L(e);return await gc(t,r.id),e.json(p({slug:t}),200)}).openapi(Fl,async e=>{let{slug:t}=e.req.valid("param"),r=e.req.valid("json"),o=L(e);try{let n=await Qt(t),i=await Tc({pluginId:n.id,userId:o.id,userName:o.username,rating:r.rating,title:r.title,content:r.content});return e.json(z(i),201)}catch{return e.json({success:false,error:"Plugin not found"},404)}}).openapi(Hl,async e=>{let{slug:t}=e.req.valid("param");try{let r=await Qt(t),o=await Pc(r.id);return e.json(p(o),200)}catch{return e.json(p([]),200)}}).openapi(Wl,async e=>{let{reviewId:t}=e.req.valid("param"),r=L(e);return await Ac(t,r.id),e.json(p({id:t}),200)}).openapi($l,async e=>{let{slug:t}=e.req.valid("param");try{return await hc(t),e.json(p({slug:t}),200)}catch{return e.json(p({slug:t}),200)}}).openapi(Vl,async e=>{try{let t=await Rc();return e.json(p(t),200)}catch{return e.json(p([]),200)}}).openapi(Gl,async e=>{let{slug:t}=e.req.valid("param"),{page:r,limit:o}=e.req.valid("query");try{let n=await vc(t,{page:r,limit:o});return e.json(p(n),200)}catch{return e.json(p({plugins:[],total:0,page:1,limit:20}),200)}}).openapi(Kl,async e=>{let t=await xc();return e.json(p(t),200)});a();J();async function Ic(e={}){let t=await i$2(),r=e.page??1,o=e.limit??20,n=(r-1)*o,i=await t.select().from(C).where(eq(C.status,"pending")).orderBy(desc(C.createdAt)).limit(o).offset(n),u=await j$3(),d=0;return u&&"execute"in u&&(d=(await u.execute("SELECT COUNT(*) as count FROM plugins WHERE status = 'pending'")).rows[0]?.count??0),{plugins:i.map(V),total:d,page:r,limit:o}}async function kc(e){let t=await i$2();if((await t.select().from(C).where(eq(C.slug,e))).length===0)throw new e$1("Plugin",e);let o=await t.update(C).set({status:"approved",rejectReason:null,updatedAt:new Date}).where(eq(C.slug,e)).returning();return V(o[0])}async function Uc(e,t){let r=await i$2();if((await r.select().from(C).where(eq(C.slug,e))).length===0)throw new e$1("Plugin",e);let n=await r.update(C).set({status:"rejected",rejectReason:t,updatedAt:new Date}).where(eq(C.slug,e)).returning();return V(n[0])}async function jc(e){let t=await i$2(),r=await t.select().from(C).where(eq(C.slug,e));if(r.length===0)throw new e$1("Plugin",e);let o=await t.update(C).set({featured:!r[0].featured,updatedAt:new Date}).where(eq(C.slug,e)).returning();return V(o[0])}async function qc(e){let t=await i$2();if((await t.select().from(C).where(eq(C.slug,e))).length===0)throw new e$1("Plugin",e);await t.delete(C).where(eq(C.slug,e));}async function Dc(e={}){let t=await i$2(),r=e.page??1,o=e.limit??20,n=(r-1)*o,i=e.status?eq(C.status,e.status):void 0,u=e.status?await t.select().from(C).where(i).orderBy(desc(C.createdAt)).limit(o).offset(n):await t.select().from(C).orderBy(desc(C.createdAt)).limit(o).offset(n),d=await j$3(),l=0;if(d&&"execute"in d){let m=e.status?`SELECT COUNT(*) as count FROM plugins WHERE status = '${e.status}'`:"SELECT COUNT(*) as count FROM plugins";l=(await d.execute(m)).rows[0]?.count??0;}return {plugins:u.map(V),total:l,page:r,limit:o}}async function Oc(e){let t=await i$2(),r=0;for(let o of e)(await t.select().from(C).where(eq(C.slug,o))).length>0&&(await t.update(C).set({status:"approved",rejectReason:null,updatedAt:new Date}).where(eq(C.slug,o)),r++);return r}async function Mc(e,t){let r=await i$2(),o=0;for(let n of e)(await r.select().from(C).where(eq(C.slug,n))).length>0&&(await r.update(C).set({status:"rejected",rejectReason:t,updatedAt:new Date}).where(eq(C.slug,n)),o++);return o}a();J();function Bn(e){return {id:e.id,name:e.name,slug:e.slug,description:e.description??void 0,icon:e.icon??void 0,sortOrder:e.sortOrder}}async function Nc(e){let t=await i$2();if((await t.select().from(F).where(eq(F.slug,e.slug))).length>0)throw new f$7(`Category with slug '${e.slug}' already exists`);let o=a$6(),n=await t.insert(F).values({id:o,name:e.name,slug:e.slug,description:e.description??null,icon:e.icon??null,sortOrder:0}).returning();return Bn(n[0])}async function Lc(e,t){let r=await i$2();if((await r.select().from(F).where(eq(F.id,e))).length===0)throw new e$1("Category",e);let n={};t.name!==void 0&&t.name!==null&&(n.name=t.name),t.slug!==void 0&&t.slug!==null&&(n.slug=t.slug),t.description!==void 0&&(n.description=t.description),t.icon!==void 0&&(n.icon=t.icon),t.sortOrder!==void 0&&t.sortOrder!==null&&(n.sortOrder=t.sortOrder);let i=await r.update(F).set(n).where(eq(F.id,e)).returning();return Bn(i[0])}async function zc(e){let t=await i$2();if((await t.select().from(F).where(eq(F.id,e))).length===0)throw new e$1("Category",e);await t.delete(F).where(eq(F.id,e));}async function Bc(){return (await(await i$2()).select().from(F).orderBy(asc(F.sortOrder))).map(Bn)}a();a();J();async function _c(){let e=await j$3();if(!e||!("execute"in e))return {totalPlugins:0,pendingPlugins:0,totalDownloads:0,totalDevelopers:0,totalCategories:0};let[t,r,o,n,i]=await Promise.all([e.execute("SELECT COUNT(*) as count FROM plugins"),e.execute("SELECT COUNT(*) as count FROM plugins WHERE status = 'pending'"),e.execute("SELECT COALESCE(SUM(download_count), 0) as total FROM plugins"),e.execute("SELECT COUNT(DISTINCT author_id) as count FROM plugins"),e.execute("SELECT COUNT(*) as count FROM plugin_categories")]),l=(await(await i$2()).select().from(C).orderBy(C.createdAt).limit(5)).map(V);return {totalPlugins:t.rows[0]?.count??0,pendingPlugins:r.rows[0]?.count??0,totalDownloads:o.rows[0]?.total??0,totalDevelopers:n.rows[0]?.count??0,totalCategories:i.rows[0]?.count??0,recentSubmissions:l}}var rm=createRoute({method:"get",path:"/stats/dashboard",tags:["admin-plugins"],responses:{200:c(Ur,"Dashboard stats")}}),om=createRoute({method:"get",path:"/plugins/pending",tags:["admin-plugins"],request:{query:Lr},responses:{200:c(Dt,"Pending plugins")}}),nm=createRoute({method:"get",path:"/plugins",tags:["admin-plugins"],request:{query:zr},responses:{200:c(Dt,"All plugins")}}),sm=createRoute({method:"put",path:"/plugins/{slug}/approve",tags:["admin-plugins"],request:{params:K},responses:{200:c(Z,"Plugin approved"),404:s("Plugin not found")}}),im=createRoute({method:"put",path:"/plugins/{slug}/reject",tags:["admin-plugins"],request:{params:K,body:{content:{"application/json":{schema:Br}}}},responses:{200:c(Z,"Plugin rejected"),404:s("Plugin not found")}}),am=createRoute({method:"put",path:"/plugins/{slug}/feature",tags:["admin-plugins"],request:{params:K},responses:{200:c(Z,"Featured toggled"),404:s("Plugin not found")}}),cm=createRoute({method:"delete",path:"/plugins/{slug}",tags:["admin-plugins"],request:{params:K},responses:{200:c(ze,"Plugin removed"),404:s("Plugin not found")}}),pm=createRoute({method:"post",path:"/plugins/bulk-approve",tags:["admin-plugins"],request:{body:{content:{"application/json":{schema:_r}}}},responses:{200:c(Ot,"Bulk approved")}}),um=createRoute({method:"post",path:"/plugins/bulk-reject",tags:["admin-plugins"],request:{body:{content:{"application/json":{schema:Fr}}}},responses:{200:c(Ot,"Bulk rejected")}}),dm=createRoute({method:"get",path:"/categories",tags:["admin-plugins"],responses:{200:c(z$1.array(Ie),"List categories")}}),lm=createRoute({method:"post",path:"/categories",tags:["admin-plugins"],request:{body:{content:{"application/json":{schema:Hr}}}},responses:{201:c(Ie,"Category created"),409:s("Category slug already exists")}}),mm=createRoute({method:"put",path:"/categories/{id}",tags:["admin-plugins"],request:{params:Mt,body:{content:{"application/json":{schema:Wr}}}},responses:{200:c(Ie,"Category updated"),404:s("Category not found")}}),gm=createRoute({method:"delete",path:"/categories/{id}",tags:["admin-plugins"],request:{params:Mt},responses:{200:c($r,"Category deleted"),404:s("Category not found")}}),Fc=new OpenAPIHono().openapi(rm,async e=>{let t=await _c();return e.json(p(t),200)}).openapi(om,async e=>{let{page:t,limit:r}=e.req.valid("query"),o=await Ic({page:t,limit:r});return e.json(p(o),200)}).openapi(nm,async e=>{let{page:t,limit:r,status:o}=e.req.valid("query"),n=await Dc({page:t,limit:r,status:o});return e.json(p(n),200)}).openapi(sm,async e=>{let{slug:t}=e.req.valid("param"),r=await kc(t);return e.json(p(r),200)}).openapi(im,async e=>{let{slug:t}=e.req.valid("param"),{reason:r}=e.req.valid("json"),o=await Uc(t,r);return e.json(p(o),200)}).openapi(am,async e=>{let{slug:t}=e.req.valid("param"),r=await jc(t);return e.json(p(r),200)}).openapi(cm,async e=>{let{slug:t}=e.req.valid("param");return await qc(t),e.json(p({slug:t}),200)}).openapi(pm,async e=>{let{slugs:t}=e.req.valid("json"),r=await Oc(t);return e.json(p({count:r}),200)}).openapi(um,async e=>{let{slugs:t,reason:r}=e.req.valid("json"),o=await Mc(t,r);return e.json(p({count:o}),200)}).openapi(dm,async e=>{let t=await Bc();return e.json(p(t),200)}).openapi(lm,async e=>{let t=e.req.valid("json"),r=await Nc(t);return e.json(z(r),201)}).openapi(mm,async e=>{let{id:t}=e.req.valid("param"),r=e.req.valid("json"),o=await Lc(t,r);return e.json(p(o),200)}).openapi(gm,async e=>{let{id:t}=e.req.valid("param");return await zc(t),e.json(p({id:t}),200)});var ym=createRoute({method:"get",path:"/admin/dashboard/stats",responses:{200:c(Xo,"Dashboard stats")}}),Hc=new OpenAPIHono().openapi(ym,async e=>e.json({success:true,data:{stats:[{label:"Total Users",value:"12,847",trend:12.5},{label:"Active Users",value:"8,234",trend:8.2},{label:"Revenue",value:"$48,293",trend:-2.4},{label:"Conversion",value:"3.2%",trend:4.1}],revenue:[{month:"Jan",value:65},{month:"Feb",value:45},{month:"Mar",value:78},{month:"Apr",value:52},{month:"May",value:90},{month:"Jun",value:70}],userGrowth:[{month:"Jan",value:30},{month:"Feb",value:45},{month:"Mar",value:55},{month:"Apr",value:60},{month:"May",value:72},{month:"Jun",value:85}],activity:[{id:1,user:"Sarah Chen",action:"Upgraded to Pro plan",date:"2024-01-15",status:"Active"},{id:2,user:"Mike Johnson",action:"Submitted support ticket",date:"2024-01-14",status:"Pending"},{id:3,user:"Emily Davis",action:"Cancelled subscription",date:"2024-01-13",status:"Inactive"},{id:4,user:"Alex Turner",action:"Registered new account",date:"2024-01-12",status:"Active"},{id:5,user:"Lisa Park",action:"Updated billing info",date:"2024-01-11",status:"Active"}]}}));var wm=50,Rm=.08,_n=[{id:1,name:"Wireless Headphones",variant:"Black",price:79.99,quantity:1,color:"#374151"},{id:2,name:"Organic Cotton T-Shirt",variant:"Medium / Sage",price:34.99,quantity:2,color:"#6ee7b7"},{id:3,name:"Ceramic Travel Mug",variant:"Amber / 350ml",price:24.99,quantity:1,color:"#f59e0b"}];function vm(e){let t=e.reduce((u,d)=>u+d.price*d.quantity,0),r=t>=wm?0:5.99,o=t*Rm,n=t+r+o,i=e.reduce((u,d)=>u+d.quantity,0);return {subtotal:t,shipping:r,tax:o,total:n,totalItems:i}}var bm=createRoute({method:"get",path:"/cart",responses:{200:c(en,"Get cart")}}),xm=createRoute({method:"post",path:"/cart/items",request:{body:{content:{"application/json":{schema:tn}}}},responses:{201:c(Vr,"Item added to cart"),400:s("Invalid input")}}),Cm=createRoute({method:"delete",path:"/cart/items/{id}",request:{params:z$1.object({id:z$1.string()})},responses:{200:c(cn,"Item removed"),404:s("Item not found")}}),$c=new OpenAPIHono().openapi(bm,async e=>{let t=vm(_n);return e.json({success:true,data:{items:_n,summary:t}})}).openapi(xm,async e=>{let t=e.req.valid("json");return e.json({success:true,data:t},201)}).openapi(Cm,async e=>{let{id:t}=e.req.valid("param");return _n.some(o=>String(o.id)===t)?e.json({success:true,data:{removedId:t}}):e.json({success:false,error:"Item not found"},404)});var Am=[{id:"ORD-2024-001",date:"2024-12-10",status:"processing",products:[{name:"Wireless Headphones",color:"#374151"},{name:"USB-C Cable",color:"#6366f1"}],total:94.98},{id:"ORD-2024-002",date:"2024-12-08",status:"shipped",products:[{name:"Organic Cotton T-Shirt",color:"#6ee7b7"},{name:"Ceramic Travel Mug",color:"#f59e0b"},{name:"Linen Tote Bag",color:"#d4a574"}],total:79.97},{id:"ORD-2024-003",date:"2024-12-01",status:"delivered",products:[{name:"Bamboo Desk Organizer",color:"#a3e635"},{name:"Recycled Notebook",color:"#f472b6"}],total:45.98},{id:"ORD-2024-004",date:"2024-11-25",status:"delivered",products:[{name:"Beeswax Candle Set",color:"#fbbf24"}],total:29.99},{id:"ORD-2024-005",date:"2024-11-20",status:"cancelled",products:[{name:"Wooden Phone Stand",color:"#92400e"},{name:"Plant-Based Soap",color:"#86efac"}],total:39.98}],Em=createRoute({method:"get",path:"/orders-mock",responses:{200:c(pn,"List e-commerce orders")}}),Vc=new OpenAPIHono().openapi(Em,async e=>e.json({success:true,data:Am}));var Gc=[{id:"1",title:"How to implement real-time notifications with SSE?",excerpt:"I am trying to set up server-sent events for my community app. The connection keeps dropping after a few minutes. Has anyone dealt with this issue before?",votes:24,replyCount:8,viewCount:342,status:"solved",tags:[{label:"SSE",color:"bg-emerald-100 text-emerald-700"},{label:"Real-time",color:"bg-blue-100 text-blue-700"}],author:{name:"Sarah Chen",initials:"SC"},createdAt:"1h ago"},{id:"2",title:"Best practices for WebSocket reconnection logic",excerpt:"My WebSocket client disconnects when the user switches tabs. What reconnection strategies do you recommend for a production environment?",votes:18,replyCount:0,viewCount:156,status:"unanswered",tags:[{label:"WebSocket",color:"bg-purple-100 text-purple-700"},{label:"Architecture",color:"bg-orange-100 text-orange-700"}],author:{name:"Alex Rivera",initials:"AR"},createdAt:"2h ago"},{id:"3",title:"Type-safe API routes with Hono RPC \u2014 a complete guide",excerpt:"After months of using Hono RPC in production, here is my comprehensive guide to achieving full end-to-end type safety across your stack.",votes:56,replyCount:12,viewCount:891,status:"hot",tags:[{label:"Hono",color:"bg-sky-100 text-sky-700"},{label:"TypeScript",color:"bg-blue-100 text-blue-700"},{label:"Guide",color:"bg-emerald-100 text-emerald-700"}],author:{name:"Jordan Park",initials:"JP"},createdAt:"3h ago"},{id:"4",title:"Deploying Hono apps to Cloudflare Workers with D1",excerpt:"Step-by-step walkthrough of deploying a full-stack Hono application to Cloudflare Workers, including database setup with D1 and R2 storage.",votes:31,replyCount:5,viewCount:478,status:"solved",tags:[{label:"Cloudflare",color:"bg-amber-100 text-amber-700"},{label:"Deployment",color:"bg-rose-100 text-rose-700"}],author:{name:"Mika Tanaka",initials:"MT"},createdAt:"5h ago"},{id:"5",title:"Zustand vs Jotai \u2014 which state manager for community apps?",excerpt:"Comparing Zustand and Jotai for a medium-complexity community application. Performance benchmarks and developer experience included.",votes:42,replyCount:0,viewCount:267,status:"unanswered",tags:[{label:"React",color:"bg-cyan-100 text-cyan-700"},{label:"State Management",color:"bg-violet-100 text-violet-700"}],author:{name:"Liam Nguyen",initials:"LN"},createdAt:"8h ago"},{id:"6",title:"Building a plugin system with module manifests",excerpt:"How we designed a declarative module manifest system that lets users scaffold apps with only the features they need. Patterns and lessons learned.",votes:67,replyCount:19,viewCount:1204,status:"hot",tags:[{label:"Architecture",color:"bg-orange-100 text-orange-700"},{label:"Plugins",color:"bg-pink-100 text-pink-700"}],author:{name:"Emma Wilson",initials:"EW"},createdAt:"12h ago"},{id:"7",title:"Optimizing React components with useMemo and useCallback",excerpt:"Understanding when and how to use React hooks for performance optimization. Real-world examples and benchmarks showing measurable improvements.",votes:45,replyCount:15,viewCount:678,status:"discussion",tags:[{label:"React",color:"bg-cyan-100 text-cyan-700"},{label:"Performance",color:"bg-amber-100 text-amber-700"}],author:{name:"\u5F20\u4F1F",initials:"ZW"},createdAt:"1d ago"},{id:"8",title:"PostgreSQL query optimization for large datasets",excerpt:"Strategies for handling millions of rows with efficient indexing, query planning, and materialized views. Includes EXPLAIN ANALYZE walkthrough.",votes:89,replyCount:23,viewCount:1567,status:"hot",tags:[{label:"PostgreSQL",color:"bg-blue-100 text-blue-700"},{label:"Database",color:"bg-indigo-100 text-indigo-700"},{label:"Performance",color:"bg-amber-100 text-amber-700"}],author:{name:"Raj Sharma",initials:"RS"},createdAt:"1d ago"},{id:"9",title:"Implementing JWT authentication with refresh tokens",excerpt:"Secure authentication flow with JWT access tokens and refresh tokens. Best practices for token storage, rotation, and revocation.",votes:72,replyCount:18,viewCount:1245,status:"solved",tags:[{label:"Auth",color:"bg-rose-100 text-rose-700"},{label:"Security",color:"bg-red-100 text-red-700"},{label:"JWT",color:"bg-pink-100 text-pink-700"}],author:{name:"\u7530\u4E2D\u592A\u90CE",initials:"TT"},createdAt:"2d ago"},{id:"10",title:"Building microservices with Docker and Kubernetes",excerpt:"Complete guide to containerizing Node.js applications and orchestrating them with Kubernetes. Includes service discovery, load balancing, and autoscaling.",votes:103,replyCount:31,viewCount:1890,status:"hot",tags:[{label:"Docker",color:"bg-sky-100 text-sky-700"},{label:"Kubernetes",color:"bg-blue-100 text-blue-700"},{label:"Microservices",color:"bg-violet-100 text-violet-700"}],author:{name:"Marie Dubois",initials:"MD"},createdAt:"2d ago"},{id:"11",title:"Writing accessible React applications",excerpt:"Essential ARIA patterns and semantic HTML for building inclusive web apps. Screen reader testing checklist and common accessibility pitfalls.",votes:58,replyCount:14,viewCount:923,status:"open",tags:[{label:"Accessibility",color:"bg-emerald-100 text-emerald-700"},{label:"React",color:"bg-cyan-100 text-cyan-700"},{label:"A11y",color:"bg-lime-100 text-lime-700"}],author:{name:"\uAE40\uBBFC\uC218",initials:"KM"},createdAt:"3d ago"},{id:"12",title:"TypeScript utility types explained with examples",excerpt:"Deep dive into TypeScript utility types like Pick, Omit, Partial, Record, and more. Practical examples for everyday use.",votes:81,replyCount:22,viewCount:1456,status:"hot",tags:[{label:"TypeScript",color:"bg-blue-100 text-blue-700"},{label:"Guide",color:"bg-emerald-100 text-emerald-700"}],author:{name:"Anna M\xFCller",initials:"AM"},createdAt:"3d ago"},{id:"13",title:"Redis caching strategies for high-traffic APIs",excerpt:"Implementing Redis caching layers for REST APIs. Cache invalidation strategies, TTL policies, and handling cache stampedes.",votes:64,replyCount:9,viewCount:1012,status:"solved",tags:[{label:"Redis",color:"bg-red-100 text-red-700"},{label:"Caching",color:"bg-orange-100 text-orange-700"},{label:"API",color:"bg-sky-100 text-sky-700"}],author:{name:"Carlos Silva",initials:"CS"},createdAt:"3d ago"},{id:"14",title:"GraphQL Federation for microservices architecture",excerpt:"Combining multiple GraphQL services into a unified API with Apollo Federation. Schema stitching, type composition, and distributed tracing.",votes:47,replyCount:0,viewCount:623,status:"unanswered",tags:[{label:"GraphQL",color:"bg-pink-100 text-pink-700"},{label:"Microservices",color:"bg-violet-100 text-violet-700"}],author:{name:"\u674E\u660E",initials:"LM"},createdAt:"4h ago"},{id:"15",title:"Testing React components with Vitest and Testing Library",excerpt:"Modern testing setup with Vitest and React Testing Library. Writing maintainable tests, mocking external dependencies, and snapshot testing.",votes:76,replyCount:17,viewCount:1234,status:"discussion",tags:[{label:"Testing",color:"bg-amber-100 text-amber-700"},{label:"React",color:"bg-cyan-100 text-cyan-700"},{label:"Vitest",color:"bg-purple-100 text-purple-700"}],author:{name:"Elena Popova",initials:"EP"},createdAt:"5h ago"},{id:"16",title:"RESTful API design best practices",excerpt:"Comprehensive guide to designing REST APIs. Resource naming, HTTP methods, status codes, pagination, filtering, and versioning strategies.",votes:92,replyCount:28,viewCount:1678,status:"hot",tags:[{label:"API Design",color:"bg-sky-100 text-sky-700"},{label:"REST",color:"bg-emerald-100 text-emerald-700"},{label:"Architecture",color:"bg-orange-100 text-orange-700"}],author:{name:"\u4F50\u85E4\u5065",initials:"SK"},createdAt:"6h ago"},{id:"17",title:"CSS Grid vs Flexbox \u2014 when to use which?",excerpt:"Practical comparison of CSS Grid and Flexbox layouts. Use cases, browser support, and examples of combining both for complex layouts.",votes:39,replyCount:8,viewCount:567,status:"open",tags:[{label:"CSS",color:"bg-indigo-100 text-indigo-700"},{label:"Layout",color:"bg-purple-100 text-purple-700"}],author:{name:"Olga Ivanova",initials:"OI"},createdAt:"8h ago"},{id:"18",title:"Setting up CI/CD pipeline with GitHub Actions",excerpt:"Automating testing, building, and deployment with GitHub Actions. Multi-environment configs, secrets management, and deployment strategies.",votes:68,replyCount:13,viewCount:1102,status:"solved",tags:[{label:"CI/CD",color:"bg-rose-100 text-rose-700"},{label:"GitHub",color:"bg-slate-100 text-slate-700"},{label:"DevOps",color:"bg-blue-100 text-blue-700"}],author:{name:"\u9EC4\u5FD7\u5F3A",initials:"HZ"},createdAt:"30m ago"},{id:"19",title:"Node.js event loop explained in depth",excerpt:"Understanding the Node.js event loop, call stack, and asynchronous operations. Performance implications and best practices for event-driven apps.",votes:55,replyCount:11,viewCount:845,status:"discussion",tags:[{label:"Node.js",color:"bg-green-100 text-green-700"},{label:"Performance",color:"bg-amber-100 text-amber-700"}],author:{name:"Giovanni Rossi",initials:"GR"},createdAt:"45m ago"},{id:"20",title:"Handling file uploads in multipart/form-data with Hono",excerpt:"Implementing secure file upload endpoints in Hono. Validation, storage with R2, handling large files, and progress tracking.",votes:71,replyCount:16,viewCount:1323,status:"solved",tags:[{label:"Hono",color:"bg-sky-100 text-sky-700"},{label:"File Upload",color:"bg-indigo-100 text-indigo-700"},{label:"R2",color:"bg-amber-100 text-amber-700"}],author:{name:"Priya Patel",initials:"PP"},createdAt:"2h ago"},{id:"21",title:"Debouncing and throttling in React applications",excerpt:"Implementing debouncing and throttling for search inputs, scroll events, and API calls. Custom hooks and performance considerations.",votes:33,replyCount:5,viewCount:445,status:"open",tags:[{label:"React",color:"bg-cyan-100 text-cyan-700"},{label:"Performance",color:"bg-amber-100 text-amber-700"},{label:"Hooks",color:"bg-pink-100 text-pink-700"}],author:{name:"\u5C71\u672C\u82B1\u5B50",initials:"YH"},createdAt:"1w ago"}],km=[{id:"1",type:"reply",text:"Replied to",target:"How to implement real-time notifications with SSE?",time:"2h ago"},{id:"2",type:"topic",text:"Created topic",target:"Best practices for WebSocket reconnection logic",time:"5h ago"},{id:"3",type:"like",text:"Liked",target:"Type-safe API routes with Hono RPC \u2014 a complete guide",time:"8h ago"},{id:"4",type:"reply",text:"Replied to",target:"Deploying Hono apps to Cloudflare Workers with D1",time:"1d ago"},{id:"5",type:"topic",text:"Created topic",target:"Zustand vs Jotai \u2014 which state manager for community apps?",time:"2d ago"},{id:"6",type:"like",text:"Liked",target:"Building a plugin system with module manifests",time:"3d ago"},{id:"7",type:"reply",text:"Replied to",target:"How to set up CI/CD for monorepo projects",time:"4d ago"},{id:"8",type:"topic",text:"Created topic",target:"Tailwind CSS v4 migration guide and tips",time:"5d ago"}],Um=createRoute({method:"get",path:"/topics",responses:{200:c(Kr,"List community topics")}}),jm=createRoute({method:"get",path:"/topics/popular",responses:{200:c(Kr,"Popular topics")}}),qm=createRoute({method:"get",path:"/profile",responses:{200:c(un,"User profile")}}),Kc=new OpenAPIHono().openapi(Um,async e=>e.json({success:true,data:Gc})).openapi(jm,async e=>{let t=[...Gc].sort((r,o)=>o.votes-r.votes);return e.json({success:true,data:t})}).openapi(qm,async e=>e.json({success:true,data:{stats:{topics:12,replies:48,likes:156},activity:km}}));var Dm=Ze({windowMs:6e4,max:100,message:"Too many requests"}),Jc=new OpenAPIHono().use("*",Dm).route("/api",Da).route("/api",dc).route("/api",oa).route("/api",ta).route("/api",_i).route("/api",Ec).route("/api",nc).route("/api",$c).route("/api",Vc).route("/api",Kc),Yc=new OpenAPIHono().route("/api",Ba).route("/api",Qa).route("/api",Ja).route("/api",rc).route("/api",lo).route("/api",za).route("/api",Fi).route("/api",Ki).route("/api",Ji).route("/api",qa).route("/api",Fc).route("/api",Hc);function Zc(e={}){let t=new OpenAPIHono().use("*",jo()).use("*",ko()).use("*",Io()).use("*",ni()).use("/api/*",ci()).use("/api/admin/*",qo({maxRequests:20,windowMs:6e4})).route("/",Jc).route("/",Yc).route("/files",lo).get("/health",async r=>{try{let{getDb:o}=await import('./db-FLI5L5DD.js');return await o(),r.json({status:"ok",timestamp:new Date().toISOString(),db:"connected"})}catch{return r.json({status:"ok",timestamp:new Date().toISOString(),db:"not configured"})}}).post("/api/__test__/cleanup",async r=>{try{let{cleanupTestDatabase:o}=await import('./test-setup-VFOPBGYM.js');return await o(),r.json({success:!0,message:"Database cleaned up"})}catch(o){return console.error("Error during database cleanup:",o),r.json({success:false,message:"Failed to cleanup database"},500)}});return Qs(t),t.onError((r,o)=>{let n=f$5("api");if(o.res.headers.set("Content-Type","application/json"),a$7.isAppError(r))return o.json({success:false,error:r.message,status:r.statusCode,details:r.details},r.statusCode);if(r instanceof HTTPException)return o.json({success:false,error:r.message,status:r.status},r.status);if(r instanceof ZodError){let i=r.issues.map(u=>({field:u.path.join("."),message:u.message}));return o.json({success:false,error:"Validation failed",status:400,details:i},400)}return n.error({err:r,path:o.req.path},"Unhandled error"),o.json({success:false,error:r.message||"Internal server error",status:500},500)}),t}a();var Lm=["/","/todos","/content","/notifications","/websocket"],zm=["/content/"];function Xc(e){if(Lm.includes(e))return true;for(let t of zm)if(e.startsWith(t))return true;return false}function Wn(e){return `isr:${e==="/"?"/index":e.replace(/\/$/,"")}`}var $n=class{cache=new Map;timer=null;constructor(){this.timer=setInterval(()=>this.cleanup(),6e4),this.timer&&typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref();}cleanup(){let t=Date.now();for(let[r,o]of this.cache)t>o.revalidateAt+6e4&&this.cache.delete(r);}async get(t){return this.cache.get(t)??null}async set(t,r,o){let n=Date.now();this.cache.set(t,{html:r,createdAt:n,revalidateAt:n+o.maxAge*1e3});}async purge(t){this.cache.delete(t);}async purgePattern(t){let r=new RegExp("^"+t.replace(/\*/g,".*")+"$");for(let o of this.cache.keys())r.test(o)&&this.cache.delete(o);}destroy(){this.timer&&(clearInterval(this.timer),this.timer=null),this.cache.clear();}},Vn=class{cache=null;origin="https://isr.local";async getCache(){return this.cache||(this.cache=await caches.open("isr-pages")),this.cache}toUrl(t){return `${this.origin}${t.replace(/^isr:/,"")}`}async get(t){let r=await this.getCache(),o=this.toUrl(t),n=await r.match(o);if(!n)return null;let i=await n.text(),u=Number(n.headers.get("x-isr-created-at")||"0"),d=Number(n.headers.get("x-isr-revalidate-at")||"0");return {html:i,createdAt:u,revalidateAt:d}}async set(t,r,o){let n=await this.getCache(),i=this.toUrl(t),u=Date.now(),d=new Response(r,{headers:{"Content-Type":"text/html;charset=UTF-8","x-isr-created-at":String(u),"x-isr-revalidate-at":String(u+o.maxAge*1e3),"x-isr-max-age":String(o.maxAge),"x-isr-stale-while-revalidate":String(o.staleWhileRevalidate),"Cache-Control":`public, max-age=${o.maxAge}, s-maxage=${o.maxAge}, stale-while-revalidate=${o.staleWhileRevalidate}`}});await n.put(i,d);}async purge(t){let r=await this.getCache(),o=this.toUrl(t);await r.delete(o);}async purgePattern(t){let r=await this.getCache(),o=new RegExp("^"+t.replace(/\*/g,".*")+"$"),n=[];for(let i of n){let d=`isr:${new URL(i.url).pathname}`;o.test(d)&&await r.delete(i);}}};function ep(e){let t=60,r=300,n=typeof caches<"u"&&typeof caches.open=="function"?new Vn:new $n;return {async lookup(i){let u=Wn(i),d=await n.get(u);if(!d)return {status:"miss",html:null};let l=Date.now(),m=d.revalidateAt+r*1e3;return l<=d.revalidateAt?{status:"fresh",html:d.html,entry:d}:l<=m?{status:"stale",html:d.html,entry:d}:{status:"miss",html:null}},async store(i,u,d){let l=Wn(i),m={maxAge:d?.maxAge??t,staleWhileRevalidate:d?.staleWhileRevalidate??r};await n.set(l,u,m);},async purge(i){let u=Wn(i);await n.purge(u);},async purgePattern(i){await n.purgePattern(i);},getStore(){return n}}}var Bm=[{path:"/",pattern:/^\/$/,meta:{title:"Todo List - Biomimic App",description:"A full-stack application template with React and Hono"}},{path:"/todos",pattern:/^\/todos$/,meta:{title:"Todo List - Biomimic App",description:"Manage your todos with real-time updates"}},{path:"/notifications",pattern:/^\/notifications$/,meta:{title:"Notifications - Biomimic App",description:"Real-time notifications via Server-Sent Events"}},{path:"/websocket",pattern:/^\/websocket$/,meta:{title:"WebSocket Demo - Biomimic App",description:"Type-safe WebSocket communication demo"}},{path:"/content",pattern:/^\/content$/,meta:{title:"\u5185\u5BB9\u4E2D\u5FC3 - Biomimic App",description:"Content management with categories and search"}},{path:"/content/:id",pattern:/^\/content\/([^/]+)$/,meta:{title:"\u5185\u5BB9\u8BE6\u60C5 - Biomimic App",description:"View content details"},loader:async e=>{try{let r=await(l$1(),c$a(k$3)).getContentById(e.id);if(r)return {__meta:{title:`${r.title} - Biomimic App`,description:r.content?.substring(0,160)||"View content details"},content:r}}catch{}return {}}}];function _m(e){for(let t of Bm){let r=e.match(t.pattern);if(r){let o={};return t.path==="/content/:id"&&r[1]&&(o.id=r[1]),{route:t,params:o}}}return null}async function Gn(e,t){let r=_m(e);if(!r)return Hm();let{route:o,params:n}=r,i={...o.meta},u={};if(o.loader)try{let l=await o.loader(n);l.__meta&&(i={...i,...l.__meta},delete l.__meta),u=l;}catch{}return {html:Fm({title:i.title,description:i.description,ogType:i.ogType||"website",data:u,pathname:e}),status:200,headers:{"Content-Type":"text/html;charset=UTF-8","X-ISR-Rendered":"true"}}}function Fm(e){let r=JSON.stringify(e.data).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return `<!DOCTYPE html>
31
37
  <html lang="en">
32
38
  <head>
33
39
  <meta charset="UTF-8" />
34
40
  <link rel="icon" type="image/svg+xml" href="/vite.svg" />
35
41
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
36
- <title>${ze(e.title)}</title>
37
- <meta name="description" content="${ze(e.description)}" />
38
- <meta property="og:title" content="${ze(e.title)}" />
39
- <meta property="og:description" content="${ze(e.description)}" />
40
- <meta property="og:type" content="${ze(e.ogType)}" />
41
- <meta property="og:url" content="${ze(e.pathname)}" />
42
+ <title>${ht(e.title)}</title>
43
+ <meta name="description" content="${ht(e.description)}" />
44
+ <meta property="og:title" content="${ht(e.title)}" />
45
+ <meta property="og:description" content="${ht(e.description)}" />
46
+ <meta property="og:type" content="${ht(e.ogType)}" />
47
+ <meta property="og:url" content="${ht(e.pathname)}" />
42
48
  <meta name="generator" content="ISR" />
43
49
  </head>
44
50
  <body>
@@ -46,7 +52,7 @@ data: ${JSON.stringify({timestamp:Date.now()})}
46
52
  <script>window.__SSR_DATA__ = ${r};window.__SSR_PATH__ = ${JSON.stringify(e.pathname)};</script>
47
53
  <script type="module" src="/src/client/main.tsx"></script>
48
54
  </body>
49
- </html>`}function $d(){return {html:`<!DOCTYPE html>
55
+ </html>`}function Hm(){return {html:`<!DOCTYPE html>
50
56
  <html lang="en">
51
57
  <head>
52
58
  <meta charset="UTF-8" />
@@ -59,7 +65,7 @@ data: ${JSON.stringify({timestamp:Date.now()})}
59
65
  <div id="root"></div>
60
66
  <script type="module" src="/src/client/main.tsx"></script>
61
67
  </body>
62
- </html>`,status:200,headers:{"Content-Type":"text/html;charset=UTF-8"}}}function ze(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}y();var nr=c$3(),Kd=process.env.NODE_ENV==="production",ir=resolve(process.cwd(),"dist/client"),ar=Kd&&existsSync(ir),li=ar?resolve(ir,"index.html"):resolve(process.cwd(),"index.html"),mi=ar?resolve(ir,"admin.html"):resolve(process.cwd(),"admin.html"),Yd=existsSync(li)?readFileSync(li,"utf-8"):"<html><body>index.html not found</body></html>",Zd=existsSync(mi)?readFileSync(mi,"utf-8"):"<html><body>admin.html not found</body></html>",fi=g.api(),sr=ui();x(sr);var Be=br();a(Be);Be.handleWS("/api/chat/ws");Be.handleSSE("/api/notifications/stream");Be.handleSSE("/api/admin/notifications/stream");var Jd=di(),Ee=Jd.use("*",async(e,t)=>{let r=Date.now();await t();let o=Date.now()-r;fi.info({method:e.req.method,path:e.req.path,status:e.res.status,ms:o},"request");});nr.enableDocs&&Ee.get("/docs",e=>e.html(`
68
+ </html>`,status:200,headers:{"Content-Type":"text/html;charset=UTF-8"}}}function ht(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}b$8();var yo=c$6(),Gm=process.env.NODE_ENV==="production",So=resolve(process.cwd(),"dist/client"),wo=Gm&&existsSync(So),tp=wo?resolve(So,"index.html"):resolve(process.cwd(),"index.html"),rp=wo?resolve(So,"admin.html"):resolve(process.cwd(),"admin.html"),Km=existsSync(tp)?readFileSync(tp,"utf-8"):"<html><body>index.html not found</body></html>",Qm=existsSync(rp)?readFileSync(rp,"utf-8"):"<html><body>admin.html not found</body></html>",np=g.api(),fo=ep();a$2(fo);var ft=zo();a$3(ft);ft.handleWS("/api/chat/ws");ft.handleSSE("/api/notifications/stream");ft.handleSSE("/api/admin/notifications/stream");var Jm=Zc(),Ke=Jm.use("*",async(e,t)=>{let r=Date.now();await t();let o=Date.now()-r;np.info({method:e.req.method,path:e.req.path,status:e.res.status,ms:o},"request");});yo.enableDocs&&Ke.get("/docs",e=>e.html(`
63
69
  <!DOCTYPE html>
64
70
  <html>
65
71
  <head>
@@ -86,5 +92,5 @@ data: ${JSON.stringify({timestamp:Date.now()})}
86
92
  </script>
87
93
  </body>
88
94
  </html>
89
- `));ar&&Ee.use("/*",async(e,t)=>e.req.path.startsWith("/api/")||e.req.path.startsWith("/files/")?await t():serveStatic({root:ir})(e,t));Ee.get("/admin/*",e=>e.html(Zd));Ee.get("*",async e=>{if(e.req.path.startsWith("/api/")||e.req.path.startsWith("/files/"))return e.notFound();let t=e.req.path;if(ar&&pi(t)){let r=await sr.lookup(t);if(r.status==="fresh"&&r.html)return e.html(r.html);if(r.status==="stale"&&r.html)return ao(t).then(n=>{sr.store(t,n.html).catch(()=>{});}).catch(()=>{}),e.html(r.html);let o=await ao(t);return sr.store(t,o.html).catch(()=>{}),e.html(o.html)}return e.html(Yd)});Ee.onError((e,t)=>{fi.error({err:e,path:t.req.path},"server error"),t.res.headers.set("Content-Type","application/json");let r=e instanceof Error&&"status"in e?e.status:500,o=e.message||"Internal server error",n=r||500;return t.json({success:false,error:o,status:n},n)});var By=Ee;async function Xd(){let e=serve({fetch:Ee.fetch,port:nr.port});return e.on("upgrade",(t,r,o)=>{let n=new URL(t.url||"","http://localhost");Be.hasWSPath(n.pathname)?new WebSocketServer({noServer:true}).handleUpgrade(t,r,o,a=>{Be.handleConnection(a);}):r.destroy();}),{server:e,port:nr.port}}async function Qd(){let e=g.bootstrap();e.info({},"Initializing database...");try{await I$1(),await L$1();let{initializeDatabase:n}=await import('./init-EKZWZXS4.js');await n(),e.info({},"Database ready");}catch(n){e.error({err:n},"Database initialization failed"),process.exit(1);}let{server:t,port:r}=await Xd();e.info({port:r},"Server running"),nr.enableDocs&&e.info({url:`http://localhost:${r}/docs`},"API docs available");let o=async()=>{e.info({},"Shutting down..."),t.close(),process.exit(0);};process.on("SIGINT",o),process.on("SIGTERM",o);}process.env.NODE_ENV==="production"&&Qd().catch(e=>{console.error("Failed to start server:",e),process.exit(1);});
90
- export{Xd as createServer,By as default,Qd as startServer};
95
+ `));wo&&Ke.use("/*",async(e,t)=>e.req.path.startsWith("/api/")||e.req.path.startsWith("/files/")?await t():serveStatic({root:So})(e,t));Ke.get("/admin/*",e=>e.html(Qm));Ke.get("*",async e=>{if(e.req.path.startsWith("/api/")||e.req.path.startsWith("/files/"))return e.notFound();let t=e.req.path;if(wo&&Xc(t)){let r=await fo.lookup(t);if(r.status==="fresh"&&r.html)return e.html(r.html);if(r.status==="stale"&&r.html)return Gn(t).then(n=>{fo.store(t,n.html).catch(i=>{console.warn("ISR cache store (background revalidation) failed:",i);});}).catch(n=>{console.warn("ISR background render failed:",n);}),e.html(r.html);let o=await Gn(t);return fo.store(t,o.html).catch(n=>{console.warn("ISR cache store failed:",n);}),e.html(o.html)}return e.html(Km)});Ke.onError((e,t)=>{np.error({err:e,path:t.req.path},"server error"),t.res.headers.set("Content-Type","application/json");let r=e instanceof Error&&"status"in e?e.status:500,o=e.message||"Internal server error",n=r||500;return t.json({success:false,error:o,status:n},n)});var Mb=Ke;async function Ym(){let e=serve({fetch:Ke.fetch,port:yo.port});return e.on("upgrade",(t,r,o)=>{let n=new URL(t.url||"","http://localhost");ft.hasWSPath(n.pathname)?new WebSocketServer({noServer:true}).handleUpgrade(t,r,o,u=>{ft.handleConnection(u);}):r.destroy();}),{server:e,port:yo.port}}async function Zm(){let e=g.bootstrap();e.info({},"Initializing database...");try{await i$2(),await l$3();let{initializeDatabase:n}=await import('./init-FWYXSKPX.js');await n(),e.info({},"Database ready");}catch(n){e.error({err:n},"Database initialization failed"),process.exit(1);}let{server:t,port:r}=await Ym();e.info({port:r},"Server running"),yo.enableDocs&&e.info({url:`http://localhost:${r}/docs`},"API docs available");let o=async()=>{e.info({},"Shutting down..."),t.close(),process.exit(0);};process.on("SIGINT",o),process.on("SIGTERM",o);}process.env.NODE_ENV==="production"&&Zm().catch(e=>{console.error("Failed to start server:",e),process.exit(1);});
96
+ export{Ym as createServer,Mb as default,Zm as startServer};