@stacksjs/orm 0.74.32 → 0.74.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -92,6 +92,8 @@ export declare const Redirect: ReturnType<typeof lazyModel<typeof import('./mode
92
92
  export declare const Site: ReturnType<typeof lazyModel<typeof import('./models/Site').default>>;
93
93
  export declare const SiteDomain: ReturnType<typeof lazyModel<typeof import('./models/SiteDomain').default>>;
94
94
  export declare const SmsOptOut: ReturnType<typeof lazyModel<typeof import('./models/SmsOptOut').default>>;
95
+ export declare const StorageItem: ReturnType<typeof lazyModel<typeof import('./models/StorageItem').default>>;
96
+ export declare const StorageItemTask: ReturnType<typeof lazyModel<typeof import('./models/StorageItemTask').default>>;
95
97
  export declare const EmailIdempotency: ReturnType<typeof lazyModel<typeof import('./models/EmailIdempotency').default>>;
96
98
  export declare const EmailSuppression: ReturnType<typeof lazyModel<typeof import('./models/EmailSuppression').default>>;
97
99
  export declare const EmailWebhookEvent: ReturnType<typeof lazyModel<typeof import('./models/EmailWebhookEvent').default>>;
@@ -122,6 +124,8 @@ export declare const ProductUnit: ReturnType<typeof lazyModel<typeof import('./m
122
124
  export declare const ProductVariant: ReturnType<typeof lazyModel<typeof import('./models/commerce/ProductVariant').default>>;
123
125
  export declare const QueryLog: ReturnType<typeof lazyModel<typeof import('./models/QueryLog').default>>;
124
126
  export declare const Receipt: ReturnType<typeof lazyModel<typeof import('./models/commerce/Receipt').default>>;
127
+ export declare const Referral: ReturnType<typeof lazyModel<typeof import('./models/Referral').default>>;
128
+ export declare const ReferralCode: ReturnType<typeof lazyModel<typeof import('./models/ReferralCode').default>>;
125
129
  export declare const Release: ReturnType<typeof lazyModel<typeof import('./models/Release').default>>;
126
130
  export declare const Request: ReturnType<typeof lazyModel<typeof import('./models/Request').default>>;
127
131
  export declare const Review: ReturnType<typeof lazyModel<typeof import('./models/commerce/Review').default>>;
package/dist/index.js CHANGED
@@ -19,4 +19,4 @@ export {}
19
19
  `),m=`${Ct(l)}${f}
20
20
  ${vt(l)}`;if(!e.dryRun){let p=S.dirname(o);if(!Q.existsSync(p))Q.mkdirSync(p,{recursive:!0});Q.writeFileSync(o,m,"utf-8"),xr.success(`[generate:db-types] wrote ${c.length} table(s) to ${o}`)}return{outFile:o,tables:c,errors:a,content:m}}function Qr(e,t="app"){let n=[...e].sort((r,o)=>r.table.localeCompare(o.table)).map((r)=>Ot(r.table,r.columns,t==="framework"?1:2)).join(`
21
21
  `);return`${Ct(t)}${n}
22
- ${vt(t)}`}import{isCursorPaginator as Ys,isPaginator as Xs,isSimplePaginator as Zs,toCursorPaginator as eu,toPaginator as tu,toSimplePaginator as nu}from"@stacksjs/pagination";import{configureOrm as Vr}from"@stacksjs/query-builder";function zr(){try{let e=process.env.DB_DATABASE_PATH||"database/stacks.sqlite";if((process.env.DB_CONNECTION||"sqlite")==="sqlite")Vr({database:e})}catch{}}zr();async function Dt(e){for(let t=0;;t++){let n=await import(e);try{return n.default}catch(r){if(t<5&&r instanceof ReferenceError&&/before initialization/.test(r.message)){await new Promise((o)=>setTimeout(o,0));continue}throw r}}}async function te(e,t=[""]){let{path:n}=await import("@stacksjs/path"),r=n.userModelsPath(`${e}.ts`);try{if(await Bun.file(r).exists())return await Dt(r)}catch(o){console.error(`[orm] Failed to import userland model ${e} from ${r} - falling back to framework default. Reason:`,o)}for(let o of t){let a=o?`${o}/`:"",i=n.frameworkPath(`defaults/app/Models/${a}${e}.ts`);try{if(await Bun.file(i).exists())return await Dt(i)}catch(s){console.error(`[orm] Failed to import framework default model ${e} from ${i} - trying next subdir. Reason:`,s)}}return null}var C={},Et=()=>{},xs=new Promise((e)=>{Et=e});function y(e){return new Proxy(function(){},{get(t,n){if(n==="then")return;let r=C[e];if(r==null)return;let o=r[n];return typeof o==="function"?o.bind(r):o},set(t,n,r){let o=C[e];if(o==null)return!1;return o[n]=r,!0},has(t,n){let r=C[e];return r==null?!1:(n in r)},apply(t,n,r){let o=C[e];if(o==null||typeof o!=="function")return;return o.apply(n,r)}})}var Hr=y("User"),Gr=y("Job"),Jr=y("FailedJob"),Yr=[["Team",[""],"auth"],["TeamInvitation",[""],"auth"],["TeamMember",[""],"auth"],["SocialAccount",[""],"auth"],["Subscriber",[""],"auth"],["SubscriberEmail",[""],"auth"],["Subscription",[""],"auth"],["Post",["Content"],"cms"],["Page",["Content"],"cms"],["PageRevision",["Content"],"cms"],["Redirect",["Content"],"cms"],["Menu",["Content"],"cms"],["MenuItem",["Content"],"cms"],["Author",["Content"],"cms"],["Comment",[""],"cms"],["Tag",[""],"cms"],["Site",[""],"auth"],["SiteDomain",[""],"auth"],["MagicLinkToken",[""],"auth"],["SmsOptOut",[""],"auth"],["Form",["Forms"],"forms"],["FormField",["Forms"],"forms"],["FormSubmission",["Forms"],"forms"],["Activity",[""],"dashboard"],["Board",[""],"dashboard"],["BoardColumn",[""],"dashboard"],["Card",[""],"dashboard"],["CardComment",[""],"dashboard"],["Deployment",[""],"dashboard"],["Label",[""],"dashboard"],["Release",[""],"dashboard"],["Notification",[""],"dashboard"],["NotificationDelivery",[""],"dashboard"],["PersonalAccessToken",[""],"dashboard"],["MailPreference",[""],"dashboard"],["Log",[""],"dashboard"],["Request",[""],"dashboard"],["AnalyticsEvent",[""],"dashboard"],["QueryLog",[""],"dashboard"],["Error",[""],"monitoring"],["Websocket",["realtime"],"realtime"],["Campaign",[""],"marketing"],["CampaignSend",[""],"marketing"],["EmailList",[""],"marketing"],["EmailListSubscriber",[""],"marketing"],["EmailIdempotency",[""],"marketing"],["EmailSuppression",[""],"marketing"],["EmailWebhookEvent",[""],"marketing"],["SocialPost",[""],"marketing"],["Automation",[""],"marketing"],["AutomationRun",[""],"marketing"],["CampaignVariant",[""],"marketing"],["CommunicationSuppression",[""],"marketing"],["ConsentEvent",[""],"marketing"],["SenderDomain",[""],"marketing"],["UsageEvent",[""],"marketing"],["PaymentMethod",[""],"commerce"],["PaymentProduct",[""],"commerce"],["PaymentTransaction",[""],"commerce"],["Order",["commerce"],"commerce"],["OrderIdempotency",["commerce"],"commerce"],["OrderItem",["commerce"],"commerce"],["Cart",["commerce"],"commerce"],["CartItem",["commerce"],"commerce"],["Customer",["commerce"],"commerce"],["Product",["commerce"],"commerce"],["ProductVariant",["commerce"],"commerce"],["ProductUnit",["commerce"],"commerce"],["Manufacturer",["commerce"],"commerce"],["Category",["commerce"],"commerce"],["Coupon",["commerce"],"commerce"],["GiftCard",["commerce"],"commerce"],["LicenseKey",["commerce"],"commerce"],["Review",["commerce"],"commerce"],["Receipt",["commerce"],"commerce"],["PrintDevice",["commerce"],"commerce"],["ShippingMethod",["commerce"],"commerce"],["ShippingRate",["commerce"],"commerce"],["ShippingZone",["commerce"],"commerce"],["DeliveryRoute",["commerce"],"commerce"],["DeliveryStop",["commerce"],"commerce"],["DigitalDelivery",["commerce"],"commerce"],["Courier",["commerce"],"commerce"],["CourierPing",["commerce"],"commerce"],["TaxRate",["commerce"],"commerce"],["WaitlistProduct",["commerce"],"commerce"],["WaitlistRestaurant",["commerce"],"commerce"],["Auction",["commerce"],"commerce"],["AuctionItem",["commerce"],"commerce"],["Bid",["commerce"],"commerce"],["Pledge",["commerce"],"commerce"],["LoyaltyPoint",["commerce"],"commerce"],["LoyaltyReward",["commerce"],"commerce"],["Payment",["commerce"],"commerce"],["Transaction",["commerce"],"commerce"]];queueMicrotask(async()=>{try{let{feature:e}=await import("@stacksjs/config"),t=await te("User");if(t)C.User=t;if(e("queue")){let n=await te("Job");if(n)C.Job=n;let r=await te("FailedJob");if(r)C.FailedJob=r}for(let[n,r,o]of Yr){if(!e(o))continue;let a=await te(n,r);if(a)C[n]=a}}catch(e){console.error("[orm] deferred model load failed:",e)}finally{Et()}});var Xr=y("Activity"),Zr=y("AnalyticsEvent"),eo=y("Automation"),to=y("AutomationRun"),no=y("Auction"),ro=y("CampaignVariant"),oo=y("CommunicationSuppression"),ao=y("ConsentEvent"),io=y("SenderDomain"),so=y("UsageEvent"),uo=y("AuctionItem"),co=y("Author"),lo=y("Bid"),fo=y("Board"),po=y("BoardColumn"),mo=y("Campaign"),yo=y("Card"),go=y("CardComment"),bo=y("Cart"),wo=y("CartItem"),ho=y("Category"),ko=y("Comment"),_o=y("Coupon"),To=y("Customer"),Ro=y("DeliveryRoute"),So=y("DeliveryStop"),Ao=y("Deployment"),Po=y("DigitalDelivery"),xo=y("Courier"),Oo=y("CourierPing"),Co=y("CampaignSend"),vo=y("EmailList"),Mo=y("EmailListSubscriber"),Do=y("Form"),Eo=y("FormField"),Fo=y("FormSubmission"),$o=y("MagicLinkToken"),Io=y("Menu"),jo=y("MenuItem"),Bo=y("PageRevision"),No=y("Pledge"),qo=y("Redirect"),Lo=y("Site"),Uo=y("SiteDomain"),Ko=y("SmsOptOut"),Wo=y("EmailIdempotency"),Qo=y("EmailSuppression"),Vo=y("EmailWebhookEvent"),zo=y("Error"),Ho=y("GiftCard"),Go=y("Label"),Jo=y("LicenseKey"),Yo=y("Log"),Xo=y("LoyaltyPoint"),Zo=y("LoyaltyReward"),ea=y("MailPreference"),ta=y("Manufacturer"),na=y("Notification"),ra=y("NotificationDelivery"),oa=y("Order"),aa=y("OrderIdempotency"),Os=y("PersonalAccessToken"),ia=y("OrderItem"),sa=y("Page"),ua=y("Payment"),ca=y("PaymentMethod"),la=y("PaymentProduct"),da=y("PaymentTransaction"),fa=y("Post"),pa=y("PrintDevice"),ma=y("Product"),ya=y("ProductUnit"),ga=y("ProductVariant"),ba=y("QueryLog"),wa=y("Receipt"),ha=y("Release"),ka=y("Request"),_a=y("Review"),Ta=y("ShippingMethod"),Ra=y("ShippingRate"),Sa=y("ShippingZone"),Aa=y("SocialPost"),Pa=y("SocialAccount"),xa=y("Subscriber"),Oa=y("SubscriberEmail"),Ca=y("Subscription"),va=y("Tag"),Ma=y("TaxRate"),Da=y("Team"),Ea=y("TeamInvitation"),Fa=y("TeamMember"),$a=y("Transaction"),Ia=y("WaitlistProduct"),ja=y("WaitlistRestaurant"),Ba=y("Websocket"),Ft={User:Hr,Job:Gr,FailedJob:Jr,Activity:Xr,AnalyticsEvent:Zr,Automation:eo,AutomationRun:to,Auction:no,AuctionItem:uo,Author:co,Bid:lo,Board:fo,BoardColumn:po,Campaign:mo,CampaignSend:Co,CampaignVariant:ro,Card:yo,CardComment:go,Cart:bo,CartItem:wo,Category:ho,Comment:ko,Coupon:_o,Customer:To,CommunicationSuppression:oo,ConsentEvent:ao,DeliveryRoute:Ro,DeliveryStop:So,Deployment:Ao,DigitalDelivery:Po,Courier:xo,CourierPing:Oo,EmailList:vo,EmailListSubscriber:Mo,EmailIdempotency:Wo,EmailSuppression:Qo,EmailWebhookEvent:Vo,ErrorModel:zo,Form:Do,FormField:Eo,FormSubmission:Fo,GiftCard:Ho,Label:Go,LicenseKey:Jo,Log:Yo,LoyaltyPoint:Xo,LoyaltyReward:Zo,MailPreference:ea,Manufacturer:ta,Notification:na,MagicLinkToken:$o,Menu:Io,MenuItem:jo,NotificationDelivery:ra,Order:oa,OrderIdempotency:aa,OrderItem:ia,Page:sa,PageRevision:Bo,Payment:ua,PaymentMethod:ca,PaymentProduct:la,PaymentTransaction:da,Pledge:No,Post:fa,PrintDevice:pa,Product:ma,ProductUnit:ya,ProductVariant:ga,QueryLog:ba,Receipt:wa,Release:ha,Request:ka,Review:_a,ShippingMethod:Ta,Redirect:qo,SenderDomain:io,ShippingRate:Ra,ShippingZone:Sa,Site:Lo,SiteDomain:Uo,SmsOptOut:Ko,SocialAccount:Pa,SocialPost:Aa,Subscriber:xa,SubscriberEmail:Oa,Subscription:Ca,Tag:va,TaxRate:Ma,Team:Da,TeamInvitation:Ea,TeamMember:Fa,Transaction:$a,UsageEvent:so,WaitlistProduct:Ia,WaitlistRestaurant:ja,Websocket:Ba},I=globalThis;for(let[e,t]of Object.entries(Ft))if(t&&I[e]===void 0)I[e]=t;var Cs=Object.keys(Ft);async function Na(e){if(!e)return[];try{if(typeof e.all==="function"){let t=await e.all();return Array.isArray(t)?t:[]}if(typeof e.get==="function"){let t=await e.get();return Array.isArray(t)?t:[]}}catch{}return[]}function qa(e,t,n=""){if(!e)return n;try{if(typeof e.get==="function"){let o=e.get(t);if(o!==void 0&&o!==null)return o}}catch{}let r=e?.[t];return r!==void 0&&r!==null?r:n}if(I.safeAll===void 0)I.safeAll=Na;if(I.safeGet===void 0)I.safeGet=qa;export{Xr as Activity,Zr as AnalyticsEvent,no as Auction,uo as AuctionItem,co as Author,eo as Automation,to as AutomationRun,lo as Bid,fo as Board,po as BoardColumn,mo as Campaign,Co as CampaignSend,ro as CampaignVariant,yo as Card,go as CardComment,bo as Cart,wo as CartItem,ho as Category,ko as Comment,oo as CommunicationSuppression,ao as ConsentEvent,_o as Coupon,xo as Courier,Oo as CourierPing,To as Customer,Ro as DeliveryRoute,So as DeliveryStop,Ao as Deployment,Po as DigitalDelivery,Wo as EmailIdempotency,vo as EmailList,Mo as EmailListSubscriber,Qo as EmailSuppression,Vo as EmailWebhookEvent,zo as ErrorModel,Jr as FailedJob,Do as Form,Eo as FormField,Fo as FormSubmission,Ho as GiftCard,Gr as Job,Go as Label,Jo as LicenseKey,Yo as Log,Xo as LoyaltyPoint,Zo as LoyaltyReward,Ce as MODEL_DEFINITION,$o as MagicLinkToken,ea as MailPreference,ta as Manufacturer,Pe as MassAssignmentException,Io as Menu,jo as MenuItem,_t as ModelNotFoundError,wt as ModelValidationError,na as Notification,ra as NotificationDelivery,oa as Order,aa as OrderIdempotency,ia as OrderItem,sa as Page,Bo as PageRevision,ua as Payment,ca as PaymentMethod,la as PaymentProduct,da as PaymentTransaction,Os as PersonalAccessToken,No as Pledge,fa as Post,pa as PrintDevice,ma as Product,ya as ProductUnit,ga as ProductVariant,ba as QueryLog,wa as Receipt,qo as Redirect,ha as Release,ka as Request,_a as Review,io as SenderDomain,Ta as ShippingMethod,Ra as ShippingRate,Sa as ShippingZone,Lo as Site,Uo as SiteDomain,Ko as SmsOptOut,Pa as SocialAccount,Aa as SocialPost,_n as SubqueryBuilder,xa as Subscriber,Oa as SubscriberEmail,Ca as Subscription,va as Tag,Ma as TaxRate,Da as Team,Ea as TeamInvitation,Fa as TeamMember,$a as Transaction,so as UsageEvent,Hr as User,Ia as WaitlistProduct,ja as WaitlistRestaurant,Ba as Websocket,Ai as batchLoad,Wr as buildDatabaseSchema,ae as collectEncryptedAttributes,Ie as createAuditMethods,pe as createCategorizableMethods,le as createCommentableMethods,me as createLikeableMethods,fe as createTaggableMethods,pn as customerOwnership,Ci as db,oe as decryptValue,St as defineModel,re as encryptValue,_e as enrichPaginatorUrls,ms as extendModel,rn as filterFillable,Qa as getPrunableConfig,nn as getWritableFields,Ys as isCursorPaginator,j as isEncrypted,Xs as isPaginator,Zs as isSimplePaginator,Ue as isUniqueViolation,en as mapWriteError,Wa as massPrunable,wr as mergeModelDefinition,Cs as modelGlobalNames,xs as ormReady,bn as parentOwnership,He as parseCursor,Oe as projectDocumentsFromTrait,It as prunable,Qr as renderDatabaseTypeFile,ke as resolveCursorArgs,he as resolvePageArgs,Ei as savepoint,mn as selfOwnership,Wt as setAuditUser,yn as siteOwnership,gn as teamMembershipOwnership,fr as toAttrs,eu as toCursorPaginator,tu as toPaginator,nu as toSimplePaginator,tn as toSnakeCaseKeys,Di as transaction,Fi as transactional,M as withoutEvents,Kn as withoutValidation};
22
+ ${vt(t)}`}import{isCursorPaginator as tu,isPaginator as nu,isSimplePaginator as ru,toCursorPaginator as ou,toPaginator as au,toSimplePaginator as iu}from"@stacksjs/pagination";import{configureOrm as Vr}from"@stacksjs/query-builder";function zr(){try{let e=process.env.DB_DATABASE_PATH||"database/stacks.sqlite";if((process.env.DB_CONNECTION||"sqlite")==="sqlite")Vr({database:e})}catch{}}zr();async function Dt(e){for(let t=0;;t++){let n=await import(e);try{return n.default}catch(r){if(t<5&&r instanceof ReferenceError&&/before initialization/.test(r.message)){await new Promise((o)=>setTimeout(o,0));continue}throw r}}}async function te(e,t=[""]){let{path:n}=await import("@stacksjs/path"),r=n.userModelsPath(`${e}.ts`);try{if(await Bun.file(r).exists())return await Dt(r)}catch(o){console.error(`[orm] Failed to import userland model ${e} from ${r} - falling back to framework default. Reason:`,o)}for(let o of t){let a=o?`${o}/`:"",i=n.frameworkPath(`defaults/app/Models/${a}${e}.ts`);try{if(await Bun.file(i).exists())return await Dt(i)}catch(s){console.error(`[orm] Failed to import framework default model ${e} from ${i} - trying next subdir. Reason:`,s)}}return null}var C={},Et=()=>{},xs=new Promise((e)=>{Et=e});function y(e){return new Proxy(function(){},{get(t,n){if(n==="then")return;let r=C[e];if(r==null)return;let o=r[n];return typeof o==="function"?o.bind(r):o},set(t,n,r){let o=C[e];if(o==null)return!1;return o[n]=r,!0},has(t,n){let r=C[e];return r==null?!1:(n in r)},apply(t,n,r){let o=C[e];if(o==null||typeof o!=="function")return;return o.apply(n,r)}})}var Hr=y("User"),Gr=y("Job"),Jr=y("FailedJob"),Yr=[["Referral",[""],"auth"],["ReferralCode",[""],"auth"],["Team",[""],"auth"],["TeamInvitation",[""],"auth"],["TeamMember",[""],"auth"],["SocialAccount",[""],"auth"],["Subscriber",[""],"auth"],["SubscriberEmail",[""],"auth"],["Subscription",[""],"auth"],["Post",["Content"],"cms"],["Page",["Content"],"cms"],["PageRevision",["Content"],"cms"],["Redirect",["Content"],"cms"],["Menu",["Content"],"cms"],["MenuItem",["Content"],"cms"],["Author",["Content"],"cms"],["Comment",[""],"cms"],["Tag",[""],"cms"],["Site",[""],"auth"],["SiteDomain",[""],"auth"],["MagicLinkToken",[""],"auth"],["SmsOptOut",[""],"auth"],["Form",["Forms"],"forms"],["FormField",["Forms"],"forms"],["FormSubmission",["Forms"],"forms"],["Activity",[""],"dashboard"],["Board",[""],"dashboard"],["BoardColumn",[""],"dashboard"],["Card",[""],"dashboard"],["CardComment",[""],"dashboard"],["Deployment",[""],"dashboard"],["Label",[""],"dashboard"],["Release",[""],"dashboard"],["Notification",[""],"dashboard"],["NotificationDelivery",[""],"dashboard"],["PersonalAccessToken",[""],"dashboard"],["MailPreference",[""],"dashboard"],["Log",[""],"dashboard"],["Request",[""],"dashboard"],["AnalyticsEvent",[""],"dashboard"],["QueryLog",[""],"dashboard"],["StorageItem",[""],"dashboard"],["StorageItemTask",[""],"dashboard"],["Error",[""],"monitoring"],["Websocket",["realtime"],"realtime"],["Campaign",[""],"marketing"],["CampaignSend",[""],"marketing"],["EmailList",[""],"marketing"],["EmailListSubscriber",[""],"marketing"],["EmailIdempotency",[""],"marketing"],["EmailSuppression",[""],"marketing"],["EmailWebhookEvent",[""],"marketing"],["SocialPost",[""],"marketing"],["Automation",[""],"marketing"],["AutomationRun",[""],"marketing"],["CampaignVariant",[""],"marketing"],["CommunicationSuppression",[""],"marketing"],["ConsentEvent",[""],"marketing"],["SenderDomain",[""],"marketing"],["UsageEvent",[""],"marketing"],["PaymentMethod",[""],"commerce"],["PaymentProduct",[""],"commerce"],["PaymentTransaction",[""],"commerce"],["Order",["commerce"],"commerce"],["OrderIdempotency",["commerce"],"commerce"],["OrderItem",["commerce"],"commerce"],["Cart",["commerce"],"commerce"],["CartItem",["commerce"],"commerce"],["Customer",["commerce"],"commerce"],["Product",["commerce"],"commerce"],["ProductVariant",["commerce"],"commerce"],["ProductUnit",["commerce"],"commerce"],["Manufacturer",["commerce"],"commerce"],["Category",["commerce"],"commerce"],["Coupon",["commerce"],"commerce"],["GiftCard",["commerce"],"commerce"],["LicenseKey",["commerce"],"commerce"],["Review",["commerce"],"commerce"],["Receipt",["commerce"],"commerce"],["PrintDevice",["commerce"],"commerce"],["ShippingMethod",["commerce"],"commerce"],["ShippingRate",["commerce"],"commerce"],["ShippingZone",["commerce"],"commerce"],["DeliveryRoute",["commerce"],"commerce"],["DeliveryStop",["commerce"],"commerce"],["DigitalDelivery",["commerce"],"commerce"],["Courier",["commerce"],"commerce"],["CourierPing",["commerce"],"commerce"],["TaxRate",["commerce"],"commerce"],["WaitlistProduct",["commerce"],"commerce"],["WaitlistRestaurant",["commerce"],"commerce"],["Auction",["commerce"],"commerce"],["AuctionItem",["commerce"],"commerce"],["Bid",["commerce"],"commerce"],["Pledge",["commerce"],"commerce"],["LoyaltyPoint",["commerce"],"commerce"],["LoyaltyReward",["commerce"],"commerce"],["Payment",["commerce"],"commerce"],["Transaction",["commerce"],"commerce"]];queueMicrotask(async()=>{try{let{feature:e}=await import("@stacksjs/config"),t=await te("User");if(t)C.User=t;if(e("queue")){let n=await te("Job");if(n)C.Job=n;let r=await te("FailedJob");if(r)C.FailedJob=r}for(let[n,r,o]of Yr){if(!e(o))continue;let a=await te(n,r);if(a)C[n]=a}}catch(e){console.error("[orm] deferred model load failed:",e)}finally{Et()}});var Xr=y("Activity"),Zr=y("AnalyticsEvent"),eo=y("Automation"),to=y("AutomationRun"),no=y("Auction"),ro=y("CampaignVariant"),oo=y("CommunicationSuppression"),ao=y("ConsentEvent"),io=y("SenderDomain"),so=y("UsageEvent"),uo=y("AuctionItem"),co=y("Author"),lo=y("Bid"),fo=y("Board"),po=y("BoardColumn"),mo=y("Campaign"),yo=y("Card"),go=y("CardComment"),bo=y("Cart"),wo=y("CartItem"),ho=y("Category"),ko=y("Comment"),_o=y("Coupon"),To=y("Customer"),Ro=y("DeliveryRoute"),So=y("DeliveryStop"),Ao=y("Deployment"),Po=y("DigitalDelivery"),xo=y("Courier"),Oo=y("CourierPing"),Co=y("CampaignSend"),vo=y("EmailList"),Mo=y("EmailListSubscriber"),Do=y("Form"),Eo=y("FormField"),Fo=y("FormSubmission"),$o=y("MagicLinkToken"),Io=y("Menu"),jo=y("MenuItem"),Bo=y("PageRevision"),No=y("Pledge"),qo=y("Redirect"),Lo=y("Site"),Uo=y("SiteDomain"),Ko=y("SmsOptOut"),Os=y("StorageItem"),Cs=y("StorageItemTask"),Wo=y("EmailIdempotency"),Qo=y("EmailSuppression"),Vo=y("EmailWebhookEvent"),zo=y("Error"),Ho=y("GiftCard"),Go=y("Label"),Jo=y("LicenseKey"),Yo=y("Log"),Xo=y("LoyaltyPoint"),Zo=y("LoyaltyReward"),ea=y("MailPreference"),ta=y("Manufacturer"),na=y("Notification"),ra=y("NotificationDelivery"),oa=y("Order"),aa=y("OrderIdempotency"),vs=y("PersonalAccessToken"),ia=y("OrderItem"),sa=y("Page"),ua=y("Payment"),ca=y("PaymentMethod"),la=y("PaymentProduct"),da=y("PaymentTransaction"),fa=y("Post"),pa=y("PrintDevice"),ma=y("Product"),ya=y("ProductUnit"),ga=y("ProductVariant"),ba=y("QueryLog"),wa=y("Receipt"),Ms=y("Referral"),Ds=y("ReferralCode"),ha=y("Release"),ka=y("Request"),_a=y("Review"),Ta=y("ShippingMethod"),Ra=y("ShippingRate"),Sa=y("ShippingZone"),Aa=y("SocialPost"),Pa=y("SocialAccount"),xa=y("Subscriber"),Oa=y("SubscriberEmail"),Ca=y("Subscription"),va=y("Tag"),Ma=y("TaxRate"),Da=y("Team"),Ea=y("TeamInvitation"),Fa=y("TeamMember"),$a=y("Transaction"),Ia=y("WaitlistProduct"),ja=y("WaitlistRestaurant"),Ba=y("Websocket"),Ft={User:Hr,Job:Gr,FailedJob:Jr,Activity:Xr,AnalyticsEvent:Zr,Automation:eo,AutomationRun:to,Auction:no,AuctionItem:uo,Author:co,Bid:lo,Board:fo,BoardColumn:po,Campaign:mo,CampaignSend:Co,CampaignVariant:ro,Card:yo,CardComment:go,Cart:bo,CartItem:wo,Category:ho,Comment:ko,Coupon:_o,Customer:To,CommunicationSuppression:oo,ConsentEvent:ao,DeliveryRoute:Ro,DeliveryStop:So,Deployment:Ao,DigitalDelivery:Po,Courier:xo,CourierPing:Oo,EmailList:vo,EmailListSubscriber:Mo,EmailIdempotency:Wo,EmailSuppression:Qo,EmailWebhookEvent:Vo,ErrorModel:zo,Form:Do,FormField:Eo,FormSubmission:Fo,GiftCard:Ho,Label:Go,LicenseKey:Jo,Log:Yo,LoyaltyPoint:Xo,LoyaltyReward:Zo,MailPreference:ea,Manufacturer:ta,Notification:na,MagicLinkToken:$o,Menu:Io,MenuItem:jo,NotificationDelivery:ra,Order:oa,OrderIdempotency:aa,OrderItem:ia,Page:sa,PageRevision:Bo,Payment:ua,PaymentMethod:ca,PaymentProduct:la,PaymentTransaction:da,Pledge:No,Post:fa,PrintDevice:pa,Product:ma,ProductUnit:ya,ProductVariant:ga,QueryLog:ba,Receipt:wa,Release:ha,Request:ka,Review:_a,ShippingMethod:Ta,Redirect:qo,SenderDomain:io,ShippingRate:Ra,ShippingZone:Sa,Site:Lo,SiteDomain:Uo,SmsOptOut:Ko,SocialAccount:Pa,SocialPost:Aa,Subscriber:xa,SubscriberEmail:Oa,Subscription:Ca,Tag:va,TaxRate:Ma,Team:Da,TeamInvitation:Ea,TeamMember:Fa,Transaction:$a,UsageEvent:so,WaitlistProduct:Ia,WaitlistRestaurant:ja,Websocket:Ba},I=globalThis;for(let[e,t]of Object.entries(Ft))if(t&&I[e]===void 0)I[e]=t;var Es=Object.keys(Ft);async function Na(e){if(!e)return[];try{if(typeof e.all==="function"){let t=await e.all();return Array.isArray(t)?t:[]}if(typeof e.get==="function"){let t=await e.get();return Array.isArray(t)?t:[]}}catch{}return[]}function qa(e,t,n=""){if(!e)return n;try{if(typeof e.get==="function"){let o=e.get(t);if(o!==void 0&&o!==null)return o}}catch{}let r=e?.[t];return r!==void 0&&r!==null?r:n}if(I.safeAll===void 0)I.safeAll=Na;if(I.safeGet===void 0)I.safeGet=qa;export{Xr as Activity,Zr as AnalyticsEvent,no as Auction,uo as AuctionItem,co as Author,eo as Automation,to as AutomationRun,lo as Bid,fo as Board,po as BoardColumn,mo as Campaign,Co as CampaignSend,ro as CampaignVariant,yo as Card,go as CardComment,bo as Cart,wo as CartItem,ho as Category,ko as Comment,oo as CommunicationSuppression,ao as ConsentEvent,_o as Coupon,xo as Courier,Oo as CourierPing,To as Customer,Ro as DeliveryRoute,So as DeliveryStop,Ao as Deployment,Po as DigitalDelivery,Wo as EmailIdempotency,vo as EmailList,Mo as EmailListSubscriber,Qo as EmailSuppression,Vo as EmailWebhookEvent,zo as ErrorModel,Jr as FailedJob,Do as Form,Eo as FormField,Fo as FormSubmission,Ho as GiftCard,Gr as Job,Go as Label,Jo as LicenseKey,Yo as Log,Xo as LoyaltyPoint,Zo as LoyaltyReward,Ce as MODEL_DEFINITION,$o as MagicLinkToken,ea as MailPreference,ta as Manufacturer,Pe as MassAssignmentException,Io as Menu,jo as MenuItem,_t as ModelNotFoundError,wt as ModelValidationError,na as Notification,ra as NotificationDelivery,oa as Order,aa as OrderIdempotency,ia as OrderItem,sa as Page,Bo as PageRevision,ua as Payment,ca as PaymentMethod,la as PaymentProduct,da as PaymentTransaction,vs as PersonalAccessToken,No as Pledge,fa as Post,pa as PrintDevice,ma as Product,ya as ProductUnit,ga as ProductVariant,ba as QueryLog,wa as Receipt,qo as Redirect,Ms as Referral,Ds as ReferralCode,ha as Release,ka as Request,_a as Review,io as SenderDomain,Ta as ShippingMethod,Ra as ShippingRate,Sa as ShippingZone,Lo as Site,Uo as SiteDomain,Ko as SmsOptOut,Pa as SocialAccount,Aa as SocialPost,Os as StorageItem,Cs as StorageItemTask,_n as SubqueryBuilder,xa as Subscriber,Oa as SubscriberEmail,Ca as Subscription,va as Tag,Ma as TaxRate,Da as Team,Ea as TeamInvitation,Fa as TeamMember,$a as Transaction,so as UsageEvent,Hr as User,Ia as WaitlistProduct,ja as WaitlistRestaurant,Ba as Websocket,Ai as batchLoad,Wr as buildDatabaseSchema,ae as collectEncryptedAttributes,Ie as createAuditMethods,pe as createCategorizableMethods,le as createCommentableMethods,me as createLikeableMethods,fe as createTaggableMethods,pn as customerOwnership,Ci as db,oe as decryptValue,St as defineModel,re as encryptValue,_e as enrichPaginatorUrls,ms as extendModel,rn as filterFillable,Qa as getPrunableConfig,nn as getWritableFields,tu as isCursorPaginator,j as isEncrypted,nu as isPaginator,ru as isSimplePaginator,Ue as isUniqueViolation,en as mapWriteError,Wa as massPrunable,wr as mergeModelDefinition,Es as modelGlobalNames,xs as ormReady,bn as parentOwnership,He as parseCursor,Oe as projectDocumentsFromTrait,It as prunable,Qr as renderDatabaseTypeFile,ke as resolveCursorArgs,he as resolvePageArgs,Ei as savepoint,mn as selfOwnership,Wt as setAuditUser,yn as siteOwnership,gn as teamMembershipOwnership,fr as toAttrs,ou as toCursorPaginator,au as toPaginator,iu as toSimplePaginator,tn as toSnakeCaseKeys,Di as transaction,Fi as transactional,M as withoutEvents,Kn as withoutValidation};
@@ -0,0 +1,123 @@
1
+ import { defineModel } from '@stacksjs/orm'
2
+ import { schema } from '@stacksjs/validation'
3
+
4
+ /**
5
+ * Dashboard metadata for one file on one disk (stacksjs/stacks#2577).
6
+ *
7
+ * Every file-manager operation shipped before this maps to a `StorageAdapter`
8
+ * method - `write`, `list`, `moveFile`, `changeVisibility`, `deleteFile`. A disk
9
+ * knows a path, some bytes, a size and an ACL. It does not know that somebody
10
+ * starred a file, and there is nowhere on a disk to write that down: extended
11
+ * attributes do not survive a copy and cost a syscall per file, and S3 object
12
+ * metadata is set at write time, so starring a 2 GB video would rewrite 2 GB.
13
+ * Both are a database row wearing a disguise, so this is the row.
14
+ *
15
+ * ## The disk is authoritative, this table is advisory
16
+ *
17
+ * That is the question #2577 asks to settle first, and it decides everything
18
+ * else. A bucket several systems write to changes without the dashboard's
19
+ * knowledge, so a table that claimed to describe its contents would be wrong
20
+ * within a day of being right. Instead:
21
+ *
22
+ * - The listing comes from the disk and is joined to these rows. A path with no
23
+ * row is a file with no stars, which is the normal case and needs no row.
24
+ * - A row whose path no longer exists is an orphan and is simply not shown. The
25
+ * listing pass already enumerates every path in the subtree, so it sweeps the
26
+ * orphans it can prove are orphans - the ones under a prefix it just walked -
27
+ * at no extra cost. Nothing walks the whole disk to garbage collect.
28
+ * - Renames and deletes made THROUGH the dashboard reconcile eagerly, so a
29
+ * starred file keeps its star the moment it moves rather than waiting for a
30
+ * sweep. A folder rename is a prefix update, because moving a folder moves
31
+ * every file beneath it.
32
+ *
33
+ * The consequence worth stating: a file renamed outside the dashboard loses its
34
+ * metadata, because nothing connects the old path to the new one. That is not
35
+ * a gap to close later - a copy and a rename are indistinguishable to a bucket
36
+ * listing, so any reconciliation would be guessing.
37
+ *
38
+ * Keyed by `(disk, path)` rather than by a file id, because a disk has no file
39
+ * ids to key by.
40
+ *
41
+ * ## Tags are the existing vocabulary, reached the way the CMS reaches it
42
+ *
43
+ * #2577 asks for the existing vocabulary rather than a second one. That is the
44
+ * `tags` table, joined through the `taggable_models` pivot, with
45
+ * `taggable_type` keeping one model's attachments away from another's - which
46
+ * is what the dashboard's own tag manager writes and reads.
47
+ *
48
+ * `file-metadata-store.ts` queries it directly rather than declaring a
49
+ * `belongsToMany` here, because every operation is a set operation over a
50
+ * subtree and the relation would do them a row at a time. The relation would
51
+ * resolve correctly, though: `taggable_models.tag_id` is a `tags` id, which
52
+ * took stacksjs/stacks#2579 to establish - the migration comment and four
53
+ * queries in `@stacksjs/cms` said `taggables`, a different table belonging to a
54
+ * different mechanism.
55
+ */
56
+ export default defineModel({
57
+ name: 'StorageItem',
58
+ table: 'storage_items',
59
+ primaryKey: 'id',
60
+ autoIncrement: true,
61
+
62
+ /**
63
+ * One row per file, enforced rather than assumed.
64
+ *
65
+ * Every write here is a get-or-create keyed on this pair, and a duplicate
66
+ * would not be a visible bug - it would be a file that is starred and also
67
+ * not starred, depending which row the query happened to read first.
68
+ */
69
+ indexes: [
70
+ {
71
+ name: 'storage_items_disk_path_unique',
72
+ columns: ['disk', 'path'],
73
+ unique: true,
74
+ },
75
+ ],
76
+
77
+ traits: {
78
+ useUuid: true,
79
+ useTimestamps: true,
80
+
81
+ useSearch: {
82
+ displayable: ['id', 'disk', 'path', 'favorite'],
83
+ searchable: ['path'],
84
+ sortable: ['path', 'createdAt'],
85
+ filterable: ['disk', 'favorite'],
86
+ },
87
+
88
+ useSeeder: { count: 0 },
89
+ },
90
+
91
+ attributes: {
92
+ disk: {
93
+ order: 1,
94
+ fillable: true,
95
+ // The disk NAME, not its driver: two disks can point at one bucket with
96
+ // different prefixes, and they are different namespaces to the dashboard.
97
+ validation: { rule: schema.string().required().min(1).max(64) },
98
+ factory: () => 'public',
99
+ },
100
+
101
+ path: {
102
+ order: 2,
103
+ fillable: true,
104
+ // Disk-relative and without a leading slash, exactly as the file manager
105
+ // reports it, so a lookup is an equality match rather than a normalization
106
+ // problem at every call site.
107
+ validation: { rule: schema.string().required().min(1).max(2048) },
108
+ factory: faker => `${faker.system.fileName()}`,
109
+ },
110
+
111
+ favorite: {
112
+ order: 3,
113
+ fillable: true,
114
+ default: false,
115
+ validation: { rule: schema.boolean() },
116
+ factory: () => false,
117
+ },
118
+ },
119
+
120
+ // Managed from the file manager, not as a top-level model row: a list of
121
+ // (disk, path, favorite) tuples is not a thing anybody wants to browse.
122
+ dashboard: { enabled: false },
123
+ } as const)
@@ -0,0 +1,134 @@
1
+ import { defineModel } from '@stacksjs/orm'
2
+ import { schema } from '@stacksjs/validation'
3
+
4
+ /**
5
+ * One unit of background processing for one file (stacksjs/stacks#2578).
6
+ *
7
+ * The three things #245 asked for that could not happen inside a request -
8
+ * image optimization, video transcode, AI tagging - share the same shape:
9
+ * dispatch work and show what happened to it. Transcoding is minutes, not
10
+ * milliseconds; a vision call is a round trip to a third party. An upload
11
+ * handler that waits for either is an upload handler that times out.
12
+ *
13
+ * ## Why this is not a column on `StorageItem`
14
+ *
15
+ * A file can have three of these at once and they succeed and fail
16
+ * independently - a video whose transcode finished and whose tagging failed is
17
+ * a normal state, and a single `processing` column cannot say it. The file
18
+ * manager aggregates these rows into the one word a UI shows; the rows are what
19
+ * a retry and an error message need.
20
+ *
21
+ * It is also keyed by `(disk, path, kind)` rather than by a `storage_items` id,
22
+ * deliberately. A `storage_items` row exists only while somebody has starred or
23
+ * tagged the file - it is deleted when it has nothing left to say - and most
24
+ * uploads are neither. Hanging a task off it would mean creating a metadata row
25
+ * for every upload just to have somewhere to put the task.
26
+ *
27
+ * Same reconciliation rules as `storage_items`, through the same store: a
28
+ * rename moves these rows, a delete forgets them, and a completed listing
29
+ * sweeps the ones whose file is gone.
30
+ */
31
+ export default defineModel({
32
+ name: 'StorageItemTask',
33
+ table: 'storage_item_tasks',
34
+ primaryKey: 'id',
35
+ autoIncrement: true,
36
+
37
+ /**
38
+ * One task per kind per file.
39
+ *
40
+ * Re-running replaces the row rather than adding a second, so "what happened
41
+ * to the transcode" has one answer. The history of previous attempts is the
42
+ * queue's to keep, not this table's.
43
+ */
44
+ indexes: [
45
+ {
46
+ name: 'storage_item_tasks_disk_path_kind_unique',
47
+ columns: ['disk', 'path', 'kind'],
48
+ unique: true,
49
+ },
50
+ ],
51
+
52
+ traits: {
53
+ useUuid: true,
54
+ useTimestamps: true,
55
+
56
+ useSearch: {
57
+ displayable: ['id', 'disk', 'path', 'kind', 'state'],
58
+ searchable: ['path'],
59
+ sortable: ['path', 'createdAt'],
60
+ filterable: ['disk', 'kind', 'state'],
61
+ },
62
+
63
+ useSeeder: { count: 0 },
64
+ },
65
+
66
+ attributes: {
67
+ disk: {
68
+ order: 1,
69
+ fillable: true,
70
+ validation: { rule: schema.string().required().min(1).max(64) },
71
+ factory: () => 'public',
72
+ },
73
+
74
+ path: {
75
+ order: 2,
76
+ fillable: true,
77
+ validation: { rule: schema.string().required().min(1).max(2048) },
78
+ factory: faker => faker.system.fileName(),
79
+ },
80
+
81
+ kind: {
82
+ order: 3,
83
+ fillable: true,
84
+ // `optimize` (images), `transcode` (video), `tag` (AI). An enum rather
85
+ // than free text so a typo in a dispatch is a validation error instead of
86
+ // a task nothing will ever run.
87
+ validation: { rule: schema.enum(['optimize', 'transcode', 'tag']) },
88
+ factory: () => 'optimize',
89
+ },
90
+
91
+ state: {
92
+ order: 4,
93
+ fillable: true,
94
+ default: 'queued',
95
+ validation: { rule: schema.enum(['queued', 'running', 'done', 'failed']) },
96
+ factory: () => 'queued',
97
+ },
98
+
99
+ attempts: {
100
+ order: 5,
101
+ fillable: true,
102
+ default: 0,
103
+ // Counted here as well as in the queue, because the queue's count is gone
104
+ // once the job leaves it and this is what the dashboard reads.
105
+ validation: { rule: schema.number() },
106
+ factory: () => 0,
107
+ },
108
+
109
+ error: {
110
+ order: 6,
111
+ fillable: true,
112
+ // The failure as the worker saw it. Truncated by the writer rather than
113
+ // by the column, so a stack trace does not silently lose its first line.
114
+ validation: { rule: schema.string().max(2000) },
115
+ factory: () => '',
116
+ },
117
+
118
+ startedAt: {
119
+ order: 7,
120
+ fillable: true,
121
+ validation: { rule: schema.string() },
122
+ factory: () => '',
123
+ },
124
+
125
+ finishedAt: {
126
+ order: 8,
127
+ fillable: true,
128
+ validation: { rule: schema.string() },
129
+ factory: () => '',
130
+ },
131
+ },
132
+
133
+ dashboard: { enabled: false },
134
+ } as const)
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/orm",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.74.32",
5
+ "version": "0.74.34",
6
6
  "description": "The Stacks ORM integration",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -63,31 +63,31 @@
63
63
  "prepublishOnly": "bun run build"
64
64
  },
65
65
  "dependencies": {
66
- "@stacksjs/cache": "0.74.32",
67
- "@stacksjs/cli": "0.74.32",
68
- "@stacksjs/config": "0.74.32",
69
- "@stacksjs/database": "0.74.32",
70
- "@stacksjs/env": "0.74.32",
71
- "@stacksjs/error-handling": "0.74.32",
72
- "@stacksjs/events": "0.74.32",
73
- "@stacksjs/logging": "0.74.32",
74
- "@stacksjs/model-meta": "0.74.32",
75
- "@stacksjs/pagination": "0.74.32",
76
- "@stacksjs/path": "0.74.32",
77
- "@stacksjs/query-builder": "0.74.32",
78
- "@stacksjs/realtime": "0.74.32",
79
- "@stacksjs/router": "0.74.32",
80
- "@stacksjs/storage": "0.74.32",
81
- "@stacksjs/strings": "0.74.32",
66
+ "@stacksjs/cache": "0.74.34",
67
+ "@stacksjs/cli": "0.74.34",
68
+ "@stacksjs/config": "0.74.34",
69
+ "@stacksjs/database": "0.74.34",
70
+ "@stacksjs/env": "0.74.34",
71
+ "@stacksjs/error-handling": "0.74.34",
72
+ "@stacksjs/events": "0.74.34",
73
+ "@stacksjs/logging": "0.74.34",
74
+ "@stacksjs/model-meta": "0.74.34",
75
+ "@stacksjs/pagination": "0.74.34",
76
+ "@stacksjs/path": "0.74.34",
77
+ "@stacksjs/query-builder": "0.74.34",
78
+ "@stacksjs/realtime": "0.74.34",
79
+ "@stacksjs/router": "0.74.34",
80
+ "@stacksjs/storage": "0.74.34",
81
+ "@stacksjs/strings": "0.74.34",
82
82
  "@stacksjs/ts-validation": "^0.5.6",
83
- "@stacksjs/validation": "0.74.32",
83
+ "@stacksjs/validation": "0.74.34",
84
84
  "bun-query-builder": "^0.2.69"
85
85
  },
86
86
  "peerDependencies": {
87
- "@stacksjs/auth": "0.74.32",
88
- "@stacksjs/payments": "0.74.32",
89
- "@stacksjs/queue": "0.74.32",
90
- "@stacksjs/search-engine": "0.74.32",
87
+ "@stacksjs/auth": "0.74.34",
88
+ "@stacksjs/payments": "0.74.34",
89
+ "@stacksjs/queue": "0.74.34",
90
+ "@stacksjs/search-engine": "0.74.34",
91
91
  "stripe": "22.3.2"
92
92
  },
93
93
  "peerDependenciesMeta": {
@@ -108,7 +108,7 @@
108
108
  }
109
109
  },
110
110
  "devDependencies": {
111
- "@stacksjs/types": "0.74.32",
111
+ "@stacksjs/types": "0.74.34",
112
112
  "better-dx": "^0.2.24",
113
113
  "stripe": "22.3.2"
114
114
  }