@kyro-cms/core 0.12.55 → 0.12.57

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 (49) hide show
  1. package/dist/api-handler-graphql.cjs +1 -1
  2. package/dist/api-handler-graphql.js +1 -1
  3. package/dist/api-handler-trpc.cjs +1 -1
  4. package/dist/api-handler-trpc.js +1 -1
  5. package/dist/api-handler.cjs +1 -1
  6. package/dist/api-handler.js +1 -1
  7. package/dist/{chunk-5YQ2HVHD.js → chunk-5VGYVQPY.js} +10 -10
  8. package/dist/chunk-5ZEYOFAK.js +2 -0
  9. package/dist/chunk-6KERPHAL.cjs +2 -0
  10. package/dist/chunk-72VOOMJI.js +20 -0
  11. package/dist/chunk-7DUKWHRN.cjs +1 -0
  12. package/dist/chunk-FJPY42VZ.cjs +20 -0
  13. package/dist/{chunk-BU6O3TP7.js → chunk-KNOFTUQV.js} +24 -24
  14. package/dist/{chunk-4MVLIR77.cjs → chunk-LBYY3W2D.cjs} +9 -9
  15. package/dist/chunk-LVHWORV4.js +3 -0
  16. package/dist/chunk-PCN6QV3Z.js +21 -0
  17. package/dist/chunk-PCVQNVSU.cjs +19 -0
  18. package/dist/{chunk-QEZKIR5V.cjs → chunk-Q4B2IRX7.cjs} +1 -1
  19. package/dist/{chunk-M645XO2L.js → chunk-R3KFYDRS.js} +1 -1
  20. package/dist/{chunk-V65273ZG.cjs → chunk-T63QLFLZ.cjs} +3 -3
  21. package/dist/{chunk-6KUL2BSA.cjs → chunk-TDGSIF5H.cjs} +24 -24
  22. package/dist/{chunk-AIE7BKVY.js → chunk-WDDKRBSY.js} +1 -1
  23. package/dist/cli/index.cjs +1 -1
  24. package/dist/cli/index.js +1 -1
  25. package/dist/drizzle/index.cjs +1 -1
  26. package/dist/drizzle/index.js +1 -1
  27. package/dist/index.cjs +5 -5
  28. package/dist/index.d.cts +1 -14
  29. package/dist/index.d.ts +1 -14
  30. package/dist/index.js +8 -8
  31. package/dist/integration.cjs +1 -1
  32. package/dist/integration.js +1 -1
  33. package/dist/{local-3V3XEQUY.js → local-2IFOTHAA.js} +1 -1
  34. package/dist/{local-YCWBUF3R.cjs → local-UESCNPQP.cjs} +1 -1
  35. package/dist/{mongo-auth-adapter-W3HLB7OR.cjs → mongo-auth-adapter-EUHAYWJ6.cjs} +1 -1
  36. package/dist/{mongo-auth-adapter-QDXVHREJ.js → mongo-auth-adapter-FW7ATYQ6.js} +1 -1
  37. package/dist/mongodb/index.cjs +1 -1
  38. package/dist/mongodb/index.js +1 -1
  39. package/dist/rest/index.cjs +1 -1
  40. package/dist/rest/index.js +1 -1
  41. package/package.json +2 -2
  42. package/dist/chunk-CMQYYIGC.js +0 -21
  43. package/dist/chunk-LELK3TYX.js +0 -3
  44. package/dist/chunk-OW3HFVPX.cjs +0 -20
  45. package/dist/chunk-PRMILS4Y.js +0 -20
  46. package/dist/chunk-UT7RGIYS.js +0 -2
  47. package/dist/chunk-WJBQ2NBD.cjs +0 -1
  48. package/dist/chunk-XDE7CFV6.cjs +0 -19
  49. package/dist/chunk-ZKHTFR5S.cjs +0 -2
@@ -0,0 +1,3 @@
1
+ import {a,c,b as b$1,d}from'./chunk-SLMIYECU.js';import {a as a$1}from'./chunk-P6JITOFF.js';import {a as a$2}from'./chunk-VVVCCB6R.js';import {g}from'./chunk-Y2YAKDEQ.js';import {randomBytes}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
+ g();g();var b=class extends a{dialect="mongodb";client;db;database;connectionString;constructor(o){if(super(),o.connectionString){this.connectionString=o.connectionString;try{let e=new URL(o.connectionString);this.database=e.pathname.replace(/^\//,"")||"kyro_cms";}catch{this.database="kyro_cms";}}else this.client=o.client,this.database=o.database;}async connect(){if(this.connectionString&&!this.client){let o;try{let e=await import('./lib-XXYYUPMW.js');o=e.MongoClient??e.default?.MongoClient;}catch{a$1(["mongodb"]);let n=await import('./lib-XXYYUPMW.js');o=n.MongoClient??n.default?.MongoClient;}this.client=new o(this.connectionString),await this.client.connect();}this.db=this.client.db(this.database),this.connected=true;}async disconnect(){this.client&&(await this.client.close(),this.connected=false);}getMongoCollection(o){if(!this.db)throw new Error("MongoDB not connected");return this.db.collection(o)}async find(o){let{collection:e,where:n={},sort:s,limit:t=10,page:i=1,tenantId:r,select:a,draft:d$1}=o,l=this.getCollectionConfig(e),f=this.getMongoCollection(e),g={...n};this.tenantContext&&l.tenantScoped&&(g=c({where:g},e,this.tenantContext,b$1).where||{});let u=this.buildFilter(g,l.tenantScoped?r:void 0),c$1=l.fields.find(p=>p.name==="status"),h=c$1?.type==="select"&&Array.isArray(c$1.options)&&c$1.options.some(p=>p.value==="published");!d$1&&h&&(u.status="published");let y=this.parseSort(s),O={[y.field]:y.direction==="asc"?1:-1},$=(i-1)*t,[x,M]=await Promise.all([f.find(u).sort(O).skip($).limit(t).project(this.buildProjection(a)).toArray(),f.countDocuments(u)]),C=x.map(p=>this.processResult(p,l));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(C=C.filter(p=>d(p,e,this.tenantContext,b$1))),d$1&&(C=await Promise.all(C.map(async p=>{let m=await this.getMongoCollection(`${e}_versions`).findOne({document_id:p.id},{sort:{createdAt:-1}});if(m){let P=typeof m.data=="string"?JSON.parse(m.data):m.data&&typeof m.data=="object"?m.data:{};return {...p,...P,status:p.status,_hasUnpublishedChanges:m.status==="draft"}}return p}))),{docs:C,...this.calculatePagination(i,t,M)}}async findByID(o){let{collection:e,id:n,tenantId:s,draft:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(e);if(this.tenantContext&&i.tenantScoped){let u={_id:n,tenantId:this.tenantContext.tenantId};if(!d(u,e,this.tenantContext,b$1))return null}let a={_id:n};s&&i.tenantScoped&&(a.tenantId=s);let d$1=i.fields.find(u=>u.name==="status"),l=d$1?.type==="select"&&Array.isArray(d$1.options)&&d$1.options.some(u=>u.value==="published");!t&&l&&(a.status="published");let f=await r.findOne(a);if(!f)return null;let g=this.processResult(f,i);if(t){let c=await this.getMongoCollection(`${e}_versions`).findOne({document_id:g.id},{sort:{createdAt:-1}});if(c){let h=typeof c.data=="string"?JSON.parse(c.data):c.data&&typeof c.data=="object"?c.data:{};g={...g,...h,status:g.status,_hasUnpublishedChanges:c.status==="draft"};}}return g}async create(o){let{collection:e,data:n,tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(e),r=this.prepareData(n,t),a=r.id||this.generateId();delete r.id;let d={...r,_id:a};return s&&t.tenantScoped&&(d.tenantId=s),await i.insertOne(d),this.processResult(d,t)}async update(o){let{collection:e,id:n,data:s,tenantId:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(e),a={_id:n};t&&i.tenantScoped&&(a.tenantId=t);let d=this.prepareData(s,i),l=await r.findOneAndUpdate(a,{$set:d},{returnDocument:"after"});if(!l)throw new Error(`Document not found: ${e}/${n}`);return this.processResult(l,i)}async delete(o){let{collection:e,id:n,tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(e),r={_id:n};s&&t.tenantScoped&&(r.tenantId=s);let a=await i.findOneAndDelete(r);if(!a)throw new Error(`Document not found: ${e}/${n}`);return this.processResult(a,t)}async count(o){let{collection:e,where:n={},tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(e),r=this.buildFilter(n,t.tenantScoped?s:void 0);return i.countDocuments(r)}async findOne(o){let{collection:e,where:n={},tenantId:s,draft:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(e),a=this.buildFilter(n,i.tenantScoped?s:void 0),d=i.fields.find(u=>u.name==="status"),l=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(u=>u.value==="published");!t&&l&&(a.status="published");let f=await r.findOne(a);if(!f)return null;let g=this.processResult(f,i);if(t){let c=await this.getMongoCollection(`${e}_versions`).findOne({document_id:g.id},{sort:{createdAt:-1}});if(c){let h=typeof c.data=="string"?JSON.parse(c.data):c.data&&typeof c.data=="object"?c.data:{};g={...g,...h,status:g.status};}}return g}async findVersions(o){let{collection:e,documentId:n,sort:s,limit:t=10,page:i=1,tenantId:r}=o,a=this.getCollectionConfig(e),d=this.getMongoCollection(`${e}_versions`),l={document_id:n,autosave:{$ne:true}};r&&a.tenantScoped&&(l.tenant_id=r);let f=(i-1)*t,g=this.parseSort(s),u={[g.field]:g.direction==="asc"?1:-1},[c,h]=await Promise.all([d.find(l).sort(u).skip(f).limit(t).toArray(),d.countDocuments(l)]);return {docs:c.map(y=>this.processResult(y,{})),...this.calculatePagination(i,t,h)}}async findVersionByID(o){let{collection:e,versionId:n,tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(`${e}_versions`),r={_id:n};s&&t.tenantScoped&&(r.tenant_id=s);let a=await i.findOne(r);return a?this.processResult(a,{}):null}async createVersion(o){let{collection:e,documentId:n,data:s,status:t,createdBy:i,changeDescription:r,tenantId:a,autosave:d}=o,l=this.getCollectionConfig(e),f=this.getMongoCollection(`${e}_versions`);if(d){let c={document_id:n,collection_slug:e,autosave:true};a&&l.tenantScoped&&(c.tenant_id=a);let h=await f.findOne(c);if(h){let y=new Date().toISOString();return await f.updateOne({_id:h._id},{$set:{data:s,status:t,updatedAt:y}}),this.processResult({...h,data:s,status:t,updatedAt:y},{})}}let g=new Date().toISOString(),u={_id:this.generateId(),document_id:n,collection_slug:e,data:s,status:t,autosave:d===true,created_by:i,change_description:r,createdAt:g,updatedAt:g};if(a&&l.tenantScoped&&(u.tenant_id=a),await f.insertOne(u),!d){let c=this.getCollectionConfig(e);c.versions?.maxPerDoc&&await this.deleteVersions({collection:e,documentId:n,keepLatest:c.versions.maxPerDoc,tenantId:a});}return this.processResult(u,{})}async updateLatestVersion(o){return this.createVersion({...o,autosave:true})}async deleteVersions(o){let{collection:e,documentId:n,keepLatest:s,tenantId:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(`${e}_versions`);if(s){let a={document_id:n,autosave:{$ne:true}};t&&i.tenantScoped&&(a.tenant_id=t);let l=(await r.find(a).sort({createdAt:-1}).limit(s).project({_id:1}).toArray()).map(f=>f._id);l.length>0&&await r.deleteMany({document_id:n,autosave:{$ne:true},_id:{$nin:l},...t&&i.tenantScoped?{tenant_id:t}:{}});}else {let a={document_id:n};t&&i.tenantScoped&&(a.tenant_id=t),await r.deleteMany(a);}}async migrate(){for(let o of this.collections.values()){let e=this.getMongoCollection(o.slug);await e.createIndex({_id:1}),o.tenantScoped&&await e.createIndex({tenantId:1}),o.timestamps&&await e.createIndex({createdAt:-1});for(let n of o.fields)n.unique&&n.name&&await e.createIndex({[n.name]:1},{unique:true}),n.indexed&&n.name&&await e.createIndex({[n.name]:1});}}getCollectionConfig(o){if(o.startsWith("_globals_")){let n=o.replace("_globals_",""),s=this.globals.get(n);if(!s)throw new Error(`Global "${n}" not found`);return s}let e=this.collections.get(o);if(!e)throw new Error(`Collection "${o}" not found`);return e}buildFilter(o={},e){let n={};e&&(n.tenantId=e);for(let[s,t]of Object.entries(o))if(s==="AND"&&Array.isArray(t)){let i=t.map(r=>this.buildFilter(r));Object.assign(n,...i);}else if(s==="OR"&&Array.isArray(t))n.$or=t.map(i=>this.buildFilter(i));else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let i={};if(t.equals!==void 0){n[s==="id"?"_id":s]=t.equals;continue}t.not_equals!==void 0&&(i.$ne=t.not_equals),t.in!==void 0&&(i.$in=t.in),t.not_in!==void 0&&(i.$nin=t.not_in),t.greater_than!==void 0&&(i.$gt=t.greater_than),t.greater_than_equal!==void 0&&(i.$gte=t.greater_than_equal),t.less_than!==void 0&&(i.$lt=t.less_than),t.less_than_equal!==void 0&&(i.$lte=t.less_than_equal),t.like!==void 0&&(i.$regex=new RegExp(t.like.replace(/%/g,".*"),"i")),t.not_like!==void 0&&(i.$not=new RegExp(t.not_like.replace(/%/g,".*"),"i")),t.contains!==void 0&&(i.$regex=new RegExp(`.*${t.contains}.*`,"i")),t.exists!==void 0&&(i.$exists=t.exists),Object.keys(i).length>0&&(n[s==="id"?"_id":s]=i);}else n[s==="id"?"_id":s]=t;return n}buildProjection(o){if(!o||o.length===0)return;let e={_id:1};for(let n of o)e[n]=1;return e}processResult(o,e){if(!o)return null;let n={...o};for(let s of Object.keys(n))/^\d+$/.test(s)&&delete n[s];return o._id&&(n.id=o._id,delete n._id),delete n.__v,n.createdAt&&(n.createdAt=new Date(n.createdAt).toISOString()),n.updatedAt&&(n.updatedAt=new Date(n.updatedAt).toISOString()),a$2(n)}generateId(){let o=Date.now().toString(16).padStart(12,"0"),e=randomBytes(6).toString("hex");return o+e}};function k(v){return new b(v)}
3
+ export{b as a,k as b};
@@ -0,0 +1,21 @@
1
+ import {g as g$1}from'./chunk-Y2YAKDEQ.js';import r from'path';import m from'fs';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
+ g$1();var l=o=>{let s=r.join(process.cwd(),"node_modules","@kyro-cms","core"),e=r.resolve(s,"src",`${o}.ts`);return m.existsSync(e)?e:r.resolve(s,"dist",`${o}.js`)},g=l("api-handler"),A=l("api-handler-graphql"),P=l("api-handler-trpc"),S=["@kyro-cms/core","@kyro-cms/admin","@kyro-cms/astro","@kyro-cms/ai"],x=["@kyro-cms/connect"],R=[...S,...x],_=["better-sqlite3","pg","mongodb","ioredis","sharp","ssh2","cpu-features","ssh2-sftp-client","nodemailer","jsonwebtoken","@mapbox/node-pre-gyp","mock-aws-s3","aws-sdk","nock","cloudflare:workers"],N=["crypto","node:crypto","module","node:module","fs","node:fs","fs/promises","node:fs/promises","path","node:path","util","node:util","stream","node:stream","events","node:events","url","node:url","http","node:http","https","node:https","os","node:os","child_process","node:child_process","assert","node:assert","zlib","node:zlib","buffer","node:buffer"],h=[...S,..._],O=[...R,...N,..._];function k(o={}){let{configPath:s="./kyro.config.ts",apiPath:e="/api",adminPath:a="/admin",admin:v=true,enableGraphQL:c=false,enableTRPC:p=false,enableWebSocket:u=false}=o;return {name:"@kyro-cms/core",hooks:{"astro:config:setup":async({config:y,updateConfig:E,injectRoute:i,logger:n})=>{if(n.info(`Setting up Kyro CMS (API: ${e}, Admin: ${a})`),e===a)throw new Error(`Kyro CMS: apiPath and adminPath cannot be the same ("${e}")`);let d=r.resolve(y.root.pathname,s),b=d;m.existsSync(d)||n.warn(`Kyro config file not found at ${s}. The API will fail to boot if collections are needed.`),E({security:{checkOrigin:false},vite:{ssr:{external:O},build:{rollupOptions:{external:h}},optimizeDeps:{exclude:h},server:{watch:{ignored:["**/*.db","**/*.db-*","**/data/**","**/public/uploads/**","**/.kyro/**"]}},plugins:[{name:"use-sync-external-store-shim-fix",enforce:"pre",resolveId(t){if(t==="use-sync-external-store/shim"||t==="use-sync-external-store/shim/index.js")return "\0virtual:use-sync-external-store-shim";if(t==="use-sync-external-store/shim/with-selector"||t==="use-sync-external-store/shim/with-selector.js")return "\0virtual:use-sync-external-store-shim-with-selector"},load(t){if(t==="\0virtual:use-sync-external-store-shim")return 'export { useSyncExternalStore } from "react";';if(t==="\0virtual:use-sync-external-store-shim-with-selector")return `
3
+ import { useSyncExternalStore, useMemo } from "react";
4
+ export function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
5
+ const memoizedSelector = useMemo(() => {
6
+ let last, lastSnap, hasMemo = false;
7
+ return (snap) => {
8
+ if (!hasMemo || !Object.is(lastSnap, snap)) {
9
+ const next = selector(snap);
10
+ if (!hasMemo || !(isEqual ? isEqual(last, next) : Object.is(last, next))) {
11
+ last = next; lastSnap = snap; hasMemo = true;
12
+ }
13
+ }
14
+ return last;
15
+ };
16
+ }, [selector, isEqual]);
17
+ const getSelection = () => memoizedSelector(getSnapshot());
18
+ const getServerSelection = getServerSnapshot != null ? () => memoizedSelector(getServerSnapshot()) : undefined;
19
+ return useSyncExternalStore(subscribe, getSelection, getServerSelection);
20
+ }
21
+ `}}],resolve:{alias:{"kyro:config":b}},define:{__KYRO_API_PATH__:JSON.stringify(e),__KYRO_ADMIN_PATH__:JSON.stringify(a),__KYRO_ENABLE_GRAPHQL__:JSON.stringify(c),__KYRO_ENABLE_TRPC__:JSON.stringify(p),__KYRO_ENABLE_WS__:JSON.stringify(u)}}}),i({pattern:`${e}/[...path]`,entrypoint:g}),c&&(i({pattern:`${e}/graphql`,entrypoint:A}),n.info(`GraphQL endpoint enabled at ${e}/graphql`)),p&&(i({pattern:`${e}/trpc/[...path]`,entrypoint:P}),n.info(`tRPC endpoint enabled at ${e}/trpc`)),u&&n.info("WebSocket support enabled (auto-starts at first request)");}}}}export{k as a};
@@ -0,0 +1,19 @@
1
+ 'use strict';var chunkVQ53TFYA_cjs=require('./chunk-VQ53TFYA.cjs'),chunkZOVH6QT5_cjs=require('./chunk-ZOVH6QT5.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),module$1=require('module'),crypto=require('crypto');chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();var R;function x(){return R||(R=module$1.createRequire("file:///")("node:sqlite").DatabaseSync,R)}function N(T){let e=[];for(let a of T)if(a.type==="tabs"&&"tabs"in a)for(let s of a.tabs)e.push(...N(s.fields));else a.type==="row"&&"fields"in a?e.push(...N(a.fields)):a.type==="collapsible"&&"fields"in a?e.push(...N(a.fields)):e.push(a);return e}function G(T,e){let a=e,s=T[a.name];if(a.type==="json"||a.type==="richtext"||a.type==="array"||a.type==="group"||a.type==="blocks"||a.type==="list"||a.type==="relationship-block")try{s=s?JSON.parse(s):null;}catch{s=null;}if(a.type==="checkbox"&&(s=!!s),a.type==="date"&&s)try{let i=new Date(s);isNaN(i.getTime())?s=null:s=i.toISOString();}catch{s=null;}if((a.type==="upload"||a.type==="image")&&s)try{let i=JSON.parse(s);Array.isArray(i)?s=i.map(o=>typeof o=="object"&&o!==null?o:{id:o}):s=typeof i=="object"?i:{id:i};}catch{s={id:s};}if(a.type==="relationship"&&s)try{let i=JSON.parse(s);Array.isArray(i),s=i;}catch{s={relationTo:Array.isArray(a.relationTo)?a.relationTo[0]:a.relationTo,value:s};}if(a.type==="list"&&s)try{let i=JSON.parse(s);s=Array.isArray(i)?i:[];}catch{s=[];}if(a.type==="relationship-block"&&s)try{let i=JSON.parse(s);s=Array.isArray(i)?i:[];}catch{s=[];}return s}function P(T,e){return Array.isArray(T)?T.map(a=>{if(!a||typeof a!="object")return a;let s=a.data?{...a.data}:void 0;if(!s)return a;let i=e.find(o=>o.slug===a.type||o.slug===a.slug);if(!i||!Array.isArray(i.fields))return a;for(let o of i.fields){if(o.name&&(o.type==="upload"||o.type==="image")&&s[o.name]){let t=s[o.name];Array.isArray(t)?s[o.name]=t.map(n=>typeof n=="string"?{id:n}:n):typeof t=="string"&&(s[o.name]={id:t});}if(o.type==="blocks"&&o.name&&s[o.name]){let t=o.blocks||[];s[o.name]=P(s[o.name],t);}}return {...a,data:s}}):T}function O(T,e){try{return T.prepare(`PRAGMA table_info(${e})`).all().map(s=>s.name)}catch{return []}}var L=class extends chunkVQ53TFYA_cjs.a{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(e){super(),this.path=e.path,e.db?this.db=e.db:this.db=null;}async connect(){if(!this.db)this.db=new(x())(this.path||":memory:");else try{this.db.exec("SELECT 1");}catch{this.db=new(x())(this.path||":memory:");}if(this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let e=this.db.prepare.bind(this.db),a=s=>{let i=e(s),o=t=>typeof t=="boolean"?t?1:0:t===void 0?null:t;return new Proxy(i,{get(t,n,r){if(n==="all")return (...c)=>t.all(...c.map(o));if(n==="get")return (...c)=>t.get(...c.map(o));if(n==="run")return (...c)=>t.run(...c.map(o));let l=Reflect.get(t,n,r);return typeof l=="function"?l.bind(t):l}})};a.__wrapped=true,this.db.prepare=a;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){if(this.db){try{this.db.close();}catch{}this.db=null;}this.connected=false;}ensureTable(e,a){let s=a||this.getTableNameFor(e.slug),i=["id TEXT PRIMARY KEY"];for(let n of N(e.fields)){if(!n.name||n.name==="id")continue;let r=this.fieldToSQL(n);r&&i.push(r);}let o=N(e.fields);o.some(n=>n.name==="createdAt")||i.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),o.some(n=>n.name==="updatedAt")||i.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),o.some(n=>n.name==="status")||i.push("status TEXT DEFAULT 'draft'"),o.some(n=>n.name==="hasDraft")||i.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&i.push("tenant_id TEXT NOT NULL");let t=O(this.db,s);if(t.length===0){let n=`CREATE TABLE IF NOT EXISTS ${s} (${i.join(", ")})`;this.db.exec(n),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_status ON ${s}(status)`);for(let r of N(e.fields))r.name&&r.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_${r.name} ON ${s}(${this.col(r.name)})`),r.name&&r.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${s}_${r.name}_unique ON ${s}(${this.col(r.name)})`);}else {let n=new Set(t);for(let r of i){let l=r.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!n.has(l)&&l!=="id")try{l==="status"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(l)} TEXT DEFAULT 'published'`):l==="hasDraft"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(l)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(l)} TEXT`);}catch{}}}this.migrations.set(s,true);}ensureVersionsTable(){this.db.exec(`
2
+ CREATE TABLE IF NOT EXISTS ${this.versionsTableName} (
3
+ id TEXT PRIMARY KEY,
4
+ collection_slug TEXT NOT NULL,
5
+ document_id TEXT NOT NULL,
6
+ tenant_id TEXT,
7
+ version INTEGER NOT NULL,
8
+ status TEXT NOT NULL DEFAULT 'draft',
9
+ autosave INTEGER NOT NULL DEFAULT 0,
10
+ data TEXT NOT NULL,
11
+ created_by TEXT,
12
+ change_description TEXT,
13
+ published_at TEXT,
14
+ created_at TEXT DEFAULT (datetime('now')),
15
+ updated_at TEXT DEFAULT (datetime('now'))
16
+ )
17
+ `);try{this.db.exec(`ALTER TABLE ${this.versionsTableName} ADD COLUMN autosave INTEGER NOT NULL DEFAULT 0`);}catch{}this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_doc ON ${this.versionsTableName}(collection_slug, document_id)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_status ON ${this.versionsTableName}(status)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_autosave ON ${this.versionsTableName}(autosave)`);}resolveCol(e,a){let s=a.replace(/^-/,""),i=O(this.db,e);if(!i.includes(s)){if(s==="created_at"&&i.includes("createdAt"))return '"createdAt"';if(s==="createdAt"&&i.includes("created_at"))return '"created_at"';if(s==="updated_at"&&i.includes("updatedAt"))return '"updatedAt"';if(s==="updatedAt"&&i.includes("updated_at"))return '"updated_at"'}return this.col(s)}col(e){return `"${e}"`}fieldToSQL(e){switch(e.type){case "text":case "email":case "password":case "textarea":case "color":case "icon":case "code":case "markdown":case "url":return this.col(e.name)+" TEXT";case "number":return this.col(e.name)+" REAL";case "checkbox":return this.col(e.name)+" INTEGER DEFAULT 0";case "date":return this.col(e.name)+" TEXT";case "select":case "radio":return this.col(e.name)+" TEXT";case "relationship":case "upload":return this.col(e.name)+" TEXT";case "json":case "richtext":case "array":case "group":case "blocks":return this.col(e.name)+" TEXT";default:return null}}parseGlobalsSlug(e){if(e.startsWith("_globals_")){let a=e.replace("_globals_","");return {isGlobal:true,globalSlug:a,tableName:`global_${a.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(e)}}async find(e){let{collection:a,where:s={},sort:i,limit:o=10,page:t=1,tenantId:n,draft:r=false}=e,l=this.parseGlobalsSlug(a),c=l.isGlobal?this.globals.get(l.globalSlug):this.getCollection(a);this.ensureTable(c,l.tableName);let d=l.tableName,b=`SELECT * FROM ${d}`,u=[],f=[],p={...s};this.tenantContext&&c.tenantScoped&&(p=chunkVQ53TFYA_cjs.c({where:p},a,this.tenantContext,chunkVQ53TFYA_cjs.b).where||{});let E=c.fields.find(h=>h.name==="status"),m=E?.type==="select"&&Array.isArray(E.options)&&E.options.some(h=>h.value==="published");!r&&m&&(f.push("status = ?"),u.push("published")),n&&c.tenantScoped&&(f.push("tenant_id = ?"),u.push(n));for(let[h,y]of Object.entries(p)){if(h==="AND"||h==="OR")continue;let S=this.resolveCol(d,h);typeof y=="object"&&y!==null?(y.equals!==void 0&&(f.push(`${S} = ?`),u.push(y.equals)),y.in!==void 0&&(f.push(`${S} IN (${y.in.map(()=>"?").join(", ")})`),u.push(...y.in)),y.not_equals!==void 0&&(f.push(`${S} != ?`),u.push(y.not_equals))):(f.push(`${S} = ?`),u.push(y));}f.length>0&&(b+=` WHERE ${f.join(" AND ")}`);let g=i||"-createdAt",U=this.resolveCol(d,g),w=g.startsWith("-")?"DESC":"ASC";b+=` ORDER BY ${U} ${w}`;let M=b.replace("SELECT *","SELECT COUNT(*) as count"),D=this.db.prepare(M).get(...u)?.count||0;b+=" LIMIT ? OFFSET ?",u.push(o,(t-1)*o);let A=this.db.prepare(b).all(...u).map(h=>this.rowToDoc(h,c));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(A=A.filter(h=>chunkVQ53TFYA_cjs.d(h,a,this.tenantContext,chunkVQ53TFYA_cjs.b))),r&&(A=await Promise.all(A.map(async h=>{let y=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(a,h.id);if(y){let S=y.data?JSON.parse(y.data):{};return chunkZOVH6QT5_cjs.a({...h,...S,status:h.status,_hasUnpublishedChanges:y.status==="draft"})}return h}))),A=A.map(h=>chunkZOVH6QT5_cjs.a(h)),{docs:A,totalDocs:D,limit:o,totalPages:Math.ceil(D/o),page:t,pagingCounter:(t-1)*o+1,hasPrevPage:t>1,hasNextPage:t<Math.ceil(D/o),prevPage:t>1?t-1:null,nextPage:t<Math.ceil(D/o)?t+1:null}}async findByID(e){let{collection:a,id:s,tenantId:i,draft:o=false}=e,t=this.parseGlobalsSlug(a),n=t.isGlobal?this.globals.get(t.globalSlug):this.getCollection(a);this.ensureTable(n,t.tableName);let l=`SELECT * FROM ${t.tableName} WHERE id = ?`,c=[s];if(this.tenantContext&&n.tenantScoped){let p={id:s,tenant_id:this.tenantContext.tenantId};if(!chunkVQ53TFYA_cjs.d(p,a,this.tenantContext,chunkVQ53TFYA_cjs.b))return null}let d=n.fields.find(p=>p.name==="status"),b=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(p=>p.value==="published");!o&&b&&(l+=" AND status = ?",c.push("published")),i&&n.tenantScoped&&(l+=" AND tenant_id = ?",c.push(i));let u=this.db.prepare(l).get(...c);if(!u)return null;let f=this.rowToDoc(u,n);if(o){let p=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(a,f.id);if(p){let E=p.data?JSON.parse(p.data):{};f={...f,...E,status:f.status,_hasUnpublishedChanges:p.status==="draft"};}}return chunkZOVH6QT5_cjs.a(f)}async create(e){let{collection:a,data:s,tenantId:i}=e,o=this.parseGlobalsSlug(a),t=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(a);this.ensureTable(t,o.tableName);let n=o.tableName,r=o.isGlobal?o.globalSlug:s.id||this.generateId(),l=this.prepareData(s,t);l.id=r;let c=new Date().toISOString();l.created_at=c,l.updated_at=c,i&&t.tenantScoped&&(l.tenant_id=i);let d=Object.keys(l),b=O(this.db,n),u={};for(let g of d)b.includes(g)&&(u[g]=l[g]);let f=Object.keys(u),p=f.map(g=>this.col(g)),E=f.map(()=>"?").join(", "),m=Object.values(u).map(g=>g!==null&&typeof g=="object"?JSON.stringify(g):g);return this.db.prepare(`INSERT OR REPLACE INTO ${n} (${p.join(", ")}) VALUES (${E})`).run(...m),this.ensureVersionsTable(),this.findByID({collection:a,id:r,tenantId:i,draft:true})}async update(e){let{collection:a,id:s,data:i,tenantId:o}=e,t=this.parseGlobalsSlug(a),n=t.isGlobal?this.globals.get(t.globalSlug):this.getCollection(a);this.ensureTable(n,t.tableName);let r=t.tableName,l=this.prepareData(i,n);l.updated_at=new Date().toISOString();let c=O(this.db,r),d={};for(let m of Object.keys(l))c.includes(m)&&(d[m]=l[m]);let u=Object.keys(d).map(m=>`${this.col(m)} = ?`).join(", "),f=Object.values(d).map(m=>m!==null&&typeof m=="object"?JSON.stringify(m):m),p=`UPDATE ${r} SET ${u} WHERE id = ?`,E=[...f,s];return o&&n.tenantScoped&&(p+=" AND tenant_id = ?",E.push(o)),this.db.prepare(p).run(...E),this.ensureVersionsTable(),this.findByID({collection:a,id:s,tenantId:o,draft:true})}async delete(e){let{collection:a,id:s,tenantId:i}=e,o=this.parseGlobalsSlug(a),t=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(a);this.ensureTable(t,o.tableName),this.ensureVersionsTable();let n=await this.findByID({collection:a,id:s,tenantId:i,draft:true});if(!n)throw new Error(`Document not found: ${a}/${s}`);let l=`DELETE FROM ${o.tableName} WHERE id = ?`,c=[s];return i&&t.tenantScoped&&(l+=" AND tenant_id = ?",c.push(i)),this.db.prepare(l).run(...c),n}async count(e){let{collection:a,tenantId:s}=e,i=this.parseGlobalsSlug(a),o=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(a);this.ensureTable(o,i.tableName);let n=`SELECT COUNT(*) as count FROM ${i.tableName}`,r=[];return s&&o.tenantScoped&&(n+=" WHERE tenant_id = ?",r.push(s)),this.db.prepare(n).get(...r)?.count||0}async findOne(e){let a=this.parseGlobalsSlug(e.collection);if(a.isGlobal){let i=this.globals.get(a.globalSlug);if(!i)throw new Error(`Global "${a.globalSlug}" not found in adapter`);this.ensureTable(i,a.tableName);let o=`SELECT * FROM ${a.tableName}`,t=[],n=[],r=i.fields.find(d=>d.name==="status"),l=r?.type==="select"&&Array.isArray(r.options)&&r.options.some(d=>d.value==="published");!e.draft&&i.versions&&l&&t.push("status = 'published'"),t.length>0&&(o+=` WHERE ${t.join(" AND ")}`),o+=" LIMIT 1";let c=this.db.prepare(o).get(...n);if(c){let d=this.rowToDoc(c,i);if(e.draft){let b=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(e.collection,a.globalSlug);if(b){let u=b.data?JSON.parse(b.data):{};d={...d,...u,status:d.status,_hasUnpublishedChanges:b.status==="draft"};}}return d}return null}return (await this.find({...e,limit:1})).docs[0]||null}async findVersions(e){this.ensureVersionsTable();let{collection:a,documentId:s,tenantId:i,limit:o=20,page:t=1}=e,n=["collection_slug = ?","document_id = ?","autosave = 0"],r=[a,s];i?(n.push("tenant_id = ?"),r.push(i)):n.push("tenant_id IS NULL");let l=`WHERE ${n.join(" AND ")}`,d=this.db.prepare(`SELECT COUNT(*) as count FROM ${this.versionsTableName} ${l}`).get(...r)?.count||0,b=(t-1)*o;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${l} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...r,o,b).map(p=>this.rowToVersion(p)),totalDocs:d,limit:o,totalPages:Math.ceil(d/o),page:t,pagingCounter:(t-1)*o+1,hasPrevPage:t>1,hasNextPage:t<Math.ceil(d/o),prevPage:t>1?t-1:null,nextPage:t<Math.ceil(d/o)?t+1:null}}async findVersionByID(e){this.ensureVersionsTable();let a=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(e.versionId,e.collection);return a?this.rowToVersion(a):null}async createVersion(e){this.ensureVersionsTable();let a=new Date().toISOString();if(e.autosave){let n=`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 1`,r=[e.collection,e.documentId];e.tenantId?(n+=" AND tenant_id = ?",r.push(e.tenantId)):n+=" AND tenant_id IS NULL",n+=" LIMIT 1";let l=this.db.prepare(n).get(...r);if(l){this.db.prepare(`UPDATE ${this.versionsTableName} SET data = ?, status = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(e.data),e.status,a,l.id);let c=await this.findVersionByID({collection:e.collection,versionId:l.id});if(c)return c}}let s=this.generateId(),o=(this.db.prepare(`SELECT version FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 0 ORDER BY version DESC LIMIT 1`).get(e.collection,e.documentId)?.version??0)+1;if(this.db.prepare(`INSERT INTO ${this.versionsTableName} (
18
+ id, collection_slug, document_id, tenant_id, version, status, autosave, data, created_by, change_description, published_at, created_at, updated_at
19
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,e.collection,e.documentId,e.tenantId??null,o,e.status,e.autosave?1:0,JSON.stringify(e.data),e.createdBy??null,e.changeDescription??null,e.status==="published"?a:null,a,a),!e.autosave){let r=this.collections.get(e.collection)?.versions?.maxPerDoc;r&&r>0&&await this.deleteVersions({collection:e.collection,documentId:e.documentId,keepLatest:r,tenantId:e.tenantId});}return await this.findVersionByID({collection:e.collection,versionId:s})}async updateLatestVersion(e){return this.createVersion({...e,autosave:true})}async deleteVersions(e){this.ensureVersionsTable();let{collection:a,documentId:s,keepLatest:i,tenantId:o}=e;if(i&&i>0){let t=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(a,s),n=0,r=[];for(let l of t)l.status==="published"||l.autosave===1||(n++,n>i&&r.push(l.id));for(let l of r)this.db.prepare(`DELETE FROM ${this.versionsTableName} WHERE id = ?`).run(l);}else {let t=`DELETE FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ?`,n=[a,s];o&&(t+=" AND tenant_id = ?",n.push(o)),this.db.prepare(t).run(...n);}}rowToVersion(e){return {id:String(e.id),collection:e.collection_slug,documentId:e.document_id,version:e.version,status:e.status,data:e.data?JSON.parse(e.data):{},createdBy:e.created_by??void 0,changeDescription:e.change_description??void 0,publishedAt:e.published_at??null,createdAt:e.created_at,updatedAt:e.updated_at}}prepareData(e,a){let s={},i=N(a.fields),o=(t,n)=>{let r=t;if(r.type==="json"||r.type==="richtext"||r.type==="array"||r.type==="group"||r.type==="blocks"||r.type==="list"||r.type==="relationship-block")return n!=null?JSON.stringify(n):null;if(r.type==="checkbox")return n?1:0;if(r.type==="number")return n!==null&&n!==""?Number(n):null;if(r.type==="upload"||r.type==="image"){if(n==null)return null;if(Array.isArray(n)){let l=n.map(c=>typeof c=="string"?c:typeof c=="object"?c.id||c._id||c:String(c));return JSON.stringify(l)}return typeof n=="string"?n:typeof n=="object"?JSON.stringify(n):String(n)}else if(t.type==="relationship"){if(n==null)return null;if(Array.isArray(n)){let l=n.map(c=>typeof c=="string"?c:typeof c=="object"?JSON.stringify({relationTo:t.relationTo,value:c.id||c}):String(c));return JSON.stringify(l)}return typeof n=="string"?n:typeof n=="object"?JSON.stringify({relationTo:t.relationTo,value:n.id||n}):String(n)}return n};for(let t of i){if(!t.name||t.name==="id"||a.fields.some(l=>l.type==="tabs"&&l.name&&"tabs"in l&&l.tabs.some(c=>c.fields.some(d=>d.name===t.name))))continue;let r=e[t.name];r!==void 0&&(s[t.name]=o(t,r));}for(let t of a.fields)if(t.type==="tabs"&&"tabs"in t&&t.name){let n=e[t.name];if(n&&typeof n=="object"){for(let r of t.tabs)for(let l of r.fields)if(l.name&&l.name!=="id"){let c=n[l.name];c!==void 0&&(s[l.name]=o(l,c));}}}return s}rowToDoc(e,a){let s={id:e.id};for(let i of N(a.fields)){if(!i.name||i.name==="id")continue;let o=i,t=e[o.name];if(o.type==="json"||o.type==="richtext"||o.type==="array"||o.type==="group"||o.type==="blocks"||o.type==="list"||o.type==="relationship-block")try{t=t?JSON.parse(t):null;}catch{t=null;}if(o.type==="blocks"&&t&&Array.isArray(t)){let n=o.blocks||[];t=P(t,n);}if(i.type==="checkbox"&&(t=!!t),i.type==="date"&&t)try{let n=new Date(t);isNaN(n.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${i.name}":`,t),t=null):t=n.toISOString();}catch{t=null;}if((i.type==="upload"||i.type==="image")&&t)try{let n=JSON.parse(t);Array.isArray(n)?t=n.map(r=>typeof r=="object"&&r!==null?r:{id:r}):t=typeof n=="object"?n:{id:n};}catch{t={id:t};}if(i.type==="relationship"&&t)try{let n=JSON.parse(t);Array.isArray(n),t=n;}catch{t={relationTo:Array.isArray(i.relationTo)?i.relationTo[0]:i.relationTo,value:t};}s[i.name]=t;}for(let i of a.fields)if(!(!i.name||i.name==="id"||i.name==="row"||i.name==="collapsible")&&i.type==="tabs"&&"tabs"in i){let o={};for(let t of i.tabs)for(let n of t.fields)n.name&&n.name!=="id"&&(o[n.name]=G(e,n));s[i.name]=o;}if(a.timestamps){let i=e.createdAt||e.created_at,o=e.updatedAt||e.updated_at;if(i)try{let t=new Date(i);isNaN(t.getTime())||(s.createdAt=t.toISOString());}catch{}if(o)try{let t=new Date(o);isNaN(t.getTime())||(s.updatedAt=t.toISOString());}catch{}}a.tenantScoped&&(s.tenantId=e.tenant_id),s.status=e.status??"published",s.hasDraft=e.hasDraft?!!e.hasDraft:false;for(let i of Object.keys(s))/^\d+$/.test(i)&&delete s[i];return s}generateId(){let e=Date.now().toString(16).padStart(12,"0"),a=crypto.randomBytes(6).toString("hex");return e+a}getMediaById(e){try{let a=this.getTableNameFor("media"),s=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${a} WHERE id = ?`).get(e);if(s)return {id:s.id,url:s.url,thumbnailUrl:s.thumbnail_url||s.url}}catch{}return null}getTableNameFor(e){return e.replace(/-/g,"_")}async migrate(){for(let e of this.collections.values())this.ensureTable(e);}async rollback(){}async transaction(e){return new Promise((a,s)=>{let i=this.db.transaction(async()=>e({db:this.db}));try{let o=i();a(o);}catch(o){s(o);}})}getDatabase(){return this.db}exec(e){this.db.exec(e);}prepare(e){return this.db.prepare(e)}};function B(T){return new L(T||{})}exports.a=L;exports.b=B;
@@ -1 +1 @@
1
- 'use strict';var chunkV65273ZG_cjs=require('./chunk-V65273ZG.cjs'),chunkECFZEY5B_cjs=require('./chunk-ECFZEY5B.cjs'),chunk4MVLIR77_cjs=require('./chunk-4MVLIR77.cjs'),chunkBHR7OAU4_cjs=require('./chunk-BHR7OAU4.cjs'),chunk6KUL2BSA_cjs=require('./chunk-6KUL2BSA.cjs'),chunkXBQ6HV3T_cjs=require('./chunk-XBQ6HV3T.cjs'),chunkWJBQ2NBD_cjs=require('./chunk-WJBQ2NBD.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),w=require('kyro:config');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var w__default=/*#__PURE__*/_interopDefault(w);chunkBUNLC3II_cjs.h();exports.a=null;var l=null;async function b(){if(!exports.a){if(globalThis.__KYRO_INSTANCE__)try{await globalThis.__KYRO_INSTANCE__.shutdown();}catch{}try{let e=w__default.default.default||w__default.default,t=e.adapter,o=t&&!t.dialect&&typeof t.connect=="function";if(globalThis.DB&&(!t||o)){let s=globalThis.DB;e.adapter=new chunk6KUL2BSA_cjs.c({type:"sqlite",client:s}),chunkV65273ZG_cjs.D.info("Hot-swapped to D1 DrizzleAdapter");}exports.a=chunkV65273ZG_cjs.A(e),await exports.a.init();let a=e.adapter,p=a&&a.dialect&&(a.dialect==="postgres"||a.dialect==="sqlite"),c=a&&a.dialect==="mongodb",n;if(p)a.dialect==="postgres"?n=new chunkXBQ6HV3T_cjs.a({db:a.client}):a.dialect==="sqlite"&&(n=new chunk4MVLIR77_cjs.fb({db:a.rawClient||a.client}));else if(o&&!globalThis.DB){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";n=new chunkBHR7OAU4_cjs.a({path:s});}else c&&(n=new chunkWJBQ2NBD_cjs.a({adapter:a}));if(n?.connect)try{await n.connect();}catch(s){chunkV65273ZG_cjs.D.warn("Auth connect warning:",s);}try{await exports.a.loadSettings();}catch(s){chunkV65273ZG_cjs.D.warn("loadSettings warning:",s);}try{await chunkECFZEY5B_cjs.e(n);}catch(s){chunkV65273ZG_cjs.D.warn("autoBootstrap warning:",s);}globalThis.__KYRO_INSTANCE__=exports.a;}catch(e){throw exports.a=null,l=null,chunkV65273ZG_cjs.D.error("Init failed, will retry:",e),e}}}async function E(e){let t=globalThis.DB?globalThis:null;try{let{env:o}=await import('cloudflare:workers');o&&(t=o);}catch{}if(e)try{t=e.locals?.cfContext?.env||e?.env||t;}catch{}if(!t)try{t=process.env;}catch{}t?.DB&&(globalThis.DB=t.DB),t?.STORAGE_BUCKET&&(globalThis.STORAGE_BUCKET=t.STORAGE_BUCKET),l||(l=b()),await l;}var _={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function T(e){return exports.a?exports.a.settings?.access?.apiAccess?.[e]??_[e]??true:_[e]??true}var R=async e=>{if(!exports.a)try{await Promise.race([E(e),new Promise((t,o)=>setTimeout(()=>o(new Error("Initialization timeout")),3e4))]);}catch(t){return console.error("[Kyro API] Warm error:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Service Unavailable",message:"Kyro CMS is still starting up. Please try again in a moment."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":"5"}})}try{let o=new URL(e.request.url).pathname,a=__KYRO_API_PATH__;if(o===`${a}/graphql`&&typeof exports.a.getGraphQL=="function"){if(!T("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let n=await exports.a.getGraphQL().fetch(e.request,e.locals);return new Response(n.body,n)}if(o.startsWith(`${a}/trpc/`)&&typeof exports.a.getTRPC=="function"){if(!T("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let n=await exports.a.getTRPC().fetch(e.request,e.locals);return new Response(n.body,n)}return await(await exports.a.getREST()).fetch(e.request,e.locals)}catch(t){return console.error("[Kyro API Execution Error]:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Internal Server Error",message:t?.message||String(t),stack:t?.stack}),{status:500,headers:{"Content-Type":"application/json"}})}},L=R;exports.b=E;exports.c=R;exports.d=L;
1
+ 'use strict';var chunkT63QLFLZ_cjs=require('./chunk-T63QLFLZ.cjs'),chunkECFZEY5B_cjs=require('./chunk-ECFZEY5B.cjs'),chunkLBYY3W2D_cjs=require('./chunk-LBYY3W2D.cjs'),chunkBHR7OAU4_cjs=require('./chunk-BHR7OAU4.cjs'),chunkTDGSIF5H_cjs=require('./chunk-TDGSIF5H.cjs'),chunkXBQ6HV3T_cjs=require('./chunk-XBQ6HV3T.cjs'),chunk7DUKWHRN_cjs=require('./chunk-7DUKWHRN.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),w=require('kyro:config');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var w__default=/*#__PURE__*/_interopDefault(w);chunkBUNLC3II_cjs.h();exports.a=null;var l=null;async function b(){if(!exports.a){if(globalThis.__KYRO_INSTANCE__)try{await globalThis.__KYRO_INSTANCE__.shutdown();}catch{}try{let e=w__default.default.default||w__default.default,t=e.adapter,o=t&&!t.dialect&&typeof t.connect=="function";if(globalThis.DB&&(!t||o)){let s=globalThis.DB;e.adapter=new chunkTDGSIF5H_cjs.c({type:"sqlite",client:s}),chunkT63QLFLZ_cjs.D.info("Hot-swapped to D1 DrizzleAdapter");}exports.a=chunkT63QLFLZ_cjs.A(e),await exports.a.init();let a=e.adapter,p=a&&a.dialect&&(a.dialect==="postgres"||a.dialect==="sqlite"),c=a&&a.dialect==="mongodb",n;if(p)a.dialect==="postgres"?n=new chunkXBQ6HV3T_cjs.a({db:a.client}):a.dialect==="sqlite"&&(n=new chunkLBYY3W2D_cjs.fb({db:a.rawClient||a.client}));else if(o&&!globalThis.DB){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";n=new chunkBHR7OAU4_cjs.a({path:s});}else c&&(n=new chunk7DUKWHRN_cjs.a({adapter:a}));if(n?.connect)try{await n.connect();}catch(s){chunkT63QLFLZ_cjs.D.warn("Auth connect warning:",s);}try{await exports.a.loadSettings();}catch(s){chunkT63QLFLZ_cjs.D.warn("loadSettings warning:",s);}try{await chunkECFZEY5B_cjs.e(n);}catch(s){chunkT63QLFLZ_cjs.D.warn("autoBootstrap warning:",s);}globalThis.__KYRO_INSTANCE__=exports.a;}catch(e){throw exports.a=null,l=null,chunkT63QLFLZ_cjs.D.error("Init failed, will retry:",e),e}}}async function E(e){let t=globalThis.DB?globalThis:null;try{let{env:o}=await import('cloudflare:workers');o&&(t=o);}catch{}if(e)try{t=e.locals?.cfContext?.env||e?.env||t;}catch{}if(!t)try{t=process.env;}catch{}t?.DB&&(globalThis.DB=t.DB),t?.STORAGE_BUCKET&&(globalThis.STORAGE_BUCKET=t.STORAGE_BUCKET),l||(l=b()),await l;}var _={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function T(e){return exports.a?exports.a.settings?.access?.apiAccess?.[e]??_[e]??true:_[e]??true}var R=async e=>{if(!exports.a)try{await Promise.race([E(e),new Promise((t,o)=>setTimeout(()=>o(new Error("Initialization timeout")),3e4))]);}catch(t){return console.error("[Kyro API] Warm error:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Service Unavailable",message:"Kyro CMS is still starting up. Please try again in a moment."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":"5"}})}try{let o=new URL(e.request.url).pathname,a=__KYRO_API_PATH__;if(o===`${a}/graphql`&&typeof exports.a.getGraphQL=="function"){if(!T("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let n=await exports.a.getGraphQL().fetch(e.request,e.locals);return new Response(n.body,n)}if(o.startsWith(`${a}/trpc/`)&&typeof exports.a.getTRPC=="function"){if(!T("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let n=await exports.a.getTRPC().fetch(e.request,e.locals);return new Response(n.body,n)}return await(await exports.a.getREST()).fetch(e.request,e.locals)}catch(t){return console.error("[Kyro API Execution Error]:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Internal Server Error",message:t?.message||String(t),stack:t?.stack}),{status:500,headers:{"Content-Type":"application/json"}})}},L=R;exports.b=E;exports.c=R;exports.d=L;
@@ -1,4 +1,4 @@
1
- import {a as a$3}from'./chunk-LWM4WABU.js';import {a as a$2}from'./chunk-SQBTIMWF.js';import {a as a$4,i as i$1}from'./chunk-PA4ZZREG.js';import {r as r$1,p as p$1,n as n$1,c as c$2,q as q$1,o as o$1,J as J$1,b as b$3,a as a$5,F as F$2,D as D$1,C as C$2,e as e$3,H as H$2,x as x$1,d as d$4,y as y$2,k as k$1,f as f$4,A as A$1,j as j$1,z as z$2,u as u$1,v as v$1,w as w$1,g as g$5,E as E$1,B as B$1,t as t$1,s as s$1,m as m$1,i as i$2,l as l$1,h as h$1}from'./chunk-ZMG7Z3KF.js';import {wa as wa$1,a as a$1,ua as ua$1,Aa as Aa$1,ra as ra$1,Da as Da$1,Na as Na$1,qa as qa$1,ka as ka$1,za as za$1,i,Ga as Ga$1,Ea as Ea$1,f as f$1,Ma as Ma$1,Qa as Qa$1,Ra,Sa as Sa$1,Oa as Oa$1,Ta as Ta$1,Ua as Ua$1,b as b$1,ya as ya$1,la as la$1,Pa as Pa$1,sa as sa$1,va as va$1,La as La$1,ma as ma$1,Fa as Fa$1,k,Ja as Ja$1,Ia as Ia$1,ha as ha$1,t,s,u,r,Ca as Ca$1,ja as ja$1,d as d$1,j,Ha as Ha$1,Ka as Ka$1,Ba as Ba$1,h,w,pa as pa$1,ga as ga$1,Va as Va$1,oa as oa$1,na as na$1,xa as xa$1,ta as ta$1,m,I,G as G$1,L,D,v,O,Y,C as C$1,x,R,P,fa as fa$1,X,ea as ea$1,c as c$1,Z,K,y as y$1,_,E,H as H$1,W,ba as ba$1,Q as Q$1,U,T,e,N as N$1,S,ia as ia$1,g as g$1,V,M as M$1,$,B,aa as aa$1,da as da$1,A,z as z$1,J,F as F$1,n,q,Wa as Wa$1,o,l,p,ca as ca$1,Xa as Xa$1,Ya as Ya$1,$a as $a$1,ib}from'./chunk-5YQ2HVHD.js';import {o as o$2,f as f$2,g as g$3}from'./chunk-YZEMLLD2.js';import {d as d$2,e as e$2,f as f$3,g as g$4}from'./chunk-RTHJ6SS5.js';import {b as b$2,d as d$3}from'./chunk-5M3FKE2V.js';import {c as c$3}from'./chunk-BU6O3TP7.js';import {g as g$2}from'./chunk-47CXBWMA.js';import {c,g,b,d,a,f,e as e$1}from'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
1
+ import {a as a$3}from'./chunk-LWM4WABU.js';import {a as a$2}from'./chunk-SQBTIMWF.js';import {a as a$4,i as i$1}from'./chunk-PA4ZZREG.js';import {r as r$1,p as p$1,n as n$1,c as c$2,q as q$1,o as o$1,J as J$1,b as b$3,a as a$5,F as F$2,D as D$1,C as C$2,e as e$3,H as H$2,x as x$1,d as d$4,y as y$2,k as k$1,f as f$4,A as A$1,j as j$1,z as z$2,u as u$1,v as v$1,w as w$1,g as g$5,E as E$1,B as B$1,t as t$1,s as s$1,m as m$1,i as i$2,l as l$1,h as h$1}from'./chunk-ZMG7Z3KF.js';import {wa as wa$1,a as a$1,ua as ua$1,Aa as Aa$1,ra as ra$1,Da as Da$1,Na as Na$1,qa as qa$1,ka as ka$1,za as za$1,i,Ga as Ga$1,Ea as Ea$1,f as f$1,Ma as Ma$1,Qa as Qa$1,Ra,Sa as Sa$1,Oa as Oa$1,Ta as Ta$1,Ua as Ua$1,b as b$1,ya as ya$1,la as la$1,Pa as Pa$1,sa as sa$1,va as va$1,La as La$1,ma as ma$1,Fa as Fa$1,k,Ja as Ja$1,Ia as Ia$1,ha as ha$1,t,s,u,r,Ca as Ca$1,ja as ja$1,d as d$1,j,Ha as Ha$1,Ka as Ka$1,Ba as Ba$1,h,w,pa as pa$1,ga as ga$1,Va as Va$1,oa as oa$1,na as na$1,xa as xa$1,ta as ta$1,m,I,G as G$1,L,D,v,O,Y,C as C$1,x,R,P,fa as fa$1,X,ea as ea$1,c as c$1,Z,K,y as y$1,_,E,H as H$1,W,ba as ba$1,Q as Q$1,U,T,e,N as N$1,S,ia as ia$1,g as g$1,V,M as M$1,$,B,aa as aa$1,da as da$1,A,z as z$1,J,F as F$1,n,q,Wa as Wa$1,o,l,p,ca as ca$1,Xa as Xa$1,Ya as Ya$1,$a as $a$1,ib}from'./chunk-5VGYVQPY.js';import {o as o$2,f as f$2,g as g$3}from'./chunk-YZEMLLD2.js';import {d as d$2,e as e$2,f as f$3,g as g$4}from'./chunk-RTHJ6SS5.js';import {b as b$2,d as d$3}from'./chunk-5M3FKE2V.js';import {c as c$3}from'./chunk-KNOFTUQV.js';import {g as g$2}from'./chunk-47CXBWMA.js';import {c,g,b,d,a,f,e as e$1}from'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
2
  var ms=c((hw,Ra)=>{g();function Rp(){return Object.keys(globalThis).some(t=>t.startsWith("__NEXT"))}Ra.exports=function(){return !!(globalThis.Deno||globalThis.Bun||Rp())};});function Aa(t,e){return (e?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(t)}function _s(t,e=false){let r=[],n=0;for(;n<t.length;){let s=t[n],i=F(function(o){if(!e)throw new TypeError(o);r.push({type:"INVALID_CHAR",index:n,value:t[n++]});},"ErrorOrInvalid");if(s==="*"){r.push({type:"ASTERISK",index:n,value:t[n++]});continue}if(s==="+"||s==="?"){r.push({type:"OTHER_MODIFIER",index:n,value:t[n++]});continue}if(s==="\\"){r.push({type:"ESCAPED_CHAR",index:n++,value:t[n++]});continue}if(s==="{"){r.push({type:"OPEN",index:n,value:t[n++]});continue}if(s==="}"){r.push({type:"CLOSE",index:n,value:t[n++]});continue}if(s===":"){let o="",a=n+1;for(;a<t.length;){let c=t.substr(a,1);if(a===n+1&&Lp.test(c)||a!==n+1&&Op.test(c)){o+=t[a++];continue}break}if(!o){i(`Missing parameter name at ${n}`);continue}r.push({type:"NAME",index:n,value:o}),n=a;continue}if(s==="("){let o=1,a="",c=n+1,l=false;if(t[c]==="?"){i(`Pattern cannot start with "?" at ${c}`);continue}for(;c<t.length;){if(!Aa(t[c],false)){i(`Invalid character '${t[c]}' at ${c}.`),l=true;break}if(t[c]==="\\"){a+=t[c++]+t[c++];continue}if(t[c]===")"){if(o--,o===0){c++;break}}else if(t[c]==="("&&(o++,t[c+1]!=="?")){i(`Capturing groups are not allowed at ${c}`),l=true;break}a+=t[c++];}if(l)continue;if(o){i(`Unbalanced pattern at ${n}`);continue}if(!a){i(`Missing pattern at ${n}`);continue}r.push({type:"REGEX",index:n,value:a}),n=c;continue}r.push({type:"CHAR",index:n,value:t[n++]});}return r.push({type:"END",index:n,value:""}),r}function ws(t,e={}){let r=_s(t);e.delimiter??="/#?",e.prefixes??="./";let n=`[^${me(e.delimiter)}]+?`,s=[],i=0,o=0,c=new Set,l=F(P=>{if(o<r.length&&r[o].type===P)return r[o++].value},"tryConsume"),u=F(()=>l("OTHER_MODIFIER")??l("ASTERISK"),"tryConsumeModifier"),h=F(P=>{let k=l(P);if(k!==void 0)return k;let{type:S,index:v}=r[o];throw new TypeError(`Unexpected ${S} at ${v}, expected ${P}`)},"mustConsume"),d=F(()=>{let P="",k;for(;k=l("CHAR")??l("ESCAPED_CHAR");)P+=k;return P},"consumeText"),p=F(P=>P,"DefaultEncodePart"),_=e.encodePart||p,E="",A=F(P=>{E+=P;},"appendToPendingFixedValue"),R=F(()=>{E.length&&(s.push(new wt(3,"","",_(E),"",3)),E="");},"maybeAddPartFromPendingFixedValue"),j=F((P,k,S,v,O)=>{let g=3;switch(O){case "?":g=1;break;case "*":g=0;break;case "+":g=2;break}if(!k&&!S&&g===3){A(P);return}if(R(),!k&&!S){if(!P)return;s.push(new wt(3,"","",_(P),"",g));return}let x;S?S==="*"?x=ys:x=S:x=n;let w=2;x===n?(w=1,x=""):x===ys&&(w=0,x="");let T;if(k?T=k:S&&(T=i++),c.has(T))throw new TypeError(`Duplicate name '${T}'.`);c.add(T),s.push(new wt(w,T,_(P),x,_(v),g));},"addPart");for(;o<r.length;){let P=l("CHAR"),k=l("NAME"),S=l("REGEX");if(!k&&!S&&(S=l("ASTERISK")),k||S){let O=P??"";e.prefixes.indexOf(O)===-1&&(A(O),O=""),R();let g=u();j(O,k,S,"",g);continue}let v=P??l("ESCAPED_CHAR");if(v){A(v);continue}if(l("OPEN")){let O=d(),g=l("NAME"),x=l("REGEX");!g&&!x&&(x=l("ASTERISK"));let w=d();h("CLOSE");let T=u();j(O,g,x,w,T);continue}R(),h("END");}return s}function me(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function gs(t){return t&&t.ignoreCase?"ui":"u"}function La(t,e,r){return Ss(ws(t,r),e,r)}function tt(t){switch(t){case 0:return "*";case 1:return "?";case 2:return "+";case 3:return ""}}function Ss(t,e,r={}){r.delimiter??="/#?",r.prefixes??="./",r.sensitive??=false,r.strict??=false,r.end??=true,r.start??=true,r.endsWith="";let n=r.start?"^":"";for(let a of t){if(a.type===3){a.modifier===3?n+=me(a.value):n+=`(?:${me(a.value)})${tt(a.modifier)}`;continue}e&&e.push(a.name);let c=`[^${me(r.delimiter)}]+?`,l=a.value;if(a.type===1?l=c:a.type===0&&(l=ys),!a.prefix.length&&!a.suffix.length){a.modifier===3||a.modifier===1?n+=`(${l})${tt(a.modifier)}`:n+=`((?:${l})${tt(a.modifier)})`;continue}if(a.modifier===3||a.modifier===1){n+=`(?:${me(a.prefix)}(${l})${me(a.suffix)})`,n+=tt(a.modifier);continue}n+=`(?:${me(a.prefix)}`,n+=`((?:${l})(?:`,n+=me(a.suffix),n+=me(a.prefix),n+=`(?:${l}))*)${me(a.suffix)})`,a.modifier===0&&(n+="?");}let s=`[${me(r.endsWith)}]|$`,i=`[${me(r.delimiter)}]`;if(r.end)return r.strict||(n+=`${i}?`),r.endsWith.length?n+=`(?=${s})`:n+="$",new RegExp(n,gs(r));r.strict||(n+=`(?:${i}(?=${s}))?`);let o=false;if(t.length){let a=t[t.length-1];a.type===3&&a.modifier===3&&(o=r.delimiter.indexOf(a)>-1);}return o||(n+=`(?=${i}|${s})`),new RegExp(n,gs(r))}function Oa(t,e){return t.length?t[0]==="/"?true:!e||t.length<2?false:(t[0]=="\\"||t[0]=="{")&&t[1]=="/":false}function Es(t,e){return t.startsWith(e)?t.substring(e.length,t.length):t}function Fa(t,e){return t.endsWith(e)?t.substr(0,t.length-e.length):t}function Ps(t){return !t||t.length<2?false:t[0]==="["||(t[0]==="\\"||t[0]==="{")&&t[1]==="["}function vs(t){if(!t)return true;for(let e of Ia)if(t.test(e))return true;return false}function Da(t,e){if(t=Es(t,"#"),e||t==="")return t;let r=new URL("https://example.com");return r.hash=t,r.hash?r.hash.substring(1,r.hash.length):""}function ja(t,e){if(t=Es(t,"?"),e||t==="")return t;let r=new URL("https://example.com");return r.search=t,r.search?r.search.substring(1,r.search.length):""}function qa(t,e){return e||t===""?t:Ps(t)?Cs(t):ks(t)}function Ua(t,e){if(e||t==="")return t;let r=new URL("https://example.com");return r.password=t,r.password}function Ma(t,e){if(e||t==="")return t;let r=new URL("https://example.com");return r.username=t,r.username}function Ba(t,e,r){if(r||t==="")return t;if(e&&!Ia.includes(e))return new URL(`${e}:${t}`).pathname;let n=t[0]=="/";return t=new URL(n?t:"/-"+t,"https://example.com").pathname,n||(t=t.substring(2,t.length)),t}function $a(t,e,r){return Ts(e)===t&&(t=""),r||t===""?t:Rs(t)}function Na(t,e){return t=Fa(t,":"),e||t===""?t:Ar(t)}function Ts(t){switch(t){case "ws":case "http":return "80";case "wws":case "https":return "443";case "ftp":return "21";default:return ""}}function Ar(t){if(t==="")return t;if(/^[-+.A-Za-z0-9]*$/.test(t))return t.toLowerCase();throw new TypeError(`Invalid protocol '${t}'.`)}function Ga(t){if(t==="")return t;let e=new URL("https://example.com");return e.username=t,e.username}function Ha(t){if(t==="")return t;let e=new URL("https://example.com");return e.password=t,e.password}function ks(t){if(t==="")return t;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(t))throw new TypeError(`Invalid hostname '${t}'`);let e=new URL("https://example.com");return e.hostname=t,e.hostname}function Cs(t){if(t==="")return t;if(/[^0-9a-fA-F[\]:]/g.test(t))throw new TypeError(`Invalid IPv6 hostname '${t}'`);return t.toLowerCase()}function Rs(t){if(t===""||/^[0-9]*$/.test(t)&&parseInt(t)<=65535)return t;throw new TypeError(`Invalid port '${t}'.`)}function za(t){if(t==="")return t;let e=new URL("https://example.com");return e.pathname=t[0]!=="/"?"/-"+t:t,t[0]!=="/"?e.pathname.substring(2,e.pathname.length):e.pathname}function Va(t){return t===""?t:new URL(`data:${t}`).pathname}function Wa(t){if(t==="")return t;let e=new URL("https://example.com");return e.search=t,e.search.substring(1,e.search.length)}function Ka(t){if(t==="")return t;let e=new URL("https://example.com");return e.hash=t,e.hash.substring(1,e.hash.length)}function xs(t,e){if(typeof t!="string")throw new TypeError("parameter 1 is not of type 'string'.");let r=new URL(t,e);return {protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search!==""?r.search.substring(1,r.search.length):void 0,hash:r.hash!==""?r.hash.substring(1,r.hash.length):void 0}}function Te(t,e){return e?_t(t):t}function xt(t,e,r){let n;if(typeof e.baseURL=="string")try{n=new URL(e.baseURL),e.protocol===void 0&&(t.protocol=Te(n.protocol.substring(0,n.protocol.length-1),r)),!r&&e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.username===void 0&&(t.username=Te(n.username,r)),!r&&e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.username===void 0&&e.password===void 0&&(t.password=Te(n.password,r)),e.protocol===void 0&&e.hostname===void 0&&(t.hostname=Te(n.hostname,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&(t.port=Te(n.port,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&(t.pathname=Te(n.pathname,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&e.search===void 0&&(t.search=Te(n.search.substring(1,n.search.length),r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&e.search===void 0&&e.hash===void 0&&(t.hash=Te(n.hash.substring(1,n.hash.length),r));}catch{throw new TypeError(`invalid baseURL '${e.baseURL}'.`)}if(typeof e.protocol=="string"&&(t.protocol=Na(e.protocol,r)),typeof e.username=="string"&&(t.username=Ma(e.username,r)),typeof e.password=="string"&&(t.password=Ua(e.password,r)),typeof e.hostname=="string"&&(t.hostname=qa(e.hostname,r)),typeof e.port=="string"&&(t.port=$a(e.port,t.protocol,r)),typeof e.pathname=="string"){if(t.pathname=e.pathname,n&&!Oa(t.pathname,r)){let s=n.pathname.lastIndexOf("/");s>=0&&(t.pathname=Te(n.pathname.substring(0,s+1),r)+t.pathname);}t.pathname=Ba(t.pathname,t.protocol,r);}return typeof e.search=="string"&&(t.search=ja(e.search,r)),typeof e.hash=="string"&&(t.hash=Da(e.hash,r)),t}function _t(t){return t.replace(/([+*?:{}()\\])/g,"\\$1")}function Za(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function Ja(t,e){e.delimiter??="/#?",e.prefixes??="./",e.sensitive??=false,e.strict??=false,e.end??=true,e.start??=true,e.endsWith="";let r=".*",n=`[^${Za(e.delimiter)}]+?`,s=/[$_\u200C\u200D\p{ID_Continue}]/u,i="";for(let o=0;o<t.length;++o){let a=t[o];if(a.type===3){if(a.modifier===3){i+=_t(a.value);continue}i+=`{${_t(a.value)}}${tt(a.modifier)}`;continue}let c=a.hasCustomName(),l=!!a.suffix.length||!!a.prefix.length&&(a.prefix.length!==1||!e.prefixes.includes(a.prefix)),u=o>0?t[o-1]:null,h=o<t.length-1?t[o+1]:null;if(!l&&c&&a.type===1&&a.modifier===3&&h&&!h.prefix.length&&!h.suffix.length)if(h.type===3){let d=h.value.length>0?h.value[0]:"";l=s.test(d);}else l=!h.hasCustomName();if(!l&&!a.prefix.length&&u&&u.type===3){let d=u.value[u.value.length-1];l=e.prefixes.includes(d);}l&&(i+="{"),i+=_t(a.prefix),c&&(i+=`:${a.name}`),a.type===2?i+=`(${a.value})`:a.type===1?c||(i+=`(${n})`):a.type===0&&(!c&&(!u||u.type===3||u.modifier!==3||l||a.prefix!=="")?i+="*":i+=`(${r})`),a.type===1&&c&&a.suffix.length&&s.test(a.suffix[0])&&(i+="\\"),i+=_t(a.suffix),l&&(i+="}"),a.modifier!==3&&(i+=tt(a.modifier));}return i}var Ap,F,wt,Lp,Op,ys,He,Fp,Ip,Ia,Qa,bs,Ge,Lr,Ya=b(()=>{g();Ap=Object.defineProperty,F=(t,e)=>Ap(t,"name",{value:e,configurable:true}),wt=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(t,e,r,n,s,i){this.type=t,this.name=e,this.prefix=r,this.value=n,this.suffix=s,this.modifier=i;}hasCustomName(){return this.name!==""&&typeof this.name!="number"}};F(wt,"Part");Lp=/[$_\p{ID_Start}]/u,Op=/[$_\u200C\u200D\p{ID_Continue}]/u,ys=".*";F(Aa,"isASCII");F(_s,"lexer");F(ws,"parse");F(me,"escapeString");F(gs,"flags");F(La,"stringToRegexp");F(tt,"modifierToString");F(Ss,"partsToRegexp");He={delimiter:"",prefixes:"",sensitive:true,strict:true},Fp={delimiter:".",prefixes:"",sensitive:true,strict:true},Ip={delimiter:"/",prefixes:"/",sensitive:true,strict:true};F(Oa,"isAbsolutePathname");F(Es,"maybeStripPrefix");F(Fa,"maybeStripSuffix");F(Ps,"treatAsIPv6Hostname");Ia=["ftp","file","http","https","ws","wss"];F(vs,"isSpecialScheme");F(Da,"canonicalizeHash");F(ja,"canonicalizeSearch");F(qa,"canonicalizeHostname");F(Ua,"canonicalizePassword");F(Ma,"canonicalizeUsername");F(Ba,"canonicalizePathname");F($a,"canonicalizePort");F(Na,"canonicalizeProtocol");F(Ts,"defaultPortForProtocol");F(Ar,"protocolEncodeCallback");F(Ga,"usernameEncodeCallback");F(Ha,"passwordEncodeCallback");F(ks,"hostnameEncodeCallback");F(Cs,"ipv6HostnameEncodeCallback");F(Rs,"portEncodeCallback");F(za,"standardURLPathnameEncodeCallback");F(Va,"pathURLPathnameEncodeCallback");F(Wa,"searchEncodeCallback");F(Ka,"hashEncodeCallback");Qa=class{#o;#r=[];#n={};#t=0;#p=1;#w=0;#s=0;#y=0;#l=0;#i=false;constructor(t){this.#o=t;}get result(){return this.#n}parse(){for(this.#r=_s(this.#o,true);this.#t<this.#r.length;this.#t+=this.#p){if(this.#p=1,this.#r[this.#t].type==="END"){if(this.#s===0){this.#b(),this.#T()?this.#e(9,1):this.#d()?this.#e(8,1):this.#e(7,0);continue}else if(this.#s===2){this.#f(5);continue}this.#e(10,0);break}if(this.#y>0)if(this.#k())this.#y-=1;else continue;if(this.#L()){this.#y+=1;continue}switch(this.#s){case 0:this.#h()&&this.#f(1);break;case 1:if(this.#h()){this.#O();let t=7,e=1;this.#E()?(t=2,e=3):this.#i&&(t=2),this.#e(t,e);}break;case 2:this.#g()?this.#f(3):(this.#v()||this.#d()||this.#T())&&this.#f(5);break;case 3:this.#x()?this.#e(4,1):this.#g()&&this.#e(5,1);break;case 4:this.#g()&&this.#e(5,1);break;case 5:this.#F()?this.#l+=1:this.#_()&&(this.#l-=1),this.#P()&&!this.#l?this.#e(6,1):this.#v()?this.#e(7,0):this.#d()?this.#e(8,1):this.#T()&&this.#e(9,1);break;case 6:this.#v()?this.#e(7,0):this.#d()?this.#e(8,1):this.#T()&&this.#e(9,1);break;case 7:this.#d()?this.#e(8,1):this.#T()&&this.#e(9,1);break;case 8:this.#T()&&this.#e(9,1);break;}}this.#n.hostname!==void 0&&this.#n.port===void 0&&(this.#n.port="");}#e(t,e){switch(this.#s){case 0:break;case 1:this.#n.protocol=this.#S();break;case 2:break;case 3:this.#n.username=this.#S();break;case 4:this.#n.password=this.#S();break;case 5:this.#n.hostname=this.#S();break;case 6:this.#n.port=this.#S();break;case 7:this.#n.pathname=this.#S();break;case 8:this.#n.search=this.#S();break;case 9:this.#n.hash=this.#S();break;}this.#s!==0&&t!==10&&([1,2,3,4].includes(this.#s)&&[6,7,8,9].includes(t)&&(this.#n.hostname??=""),[1,2,3,4,5,6].includes(this.#s)&&[8,9].includes(t)&&(this.#n.pathname??=this.#i?"/":""),[1,2,3,4,5,6,7].includes(this.#s)&&t===9&&(this.#n.search??="")),this.#m(t,e);}#m(t,e){this.#s=t,this.#w=this.#t+e,this.#t+=e,this.#p=0;}#b(){this.#t=this.#w,this.#p=0;}#f(t){this.#b(),this.#s=t;}#u(t){return t<0&&(t=this.#r.length-t),t<this.#r.length?this.#r[t]:this.#r[this.#r.length-1]}#c(t,e){let r=this.#u(t);return r.value===e&&(r.type==="CHAR"||r.type==="ESCAPED_CHAR"||r.type==="INVALID_CHAR")}#h(){return this.#c(this.#t,":")}#E(){return this.#c(this.#t+1,"/")&&this.#c(this.#t+2,"/")}#g(){return this.#c(this.#t,"@")}#x(){return this.#c(this.#t,":")}#P(){return this.#c(this.#t,":")}#v(){return this.#c(this.#t,"/")}#d(){if(this.#c(this.#t,"?"))return true;if(this.#r[this.#t].value!=="?")return false;let t=this.#u(this.#t-1);return t.type!=="NAME"&&t.type!=="REGEX"&&t.type!=="CLOSE"&&t.type!=="ASTERISK"}#T(){return this.#c(this.#t,"#")}#L(){return this.#r[this.#t].type=="OPEN"}#k(){return this.#r[this.#t].type=="CLOSE"}#F(){return this.#c(this.#t,"[")}#_(){return this.#c(this.#t,"]")}#S(){let t=this.#r[this.#t],e=this.#u(this.#w).index;return this.#o.substring(e,t.index)}#O(){let t={};Object.assign(t,He),t.encodePart=Ar;let e=La(this.#S(),void 0,t);this.#i=vs(e);}};F(Qa,"Parser");bs=["protocol","username","password","hostname","port","pathname","search","hash"],Ge="*";F(xs,"extractValues");F(Te,"processBaseURLString");F(xt,"applyInit");F(_t,"escapePatternString");F(Za,"escapeRegexpString");F(Ja,"partsToPattern");Lr=class{#o;#r={};#n={};#t={};#p={};#w=false;constructor(t={},e,r){try{let n;if(typeof e=="string"?n=e:r=e,typeof t=="string"){let a=new Qa(t);if(a.parse(),t=a.result,n===void 0&&typeof t.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");t.baseURL=n;}else {if(!t||typeof t!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(n)throw new TypeError("parameter 1 is not of type 'string'.")}typeof r>"u"&&(r={ignoreCase:!1});let s={ignoreCase:r.ignoreCase===!0},i={pathname:Ge,protocol:Ge,username:Ge,password:Ge,hostname:Ge,port:Ge,search:Ge,hash:Ge};this.#o=xt(i,t,!0),Ts(this.#o.protocol)===this.#o.port&&(this.#o.port="");let o;for(o of bs){if(!(o in this.#o))continue;let a={},c=this.#o[o];switch(this.#n[o]=[],o){case "protocol":Object.assign(a,He),a.encodePart=Ar;break;case "username":Object.assign(a,He),a.encodePart=Ga;break;case "password":Object.assign(a,He),a.encodePart=Ha;break;case "hostname":Object.assign(a,Fp),Ps(c)?a.encodePart=Cs:a.encodePart=ks;break;case "port":Object.assign(a,He),a.encodePart=Rs;break;case "pathname":vs(this.#r.protocol)?(Object.assign(a,Ip,s),a.encodePart=za):(Object.assign(a,He,s),a.encodePart=Va);break;case "search":Object.assign(a,He,s),a.encodePart=Wa;break;case "hash":Object.assign(a,He,s),a.encodePart=Ka;break}try{this.#p[o]=ws(c,a),this.#r[o]=Ss(this.#p[o],this.#n[o],a),this.#t[o]=Ja(this.#p[o],a),this.#w=this.#w||this.#p[o].some(l=>l.type===2);}catch{throw new TypeError(`invalid ${o} pattern '${this.#o[o]}'.`)}}}catch(n){throw new TypeError(`Failed to construct 'URLPattern': ${n.message}`)}}get[Symbol.toStringTag](){return "URLPattern"}test(t={},e){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return false;try{typeof t=="object"?r=xt(r,t,!1):r=xt(r,xs(t,e),!1);}catch{return false}let n;for(n of bs)if(!this.#r[n].exec(r[n]))return false;return true}exec(t={},e){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return;try{typeof t=="object"?r=xt(r,t,!1):r=xt(r,xs(t,e),!1);}catch{return null}let n={};e?n.inputs=[t,e]:n.inputs=[t];let s;for(s of bs){let i=this.#r[s].exec(r[s]);if(!i)return null;let o={};for(let[a,c]of this.#n[s].entries())if(typeof c=="string"||typeof c=="number"){let l=i[a+1];o[c]=l;}n[s]={input:r[s]??"",groups:o};}return n}static compareComponent(t,e,r){let n=F((a,c)=>{for(let l of ["type","modifier","prefix","value","suffix"]){if(a[l]<c[l])return -1;if(a[l]!==c[l])return 1}return 0},"comparePart"),s=new wt(3,"","","","",3),i=new wt(0,"","","","",3),o=F((a,c)=>{let l=0;for(;l<Math.min(a.length,c.length);++l){let u=n(a[l],c[l]);if(u)return u}return a.length===c.length?0:n(a[l]??s,c[l]??s)},"comparePartList");return !e.#t[t]&&!r.#t[t]?0:e.#t[t]&&!r.#t[t]?o(e.#p[t],[i]):!e.#t[t]&&r.#t[t]?o([i],r.#p[t]):o(e.#p[t],r.#p[t])}get protocol(){return this.#t.protocol}get username(){return this.#t.username}get password(){return this.#t.password}get hostname(){return this.#t.hostname}get port(){return this.#t.port}get pathname(){return this.#t.pathname}get search(){return this.#t.search}get hash(){return this.#t.hash}get hasRegExpGroups(){return this.#w}};F(Lr,"URLPattern");});var Xa={};d(Xa,{URLPattern:()=>Lr});var el=b(()=>{g();Ya();globalThis.URLPattern||(globalThis.URLPattern=Lr);});var Ve=c(de=>{g();Object.defineProperty(de,"__esModule",{value:true});de.isPromise=Or;de.isActualPromise=rl;de.handleMaybePromise=ze;de.fakePromise=ke;de.createDeferredPromise=Dp;de.iterateAsync=nl;de.iterateAsyncVoid=nl;de.fakeRejectPromise=rt;de.mapMaybePromise=jp;de.mapAsyncIterator=qp;de.promiseLikeFinally=sl;de.unfakePromise=il;var Fr=Symbol.for("@whatwg-node/promise-helpers/FakePromise");function Or(t){return t?.then!=null}function rl(t){let e=t;return e&&e.then&&e.catch&&e.finally}function ze(t,e,r,n){let s=ke().then(t).then(e,r);return n&&(s=s.finally(n)),il(s)}function ke(t){return t&&rl(t)?t:Or(t)?{then:(e,r)=>ke(t.then(e,r)),catch:e=>ke(t.then(r=>r,e)),finally:e=>ke(e?sl(t,e):t),[Symbol.toStringTag]:"Promise"}:{then(e){if(e)try{return ke(e(t))}catch(r){return rt(r)}return this},catch(){return this},finally(e){if(e)try{return ke(e()).then(()=>t,()=>t)}catch(r){return rt(r)}return this},[Symbol.toStringTag]:"Promise",__fakePromiseValue:t,[Fr]:"resolved"}}function Dp(){if(Promise.withResolvers)return Promise.withResolvers();let t,e;return {promise:new Promise(function(s,i){t=s,e=i;}),get resolve(){return t},get reject(){return e}}}function nl(t,e,r){if(t?.length===0)return;let n=t[Symbol.iterator](),s=0;function i(){let{done:o,value:a}=n.next();if(o)return;let c=false;function l(){c=true;}return ze(function(){return e(a,l,s++)},function(h){if(h&&r?.push(h),!c)return i()})}return i()}function rt(t){return {then(e,r){if(r)try{return ke(r(t))}catch(n){return rt(n)}return this},catch(e){if(e)try{return ke(e(t))}catch(r){return rt(r)}return this},finally(e){if(e)try{e();}catch(r){return rt(r)}return this},__fakeRejectError:t,[Symbol.toStringTag]:"Promise",[Fr]:"rejected"}}function jp(t,e,r){return ze(()=>t,e,r)}function qp(t,e,r,n){Symbol.asyncIterator in t&&(t=t[Symbol.asyncIterator]());let s,i,o;if(n){let l;o=u=>(l||=ze(n,()=>u,()=>u),l);}typeof t.return=="function"&&(s=t.return,i=l=>{let u=()=>{throw l};return s.call(t).then(u,u)});function a(l){return l.done?o?o(l):l:ze(()=>l.value,u=>ze(()=>e(u),tl,i))}let c;if(r){let l,u=r;c=h=>(l||=ze(()=>h,d=>ze(()=>u(d),tl,i)),l);}return {next(){return t.next().then(a,c)},return(){let l=s?s.call(t).then(a,c):ke({value:void 0,done:true});return o?l.then(o):l},throw(l){return typeof t.throw=="function"?t.throw(l).then(a,c):i?i(l):rt(l)},[Symbol.asyncIterator](){return this}}}function tl(t){return {value:t,done:false}}function Up(t){return t?.[Fr]==="resolved"}function Mp(t){return t?.[Fr]==="rejected"}function sl(t,e){return "finally"in t?t.finally(e):t.then(r=>{let n=e();return Or(n)?n.then(()=>r):r},r=>{let n=e();if(Or(n))return n.then(()=>{throw r});throw r})}function il(t){if(Up(t))return t.__fakePromiseValue;if(Mp(t))throw t.__fakeRejectError;return t}});var As=c((Ew,ol)=>{g();var{EventEmitter:Bp}=a("events"),{inherits:$p}=a("util");function nt(t){if(typeof t=="string"&&(t=Buffer.from(t)),!Buffer.isBuffer(t))throw new TypeError("The needle has to be a String or a Buffer.");let e=t.length,r=e-1;if(e===0)throw new Error("The needle cannot be an empty String/Buffer.");if(e>256)throw new Error("The needle cannot have a length bigger than 256.");this.maxMatches=1/0,this.matches=0,this._occ=new Uint8Array(256).fill(e),this._lookbehind_size=0,this._needle=t,this._bufpos=0,this._lookbehind=Buffer.alloc(r);for(var n=0;n<r;++n)this._occ[t[n]]=r-n;}$p(nt,Bp);nt.prototype.reset=function(){this._lookbehind_size=0,this.matches=0,this._bufpos=0;};nt.prototype.push=function(t,e){Buffer.isBuffer(t)||(t=Buffer.from(t,"binary"));let r=t.length;this._bufpos=e||0;let n;for(;n!==r&&this.matches<this.maxMatches;)n=this._sbmh_feed(t);return n};nt.prototype._sbmh_feed=function(t){let e=t.length,r=this._needle,n=r.length,s=n-1,i=r[s],o=-this._lookbehind_size,a;if(o<0){for(;o<0&&o<=e-n;){if(a=t[o+s],a===i&&this._sbmh_memcmp(t,o,s))return this._lookbehind_size=0,++this.matches,this.emit("info",true),this._bufpos=o+n;o+=this._occ[a];}for(;o<0&&!this._sbmh_memcmp(t,o,e-o);)++o;if(o>=0)this.emit("info",false,this._lookbehind,0,this._lookbehind_size),this._lookbehind_size=0;else {let c=this._lookbehind_size+o;return c>0&&this.emit("info",false,this._lookbehind,0,c),this._lookbehind_size-=c,this._lookbehind.copy(this._lookbehind,0,c,this._lookbehind_size),t.copy(this._lookbehind,this._lookbehind_size),this._lookbehind_size+=e,this._bufpos=e,e}}if(o=t.indexOf(r,o+this._bufpos),o!==-1)return ++this.matches,o===0?this.emit("info",true):this.emit("info",true,t,this._bufpos,o),this._bufpos=o+n;for(o=e-s,o<0&&(o=0);o!==e&&(t[o]!==r[0]||Buffer.compare(t.subarray(o+1,e),r.subarray(1,e-o))!==0);)++o;return o!==e&&(t.copy(this._lookbehind,0,o,e),this._lookbehind_size=e-o),o!==0&&this.emit("info",false,t,this._bufpos,o),this._bufpos=e,e};nt.prototype._sbmh_lookup_char=function(t,e){return e<0?this._lookbehind[this._lookbehind_size+e]:t[e]};nt.prototype._sbmh_memcmp=function(t,e,r){for(var n=0;n<r;++n)if(this._sbmh_lookup_char(t,e+n)!==this._needle[n])return false;return true};ol.exports=nt;});var cl=c((vw,ll)=>{g();var Np=a("util").inherits,al=a("stream").Readable;function Ls(t){al.call(this,t);}Np(Ls,al);Ls.prototype._read=function(t){};ll.exports=Ls;});var Ir=c((kw,ul)=>{g();ul.exports=function(e,r,n){if(!e||e[r]===void 0||e[r]===null)return n;if(typeof e[r]!="number"||isNaN(e[r]))throw new TypeError("Limit "+r+" is not a valid number");return e[r]};});var pl=c((Rw,dl)=>{g();var hl=a("events").EventEmitter,Gp=a("util").inherits,fl=Ir(),Hp=As(),zp=Buffer.from(`\r
3
3
  \r
4
4
  `),Vp=/\r\n/g,Wp=/^([^:]+):[ \t]?([\x00-\xFF]+)?$/;function St(t){hl.call(this),t=t||{};let e=this;this.nread=0,this.maxed=false,this.npairs=0,this.maxHeaderPairs=fl(t,"maxHeaderPairs",2e3),this.maxHeaderSize=fl(t,"maxHeaderSize",80*1024),this.buffer="",this.header={},this.finished=false,this.ss=new Hp(zp),this.ss.on("info",function(r,n,s,i){n&&!e.maxed&&(e.nread+i-s>=e.maxHeaderSize?(i=e.maxHeaderSize-e.nread+s,e.nread=e.maxHeaderSize,e.maxed=true):e.nread+=i-s,e.buffer+=n.toString("binary",s,i)),r&&e._finish();});}Gp(St,hl);St.prototype.push=function(t){let e=this.ss.push(t);if(this.finished)return e};St.prototype.reset=function(){this.finished=false,this.buffer="",this.header={},this.ss.reset();};St.prototype._finish=function(){this.buffer&&this._parseHeader(),this.ss.matches=this.ss.maxMatches;let t=this.header;this.header={},this.buffer="",this.finished=true,this.nread=this.npairs=0,this.maxed=false,this.emit("header",t);};St.prototype._parseHeader=function(){if(this.npairs===this.maxHeaderPairs)return;let t=this.buffer.split(Vp),e=t.length,r,n;for(var s=0;s<e;++s){if(t[s].length===0)continue;if((t[s][0]===" "||t[s][0]===" ")&&n){this.header[n][this.header[n].length-1]+=t[s];continue}let i=t[s].indexOf(":");if(i===-1||i===0)return;if(r=Wp.exec(t[s]),n=r[1].toLowerCase(),this.header[n]=this.header[n]||[],this.header[n].push(r[2]||""),++this.npairs===this.maxHeaderPairs)break}};dl.exports=St;});var Fs=c((Lw,bl)=>{g();var Os=a("stream").Writable,Kp=a("util").inherits,Qp=As(),ml=cl(),Zp=pl(),Jp=45,Yp=Buffer.from("-"),Xp=Buffer.from(`\r