@auth-craft/aws-cf-stack 1.6.1 → 1.6.2
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/assets/admin/cli.mjs +1 -1
- package/assets/lambda/index.mjs +1 -1
- package/package.json +1 -1
package/assets/admin/cli.mjs
CHANGED
|
@@ -184,7 +184,7 @@ Expecting one of '${n.join("', '")}'`);let i=`${e}Help`;return this.on(i,s=>{let
|
|
|
184
184
|
RETURNING *`,[e.provider,e.externalId,e.userId,e.externalUsername??null,e.externalEmail??null,e.externalPhone??null,e.externalName??null,e.externalAvatarUrl??null,e.metadata?JSON.stringify(e.metadata):null]);return w(this.toEntity(r[0]))}catch(r){let n=r;return n.code==="23505"?T(N.UniqueConstraintViolation({field:"provider link"})):n.code==="23503"?T(N.ForeignKeyViolation({field:"userId"})):T(N.DatabaseQueryError({query:"create provider"}))}}async update(e,r,n){try{let i=[],s=[],o=1;return n.externalUsername!==void 0&&(i.push(`external_username = $${o++}`),s.push(n.externalUsername??null)),n.externalEmail!==void 0&&(i.push(`external_email = $${o++}`),s.push(n.externalEmail??null)),n.externalPhone!==void 0&&(i.push(`external_phone = $${o++}`),s.push(n.externalPhone??null)),n.externalName!==void 0&&(i.push(`external_name = $${o++}`),s.push(n.externalName??null)),n.externalAvatarUrl!==void 0&&(i.push(`external_avatar_url = $${o++}`),s.push(n.externalAvatarUrl??null)),n.metadata!==void 0&&(i.push(`metadata = $${o++}`),s.push(n.metadata?JSON.stringify(n.metadata):null)),i.length===0?w(void 0):(s.push(e,r),await this.pool.query(`UPDATE user_providers SET ${i.join(", ")} WHERE provider = $${o++} AND external_id = $${o}`,s),w(void 0))}catch{return T(N.DatabaseQueryError({query:"update provider"}))}}async remove(e,r){try{return await this.pool.query("DELETE FROM user_providers WHERE provider = $1 AND external_id = $2",[e,r]),w(void 0)}catch{return T(N.DatabaseQueryError({query:"remove provider"}))}}toEntity(e){let r={userId:e.user_id,provider:e.provider,externalId:e.external_id,createdAt:new Date(e.created_at)};return e.external_username&&(r.externalUsername=e.external_username),e.external_email&&(r.externalEmail=e.external_email),e.external_phone&&(r.externalPhone=e.external_phone),e.external_name&&(r.externalName=e.external_name),e.external_avatar_url&&(r.externalAvatarUrl=e.external_avatar_url),e.metadata&&(r.metadata=e.metadata),r}};var yd=class{pool;constructor(e){this.pool=e}async get(e,r){try{let{rows:n}=await this.pool.query("SELECT * FROM user_tenant_profiles WHERE tenant_id = $1 AND user_id = $2",[e,r]);return n.length===0?w(null):w(this.toEntity(n[0]))}catch{return T(N.DatabaseQueryError({query:"get user tenant profile"}))}}async create(e){try{let{rows:r}=await this.pool.query(`INSERT INTO user_tenant_profiles (
|
|
185
185
|
tenant_id, user_id, contact_email, contact_phone, display_name, display_name_source, given_name, family_name, avatar_url, locale, job_title, bio, metadata
|
|
186
186
|
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
|
|
187
|
-
RETURNING *`,[e.tenantId,e.userId,e.contactEmail??null,e.contactPhone??null,e.displayName??null,e.displayNameSource??null,e.givenName??null,e.familyName??null,e.avatarUrl??null,e.locale??null,e.jobTitle??null,e.bio??null,e.metadata?JSON.stringify(e.metadata):null]);return w(this.toEntity(r[0]))}catch(r){console.error("[DEBUG] user_tenant_profiles insert error:",r);let n=r;return n.code==="23505"?T(N.UniqueConstraintViolation({field:"tenant profile"})):n.code==="23503"?T(N.ForeignKeyViolation({field:"userId"})):T(N.DatabaseQueryError({query:"create user tenant profile"}))}}async update(e,r,n){try{let i=["updated_at = NOW()"],s=[],o=1,a=[["contactEmail","contact_email"],["contactPhone","contact_phone"],["displayName","display_name"],["displayNameSource","display_name_source"],["givenName","given_name"],["familyName","family_name"],["avatarUrl","avatar_url"],["locale","locale"],["jobTitle","job_title"],["bio","bio"]];for(let[c,u]of a)n[c]!==void 0&&(i.push(`${u} = $${o++}`),s.push(n[c]??null));return n.metadata!==void 0&&(i.push(`metadata = $${o++}`),s.push(n.metadata?JSON.stringify(n.metadata):null)),s.length===0?w(void 0):(s.push(e,r),await this.pool.query(`UPDATE user_tenant_profiles SET ${i.join(", ")} WHERE tenant_id = $${o++} AND user_id = $${o}`,s),w(void 0))}catch{return T(N.DatabaseQueryError({query:"update user tenant profile"}))}}async remove(e,r){try{return await this.pool.query("DELETE FROM user_tenant_profiles WHERE tenant_id = $1 AND user_id = $2",[e,r]),w(void 0)}catch{return T(N.DatabaseQueryError({query:"remove user tenant profile"}))}}toEntity(e){let r={tenantId:e.tenant_id,userId:e.user_id,createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at)};return e.contact_email&&(r.contactEmail=e.contact_email),e.contact_phone&&(r.contactPhone=e.contact_phone),e.display_name&&(r.displayName=e.display_name),e.display_name_source&&(r.displayNameSource=e.display_name_source),e.given_name&&(r.givenName=e.given_name),e.family_name&&(r.familyName=e.family_name),e.avatar_url&&(r.avatarUrl=e.avatar_url),e.locale&&(r.locale=e.locale),e.job_title&&(r.jobTitle=e.job_title),e.bio&&(r.bio=e.bio),e.metadata&&(r.metadata=typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata),r}};var mb=class{name="database-postgresql";version="1.0.0";users;sessions;userProviders;userMfaAuthenticators;challenges;identities;credentials;userAuths;tenants;tenantMembers;tenantInvites;userTenantProfiles;queries;pool;constructor(e){this.pool=e,this.users=new Ed(e),this.userAuths=new md(e),this.sessions=new sd(e),this.identities=new id(e),this.credentials=new nd(e),this.challenges=new rd(e),this.userProviders=new gd(e),this.userMfaAuthenticators=new hd(e),this.tenants=new fd(e),this.tenantMembers=new ud(e),this.tenantInvites=new ad(e),this.userTenantProfiles=new yd(e),this.queries={tenantInvites:new od(e),tenantMembers:new cd(e),tenants:new ld(e)}}async initialize(){}async health(){try{let e=await this.pool.connect();return await e.query("SELECT 1"),e.release(),!0}catch{return!1}}async cleanup(){await this.pool.end()}};function HO(t){let e=new mh(t);return new mb(e)}var _J={allowPlusAddressing:!0,allowDots:!0,requireTLD:!0};function GO(t={}){let e={..._J,...t},n=(()=>{if(t.customRegex)return t.customRegex;let i="[a-zA-Z0-9_\\-]";e.allowDots?(i+="+",i=`(${i}\\.?)+`):i+="+",e.allowPlusAddressing&&(i=`${i}(\\+[a-zA-Z0-9_\\-]+)?`);let s=e.requireTLD?"[a-zA-Z0-9][a-zA-Z0-9\\-]*\\.[a-zA-Z]{2,}":"[a-zA-Z0-9][a-zA-Z0-9\\-\\.]*";return new RegExp(`^${i}@${s}$`)})();return{name:"email-identity",version:"1.0.0",identityType:"email",normalize(i){return i.toLowerCase().trim()},validate(i){if(!i||i.trim().length===0)return T([{code:"EMAIL_REQUIRED",message:"Email address is required"}]);if(i.length>254)return T([{code:"EMAIL_TOO_LONG",message:"Email address is too long (max 254 characters)"}]);if(!n.test(i))return T([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);if(i.includes(".."))return T([{code:"INVALID_EMAIL_FORMAT",message:"Email address cannot contain consecutive dots"}]);let s=i.split("@");if(s.length!==2)return T([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);let[o,a]=s;return!o||o.length>64?T([{code:"EMAIL_LOCAL_PART_TOO_LONG",message:"Email local part is too long (max 64 characters)"}]):a&&a.length>253?T([{code:"EMAIL_DOMAIN_TOO_LONG",message:"Email domain is too long (max 253 characters)"}]):w()}}}var z_=ge(v_(),1),m8=ge(ir(),1);function Te(t){return t.getTime()}function oe(t){return new Date(t)}function n8(t){return Math.floor(t/1e3)}function Ne(){return Date.now()}function Kf(t){return t instanceof Date?n8(t.getTime()):n8(t)}function tv(t){return t<Date.now()}function Ui(t){return t?Te(t):null}function Xr(t){return t==null?null:oe(t)}function Zr(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}function $i(t){let e=[],r=[],n={},i={},s=0;for(let[c,u]of Object.entries(t)){if(c==="PK"||c==="SK")continue;let p=`#${c}`;if(n[p]=c,u==null)r.push(p);else{let d=`:val${s}`;e.push(`${p} = ${d}`),i[d]=u,s++}}let o=[];return e.length>0&&o.push(`SET ${e.join(", ")}`),r.length>0&&o.push(`REMOVE ${r.join(", ")}`),{UpdateExpression:o.join(" "),ExpressionAttributeNames:n,ExpressionAttributeValues:i}}function rv(t="PK"){return`attribute_not_exists(${t})`}var wr={INVITE_MEMBERS:1,REMOVE_MEMBERS:2,VIEW_MEMBERS:4,CHANGE_MEMBER_PERMISSION:8,UPDATE_MEMBER_PROFILE:16,UPDATE_MEMBER_STATUS:32,VIEW_ACCOUNTS:64,UPDATE_ACCOUNT_PROFILE:128,UPDATE_ACCOUNT_STATUS:256,RESET_ACCOUNT_CREDENTIALS:512,REMOVE_ACCOUNTS:1024},mge=wr.VIEW_ACCOUNTS|wr.UPDATE_ACCOUNT_PROFILE|wr.UPDATE_ACCOUNT_STATUS|wr.RESET_ACCOUNT_CREDENTIALS|wr.REMOVE_ACCOUNTS;var i8={[wr.INVITE_MEMBERS]:"tenant.member.invite",[wr.REMOVE_MEMBERS]:"tenant.member.remove",[wr.VIEW_MEMBERS]:"tenant.member.view",[wr.CHANGE_MEMBER_PERMISSION]:"tenant.member.permission",[wr.UPDATE_MEMBER_PROFILE]:"tenant.member.profile.update",[wr.UPDATE_MEMBER_STATUS]:"tenant.member.status.update",[wr.VIEW_ACCOUNTS]:"account.view",[wr.UPDATE_ACCOUNT_PROFILE]:"account.profile.update",[wr.UPDATE_ACCOUNT_STATUS]:"account.status.update",[wr.RESET_ACCOUNT_CREDENTIALS]:"account.credentials.reset",[wr.REMOVE_ACCOUNTS]:"account.remove"},hge=Object.fromEntries(Object.entries(i8).map(([t,e])=>[e,Number(t)]));var nv={SYSTEM:"system",DEFAULT:"org"};var iv={USER:"USR"},De={USER:`${iv.USER}#`,SESSION:"SES#",PROVIDER:"PRV#",CHALLENGE:"CHL#",IDENTITY:"IDT#",CREDENTIAL:"CRD#",TENANT:"TNT#",INVITE:"INV#"},_t={METADATA:"MD",AUTH:"AUTH",PROFILE:"PROF",PROVIDER:"PRV#",MFA:"MFA#",TENANT_PROFILE:"TPRF#",OWNER:"OWNER"},Cr="#",K={USER_PK:t=>`${De.USER}${t}`,USER_AUTH_SK:()=>_t.AUTH,USER_PROFILE_SK:()=>_t.PROFILE,USER_MFA_SK:t=>`${_t.MFA}${t}`,USER_MFA_WITH_ID_SK:(t,e)=>`${_t.MFA}${t}${Cr}${e}`,TENANT_MEMBER_PK:t=>`${De.TENANT}${t}`,TENANT_MEMBER_SK:t=>`${De.USER}${t}`,TENANT_OWNER_MARKER_SK:()=>_t.OWNER,TENANT_PK:t=>`${De.TENANT}${t}`,TENANT_SK:()=>_t.METADATA,INVITE_PK:t=>`${De.INVITE}${t}`,INVITE_SK:()=>_t.METADATA,TENANT_PROFILE_PK:t=>`${De.TENANT}${t}`,TENANT_PROFILE_SK:t=>`${_t.TENANT_PROFILE}${De.USER}${t}`,SESSION_PK:t=>`${De.SESSION}${t}`,SESSION_METADATA_SK:()=>_t.METADATA,SESSION_SK:()=>_t.METADATA,PROVIDER_SK:(t,e)=>`${_t.PROVIDER}${t}${Cr}${e}`,PROVIDER_PK:(t,e)=>`${De.PROVIDER}${t}${Cr}${e}`,PROVIDER_METADATA_SK:()=>_t.METADATA,CHALLENGE_PK:t=>`${De.CHALLENGE}${t}`,CHALLENGE_SK:()=>_t.METADATA,IDENTITY_PK:(t,e)=>`${De.IDENTITY}${t}#${e}`,IDENTITY_SK:()=>_t.METADATA,CREDENTIAL_PK:t=>`${De.CREDENTIAL}${t}`,CREDENTIAL_SK:()=>_t.METADATA,CREDENTIAL_TYPE_PREFIX:t=>`${De.CREDENTIAL}${t}#`,CREDENTIAL_USER_SK:(t,e)=>`${De.CREDENTIAL}${t}#${e}`,USER_INDEX_PK:t=>`${De.USER}${t}`,USER_INDEX_SK:(t,e)=>`${De.IDENTITY}${t}#${e}`},ve={userId:t=>t.slice(De.USER.length),sessionId:t=>t.slice(De.SESSION.length),providerPKInfo:t=>{let e=t.slice(De.PROVIDER.length),r=e.indexOf("#");if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{provider:n,externalId:i}},providerInfo:t=>{let e=t.slice(_t.PROVIDER.length),r=e.indexOf(Cr);if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{provider:n,externalId:i}},mfaSKInfo:t=>{let e=t.slice(_t.MFA.length),r=e.indexOf(Cr);if(r===-1)return{method:e};let n=e.slice(0,r),i=e.slice(r+1);return{method:n,id:i}},tenantId:t=>t.slice(De.TENANT.length),tenantMemberUserId:t=>t.slice(De.USER.length),challengeIdFromPK:t=>t.slice(De.CHALLENGE.length),inviteId:t=>t.slice(De.INVITE.length),tenantProfileUserId:t=>t.slice(_t.TENANT_PROFILE.length+De.USER.length),identityPKInfo:t=>{let e=t.slice(De.IDENTITY.length),r=e.indexOf("#");if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{type:n,value:i}},credentialId:t=>t.slice(De.CREDENTIAL.length),credentialTypeFromUserSK:t=>{let e=t.slice(De.CREDENTIAL.length),r=e.indexOf("#");return r===-1?"":e.slice(0,r)},userIndexSKInfo:t=>{let e=t.slice(De.IDENTITY.length),r=e.indexOf("#");if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{type:n,value:i}}};var ze={ACTIVE_SESSION_PK:t=>`${De.USER}${t}`,ACTIVE_SESSION_SK:(t,e)=>`${t}${Cr}${e}`,USER_SESSION_PK:t=>`${De.USER}${t}`,USER_SESSION_SK:(t,e)=>`${t}${Cr}${e}`,USER_STATUS_PK:t=>{let e=t===Hi.ACTIVE?"ACTIVE":"INACTIVE";return`${iv.USER}${Cr}${e}`},USER_STATUS_SK:t=>t,USER_PROVIDER_PK:t=>`${De.USER}${t}`,USER_PROVIDER_SK:(t,e)=>`${_t.PROVIDER}${t}${Cr}${e}`,INVITE_TENANT_PK:t=>`${De.TENANT}${t}`,INVITE_TENANT_SK:(t,e,r)=>`${t}${Cr}${e}${Cr}${r}`,INVITE_TENANT_STATUS_PREFIX:t=>`${t}${Cr}`,USER_TENANT_PK:t=>`${De.USER}${t}`,USER_TENANT_SK:(t,e,r,n)=>`${t}${Cr}${e??"ROOT"}${Cr}${r}${Cr}${n}`},E={PK:"PK",SK:"SK",TTL:"TTL",ACTIVE_SESSION_PK:"activeSessionPk",ACTIVE_SESSION_SK:"activeSessionSk",USER_SESSION_PK:"userSessionPk",USER_SESSION_SK:"userSessionSk",USER_STATUS_PK:"userStatusPk",USER_STATUS_SK:"userStatusSk",USER_PROVIDER_PK:"userProviderPk",USER_PROVIDER_SK:"userProviderSk",USER_ID:"userId",TENANT_ID:"tenantId",TENANT_TYPE:"tenantType",AUDIENCE:"audience",PURPOSE:"purpose",CHALLENGE_STATUS:"challengeStatus",PHASE:"phase",ALLOWED_METHODS:"allowedMethods",METHOD:"method",IDENTITY_TYPE:"identityType",IDENTITY_VALUE:"identityValue",CODE_HASH:"codeHash",ATTEMPTS:"attempts",MAX_ATTEMPTS:"maxAttempts",METADATA:"metadata",FLOW_KEY:"flowKey",EXPIRES_AT:"expiresAt",CREATED_AT:"createdAt",TOKEN_ID:"tokenId",PREVIOUS_TOKEN_ID:"previousTokenId",ROTATED_AT:"rotatedAt",LAST_USED_AT:"lastUsedAt",REVOKED_AT:"revokedAt",ROLE:"role",ROLES:"roles",PERM:"perm",AUTH_PERM:"authPerm",IS_OWNER:"isOwner",DEVICE_LABEL:"deviceLabel",COUNTRY:"country",CITY:"city",IDENTITY_USER_PK:"identityUserPk",IDENTITY_USER_SK:"identityUserSk",LOGIN_ENABLED:"loginEnabled",VERIFIED_AT:"verifiedAt",GUARDS:"guards",PENDING_VERIFICATION:"pendingVerification",UPDATED_AT:"updatedAt",CREDENTIAL_USER_PK:"credentialUserPk",CREDENTIAL_USER_SK:"credentialUserSk",CREDENTIAL_VALUE:"value",INVITE_STATUS:"inviteStatus",INVITE_TOKEN:"inviteToken",INVITED_BY_ID:"invitedById",INVITED_BY_INFO:"invitedByInfo",INVITEE_USER_ID:"inviteeUserId",INVITEE_EMAIL:"inviteeEmail",INVITEE_PHONE:"inviteePhone",ACCEPTED_AT:"acceptedAt",DECLINED_AT:"declinedAt",INVITE_TENANT_PK:"inviteTenantPk",INVITE_TENANT_SK:"inviteTenantSk",INVITE_TOKEN_GSI:"inviteTokenGsi",INVITEE_EMAIL_GSI:"inviteeEmailGsi",INVITEE_EMAIL_TENANT_SK:"inviteeEmailTenantSk",INVITEE_PHONE_GSI:"inviteePhoneGsi",INVITEE_PHONE_TENANT_SK:"inviteePhoneTenantSk",USER_TENANT_PK:"userTenantPk",USER_TENANT_SK:"userTenantSk",DISPLAY_NAME:"displayName",AVATAR_URL:"avatarUrl",TITLE:"title",BIO:"bio"},tt={ACTIVE_SESSIONS:"GSI_ActiveSessions",USER_SESSIONS:"GSI_UserSessions",USERS_BY_STATUS:"GSI_UsersByStatus",USER_PROVIDERS:"GSI_UserProviders",USER_IDENTITIES:"GSI_UserIdentities",USER_CREDENTIALS:"GSI_UserCredentials",TENANT_INVITES:"GSI_TenantInvites",INVITE_TOKEN:"GSI_InviteToken",INVITEE_EMAIL:"GSI_InviteeEmail",INVITEE_PHONE:"GSI_InviteePhone",USER_TENANTS:"GSI_UserTenants"},q_={sessionSK:(t,e)=>`${t instanceof Date?t.getTime():t}${Cr}${e}`,extractCreatedAt:t=>{let e=t.indexOf(Cr),r=e===-1?t:t.slice(0,e);return Number(r)}};var Po=ge(ir(),1);function Vf(t){if(typeof t=="object"&&t!==null&&"name"in t){let{name:e}=t;return typeof e=="string"?e:void 0}}function lt(t){return Vf(t)==="ConditionalCheckFailedException"}var Hf=class{docClient;tableName;ttlGracePeriod;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||3600*1e3}generateChallengeId(){return Lt()}async get(e){try{let r=await this.docClient.send(new Po.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.CHALLENGE_PK(e),[E.SK]:K.CHALLENGE_SK()}}));if(!r.Item)return w(null);let n=this.unmarshall(r.Item);return tv(Te(n.expiresAt))?w(null):w(n)}catch{return T(N.DatabaseQueryError({query:"get challenge"}))}}async create(e){try{let r=Ne(),n=e.id||this.generateChallengeId(),i={...e,id:n,createdAt:oe(r)},s=Te(e.expiresAt),o=Math.floor((s+this.ttlGracePeriod)/1e3);return await this.docClient.send(new Po.PutCommand({TableName:this.tableName,Item:this.marshall(i,o)})),w(i)}catch{return T(N.DatabaseQueryError({query:"create challenge"}))}}async update(e,r){try{let n=[],i={},s={};return r.method!==void 0&&(n.push("#method = :method"),i["#method"]=E.METHOD,s[":method"]=r.method),r.phase!==void 0&&(n.push("#phase = :phase"),i["#phase"]=E.PHASE,s[":phase"]=r.phase),r.codeHash!==void 0&&(n.push("#codeHash = :codeHash"),i["#codeHash"]=E.CODE_HASH,s[":codeHash"]=r.codeHash),r.status!==void 0&&(n.push("#challengeStatus = :challengeStatus"),i["#challengeStatus"]=E.CHALLENGE_STATUS,s[":challengeStatus"]=r.status),n.length===0?w(void 0):(await this.docClient.send(new Po.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.CHALLENGE_PK(e),[E.SK]:K.CHALLENGE_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:i,ExpressionAttributeValues:s})),w(void 0))}catch{return T(N.DatabaseQueryError({query:"update challenge"}))}}async incrementAttempts(e,r){let n={":zero":0,":inc":1},i;r!==void 0&&(i="attribute_not_exists(#attempts) OR #attempts < :max",n[":max"]=r);try{let o=(await this.docClient.send(new Po.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.CHALLENGE_PK(e),[E.SK]:K.CHALLENGE_SK()},UpdateExpression:"SET #attempts = if_not_exists(#attempts, :zero) + :inc",...i?{ConditionExpression:i}:{},ExpressionAttributeNames:{"#attempts":E.ATTEMPTS},ExpressionAttributeValues:n,ReturnValues:"UPDATED_NEW"}))).Attributes?.[E.ATTEMPTS]??0;return w(o)}catch(s){return lt(s)?T(N.AttemptsExceeded()):T(N.DatabaseQueryError({query:"increment challenge attempts"}))}}async remove(e){try{return await this.docClient.send(new Po.DeleteCommand({TableName:this.tableName,Key:{[E.PK]:K.CHALLENGE_PK(e),[E.SK]:K.CHALLENGE_SK()},ConditionExpression:"attribute_exists(#pk)",ExpressionAttributeNames:{"#pk":E.PK}})),w(void 0)}catch(r){return lt(r)?w(void 0):T(N.DatabaseQueryError({query:"remove challenge"}))}}marshall(e,r){let n={[E.PK]:K.CHALLENGE_PK(e.id),[E.SK]:K.CHALLENGE_SK(),[E.USER_ID]:e.userId,[E.PURPOSE]:e.purpose,[E.CHALLENGE_STATUS]:e.status,[E.EXPIRES_AT]:Te(e.expiresAt),[E.CREATED_AT]:Te(e.createdAt),[E.TTL]:r};return e.tenantId&&(n[E.TENANT_ID]=e.tenantId),e.phase&&(n[E.PHASE]=e.phase),e.allowedMethods&&e.allowedMethods.length>0&&(n[E.ALLOWED_METHODS]=e.allowedMethods),e.method&&(n[E.METHOD]=e.method),e.codeHash&&(n[E.CODE_HASH]=e.codeHash),e.attempts!==void 0&&(n[E.ATTEMPTS]=e.attempts),e.maxAttempts!==void 0&&(n[E.MAX_ATTEMPTS]=e.maxAttempts),e.identityType&&(n[E.IDENTITY_TYPE]=e.identityType),e.identityValue&&(n[E.IDENTITY_VALUE]=e.identityValue),e.deviceLabel&&(n[E.DEVICE_LABEL]=e.deviceLabel),e.country&&(n[E.COUNTRY]=e.country),e.city&&(n[E.CITY]=e.city),e.metadata&&(n[E.METADATA]=e.metadata),e.flowKey&&(n[E.FLOW_KEY]=e.flowKey),n}unmarshall(e){let n={id:ve.challengeIdFromPK(e[E.PK]),userId:e[E.USER_ID],purpose:e[E.PURPOSE],status:e[E.CHALLENGE_STATUS],expiresAt:oe(e[E.EXPIRES_AT]),createdAt:oe(e[E.CREATED_AT])};return e[E.TENANT_ID]&&(n.tenantId=e[E.TENANT_ID]),e[E.PHASE]&&(n.phase=e[E.PHASE]),e[E.ALLOWED_METHODS]&&(n.allowedMethods=e[E.ALLOWED_METHODS]),e[E.METHOD]&&(n.method=e[E.METHOD]),e[E.CODE_HASH]&&(n.codeHash=e[E.CODE_HASH]),e[E.ATTEMPTS]!==void 0&&(n.attempts=e[E.ATTEMPTS]),e[E.MAX_ATTEMPTS]!==void 0&&(n.maxAttempts=e[E.MAX_ATTEMPTS]),e[E.IDENTITY_TYPE]&&(n.identityType=e[E.IDENTITY_TYPE]),e[E.IDENTITY_VALUE]&&(n.identityValue=e[E.IDENTITY_VALUE]),e[E.DEVICE_LABEL]&&(n.deviceLabel=e[E.DEVICE_LABEL]),e[E.COUNTRY]&&(n.country=e[E.COUNTRY]),e[E.CITY]&&(n.city=e[E.CITY]),e[E.METADATA]&&(n.metadata=e[E.METADATA]),e[E.FLOW_KEY]&&(n.flowKey=e[E.FLOW_KEY]),n}};var en=ge(ir(),1);var Gf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateCredentialId(){return Lt()}async get(e){try{let r=await this.docClient.send(new en.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.CREDENTIAL_PK(e),[E.SK]:K.CREDENTIAL_SK()}}));return r.Item?w(this.unmarshall(r.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"get credential"}))}}async getByUserIdAndType(e,r){try{let n=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:tt.USER_CREDENTIALS,KeyConditionExpression:`${E.CREDENTIAL_USER_PK} = :userPk AND begins_with(${E.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":K.USER_PK(e),":typePrefix":K.CREDENTIAL_TYPE_PREFIX(r)},Limit:1}));if(!n.Items||n.Items.length===0)return w(null);let i=n.Items[0];if(!i)return w(null);let s=ve.credentialId(i[E.PK]);return this.get(s)}catch{return T(N.DatabaseQueryError({query:"get credential by user and type"}))}}async getByUserId(e){try{let r=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:tt.USER_CREDENTIALS,KeyConditionExpression:`${E.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":K.USER_PK(e)}}));if(!r.Items||r.Items.length===0)return w([]);let n=r.Items.map(o=>ve.credentialId(o[E.PK])),i=await this.batchGet(n);if(i.ok===!1)return T(i.errors,i.meta);if(!i.data)return w([]);let s=i.data.filter(o=>o!==null);return w(s)}catch{return T(N.DatabaseQueryError({query:"get credentials by user"}))}}async create(e){try{let r=Ne(),n=this.generateCredentialId(),i={revokedAt:null,lastUsedAt:null,...e,id:n,createdAt:new Date(r),updatedAt:new Date(r)};return await this.docClient.send(new en.PutCommand({TableName:this.tableName,Item:this.marshall(i),ConditionExpression:`attribute_not_exists(${E.PK})`})),w(i)}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"credential"})):T(N.DatabaseQueryError({query:"create credential"}))}}async update(e,r){try{let n=Ne(),i=[],s={},o={};return i.push(`#${E.UPDATED_AT} = :updatedAt`),s[`#${E.UPDATED_AT}`]=E.UPDATED_AT,o[":updatedAt"]=n,r.value!==void 0&&(i.push(`#${E.CREDENTIAL_VALUE} = :value`),s[`#${E.CREDENTIAL_VALUE}`]=E.CREDENTIAL_VALUE,o[":value"]=r.value),r.data!==void 0&&(i.push(`#${E.METADATA} = :data`),s[`#${E.METADATA}`]=E.METADATA,o[":data"]=r.data),r.revokedAt!==void 0&&(i.push(`#${E.REVOKED_AT} = :revokedAt`),s[`#${E.REVOKED_AT}`]=E.REVOKED_AT,o[":revokedAt"]=r.revokedAt?Te(r.revokedAt):null),r.lastUsedAt!==void 0&&(i.push(`#${E.LAST_USED_AT} = :lastUsedAt`),s[`#${E.LAST_USED_AT}`]=E.LAST_USED_AT,o[":lastUsedAt"]=r.lastUsedAt?Te(r.lastUsedAt):null),await this.docClient.send(new en.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.CREDENTIAL_PK(e),[E.SK]:K.CREDENTIAL_SK()},UpdateExpression:`SET ${i.join(", ")}`,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"credential",id:e})):T(N.DatabaseQueryError({query:"update credential"}))}}async remove(e){try{return await this.docClient.send(new en.DeleteCommand({TableName:this.tableName,Key:{[E.PK]:K.CREDENTIAL_PK(e),[E.SK]:K.CREDENTIAL_SK()},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(r){return lt(r)?T(N.NotFound({entity:"credential",id:e})):T(N.DatabaseQueryError({query:"delete credential"}))}}async hasType(e,r){try{let n=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:tt.USER_CREDENTIALS,KeyConditionExpression:`${E.CREDENTIAL_USER_PK} = :userPk AND begins_with(${E.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":K.USER_PK(e),":typePrefix":K.CREDENTIAL_TYPE_PREFIX(r)},Select:"COUNT",Limit:1}));return w((n.Count||0)>0)}catch{return T(N.DatabaseQueryError({query:"check credential type"}))}}async countByUserId(e){try{let r=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:tt.USER_CREDENTIALS,KeyConditionExpression:`${E.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":K.USER_PK(e)},Select:"COUNT"}));return w(r.Count||0)}catch{return T(N.DatabaseQueryError({query:"count credentials"}))}}async batchGet(e){if(e.length===0)return w([]);try{let r=[];for(let i=0;i<e.length;i+=100)r.push(e.slice(i,i+100));let n=[];for(let i of r){let o=(await this.docClient.send(new en.BatchGetCommand({RequestItems:{[this.tableName]:{Keys:i.map(c=>({[E.PK]:K.CREDENTIAL_PK(c),[E.SK]:K.CREDENTIAL_SK()}))}}}))).Responses?.[this.tableName]||[],a=new Map;for(let c of o){let u=this.unmarshall(c);a.set(u.id,u)}for(let c of i)n.push(a.get(c)||null)}return w(n)}catch{return T(N.DatabaseQueryError({query:"batch get credentials"}))}}marshall(e){let r={[E.PK]:K.CREDENTIAL_PK(e.id),[E.SK]:K.CREDENTIAL_SK(),[E.CREDENTIAL_USER_PK]:K.USER_PK(e.userId),[E.CREDENTIAL_USER_SK]:K.CREDENTIAL_USER_SK(e.type,e.id),[E.USER_ID]:e.userId,[E.CREDENTIAL_VALUE]:e.value,[E.METADATA]:e.data,[E.REVOKED_AT]:e.revokedAt?Te(e.revokedAt):null,[E.CREATED_AT]:Te(e.createdAt),[E.UPDATED_AT]:Te(e.updatedAt)};return e.lastUsedAt&&(r[E.LAST_USED_AT]=Te(e.lastUsedAt)),r}unmarshall(e){let r=ve.credentialId(e[E.PK]),n=ve.credentialTypeFromUserSK(e[E.CREDENTIAL_USER_SK]);return{id:r,userId:e[E.USER_ID],type:n,value:e[E.CREDENTIAL_VALUE],data:e[E.METADATA]||{},revokedAt:Xr(e[E.REVOKED_AT]),createdAt:oe(e[E.CREATED_AT]),updatedAt:oe(e[E.UPDATED_AT]),lastUsedAt:Xr(e[E.LAST_USED_AT])}}};var Tn=ge(ir(),1);function sv(t){return{failedAttempts:t.failedAttempts,lastFailedAt:Ui(t.lastFailedAt),lockedUntil:Ui(t.lockedUntil)}}function s8(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t))e[r]={failedAttempts:n.failedAttempts??0,lastFailedAt:Xr(n.lastFailedAt),lockedUntil:Xr(n.lockedUntil)};return e}function o8(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t))n&&(e[r]=sv(n));return e}var qf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async get(e,r){try{let n=await this.docClient.send(new Tn.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.IDENTITY_PK(e,r),[E.SK]:K.IDENTITY_SK()}}));if(!n.Item)return w(null);let i=this.unmarshall(n.Item);return w(i)}catch(n){return console.error("[DynamoDB] identities.get error:",n),T(N.DatabaseQueryError({query:"get identity"}))}}async getByUserId(e){try{let r=await this.docClient.send(new Tn.QueryCommand({TableName:this.tableName,IndexName:tt.USER_IDENTITIES,KeyConditionExpression:`${E.IDENTITY_USER_PK} = :pk`,ExpressionAttributeValues:{":pk":K.USER_INDEX_PK(e)}})),n=[];for(let i of r.Items||[]){let s=this.unmarshall(i);s!==null&&n.push(s)}return w(n)}catch{return T(N.DatabaseQueryError({query:"get identities by userId"}))}}async create(e){try{let r=Ne(),n={...e,createdAt:oe(r),updatedAt:oe(r)};return await this.docClient.send(new Tn.PutCommand({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:"attribute_not_exists(PK)"})),w(n)}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"identity"})):T(N.DatabaseQueryError({query:"create identity"}))}}async update(e,r,n){try{let i=[],s=[],o={},a={};if(n.loginEnabled!==void 0&&(i.push("#loginEnabled = :loginEnabled"),o["#loginEnabled"]=E.LOGIN_ENABLED,a[":loginEnabled"]=n.loginEnabled),n.verifiedAt!==void 0){let u=Ui(n.verifiedAt);u===null?(s.push("#verifiedAt"),o["#verifiedAt"]=E.VERIFIED_AT):(i.push("#verifiedAt = :verifiedAt"),o["#verifiedAt"]=E.VERIFIED_AT,a[":verifiedAt"]=u)}n.guards!==void 0&&(i.push("#guards = :guards"),o["#guards"]=E.GUARDS,a[":guards"]=o8(n.guards)),n.pendingVerification!==void 0&&(o["#pendingVerification"]=E.PENDING_VERIFICATION,n.pendingVerification===null?s.push("#pendingVerification"):(i.push("#pendingVerification = :pendingVerification"),a[":pendingVerification"]=Zr({...n.pendingVerification,expiresAt:Te(n.pendingVerification.expiresAt),resendAvailableAt:Ui(n.pendingVerification.resendAvailableAt)}))),i.push("#updatedAt = :updatedAt"),o["#updatedAt"]=E.UPDATED_AT,a[":updatedAt"]=Ne();let c=[];return i.length>0&&c.push(`SET ${i.join(", ")}`),s.length>0&&c.push(`REMOVE ${s.join(", ")}`),await this.docClient.send(new Tn.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.IDENTITY_PK(e,r),[E.SK]:K.IDENTITY_SK()},UpdateExpression:c.join(" "),ExpressionAttributeNames:o,ExpressionAttributeValues:a})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"update identity"}))}}async remove(e,r){try{return await this.docClient.send(new Tn.DeleteCommand({TableName:this.tableName,Key:{[E.PK]:K.IDENTITY_PK(e,r),[E.SK]:K.IDENTITY_SK()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"remove identity"}))}}async updateGuard(e,r,n,i){let s={[E.PK]:K.IDENTITY_PK(e,r),[E.SK]:K.IDENTITY_SK()};try{return await this.docClient.send(new Tn.UpdateCommand({TableName:this.tableName,Key:s,UpdateExpression:"SET #guards.#guardKey = :guard, #updatedAt = :updatedAt",ConditionExpression:"attribute_exists(#guards)",ExpressionAttributeNames:{"#guards":E.GUARDS,"#guardKey":n,"#updatedAt":E.UPDATED_AT},ExpressionAttributeValues:{":guard":sv(i),":updatedAt":Ne()}})),w(void 0)}catch(o){if(lt(o))try{return await this.docClient.send(new Tn.UpdateCommand({TableName:this.tableName,Key:s,UpdateExpression:"SET #guards = :guards, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#guards":E.GUARDS,"#updatedAt":E.UPDATED_AT},ExpressionAttributeValues:{":guards":{[n]:sv(i)},":updatedAt":Ne()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"update guard"}))}return T(N.DatabaseQueryError({query:"update guard"}))}}async batchGet(e){try{if(e.length===0)return w([]);let n=(await this.docClient.send(new Tn.BatchGetCommand({RequestItems:{[this.tableName]:{Keys:e.map(({type:o,value:a})=>({[E.PK]:K.IDENTITY_PK(o,a),[E.SK]:K.IDENTITY_SK()}))}}}))).Responses?.[this.tableName]||[],i=new Map;for(let o of n){let a=this.unmarshall(o);if(a!==null){let c=`${a.type}#${a.value}`;i.set(c,a)}}let s=e.map(({type:o,value:a})=>{let c=`${o}#${a}`;return i.get(c)||null});return w(s)}catch{return T(N.DatabaseQueryError({query:"batch get identities"}))}}marshall(e){let r={[E.PK]:K.IDENTITY_PK(e.type,e.value),[E.SK]:K.IDENTITY_SK(),[E.IDENTITY_USER_PK]:K.USER_INDEX_PK(e.userId),[E.IDENTITY_USER_SK]:K.USER_INDEX_SK(e.type,e.value),[E.USER_ID]:e.userId,[E.LOGIN_ENABLED]:e.loginEnabled,[E.CREATED_AT]:Te(e.createdAt),[E.UPDATED_AT]:Te(e.updatedAt)},n=Ui(e.verifiedAt);return n!==null&&(r[E.VERIFIED_AT]=n),r[E.GUARDS]=o8(e.guards),e.pendingVerification&&(r[E.PENDING_VERIFICATION]=Zr({...e.pendingVerification,expiresAt:Te(e.pendingVerification.expiresAt),resendAvailableAt:Ui(e.pendingVerification.resendAvailableAt)})),r}unmarshall(e){let r=ve.identityPKInfo(e[E.PK]);if(!r){let n=e[E.IDENTITY_USER_SK]?ve.userIndexSKInfo(e[E.IDENTITY_USER_SK]):null;return n?{type:n.type,value:n.value,userId:e[E.USER_ID],loginEnabled:e[E.LOGIN_ENABLED],verifiedAt:Xr(e[E.VERIFIED_AT]),guards:s8(e[E.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[E.PENDING_VERIFICATION]),createdAt:oe(e[E.CREATED_AT]),updatedAt:oe(e[E.UPDATED_AT])}:(console.warn("Invalid identity item format, skipping:",{PK:e[E.PK],GSI1SK:e[E.IDENTITY_USER_SK]}),null)}return{type:r.type,value:r.value,userId:e[E.USER_ID],loginEnabled:e[E.LOGIN_ENABLED],verifiedAt:Xr(e[E.VERIFIED_AT]),guards:s8(e[E.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[E.PENDING_VERIFICATION]),createdAt:oe(e[E.CREATED_AT]),updatedAt:oe(e[E.UPDATED_AT])}}unmarshallPendingVerification(e){if(!e||typeof e!="object")return null;let r=e;return{challengeId:r.challengeId,purpose:r.purpose,channel:r.channel,expiresAt:oe(r.expiresAt),resendAvailableAt:Xr(r.resendAvailableAt)}}};var a8=ge(ir(),1);var Wf=class{docClient;tableName;ttlGracePeriod;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||3600*1e3}async createEmailVerificationRegistration(e){try{let r=Ne(),n=Lt(),i=Te(e.challenge.expiresAt),s=Math.floor((i+this.ttlGracePeriod)/1e3);return await this.docClient.send(new a8.TransactWriteCommand({TransactItems:[this.putItem(this.marshallProfile(e,r)),this.putItem(this.marshallUserAuth(e,r)),this.putItem(this.marshallIdentity(e,r)),this.putItem(this.marshallCredential(e,n,r)),this.putItem(this.marshallChallenge(e,r,s))]})),w(void 0)}catch(r){return Vf(r)==="TransactionCanceledException"||lt(r)?T(N.UniqueConstraintViolation({field:"registration"})):T(N.DatabaseQueryError({query:"create email verification registration transaction"}))}}putItem(e){return{Put:{TableName:this.tableName,Item:Zr(e),ConditionExpression:`attribute_not_exists(${E.PK})`}}}marshallProfile(e,r){let n=e.profile.status,i={[E.PK]:K.USER_PK(e.profile.id),[E.SK]:K.USER_PROFILE_SK(),userStatus:n,[E.CREATED_AT]:r,[E.UPDATED_AT]:r,[E.USER_STATUS_PK]:ze.USER_STATUS_PK(n),[E.USER_STATUS_SK]:ze.USER_STATUS_SK(e.profile.id)};return e.profile.contactEmail&&(i.contactEmail=e.profile.contactEmail),e.profile.contactPhone&&(i.contactPhone=e.profile.contactPhone),e.profile.username&&(i.username=e.profile.username),e.profile.displayName&&(i.displayName=e.profile.displayName),e.profile.givenName&&(i.givenName=e.profile.givenName),e.profile.familyName&&(i.familyName=e.profile.familyName),e.profile.avatarUrl&&(i.avatarUrl=e.profile.avatarUrl),e.profile.locale&&(i.locale=e.profile.locale),e.profile.metadata&&(i.metadata=JSON.stringify(e.profile.metadata)),i}marshallUserAuth(e,r){return{[E.PK]:K.USER_PK(e.userAuth.userId),[E.SK]:K.USER_AUTH_SK(),userStatus:e.userAuth.userStatus,mfaRequired:e.userAuth.mfaRequired,mfaMethods:e.userAuth.mfaMethods,[E.CREATED_AT]:r,[E.UPDATED_AT]:r}}marshallIdentity(e,r){let n=e.identity,i={[E.PK]:K.IDENTITY_PK(n.type,n.value),[E.SK]:K.IDENTITY_SK(),[E.IDENTITY_USER_PK]:K.USER_INDEX_PK(n.userId),[E.IDENTITY_USER_SK]:K.USER_INDEX_SK(n.type,n.value),[E.USER_ID]:n.userId,[E.LOGIN_ENABLED]:n.loginEnabled,[E.CREATED_AT]:r,[E.UPDATED_AT]:r,[E.PENDING_VERIFICATION]:Zr({...n.pendingVerification,expiresAt:Te(n.pendingVerification.expiresAt),resendAvailableAt:Ui(n.pendingVerification.resendAvailableAt)})},s=Ui(n.verifiedAt);return s!==null&&(i[E.VERIFIED_AT]=s),i[E.GUARDS]=n.guards??{},i}marshallCredential(e,r,n){let i=e.credential,s={[E.PK]:K.CREDENTIAL_PK(r),[E.SK]:K.CREDENTIAL_SK(),[E.CREDENTIAL_USER_PK]:K.USER_PK(i.userId),[E.CREDENTIAL_USER_SK]:K.CREDENTIAL_USER_SK(i.type,r),[E.USER_ID]:i.userId,[E.CREDENTIAL_VALUE]:i.value,[E.METADATA]:i.data,[E.REVOKED_AT]:i.revokedAt?Te(i.revokedAt):null,[E.CREATED_AT]:n,[E.UPDATED_AT]:n};return i.lastUsedAt&&(s[E.LAST_USED_AT]=Te(i.lastUsedAt)),s}marshallChallenge(e,r,n){let i=e.challenge,s={[E.PK]:K.CHALLENGE_PK(i.id),[E.SK]:K.CHALLENGE_SK(),[E.USER_ID]:i.userId,[E.PURPOSE]:i.purpose,[E.CHALLENGE_STATUS]:i.status,[E.EXPIRES_AT]:Te(i.expiresAt),[E.CREATED_AT]:r,[E.TTL]:n};return i.tenantId&&(s[E.TENANT_ID]=i.tenantId),i.phase&&(s[E.PHASE]=i.phase),i.allowedMethods&&i.allowedMethods.length>0&&(s[E.ALLOWED_METHODS]=i.allowedMethods),i.method&&(s[E.METHOD]=i.method),i.codeHash&&(s[E.CODE_HASH]=i.codeHash),i.attempts!==void 0&&(s[E.ATTEMPTS]=i.attempts),i.maxAttempts!==void 0&&(s[E.MAX_ATTEMPTS]=i.maxAttempts),i.identityType&&(s[E.IDENTITY_TYPE]=i.identityType),i.identityValue&&(s[E.IDENTITY_VALUE]=i.identityValue),i.deviceLabel&&(s[E.DEVICE_LABEL]=i.deviceLabel),i.country&&(s[E.COUNTRY]=i.country),i.city&&(s[E.CITY]=i.city),i.metadata&&(s[E.METADATA]=i.metadata),i.flowKey&&(s[E.FLOW_KEY]=i.flowKey),s}};var d8=ge(v_(),1),Zt=ge(ir(),1);var l8=ge(ir(),1),c8=100,u8=5;function Ege(t){return new Promise(e=>setTimeout(e,t))}async function Sl(t,e,r){if(r.length===0)return[];let n=[];for(let i=0;i<r.length;i+=c8){let s=r.slice(i,i+c8),o=0;for(;s.length>0;){let a=await t.send(new l8.BatchGetCommand({RequestItems:{[e]:{Keys:s}}})),c=a.Responses?.[e];c&&n.push(...c);let u=a.UnprocessedKeys?.[e]?.Keys;if(!u||u.length===0)break;if(o+=1,o>u8)throw new Error(`BatchGet left ${u.length} unprocessed keys after ${u8} retries`);s=u,await Ege(2**o*25)}}return n}var jf=class{docClient;tableName;ttlGracePeriod;constructor(e){let r=e.client||new d8.DynamoDBClient({});this.docClient=e.docClient||Zt.DynamoDBDocumentClient.from(r),this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||10080*60*1e3}generateSessionId(){return Lt()}generateTokenId(){return Lt()}async get(e){try{let r=await this.docClient.send(new Zt.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()}}));return r.Item?w(this.unmarshall(r.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"get session"}))}}async create(e){try{let r=Ne(),n=e.id||this.generateSessionId(),i=e.tokenId||this.generateTokenId(),s={...e,id:n,tokenId:i,revokedAt:null,createdAt:new Date(r),lastUsedAt:new Date(r)},o=Kf(Te(e.expiresAt)+this.ttlGracePeriod),a=q_.sessionSK(r,n);return await this.docClient.send(new Zt.PutCommand({TableName:this.tableName,Item:this.marshall(s,o,a)})),w(s)}catch{return T(N.DatabaseQueryError({query:"create session"}))}}async update(e,r){try{let n=[],i={},s={};if(r.tokenId!==void 0&&(n.push(`#${E.TOKEN_ID} = :tokenId`),i[`#${E.TOKEN_ID}`]=E.TOKEN_ID,s[":tokenId"]=r.tokenId),r.expiresAt!==void 0){n.push(`#${E.EXPIRES_AT} = :expiresAt`),i[`#${E.EXPIRES_AT}`]=E.EXPIRES_AT,s[":expiresAt"]=Te(r.expiresAt);let o=Kf(Te(r.expiresAt)+this.ttlGracePeriod);n.push(`#${E.TTL} = :ttl`),i[`#${E.TTL}`]=E.TTL,s[":ttl"]=o}return r.lastUsedAt!==void 0&&(n.push(`#${E.LAST_USED_AT} = :lastUsedAt`),i[`#${E.LAST_USED_AT}`]=E.LAST_USED_AT,s[":lastUsedAt"]=Te(r.lastUsedAt)),r.metadata!==void 0&&(n.push(`#${E.METADATA} = :metadata`),i[`#${E.METADATA}`]=E.METADATA,s[":metadata"]=r.metadata),r.previousTokenId!==void 0&&(n.push(`#${E.PREVIOUS_TOKEN_ID} = :previousTokenId`),i[`#${E.PREVIOUS_TOKEN_ID}`]=E.PREVIOUS_TOKEN_ID,s[":previousTokenId"]=r.previousTokenId),r.rotatedAt!==void 0&&(n.push(`#${E.ROTATED_AT} = :rotatedAt`),i[`#${E.ROTATED_AT}`]=E.ROTATED_AT,s[":rotatedAt"]=r.rotatedAt),n.length===0?w():(await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:i,ExpressionAttributeValues:s})),w())}catch{return T(N.DatabaseQueryError({query:"update session"}))}}async rotateToken(e,r,n){try{let i=Kf(Te(n.expiresAt)+this.ttlGracePeriod);return await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET #${E.TOKEN_ID} = :tokenId, #${E.PREVIOUS_TOKEN_ID} = :previousTokenId, #${E.ROTATED_AT} = :rotatedAt, #${E.EXPIRES_AT} = :expiresAt, #${E.LAST_USED_AT} = :lastUsedAt, #${E.TTL} = :ttl`,ConditionExpression:`#${E.TOKEN_ID} = :expectedCurrentTokenId`,ExpressionAttributeNames:{[`#${E.TOKEN_ID}`]:E.TOKEN_ID,[`#${E.PREVIOUS_TOKEN_ID}`]:E.PREVIOUS_TOKEN_ID,[`#${E.ROTATED_AT}`]:E.ROTATED_AT,[`#${E.EXPIRES_AT}`]:E.EXPIRES_AT,[`#${E.LAST_USED_AT}`]:E.LAST_USED_AT,[`#${E.TTL}`]:E.TTL},ExpressionAttributeValues:{":tokenId":n.tokenId,":previousTokenId":n.previousTokenId,":rotatedAt":n.rotatedAt,":expiresAt":Te(n.expiresAt),":lastUsedAt":Te(n.lastUsedAt),":ttl":i,":expectedCurrentTokenId":r}})),w(!0)}catch(i){return lt(i)?w(!1):T(N.DatabaseQueryError({query:"rotate session token"}))}}async switchTenant(e,r){try{let n=[`#${E.TENANT_ID} = :tenantId`,`#${E.TOKEN_ID} = :tokenId`,`#${E.LAST_USED_AT} = :lastUsedAt`],i=[],s={[`#${E.TENANT_ID}`]:E.TENANT_ID,[`#${E.TOKEN_ID}`]:E.TOKEN_ID,[`#${E.LAST_USED_AT}`]:E.LAST_USED_AT},o={":tenantId":r.tenantId,":tokenId":r.tokenId,":lastUsedAt":Ne()};s[`#${E.TENANT_TYPE}`]=E.TENANT_TYPE,r.tenantType!==void 0?(n.push(`#${E.TENANT_TYPE} = :tenantType`),o[":tenantType"]=r.tenantType):i.push(`#${E.TENANT_TYPE}`),s[`#${E.PERM}`]=E.PERM,r.perms!==void 0?(n.push(`#${E.PERM} = :perms`),o[":perms"]=JSON.stringify(r.perms)):i.push(`#${E.PERM}`),s[`#${E.ROLES}`]=E.ROLES,r.roles!==void 0?(n.push(`#${E.ROLES} = :roles`),o[":roles"]=r.roles):i.push(`#${E.ROLES}`),s["#revokedAt"]=E.REVOKED_AT;let a=`SET ${n.join(", ")}${i.length>0?` REMOVE ${i.join(", ")}`:""}`;return await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:a,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:`attribute_exists(${E.PK}) AND attribute_not_exists(#revokedAt)`})),w()}catch(n){return lt(n)?T(N.DatabaseQueryError({query:"switch tenant - session not found or revoked"})):T(N.DatabaseQueryError({query:"switch tenant"}))}}async revoke(e){try{return await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET #${E.REVOKED_AT} = :revokedAt REMOVE #${E.ACTIVE_SESSION_PK}, #${E.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${E.REVOKED_AT}`]:E.REVOKED_AT,[`#${E.ACTIVE_SESSION_PK}`]:E.ACTIVE_SESSION_PK,[`#${E.ACTIVE_SESSION_SK}`]:E.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":Te(new Date)},ConditionExpression:`attribute_exists(${E.PK})`})),w()}catch(r){return lt(r)?w():T(N.DatabaseQueryError({query:"revoke session"}))}}async revokeByIdAndUserId(e,r){try{return await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET #${E.REVOKED_AT} = :revokedAt REMOVE #${E.ACTIVE_SESSION_PK}, #${E.ACTIVE_SESSION_SK}`,ConditionExpression:`#${E.USER_ID} = :userId AND attribute_not_exists(#${E.REVOKED_AT})`,ExpressionAttributeNames:{[`#${E.REVOKED_AT}`]:E.REVOKED_AT,[`#${E.USER_ID}`]:E.USER_ID,[`#${E.ACTIVE_SESSION_PK}`]:E.ACTIVE_SESSION_PK,[`#${E.ACTIVE_SESSION_SK}`]:E.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":Te(new Date),":userId":r}})),w()}catch(n){return lt(n)?w():T(N.DatabaseQueryError({query:"revoke session by user"}))}}async findByUserId(e,r){try{let n=Math.min(r?.limit||50,100),i;if(r?.cursor)try{i=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))}catch{return T(N.DatabaseQueryError({query:"invalid pagination cursor"}))}let s=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.USER_SESSIONS,KeyConditionExpression:`${E.USER_SESSION_PK} = :userPk`,ExpressionAttributeValues:{":userPk":K.USER_PK(e)},Limit:n,ExclusiveStartKey:i,ScanIndexForward:!1}));if(!s.Items||s.Items.length===0){let y={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!r?.cursor,cursor:null};return w([],{pagination:y})}let a=s.Items.map(y=>ve.sessionId(y[E.PK])).map(y=>({[E.PK]:K.SESSION_PK(y),[E.SK]:K.SESSION_SK()})),u=(await Sl(this.docClient,this.tableName,a)).map(y=>this.unmarshall(y)),p=!!s.LastEvaluatedKey,d=p?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null,h={type:"cursor",limit:n,count:u.length,hasNext:p,hasPrev:!!r?.cursor,cursor:d};return w(u,{pagination:h})}catch{return T(N.DatabaseQueryError({query:"find sessions by user"}))}}async findActiveByUserId(e,r){try{let n=Math.min(r?.limit||50,100),i;if(r?.cursor)try{i=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))}catch{return T(N.DatabaseQueryError({query:"invalid pagination cursor"}))}let s=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.ACTIVE_SESSIONS,KeyConditionExpression:`${E.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":ze.ACTIVE_SESSION_PK(e)},Limit:n,ExclusiveStartKey:i,ScanIndexForward:!1}));if(!s.Items||s.Items.length===0){let y={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!r?.cursor,cursor:null};return w([],{pagination:y})}let a=s.Items.map(y=>ve.sessionId(y[E.PK])).map(y=>({[E.PK]:K.SESSION_PK(y),[E.SK]:K.SESSION_SK()})),u=(await Sl(this.docClient,this.tableName,a)).map(y=>this.unmarshall(y)),p=!!s.LastEvaluatedKey,d=p?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null,h={type:"cursor",limit:n,count:u.length,hasNext:p,hasPrev:!!r?.cursor,cursor:d};return w(u,{pagination:h})}catch{return T(N.DatabaseQueryError({query:"find active sessions by user"}))}}async getActiveSessionsForLimit(e){try{let r=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.ACTIVE_SESSIONS,KeyConditionExpression:`${E.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":ze.ACTIVE_SESSION_PK(e)},ScanIndexForward:!0}));if(!r.Items||r.Items.length===0)return w([]);let n=r.Items.map(i=>{let s=ve.sessionId(i[E.PK]),o=q_.extractCreatedAt(i[E.ACTIVE_SESSION_SK]);return{id:s,createdAt:new Date(o)}});return w(n)}catch{return T(N.DatabaseQueryError({query:"get active sessions for limit"}))}}async revokeSessionsByIds(e,r){if(e.length===0)return 0;let n=Te(new Date),i=await Promise.allSettled(e.map(o=>this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(o),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET #${E.REVOKED_AT} = :revokedAt REMOVE #${E.ACTIVE_SESSION_PK}, #${E.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${E.REVOKED_AT}`]:E.REVOKED_AT,[`#${E.ACTIVE_SESSION_PK}`]:E.ACTIVE_SESSION_PK,[`#${E.ACTIVE_SESSION_SK}`]:E.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":n}})))),s=0;for(let o of i)o.status==="fulfilled"?s+=1:console.error(`[session-repo] ${r}: session revoke failed (may remain active):`,{name:Vf(o.reason)});return s}async revokeAllByUserId(e,r){try{let n=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.ACTIVE_SESSIONS,KeyConditionExpression:`${E.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":ze.ACTIVE_SESSION_PK(e)}}));if(!n.Items||n.Items.length===0)return w(0);let i=n.Items.map(o=>ve.sessionId(o[E.PK])).filter(o=>!r||o!==r),s=await this.revokeSessionsByIds(i,"revokeAllByUserId");return w(s)}catch{return T(N.DatabaseQueryError({query:"revoke all sessions by user"}))}}async revokeBatch(e){try{let r=await this.revokeSessionsByIds(e,"revokeBatch");return w(r)}catch{return T(N.DatabaseQueryError({query:"revoke batch sessions"}))}}async countByUserId(e){try{let r=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.ACTIVE_SESSIONS,KeyConditionExpression:`${E.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":ze.ACTIVE_SESSION_PK(e)},Select:"COUNT"}));return w(r.Count||0)}catch{return T(N.DatabaseQueryError({query:"count active sessions by user"}))}}async isTokenActive(e,r){try{let n=await this.docClient.send(new Zt.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(r),[E.SK]:K.SESSION_SK()},ProjectionExpression:`${E.TOKEN_ID}, ${E.REVOKED_AT}, ${E.EXPIRES_AT}`}));if(!n.Item)return w(!1);let i=n.Item,s=i[E.TOKEN_ID]===e&&!i[E.REVOKED_AT]&&oe(i[E.EXPIRES_AT])>new Date;return w(s)}catch{return T(N.DatabaseQueryError({query:"check token active"}))}}marshall(e,r,n){let i={[E.PK]:K.SESSION_PK(e.id),[E.SK]:K.SESSION_SK(),[E.USER_SESSION_PK]:K.USER_PK(e.userId),[E.USER_SESSION_SK]:n,...!e.revokedAt&&{[E.ACTIVE_SESSION_PK]:ze.ACTIVE_SESSION_PK(e.userId),[E.ACTIVE_SESSION_SK]:n},[E.USER_ID]:e.userId,[E.TOKEN_ID]:e.tokenId,[E.EXPIRES_AT]:Te(e.expiresAt),[E.CREATED_AT]:Te(e.createdAt),[E.LAST_USED_AT]:Te(e.lastUsedAt),[E.TTL]:r};return e.tenantId&&(i[E.TENANT_ID]=e.tenantId),e.tenantType&&(i[E.TENANT_TYPE]=e.tenantType),e.perms!==void 0&&(i[E.PERM]=JSON.stringify(e.perms)),e.roles!==void 0&&(i[E.ROLES]=e.roles),e.deviceLabel&&(i[E.DEVICE_LABEL]=e.deviceLabel),e.country&&(i[E.COUNTRY]=e.country),e.city&&(i[E.CITY]=e.city),e.metadata&&(i[E.METADATA]=e.metadata),e.revokedAt&&(i[E.REVOKED_AT]=Te(e.revokedAt)),e.previousTokenId&&(i[E.PREVIOUS_TOKEN_ID]=e.previousTokenId),e.rotatedAt!==void 0&&(i[E.ROTATED_AT]=e.rotatedAt),i}unmarshall(e){let n={id:ve.sessionId(e[E.PK]),userId:e[E.USER_ID],tokenId:e[E.TOKEN_ID],expiresAt:oe(e[E.EXPIRES_AT]),createdAt:oe(e[E.CREATED_AT]),lastUsedAt:oe(e[E.LAST_USED_AT]),revokedAt:e[E.REVOKED_AT]?oe(e[E.REVOKED_AT]):null};return e[E.TENANT_ID]&&(n.tenantId=e[E.TENANT_ID]),e[E.TENANT_TYPE]&&(n.tenantType=e[E.TENANT_TYPE]),e[E.PERM]!==void 0&&(n.perms=JSON.parse(e[E.PERM])),e[E.ROLES]!==void 0&&(n.roles=e[E.ROLES]),e[E.DEVICE_LABEL]&&(n.deviceLabel=e[E.DEVICE_LABEL]),e[E.COUNTRY]&&(n.country=e[E.COUNTRY]),e[E.CITY]&&(n.city=e[E.CITY]),e[E.METADATA]&&(n.metadata=e[E.METADATA]),e[E.PREVIOUS_TOKEN_ID]&&(n.previousTokenId=e[E.PREVIOUS_TOKEN_ID]),e[E.ROTATED_AT]!==void 0&&(n.rotatedAt=e[E.ROTATED_AT]),n}};var p8=ge(ir(),1);var zf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={"#pk":E.INVITE_TENANT_PK},s={":pk":ze.INVITE_TENANT_PK(e)},o={TableName:this.tableName,IndexName:tt.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:i,ExpressionAttributeValues:s,ScanIndexForward:!1,Limit:n};r?.cursor&&(o.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))),r?.status&&(o.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",i["#sk"]=E.INVITE_TENANT_SK,s[":statusPrefix"]=ze.INVITE_TENANT_STATUS_PREFIX(r.status));let a=await this.docClient.send(new p8.QueryCommand(o)),c=(a.Items||[]).map(d=>this.toListItem(d)),u=!!a.LastEvaluatedKey,p=u?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return gt(c,{limit:n,hasNext:u,cursor:p,prevCursor:r?.cursor??null})}catch(n){return console.error("[DynamoDBTenantInviteQuery.listByTenant] Error:",n instanceof Error?n.message:n),T(N.DatabaseQueryError({query:"listByTenant query"}))}}toListItem(e){let r=ve.inviteId(e.PK),n={id:e.invitedById};e.invitedByInfo&&(e.invitedByInfo.name&&(n.name=e.invitedByInfo.name),e.invitedByInfo.email&&(n.email=e.invitedByInfo.email),e.invitedByInfo.jobTitle&&(n.jobTitle=e.invitedByInfo.jobTitle));let i={id:r,tenantId:e.tenantId,invitedBy:n,status:e.inviteStatus,expiresAt:oe(e.expiresAt),createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};return e.inviteeUserId&&(i.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(i.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(i.inviteePhone=e.inviteePhone),e.roles!==void 0&&(i.roles=e.roles),e.perms!==void 0&&(i.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(i.authPerm=e.authPerm),e.displayName&&(i.displayName=e.displayName),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.jobTitle&&(i.jobTitle=e.jobTitle),e.acceptedAt&&(i.acceptedAt=oe(e.acceptedAt)),e.declinedAt&&(i.declinedAt=oe(e.declinedAt)),e.revokedAt&&(i.revokedAt=oe(e.revokedAt)),i}};var Fr=ge(ir(),1);var gge=10080*60*1e3,Qf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}mapItemToEntity(e){let n={id:ve.inviteId(e.PK),tenantId:e.tenantId,invitedById:e.invitedById,tenantType:e.tenantType,status:e.inviteStatus,inviteToken:e.inviteToken,expiresAt:oe(e.expiresAt),createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};e.inviteeUserId&&(n.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(n.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(n.inviteePhone=e.inviteePhone),e.roles!==void 0&&(n.roles=e.roles);let i=e[E.PERM];return i!==void 0&&(n.perms=JSON.parse(i)),e.authPerm!==void 0&&(n.authPerm=e.authPerm),e.displayName&&(n.displayName=e.displayName),e.givenName&&(n.givenName=e.givenName),e.familyName&&(n.familyName=e.familyName),e.jobTitle&&(n.jobTitle=e.jobTitle),e.acceptedAt&&(n.acceptedAt=oe(e.acceptedAt)),e.declinedAt&&(n.declinedAt=oe(e.declinedAt)),e.revokedAt&&(n.revokedAt=oe(e.revokedAt)),n}generateInviteId(){return Lt()}async getById(e){try{let r=await this.docClient.send(new Fr.GetCommand({TableName:this.tableName,Key:{PK:K.INVITE_PK(e),SK:K.INVITE_SK()}}));return r.Item?w(this.mapItemToEntity(r.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"getById invite"}))}}async getByToken(e){try{let n=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITE_TOKEN,KeyConditionExpression:"#inviteTokenGsi = :token",ExpressionAttributeNames:{"#inviteTokenGsi":E.INVITE_TOKEN_GSI},ExpressionAttributeValues:{":token":e},Limit:1}))).Items;if(!n||n.length===0)return w(null);let i=n[0],s=await this.docClient.send(new Fr.GetCommand({TableName:this.tableName,Key:{PK:i.PK,SK:i.SK}}));return s.Item?w(this.mapItemToEntity(s.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"getByToken invite"}))}}async create(e){try{let r=Ne(),n=Te(e.expiresAt),i=Math.floor((n+gge)/1e3),s={PK:K.INVITE_PK(e.id),SK:K.INVITE_SK(),[E.TENANT_ID]:e.tenantId,tenantType:e.tenantType,[E.INVITED_BY_ID]:e.invitedById,[E.INVITE_STATUS]:e.status,[E.INVITE_TOKEN]:e.inviteToken,[E.EXPIRES_AT]:n,[E.CREATED_AT]:r,[E.UPDATED_AT]:r,[E.TTL]:i,[E.INVITE_TENANT_PK]:ze.INVITE_TENANT_PK(e.tenantId),[E.INVITE_TENANT_SK]:ze.INVITE_TENANT_SK(e.status,r,e.id),[E.INVITE_TOKEN_GSI]:e.inviteToken},o={};e.invitedByName&&(o.name=e.invitedByName),e.invitedByEmail&&(o.email=e.invitedByEmail),e.invitedByJobTitle&&(o.jobTitle=e.invitedByJobTitle),Object.keys(o).length>0&&(s[E.INVITED_BY_INFO]=o),e.inviteeUserId&&(s[E.INVITEE_USER_ID]=e.inviteeUserId),e.inviteeEmail&&(s[E.INVITEE_EMAIL]=e.inviteeEmail,s[E.INVITEE_EMAIL_GSI]=e.inviteeEmail,s[E.INVITEE_EMAIL_TENANT_SK]=`${De.TENANT}${e.tenantId}`),e.inviteePhone&&(s[E.INVITEE_PHONE]=e.inviteePhone,s[E.INVITEE_PHONE_GSI]=e.inviteePhone,s[E.INVITEE_PHONE_TENANT_SK]=`${De.TENANT}${e.tenantId}`),e.roles!==void 0&&(s[E.ROLES]=e.roles),e.perms!==void 0&&(s[E.PERM]=JSON.stringify(e.perms)),e.authPerm!==void 0&&(s[E.AUTH_PERM]=e.authPerm),e.displayName&&(s[E.DISPLAY_NAME]=e.displayName),e.givenName&&(s.givenName=e.givenName),e.familyName&&(s.familyName=e.familyName),e.jobTitle&&(s.jobTitle=e.jobTitle),await this.docClient.send(new Fr.PutCommand({TableName:this.tableName,Item:s,ConditionExpression:"attribute_not_exists(PK)"}));let a={id:e.id,tenantId:e.tenantId,invitedById:e.invitedById,tenantType:e.tenantType,status:e.status,inviteToken:e.inviteToken,expiresAt:e.expiresAt,createdAt:oe(r),updatedAt:oe(r)};return e.inviteeUserId&&(a.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(a.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(a.inviteePhone=e.inviteePhone),e.roles!==void 0&&(a.roles=e.roles),e.perms!==void 0&&(a.perms=e.perms),e.authPerm!==void 0&&(a.authPerm=e.authPerm),e.displayName&&(a.displayName=e.displayName),e.givenName&&(a.givenName=e.givenName),e.familyName&&(a.familyName=e.familyName),e.jobTitle&&(a.jobTitle=e.jobTitle),w(a)}catch(r){return r.name==="ConditionalCheckFailedException"?T(N.UniqueConstraintViolation({field:"invite id"})):T(N.UnknownError({message:r.message}))}}async updateStatus(e,r){try{let n=Ne(),i=["#inviteStatus = :inviteStatus","#inviteTenantSk = :inviteTenantSk","#updatedAt = :updatedAt"],s={"#inviteStatus":E.INVITE_STATUS,"#inviteTenantSk":E.INVITE_TENANT_SK,"#updatedAt":E.UPDATED_AT},o={":inviteStatus":r.status,":inviteTenantSk":ze.INVITE_TENANT_SK(r.status,n,e),":updatedAt":n};r.acceptedAt&&(i.push("#acceptedAt = :acceptedAt"),s["#acceptedAt"]=E.ACCEPTED_AT,o[":acceptedAt"]=Te(r.acceptedAt)),r.declinedAt&&(i.push("#declinedAt = :declinedAt"),s["#declinedAt"]=E.DECLINED_AT,o[":declinedAt"]=Te(r.declinedAt)),r.revokedAt&&(i.push("#revokedAt = :revokedAt"),s["#revokedAt"]=E.REVOKED_AT,o[":revokedAt"]=Te(r.revokedAt));let a=[];r.status!=="pending"&&(a.push("#inviteTokenGsi","#inviteeEmailGsi","#inviteeEmailTenantSk","#inviteePhoneGsi","#inviteePhoneTenantSk"),s["#inviteTokenGsi"]=E.INVITE_TOKEN_GSI,s["#inviteeEmailGsi"]=E.INVITEE_EMAIL_GSI,s["#inviteeEmailTenantSk"]=E.INVITEE_EMAIL_TENANT_SK,s["#inviteePhoneGsi"]=E.INVITEE_PHONE_GSI,s["#inviteePhoneTenantSk"]=E.INVITEE_PHONE_TENANT_SK);let c=`SET ${i.join(", ")}`;return a.length>0&&(c+=` REMOVE ${a.join(", ")}`),await this.docClient.send(new Fr.UpdateCommand({TableName:this.tableName,Key:{PK:K.INVITE_PK(e),SK:K.INVITE_SK()},UpdateExpression:c,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:"attribute_exists(PK)"})),w(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"TenantInvite",id:e})):T(N.UnknownError({message:n.message}))}}async findByTenantAndEmail(e,r){try{let i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email AND #inviteeEmailTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteeEmailGsi":E.INVITEE_EMAIL_GSI,"#inviteeEmailTenantSk":E.INVITEE_EMAIL_TENANT_SK},ExpressionAttributeValues:{":email":r,":tenantSk":`${De.TENANT}${e}`},Limit:1}))).Items;return!i||i.length===0?w(null):w(this.mapItemToEntity(i[0]))}catch{return T(N.DatabaseQueryError({query:"findByTenantAndEmail"}))}}async findByTenantAndPhone(e,r){try{let i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone AND #inviteePhoneTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteePhoneGsi":E.INVITEE_PHONE_GSI,"#inviteePhoneTenantSk":E.INVITEE_PHONE_TENANT_SK},ExpressionAttributeValues:{":phone":r,":tenantSk":`${De.TENANT}${e}`},Limit:1}))).Items;return!i||i.length===0?w(null):w(this.mapItemToEntity(i[0]))}catch{return T(N.DatabaseQueryError({query:"findByTenantAndPhone"}))}}async findByTenantAndUserId(e,r){try{let i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",FilterExpression:"#inviteeUserId = :userId",ExpressionAttributeNames:{"#pk":E.INVITE_TENANT_PK,"#sk":E.INVITE_TENANT_SK,"#inviteeUserId":E.INVITEE_USER_ID},ExpressionAttributeValues:{":pk":ze.INVITE_TENANT_PK(e),":pendingPrefix":ze.INVITE_TENANT_STATUS_PREFIX("pending"),":userId":r},Limit:1}))).Items;return!i||i.length===0?w(null):w(this.mapItemToEntity(i[0]))}catch{return T(N.DatabaseQueryError({query:"findByTenantAndUserId"}))}}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={"#pk":E.INVITE_TENANT_PK},s={":pk":ze.INVITE_TENANT_PK(e)},o={TableName:this.tableName,IndexName:tt.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:i,ExpressionAttributeValues:s,ScanIndexForward:!1,Limit:n};r?.cursor&&(o.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))),r?.status&&(o.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",i["#sk"]=E.INVITE_TENANT_SK,s[":statusPrefix"]=ze.INVITE_TENANT_STATUS_PREFIX(r.status));let a=await this.docClient.send(new Fr.QueryCommand(o)),c=(a.Items||[]).map(d=>this.mapItemToEntity(d)),u=!!a.LastEvaluatedKey,p=u?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return gt(c,{limit:n,hasNext:u,cursor:p,prevCursor:r?.cursor??null})}catch{return T(N.DatabaseQueryError({query:"listByTenant"}))}}async findPendingByEmail(e){try{let r=Ne(),i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteeEmailGsi":E.INVITEE_EMAIL_GSI,"#expiresAt":E.EXPIRES_AT},ExpressionAttributeValues:{":email":e,":now":r}}))).Items||[];if(i.length===0)return w([]);let s=i.map(c=>({PK:c.PK,SK:c.SK})),a=(await Sl(this.docClient,this.tableName,s)).map(c=>this.mapItemToEntity(c));return w(a)}catch{return T(N.DatabaseQueryError({query:"findPendingByEmail"}))}}async findPendingByPhone(e){try{let r=Ne(),i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteePhoneGsi":E.INVITEE_PHONE_GSI,"#expiresAt":E.EXPIRES_AT},ExpressionAttributeValues:{":phone":e,":now":r}}))).Items||[];if(i.length===0)return w([]);let s=i.map(c=>({PK:c.PK,SK:c.SK})),a=(await Sl(this.docClient,this.tableName,s)).map(c=>this.mapItemToEntity(c));return w(a)}catch{return T(N.DatabaseQueryError({query:"findPendingByPhone"}))}}async countPendingByTenant(e){try{let r=await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",ExpressionAttributeNames:{"#pk":E.INVITE_TENANT_PK,"#sk":E.INVITE_TENANT_SK},ExpressionAttributeValues:{":pk":ze.INVITE_TENANT_PK(e),":pendingPrefix":ze.INVITE_TENANT_STATUS_PREFIX("pending")},Select:"COUNT"}));return w(r.Count??0)}catch{return T(N.DatabaseQueryError({query:"countPendingByTenant"}))}}async expireOld(e){return w(0)}};var f8=ge(ir(),1);var Jf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={TableName:this.tableName,KeyConditionExpression:"PK = :pk",ExpressionAttributeValues:{":pk":K.TENANT_MEMBER_PK(e)}};r?.cursor&&(i.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let o=(await this.docClient.send(new f8.QueryCommand(i))).Items||[],a=[],c=new Map;for(let y of o){let _=y.SK;if(_.startsWith(_t.TENANT_PROFILE)){let C=ve.tenantProfileUserId(_);c.set(C,y)}else _.startsWith(De.USER)&&a.push(y)}a.sort((y,_)=>_.createdAt-y.createdAt);let u=a.slice(0,n),p=a.length>n,d=u.map(y=>{let _=ve.tenantMemberUserId(y.SK),C=c.get(_);return this.toListItem(y,e,_,C)}),h=p&&u.length>0?Buffer.from(JSON.stringify({PK:u[u.length-1].PK,SK:u[u.length-1].SK})).toString("base64url"):null;return gt(d,{limit:n,hasNext:p,cursor:h,prevCursor:r?.cursor??null})}catch{return T(N.DatabaseQueryError({query:"listByTenant query"}))}}toListItem(e,r,n,i){let s={tenantId:r,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};if(e.roles!==void 0&&(s.roles=e.roles),e.perms!==void 0&&(s.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(s.authPerm=e.authPerm),i){let o={tenantId:r,userId:n,createdAt:oe(i.createdAt),updatedAt:oe(i.updatedAt)};i.contactEmail&&(o.contactEmail=i.contactEmail),i.contactPhone&&(o.contactPhone=i.contactPhone),i.displayName&&(o.displayName=i.displayName),i.displayNameSource&&(o.displayNameSource=i.displayNameSource),i.givenName&&(o.givenName=i.givenName),i.familyName&&(o.familyName=i.familyName),i.avatarUrl&&(o.avatarUrl=i.avatarUrl),i.locale&&(o.locale=i.locale),i.jobTitle&&(o.jobTitle=i.jobTitle),i.bio&&(o.bio=i.bio),i.metadata&&(o.metadata=JSON.parse(i.metadata)),s.tenantProfile=o}return s}};var Kr=ge(ir(),1);var Yf=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=Kr.DynamoDBDocumentClient.from(e)}mapItemToEntity(e){let r=ve.tenantId(e.PK),n=ve.tenantMemberUserId(e.SK),i={tenantId:r,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};return e.roles!==void 0&&(i.roles=e.roles),e.perms!==void 0&&(i.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(i.authPerm=e.authPerm),i}async get(e,r){try{let n=await this.docClient.send(new Kr.GetCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_MEMBER_SK(r)}}));if(!n.Item)return w(null);let i=this.mapItemToEntity(n.Item);return w(i)}catch{return T(N.DatabaseQueryError({query:"get"}))}}async create(e){try{let r=Ne(),n=e.isOwner?void 0:e.authPerm,i=Zr({PK:K.TENANT_MEMBER_PK(e.tenantId),SK:K.TENANT_MEMBER_SK(e.userId),userStatus:e.status,roles:e.roles,perms:e.perms!==void 0?JSON.stringify(e.perms):void 0,authPerm:n,isOwner:e.isOwner,createdAt:r,updatedAt:r,userTenantPk:ze.USER_TENANT_PK(e.userId),userTenantSk:ze.USER_TENANT_SK(e.tenantType??"org",e.parentTenantId,r,e.tenantId),parentTenantId:e.parentTenantId});return e.isOwner?await this.docClient.send(new Kr.TransactWriteCommand({TransactItems:[{Put:{TableName:this.tableName,Item:{PK:K.TENANT_MEMBER_PK(e.tenantId),SK:K.TENANT_OWNER_MARKER_SK(),createdAt:r},ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}},{Put:{TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}}]})):await this.docClient.send(new Kr.PutCommand({TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),w(void 0)}catch(r){return r.name==="TransactionCanceledException"?r.CancellationReasons?.[0]?.Code==="ConditionalCheckFailed"?T(N.UniqueConstraintViolation({field:"tenant owner"})):T(N.UniqueConstraintViolation({field:"tenant member"})):r.name==="ConditionalCheckFailedException"?T(N.UniqueConstraintViolation({field:"tenant member"})):T(N.UnknownError({message:r.message}))}}async updatePermissions(e,r,n){try{let i={...n,updatedAt:Ne()},{UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=$i(i);return await this.docClient.send(new Kr.UpdateCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_MEMBER_SK(r)},UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"TenantMember",id:`${e}:${r}`})):T(N.UnknownError({message:i.message}))}}async updateStatus(e,r,n){try{return await this.docClient.send(new Kr.UpdateCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_MEMBER_SK(r)},UpdateExpression:"SET #userStatus = :userStatus, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#userStatus":"userStatus","#updatedAt":"updatedAt"},ExpressionAttributeValues:{":userStatus":n,":updatedAt":Ne()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"TenantMember",id:`${e}:${r}`})):T(N.UnknownError({message:i.message}))}}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":K.TENANT_MEMBER_PK(e),":skPrefix":De.USER},Limit:n};r?.cursor&&(i.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let s=await this.docClient.send(new Kr.QueryCommand(i)),o=(s.Items||[]).map(u=>this.mapItemToEntity(u)),a=!!s.LastEvaluatedKey,c=a?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null;return gt(o,{limit:n,hasNext:a,cursor:c,prevCursor:r?.cursor??null})}catch{return T(N.DatabaseQueryError({query:"listByTenant"}))}}async hasOwner(e){try{let r=await this.docClient.send(new Kr.GetCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_OWNER_MARKER_SK()}}));return w(!!r.Item)}catch{return T(N.DatabaseQueryError({query:"hasOwner"}))}}async remove(e,r){try{return await this.docClient.send(new Kr.DeleteCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_MEMBER_SK(r)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"TenantMember",id:`${e}:${r}`})):T(N.UnknownError({message:n.message}))}}};var W_=ge(ir(),1);var Xf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByUser(e,r){try{let n=Math.min(r?.limit??50,100),i=r?.tenantType??nv.DEFAULT,s=r?.parentTenantId,o=s?`${i}#${s}#`:`${i}#`,a={TableName:this.tableName,IndexName:tt.USER_TENANTS,KeyConditionExpression:"userTenantPk = :pk AND begins_with(userTenantSk, :skPrefix)",ExpressionAttributeValues:{":pk":ze.USER_TENANT_PK(e),":skPrefix":o},ScanIndexForward:!1,Limit:n};r?.cursor&&(a.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let c=await this.docClient.send(new W_.QueryCommand(a)),u=c.Items??[],p=await this.fetchProfileMap(e,u),d=u.map(_=>this.toListItem(_,e,p)),h=!!c.LastEvaluatedKey,y=h?Buffer.from(JSON.stringify(c.LastEvaluatedKey)).toString("base64url"):null;return gt(d,{limit:n,hasNext:h,cursor:y,prevCursor:r?.cursor??null})}catch{return T(N.DatabaseQueryError({query:"listByUser query"}))}}async fetchProfileMap(e,r){let n=new Map;if(r.length===0)return n;let i=r.map(o=>({PK:K.TENANT_PROFILE_PK(ve.tenantId(o.PK)),SK:K.TENANT_PROFILE_SK(e)})),s=await this.docClient.send(new W_.BatchGetCommand({RequestItems:{[this.tableName]:{Keys:i}}}));for(let o of s.Responses?.[this.tableName]??[]){let a=o,c=ve.tenantId(a.PK);n.set(c,a)}return n}toListItem(e,r,n){let i=ve.tenantId(e.PK),s={tenantId:i,userId:r,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};e.roles!==void 0&&(s.roles=e.roles),e.perms!==void 0&&(s.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(s.authPerm=e.authPerm);let o=n.get(i);return o&&(o.contactEmail&&(s.contactEmail=o.contactEmail),o.contactPhone&&(s.contactPhone=o.contactPhone),o.displayName&&(s.displayName=o.displayName),o.displayNameSource&&(s.displayNameSource=o.displayNameSource),o.givenName&&(s.givenName=o.givenName),o.familyName&&(s.familyName=o.familyName),o.avatarUrl&&(s.avatarUrl=o.avatarUrl),o.locale&&(s.locale=o.locale),o.jobTitle&&(s.jobTitle=o.jobTitle),o.bio&&(s.bio=o.bio),o.metadata&&(s.metadata=JSON.parse(o.metadata))),s}};var xa=ge(ir(),1);var Zf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateTenantId(){return Lt()}toEntity(e){let n={id:ve.tenantId(e.PK),type:e.tenantType,ownerId:e.ownerId,createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};return e.parentTenantId&&(n.parentTenantId=e.parentTenantId),n}async get(e){try{let r=await this.docClient.send(new xa.GetCommand({TableName:this.tableName,Key:{PK:K.TENANT_PK(e),SK:K.TENANT_SK()}}));return r.Item?w(this.toEntity(r.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"get tenant"}))}}async create(e){try{let r=e.id??this.generateTenantId(),n=Ne(),i=Zr({PK:K.TENANT_PK(r),SK:K.TENANT_SK(),tenantType:e.type,parentTenantId:e.parentTenantId,ownerId:e.ownerId,createdAt:n,updatedAt:n});return await this.docClient.send(new xa.PutCommand({TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),w(void 0)}catch(r){return r.name==="ConditionalCheckFailedException"?T(N.UniqueConstraintViolation({field:"tenant"})):T(N.UnknownError({message:r.message}))}}async update(e,r){try{let n={updatedAt:Ne()};r.type!==void 0&&(n.tenantType=r.type),r.ownerId!==void 0&&(n.ownerId=r.ownerId),r.parentTenantId!==void 0&&(n.parentTenantId=r.parentTenantId===null?void 0:r.parentTenantId);let{UpdateExpression:i,ExpressionAttributeNames:s,ExpressionAttributeValues:o}=$i(n);return await this.docClient.send(new xa.UpdateCommand({TableName:this.tableName,Key:{PK:K.TENANT_PK(e),SK:K.TENANT_SK()},UpdateExpression:i,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"Tenant",id:e})):T(N.UnknownError({message:n.message}))}}async delete(e){try{return await this.docClient.send(new xa.DeleteCommand({TableName:this.tableName,Key:{PK:K.TENANT_PK(e),SK:K.TENANT_SK()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(r){return r.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"Tenant",id:e})):T(N.UnknownError({message:r.message}))}}async list(){return T(N.InvalidData({reason:"DynamoDB tenant list requires a dedicated GSI; scan is disabled"}))}async listByParent(e){return T(N.InvalidData({reason:`DynamoDB tenant listByParent(${e}) requires a dedicated GSI; scan is disabled`}))}async listRoots(){return T(N.InvalidData({reason:"DynamoDB tenant listRoots requires a dedicated GSI; scan is disabled"}))}};var Bi=ge(ir(),1);var em=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async get(e){try{let r=await this.docClient.send(new Bi.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()}}));return r.Item?w(this.unmarshall(r.Item,e)):w(null)}catch{return T(N.DatabaseQueryError({query:"get user auth"}))}}async create(e){try{let r=Ne(),n={...e,createdAt:new Date(r),updatedAt:new Date(r)};return await this.docClient.send(new Bi.PutCommand({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:`attribute_not_exists(${E.PK})`})),w(n)}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"userAuth"})):T(N.DatabaseQueryError({query:"create user auth"}))}}async updateStatus(e,r){try{let n=Ne();return await this.docClient.send(new Bi.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()},UpdateExpression:`SET #userStatus = :userStatus, #${E.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#userStatus":"userStatus",[`#${E.UPDATED_AT}`]:E.UPDATED_AT},ExpressionAttributeValues:{":userStatus":r,":updatedAt":n},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userAuth",id:e})):T(N.DatabaseQueryError({query:"update user auth status"}))}}async updateMfaRequired(e,r){try{let n=Ne();return await this.docClient.send(new Bi.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #${E.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired",[`#${E.UPDATED_AT}`]:E.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":r,":updatedAt":n},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userAuth",id:e})):T(N.DatabaseQueryError({query:"update mfa required"}))}}async updateMfaMethods(e,r){try{let n=Ne();return await this.docClient.send(new Bi.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()},UpdateExpression:`SET #mfaMethods = :mfaMethods, #${E.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaMethods":"mfaMethods",[`#${E.UPDATED_AT}`]:E.UPDATED_AT},ExpressionAttributeValues:{":mfaMethods":r,":updatedAt":n},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userAuth",id:e})):T(N.DatabaseQueryError({query:"update mfa methods"}))}}async updateMfaSettings(e,r){try{let n=Ne();return await this.docClient.send(new Bi.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #mfaMethods = :mfaMethods, #${E.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired","#mfaMethods":"mfaMethods",[`#${E.UPDATED_AT}`]:E.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":r.mfaRequired,":mfaMethods":r.mfaMethods,":updatedAt":n},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userAuth",id:e})):T(N.DatabaseQueryError({query:"update mfa settings"}))}}async remove(e){try{return await this.docClient.send(new Bi.DeleteCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"remove user auth"}))}}marshall(e){return{[E.PK]:K.USER_PK(e.userId),[E.SK]:K.USER_AUTH_SK(),userStatus:e.userStatus,mfaRequired:e.mfaRequired,mfaMethods:e.mfaMethods,[E.CREATED_AT]:Te(e.createdAt),[E.UPDATED_AT]:Te(e.updatedAt)}}unmarshall(e,r){return{userId:r,userStatus:e.userStatus,mfaRequired:e.mfaRequired||!1,mfaMethods:e.mfaMethods||null,createdAt:oe(e[E.CREATED_AT]),updatedAt:oe(e[E.UPDATED_AT])}}};var tn=ge(ir(),1);function _l(t,e){return e?K.USER_MFA_WITH_ID_SK(t,e):K.USER_MFA_SK(t)}var tm=class{client;tableName;docClient;constructor(e,r){this.client=e,this.tableName=r,this.docClient=tn.DynamoDBDocumentClient.from(e)}toDynamoDBItem(e){let r={PK:K.USER_PK(e.userId),SK:_l(e.method,e.id),method:e.method,data:JSON.stringify(e.data),createdAt:Date.now(),failedAttempts:0};return e.label&&(r.label=e.label),e.verifiedAt&&(r.verifiedAt=e.verifiedAt.getTime()),e.metadata&&(r.metadata=JSON.stringify(e.metadata)),r}fromDynamoDBItem(e,r){let n=ve.mfaSKInfo(e.SK),i={userId:r,method:e.method,data:JSON.parse(e.data),createdAt:oe(e.createdAt),verifiedAt:Xr(e.verifiedAt)??null};return n?.id&&(i.id=n.id),e.label&&(i.label=e.label),e.failedAttempts!==void 0&&(i.failedAttempts=e.failedAttempts),e.lastFailedAt!==void 0&&(i.lastFailedAt=Xr(e.lastFailedAt)),e.lockedUntil!==void 0&&(i.lockedUntil=Xr(e.lockedUntil)),e.lastUsedAt!==void 0&&(i.lastUsedAt=Xr(e.lastUsedAt)),e.metadata&&(i.metadata=JSON.parse(e.metadata)),i}async get(e,r,n){try{let i=_l(r,n),s=await this.docClient.send(new tn.GetCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:i}}));return s.Item?w(this.fromDynamoDBItem(s.Item,e)):w(null)}catch(i){return console.error("DynamoDBUserMFAAuthenticatorRepository.get error:",i),T(N.DatabaseQueryError({query:"get MFA authenticator"}))}}async findByUserId(e){try{let r={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":K.USER_PK(e),":skPrefix":_t.MFA}},s=((await this.docClient.send(new tn.QueryCommand(r))).Items??[]).map(o=>this.fromDynamoDBItem(o,e));return w(s)}catch(r){return console.error("DynamoDBUserMFAAuthenticatorRepository.findByUserId error:",r),T(N.DatabaseQueryError({query:"find MFA authenticators by user"}))}}async findByUserIdAndMethod(e,r){try{let n={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":K.USER_PK(e),":skPrefix":`${_t.MFA}${r}`}},o=((await this.docClient.send(new tn.QueryCommand(n))).Items??[]).filter(a=>a.method===r).map(a=>this.fromDynamoDBItem(a,e));return w(o)}catch(n){return console.error("DynamoDBUserMFAAuthenticatorRepository.findByUserIdAndMethod error:",n),T(N.DatabaseQueryError({query:"find MFA authenticators by method"}))}}async create(e){try{let r={...e};e.id===void 0&&this.isMultiInstanceMethod(e.method)&&(r.id=Lt());let n=this.toDynamoDBItem(r);return await this.docClient.send(new tn.PutCommand({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),w(this.fromDynamoDBItem(n,e.userId))}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"MFA authenticator"})):(console.error("DynamoDBUserMFAAuthenticatorRepository.create error:",r),T(N.DatabaseQueryError({query:"create MFA authenticator"})))}}async update(e,r,n,i){try{let s=_l(r,n),o=[],a={},c={};if(i.label!==void 0&&(o.push("#label = :label"),a["#label"]="label",c[":label"]=i.label),i.data!==void 0&&(o.push("#data = :data"),a["#data"]="data",c[":data"]=JSON.stringify(i.data)),i.verifiedAt!==void 0&&(o.push("#verifiedAt = :verifiedAt"),a["#verifiedAt"]="verifiedAt",c[":verifiedAt"]=i.verifiedAt instanceof Date?i.verifiedAt.getTime():i.verifiedAt===null?void 0:i.verifiedAt),i.lastUsedAt!==void 0&&(o.push("#lastUsedAt = :lastUsedAt"),a["#lastUsedAt"]="lastUsedAt",c[":lastUsedAt"]=i.lastUsedAt instanceof Date?i.lastUsedAt.getTime():i.lastUsedAt===null?void 0:i.lastUsedAt),i.failedAttempts!==void 0&&(o.push("#failedAttempts = :failedAttempts"),a["#failedAttempts"]="failedAttempts",c[":failedAttempts"]=i.failedAttempts),i.lastFailedAt!==void 0&&(o.push("#lastFailedAt = :lastFailedAt"),a["#lastFailedAt"]="lastFailedAt",c[":lastFailedAt"]=i.lastFailedAt instanceof Date?i.lastFailedAt.getTime():i.lastFailedAt===null?void 0:i.lastFailedAt),i.lockedUntil!==void 0&&(o.push("#lockedUntil = :lockedUntil"),a["#lockedUntil"]="lockedUntil",c[":lockedUntil"]=i.lockedUntil instanceof Date?i.lockedUntil.getTime():i.lockedUntil===null?void 0:i.lockedUntil),i.metadata!==void 0&&(o.push("#metadata = :metadata"),a["#metadata"]="metadata",c[":metadata"]=JSON.stringify(i.metadata)),o.length===0)return w(void 0);let u={TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:s},UpdateExpression:`SET ${o.join(", ")}`,ExpressionAttributeNames:a,ExpressionAttributeValues:c};return await this.docClient.send(new tn.UpdateCommand(u)),w(void 0)}catch(s){return console.error("DynamoDBUserMFAAuthenticatorRepository.update error:",s),T(N.DatabaseQueryError({query:"update MFA authenticator"}))}}async remove(e,r,n){try{let i=_l(r,n);return await this.docClient.send(new tn.DeleteCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:i}})),w(void 0)}catch(i){return console.error("DynamoDBUserMFAAuthenticatorRepository.remove error:",i),T(N.DatabaseQueryError({query:"remove MFA authenticator"}))}}async incrementFailedAttempts(e,r,n,i,s){try{let o=_l(r,n),a=Date.now(),c=["#failedAttempts = if_not_exists(#failedAttempts, :zero) + :inc","#lastFailedAt = :lastFailedAt"],u={"#failedAttempts":"failedAttempts","#lastFailedAt":"lastFailedAt"},p={":zero":0,":inc":1,":lastFailedAt":a};s!==null&&(c.push("#lockedUntil = if_not_exists(#lockedUntil, :lockedUntil)"),u["#lockedUntil"]="lockedUntil",p[":lockedUntil"]=a+s*60*1e3,p[":maxAttempts"]=i);let d={TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:o},UpdateExpression:`SET ${c.join(", ")}`,ExpressionAttributeNames:u,ExpressionAttributeValues:p};return await this.docClient.send(new tn.UpdateCommand(d)),w(void 0)}catch(o){return console.error("DynamoDBUserMFAAuthenticatorRepository.incrementFailedAttempts error:",o),T(N.DatabaseQueryError({query:"increment failed attempts"}))}}async resetFailedAttempts(e,r,n){try{let i=_l(r,n),s={TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:i},UpdateExpression:"SET #failedAttempts = :zero REMOVE #lastFailedAt, #lockedUntil",ExpressionAttributeNames:{"#failedAttempts":"failedAttempts","#lastFailedAt":"lastFailedAt","#lockedUntil":"lockedUntil"},ExpressionAttributeValues:{":zero":0}};return await this.docClient.send(new tn.UpdateCommand(s)),w(void 0)}catch(i){return console.error("DynamoDBUserMFAAuthenticatorRepository.resetFailedAttempts error:",i),T(N.DatabaseQueryError({query:"reset failed attempts"}))}}async unlock(e,r,n){return this.resetFailedAttempts(e,r,n)}isMultiInstanceMethod(e){return["webauthn","passkey","hardware","backup"].includes(e)}};var bn=ge(ir(),1);var rm=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=bn.DynamoDBDocumentClient.from(e)}generateUserId(){return Lt()}async getById(e){try{let r=await this.docClient.send(new bn.GetCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:K.USER_PROFILE_SK()}}));if(!r.Item)return w(null);let n=r.Item;if(n.deletedAt)return w(null);let s={id:ve.userId(n.PK),status:n.userStatus,createdAt:oe(n.createdAt),updatedAt:oe(n.updatedAt),...n.deletedAt!==void 0&&{deletedAt:oe(n.deletedAt)},...n.contactEmail!==void 0&&{contactEmail:n.contactEmail},...n.contactPhone!==void 0&&{contactPhone:n.contactPhone},...n.username!==void 0&&{username:n.username},...n.displayName!==void 0&&{displayName:n.displayName},...n.givenName!==void 0&&{givenName:n.givenName},...n.familyName!==void 0&&{familyName:n.familyName},...n.avatarUrl!==void 0&&{avatarUrl:n.avatarUrl},...n.locale!==void 0&&{locale:n.locale},...n.metadata!==void 0&&{metadata:JSON.parse(n.metadata)}};return w(s)}catch{return T(N.DatabaseQueryError({query:"getById user"}))}}async create(e){try{let r=Ne(),n=e.id||this.generateUserId(),i=e.status||"pending",s={PK:K.USER_PK(n),SK:K.USER_PROFILE_SK(),userStatus:i,createdAt:r,updatedAt:r};e.contactEmail&&(s.contactEmail=e.contactEmail),e.contactPhone&&(s.contactPhone=e.contactPhone),e.username&&(s.username=e.username),e.displayName&&(s.displayName=e.displayName),e.givenName&&(s.givenName=e.givenName),e.familyName&&(s.familyName=e.familyName),e.avatarUrl&&(s.avatarUrl=e.avatarUrl),e.locale&&(s.locale=e.locale),e.metadata&&(s.metadata=JSON.stringify(e.metadata)),s[E.USER_STATUS_PK]=ze.USER_STATUS_PK(i),s[E.USER_STATUS_SK]=ze.USER_STATUS_SK(n),await this.docClient.send(new bn.PutCommand({TableName:this.tableName,Item:Zr(s),ConditionExpression:rv("PK")}));let o={id:n,status:i,createdAt:oe(r),updatedAt:oe(r),...e.contactEmail&&{contactEmail:e.contactEmail},...e.contactPhone&&{contactPhone:e.contactPhone},...e.username&&{username:e.username},...e.displayName&&{displayName:e.displayName},...e.givenName&&{givenName:e.givenName},...e.familyName&&{familyName:e.familyName},...e.avatarUrl&&{avatarUrl:e.avatarUrl},...e.locale&&{locale:e.locale},...e.metadata&&{metadata:e.metadata}};return w(o)}catch{return T(N.DatabaseQueryError({query:"create user"}))}}async updateProfile(e,r){try{let n=Ne(),i={};if(r.contactEmail!==void 0&&(i.contactEmail=r.contactEmail),r.contactPhone!==void 0&&(i.contactPhone=r.contactPhone),r.displayName!==void 0&&(i.displayName=r.displayName),r.givenName!==void 0&&(i.givenName=r.givenName),r.familyName!==void 0&&(i.familyName=r.familyName),r.avatarUrl!==void 0&&(i.avatarUrl=r.avatarUrl),r.locale!==void 0&&(i.locale=r.locale),r.metadata!==void 0&&(i.metadata=JSON.stringify(r.metadata)),Object.keys(i).length===0)return w(void 0);i.updatedAt=n;let s=$i(i);return await this.docClient.send(new bn.UpdateCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:K.USER_PROFILE_SK()},UpdateExpression:s.UpdateExpression,ExpressionAttributeNames:s.ExpressionAttributeNames,ExpressionAttributeValues:s.ExpressionAttributeValues})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"updateProfile"}))}}async getByStatus(e,r){try{let n=Math.min(r?.limit||50,100),i;if(r?.cursor)try{i=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))}catch{return T(N.DatabaseQueryError({query:"invalid pagination cursor"}))}let s=ze.USER_STATUS_PK(e),o=await this.docClient.send(new bn.QueryCommand({TableName:this.tableName,IndexName:tt.USERS_BY_STATUS,KeyConditionExpression:`${E.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":s},Limit:n,ExclusiveStartKey:i})),a=[];if(o.Items&&o.Items.length>0)for(let p of o.Items){let d=ve.userId(p.PK);a.push(d)}let c=!!o.LastEvaluatedKey,u=c?Buffer.from(JSON.stringify(o.LastEvaluatedKey)).toString("base64url"):null;return w(a,{pagination:{type:"cursor",limit:n,count:a.length,hasNext:c,hasPrev:!!r?.cursor,cursor:u}})}catch{return T(N.DatabaseQueryError({query:"get users by status"}))}}async countByStatus(e){try{let r=ze.USER_STATUS_PK(e),n=await this.docClient.send(new bn.QueryCommand({TableName:this.tableName,IndexName:tt.USERS_BY_STATUS,KeyConditionExpression:`${E.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":r},Select:"COUNT"}));return w(n.Count||0)}catch{return T(N.DatabaseQueryError({query:"count users by status"}))}}async syncAuthStatus(e,r){try{let n=Ne(),i=`SET userStatus = :userStatus, #${E.UPDATED_AT} = :updatedAt, #${E.USER_STATUS_PK} = :statusPk, #${E.USER_STATUS_SK} = :statusSk`,s={":userStatus":r,":updatedAt":n,":statusPk":ze.USER_STATUS_PK(r),":statusSk":ze.USER_STATUS_SK(e)};return r===Hi.DELETED?(i+=", deletedAt = :deletedAt",s[":deletedAt"]=n):i+=" REMOVE deletedAt",await this.docClient.send(new bn.UpdateCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:K.USER_PROFILE_SK()},UpdateExpression:i,ExpressionAttributeNames:{[`#${E.UPDATED_AT}`]:E.UPDATED_AT,[`#${E.USER_STATUS_PK}`]:E.USER_STATUS_PK,[`#${E.USER_STATUS_SK}`]:E.USER_STATUS_SK},ExpressionAttributeValues:s,ConditionExpression:"attribute_exists(PK)"})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userProfile",id:e})):T(N.DatabaseQueryError({query:"sync auth status"}))}}async remove(e){try{return await this.docClient.send(new bn.DeleteCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:K.USER_PROFILE_SK()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"remove user profile"}))}}};var li=ge(ir(),1);var nm=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=li.DynamoDBDocumentClient.from(e)}mapItemToUserProviderLink(e){let r=ve.providerPKInfo(e.PK);if(!r)throw new Error(`Invalid provider PK: ${e.PK}`);let n={userId:e.userId,provider:r.provider,externalId:r.externalId,createdAt:oe(e.createdAt)};if(e.externalUsername&&(n.externalUsername=e.externalUsername),e.externalEmail&&(n.externalEmail=e.externalEmail),e.externalPhone&&(n.externalPhone=e.externalPhone),e.externalName&&(n.externalName=e.externalName),e.externalAvatarUrl&&(n.externalAvatarUrl=e.externalAvatarUrl),e.metadata)try{n.metadata=JSON.parse(e.metadata)}catch{}return n}mapUserProviderLinkToItem(e){let r=Ne(),n={PK:K.PROVIDER_PK(e.provider,e.externalId),SK:K.PROVIDER_METADATA_SK(),userProviderPk:K.USER_PK(e.userId),userProviderSk:K.PROVIDER_PK(e.provider,e.externalId),userId:e.userId,createdAt:e.createdAt?Te(e.createdAt):r};return e.externalUsername&&(n.externalUsername=e.externalUsername),e.externalEmail&&(n.externalEmail=e.externalEmail),e.externalPhone&&(n.externalPhone=e.externalPhone),e.externalName&&(n.externalName=e.externalName),e.externalAvatarUrl&&(n.externalAvatarUrl=e.externalAvatarUrl),e.metadata&&(n.metadata=JSON.stringify(e.metadata)),Zr(n)}async findByProviderAndExternalId(e,r){try{let n=await this.docClient.send(new li.GetCommand({TableName:this.tableName,Key:{PK:K.PROVIDER_PK(e,r),SK:K.PROVIDER_METADATA_SK()}}));return n.Item?w(this.mapItemToUserProviderLink(n.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"find provider by external id"}))}}async findByUserId(e){try{let r=await this.docClient.send(new li.QueryCommand({TableName:this.tableName,IndexName:tt.USER_PROVIDERS,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:{"#pk":E.USER_PROVIDER_PK},ExpressionAttributeValues:{":pk":K.USER_PK(e)}}));return!r.Items||r.Items.length===0?w([]):w(r.Items.map(n=>this.mapItemToUserProviderLink(n)))}catch{return T(N.DatabaseQueryError({query:"find providers by user id"}))}}async create(e){try{let r={...e,createdAt:new Date},n=this.mapUserProviderLinkToItem(r);return await this.docClient.send(new li.PutCommand({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK)"})),w(this.mapItemToUserProviderLink(n))}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"provider connection",message:"Provider connection already exists"})):T(N.DatabaseQueryError({query:"create user provider"}))}}async update(e,r,n){try{let i={};if(n.externalUsername!==void 0&&(i.externalUsername=n.externalUsername),n.externalEmail!==void 0&&(i.externalEmail=n.externalEmail),n.externalPhone!==void 0&&(i.externalPhone=n.externalPhone),n.externalName!==void 0&&(i.externalName=n.externalName),n.externalAvatarUrl!==void 0&&(i.externalAvatarUrl=n.externalAvatarUrl),n.metadata!==void 0&&(i.metadata=JSON.stringify(n.metadata)),Object.keys(i).length===0)return w(void 0);let{UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=$i(i);return await this.docClient.send(new li.UpdateCommand({TableName:this.tableName,Key:{PK:K.PROVIDER_PK(e,r),SK:K.PROVIDER_METADATA_SK()},UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"update user provider"}))}}async remove(e,r){try{return await this.docClient.send(new li.DeleteCommand({TableName:this.tableName,Key:{PK:K.PROVIDER_PK(e,r),SK:K.PROVIDER_METADATA_SK()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"delete user provider"}))}}};var wa=ge(ir(),1);var im=class{docClient;tableName;constructor(e,r){this.docClient=e,this.tableName=r}mapItemToEntity(e){let r=ve.tenantId(e.PK),n=ve.tenantProfileUserId(e.SK),i={tenantId:r,userId:n,createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};return e.contactEmail&&(i.contactEmail=e.contactEmail),e.contactPhone&&(i.contactPhone=e.contactPhone),e.displayName&&(i.displayName=e.displayName),e.displayNameSource&&(i.displayNameSource=e.displayNameSource),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.avatarUrl&&(i.avatarUrl=e.avatarUrl),e.locale&&(i.locale=e.locale),e.jobTitle&&(i.jobTitle=e.jobTitle),e.bio&&(i.bio=e.bio),e.metadata&&(i.metadata=JSON.parse(e.metadata)),i}async get(e,r){try{let n=await this.docClient.send(new wa.GetCommand({TableName:this.tableName,Key:{PK:K.TENANT_PROFILE_PK(e),SK:K.TENANT_PROFILE_SK(r)}}));return n.Item?w(this.mapItemToEntity(n.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"get user tenant profile"}))}}async create(e){try{let r=Ne(),n={PK:K.TENANT_PROFILE_PK(e.tenantId),SK:K.TENANT_PROFILE_SK(e.userId),createdAt:r,updatedAt:r};e.contactEmail&&(n.contactEmail=e.contactEmail),e.contactPhone&&(n.contactPhone=e.contactPhone),e.displayName&&(n.displayName=e.displayName),e.displayNameSource&&(n.displayNameSource=e.displayNameSource),e.givenName&&(n.givenName=e.givenName),e.familyName&&(n.familyName=e.familyName),e.avatarUrl&&(n.avatarUrl=e.avatarUrl),e.locale&&(n.locale=e.locale),e.jobTitle&&(n.jobTitle=e.jobTitle),e.bio&&(n.bio=e.bio),e.metadata&&(n.metadata=JSON.stringify(e.metadata)),await this.docClient.send(new wa.PutCommand({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}));let i={tenantId:e.tenantId,userId:e.userId,createdAt:oe(r),updatedAt:oe(r)};return e.contactEmail&&(i.contactEmail=e.contactEmail),e.contactPhone&&(i.contactPhone=e.contactPhone),e.displayName&&(i.displayName=e.displayName),e.displayNameSource&&(i.displayNameSource=e.displayNameSource),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.avatarUrl&&(i.avatarUrl=e.avatarUrl),e.locale&&(i.locale=e.locale),e.jobTitle&&(i.jobTitle=e.jobTitle),e.bio&&(i.bio=e.bio),e.metadata&&(i.metadata=e.metadata),w(i)}catch(r){return r.name==="ConditionalCheckFailedException"?T(N.UniqueConstraintViolation({field:"user tenant profile"})):T(N.UnknownError({message:r.message}))}}async update(e,r,n){try{let i={updatedAt:Ne()};n.contactEmail!==void 0&&(i.contactEmail=n.contactEmail),n.contactPhone!==void 0&&(i.contactPhone=n.contactPhone),n.displayName!==void 0&&(i.displayName=n.displayName),n.displayNameSource!==void 0&&(i.displayNameSource=n.displayNameSource),n.givenName!==void 0&&(i.givenName=n.givenName),n.familyName!==void 0&&(i.familyName=n.familyName),n.avatarUrl!==void 0&&(i.avatarUrl=n.avatarUrl),n.locale!==void 0&&(i.locale=n.locale),n.jobTitle!==void 0&&(i.jobTitle=n.jobTitle),n.bio!==void 0&&(i.bio=n.bio),n.metadata!==void 0&&(i.metadata=n.metadata?JSON.stringify(n.metadata):null);let{UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=$i(i);return await this.docClient.send(new wa.UpdateCommand({TableName:this.tableName,Key:{PK:K.TENANT_PROFILE_PK(e),SK:K.TENANT_PROFILE_SK(r)},UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"UserTenantProfile",id:`${e}:${r}`})):T(N.UnknownError({message:i.message}))}}async remove(e,r){try{return await this.docClient.send(new wa.DeleteCommand({TableName:this.tableName,Key:{PK:K.TENANT_PROFILE_PK(e),SK:K.TENANT_PROFILE_SK(r)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"UserTenantProfile",id:`${e}:${r}`})):T(N.UnknownError({message:n.message}))}}};var j_=class{name="database-dynamodb";version="1.0.0";users;sessions;userProviders;userMfaAuthenticators;challenges;identities;credentials;registration;userAuths;tenantMembers;tenantInvites;userTenantProfiles;tenants;queries;client;tableName;constructor(e){this.tableName=e.tableName,this.client=e.client||new z_.DynamoDBClient(e.clientConfig||{});let r=m8.DynamoDBDocumentClient.from(this.client,{marshallOptions:{removeUndefinedValues:!0,convertClassInstanceToMap:!0}});this.users=new rm(this.client,this.tableName),this.sessions=new jf({client:this.client,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userProviders=new nm(this.client,this.tableName),this.userMfaAuthenticators=new tm(this.client,this.tableName),this.challenges=new Hf({docClient:r,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.identities=new qf({docClient:r,tableName:this.tableName}),this.credentials=new Gf({docClient:r,tableName:this.tableName}),this.registration=new Wf({docClient:r,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userAuths=new em({docClient:r,tableName:this.tableName}),this.tenantMembers=new Yf(this.client,this.tableName),this.tenantInvites=new Qf({docClient:r,tableName:this.tableName}),this.userTenantProfiles=new im(r,this.tableName),this.tenants=new Zf({docClient:r,tableName:this.tableName}),this.queries={tenantInvites:new zf({docClient:r,tableName:this.tableName}),tenantMembers:new Jf({docClient:r,tableName:this.tableName}),tenants:new Xf({docClient:r,tableName:this.tableName})}}async initialize(){}async health(){try{return await this.client.send(new z_.DescribeTableCommand({TableName:this.tableName})),!0}catch(e){return console.error("DynamoDB health check failed:",e),!1}}async cleanup(){this.client.destroy()}};Bv();var Fv=1,H5=2,G5=3,q5="auth-craft:internal";async function tye(t){let e=t.replace(/^0x/,""),r=j5(e),n=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length);let s=`-----BEGIN PRIVATE KEY-----
|
|
187
|
+
RETURNING *`,[e.tenantId,e.userId,e.contactEmail??null,e.contactPhone??null,e.displayName??null,e.displayNameSource??null,e.givenName??null,e.familyName??null,e.avatarUrl??null,e.locale??null,e.jobTitle??null,e.bio??null,e.metadata?JSON.stringify(e.metadata):null]);return w(this.toEntity(r[0]))}catch(r){console.error("[DEBUG] user_tenant_profiles insert error:",r);let n=r;return n.code==="23505"?T(N.UniqueConstraintViolation({field:"tenant profile"})):n.code==="23503"?T(N.ForeignKeyViolation({field:"userId"})):T(N.DatabaseQueryError({query:"create user tenant profile"}))}}async update(e,r,n){try{let i=["updated_at = NOW()"],s=[],o=1,a=[["contactEmail","contact_email"],["contactPhone","contact_phone"],["displayName","display_name"],["displayNameSource","display_name_source"],["givenName","given_name"],["familyName","family_name"],["avatarUrl","avatar_url"],["locale","locale"],["jobTitle","job_title"],["bio","bio"]];for(let[c,u]of a)n[c]!==void 0&&(i.push(`${u} = $${o++}`),s.push(n[c]??null));return n.metadata!==void 0&&(i.push(`metadata = $${o++}`),s.push(n.metadata?JSON.stringify(n.metadata):null)),s.length===0?w(void 0):(s.push(e,r),await this.pool.query(`UPDATE user_tenant_profiles SET ${i.join(", ")} WHERE tenant_id = $${o++} AND user_id = $${o}`,s),w(void 0))}catch{return T(N.DatabaseQueryError({query:"update user tenant profile"}))}}async remove(e,r){try{return await this.pool.query("DELETE FROM user_tenant_profiles WHERE tenant_id = $1 AND user_id = $2",[e,r]),w(void 0)}catch{return T(N.DatabaseQueryError({query:"remove user tenant profile"}))}}toEntity(e){let r={tenantId:e.tenant_id,userId:e.user_id,createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at)};return e.contact_email&&(r.contactEmail=e.contact_email),e.contact_phone&&(r.contactPhone=e.contact_phone),e.display_name&&(r.displayName=e.display_name),e.display_name_source&&(r.displayNameSource=e.display_name_source),e.given_name&&(r.givenName=e.given_name),e.family_name&&(r.familyName=e.family_name),e.avatar_url&&(r.avatarUrl=e.avatar_url),e.locale&&(r.locale=e.locale),e.job_title&&(r.jobTitle=e.job_title),e.bio&&(r.bio=e.bio),e.metadata&&(r.metadata=typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata),r}};var mb=class{name="database-postgresql";version="1.0.0";users;sessions;userProviders;userMfaAuthenticators;challenges;identities;credentials;userAuths;tenants;tenantMembers;tenantInvites;userTenantProfiles;queries;pool;constructor(e){this.pool=e,this.users=new Ed(e),this.userAuths=new md(e),this.sessions=new sd(e),this.identities=new id(e),this.credentials=new nd(e),this.challenges=new rd(e),this.userProviders=new gd(e),this.userMfaAuthenticators=new hd(e),this.tenants=new fd(e),this.tenantMembers=new ud(e),this.tenantInvites=new ad(e),this.userTenantProfiles=new yd(e),this.queries={tenantInvites:new od(e),tenantMembers:new cd(e),tenants:new ld(e)}}async initialize(){}async health(){try{let e=await this.pool.connect();return await e.query("SELECT 1"),e.release(),!0}catch{return!1}}async cleanup(){await this.pool.end()}};function HO(t){let e=new mh(t);return new mb(e)}var _J={allowPlusAddressing:!0,allowDots:!0,requireTLD:!0};function GO(t={}){let e={..._J,...t},n=(()=>{if(t.customRegex)return t.customRegex;let i="[a-zA-Z0-9_\\-]";e.allowDots?(i+="+",i=`(${i}\\.?)+`):i+="+",e.allowPlusAddressing&&(i=`${i}(\\+[a-zA-Z0-9_\\-]+)?`);let s=e.requireTLD?"[a-zA-Z0-9][a-zA-Z0-9\\-]*\\.[a-zA-Z]{2,}":"[a-zA-Z0-9][a-zA-Z0-9\\-\\.]*";return new RegExp(`^${i}@${s}$`)})();return{name:"email-identity",version:"1.0.0",identityType:"email",normalize(i){return i.toLowerCase().trim()},validate(i){if(!i||i.trim().length===0)return T([{code:"EMAIL_REQUIRED",message:"Email address is required"}]);if(i.length>254)return T([{code:"EMAIL_TOO_LONG",message:"Email address is too long (max 254 characters)"}]);if(!n.test(i))return T([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);if(i.includes(".."))return T([{code:"INVALID_EMAIL_FORMAT",message:"Email address cannot contain consecutive dots"}]);let s=i.split("@");if(s.length!==2)return T([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);let[o,a]=s;return!o||o.length>64?T([{code:"EMAIL_LOCAL_PART_TOO_LONG",message:"Email local part is too long (max 64 characters)"}]):a&&a.length>253?T([{code:"EMAIL_DOMAIN_TOO_LONG",message:"Email domain is too long (max 253 characters)"}]):w()}}}var z_=ge(v_(),1),m8=ge(ir(),1);function Te(t){return t.getTime()}function oe(t){return new Date(t)}function n8(t){return Math.floor(t/1e3)}function Ne(){return Date.now()}function Kf(t){return t instanceof Date?n8(t.getTime()):n8(t)}function tv(t){return t<Date.now()}function Ui(t){return t?Te(t):null}function Xr(t){return t==null?null:oe(t)}function Zr(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}function $i(t){let e=[],r=[],n={},i={},s=0;for(let[c,u]of Object.entries(t)){if(c==="PK"||c==="SK")continue;let p=`#${c}`;if(n[p]=c,u==null)r.push(p);else{let d=`:val${s}`;e.push(`${p} = ${d}`),i[d]=u,s++}}let o=[];return e.length>0&&o.push(`SET ${e.join(", ")}`),r.length>0&&o.push(`REMOVE ${r.join(", ")}`),{UpdateExpression:o.join(" "),ExpressionAttributeNames:n,ExpressionAttributeValues:i}}function rv(t="PK"){return`attribute_not_exists(${t})`}var wr={INVITE_MEMBERS:1,REMOVE_MEMBERS:2,VIEW_MEMBERS:4,CHANGE_MEMBER_PERMISSION:8,UPDATE_MEMBER_PROFILE:16,UPDATE_MEMBER_STATUS:32,VIEW_ACCOUNTS:64,UPDATE_ACCOUNT_PROFILE:128,UPDATE_ACCOUNT_STATUS:256,RESET_ACCOUNT_CREDENTIALS:512,REMOVE_ACCOUNTS:1024},mge=wr.VIEW_ACCOUNTS|wr.UPDATE_ACCOUNT_PROFILE|wr.UPDATE_ACCOUNT_STATUS|wr.RESET_ACCOUNT_CREDENTIALS|wr.REMOVE_ACCOUNTS;var i8={[wr.INVITE_MEMBERS]:"tenant.member.invite",[wr.REMOVE_MEMBERS]:"tenant.member.remove",[wr.VIEW_MEMBERS]:"tenant.member.view",[wr.CHANGE_MEMBER_PERMISSION]:"tenant.member.permission",[wr.UPDATE_MEMBER_PROFILE]:"tenant.member.profile.update",[wr.UPDATE_MEMBER_STATUS]:"tenant.member.status.update",[wr.VIEW_ACCOUNTS]:"account.view",[wr.UPDATE_ACCOUNT_PROFILE]:"account.profile.update",[wr.UPDATE_ACCOUNT_STATUS]:"account.status.update",[wr.RESET_ACCOUNT_CREDENTIALS]:"account.credentials.reset",[wr.REMOVE_ACCOUNTS]:"account.remove"},hge=Object.fromEntries(Object.entries(i8).map(([t,e])=>[e,Number(t)]));var nv={SYSTEM:"system",DEFAULT:"org"};var iv={USER:"USR"},De={USER:`${iv.USER}#`,SESSION:"SES#",PROVIDER:"PRV#",CHALLENGE:"CHL#",IDENTITY:"IDT#",CREDENTIAL:"CRD#",TENANT:"TNT#",INVITE:"INV#"},_t={METADATA:"MD",AUTH:"AUTH",PROFILE:"PROF",PROVIDER:"PRV#",MFA:"MFA#",TENANT_PROFILE:"TPRF#",OWNER:"OWNER"},Cr="#",K={USER_PK:t=>`${De.USER}${t}`,USER_AUTH_SK:()=>_t.AUTH,USER_PROFILE_SK:()=>_t.PROFILE,USER_MFA_SK:t=>`${_t.MFA}${t}`,USER_MFA_WITH_ID_SK:(t,e)=>`${_t.MFA}${t}${Cr}${e}`,TENANT_MEMBER_PK:t=>`${De.TENANT}${t}`,TENANT_MEMBER_SK:t=>`${De.USER}${t}`,TENANT_OWNER_MARKER_SK:()=>_t.OWNER,TENANT_PK:t=>`${De.TENANT}${t}`,TENANT_SK:()=>_t.METADATA,INVITE_PK:t=>`${De.INVITE}${t}`,INVITE_SK:()=>_t.METADATA,TENANT_PROFILE_PK:t=>`${De.TENANT}${t}`,TENANT_PROFILE_SK:t=>`${_t.TENANT_PROFILE}${De.USER}${t}`,SESSION_PK:t=>`${De.SESSION}${t}`,SESSION_METADATA_SK:()=>_t.METADATA,SESSION_SK:()=>_t.METADATA,PROVIDER_SK:(t,e)=>`${_t.PROVIDER}${t}${Cr}${e}`,PROVIDER_PK:(t,e)=>`${De.PROVIDER}${t}${Cr}${e}`,PROVIDER_METADATA_SK:()=>_t.METADATA,CHALLENGE_PK:t=>`${De.CHALLENGE}${t}`,CHALLENGE_SK:()=>_t.METADATA,IDENTITY_PK:(t,e)=>`${De.IDENTITY}${t}#${e}`,IDENTITY_SK:()=>_t.METADATA,CREDENTIAL_PK:t=>`${De.CREDENTIAL}${t}`,CREDENTIAL_SK:()=>_t.METADATA,CREDENTIAL_TYPE_PREFIX:t=>`${De.CREDENTIAL}${t}#`,CREDENTIAL_USER_SK:(t,e)=>`${De.CREDENTIAL}${t}#${e}`,USER_INDEX_PK:t=>`${De.USER}${t}`,USER_INDEX_SK:(t,e)=>`${De.IDENTITY}${t}#${e}`},ve={userId:t=>t.slice(De.USER.length),sessionId:t=>t.slice(De.SESSION.length),providerPKInfo:t=>{let e=t.slice(De.PROVIDER.length),r=e.indexOf("#");if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{provider:n,externalId:i}},providerInfo:t=>{let e=t.slice(_t.PROVIDER.length),r=e.indexOf(Cr);if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{provider:n,externalId:i}},mfaSKInfo:t=>{let e=t.slice(_t.MFA.length),r=e.indexOf(Cr);if(r===-1)return{method:e};let n=e.slice(0,r),i=e.slice(r+1);return{method:n,id:i}},tenantId:t=>t.slice(De.TENANT.length),tenantMemberUserId:t=>t.slice(De.USER.length),challengeIdFromPK:t=>t.slice(De.CHALLENGE.length),inviteId:t=>t.slice(De.INVITE.length),tenantProfileUserId:t=>t.slice(_t.TENANT_PROFILE.length+De.USER.length),identityPKInfo:t=>{let e=t.slice(De.IDENTITY.length),r=e.indexOf("#");if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{type:n,value:i}},credentialId:t=>t.slice(De.CREDENTIAL.length),credentialTypeFromUserSK:t=>{let e=t.slice(De.CREDENTIAL.length),r=e.indexOf("#");return r===-1?"":e.slice(0,r)},userIndexSKInfo:t=>{let e=t.slice(De.IDENTITY.length),r=e.indexOf("#");if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{type:n,value:i}}};var ze={ACTIVE_SESSION_PK:t=>`${De.USER}${t}`,ACTIVE_SESSION_SK:(t,e)=>`${t}${Cr}${e}`,USER_SESSION_PK:t=>`${De.USER}${t}`,USER_SESSION_SK:(t,e)=>`${t}${Cr}${e}`,USER_STATUS_PK:t=>{let e=t===Hi.ACTIVE?"ACTIVE":"INACTIVE";return`${iv.USER}${Cr}${e}`},USER_STATUS_SK:t=>t,USER_PROVIDER_PK:t=>`${De.USER}${t}`,USER_PROVIDER_SK:(t,e)=>`${_t.PROVIDER}${t}${Cr}${e}`,INVITE_TENANT_PK:t=>`${De.TENANT}${t}`,INVITE_TENANT_SK:(t,e,r)=>`${t}${Cr}${e}${Cr}${r}`,INVITE_TENANT_STATUS_PREFIX:t=>`${t}${Cr}`,USER_TENANT_PK:t=>`${De.USER}${t}`,USER_TENANT_SK:(t,e,r,n)=>`${t}${Cr}${e??"ROOT"}${Cr}${r}${Cr}${n}`},E={PK:"PK",SK:"SK",TTL:"TTL",ACTIVE_SESSION_PK:"activeSessionPk",ACTIVE_SESSION_SK:"activeSessionSk",USER_SESSION_PK:"userSessionPk",USER_SESSION_SK:"userSessionSk",USER_STATUS_PK:"userStatusPk",USER_STATUS_SK:"userStatusSk",USER_PROVIDER_PK:"userProviderPk",USER_PROVIDER_SK:"userProviderSk",USER_ID:"userId",TENANT_ID:"tenantId",TENANT_TYPE:"tenantType",AUDIENCE:"audience",PURPOSE:"purpose",CHALLENGE_STATUS:"challengeStatus",PHASE:"phase",ALLOWED_METHODS:"allowedMethods",METHOD:"method",IDENTITY_TYPE:"identityType",IDENTITY_VALUE:"identityValue",CODE_HASH:"codeHash",ATTEMPTS:"attempts",MAX_ATTEMPTS:"maxAttempts",METADATA:"metadata",FLOW_KEY:"flowKey",EXPIRES_AT:"expiresAt",CREATED_AT:"createdAt",TOKEN_ID:"tokenId",PREVIOUS_TOKEN_ID:"previousTokenId",ROTATED_AT:"rotatedAt",LAST_USED_AT:"lastUsedAt",REVOKED_AT:"revokedAt",ROLE:"role",ROLES:"roles",PERM:"perm",AUTH_PERM:"authPerm",IS_OWNER:"isOwner",DEVICE_LABEL:"deviceLabel",COUNTRY:"country",CITY:"city",IDENTITY_USER_PK:"identityUserPk",IDENTITY_USER_SK:"identityUserSk",LOGIN_ENABLED:"loginEnabled",VERIFIED_AT:"verifiedAt",GUARDS:"guards",PENDING_VERIFICATION:"pendingVerification",UPDATED_AT:"updatedAt",CREDENTIAL_USER_PK:"credentialUserPk",CREDENTIAL_USER_SK:"credentialUserSk",CREDENTIAL_VALUE:"value",INVITE_STATUS:"inviteStatus",INVITE_TOKEN:"inviteToken",INVITED_BY_ID:"invitedById",INVITED_BY_INFO:"invitedByInfo",INVITEE_USER_ID:"inviteeUserId",INVITEE_EMAIL:"inviteeEmail",INVITEE_PHONE:"inviteePhone",ACCEPTED_AT:"acceptedAt",DECLINED_AT:"declinedAt",INVITE_TENANT_PK:"inviteTenantPk",INVITE_TENANT_SK:"inviteTenantSk",INVITE_TOKEN_GSI:"inviteTokenGsi",INVITEE_EMAIL_GSI:"inviteeEmailGsi",INVITEE_EMAIL_TENANT_SK:"inviteeEmailTenantSk",INVITEE_PHONE_GSI:"inviteePhoneGsi",INVITEE_PHONE_TENANT_SK:"inviteePhoneTenantSk",USER_TENANT_PK:"userTenantPk",USER_TENANT_SK:"userTenantSk",DISPLAY_NAME:"displayName",AVATAR_URL:"avatarUrl",TITLE:"title",BIO:"bio"},tt={ACTIVE_SESSIONS:"GSI_ActiveSessions",USER_SESSIONS:"GSI_UserSessions",USERS_BY_STATUS:"GSI_UsersByStatus",USER_PROVIDERS:"GSI_UserProviders",USER_IDENTITIES:"GSI_UserIdentities",USER_CREDENTIALS:"GSI_UserCredentials",TENANT_INVITES:"GSI_TenantInvites",INVITE_TOKEN:"GSI_InviteToken",INVITEE_EMAIL:"GSI_InviteeEmail",INVITEE_PHONE:"GSI_InviteePhone",USER_TENANTS:"GSI_UserTenants"},q_={sessionSK:(t,e)=>`${t instanceof Date?t.getTime():t}${Cr}${e}`,extractCreatedAt:t=>{let e=t.indexOf(Cr),r=e===-1?t:t.slice(0,e);return Number(r)}};var Po=ge(ir(),1);function Vf(t){if(typeof t=="object"&&t!==null&&"name"in t){let{name:e}=t;return typeof e=="string"?e:void 0}}function lt(t){return Vf(t)==="ConditionalCheckFailedException"}var Hf=class{docClient;tableName;ttlGracePeriod;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||3600*1e3}generateChallengeId(){return Lt()}async get(e){try{let r=await this.docClient.send(new Po.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.CHALLENGE_PK(e),[E.SK]:K.CHALLENGE_SK()}}));if(!r.Item)return w(null);let n=this.unmarshall(r.Item);return tv(Te(n.expiresAt))?w(null):w(n)}catch{return T(N.DatabaseQueryError({query:"get challenge"}))}}async create(e){try{let r=Ne(),n=e.id||this.generateChallengeId(),i={...e,id:n,createdAt:oe(r)},s=Te(e.expiresAt),o=Math.floor((s+this.ttlGracePeriod)/1e3);return await this.docClient.send(new Po.PutCommand({TableName:this.tableName,Item:this.marshall(i,o)})),w(i)}catch{return T(N.DatabaseQueryError({query:"create challenge"}))}}async update(e,r){try{let n=[],i={},s={};return r.method!==void 0&&(n.push("#method = :method"),i["#method"]=E.METHOD,s[":method"]=r.method),r.phase!==void 0&&(n.push("#phase = :phase"),i["#phase"]=E.PHASE,s[":phase"]=r.phase),r.codeHash!==void 0&&(n.push("#codeHash = :codeHash"),i["#codeHash"]=E.CODE_HASH,s[":codeHash"]=r.codeHash),r.status!==void 0&&(n.push("#challengeStatus = :challengeStatus"),i["#challengeStatus"]=E.CHALLENGE_STATUS,s[":challengeStatus"]=r.status),n.length===0?w(void 0):(await this.docClient.send(new Po.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.CHALLENGE_PK(e),[E.SK]:K.CHALLENGE_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:i,ExpressionAttributeValues:s})),w(void 0))}catch{return T(N.DatabaseQueryError({query:"update challenge"}))}}async incrementAttempts(e,r){let n={":zero":0,":inc":1},i;r!==void 0&&(i="attribute_not_exists(#attempts) OR #attempts < :max",n[":max"]=r);try{let o=(await this.docClient.send(new Po.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.CHALLENGE_PK(e),[E.SK]:K.CHALLENGE_SK()},UpdateExpression:"SET #attempts = if_not_exists(#attempts, :zero) + :inc",...i?{ConditionExpression:i}:{},ExpressionAttributeNames:{"#attempts":E.ATTEMPTS},ExpressionAttributeValues:n,ReturnValues:"UPDATED_NEW"}))).Attributes?.[E.ATTEMPTS]??0;return w(o)}catch(s){return lt(s)?T(N.AttemptsExceeded()):T(N.DatabaseQueryError({query:"increment challenge attempts"}))}}async remove(e){try{return await this.docClient.send(new Po.DeleteCommand({TableName:this.tableName,Key:{[E.PK]:K.CHALLENGE_PK(e),[E.SK]:K.CHALLENGE_SK()},ConditionExpression:"attribute_exists(#pk)",ExpressionAttributeNames:{"#pk":E.PK}})),w(void 0)}catch(r){return lt(r)?w(void 0):T(N.DatabaseQueryError({query:"remove challenge"}))}}marshall(e,r){let n={[E.PK]:K.CHALLENGE_PK(e.id),[E.SK]:K.CHALLENGE_SK(),[E.USER_ID]:e.userId,[E.PURPOSE]:e.purpose,[E.CHALLENGE_STATUS]:e.status,[E.EXPIRES_AT]:Te(e.expiresAt),[E.CREATED_AT]:Te(e.createdAt),[E.TTL]:r};return e.tenantId&&(n[E.TENANT_ID]=e.tenantId),e.phase&&(n[E.PHASE]=e.phase),e.allowedMethods&&e.allowedMethods.length>0&&(n[E.ALLOWED_METHODS]=e.allowedMethods),e.method&&(n[E.METHOD]=e.method),e.codeHash&&(n[E.CODE_HASH]=e.codeHash),e.attempts!==void 0&&(n[E.ATTEMPTS]=e.attempts),e.maxAttempts!==void 0&&(n[E.MAX_ATTEMPTS]=e.maxAttempts),e.identityType&&(n[E.IDENTITY_TYPE]=e.identityType),e.identityValue&&(n[E.IDENTITY_VALUE]=e.identityValue),e.deviceLabel&&(n[E.DEVICE_LABEL]=e.deviceLabel),e.country&&(n[E.COUNTRY]=e.country),e.city&&(n[E.CITY]=e.city),e.metadata&&(n[E.METADATA]=e.metadata),e.flowKey&&(n[E.FLOW_KEY]=e.flowKey),n}unmarshall(e){let n={id:ve.challengeIdFromPK(e[E.PK]),userId:e[E.USER_ID],purpose:e[E.PURPOSE],status:e[E.CHALLENGE_STATUS],expiresAt:oe(e[E.EXPIRES_AT]),createdAt:oe(e[E.CREATED_AT])};return e[E.TENANT_ID]&&(n.tenantId=e[E.TENANT_ID]),e[E.PHASE]&&(n.phase=e[E.PHASE]),e[E.ALLOWED_METHODS]&&(n.allowedMethods=e[E.ALLOWED_METHODS]),e[E.METHOD]&&(n.method=e[E.METHOD]),e[E.CODE_HASH]&&(n.codeHash=e[E.CODE_HASH]),e[E.ATTEMPTS]!==void 0&&(n.attempts=e[E.ATTEMPTS]),e[E.MAX_ATTEMPTS]!==void 0&&(n.maxAttempts=e[E.MAX_ATTEMPTS]),e[E.IDENTITY_TYPE]&&(n.identityType=e[E.IDENTITY_TYPE]),e[E.IDENTITY_VALUE]&&(n.identityValue=e[E.IDENTITY_VALUE]),e[E.DEVICE_LABEL]&&(n.deviceLabel=e[E.DEVICE_LABEL]),e[E.COUNTRY]&&(n.country=e[E.COUNTRY]),e[E.CITY]&&(n.city=e[E.CITY]),e[E.METADATA]&&(n.metadata=e[E.METADATA]),e[E.FLOW_KEY]&&(n.flowKey=e[E.FLOW_KEY]),n}};var en=ge(ir(),1);var Gf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateCredentialId(){return Lt()}async get(e){try{let r=await this.docClient.send(new en.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.CREDENTIAL_PK(e),[E.SK]:K.CREDENTIAL_SK()}}));return r.Item?w(this.unmarshall(r.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"get credential"}))}}async getByUserIdAndType(e,r){try{let n=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:tt.USER_CREDENTIALS,KeyConditionExpression:`${E.CREDENTIAL_USER_PK} = :userPk AND begins_with(${E.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":K.USER_PK(e),":typePrefix":K.CREDENTIAL_TYPE_PREFIX(r)},Limit:1}));if(!n.Items||n.Items.length===0)return w(null);let i=n.Items[0];if(!i)return w(null);let s=ve.credentialId(i[E.PK]);return this.get(s)}catch{return T(N.DatabaseQueryError({query:"get credential by user and type"}))}}async getByUserId(e){try{let r=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:tt.USER_CREDENTIALS,KeyConditionExpression:`${E.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":K.USER_PK(e)}}));if(!r.Items||r.Items.length===0)return w([]);let n=r.Items.map(o=>ve.credentialId(o[E.PK])),i=await this.batchGet(n);if(i.ok===!1)return T(i.errors,i.meta);if(!i.data)return w([]);let s=i.data.filter(o=>o!==null);return w(s)}catch{return T(N.DatabaseQueryError({query:"get credentials by user"}))}}async create(e){try{let r=Ne(),n=this.generateCredentialId(),i={revokedAt:null,lastUsedAt:null,...e,id:n,createdAt:new Date(r),updatedAt:new Date(r)};return await this.docClient.send(new en.PutCommand({TableName:this.tableName,Item:this.marshall(i),ConditionExpression:`attribute_not_exists(${E.PK})`})),w(i)}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"credential"})):T(N.DatabaseQueryError({query:"create credential"}))}}async update(e,r){try{let n=Ne(),i=[],s={},o={};return i.push(`#${E.UPDATED_AT} = :updatedAt`),s[`#${E.UPDATED_AT}`]=E.UPDATED_AT,o[":updatedAt"]=n,r.value!==void 0&&(i.push(`#${E.CREDENTIAL_VALUE} = :value`),s[`#${E.CREDENTIAL_VALUE}`]=E.CREDENTIAL_VALUE,o[":value"]=r.value),r.data!==void 0&&(i.push(`#${E.METADATA} = :data`),s[`#${E.METADATA}`]=E.METADATA,o[":data"]=r.data),r.revokedAt!==void 0&&(i.push(`#${E.REVOKED_AT} = :revokedAt`),s[`#${E.REVOKED_AT}`]=E.REVOKED_AT,o[":revokedAt"]=r.revokedAt?Te(r.revokedAt):null),r.lastUsedAt!==void 0&&(i.push(`#${E.LAST_USED_AT} = :lastUsedAt`),s[`#${E.LAST_USED_AT}`]=E.LAST_USED_AT,o[":lastUsedAt"]=r.lastUsedAt?Te(r.lastUsedAt):null),await this.docClient.send(new en.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.CREDENTIAL_PK(e),[E.SK]:K.CREDENTIAL_SK()},UpdateExpression:`SET ${i.join(", ")}`,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"credential",id:e})):T(N.DatabaseQueryError({query:"update credential"}))}}async remove(e){try{return await this.docClient.send(new en.DeleteCommand({TableName:this.tableName,Key:{[E.PK]:K.CREDENTIAL_PK(e),[E.SK]:K.CREDENTIAL_SK()},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(r){return lt(r)?T(N.NotFound({entity:"credential",id:e})):T(N.DatabaseQueryError({query:"delete credential"}))}}async hasType(e,r){try{let n=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:tt.USER_CREDENTIALS,KeyConditionExpression:`${E.CREDENTIAL_USER_PK} = :userPk AND begins_with(${E.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":K.USER_PK(e),":typePrefix":K.CREDENTIAL_TYPE_PREFIX(r)},Select:"COUNT",Limit:1}));return w((n.Count||0)>0)}catch{return T(N.DatabaseQueryError({query:"check credential type"}))}}async countByUserId(e){try{let r=await this.docClient.send(new en.QueryCommand({TableName:this.tableName,IndexName:tt.USER_CREDENTIALS,KeyConditionExpression:`${E.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":K.USER_PK(e)},Select:"COUNT"}));return w(r.Count||0)}catch{return T(N.DatabaseQueryError({query:"count credentials"}))}}async batchGet(e){if(e.length===0)return w([]);try{let r=[];for(let i=0;i<e.length;i+=100)r.push(e.slice(i,i+100));let n=[];for(let i of r){let o=(await this.docClient.send(new en.BatchGetCommand({RequestItems:{[this.tableName]:{Keys:i.map(c=>({[E.PK]:K.CREDENTIAL_PK(c),[E.SK]:K.CREDENTIAL_SK()}))}}}))).Responses?.[this.tableName]||[],a=new Map;for(let c of o){let u=this.unmarshall(c);a.set(u.id,u)}for(let c of i)n.push(a.get(c)||null)}return w(n)}catch{return T(N.DatabaseQueryError({query:"batch get credentials"}))}}marshall(e){let r={[E.PK]:K.CREDENTIAL_PK(e.id),[E.SK]:K.CREDENTIAL_SK(),[E.CREDENTIAL_USER_PK]:K.USER_PK(e.userId),[E.CREDENTIAL_USER_SK]:K.CREDENTIAL_USER_SK(e.type,e.id),[E.USER_ID]:e.userId,[E.CREDENTIAL_VALUE]:e.value,[E.METADATA]:e.data,[E.REVOKED_AT]:e.revokedAt?Te(e.revokedAt):null,[E.CREATED_AT]:Te(e.createdAt),[E.UPDATED_AT]:Te(e.updatedAt)};return e.lastUsedAt&&(r[E.LAST_USED_AT]=Te(e.lastUsedAt)),r}unmarshall(e){let r=ve.credentialId(e[E.PK]),n=ve.credentialTypeFromUserSK(e[E.CREDENTIAL_USER_SK]);return{id:r,userId:e[E.USER_ID],type:n,value:e[E.CREDENTIAL_VALUE],data:e[E.METADATA]||{},revokedAt:Xr(e[E.REVOKED_AT]),createdAt:oe(e[E.CREATED_AT]),updatedAt:oe(e[E.UPDATED_AT]),lastUsedAt:Xr(e[E.LAST_USED_AT])}}};var Tn=ge(ir(),1);function sv(t){return{failedAttempts:t.failedAttempts,lastFailedAt:Ui(t.lastFailedAt),lockedUntil:Ui(t.lockedUntil)}}function s8(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t))e[r]={failedAttempts:n.failedAttempts??0,lastFailedAt:Xr(n.lastFailedAt),lockedUntil:Xr(n.lockedUntil)};return e}function o8(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t))n&&(e[r]=sv(n));return e}var qf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async get(e,r){try{let n=await this.docClient.send(new Tn.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.IDENTITY_PK(e,r),[E.SK]:K.IDENTITY_SK()}}));if(!n.Item)return w(null);let i=this.unmarshall(n.Item);return w(i)}catch(n){return console.error("[DynamoDB] identities.get error:",n),T(N.DatabaseQueryError({query:"get identity"}))}}async getByUserId(e){try{let r=await this.docClient.send(new Tn.QueryCommand({TableName:this.tableName,IndexName:tt.USER_IDENTITIES,KeyConditionExpression:`${E.IDENTITY_USER_PK} = :pk`,ExpressionAttributeValues:{":pk":K.USER_INDEX_PK(e)}})),n=[];for(let i of r.Items||[]){let s=this.unmarshall(i);s!==null&&n.push(s)}return w(n)}catch{return T(N.DatabaseQueryError({query:"get identities by userId"}))}}async create(e){try{let r=Ne(),n={...e,createdAt:oe(r),updatedAt:oe(r)};return await this.docClient.send(new Tn.PutCommand({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:"attribute_not_exists(PK)"})),w(n)}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"identity"})):T(N.DatabaseQueryError({query:"create identity"}))}}async update(e,r,n){try{let i=[],s=[],o={},a={};if(n.loginEnabled!==void 0&&(i.push("#loginEnabled = :loginEnabled"),o["#loginEnabled"]=E.LOGIN_ENABLED,a[":loginEnabled"]=n.loginEnabled),n.verifiedAt!==void 0){let u=Ui(n.verifiedAt);u===null?(s.push("#verifiedAt"),o["#verifiedAt"]=E.VERIFIED_AT):(i.push("#verifiedAt = :verifiedAt"),o["#verifiedAt"]=E.VERIFIED_AT,a[":verifiedAt"]=u)}n.guards!==void 0&&(i.push("#guards = :guards"),o["#guards"]=E.GUARDS,a[":guards"]=o8(n.guards)),n.pendingVerification!==void 0&&(o["#pendingVerification"]=E.PENDING_VERIFICATION,n.pendingVerification===null?s.push("#pendingVerification"):(i.push("#pendingVerification = :pendingVerification"),a[":pendingVerification"]=Zr({...n.pendingVerification,expiresAt:Te(n.pendingVerification.expiresAt),resendAvailableAt:Ui(n.pendingVerification.resendAvailableAt)}))),i.push("#updatedAt = :updatedAt"),o["#updatedAt"]=E.UPDATED_AT,a[":updatedAt"]=Ne();let c=[];return i.length>0&&c.push(`SET ${i.join(", ")}`),s.length>0&&c.push(`REMOVE ${s.join(", ")}`),await this.docClient.send(new Tn.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.IDENTITY_PK(e,r),[E.SK]:K.IDENTITY_SK()},UpdateExpression:c.join(" "),ExpressionAttributeNames:o,ExpressionAttributeValues:a})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"update identity"}))}}async remove(e,r){try{return await this.docClient.send(new Tn.DeleteCommand({TableName:this.tableName,Key:{[E.PK]:K.IDENTITY_PK(e,r),[E.SK]:K.IDENTITY_SK()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"remove identity"}))}}async updateGuard(e,r,n,i){let s={[E.PK]:K.IDENTITY_PK(e,r),[E.SK]:K.IDENTITY_SK()};try{return await this.docClient.send(new Tn.UpdateCommand({TableName:this.tableName,Key:s,UpdateExpression:"SET #guards.#guardKey = :guard, #updatedAt = :updatedAt",ConditionExpression:"attribute_exists(#guards)",ExpressionAttributeNames:{"#guards":E.GUARDS,"#guardKey":n,"#updatedAt":E.UPDATED_AT},ExpressionAttributeValues:{":guard":sv(i),":updatedAt":Ne()}})),w(void 0)}catch(o){if(lt(o))try{return await this.docClient.send(new Tn.UpdateCommand({TableName:this.tableName,Key:s,UpdateExpression:"SET #guards = :guards, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#guards":E.GUARDS,"#updatedAt":E.UPDATED_AT},ExpressionAttributeValues:{":guards":{[n]:sv(i)},":updatedAt":Ne()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"update guard"}))}return T(N.DatabaseQueryError({query:"update guard"}))}}async batchGet(e){try{if(e.length===0)return w([]);let n=(await this.docClient.send(new Tn.BatchGetCommand({RequestItems:{[this.tableName]:{Keys:e.map(({type:o,value:a})=>({[E.PK]:K.IDENTITY_PK(o,a),[E.SK]:K.IDENTITY_SK()}))}}}))).Responses?.[this.tableName]||[],i=new Map;for(let o of n){let a=this.unmarshall(o);if(a!==null){let c=`${a.type}#${a.value}`;i.set(c,a)}}let s=e.map(({type:o,value:a})=>{let c=`${o}#${a}`;return i.get(c)||null});return w(s)}catch{return T(N.DatabaseQueryError({query:"batch get identities"}))}}marshall(e){let r={[E.PK]:K.IDENTITY_PK(e.type,e.value),[E.SK]:K.IDENTITY_SK(),[E.IDENTITY_USER_PK]:K.USER_INDEX_PK(e.userId),[E.IDENTITY_USER_SK]:K.USER_INDEX_SK(e.type,e.value),[E.USER_ID]:e.userId,[E.LOGIN_ENABLED]:e.loginEnabled,[E.CREATED_AT]:Te(e.createdAt),[E.UPDATED_AT]:Te(e.updatedAt)},n=Ui(e.verifiedAt);return n!==null&&(r[E.VERIFIED_AT]=n),r[E.GUARDS]=o8(e.guards),e.pendingVerification&&(r[E.PENDING_VERIFICATION]=Zr({...e.pendingVerification,expiresAt:Te(e.pendingVerification.expiresAt),resendAvailableAt:Ui(e.pendingVerification.resendAvailableAt)})),r}unmarshall(e){let r=ve.identityPKInfo(e[E.PK]);if(!r){let n=e[E.IDENTITY_USER_SK]?ve.userIndexSKInfo(e[E.IDENTITY_USER_SK]):null;return n?{type:n.type,value:n.value,userId:e[E.USER_ID],loginEnabled:e[E.LOGIN_ENABLED],verifiedAt:Xr(e[E.VERIFIED_AT]),guards:s8(e[E.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[E.PENDING_VERIFICATION]),createdAt:oe(e[E.CREATED_AT]),updatedAt:oe(e[E.UPDATED_AT])}:(console.warn("Invalid identity item format, skipping:",{PK:e[E.PK],GSI1SK:e[E.IDENTITY_USER_SK]}),null)}return{type:r.type,value:r.value,userId:e[E.USER_ID],loginEnabled:e[E.LOGIN_ENABLED],verifiedAt:Xr(e[E.VERIFIED_AT]),guards:s8(e[E.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[E.PENDING_VERIFICATION]),createdAt:oe(e[E.CREATED_AT]),updatedAt:oe(e[E.UPDATED_AT])}}unmarshallPendingVerification(e){if(!e||typeof e!="object")return null;let r=e;return{challengeId:r.challengeId,purpose:r.purpose,channel:r.channel,expiresAt:oe(r.expiresAt),resendAvailableAt:Xr(r.resendAvailableAt)}}};var a8=ge(ir(),1);var Wf=class{docClient;tableName;ttlGracePeriod;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||3600*1e3}async createEmailVerificationRegistration(e){try{let r=Ne(),n=Lt(),i=Te(e.challenge.expiresAt),s=Math.floor((i+this.ttlGracePeriod)/1e3);return await this.docClient.send(new a8.TransactWriteCommand({TransactItems:[this.putItem(this.marshallProfile(e,r)),this.putItem(this.marshallUserAuth(e,r)),this.putItem(this.marshallIdentity(e,r)),this.putItem(this.marshallCredential(e,n,r)),this.putItem(this.marshallChallenge(e,r,s))]})),w(void 0)}catch(r){return Vf(r)==="TransactionCanceledException"||lt(r)?T(N.UniqueConstraintViolation({field:"registration"})):T(N.DatabaseQueryError({query:"create email verification registration transaction"}))}}putItem(e){return{Put:{TableName:this.tableName,Item:Zr(e),ConditionExpression:`attribute_not_exists(${E.PK})`}}}marshallProfile(e,r){let n=e.profile.status,i={[E.PK]:K.USER_PK(e.profile.id),[E.SK]:K.USER_PROFILE_SK(),userStatus:n,[E.CREATED_AT]:r,[E.UPDATED_AT]:r,[E.USER_STATUS_PK]:ze.USER_STATUS_PK(n),[E.USER_STATUS_SK]:ze.USER_STATUS_SK(e.profile.id)};return e.profile.contactEmail&&(i.contactEmail=e.profile.contactEmail),e.profile.contactPhone&&(i.contactPhone=e.profile.contactPhone),e.profile.username&&(i.username=e.profile.username),e.profile.displayName&&(i.displayName=e.profile.displayName),e.profile.givenName&&(i.givenName=e.profile.givenName),e.profile.familyName&&(i.familyName=e.profile.familyName),e.profile.avatarUrl&&(i.avatarUrl=e.profile.avatarUrl),e.profile.locale&&(i.locale=e.profile.locale),e.profile.metadata&&(i.metadata=JSON.stringify(e.profile.metadata)),i}marshallUserAuth(e,r){return{[E.PK]:K.USER_PK(e.userAuth.userId),[E.SK]:K.USER_AUTH_SK(),userStatus:e.userAuth.userStatus,mfaRequired:e.userAuth.mfaRequired,mfaMethods:e.userAuth.mfaMethods,[E.CREATED_AT]:r,[E.UPDATED_AT]:r}}marshallIdentity(e,r){let n=e.identity,i={[E.PK]:K.IDENTITY_PK(n.type,n.value),[E.SK]:K.IDENTITY_SK(),[E.IDENTITY_USER_PK]:K.USER_INDEX_PK(n.userId),[E.IDENTITY_USER_SK]:K.USER_INDEX_SK(n.type,n.value),[E.USER_ID]:n.userId,[E.LOGIN_ENABLED]:n.loginEnabled,[E.CREATED_AT]:r,[E.UPDATED_AT]:r,[E.PENDING_VERIFICATION]:Zr({...n.pendingVerification,expiresAt:Te(n.pendingVerification.expiresAt),resendAvailableAt:Ui(n.pendingVerification.resendAvailableAt)})},s=Ui(n.verifiedAt);return s!==null&&(i[E.VERIFIED_AT]=s),i[E.GUARDS]=n.guards??{},i}marshallCredential(e,r,n){let i=e.credential,s={[E.PK]:K.CREDENTIAL_PK(r),[E.SK]:K.CREDENTIAL_SK(),[E.CREDENTIAL_USER_PK]:K.USER_PK(i.userId),[E.CREDENTIAL_USER_SK]:K.CREDENTIAL_USER_SK(i.type,r),[E.USER_ID]:i.userId,[E.CREDENTIAL_VALUE]:i.value,[E.METADATA]:i.data,[E.REVOKED_AT]:i.revokedAt?Te(i.revokedAt):null,[E.CREATED_AT]:n,[E.UPDATED_AT]:n};return i.lastUsedAt&&(s[E.LAST_USED_AT]=Te(i.lastUsedAt)),s}marshallChallenge(e,r,n){let i=e.challenge,s={[E.PK]:K.CHALLENGE_PK(i.id),[E.SK]:K.CHALLENGE_SK(),[E.USER_ID]:i.userId,[E.PURPOSE]:i.purpose,[E.CHALLENGE_STATUS]:i.status,[E.EXPIRES_AT]:Te(i.expiresAt),[E.CREATED_AT]:r,[E.TTL]:n};return i.tenantId&&(s[E.TENANT_ID]=i.tenantId),i.phase&&(s[E.PHASE]=i.phase),i.allowedMethods&&i.allowedMethods.length>0&&(s[E.ALLOWED_METHODS]=i.allowedMethods),i.method&&(s[E.METHOD]=i.method),i.codeHash&&(s[E.CODE_HASH]=i.codeHash),i.attempts!==void 0&&(s[E.ATTEMPTS]=i.attempts),i.maxAttempts!==void 0&&(s[E.MAX_ATTEMPTS]=i.maxAttempts),i.identityType&&(s[E.IDENTITY_TYPE]=i.identityType),i.identityValue&&(s[E.IDENTITY_VALUE]=i.identityValue),i.deviceLabel&&(s[E.DEVICE_LABEL]=i.deviceLabel),i.country&&(s[E.COUNTRY]=i.country),i.city&&(s[E.CITY]=i.city),i.metadata&&(s[E.METADATA]=i.metadata),i.flowKey&&(s[E.FLOW_KEY]=i.flowKey),s}};var d8=ge(v_(),1),Zt=ge(ir(),1);var l8=ge(ir(),1),c8=100,u8=5;function Ege(t){return new Promise(e=>setTimeout(e,t))}async function Sl(t,e,r){if(r.length===0)return[];let n=[];for(let i=0;i<r.length;i+=c8){let s=r.slice(i,i+c8),o=0;for(;s.length>0;){let a=await t.send(new l8.BatchGetCommand({RequestItems:{[e]:{Keys:s}}})),c=a.Responses?.[e];c&&n.push(...c);let u=a.UnprocessedKeys?.[e]?.Keys;if(!u||u.length===0)break;if(o+=1,o>u8)throw new Error(`BatchGet left ${u.length} unprocessed keys after ${u8} retries`);s=u,await Ege(2**o*25)}}return n}var jf=class{docClient;tableName;ttlGracePeriod;constructor(e){let r=e.client||new d8.DynamoDBClient({});this.docClient=e.docClient||Zt.DynamoDBDocumentClient.from(r),this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||10080*60*1e3}generateSessionId(){return Lt()}generateTokenId(){return Lt()}async get(e){try{let r=await this.docClient.send(new Zt.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()}}));return r.Item?w(this.unmarshall(r.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"get session"}))}}async create(e){try{let r=Ne(),n=e.id||this.generateSessionId(),i=e.tokenId||this.generateTokenId(),s={...e,id:n,tokenId:i,revokedAt:null,createdAt:new Date(r),lastUsedAt:new Date(r)},o=Kf(Te(e.expiresAt)+this.ttlGracePeriod),a=q_.sessionSK(r,n);return await this.docClient.send(new Zt.PutCommand({TableName:this.tableName,Item:this.marshall(s,o,a)})),w(s)}catch{return T(N.DatabaseQueryError({query:"create session"}))}}async update(e,r){try{let n=[],i={},s={};if(r.tokenId!==void 0&&(n.push(`#${E.TOKEN_ID} = :tokenId`),i[`#${E.TOKEN_ID}`]=E.TOKEN_ID,s[":tokenId"]=r.tokenId),r.expiresAt!==void 0){n.push(`#${E.EXPIRES_AT} = :expiresAt`),i[`#${E.EXPIRES_AT}`]=E.EXPIRES_AT,s[":expiresAt"]=Te(r.expiresAt);let o=Kf(Te(r.expiresAt)+this.ttlGracePeriod);n.push(`#${E.TTL} = :ttl`),i[`#${E.TTL}`]=E.TTL,s[":ttl"]=o}return r.lastUsedAt!==void 0&&(n.push(`#${E.LAST_USED_AT} = :lastUsedAt`),i[`#${E.LAST_USED_AT}`]=E.LAST_USED_AT,s[":lastUsedAt"]=Te(r.lastUsedAt)),r.metadata!==void 0&&(n.push(`#${E.METADATA} = :metadata`),i[`#${E.METADATA}`]=E.METADATA,s[":metadata"]=r.metadata),r.previousTokenId!==void 0&&(n.push(`#${E.PREVIOUS_TOKEN_ID} = :previousTokenId`),i[`#${E.PREVIOUS_TOKEN_ID}`]=E.PREVIOUS_TOKEN_ID,s[":previousTokenId"]=r.previousTokenId),r.rotatedAt!==void 0&&(n.push(`#${E.ROTATED_AT} = :rotatedAt`),i[`#${E.ROTATED_AT}`]=E.ROTATED_AT,s[":rotatedAt"]=r.rotatedAt),n.length===0?w():(await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:i,ExpressionAttributeValues:s})),w())}catch{return T(N.DatabaseQueryError({query:"update session"}))}}async rotateToken(e,r,n){try{let i=Kf(Te(n.expiresAt)+this.ttlGracePeriod);return await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET #${E.TOKEN_ID} = :tokenId, #${E.PREVIOUS_TOKEN_ID} = :previousTokenId, #${E.ROTATED_AT} = :rotatedAt, #${E.EXPIRES_AT} = :expiresAt, #${E.LAST_USED_AT} = :lastUsedAt, #${E.TTL} = :ttl`,ConditionExpression:`#${E.TOKEN_ID} = :expectedCurrentTokenId`,ExpressionAttributeNames:{[`#${E.TOKEN_ID}`]:E.TOKEN_ID,[`#${E.PREVIOUS_TOKEN_ID}`]:E.PREVIOUS_TOKEN_ID,[`#${E.ROTATED_AT}`]:E.ROTATED_AT,[`#${E.EXPIRES_AT}`]:E.EXPIRES_AT,[`#${E.LAST_USED_AT}`]:E.LAST_USED_AT,[`#${E.TTL}`]:E.TTL},ExpressionAttributeValues:{":tokenId":n.tokenId,":previousTokenId":n.previousTokenId,":rotatedAt":n.rotatedAt,":expiresAt":Te(n.expiresAt),":lastUsedAt":Te(n.lastUsedAt),":ttl":i,":expectedCurrentTokenId":r}})),w(!0)}catch(i){return lt(i)?w(!1):T(N.DatabaseQueryError({query:"rotate session token"}))}}async switchTenant(e,r){try{let n=[`#${E.TENANT_ID} = :tenantId`,`#${E.TOKEN_ID} = :tokenId`,`#${E.LAST_USED_AT} = :lastUsedAt`],i=[],s={[`#${E.TENANT_ID}`]:E.TENANT_ID,[`#${E.TOKEN_ID}`]:E.TOKEN_ID,[`#${E.LAST_USED_AT}`]:E.LAST_USED_AT},o={":tenantId":r.tenantId,":tokenId":r.tokenId,":lastUsedAt":Ne()};s[`#${E.TENANT_TYPE}`]=E.TENANT_TYPE,r.tenantType!==void 0?(n.push(`#${E.TENANT_TYPE} = :tenantType`),o[":tenantType"]=r.tenantType):i.push(`#${E.TENANT_TYPE}`),s[`#${E.PERM}`]=E.PERM,r.perms!==void 0?(n.push(`#${E.PERM} = :perms`),o[":perms"]=JSON.stringify(r.perms)):i.push(`#${E.PERM}`),s[`#${E.ROLES}`]=E.ROLES,r.roles!==void 0?(n.push(`#${E.ROLES} = :roles`),o[":roles"]=r.roles):i.push(`#${E.ROLES}`),s["#revokedAt"]=E.REVOKED_AT;let a=`SET ${n.join(", ")}${i.length>0?` REMOVE ${i.join(", ")}`:""}`;return await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:a,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:`attribute_exists(${E.PK}) AND attribute_not_exists(#revokedAt)`})),w()}catch(n){return lt(n)?T(N.DatabaseQueryError({query:"switch tenant - session not found or revoked"})):T(N.DatabaseQueryError({query:"switch tenant"}))}}async revoke(e){try{return await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET #${E.REVOKED_AT} = :revokedAt REMOVE #${E.ACTIVE_SESSION_PK}, #${E.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${E.REVOKED_AT}`]:E.REVOKED_AT,[`#${E.ACTIVE_SESSION_PK}`]:E.ACTIVE_SESSION_PK,[`#${E.ACTIVE_SESSION_SK}`]:E.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":Te(new Date)},ConditionExpression:`attribute_exists(${E.PK})`})),w()}catch(r){return lt(r)?w():T(N.DatabaseQueryError({query:"revoke session"}))}}async revokeByIdAndUserId(e,r){try{return await this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(e),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET #${E.REVOKED_AT} = :revokedAt REMOVE #${E.ACTIVE_SESSION_PK}, #${E.ACTIVE_SESSION_SK}`,ConditionExpression:`#${E.USER_ID} = :userId AND attribute_not_exists(#${E.REVOKED_AT})`,ExpressionAttributeNames:{[`#${E.REVOKED_AT}`]:E.REVOKED_AT,[`#${E.USER_ID}`]:E.USER_ID,[`#${E.ACTIVE_SESSION_PK}`]:E.ACTIVE_SESSION_PK,[`#${E.ACTIVE_SESSION_SK}`]:E.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":Te(new Date),":userId":r}})),w()}catch(n){return lt(n)?w():T(N.DatabaseQueryError({query:"revoke session by user"}))}}async findByUserId(e,r){try{let n=Math.min(r?.limit||50,100),i;if(r?.cursor)try{i=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))}catch{return T(N.DatabaseQueryError({query:"invalid pagination cursor"}))}let s=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.USER_SESSIONS,KeyConditionExpression:`${E.USER_SESSION_PK} = :userPk`,ExpressionAttributeValues:{":userPk":K.USER_PK(e)},Limit:n,ExclusiveStartKey:i,ScanIndexForward:!1}));if(!s.Items||s.Items.length===0){let y={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!r?.cursor,cursor:null};return w([],{pagination:y})}let a=s.Items.map(y=>ve.sessionId(y[E.PK])).map(y=>({[E.PK]:K.SESSION_PK(y),[E.SK]:K.SESSION_SK()})),u=(await Sl(this.docClient,this.tableName,a)).map(y=>this.unmarshall(y)),p=!!s.LastEvaluatedKey,d=p?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null,h={type:"cursor",limit:n,count:u.length,hasNext:p,hasPrev:!!r?.cursor,cursor:d};return w(u,{pagination:h})}catch{return T(N.DatabaseQueryError({query:"find sessions by user"}))}}async findActiveByUserId(e,r){try{let n=Math.min(r?.limit||50,100),i;if(r?.cursor)try{i=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))}catch{return T(N.DatabaseQueryError({query:"invalid pagination cursor"}))}let s=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.ACTIVE_SESSIONS,KeyConditionExpression:`${E.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":ze.ACTIVE_SESSION_PK(e)},Limit:n,ExclusiveStartKey:i,ScanIndexForward:!1}));if(!s.Items||s.Items.length===0){let y={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!r?.cursor,cursor:null};return w([],{pagination:y})}let a=s.Items.map(y=>ve.sessionId(y[E.PK])).map(y=>({[E.PK]:K.SESSION_PK(y),[E.SK]:K.SESSION_SK()})),u=(await Sl(this.docClient,this.tableName,a)).map(y=>this.unmarshall(y)),p=!!s.LastEvaluatedKey,d=p?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null,h={type:"cursor",limit:n,count:u.length,hasNext:p,hasPrev:!!r?.cursor,cursor:d};return w(u,{pagination:h})}catch{return T(N.DatabaseQueryError({query:"find active sessions by user"}))}}async getActiveSessionsForLimit(e){try{let r=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.ACTIVE_SESSIONS,KeyConditionExpression:`${E.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":ze.ACTIVE_SESSION_PK(e)},ScanIndexForward:!0}));if(!r.Items||r.Items.length===0)return w([]);let n=r.Items.map(i=>{let s=ve.sessionId(i[E.PK]),o=q_.extractCreatedAt(i[E.ACTIVE_SESSION_SK]);return{id:s,createdAt:new Date(o)}});return w(n)}catch{return T(N.DatabaseQueryError({query:"get active sessions for limit"}))}}async revokeSessionsByIds(e,r){if(e.length===0)return 0;let n=Te(new Date),i=await Promise.allSettled(e.map(o=>this.docClient.send(new Zt.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(o),[E.SK]:K.SESSION_SK()},UpdateExpression:`SET #${E.REVOKED_AT} = :revokedAt REMOVE #${E.ACTIVE_SESSION_PK}, #${E.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${E.REVOKED_AT}`]:E.REVOKED_AT,[`#${E.ACTIVE_SESSION_PK}`]:E.ACTIVE_SESSION_PK,[`#${E.ACTIVE_SESSION_SK}`]:E.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":n}})))),s=0;for(let o of i)o.status==="fulfilled"?s+=1:console.error(`[session-repo] ${r}: session revoke failed (may remain active):`,{name:Vf(o.reason)});return s}async revokeAllByUserId(e,r){try{let n=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.ACTIVE_SESSIONS,KeyConditionExpression:`${E.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":ze.ACTIVE_SESSION_PK(e)}}));if(!n.Items||n.Items.length===0)return w(0);let i=n.Items.map(o=>ve.sessionId(o[E.PK])).filter(o=>!r||o!==r),s=await this.revokeSessionsByIds(i,"revokeAllByUserId");return w(s)}catch{return T(N.DatabaseQueryError({query:"revoke all sessions by user"}))}}async revokeBatch(e){try{let r=await this.revokeSessionsByIds(e,"revokeBatch");return w(r)}catch{return T(N.DatabaseQueryError({query:"revoke batch sessions"}))}}async countByUserId(e){try{let r=await this.docClient.send(new Zt.QueryCommand({TableName:this.tableName,IndexName:tt.ACTIVE_SESSIONS,KeyConditionExpression:`${E.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":ze.ACTIVE_SESSION_PK(e)},Select:"COUNT"}));return w(r.Count||0)}catch{return T(N.DatabaseQueryError({query:"count active sessions by user"}))}}async isTokenActive(e,r){try{let n=await this.docClient.send(new Zt.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.SESSION_PK(r),[E.SK]:K.SESSION_SK()},ProjectionExpression:`${E.TOKEN_ID}, ${E.REVOKED_AT}, ${E.EXPIRES_AT}`}));if(!n.Item)return w(!1);let i=n.Item,s=i[E.TOKEN_ID]===e&&!i[E.REVOKED_AT]&&oe(i[E.EXPIRES_AT])>new Date;return w(s)}catch{return T(N.DatabaseQueryError({query:"check token active"}))}}marshall(e,r,n){let i={[E.PK]:K.SESSION_PK(e.id),[E.SK]:K.SESSION_SK(),[E.USER_SESSION_PK]:K.USER_PK(e.userId),[E.USER_SESSION_SK]:n,...!e.revokedAt&&{[E.ACTIVE_SESSION_PK]:ze.ACTIVE_SESSION_PK(e.userId),[E.ACTIVE_SESSION_SK]:n},[E.USER_ID]:e.userId,[E.TOKEN_ID]:e.tokenId,[E.EXPIRES_AT]:Te(e.expiresAt),[E.CREATED_AT]:Te(e.createdAt),[E.LAST_USED_AT]:Te(e.lastUsedAt),[E.TTL]:r};return e.tenantId&&(i[E.TENANT_ID]=e.tenantId),e.tenantType&&(i[E.TENANT_TYPE]=e.tenantType),e.perms!==void 0&&(i[E.PERM]=JSON.stringify(e.perms)),e.roles!==void 0&&(i[E.ROLES]=e.roles),e.deviceLabel&&(i[E.DEVICE_LABEL]=e.deviceLabel),e.country&&(i[E.COUNTRY]=e.country),e.city&&(i[E.CITY]=e.city),e.metadata&&(i[E.METADATA]=e.metadata),e.revokedAt&&(i[E.REVOKED_AT]=Te(e.revokedAt)),e.previousTokenId&&(i[E.PREVIOUS_TOKEN_ID]=e.previousTokenId),e.rotatedAt!==void 0&&(i[E.ROTATED_AT]=e.rotatedAt),i}unmarshall(e){let n={id:ve.sessionId(e[E.PK]),userId:e[E.USER_ID],tokenId:e[E.TOKEN_ID],expiresAt:oe(e[E.EXPIRES_AT]),createdAt:oe(e[E.CREATED_AT]),lastUsedAt:oe(e[E.LAST_USED_AT]),revokedAt:e[E.REVOKED_AT]?oe(e[E.REVOKED_AT]):null};return e[E.TENANT_ID]&&(n.tenantId=e[E.TENANT_ID]),e[E.TENANT_TYPE]&&(n.tenantType=e[E.TENANT_TYPE]),e[E.PERM]!==void 0&&(n.perms=JSON.parse(e[E.PERM])),e[E.ROLES]!==void 0&&(n.roles=e[E.ROLES]),e[E.DEVICE_LABEL]&&(n.deviceLabel=e[E.DEVICE_LABEL]),e[E.COUNTRY]&&(n.country=e[E.COUNTRY]),e[E.CITY]&&(n.city=e[E.CITY]),e[E.METADATA]&&(n.metadata=e[E.METADATA]),e[E.PREVIOUS_TOKEN_ID]&&(n.previousTokenId=e[E.PREVIOUS_TOKEN_ID]),e[E.ROTATED_AT]!==void 0&&(n.rotatedAt=e[E.ROTATED_AT]),n}};var p8=ge(ir(),1);var zf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={"#pk":E.INVITE_TENANT_PK},s={":pk":ze.INVITE_TENANT_PK(e)},o={TableName:this.tableName,IndexName:tt.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:i,ExpressionAttributeValues:s,ScanIndexForward:!1,Limit:n};r?.cursor&&(o.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))),r?.status&&(o.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",i["#sk"]=E.INVITE_TENANT_SK,s[":statusPrefix"]=ze.INVITE_TENANT_STATUS_PREFIX(r.status));let a=await this.docClient.send(new p8.QueryCommand(o)),c=(a.Items||[]).map(d=>this.toListItem(d)),u=!!a.LastEvaluatedKey,p=u?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return gt(c,{limit:n,hasNext:u,cursor:p,prevCursor:r?.cursor??null})}catch(n){return console.error("[DynamoDBTenantInviteQuery.listByTenant] Error:",n instanceof Error?n.message:n),T(N.DatabaseQueryError({query:"listByTenant query"}))}}toListItem(e){let r=ve.inviteId(e.PK),n={id:e.invitedById};e.invitedByInfo&&(e.invitedByInfo.name&&(n.name=e.invitedByInfo.name),e.invitedByInfo.email&&(n.email=e.invitedByInfo.email),e.invitedByInfo.jobTitle&&(n.jobTitle=e.invitedByInfo.jobTitle));let i={id:r,tenantId:e.tenantId,invitedBy:n,status:e.inviteStatus,expiresAt:oe(e.expiresAt),createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};return e.inviteeUserId&&(i.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(i.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(i.inviteePhone=e.inviteePhone),e.roles!==void 0&&(i.roles=e.roles),e.perms!==void 0&&(i.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(i.authPerm=e.authPerm),e.displayName&&(i.displayName=e.displayName),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.jobTitle&&(i.jobTitle=e.jobTitle),e.acceptedAt&&(i.acceptedAt=oe(e.acceptedAt)),e.declinedAt&&(i.declinedAt=oe(e.declinedAt)),e.revokedAt&&(i.revokedAt=oe(e.revokedAt)),i}};var Fr=ge(ir(),1);var gge=10080*60*1e3,Qf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}mapItemToEntity(e){let n={id:ve.inviteId(e.PK),tenantId:e.tenantId,invitedById:e.invitedById,tenantType:e.tenantType,status:e.inviteStatus,inviteToken:e.inviteToken,expiresAt:oe(e.expiresAt),createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};e.inviteeUserId&&(n.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(n.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(n.inviteePhone=e.inviteePhone),e.roles!==void 0&&(n.roles=e.roles);let i=e[E.PERM];return i!==void 0&&(n.perms=JSON.parse(i)),e.authPerm!==void 0&&(n.authPerm=e.authPerm),e.displayName&&(n.displayName=e.displayName),e.givenName&&(n.givenName=e.givenName),e.familyName&&(n.familyName=e.familyName),e.jobTitle&&(n.jobTitle=e.jobTitle),e.acceptedAt&&(n.acceptedAt=oe(e.acceptedAt)),e.declinedAt&&(n.declinedAt=oe(e.declinedAt)),e.revokedAt&&(n.revokedAt=oe(e.revokedAt)),n}generateInviteId(){return Lt()}async getById(e){try{let r=await this.docClient.send(new Fr.GetCommand({TableName:this.tableName,Key:{PK:K.INVITE_PK(e),SK:K.INVITE_SK()}}));return r.Item?w(this.mapItemToEntity(r.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"getById invite"}))}}async getByToken(e){try{let n=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITE_TOKEN,KeyConditionExpression:"#inviteTokenGsi = :token",ExpressionAttributeNames:{"#inviteTokenGsi":E.INVITE_TOKEN_GSI},ExpressionAttributeValues:{":token":e},Limit:1}))).Items;if(!n||n.length===0)return w(null);let i=n[0],s=await this.docClient.send(new Fr.GetCommand({TableName:this.tableName,Key:{PK:i.PK,SK:i.SK}}));return s.Item?w(this.mapItemToEntity(s.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"getByToken invite"}))}}async create(e){try{let r=Ne(),n=Te(e.expiresAt),i=Math.floor((n+gge)/1e3),s={PK:K.INVITE_PK(e.id),SK:K.INVITE_SK(),[E.TENANT_ID]:e.tenantId,tenantType:e.tenantType,[E.INVITED_BY_ID]:e.invitedById,[E.INVITE_STATUS]:e.status,[E.INVITE_TOKEN]:e.inviteToken,[E.EXPIRES_AT]:n,[E.CREATED_AT]:r,[E.UPDATED_AT]:r,[E.TTL]:i,[E.INVITE_TENANT_PK]:ze.INVITE_TENANT_PK(e.tenantId),[E.INVITE_TENANT_SK]:ze.INVITE_TENANT_SK(e.status,r,e.id),[E.INVITE_TOKEN_GSI]:e.inviteToken},o={};e.invitedByName&&(o.name=e.invitedByName),e.invitedByEmail&&(o.email=e.invitedByEmail),e.invitedByJobTitle&&(o.jobTitle=e.invitedByJobTitle),Object.keys(o).length>0&&(s[E.INVITED_BY_INFO]=o),e.inviteeUserId&&(s[E.INVITEE_USER_ID]=e.inviteeUserId),e.inviteeEmail&&(s[E.INVITEE_EMAIL]=e.inviteeEmail,s[E.INVITEE_EMAIL_GSI]=e.inviteeEmail,s[E.INVITEE_EMAIL_TENANT_SK]=`${De.TENANT}${e.tenantId}`),e.inviteePhone&&(s[E.INVITEE_PHONE]=e.inviteePhone,s[E.INVITEE_PHONE_GSI]=e.inviteePhone,s[E.INVITEE_PHONE_TENANT_SK]=`${De.TENANT}${e.tenantId}`),e.roles!==void 0&&(s[E.ROLES]=e.roles),e.perms!==void 0&&(s[E.PERM]=JSON.stringify(e.perms)),e.authPerm!==void 0&&(s[E.AUTH_PERM]=e.authPerm),e.displayName&&(s[E.DISPLAY_NAME]=e.displayName),e.givenName&&(s.givenName=e.givenName),e.familyName&&(s.familyName=e.familyName),e.jobTitle&&(s.jobTitle=e.jobTitle),await this.docClient.send(new Fr.PutCommand({TableName:this.tableName,Item:s,ConditionExpression:"attribute_not_exists(PK)"}));let a={id:e.id,tenantId:e.tenantId,invitedById:e.invitedById,tenantType:e.tenantType,status:e.status,inviteToken:e.inviteToken,expiresAt:e.expiresAt,createdAt:oe(r),updatedAt:oe(r)};return e.inviteeUserId&&(a.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(a.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(a.inviteePhone=e.inviteePhone),e.roles!==void 0&&(a.roles=e.roles),e.perms!==void 0&&(a.perms=e.perms),e.authPerm!==void 0&&(a.authPerm=e.authPerm),e.displayName&&(a.displayName=e.displayName),e.givenName&&(a.givenName=e.givenName),e.familyName&&(a.familyName=e.familyName),e.jobTitle&&(a.jobTitle=e.jobTitle),w(a)}catch(r){return r.name==="ConditionalCheckFailedException"?T(N.UniqueConstraintViolation({field:"invite id"})):T(N.UnknownError({message:r.message}))}}async updateStatus(e,r){try{let n=Ne(),i=["#inviteStatus = :inviteStatus","#inviteTenantSk = :inviteTenantSk","#updatedAt = :updatedAt"],s={"#inviteStatus":E.INVITE_STATUS,"#inviteTenantSk":E.INVITE_TENANT_SK,"#updatedAt":E.UPDATED_AT},o={":inviteStatus":r.status,":inviteTenantSk":ze.INVITE_TENANT_SK(r.status,n,e),":updatedAt":n};r.acceptedAt&&(i.push("#acceptedAt = :acceptedAt"),s["#acceptedAt"]=E.ACCEPTED_AT,o[":acceptedAt"]=Te(r.acceptedAt)),r.declinedAt&&(i.push("#declinedAt = :declinedAt"),s["#declinedAt"]=E.DECLINED_AT,o[":declinedAt"]=Te(r.declinedAt)),r.revokedAt&&(i.push("#revokedAt = :revokedAt"),s["#revokedAt"]=E.REVOKED_AT,o[":revokedAt"]=Te(r.revokedAt));let a=[];r.status!=="pending"&&(a.push("#inviteTokenGsi","#inviteeEmailGsi","#inviteeEmailTenantSk","#inviteePhoneGsi","#inviteePhoneTenantSk"),s["#inviteTokenGsi"]=E.INVITE_TOKEN_GSI,s["#inviteeEmailGsi"]=E.INVITEE_EMAIL_GSI,s["#inviteeEmailTenantSk"]=E.INVITEE_EMAIL_TENANT_SK,s["#inviteePhoneGsi"]=E.INVITEE_PHONE_GSI,s["#inviteePhoneTenantSk"]=E.INVITEE_PHONE_TENANT_SK);let c=`SET ${i.join(", ")}`;return a.length>0&&(c+=` REMOVE ${a.join(", ")}`),await this.docClient.send(new Fr.UpdateCommand({TableName:this.tableName,Key:{PK:K.INVITE_PK(e),SK:K.INVITE_SK()},UpdateExpression:c,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:"attribute_exists(PK)"})),w(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"TenantInvite",id:e})):T(N.UnknownError({message:n.message}))}}async findByTenantAndEmail(e,r){try{let i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email AND #inviteeEmailTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteeEmailGsi":E.INVITEE_EMAIL_GSI,"#inviteeEmailTenantSk":E.INVITEE_EMAIL_TENANT_SK},ExpressionAttributeValues:{":email":r,":tenantSk":`${De.TENANT}${e}`},Limit:1}))).Items;return!i||i.length===0?w(null):w(this.mapItemToEntity(i[0]))}catch{return T(N.DatabaseQueryError({query:"findByTenantAndEmail"}))}}async findByTenantAndPhone(e,r){try{let i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone AND #inviteePhoneTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteePhoneGsi":E.INVITEE_PHONE_GSI,"#inviteePhoneTenantSk":E.INVITEE_PHONE_TENANT_SK},ExpressionAttributeValues:{":phone":r,":tenantSk":`${De.TENANT}${e}`},Limit:1}))).Items;return!i||i.length===0?w(null):w(this.mapItemToEntity(i[0]))}catch{return T(N.DatabaseQueryError({query:"findByTenantAndPhone"}))}}async findByTenantAndUserId(e,r){try{let i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",FilterExpression:"#inviteeUserId = :userId",ExpressionAttributeNames:{"#pk":E.INVITE_TENANT_PK,"#sk":E.INVITE_TENANT_SK,"#inviteeUserId":E.INVITEE_USER_ID},ExpressionAttributeValues:{":pk":ze.INVITE_TENANT_PK(e),":pendingPrefix":ze.INVITE_TENANT_STATUS_PREFIX("pending"),":userId":r},Limit:1}))).Items;return!i||i.length===0?w(null):w(this.mapItemToEntity(i[0]))}catch{return T(N.DatabaseQueryError({query:"findByTenantAndUserId"}))}}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={"#pk":E.INVITE_TENANT_PK},s={":pk":ze.INVITE_TENANT_PK(e)},o={TableName:this.tableName,IndexName:tt.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:i,ExpressionAttributeValues:s,ScanIndexForward:!1,Limit:n};r?.cursor&&(o.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))),r?.status&&(o.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",i["#sk"]=E.INVITE_TENANT_SK,s[":statusPrefix"]=ze.INVITE_TENANT_STATUS_PREFIX(r.status));let a=await this.docClient.send(new Fr.QueryCommand(o)),c=(a.Items||[]).map(d=>this.mapItemToEntity(d)),u=!!a.LastEvaluatedKey,p=u?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return gt(c,{limit:n,hasNext:u,cursor:p,prevCursor:r?.cursor??null})}catch{return T(N.DatabaseQueryError({query:"listByTenant"}))}}async findPendingByEmail(e){try{let r=Ne(),i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteeEmailGsi":E.INVITEE_EMAIL_GSI,"#expiresAt":E.EXPIRES_AT},ExpressionAttributeValues:{":email":e,":now":r}}))).Items||[];if(i.length===0)return w([]);let s=i.map(c=>({PK:c.PK,SK:c.SK})),a=(await Sl(this.docClient,this.tableName,s)).map(c=>this.mapItemToEntity(c));return w(a)}catch{return T(N.DatabaseQueryError({query:"findPendingByEmail"}))}}async findPendingByPhone(e){try{let r=Ne(),i=(await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteePhoneGsi":E.INVITEE_PHONE_GSI,"#expiresAt":E.EXPIRES_AT},ExpressionAttributeValues:{":phone":e,":now":r}}))).Items||[];if(i.length===0)return w([]);let s=i.map(c=>({PK:c.PK,SK:c.SK})),a=(await Sl(this.docClient,this.tableName,s)).map(c=>this.mapItemToEntity(c));return w(a)}catch{return T(N.DatabaseQueryError({query:"findPendingByPhone"}))}}async countPendingByTenant(e){try{let r=await this.docClient.send(new Fr.QueryCommand({TableName:this.tableName,IndexName:tt.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",ExpressionAttributeNames:{"#pk":E.INVITE_TENANT_PK,"#sk":E.INVITE_TENANT_SK},ExpressionAttributeValues:{":pk":ze.INVITE_TENANT_PK(e),":pendingPrefix":ze.INVITE_TENANT_STATUS_PREFIX("pending")},Select:"COUNT"}));return w(r.Count??0)}catch{return T(N.DatabaseQueryError({query:"countPendingByTenant"}))}}async expireOld(e){return w(0)}};var f8=ge(ir(),1);var Jf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={TableName:this.tableName,KeyConditionExpression:"PK = :pk",ExpressionAttributeValues:{":pk":K.TENANT_MEMBER_PK(e)}};r?.cursor&&(i.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let o=(await this.docClient.send(new f8.QueryCommand(i))).Items||[],a=[],c=new Map;for(let y of o){let _=y.SK;if(_.startsWith(_t.TENANT_PROFILE)){let C=ve.tenantProfileUserId(_);c.set(C,y)}else _.startsWith(De.USER)&&a.push(y)}a.sort((y,_)=>_.createdAt-y.createdAt);let u=a.slice(0,n),p=a.length>n,d=u.map(y=>{let _=ve.tenantMemberUserId(y.SK),C=c.get(_);return this.toListItem(y,e,_,C)}),h=p&&u.length>0?Buffer.from(JSON.stringify({PK:u[u.length-1].PK,SK:u[u.length-1].SK})).toString("base64url"):null;return gt(d,{limit:n,hasNext:p,cursor:h,prevCursor:r?.cursor??null})}catch{return T(N.DatabaseQueryError({query:"listByTenant query"}))}}toListItem(e,r,n,i){let s={tenantId:r,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};if(e.roles!==void 0&&(s.roles=e.roles),e.perms!==void 0&&(s.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(s.authPerm=e.authPerm),i){let o={tenantId:r,userId:n,createdAt:oe(i.createdAt),updatedAt:oe(i.updatedAt)};i.contactEmail&&(o.contactEmail=i.contactEmail),i.contactPhone&&(o.contactPhone=i.contactPhone),i.displayName&&(o.displayName=i.displayName),i.displayNameSource&&(o.displayNameSource=i.displayNameSource),i.givenName&&(o.givenName=i.givenName),i.familyName&&(o.familyName=i.familyName),i.avatarUrl&&(o.avatarUrl=i.avatarUrl),i.locale&&(o.locale=i.locale),i.jobTitle&&(o.jobTitle=i.jobTitle),i.bio&&(o.bio=i.bio),i.metadata&&(o.metadata=JSON.parse(i.metadata)),s.tenantProfile=o}return s}};var Kr=ge(ir(),1);var Yf=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=Kr.DynamoDBDocumentClient.from(e)}mapItemToEntity(e){let r=ve.tenantId(e.PK),n=ve.tenantMemberUserId(e.SK),i={tenantId:r,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};return e.roles!==void 0&&(i.roles=e.roles),e.perms!==void 0&&(i.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(i.authPerm=e.authPerm),i}async get(e,r){try{let n=await this.docClient.send(new Kr.GetCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_MEMBER_SK(r)}}));if(!n.Item)return w(null);let i=this.mapItemToEntity(n.Item);return w(i)}catch{return T(N.DatabaseQueryError({query:"get"}))}}async create(e){try{let r=Ne(),n=e.isOwner?void 0:e.authPerm,i=Zr({PK:K.TENANT_MEMBER_PK(e.tenantId),SK:K.TENANT_MEMBER_SK(e.userId),userStatus:e.status,roles:e.roles,perms:e.perms!==void 0?JSON.stringify(e.perms):void 0,authPerm:n,isOwner:e.isOwner,createdAt:r,updatedAt:r,userTenantPk:ze.USER_TENANT_PK(e.userId),userTenantSk:ze.USER_TENANT_SK(e.tenantType??"org",e.parentTenantId,r,e.tenantId),parentTenantId:e.parentTenantId});return e.isOwner?await this.docClient.send(new Kr.TransactWriteCommand({TransactItems:[{Put:{TableName:this.tableName,Item:{PK:K.TENANT_MEMBER_PK(e.tenantId),SK:K.TENANT_OWNER_MARKER_SK(),createdAt:r},ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}},{Put:{TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}}]})):await this.docClient.send(new Kr.PutCommand({TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),w(void 0)}catch(r){return r.name==="TransactionCanceledException"?r.CancellationReasons?.[0]?.Code==="ConditionalCheckFailed"?T(N.UniqueConstraintViolation({field:"tenant owner"})):T(N.UniqueConstraintViolation({field:"tenant member"})):r.name==="ConditionalCheckFailedException"?T(N.UniqueConstraintViolation({field:"tenant member"})):T(N.UnknownError({message:r.message}))}}async updatePermissions(e,r,n){try{let i={...n,updatedAt:Ne()},{UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=$i(i);return await this.docClient.send(new Kr.UpdateCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_MEMBER_SK(r)},UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"TenantMember",id:`${e}:${r}`})):T(N.UnknownError({message:i.message}))}}async updateStatus(e,r,n){try{return await this.docClient.send(new Kr.UpdateCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_MEMBER_SK(r)},UpdateExpression:"SET #userStatus = :userStatus, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#userStatus":"userStatus","#updatedAt":"updatedAt"},ExpressionAttributeValues:{":userStatus":n,":updatedAt":Ne()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"TenantMember",id:`${e}:${r}`})):T(N.UnknownError({message:i.message}))}}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":K.TENANT_MEMBER_PK(e),":skPrefix":De.USER},Limit:n};r?.cursor&&(i.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let s=await this.docClient.send(new Kr.QueryCommand(i)),o=(s.Items||[]).map(u=>this.mapItemToEntity(u)),a=!!s.LastEvaluatedKey,c=a?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null;return gt(o,{limit:n,hasNext:a,cursor:c,prevCursor:r?.cursor??null})}catch(n){let i=n instanceof Error?`${n.name}: ${n.message}`:String(n);return console.error("[DynamoDBTenantMemberRepository.listByTenant] Error:",i),T(N.DatabaseQueryError({query:`listByTenant \u2014 ${i}`}))}}async hasOwner(e){try{let r=await this.docClient.send(new Kr.GetCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_OWNER_MARKER_SK()}}));return w(!!r.Item)}catch{return T(N.DatabaseQueryError({query:"hasOwner"}))}}async remove(e,r){try{return await this.docClient.send(new Kr.DeleteCommand({TableName:this.tableName,Key:{PK:K.TENANT_MEMBER_PK(e),SK:K.TENANT_MEMBER_SK(r)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"TenantMember",id:`${e}:${r}`})):T(N.UnknownError({message:n.message}))}}};var W_=ge(ir(),1);var Xf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByUser(e,r){try{let n=Math.min(r?.limit??50,100),i=r?.tenantType??nv.DEFAULT,s=r?.parentTenantId,o=s?`${i}#${s}#`:`${i}#`,a={TableName:this.tableName,IndexName:tt.USER_TENANTS,KeyConditionExpression:"userTenantPk = :pk AND begins_with(userTenantSk, :skPrefix)",ExpressionAttributeValues:{":pk":ze.USER_TENANT_PK(e),":skPrefix":o},ScanIndexForward:!1,Limit:n};r?.cursor&&(a.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let c=await this.docClient.send(new W_.QueryCommand(a)),u=c.Items??[],p=await this.fetchProfileMap(e,u),d=u.map(_=>this.toListItem(_,e,p)),h=!!c.LastEvaluatedKey,y=h?Buffer.from(JSON.stringify(c.LastEvaluatedKey)).toString("base64url"):null;return gt(d,{limit:n,hasNext:h,cursor:y,prevCursor:r?.cursor??null})}catch{return T(N.DatabaseQueryError({query:"listByUser query"}))}}async fetchProfileMap(e,r){let n=new Map;if(r.length===0)return n;let i=r.map(o=>({PK:K.TENANT_PROFILE_PK(ve.tenantId(o.PK)),SK:K.TENANT_PROFILE_SK(e)})),s=await this.docClient.send(new W_.BatchGetCommand({RequestItems:{[this.tableName]:{Keys:i}}}));for(let o of s.Responses?.[this.tableName]??[]){let a=o,c=ve.tenantId(a.PK);n.set(c,a)}return n}toListItem(e,r,n){let i=ve.tenantId(e.PK),s={tenantId:i,userId:r,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};e.roles!==void 0&&(s.roles=e.roles),e.perms!==void 0&&(s.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(s.authPerm=e.authPerm);let o=n.get(i);return o&&(o.contactEmail&&(s.contactEmail=o.contactEmail),o.contactPhone&&(s.contactPhone=o.contactPhone),o.displayName&&(s.displayName=o.displayName),o.displayNameSource&&(s.displayNameSource=o.displayNameSource),o.givenName&&(s.givenName=o.givenName),o.familyName&&(s.familyName=o.familyName),o.avatarUrl&&(s.avatarUrl=o.avatarUrl),o.locale&&(s.locale=o.locale),o.jobTitle&&(s.jobTitle=o.jobTitle),o.bio&&(s.bio=o.bio),o.metadata&&(s.metadata=JSON.parse(o.metadata))),s}};var xa=ge(ir(),1);var Zf=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateTenantId(){return Lt()}toEntity(e){let n={id:ve.tenantId(e.PK),type:e.tenantType,ownerId:e.ownerId,createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};return e.parentTenantId&&(n.parentTenantId=e.parentTenantId),n}async get(e){try{let r=await this.docClient.send(new xa.GetCommand({TableName:this.tableName,Key:{PK:K.TENANT_PK(e),SK:K.TENANT_SK()}}));return r.Item?w(this.toEntity(r.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"get tenant"}))}}async create(e){try{let r=e.id??this.generateTenantId(),n=Ne(),i=Zr({PK:K.TENANT_PK(r),SK:K.TENANT_SK(),tenantType:e.type,parentTenantId:e.parentTenantId,ownerId:e.ownerId,createdAt:n,updatedAt:n});return await this.docClient.send(new xa.PutCommand({TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),w(void 0)}catch(r){return r.name==="ConditionalCheckFailedException"?T(N.UniqueConstraintViolation({field:"tenant"})):T(N.UnknownError({message:r.message}))}}async update(e,r){try{let n={updatedAt:Ne()};r.type!==void 0&&(n.tenantType=r.type),r.ownerId!==void 0&&(n.ownerId=r.ownerId),r.parentTenantId!==void 0&&(n.parentTenantId=r.parentTenantId===null?void 0:r.parentTenantId);let{UpdateExpression:i,ExpressionAttributeNames:s,ExpressionAttributeValues:o}=$i(n);return await this.docClient.send(new xa.UpdateCommand({TableName:this.tableName,Key:{PK:K.TENANT_PK(e),SK:K.TENANT_SK()},UpdateExpression:i,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"Tenant",id:e})):T(N.UnknownError({message:n.message}))}}async delete(e){try{return await this.docClient.send(new xa.DeleteCommand({TableName:this.tableName,Key:{PK:K.TENANT_PK(e),SK:K.TENANT_SK()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(r){return r.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"Tenant",id:e})):T(N.UnknownError({message:r.message}))}}async list(){return T(N.InvalidData({reason:"DynamoDB tenant list requires a dedicated GSI; scan is disabled"}))}async listByParent(e){return T(N.InvalidData({reason:`DynamoDB tenant listByParent(${e}) requires a dedicated GSI; scan is disabled`}))}async listRoots(){return T(N.InvalidData({reason:"DynamoDB tenant listRoots requires a dedicated GSI; scan is disabled"}))}};var Bi=ge(ir(),1);var em=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async get(e){try{let r=await this.docClient.send(new Bi.GetCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()}}));return r.Item?w(this.unmarshall(r.Item,e)):w(null)}catch{return T(N.DatabaseQueryError({query:"get user auth"}))}}async create(e){try{let r=Ne(),n={...e,createdAt:new Date(r),updatedAt:new Date(r)};return await this.docClient.send(new Bi.PutCommand({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:`attribute_not_exists(${E.PK})`})),w(n)}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"userAuth"})):T(N.DatabaseQueryError({query:"create user auth"}))}}async updateStatus(e,r){try{let n=Ne();return await this.docClient.send(new Bi.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()},UpdateExpression:`SET #userStatus = :userStatus, #${E.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#userStatus":"userStatus",[`#${E.UPDATED_AT}`]:E.UPDATED_AT},ExpressionAttributeValues:{":userStatus":r,":updatedAt":n},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userAuth",id:e})):T(N.DatabaseQueryError({query:"update user auth status"}))}}async updateMfaRequired(e,r){try{let n=Ne();return await this.docClient.send(new Bi.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #${E.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired",[`#${E.UPDATED_AT}`]:E.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":r,":updatedAt":n},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userAuth",id:e})):T(N.DatabaseQueryError({query:"update mfa required"}))}}async updateMfaMethods(e,r){try{let n=Ne();return await this.docClient.send(new Bi.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()},UpdateExpression:`SET #mfaMethods = :mfaMethods, #${E.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaMethods":"mfaMethods",[`#${E.UPDATED_AT}`]:E.UPDATED_AT},ExpressionAttributeValues:{":mfaMethods":r,":updatedAt":n},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userAuth",id:e})):T(N.DatabaseQueryError({query:"update mfa methods"}))}}async updateMfaSettings(e,r){try{let n=Ne();return await this.docClient.send(new Bi.UpdateCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #mfaMethods = :mfaMethods, #${E.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired","#mfaMethods":"mfaMethods",[`#${E.UPDATED_AT}`]:E.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":r.mfaRequired,":mfaMethods":r.mfaMethods,":updatedAt":n},ConditionExpression:`attribute_exists(${E.PK})`})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userAuth",id:e})):T(N.DatabaseQueryError({query:"update mfa settings"}))}}async remove(e){try{return await this.docClient.send(new Bi.DeleteCommand({TableName:this.tableName,Key:{[E.PK]:K.USER_PK(e),[E.SK]:K.USER_AUTH_SK()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"remove user auth"}))}}marshall(e){return{[E.PK]:K.USER_PK(e.userId),[E.SK]:K.USER_AUTH_SK(),userStatus:e.userStatus,mfaRequired:e.mfaRequired,mfaMethods:e.mfaMethods,[E.CREATED_AT]:Te(e.createdAt),[E.UPDATED_AT]:Te(e.updatedAt)}}unmarshall(e,r){return{userId:r,userStatus:e.userStatus,mfaRequired:e.mfaRequired||!1,mfaMethods:e.mfaMethods||null,createdAt:oe(e[E.CREATED_AT]),updatedAt:oe(e[E.UPDATED_AT])}}};var tn=ge(ir(),1);function _l(t,e){return e?K.USER_MFA_WITH_ID_SK(t,e):K.USER_MFA_SK(t)}var tm=class{client;tableName;docClient;constructor(e,r){this.client=e,this.tableName=r,this.docClient=tn.DynamoDBDocumentClient.from(e)}toDynamoDBItem(e){let r={PK:K.USER_PK(e.userId),SK:_l(e.method,e.id),method:e.method,data:JSON.stringify(e.data),createdAt:Date.now(),failedAttempts:0};return e.label&&(r.label=e.label),e.verifiedAt&&(r.verifiedAt=e.verifiedAt.getTime()),e.metadata&&(r.metadata=JSON.stringify(e.metadata)),r}fromDynamoDBItem(e,r){let n=ve.mfaSKInfo(e.SK),i={userId:r,method:e.method,data:JSON.parse(e.data),createdAt:oe(e.createdAt),verifiedAt:Xr(e.verifiedAt)??null};return n?.id&&(i.id=n.id),e.label&&(i.label=e.label),e.failedAttempts!==void 0&&(i.failedAttempts=e.failedAttempts),e.lastFailedAt!==void 0&&(i.lastFailedAt=Xr(e.lastFailedAt)),e.lockedUntil!==void 0&&(i.lockedUntil=Xr(e.lockedUntil)),e.lastUsedAt!==void 0&&(i.lastUsedAt=Xr(e.lastUsedAt)),e.metadata&&(i.metadata=JSON.parse(e.metadata)),i}async get(e,r,n){try{let i=_l(r,n),s=await this.docClient.send(new tn.GetCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:i}}));return s.Item?w(this.fromDynamoDBItem(s.Item,e)):w(null)}catch(i){return console.error("DynamoDBUserMFAAuthenticatorRepository.get error:",i),T(N.DatabaseQueryError({query:"get MFA authenticator"}))}}async findByUserId(e){try{let r={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":K.USER_PK(e),":skPrefix":_t.MFA}},s=((await this.docClient.send(new tn.QueryCommand(r))).Items??[]).map(o=>this.fromDynamoDBItem(o,e));return w(s)}catch(r){return console.error("DynamoDBUserMFAAuthenticatorRepository.findByUserId error:",r),T(N.DatabaseQueryError({query:"find MFA authenticators by user"}))}}async findByUserIdAndMethod(e,r){try{let n={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":K.USER_PK(e),":skPrefix":`${_t.MFA}${r}`}},o=((await this.docClient.send(new tn.QueryCommand(n))).Items??[]).filter(a=>a.method===r).map(a=>this.fromDynamoDBItem(a,e));return w(o)}catch(n){return console.error("DynamoDBUserMFAAuthenticatorRepository.findByUserIdAndMethod error:",n),T(N.DatabaseQueryError({query:"find MFA authenticators by method"}))}}async create(e){try{let r={...e};e.id===void 0&&this.isMultiInstanceMethod(e.method)&&(r.id=Lt());let n=this.toDynamoDBItem(r);return await this.docClient.send(new tn.PutCommand({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),w(this.fromDynamoDBItem(n,e.userId))}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"MFA authenticator"})):(console.error("DynamoDBUserMFAAuthenticatorRepository.create error:",r),T(N.DatabaseQueryError({query:"create MFA authenticator"})))}}async update(e,r,n,i){try{let s=_l(r,n),o=[],a={},c={};if(i.label!==void 0&&(o.push("#label = :label"),a["#label"]="label",c[":label"]=i.label),i.data!==void 0&&(o.push("#data = :data"),a["#data"]="data",c[":data"]=JSON.stringify(i.data)),i.verifiedAt!==void 0&&(o.push("#verifiedAt = :verifiedAt"),a["#verifiedAt"]="verifiedAt",c[":verifiedAt"]=i.verifiedAt instanceof Date?i.verifiedAt.getTime():i.verifiedAt===null?void 0:i.verifiedAt),i.lastUsedAt!==void 0&&(o.push("#lastUsedAt = :lastUsedAt"),a["#lastUsedAt"]="lastUsedAt",c[":lastUsedAt"]=i.lastUsedAt instanceof Date?i.lastUsedAt.getTime():i.lastUsedAt===null?void 0:i.lastUsedAt),i.failedAttempts!==void 0&&(o.push("#failedAttempts = :failedAttempts"),a["#failedAttempts"]="failedAttempts",c[":failedAttempts"]=i.failedAttempts),i.lastFailedAt!==void 0&&(o.push("#lastFailedAt = :lastFailedAt"),a["#lastFailedAt"]="lastFailedAt",c[":lastFailedAt"]=i.lastFailedAt instanceof Date?i.lastFailedAt.getTime():i.lastFailedAt===null?void 0:i.lastFailedAt),i.lockedUntil!==void 0&&(o.push("#lockedUntil = :lockedUntil"),a["#lockedUntil"]="lockedUntil",c[":lockedUntil"]=i.lockedUntil instanceof Date?i.lockedUntil.getTime():i.lockedUntil===null?void 0:i.lockedUntil),i.metadata!==void 0&&(o.push("#metadata = :metadata"),a["#metadata"]="metadata",c[":metadata"]=JSON.stringify(i.metadata)),o.length===0)return w(void 0);let u={TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:s},UpdateExpression:`SET ${o.join(", ")}`,ExpressionAttributeNames:a,ExpressionAttributeValues:c};return await this.docClient.send(new tn.UpdateCommand(u)),w(void 0)}catch(s){return console.error("DynamoDBUserMFAAuthenticatorRepository.update error:",s),T(N.DatabaseQueryError({query:"update MFA authenticator"}))}}async remove(e,r,n){try{let i=_l(r,n);return await this.docClient.send(new tn.DeleteCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:i}})),w(void 0)}catch(i){return console.error("DynamoDBUserMFAAuthenticatorRepository.remove error:",i),T(N.DatabaseQueryError({query:"remove MFA authenticator"}))}}async incrementFailedAttempts(e,r,n,i,s){try{let o=_l(r,n),a=Date.now(),c=["#failedAttempts = if_not_exists(#failedAttempts, :zero) + :inc","#lastFailedAt = :lastFailedAt"],u={"#failedAttempts":"failedAttempts","#lastFailedAt":"lastFailedAt"},p={":zero":0,":inc":1,":lastFailedAt":a};s!==null&&(c.push("#lockedUntil = if_not_exists(#lockedUntil, :lockedUntil)"),u["#lockedUntil"]="lockedUntil",p[":lockedUntil"]=a+s*60*1e3,p[":maxAttempts"]=i);let d={TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:o},UpdateExpression:`SET ${c.join(", ")}`,ExpressionAttributeNames:u,ExpressionAttributeValues:p};return await this.docClient.send(new tn.UpdateCommand(d)),w(void 0)}catch(o){return console.error("DynamoDBUserMFAAuthenticatorRepository.incrementFailedAttempts error:",o),T(N.DatabaseQueryError({query:"increment failed attempts"}))}}async resetFailedAttempts(e,r,n){try{let i=_l(r,n),s={TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:i},UpdateExpression:"SET #failedAttempts = :zero REMOVE #lastFailedAt, #lockedUntil",ExpressionAttributeNames:{"#failedAttempts":"failedAttempts","#lastFailedAt":"lastFailedAt","#lockedUntil":"lockedUntil"},ExpressionAttributeValues:{":zero":0}};return await this.docClient.send(new tn.UpdateCommand(s)),w(void 0)}catch(i){return console.error("DynamoDBUserMFAAuthenticatorRepository.resetFailedAttempts error:",i),T(N.DatabaseQueryError({query:"reset failed attempts"}))}}async unlock(e,r,n){return this.resetFailedAttempts(e,r,n)}isMultiInstanceMethod(e){return["webauthn","passkey","hardware","backup"].includes(e)}};var bn=ge(ir(),1);var rm=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=bn.DynamoDBDocumentClient.from(e)}generateUserId(){return Lt()}async getById(e){try{let r=await this.docClient.send(new bn.GetCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:K.USER_PROFILE_SK()}}));if(!r.Item)return w(null);let n=r.Item;if(n.deletedAt)return w(null);let s={id:ve.userId(n.PK),status:n.userStatus,createdAt:oe(n.createdAt),updatedAt:oe(n.updatedAt),...n.deletedAt!==void 0&&{deletedAt:oe(n.deletedAt)},...n.contactEmail!==void 0&&{contactEmail:n.contactEmail},...n.contactPhone!==void 0&&{contactPhone:n.contactPhone},...n.username!==void 0&&{username:n.username},...n.displayName!==void 0&&{displayName:n.displayName},...n.givenName!==void 0&&{givenName:n.givenName},...n.familyName!==void 0&&{familyName:n.familyName},...n.avatarUrl!==void 0&&{avatarUrl:n.avatarUrl},...n.locale!==void 0&&{locale:n.locale},...n.metadata!==void 0&&{metadata:JSON.parse(n.metadata)}};return w(s)}catch{return T(N.DatabaseQueryError({query:"getById user"}))}}async create(e){try{let r=Ne(),n=e.id||this.generateUserId(),i=e.status||"pending",s={PK:K.USER_PK(n),SK:K.USER_PROFILE_SK(),userStatus:i,createdAt:r,updatedAt:r};e.contactEmail&&(s.contactEmail=e.contactEmail),e.contactPhone&&(s.contactPhone=e.contactPhone),e.username&&(s.username=e.username),e.displayName&&(s.displayName=e.displayName),e.givenName&&(s.givenName=e.givenName),e.familyName&&(s.familyName=e.familyName),e.avatarUrl&&(s.avatarUrl=e.avatarUrl),e.locale&&(s.locale=e.locale),e.metadata&&(s.metadata=JSON.stringify(e.metadata)),s[E.USER_STATUS_PK]=ze.USER_STATUS_PK(i),s[E.USER_STATUS_SK]=ze.USER_STATUS_SK(n),await this.docClient.send(new bn.PutCommand({TableName:this.tableName,Item:Zr(s),ConditionExpression:rv("PK")}));let o={id:n,status:i,createdAt:oe(r),updatedAt:oe(r),...e.contactEmail&&{contactEmail:e.contactEmail},...e.contactPhone&&{contactPhone:e.contactPhone},...e.username&&{username:e.username},...e.displayName&&{displayName:e.displayName},...e.givenName&&{givenName:e.givenName},...e.familyName&&{familyName:e.familyName},...e.avatarUrl&&{avatarUrl:e.avatarUrl},...e.locale&&{locale:e.locale},...e.metadata&&{metadata:e.metadata}};return w(o)}catch{return T(N.DatabaseQueryError({query:"create user"}))}}async updateProfile(e,r){try{let n=Ne(),i={};if(r.contactEmail!==void 0&&(i.contactEmail=r.contactEmail),r.contactPhone!==void 0&&(i.contactPhone=r.contactPhone),r.displayName!==void 0&&(i.displayName=r.displayName),r.givenName!==void 0&&(i.givenName=r.givenName),r.familyName!==void 0&&(i.familyName=r.familyName),r.avatarUrl!==void 0&&(i.avatarUrl=r.avatarUrl),r.locale!==void 0&&(i.locale=r.locale),r.metadata!==void 0&&(i.metadata=JSON.stringify(r.metadata)),Object.keys(i).length===0)return w(void 0);i.updatedAt=n;let s=$i(i);return await this.docClient.send(new bn.UpdateCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:K.USER_PROFILE_SK()},UpdateExpression:s.UpdateExpression,ExpressionAttributeNames:s.ExpressionAttributeNames,ExpressionAttributeValues:s.ExpressionAttributeValues})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"updateProfile"}))}}async getByStatus(e,r){try{let n=Math.min(r?.limit||50,100),i;if(r?.cursor)try{i=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))}catch{return T(N.DatabaseQueryError({query:"invalid pagination cursor"}))}let s=ze.USER_STATUS_PK(e),o=await this.docClient.send(new bn.QueryCommand({TableName:this.tableName,IndexName:tt.USERS_BY_STATUS,KeyConditionExpression:`${E.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":s},Limit:n,ExclusiveStartKey:i})),a=[];if(o.Items&&o.Items.length>0)for(let p of o.Items){let d=ve.userId(p.PK);a.push(d)}let c=!!o.LastEvaluatedKey,u=c?Buffer.from(JSON.stringify(o.LastEvaluatedKey)).toString("base64url"):null;return w(a,{pagination:{type:"cursor",limit:n,count:a.length,hasNext:c,hasPrev:!!r?.cursor,cursor:u}})}catch{return T(N.DatabaseQueryError({query:"get users by status"}))}}async countByStatus(e){try{let r=ze.USER_STATUS_PK(e),n=await this.docClient.send(new bn.QueryCommand({TableName:this.tableName,IndexName:tt.USERS_BY_STATUS,KeyConditionExpression:`${E.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":r},Select:"COUNT"}));return w(n.Count||0)}catch{return T(N.DatabaseQueryError({query:"count users by status"}))}}async syncAuthStatus(e,r){try{let n=Ne(),i=`SET userStatus = :userStatus, #${E.UPDATED_AT} = :updatedAt, #${E.USER_STATUS_PK} = :statusPk, #${E.USER_STATUS_SK} = :statusSk`,s={":userStatus":r,":updatedAt":n,":statusPk":ze.USER_STATUS_PK(r),":statusSk":ze.USER_STATUS_SK(e)};return r===Hi.DELETED?(i+=", deletedAt = :deletedAt",s[":deletedAt"]=n):i+=" REMOVE deletedAt",await this.docClient.send(new bn.UpdateCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:K.USER_PROFILE_SK()},UpdateExpression:i,ExpressionAttributeNames:{[`#${E.UPDATED_AT}`]:E.UPDATED_AT,[`#${E.USER_STATUS_PK}`]:E.USER_STATUS_PK,[`#${E.USER_STATUS_SK}`]:E.USER_STATUS_SK},ExpressionAttributeValues:s,ConditionExpression:"attribute_exists(PK)"})),w(void 0)}catch(n){return lt(n)?T(N.NotFound({entity:"userProfile",id:e})):T(N.DatabaseQueryError({query:"sync auth status"}))}}async remove(e){try{return await this.docClient.send(new bn.DeleteCommand({TableName:this.tableName,Key:{PK:K.USER_PK(e),SK:K.USER_PROFILE_SK()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"remove user profile"}))}}};var li=ge(ir(),1);var nm=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=li.DynamoDBDocumentClient.from(e)}mapItemToUserProviderLink(e){let r=ve.providerPKInfo(e.PK);if(!r)throw new Error(`Invalid provider PK: ${e.PK}`);let n={userId:e.userId,provider:r.provider,externalId:r.externalId,createdAt:oe(e.createdAt)};if(e.externalUsername&&(n.externalUsername=e.externalUsername),e.externalEmail&&(n.externalEmail=e.externalEmail),e.externalPhone&&(n.externalPhone=e.externalPhone),e.externalName&&(n.externalName=e.externalName),e.externalAvatarUrl&&(n.externalAvatarUrl=e.externalAvatarUrl),e.metadata)try{n.metadata=JSON.parse(e.metadata)}catch{}return n}mapUserProviderLinkToItem(e){let r=Ne(),n={PK:K.PROVIDER_PK(e.provider,e.externalId),SK:K.PROVIDER_METADATA_SK(),userProviderPk:K.USER_PK(e.userId),userProviderSk:K.PROVIDER_PK(e.provider,e.externalId),userId:e.userId,createdAt:e.createdAt?Te(e.createdAt):r};return e.externalUsername&&(n.externalUsername=e.externalUsername),e.externalEmail&&(n.externalEmail=e.externalEmail),e.externalPhone&&(n.externalPhone=e.externalPhone),e.externalName&&(n.externalName=e.externalName),e.externalAvatarUrl&&(n.externalAvatarUrl=e.externalAvatarUrl),e.metadata&&(n.metadata=JSON.stringify(e.metadata)),Zr(n)}async findByProviderAndExternalId(e,r){try{let n=await this.docClient.send(new li.GetCommand({TableName:this.tableName,Key:{PK:K.PROVIDER_PK(e,r),SK:K.PROVIDER_METADATA_SK()}}));return n.Item?w(this.mapItemToUserProviderLink(n.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"find provider by external id"}))}}async findByUserId(e){try{let r=await this.docClient.send(new li.QueryCommand({TableName:this.tableName,IndexName:tt.USER_PROVIDERS,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:{"#pk":E.USER_PROVIDER_PK},ExpressionAttributeValues:{":pk":K.USER_PK(e)}}));return!r.Items||r.Items.length===0?w([]):w(r.Items.map(n=>this.mapItemToUserProviderLink(n)))}catch{return T(N.DatabaseQueryError({query:"find providers by user id"}))}}async create(e){try{let r={...e,createdAt:new Date},n=this.mapUserProviderLinkToItem(r);return await this.docClient.send(new li.PutCommand({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK)"})),w(this.mapItemToUserProviderLink(n))}catch(r){return lt(r)?T(N.UniqueConstraintViolation({field:"provider connection",message:"Provider connection already exists"})):T(N.DatabaseQueryError({query:"create user provider"}))}}async update(e,r,n){try{let i={};if(n.externalUsername!==void 0&&(i.externalUsername=n.externalUsername),n.externalEmail!==void 0&&(i.externalEmail=n.externalEmail),n.externalPhone!==void 0&&(i.externalPhone=n.externalPhone),n.externalName!==void 0&&(i.externalName=n.externalName),n.externalAvatarUrl!==void 0&&(i.externalAvatarUrl=n.externalAvatarUrl),n.metadata!==void 0&&(i.metadata=JSON.stringify(n.metadata)),Object.keys(i).length===0)return w(void 0);let{UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=$i(i);return await this.docClient.send(new li.UpdateCommand({TableName:this.tableName,Key:{PK:K.PROVIDER_PK(e,r),SK:K.PROVIDER_METADATA_SK()},UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"update user provider"}))}}async remove(e,r){try{return await this.docClient.send(new li.DeleteCommand({TableName:this.tableName,Key:{PK:K.PROVIDER_PK(e,r),SK:K.PROVIDER_METADATA_SK()}})),w(void 0)}catch{return T(N.DatabaseQueryError({query:"delete user provider"}))}}};var wa=ge(ir(),1);var im=class{docClient;tableName;constructor(e,r){this.docClient=e,this.tableName=r}mapItemToEntity(e){let r=ve.tenantId(e.PK),n=ve.tenantProfileUserId(e.SK),i={tenantId:r,userId:n,createdAt:oe(e.createdAt),updatedAt:oe(e.updatedAt)};return e.contactEmail&&(i.contactEmail=e.contactEmail),e.contactPhone&&(i.contactPhone=e.contactPhone),e.displayName&&(i.displayName=e.displayName),e.displayNameSource&&(i.displayNameSource=e.displayNameSource),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.avatarUrl&&(i.avatarUrl=e.avatarUrl),e.locale&&(i.locale=e.locale),e.jobTitle&&(i.jobTitle=e.jobTitle),e.bio&&(i.bio=e.bio),e.metadata&&(i.metadata=JSON.parse(e.metadata)),i}async get(e,r){try{let n=await this.docClient.send(new wa.GetCommand({TableName:this.tableName,Key:{PK:K.TENANT_PROFILE_PK(e),SK:K.TENANT_PROFILE_SK(r)}}));return n.Item?w(this.mapItemToEntity(n.Item)):w(null)}catch{return T(N.DatabaseQueryError({query:"get user tenant profile"}))}}async create(e){try{let r=Ne(),n={PK:K.TENANT_PROFILE_PK(e.tenantId),SK:K.TENANT_PROFILE_SK(e.userId),createdAt:r,updatedAt:r};e.contactEmail&&(n.contactEmail=e.contactEmail),e.contactPhone&&(n.contactPhone=e.contactPhone),e.displayName&&(n.displayName=e.displayName),e.displayNameSource&&(n.displayNameSource=e.displayNameSource),e.givenName&&(n.givenName=e.givenName),e.familyName&&(n.familyName=e.familyName),e.avatarUrl&&(n.avatarUrl=e.avatarUrl),e.locale&&(n.locale=e.locale),e.jobTitle&&(n.jobTitle=e.jobTitle),e.bio&&(n.bio=e.bio),e.metadata&&(n.metadata=JSON.stringify(e.metadata)),await this.docClient.send(new wa.PutCommand({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}));let i={tenantId:e.tenantId,userId:e.userId,createdAt:oe(r),updatedAt:oe(r)};return e.contactEmail&&(i.contactEmail=e.contactEmail),e.contactPhone&&(i.contactPhone=e.contactPhone),e.displayName&&(i.displayName=e.displayName),e.displayNameSource&&(i.displayNameSource=e.displayNameSource),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.avatarUrl&&(i.avatarUrl=e.avatarUrl),e.locale&&(i.locale=e.locale),e.jobTitle&&(i.jobTitle=e.jobTitle),e.bio&&(i.bio=e.bio),e.metadata&&(i.metadata=e.metadata),w(i)}catch(r){return r.name==="ConditionalCheckFailedException"?T(N.UniqueConstraintViolation({field:"user tenant profile"})):T(N.UnknownError({message:r.message}))}}async update(e,r,n){try{let i={updatedAt:Ne()};n.contactEmail!==void 0&&(i.contactEmail=n.contactEmail),n.contactPhone!==void 0&&(i.contactPhone=n.contactPhone),n.displayName!==void 0&&(i.displayName=n.displayName),n.displayNameSource!==void 0&&(i.displayNameSource=n.displayNameSource),n.givenName!==void 0&&(i.givenName=n.givenName),n.familyName!==void 0&&(i.familyName=n.familyName),n.avatarUrl!==void 0&&(i.avatarUrl=n.avatarUrl),n.locale!==void 0&&(i.locale=n.locale),n.jobTitle!==void 0&&(i.jobTitle=n.jobTitle),n.bio!==void 0&&(i.bio=n.bio),n.metadata!==void 0&&(i.metadata=n.metadata?JSON.stringify(n.metadata):null);let{UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=$i(i);return await this.docClient.send(new wa.UpdateCommand({TableName:this.tableName,Key:{PK:K.TENANT_PROFILE_PK(e),SK:K.TENANT_PROFILE_SK(r)},UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"UserTenantProfile",id:`${e}:${r}`})):T(N.UnknownError({message:i.message}))}}async remove(e,r){try{return await this.docClient.send(new wa.DeleteCommand({TableName:this.tableName,Key:{PK:K.TENANT_PROFILE_PK(e),SK:K.TENANT_PROFILE_SK(r)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),w(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?T(N.NotFound({entity:"UserTenantProfile",id:`${e}:${r}`})):T(N.UnknownError({message:n.message}))}}};var j_=class{name="database-dynamodb";version="1.0.0";users;sessions;userProviders;userMfaAuthenticators;challenges;identities;credentials;registration;userAuths;tenantMembers;tenantInvites;userTenantProfiles;tenants;queries;client;tableName;constructor(e){this.tableName=e.tableName,this.client=e.client||new z_.DynamoDBClient(e.clientConfig||{});let r=m8.DynamoDBDocumentClient.from(this.client,{marshallOptions:{removeUndefinedValues:!0,convertClassInstanceToMap:!0}});this.users=new rm(this.client,this.tableName),this.sessions=new jf({client:this.client,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userProviders=new nm(this.client,this.tableName),this.userMfaAuthenticators=new tm(this.client,this.tableName),this.challenges=new Hf({docClient:r,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.identities=new qf({docClient:r,tableName:this.tableName}),this.credentials=new Gf({docClient:r,tableName:this.tableName}),this.registration=new Wf({docClient:r,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userAuths=new em({docClient:r,tableName:this.tableName}),this.tenantMembers=new Yf(this.client,this.tableName),this.tenantInvites=new Qf({docClient:r,tableName:this.tableName}),this.userTenantProfiles=new im(r,this.tableName),this.tenants=new Zf({docClient:r,tableName:this.tableName}),this.queries={tenantInvites:new zf({docClient:r,tableName:this.tableName}),tenantMembers:new Jf({docClient:r,tableName:this.tableName}),tenants:new Xf({docClient:r,tableName:this.tableName})}}async initialize(){}async health(){try{return await this.client.send(new z_.DescribeTableCommand({TableName:this.tableName})),!0}catch(e){return console.error("DynamoDB health check failed:",e),!1}}async cleanup(){this.client.destroy()}};Bv();var Fv=1,H5=2,G5=3,q5="auth-craft:internal";async function tye(t){let e=t.replace(/^0x/,""),r=j5(e),n=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length);let s=`-----BEGIN PRIVATE KEY-----
|
|
188
188
|
`+btoa(String.fromCharCode(...i)).match(/.{1,64}/g).join(`
|
|
189
189
|
`)+`
|
|
190
190
|
-----END PRIVATE KEY-----`;return fm(s,"EdDSA")}async function rye(t){let e=t.replace(/^0x/,""),r=j5(e),n=iye(r);return In({kty:"OKP",crv:"Ed25519",x:n},"EdDSA")}async function Kv(t,e){if(e==="EdDSA"){let r=t.trim();if(r.startsWith("{"))return In(JSON.parse(r),e);if(!r.includes(`
|
package/assets/lambda/index.mjs
CHANGED
|
@@ -125,7 +125,7 @@ ${t}`)}if(F.nodeEnv==="production"&&!F.gatewaySecret)throw new Error("GATEWAY_SE
|
|
|
125
125
|
</div>
|
|
126
126
|
</body>
|
|
127
127
|
</html>
|
|
128
|
-
`}};var Ea=class t{static createDirectSmtp(e){return new Ll(e)}static create(e){return t.createDirectSmtp(e.smtp)}};var Rw={allowPlusAddressing:!0,allowDots:!0,requireTLD:!0};function Zv(t={}){let e={...Rw,...t},n=(()=>{if(t.customRegex)return t.customRegex;let i="[a-zA-Z0-9_\\-]";e.allowDots?(i+="+",i=`(${i}\\.?)+`):i+="+",e.allowPlusAddressing&&(i=`${i}(\\+[a-zA-Z0-9_\\-]+)?`);let s=e.requireTLD?"[a-zA-Z0-9][a-zA-Z0-9\\-]*\\.[a-zA-Z]{2,}":"[a-zA-Z0-9][a-zA-Z0-9\\-\\.]*";return new RegExp(`^${i}@${s}$`)})();return{name:"email-identity",version:"1.0.0",identityType:"email",normalize(i){return i.toLowerCase().trim()},validate(i){if(!i||i.trim().length===0)return u([{code:"EMAIL_REQUIRED",message:"Email address is required"}]);if(i.length>254)return u([{code:"EMAIL_TOO_LONG",message:"Email address is too long (max 254 characters)"}]);if(!n.test(i))return u([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);if(i.includes(".."))return u([{code:"INVALID_EMAIL_FORMAT",message:"Email address cannot contain consecutive dots"}]);let s=i.split("@");if(s.length!==2)return u([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);let[o,a]=s;return!o||o.length>64?u([{code:"EMAIL_LOCAL_PART_TOO_LONG",message:"Email local part is too long (max 64 characters)"}]):a&&a.length>253?u([{code:"EMAIL_DOMAIN_TOO_LONG",message:"Email domain is too long (max 253 characters)"}]):g()}}}function Zp(t=6){let e="";for(;e.length<t;){let r=new Uint8Array(t);crypto.getRandomValues(r);for(let n=0;n<r.length&&e.length<t;n++){let i=r[n];i>=250||(e+=(i%10).toString())}}return e}function Ow(t){return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}async function ef(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Ow(r)}var tf="email",Ml={EMAIL_SYSTEM_NOT_AVAILABLE:T("MFA_EMAIL_SYSTEM_NOT_AVAILABLE","Email system is not configured"),RECIPIENT_NOT_FOUND:T("MFA_EMAIL_RECIPIENT_NOT_FOUND","No email address on file for this user"),SEND_FAILED:T("MFA_EMAIL_SEND_FAILED","Failed to send the verification email"),USE_CHALLENGE_CODE_HASH:T("MFA_EMAIL_USE_CHALLENGE_CODE_HASH","Email MFA codes are verified against the challenge code hash, not stored credentials")};function kw(t){let[e,r]=t.split("@");return!e||!r?"***":`${e.slice(0,1)}***@${r}`}function eA(t={}){let e=t.codeLength??6,r=t.template??"mfa-email-code";return{name:"email-mfa",version:"1.0.0",method:tf,requiresServerDelivery:!0,async sendCode(n,i){if(!i.plugins.emailSystem)return u(Ml.EMAIL_SYSTEM_NOT_AVAILABLE());let s=await i.plugins.database.users.getById(n.userId),o=s.ok&&s.data?s.data.contactEmail:void 0;if(!o)return u(Ml.RECIPIENT_NOT_FOUND());let a=Zp(e),c=await ef(a);return(await i.plugins.emailSystem.send({to:o,template:r,variables:{code:a,purpose:"mfa"}})).ok===!1?u(Ml.SEND_FAILED()):g({codeHash:c,maskedRecipient:kw(o)})},async issueChallenge(n){return g({challengeId:`email_${Date.now()}`,methods:n.availableMethods.includes(tf)?[tf]:n.availableMethods,expiresAt:new Date(Date.now()+300*1e3)})},async verify(){return u(Ml.USE_CHALLENGE_CODE_HASH())}}}var tA="ABCDEFGHIJKLMNPQRSTUVWXYZ23456789";function Kl(t=10,e=10){let r=[];for(let n=0;n<t;n++){let i=new Uint8Array(e);crypto.getRandomValues(i);let s="";for(let o of i)s+=tA[o%tA.length];r.push(s)}return r}function Cw(t){return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}async function Hl(t){let e=new TextEncoder().encode(t.toUpperCase().trim()),r=await crypto.subtle.digest("SHA-256",e);return Cw(r)}function Dw(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t.charCodeAt(n)^e.charCodeAt(n);return r===0}async function rf(t,e){let r=await Hl(t),n=null;for(let i of e)Dw(r,i)&&(n=i);return n}var nf="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function rA(t){let e=t.toUpperCase().replace(/=+$/u,"").replace(/\s+/gu,""),r=0,n=0,i=[];for(let s of e){let o=nf.indexOf(s);if(o===-1)throw new Error("Invalid base32 character in TOTP secret");n=n<<5|o,r+=5,r>=8&&(r-=8,i.push(n>>>r&255))}return new Uint8Array(i)}function nA(t){let e=0,r=0,n="";for(let i of t)for(r=r<<8|i,e+=8;e>=5;)e-=5,n+=nf[r>>>e&31];return e>0&&(n+=nf[r<<5-e&31]),n}function Fl(t=20){let e=new Uint8Array(t);return crypto.getRandomValues(e),nA(e)}function Pw(t){let e=new Uint8Array(8),r=t;for(let n=7;n>=0;n--)e[n]=r&255,r=Math.floor(r/256);return e}async function Uw(t,e,r){let n=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-1"},!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign("HMAC",n,Pw(e))),s=i[i.length-1]&15;return(((i[s]&127)<<24|(i[s+1]&255)<<16|(i[s+2]&255)<<8|i[s+3]&255)%10**r).toString().padStart(r,"0")}async function Vl(t,e,r=Date.now(),n={}){let i=n.period??30,s=n.digits??6,o=n.window??1,a=e.trim();if(a.length!==s||!/^\d+$/u.test(a))return!1;let c=rA(t),l=Math.floor(r/1e3/i),d=!1;for(let p=-o;p<=o;p++){let m=await Uw(c,l+p,s);Lw(m,a)&&(d=!0)}return d}function Lw(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t.charCodeAt(n)^e.charCodeAt(n);return r===0}function iA(t){let e=encodeURIComponent(`${t.issuer}:${t.accountName}`),r=new URLSearchParams({secret:t.secretBase32,issuer:t.issuer,algorithm:"SHA1",digits:String(t.digits??6),period:String(t.period??30)});return`otpauth://totp/${e}?${r.toString()}`}var sf="totp",Mw={USE_VERIFY_WITH_CREDENTIALS:{code:"TOTP_USE_VERIFY_WITH_CREDENTIALS",message:"TOTP verification requires credential data; call verifyWithCredentials()"}};function sA(t={}){let e=t.issuer??"Auth Craft",r=t.backupCodeCount??10,n=t.window??1;return{name:"totp-mfa",version:"1.0.0",method:sf,requiresServerDelivery:!1,generateSecret(){return Fl()},generateBackupCodes(i){return Kl(i||r)},async issueChallenge(i){return g({challengeId:`totp_${Date.now()}`,methods:i.availableMethods.includes(sf)?[sf]:i.availableMethods,expiresAt:new Date(Date.now()+300*1e3)})},async verify(){return u(Mw.USE_VERIFY_WITH_CREDENTIALS)},async setup(i){let s=Fl(),o=Kl(r),a=await Promise.all(o.map(p=>Hl(p))),c=i.data.accountName??i.userId,l=iA({secretBase32:s,accountName:c,issuer:e});return g({secret:s,otpauthUri:l,backupCodes:o,credentialData:{secret:s,backupCodeHashes:a}})},async verifyWithCredentials(i){let s=i.credentialData,o=i.data.code?.trim();if(!o||!s?.secret)return g({verified:!1,data:{}});if(await Vl(s.secret,o,Date.now(),{window:n}))return g({verified:!0,data:{}});let c=s.backupCodeHashes??[];if(c.length>0){let l=await rf(o,c);if(l)return g({verified:!0,data:{usedBackupCodeHash:l}})}return g({verified:!1,data:{}})},async verifyCredential(i,s){let o=i.data.code,a=i.data.secret;if(!o||!a)return g({verified:!1,data:{}});let c=await Vl(a,o,Date.now(),{window:n});return g({verified:c,data:{}})}}}var of={scopes:["email","public_profile"],apiVersion:"v18.0"};var Yr={INVALID_CODE:T("FACEBOOK_INVALID_CODE","Invalid authorization code"),TOKEN_EXCHANGE_FAILED:T("FACEBOOK_TOKEN_EXCHANGE_FAILED","Failed to exchange code for token"),USER_PROFILE_FAILED:T("FACEBOOK_USER_PROFILE_FAILED","Failed to fetch user profile"),INVALID_TOKEN:T("FACEBOOK_INVALID_TOKEN","Invalid access token"),MISSING_CONFIG:T("FACEBOOK_MISSING_CONFIG","Missing required Facebook OAuth configuration")};function af(t={}){let{scopes:e=of.scopes,apiVersion:r=of.apiVersion}=t,n={AUTHORIZATION:`https://www.facebook.com/${r}/dialog/oauth`,TOKEN:`https://graph.facebook.com/${r}/oauth/access_token`,USER_INFO:`https://graph.facebook.com/${r}/me`,DEBUG_TOKEN:`https://graph.facebook.com/${r}/debug_token`};return{name:"facebook-oauth-provider",version:"1.0.0",getAuthorizationUrl(i,s){let o=new URLSearchParams({client_id:i.clientId,redirect_uri:i.redirectUri,scope:(i.scopes??e).join(","),response_type:"code",...s&&{state:s}});return`${n.AUTHORIZATION}?${o.toString()}`},async exchangeCodeForToken(i,s){try{if(!i)return u(Yr.INVALID_CODE());let o=new URLSearchParams({client_id:s.clientId,client_secret:s.clientSecret,code:i,redirect_uri:s.redirectUri}),a=await fetch(`${n.TOKEN}?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!a.ok)return u(Yr.TOKEN_EXCHANGE_FAILED());let c=await a.json();return g({accessToken:c.access_token,...c.expires_in&&{expiresIn:c.expires_in}})}catch(o){return console.error("Facebook token exchange error:",o),u(Yr.TOKEN_EXCHANGE_FAILED())}},async getUserProfile(i){try{if(!i)return u(Yr.INVALID_TOKEN());let s=["id","email","name","first_name","last_name","picture","locale"],o=new URLSearchParams({fields:s.join(","),access_token:i}),a=await fetch(`${n.USER_INFO}?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!a.ok)return u(Yr.USER_PROFILE_FAILED());let c=await a.json(),l={id:c.id,...c.email&&{email:c.email},...c.email&&{emailVerified:!1},...c.name&&{name:c.name},...c.first_name&&{givenName:c.first_name},...c.last_name&&{familyName:c.last_name},...c.picture?.data?.url&&{avatarUrl:c.picture.data.url},...c.locale&&{locale:c.locale},provider:"facebook"};return g(l)}catch(s){return console.error("Facebook user profile error:",s),u(Yr.USER_PROFILE_FAILED())}},async verifyAccessToken(i){try{if(!i)return u(Yr.INVALID_TOKEN());let s=`${t.appId}|${t.appSecret}`,o=new URLSearchParams({input_token:i,access_token:s}),a=await fetch(`${n.DEBUG_TOKEN}?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}});return a.ok?(await a.json()).data.is_valid?this.getUserProfile(i):u(Yr.INVALID_TOKEN()):u(Yr.INVALID_TOKEN())}catch(s){return console.error("Facebook token verification error:",s),u(Yr.INVALID_TOKEN())}}}}var Bl={scopes:["openid","email","profile"],accessType:"online",includeGrantedScopes:!1},bi={AUTHORIZATION:"https://accounts.google.com/o/oauth2/v2/auth",TOKEN:"https://oauth2.googleapis.com/token",USER_INFO:"https://www.googleapis.com/oauth2/v2/userinfo",TOKEN_INFO:"https://oauth2.googleapis.com/tokeninfo",REVOKE:"https://oauth2.googleapis.com/revoke"};var et={INVALID_CODE:T("GOOGLE_INVALID_CODE","Invalid authorization code"),TOKEN_EXCHANGE_FAILED:T("GOOGLE_TOKEN_EXCHANGE_FAILED","Failed to exchange code for token"),USER_PROFILE_FAILED:T("GOOGLE_USER_PROFILE_FAILED","Failed to fetch user profile"),INVALID_TOKEN:T("GOOGLE_INVALID_TOKEN","Invalid access token"),INVALID_CREDENTIAL:T("GOOGLE_INVALID_CREDENTIAL","Invalid ID token or credential"),CREDENTIAL_VERIFICATION_FAILED:T("GOOGLE_CREDENTIAL_VERIFICATION_FAILED","Failed to verify credential"),REFRESH_TOKEN_FAILED:T("GOOGLE_REFRESH_TOKEN_FAILED","Failed to refresh access token"),MISSING_CONFIG:T("GOOGLE_MISSING_CONFIG","Missing required Google OAuth configuration")};function Kw(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4;if(r){if(r===1)throw new Error("Invalid base64url string");e+=new Array(5-r).join("=")}try{return decodeURIComponent(atob(e).split("").map(n=>`%${`00${n.charCodeAt(0).toString(16)}`.slice(-2)}`).join(""))}catch{throw new Error("Failed to decode base64url")}}function Hw(t){try{let e=t.split(".");if(e.length!==3)return null;let r=e[1];if(!r)return null;let n=Kw(r);return JSON.parse(n)}catch(e){return console.error("Failed to decode JWT:",e),null}}function cf(t={}){let{clientId:e,clientSecret:r,redirectUri:n,scopes:i=Bl.scopes,accessType:s=Bl.accessType,includeGrantedScopes:o=Bl.includeGrantedScopes,prompt:a}=t;return{name:"google-oauth-provider",version:"1.0.0",getAuthorizationUrl(c,l){let d=c?.clientId??e,p=c?.redirectUri??n;if(!d||!p)throw new Error("Google OAuth: clientId and redirectUri are required");let m=new URLSearchParams({client_id:d,redirect_uri:p,response_type:"code",scope:(c?.scopes??i).join(" "),access_type:s,...l&&{state:l},...a&&{prompt:a},...o&&{include_granted_scopes:"true"}});return`${bi.AUTHORIZATION}?${m.toString()}`},async exchangeCodeForToken(c,l){let d=l?.clientId??e,p=l?.clientSecret??r,m=l?.redirectUri??n;try{if(!c)return u(et.INVALID_CODE());if(!d||!p||!m)return u(et.MISSING_CONFIG());let E=new URLSearchParams({client_id:d,client_secret:p,code:c,redirect_uri:m,grant_type:"authorization_code"}),v=await fetch(bi.TOKEN,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E.toString()});if(!v.ok)return console.error("Google token exchange failed with status:",v.status),u(et.TOKEN_EXCHANGE_FAILED());let b=await v.json();return g({accessToken:b.access_token,...b.refresh_token&&{refreshToken:b.refresh_token},...b.expires_in&&{expiresIn:b.expires_in}})}catch(E){return console.error("Google token exchange error:",E),u(et.TOKEN_EXCHANGE_FAILED())}},async getUserProfile(c){try{if(!c)return u(et.INVALID_TOKEN());let l=await fetch(bi.USER_INFO,{method:"GET",headers:{Authorization:`Bearer ${c}`,Accept:"application/json"}});if(!l.ok)return console.error("Google user profile failed with status:",l.status),u(et.USER_PROFILE_FAILED());let d=await l.json(),p={id:d.id,...d.email&&{email:d.email},...d.verified_email!==void 0&&{emailVerified:d.verified_email},...d.name&&{name:d.name},...d.given_name&&{givenName:d.given_name},...d.family_name&&{familyName:d.family_name},...d.picture&&{avatarUrl:d.picture},...d.locale&&{locale:d.locale},provider:"google"};return g(p)}catch(l){return console.error("Google user profile error:",l),u(et.USER_PROFILE_FAILED())}},async verifyAccessToken(c){try{if(!c)return u(et.INVALID_TOKEN());let l=await fetch(`${bi.TOKEN_INFO}?access_token=${c}`,{method:"GET",headers:{Accept:"application/json"}});if(!l.ok)return u(et.INVALID_TOKEN());let d=await l.json();return parseInt(d.expires_in,10)<=0?u(et.INVALID_TOKEN()):this.getUserProfile(c)}catch(l){return console.error("Google token verification error:",l),u(et.INVALID_TOKEN())}},async verifyCredential(c){try{if(!c)return u(et.INVALID_CREDENTIAL());let l=await fetch(`${bi.TOKEN_INFO}?id_token=${encodeURIComponent(c)}`,{method:"GET",headers:{Accept:"application/json"}});if(!l.ok)return console.error("Google credential verification failed with status:",l.status),u(et.INVALID_CREDENTIAL());let d=await l.json();if(!e)return u(et.MISSING_CONFIG());if(d.aud!==e)return u(et.INVALID_CREDENTIAL());if(parseInt(d.expires_in,10)<=0)return u(et.INVALID_CREDENTIAL());let m=d.email_verified==="true",E=Hw(c),v={id:d.sub,...d.email&&{email:d.email},...d.email&&{emailVerified:m},...E?.name&&{name:E.name},...E?.given_name&&{givenName:E.given_name},...E?.family_name&&{familyName:E.family_name},...E?.picture&&{avatarUrl:E.picture},...E?.locale&&{locale:E.locale},provider:"google"};return g(v)}catch(l){return console.error("Google credential verification error:",l),u(et.CREDENTIAL_VERIFICATION_FAILED())}},async refreshAccessToken(c,l){let d=l?.clientId??e,p=l?.clientSecret??r;try{if(!c)return u(et.INVALID_TOKEN());if(!d||!p)return u(et.MISSING_CONFIG());let m=new URLSearchParams({client_id:d,client_secret:p,refresh_token:c,grant_type:"refresh_token"}),E=await fetch(bi.TOKEN,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:m.toString()});if(!E.ok)return console.error("Google refresh token failed with status:",E.status),u(et.REFRESH_TOKEN_FAILED());let v=await E.json();return g({accessToken:v.access_token,...v.expires_in&&{expiresIn:v.expires_in}})}catch(m){return console.error("Google refresh token error:",m),u(et.REFRESH_TOKEN_FAILED())}}}}function oA(t={}){let e=new Map,r=t.sweepIntervalMs??6e4,n=0,i;function s(){if(n===0)return;let o=Date.now()-n;for(let[a,c]of e){let l=c.hits.filter(d=>d>o);l.length===0?e.delete(a):c.hits=l}}return r>0&&(i=setInterval(s,r),i.unref?.()),{name:"rate-limiter-memory",version:"1.0.0",async consume(o,a){let{limit:c,windowMs:l}=a;l>n&&(n=l);let d=Date.now(),p=d-l,m=e.get(o)??{hits:[]},E=m.hits.filter(v=>v>p);if(E.length>=c){let v=E[0]??d,b=Math.max(0,v+l-d);return m.hits=E,e.set(o,m),{allowed:!1,remaining:0,retryAfterMs:b,limit:c}}return E.push(d),m.hits=E,e.set(o,m),{allowed:!0,remaining:c-E.length,retryAfterMs:0,limit:c}},async reset(o){e.delete(o)},async cleanup(){i&&clearInterval(i),e.clear()}}}import{DescribeTableCommand as a0,DynamoDBClient as c0}from"@aws-sdk/client-dynamodb";import{DynamoDBDocumentClient as l0}from"@aws-sdk/lib-dynamodb";var M={DatabaseConnectionError:T("DATABASE_CONNECTION_ERROR","Failed to connect to database"),DatabaseQueryError:X("DATABASE_QUERY_ERROR","Database query execution failed: {query}"),NotFound:X("REPOSITORY_NOT_FOUND","{entity} with {id} not found"),UniqueConstraintViolation:X("UNIQUE_CONSTRAINT_VIOLATION","Record with this {field} already exists"),ForeignKeyViolation:X("FOREIGN_KEY_VIOLATION","Referenced {field} does not exist"),RecordLocked:T("RECORD_LOCKED","Record is currently locked by another operation"),DeadlockDetected:T("DEADLOCK_DETECTED","Transaction deadlock detected"),InvalidData:X("INVALID_DATA","Invalid data: {reason}"),Timeout:T("REPOSITORY_TIMEOUT","Database operation timed out"),AttemptsExceeded:T("ATTEMPTS_EXCEEDED","Attempt limit reached"),TransactionFailed:X("TRANSACTION_FAILED","Transaction failed: {reason}"),UnknownError:X("REPOSITORY_UNKNOWN_ERROR","Unexpected database error: {message}")};function ne(t){return t.getTime()}function z(t){return new Date(t)}function aA(t){return Math.floor(t/1e3)}function ae(){return Date.now()}function ya(t){return t instanceof Date?aA(t.getTime()):aA(t)}function lf(t){return t<Date.now()}function Nr(t){return t?ne(t):null}function Ht(t){return t==null?null:z(t)}function Ft(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}function wr(t){let e=[],r=[],n={},i={},s=0;for(let[c,l]of Object.entries(t)){if(c==="PK"||c==="SK")continue;let d=`#${c}`;if(n[d]=c,l==null)r.push(d);else{let p=`:val${s}`;e.push(`${d} = ${p}`),i[p]=l,s++}}let o=[];return e.length>0&&o.push(`SET ${e.join(", ")}`),r.length>0&&o.push(`REMOVE ${r.join(", ")}`),{UpdateExpression:o.join(" "),ExpressionAttributeNames:n,ExpressionAttributeValues:i}}function uf(t="PK"){return`attribute_not_exists(${t})`}var df={USER:"USR"},ce={USER:`${df.USER}#`,SESSION:"SES#",PROVIDER:"PRV#",CHALLENGE:"CHL#",IDENTITY:"IDT#",CREDENTIAL:"CRD#",TENANT:"TNT#",INVITE:"INV#"},Ve={METADATA:"MD",AUTH:"AUTH",PROFILE:"PROF",PROVIDER:"PRV#",MFA:"MFA#",TENANT_PROFILE:"TPRF#",OWNER:"OWNER"},St="#",D={USER_PK:t=>`${ce.USER}${t}`,USER_AUTH_SK:()=>Ve.AUTH,USER_PROFILE_SK:()=>Ve.PROFILE,USER_MFA_SK:t=>`${Ve.MFA}${t}`,USER_MFA_WITH_ID_SK:(t,e)=>`${Ve.MFA}${t}${St}${e}`,TENANT_MEMBER_PK:t=>`${ce.TENANT}${t}`,TENANT_MEMBER_SK:t=>`${ce.USER}${t}`,TENANT_OWNER_MARKER_SK:()=>Ve.OWNER,TENANT_PK:t=>`${ce.TENANT}${t}`,TENANT_SK:()=>Ve.METADATA,INVITE_PK:t=>`${ce.INVITE}${t}`,INVITE_SK:()=>Ve.METADATA,TENANT_PROFILE_PK:t=>`${ce.TENANT}${t}`,TENANT_PROFILE_SK:t=>`${Ve.TENANT_PROFILE}${ce.USER}${t}`,SESSION_PK:t=>`${ce.SESSION}${t}`,SESSION_METADATA_SK:()=>Ve.METADATA,SESSION_SK:()=>Ve.METADATA,PROVIDER_SK:(t,e)=>`${Ve.PROVIDER}${t}${St}${e}`,PROVIDER_PK:(t,e)=>`${ce.PROVIDER}${t}${St}${e}`,PROVIDER_METADATA_SK:()=>Ve.METADATA,CHALLENGE_PK:t=>`${ce.CHALLENGE}${t}`,CHALLENGE_SK:()=>Ve.METADATA,IDENTITY_PK:(t,e)=>`${ce.IDENTITY}${t}#${e}`,IDENTITY_SK:()=>Ve.METADATA,CREDENTIAL_PK:t=>`${ce.CREDENTIAL}${t}`,CREDENTIAL_SK:()=>Ve.METADATA,CREDENTIAL_TYPE_PREFIX:t=>`${ce.CREDENTIAL}${t}#`,CREDENTIAL_USER_SK:(t,e)=>`${ce.CREDENTIAL}${t}#${e}`,USER_INDEX_PK:t=>`${ce.USER}${t}`,USER_INDEX_SK:(t,e)=>`${ce.IDENTITY}${t}#${e}`},le={userId:t=>t.slice(ce.USER.length),sessionId:t=>t.slice(ce.SESSION.length),providerPKInfo:t=>{let e=t.slice(ce.PROVIDER.length),r=e.indexOf("#");if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{provider:n,externalId:i}},providerInfo:t=>{let e=t.slice(Ve.PROVIDER.length),r=e.indexOf(St);if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{provider:n,externalId:i}},mfaSKInfo:t=>{let e=t.slice(Ve.MFA.length),r=e.indexOf(St);if(r===-1)return{method:e};let n=e.slice(0,r),i=e.slice(r+1);return{method:n,id:i}},tenantId:t=>t.slice(ce.TENANT.length),tenantMemberUserId:t=>t.slice(ce.USER.length),challengeIdFromPK:t=>t.slice(ce.CHALLENGE.length),inviteId:t=>t.slice(ce.INVITE.length),tenantProfileUserId:t=>t.slice(Ve.TENANT_PROFILE.length+ce.USER.length),identityPKInfo:t=>{let e=t.slice(ce.IDENTITY.length),r=e.indexOf("#");if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{type:n,value:i}},credentialId:t=>t.slice(ce.CREDENTIAL.length),credentialTypeFromUserSK:t=>{let e=t.slice(ce.CREDENTIAL.length),r=e.indexOf("#");return r===-1?"":e.slice(0,r)},userIndexSKInfo:t=>{let e=t.slice(ce.IDENTITY.length),r=e.indexOf("#");if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{type:n,value:i}}};var Ae={ACTIVE_SESSION_PK:t=>`${ce.USER}${t}`,ACTIVE_SESSION_SK:(t,e)=>`${t}${St}${e}`,USER_SESSION_PK:t=>`${ce.USER}${t}`,USER_SESSION_SK:(t,e)=>`${t}${St}${e}`,USER_STATUS_PK:t=>{let e=t===ye.ACTIVE?"ACTIVE":"INACTIVE";return`${df.USER}${St}${e}`},USER_STATUS_SK:t=>t,USER_PROVIDER_PK:t=>`${ce.USER}${t}`,USER_PROVIDER_SK:(t,e)=>`${Ve.PROVIDER}${t}${St}${e}`,INVITE_TENANT_PK:t=>`${ce.TENANT}${t}`,INVITE_TENANT_SK:(t,e,r)=>`${t}${St}${e}${St}${r}`,INVITE_TENANT_STATUS_PREFIX:t=>`${t}${St}`,USER_TENANT_PK:t=>`${ce.USER}${t}`,USER_TENANT_SK:(t,e,r,n)=>`${t}${St}${e??"ROOT"}${St}${r}${St}${n}`},f={PK:"PK",SK:"SK",TTL:"TTL",ACTIVE_SESSION_PK:"activeSessionPk",ACTIVE_SESSION_SK:"activeSessionSk",USER_SESSION_PK:"userSessionPk",USER_SESSION_SK:"userSessionSk",USER_STATUS_PK:"userStatusPk",USER_STATUS_SK:"userStatusSk",USER_PROVIDER_PK:"userProviderPk",USER_PROVIDER_SK:"userProviderSk",USER_ID:"userId",TENANT_ID:"tenantId",TENANT_TYPE:"tenantType",AUDIENCE:"audience",PURPOSE:"purpose",CHALLENGE_STATUS:"challengeStatus",PHASE:"phase",ALLOWED_METHODS:"allowedMethods",METHOD:"method",IDENTITY_TYPE:"identityType",IDENTITY_VALUE:"identityValue",CODE_HASH:"codeHash",ATTEMPTS:"attempts",MAX_ATTEMPTS:"maxAttempts",METADATA:"metadata",FLOW_KEY:"flowKey",EXPIRES_AT:"expiresAt",CREATED_AT:"createdAt",TOKEN_ID:"tokenId",PREVIOUS_TOKEN_ID:"previousTokenId",ROTATED_AT:"rotatedAt",LAST_USED_AT:"lastUsedAt",REVOKED_AT:"revokedAt",ROLE:"role",ROLES:"roles",PERM:"perm",AUTH_PERM:"authPerm",IS_OWNER:"isOwner",DEVICE_LABEL:"deviceLabel",COUNTRY:"country",CITY:"city",IDENTITY_USER_PK:"identityUserPk",IDENTITY_USER_SK:"identityUserSk",LOGIN_ENABLED:"loginEnabled",VERIFIED_AT:"verifiedAt",GUARDS:"guards",PENDING_VERIFICATION:"pendingVerification",UPDATED_AT:"updatedAt",CREDENTIAL_USER_PK:"credentialUserPk",CREDENTIAL_USER_SK:"credentialUserSk",CREDENTIAL_VALUE:"value",INVITE_STATUS:"inviteStatus",INVITE_TOKEN:"inviteToken",INVITED_BY_ID:"invitedById",INVITED_BY_INFO:"invitedByInfo",INVITEE_USER_ID:"inviteeUserId",INVITEE_EMAIL:"inviteeEmail",INVITEE_PHONE:"inviteePhone",ACCEPTED_AT:"acceptedAt",DECLINED_AT:"declinedAt",INVITE_TENANT_PK:"inviteTenantPk",INVITE_TENANT_SK:"inviteTenantSk",INVITE_TOKEN_GSI:"inviteTokenGsi",INVITEE_EMAIL_GSI:"inviteeEmailGsi",INVITEE_EMAIL_TENANT_SK:"inviteeEmailTenantSk",INVITEE_PHONE_GSI:"inviteePhoneGsi",INVITEE_PHONE_TENANT_SK:"inviteePhoneTenantSk",USER_TENANT_PK:"userTenantPk",USER_TENANT_SK:"userTenantSk",DISPLAY_NAME:"displayName",AVATAR_URL:"avatarUrl",TITLE:"title",BIO:"bio"},Se={ACTIVE_SESSIONS:"GSI_ActiveSessions",USER_SESSIONS:"GSI_UserSessions",USERS_BY_STATUS:"GSI_UsersByStatus",USER_PROVIDERS:"GSI_UserProviders",USER_IDENTITIES:"GSI_UserIdentities",USER_CREDENTIALS:"GSI_UserCredentials",TENANT_INVITES:"GSI_TenantInvites",INVITE_TOKEN:"GSI_InviteToken",INVITEE_EMAIL:"GSI_InviteeEmail",INVITEE_PHONE:"GSI_InviteePhone",USER_TENANTS:"GSI_UserTenants"},ql={sessionSK:(t,e)=>`${t instanceof Date?t.getTime():t}${St}${e}`,extractCreatedAt:t=>{let e=t.indexOf(St),r=e===-1?t:t.slice(0,e);return Number(r)}};import{DeleteCommand as sR,GetCommand as oR,PutCommand as aR,UpdateCommand as TA}from"@aws-sdk/lib-dynamodb";var Fw=BigInt(0),ga=BigInt(1),Vw=BigInt(2),Bw=BigInt(7),qw=BigInt(256),jw=BigInt(113),uA=[],dA=[],pA=[];for(let t=0,e=ga,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],uA.push(2*(5*n+r)),dA.push((t+1)*(t+2)/2%64);let i=Fw;for(let s=0;s<7;s++)e=(e<<ga^(e>>Bw)*jw)%qw,e&Vw&&(i^=ga<<(ga<<BigInt(s))-ga);pA.push(i)}var fA=Gy(pA,!0),Gw=fA[0],$w=fA[1],cA=(t,e,r)=>r>32?zy(t,e,r):$y(t,e,r),lA=(t,e,r)=>r>32?Jy(t,e,r):Wy(t,e,r);function Ww(t,e=24){if(yt(e,"rounds"),e<1||e>24)throw new Error('"rounds" expected integer 1..24');let r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){let a=(o+8)%10,c=(o+2)%10,l=r[c],d=r[c+1],p=cA(l,d,1)^r[a],m=lA(l,d,1)^r[a+1];for(let E=0;E<50;E+=10)t[o+E]^=p,t[o+E+1]^=m}let i=t[2],s=t[3];for(let o=0;o<24;o++){let a=dA[o],c=cA(i,s,a),l=lA(i,s,a),d=uA[o];i=t[d],s=t[d+1],t[d]=c,t[d+1]=l}for(let o=0;o<50;o+=10){let a=t[o],c=t[o+1],l=t[o+2],d=t[o+3];t[o]^=~t[o+2]&t[o+4],t[o+1]^=~t[o+3]&t[o+5],t[o+2]^=~t[o+4]&t[o+6],t[o+3]^=~t[o+5]&t[o+7],t[o+4]^=~t[o+6]&t[o+8],t[o+5]^=~t[o+7]&t[o+9],t[o+6]^=~t[o+8]&a,t[o+7]^=~t[o+9]&c,t[o+8]^=~a&l,t[o+9]^=~c&d}t[0]^=Gw[n],t[1]^=$w[n]}jt(r)}var pf=class t{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;canXOF;enableXOF=!1;rounds;constructor(e,r,n,i=!1,s=24){if(this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.canXOF=i,this.rounds=s,yt(n,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Ks(this.state)}clone(){return this._cloneInto()}keccak(){Fs(this.state32),Ww(this.state32,this.rounds),Fs(this.state32),this.posOut=0,this.pos=0}update(e){hn(this),mn(e);let{blockLen:r,state:n}=this,i=e.length;for(let s=0;s<i;){let o=Math.min(r-this.pos,i-s);for(let a=0;a<o;a++)n[this.pos++]^=e[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:r,pos:n,blockLen:i}=this;e[n]^=r,(r&128)!==0&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){hn(this,!1),mn(e),this.finish();let r=this.state,{blockLen:n}=this;for(let i=0,s=e.length;i<s;){this.posOut>=n&&this.keccak();let o=Math.min(n-this.posOut,s-i);e.set(r.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return yt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ms(e,this),this.finished)throw new Error("digest() was already called");this.writeInto(e.subarray(0,this.outputLen)),this.destroy()}digest(){let e=new Uint8Array(this.outputLen);return this.digestInto(e),e}destroy(){this.destroyed=!0,jt(this.state)}_cloneInto(e){let{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return e||=new t(r,n,i,o,s),e.blockLen=r,e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=i,e.enableXOF=o,e.canXOF=this.canXOF,e.destroyed=this.destroyed,e}},zw=(t,e,r,n={})=>Tl(()=>new pf(e,t,r),n);var mA=zw(6,72,64,Il(10));var Jw=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,ff=Math.ceil,pr=Math.floor,Gt="[BigNumber Error] ",hA=Gt+"Number primitive has more than 15 significant digits: ",Rr=1e14,ue=14,mf=9007199254740991,hf=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Bn=1e7,vt=1e9;function EA(t){var e,r,n,i=L.prototype={constructor:L,toString:null,valueOf:null},s=new L(1),o=20,a=4,c=-7,l=21,d=-1e7,p=1e7,m=!1,E=1,v=0,b={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},k="0123456789abcdefghijklmnopqrstuvwxyz",C=!0;function L(A,x){var S,y,I,w,R,N,O,P,U=this;if(!(U instanceof L))return new L(A,x);if(x==null){if(A&&A._isBigNumber===!0){U.s=A.s,!A.c||A.e>p?U.c=U.e=null:A.e<d?U.c=[U.e=0]:(U.e=A.e,U.c=A.c.slice());return}if((N=typeof A=="number")&&A*0==0){if(U.s=1/A<0?(A=-A,-1):1,A===~~A){for(w=0,R=A;R>=10;R/=10,w++);w>p?U.c=U.e=null:(U.e=w,U.c=[A]);return}P=String(A)}else{if(!Jw.test(P=String(A)))return n(U,P,N);U.s=P.charCodeAt(0)==45?(P=P.slice(1),-1):1}(w=P.indexOf("."))>-1&&(P=P.replace(".","")),(R=P.search(/e/i))>0?(w<0&&(w=R),w+=+P.slice(R+1),P=P.substring(0,R)):w<0&&(w=P.length)}else{if(We(x,2,k.length,"Base"),x==10&&C)return U=new L(A),$(U,o+U.e+1,a);if(P=String(A),N=typeof A=="number"){if(A*0!=0)return n(U,P,N,x);if(U.s=1/A<0?(P=P.slice(1),-1):1,L.DEBUG&&P.replace(/^0\.0*|\./,"").length>15)throw Error(hA+A)}else U.s=P.charCodeAt(0)===45?(P=P.slice(1),-1):1;for(S=k.slice(0,x),w=R=0,O=P.length;R<O;R++)if(S.indexOf(y=P.charAt(R))<0){if(y=="."){if(R>w){w=O;continue}}else if(!I&&(P==P.toUpperCase()&&(P=P.toLowerCase())||P==P.toLowerCase()&&(P=P.toUpperCase()))){I=!0,R=-1,w=0;continue}return n(U,String(A),N,x)}N=!1,P=r(P,x,10,U.s),(w=P.indexOf("."))>-1?P=P.replace(".",""):w=P.length}for(R=0;P.charCodeAt(R)===48;R++);for(O=P.length;P.charCodeAt(--O)===48;);if(P=P.slice(R,++O)){if(O-=R,N&&L.DEBUG&&O>15&&(A>mf||A!==pr(A)))throw Error(hA+U.s*A);if((w=w-R-1)>p)U.c=U.e=null;else if(w<d)U.c=[U.e=0];else{if(U.e=w,U.c=[],R=(w+1)%ue,w<0&&(R+=ue),R<O){for(R&&U.c.push(+P.slice(0,R)),O-=ue;R<O;)U.c.push(+P.slice(R,R+=ue));R=ue-(P=P.slice(R)).length}else R-=O;for(;R--;P+="0");U.c.push(+P)}}else U.c=[U.e=0]}L.clone=EA,L.ROUND_UP=0,L.ROUND_DOWN=1,L.ROUND_CEIL=2,L.ROUND_FLOOR=3,L.ROUND_HALF_UP=4,L.ROUND_HALF_DOWN=5,L.ROUND_HALF_EVEN=6,L.ROUND_HALF_CEIL=7,L.ROUND_HALF_FLOOR=8,L.EUCLID=9,L.config=L.set=function(A){var x,S;if(A!=null)if(typeof A=="object"){if(A.hasOwnProperty(x="DECIMAL_PLACES")&&(S=A[x],We(S,0,vt,x),o=S),A.hasOwnProperty(x="ROUNDING_MODE")&&(S=A[x],We(S,0,8,x),a=S),A.hasOwnProperty(x="EXPONENTIAL_AT")&&(S=A[x],S&&S.pop?(We(S[0],-vt,0,x),We(S[1],0,vt,x),c=S[0],l=S[1]):(We(S,-vt,vt,x),c=-(l=S<0?-S:S))),A.hasOwnProperty(x="RANGE"))if(S=A[x],S&&S.pop)We(S[0],-vt,-1,x),We(S[1],1,vt,x),d=S[0],p=S[1];else if(We(S,-vt,vt,x),S)d=-(p=S<0?-S:S);else throw Error(Gt+x+" cannot be zero: "+S);if(A.hasOwnProperty(x="CRYPTO"))if(S=A[x],S===!!S)if(S)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))m=S;else throw m=!S,Error(Gt+"crypto unavailable");else m=S;else throw Error(Gt+x+" not true or false: "+S);if(A.hasOwnProperty(x="MODULO_MODE")&&(S=A[x],We(S,0,9,x),E=S),A.hasOwnProperty(x="POW_PRECISION")&&(S=A[x],We(S,0,vt,x),v=S),A.hasOwnProperty(x="FORMAT"))if(S=A[x],typeof S=="object")b=S;else throw Error(Gt+x+" not an object: "+S);if(A.hasOwnProperty(x="ALPHABET"))if(S=A[x],typeof S=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(S))C=S.slice(0,10)=="0123456789",k=S;else throw Error(Gt+x+" invalid: "+S)}else throw Error(Gt+"Object expected: "+A);return{DECIMAL_PLACES:o,ROUNDING_MODE:a,EXPONENTIAL_AT:[c,l],RANGE:[d,p],CRYPTO:m,MODULO_MODE:E,POW_PRECISION:v,FORMAT:b,ALPHABET:k}},L.isBigNumber=function(A){if(!A||A._isBigNumber!==!0)return!1;if(!L.DEBUG)return!0;var x,S,y=A.c,I=A.e,w=A.s;e:if({}.toString.call(y)=="[object Array]"){if((w===1||w===-1)&&I>=-vt&&I<=vt&&I===pr(I)){if(y[0]===0){if(I===0&&y.length===1)return!0;break e}if(x=(I+1)%ue,x<1&&(x+=ue),String(y[0]).length==x){for(x=0;x<y.length;x++)if(S=y[x],S<0||S>=Rr||S!==pr(S))break e;if(S!==0)return!0}}}else if(y===null&&I===null&&(w===null||w===1||w===-1))return!0;throw Error(Gt+"Invalid BigNumber: "+A)},L.maximum=L.max=function(){return G(arguments,-1)},L.minimum=L.min=function(){return G(arguments,1)},L.random=(function(){var A=9007199254740992,x=Math.random()*A&2097151?function(){return pr(Math.random()*A)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(S){var y,I,w,R,N,O=0,P=[],U=new L(s);if(S==null?S=o:We(S,0,vt),R=ff(S/ue),m)if(crypto.getRandomValues){for(y=crypto.getRandomValues(new Uint32Array(R*=2));O<R;)N=y[O]*131072+(y[O+1]>>>11),N>=9e15?(I=crypto.getRandomValues(new Uint32Array(2)),y[O]=I[0],y[O+1]=I[1]):(P.push(N%1e14),O+=2);O=R/2}else if(crypto.randomBytes){for(y=crypto.randomBytes(R*=7);O<R;)N=(y[O]&31)*281474976710656+y[O+1]*1099511627776+y[O+2]*4294967296+y[O+3]*16777216+(y[O+4]<<16)+(y[O+5]<<8)+y[O+6],N>=9e15?crypto.randomBytes(7).copy(y,O):(P.push(N%1e14),O+=7);O=R/7}else throw m=!1,Error(Gt+"crypto unavailable");if(!m)for(;O<R;)N=x(),N<9e15&&(P[O++]=N%1e14);for(R=P[--O],S%=ue,R&&S&&(N=hf[ue-S],P[O]=pr(R/N)*N);P[O]===0;P.pop(),O--);if(O<0)P=[w=0];else{for(w=-1;P[0]===0;P.splice(0,1),w-=ue);for(O=1,N=P[0];N>=10;N/=10,O++);O<ue&&(w-=ue-O)}return U.e=w,U.c=P,U}})(),L.sum=function(){for(var A=1,x=arguments,S=new L(x[0]);A<x.length;)S=S.plus(x[A++]);return S},r=(function(){var A="0123456789";function x(S,y,I,w){for(var R,N=[0],O,P=0,U=S.length;P<U;){for(O=N.length;O--;N[O]*=y);for(N[0]+=w.indexOf(S.charAt(P++)),R=0;R<N.length;R++)N[R]>I-1&&(N[R+1]==null&&(N[R+1]=0),N[R+1]+=N[R]/I|0,N[R]%=I)}return N.reverse()}return function(S,y,I,w,R){var N,O,P,U,K,W,J,de,ke=S.indexOf("."),He=o,fe=a;for(ke>=0&&(U=v,v=0,S=S.replace(".",""),de=new L(y),W=de.pow(S.length-ke),v=U,de.c=x(yn(dr(W.c),W.e,"0"),10,I,A),de.e=de.c.length),J=x(S,y,I,R?(N=k,A):(N=A,k)),P=U=J.length;J[--U]==0;J.pop());if(!J[0])return N.charAt(0);if(ke<0?--P:(W.c=J,W.e=P,W.s=w,W=e(W,de,He,fe,I),J=W.c,K=W.r,P=W.e),O=P+He+1,ke=J[O],U=I/2,K=K||O<0||J[O+1]!=null,K=fe<4?(ke!=null||K)&&(fe==0||fe==(W.s<0?3:2)):ke>U||ke==U&&(fe==4||K||fe==6&&J[O-1]&1||fe==(W.s<0?8:7)),O<1||!J[0])S=K?yn(N.charAt(1),-He,N.charAt(0)):N.charAt(0);else{if(J.length=O,K)for(--I;++J[--O]>I;)J[O]=0,O||(++P,J=[1].concat(J));for(U=J.length;!J[--U];);for(ke=0,S="";ke<=U;S+=N.charAt(J[ke++]));S=yn(S,P,N.charAt(0))}return S}})(),e=(function(){function A(y,I,w){var R,N,O,P,U=0,K=y.length,W=I%Bn,J=I/Bn|0;for(y=y.slice();K--;)O=y[K]%Bn,P=y[K]/Bn|0,R=J*O+P*W,N=W*O+R%Bn*Bn+U,U=(N/w|0)+(R/Bn|0)+J*P,y[K]=N%w;return U&&(y=[U].concat(y)),y}function x(y,I,w,R){var N,O;if(w!=R)O=w>R?1:-1;else for(N=O=0;N<w;N++)if(y[N]!=I[N]){O=y[N]>I[N]?1:-1;break}return O}function S(y,I,w,R){for(var N=0;w--;)y[w]-=N,N=y[w]<I[w]?1:0,y[w]=N*R+y[w]-I[w];for(;!y[0]&&y.length>1;y.splice(0,1));}return function(y,I,w,R,N){var O,P,U,K,W,J,de,ke,He,fe,Ne,at,Ri,gn,Oi,Nt,Gn,wt=y.s==I.s?1:-1,Ye=y.c,Me=I.c;if(!Ye||!Ye[0]||!Me||!Me[0])return new L(!y.s||!I.s||(Ye?Me&&Ye[0]==Me[0]:!Me)?NaN:Ye&&Ye[0]==0||!Me?wt*0:wt/0);for(ke=new L(wt),He=ke.c=[],P=y.e-I.e,wt=w+P+1,N||(N=Rr,P=fr(y.e/ue)-fr(I.e/ue),wt=wt/ue|0),U=0;Me[U]==(Ye[U]||0);U++);if(Me[U]>(Ye[U]||0)&&P--,wt<0)He.push(1),K=!0;else{for(gn=Ye.length,Nt=Me.length,U=0,wt+=2,W=pr(N/(Me[0]+1)),W>1&&(Me=A(Me,W,N),Ye=A(Ye,W,N),Nt=Me.length,gn=Ye.length),Ri=Nt,fe=Ye.slice(0,Nt),Ne=fe.length;Ne<Nt;fe[Ne++]=0);Gn=Me.slice(),Gn=[0].concat(Gn),Oi=Me[0],Me[1]>=N/2&&Oi++;do{if(W=0,O=x(Me,fe,Nt,Ne),O<0){if(at=fe[0],Nt!=Ne&&(at=at*N+(fe[1]||0)),W=pr(at/Oi),W>1)for(W>=N&&(W=N-1),J=A(Me,W,N),de=J.length,Ne=fe.length;x(J,fe,de,Ne)==1;)W--,S(J,Nt<de?Gn:Me,de,N),de=J.length,O=1;else W==0&&(O=W=1),J=Me.slice(),de=J.length;if(de<Ne&&(J=[0].concat(J)),S(fe,J,Ne,N),Ne=fe.length,O==-1)for(;x(Me,fe,Nt,Ne)<1;)W++,S(fe,Nt<Ne?Gn:Me,Ne,N),Ne=fe.length}else O===0&&(W++,fe=[0]);He[U++]=W,fe[0]?fe[Ne++]=Ye[Ri]||0:(fe=[Ye[Ri]],Ne=1)}while((Ri++<gn||fe[0]!=null)&&wt--);K=fe[0]!=null,He[0]||He.splice(0,1)}if(N==Rr){for(U=1,wt=He[0];wt>=10;wt/=10,U++);$(ke,w+(ke.e=U+P*ue-1)+1,R,K)}else ke.e=P,ke.r=+K;return ke}})();function B(A,x,S,y){var I,w,R,N,O;if(S==null?S=a:We(S,0,8),!A.c)return A.toString();if(I=A.c[0],R=A.e,x==null)O=dr(A.c),O=y==1||y==2&&(R<=c||R>=l)?Gl(O,R):yn(O,R,"0");else if(A=$(new L(A),x,S),w=A.e,O=dr(A.c),N=O.length,y==1||y==2&&(x<=w||w<=c)){for(;N<x;O+="0",N++);O=Gl(O,w)}else if(x-=R+(y===2&&w>R),O=yn(O,w,"0"),w+1>N){if(--x>0)for(O+=".";x--;O+="0");}else if(x+=w-N,x>0)for(w+1==N&&(O+=".");x--;O+="0");return A.s<0&&I?"-"+O:O}function G(A,x){for(var S,y,I=1,w=new L(A[0]);I<A.length;I++)y=new L(A[I]),(!y.s||(S=Si(w,y))===x||S===0&&w.s===x)&&(w=y);return w}function j(A,x,S){for(var y=1,I=x.length;!x[--I];x.pop());for(I=x[0];I>=10;I/=10,y++);return(S=y+S*ue-1)>p?A.c=A.e=null:S<d?A.c=[A.e=0]:(A.e=S,A.c=x),A}n=(function(){var A=/^(-?)0([xbo])(?=\w[\w.]*$)/i,x=/^([^.]+)\.$/,S=/^\.([^.]+)$/,y=/^-?(Infinity|NaN)$/,I=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(w,R,N,O){var P,U=N?R:R.replace(I,"");if(y.test(U))w.s=isNaN(U)?null:U<0?-1:1;else{if(!N&&(U=U.replace(A,function(K,W,J){return P=(J=J.toLowerCase())=="x"?16:J=="b"?2:8,!O||O==P?W:K}),O&&(P=O,U=U.replace(x,"$1").replace(S,"0.$1")),R!=U))return new L(U,P);if(L.DEBUG)throw Error(Gt+"Not a"+(O?" base "+O:"")+" number: "+R);w.s=null}w.c=w.e=null}})();function $(A,x,S,y){var I,w,R,N,O,P,U,K=A.c,W=hf;if(K){e:{for(I=1,N=K[0];N>=10;N/=10,I++);if(w=x-I,w<0)w+=ue,R=x,O=K[P=0],U=pr(O/W[I-R-1]%10);else if(P=ff((w+1)/ue),P>=K.length)if(y){for(;K.length<=P;K.push(0));O=U=0,I=1,w%=ue,R=w-ue+1}else break e;else{for(O=N=K[P],I=1;N>=10;N/=10,I++);w%=ue,R=w-ue+I,U=R<0?0:pr(O/W[I-R-1]%10)}if(y=y||x<0||K[P+1]!=null||(R<0?O:O%W[I-R-1]),y=S<4?(U||y)&&(S==0||S==(A.s<0?3:2)):U>5||U==5&&(S==4||y||S==6&&(w>0?R>0?O/W[I-R]:0:K[P-1])%10&1||S==(A.s<0?8:7)),x<1||!K[0])return K.length=0,y?(x-=A.e+1,K[0]=W[(ue-x%ue)%ue],A.e=-x||0):K[0]=A.e=0,A;if(w==0?(K.length=P,N=1,P--):(K.length=P+1,N=W[ue-w],K[P]=R>0?pr(O/W[I-R]%W[R])*N:0),y)for(;;)if(P==0){for(w=1,R=K[0];R>=10;R/=10,w++);for(R=K[0]+=N,N=1;R>=10;R/=10,N++);w!=N&&(A.e++,K[0]==Rr&&(K[0]=1));break}else{if(K[P]+=N,K[P]!=Rr)break;K[P--]=0,N=1}for(w=K.length;K[--w]===0;K.pop());}A.e>p?A.c=A.e=null:A.e<d&&(A.c=[A.e=0])}return A}function te(A){var x,S=A.e;return S===null?A.toString():(x=dr(A.c),x=S<=c||S>=l?Gl(x,S):yn(x,S,"0"),A.s<0?"-"+x:x)}return i.absoluteValue=i.abs=function(){var A=new L(this);return A.s<0&&(A.s=1),A},i.comparedTo=function(A,x){return Si(this,new L(A,x))},i.decimalPlaces=i.dp=function(A,x){var S,y,I,w=this;if(A!=null)return We(A,0,vt),x==null?x=a:We(x,0,8),$(new L(w),A+w.e+1,x);if(!(S=w.c))return null;if(y=((I=S.length-1)-fr(this.e/ue))*ue,I=S[I])for(;I%10==0;I/=10,y--);return y<0&&(y=0),y},i.dividedBy=i.div=function(A,x){return e(this,new L(A,x),o,a)},i.dividedToIntegerBy=i.idiv=function(A,x){return e(this,new L(A,x),0,1)},i.exponentiatedBy=i.pow=function(A,x){var S,y,I,w,R,N,O,P,U,K=this;if(A=new L(A),A.c&&!A.isInteger())throw Error(Gt+"Exponent not an integer: "+te(A));if(x!=null&&(x=new L(x)),N=A.e>14,!K.c||!K.c[0]||K.c[0]==1&&!K.e&&K.c.length==1||!A.c||!A.c[0])return U=new L(Math.pow(+te(K),N?A.s*(2-jl(A)):+te(A))),x?U.mod(x):U;if(O=A.s<0,x){if(x.c?!x.c[0]:!x.s)return new L(NaN);y=!O&&K.isInteger()&&x.isInteger(),y&&(K=K.mod(x))}else{if(A.e>9&&(K.e>0||K.e<-1||(K.e==0?K.c[0]>1||N&&K.c[1]>=24e7:K.c[0]<8e13||N&&K.c[0]<=9999975e7)))return w=K.s<0&&jl(A)?-0:0,K.e>-1&&(w=1/w),new L(O?1/w:w);v&&(w=ff(v/ue+2))}for(N?(S=new L(.5),O&&(A.s=1),P=jl(A)):(I=Math.abs(+te(A)),P=I%2),U=new L(s);;){if(P){if(U=U.times(K),!U.c)break;w?U.c.length>w&&(U.c.length=w):y&&(U=U.mod(x))}if(I){if(I=pr(I/2),I===0)break;P=I%2}else if(A=A.times(S),$(A,A.e+1,1),A.e>14)P=jl(A);else{if(I=+te(A),I===0)break;P=I%2}K=K.times(K),w?K.c&&K.c.length>w&&(K.c.length=w):y&&(K=K.mod(x))}return y?U:(O&&(U=s.div(U)),x?U.mod(x):w?$(U,v,a,R):U)},i.integerValue=function(A){var x=new L(this);return A==null?A=a:We(A,0,8),$(x,x.e+1,A)},i.isEqualTo=i.eq=function(A,x){return Si(this,new L(A,x))===0},i.isFinite=function(){return!!this.c},i.isGreaterThan=i.gt=function(A,x){return Si(this,new L(A,x))>0},i.isGreaterThanOrEqualTo=i.gte=function(A,x){return(x=Si(this,new L(A,x)))===1||x===0},i.isInteger=function(){return!!this.c&&fr(this.e/ue)>this.c.length-2},i.isLessThan=i.lt=function(A,x){return Si(this,new L(A,x))<0},i.isLessThanOrEqualTo=i.lte=function(A,x){return(x=Si(this,new L(A,x)))===-1||x===0},i.isNaN=function(){return!this.s},i.isNegative=function(){return this.s<0},i.isPositive=function(){return this.s>0},i.isZero=function(){return!!this.c&&this.c[0]==0},i.minus=function(A,x){var S,y,I,w,R=this,N=R.s;if(A=new L(A,x),x=A.s,!N||!x)return new L(NaN);if(N!=x)return A.s=-x,R.plus(A);var O=R.e/ue,P=A.e/ue,U=R.c,K=A.c;if(!O||!P){if(!U||!K)return U?(A.s=-x,A):new L(K?R:NaN);if(!U[0]||!K[0])return K[0]?(A.s=-x,A):new L(U[0]?R:a==3?-0:0)}if(O=fr(O),P=fr(P),U=U.slice(),N=O-P){for((w=N<0)?(N=-N,I=U):(P=O,I=K),I.reverse(),x=N;x--;I.push(0));I.reverse()}else for(y=(w=(N=U.length)<(x=K.length))?N:x,N=x=0;x<y;x++)if(U[x]!=K[x]){w=U[x]<K[x];break}if(w&&(I=U,U=K,K=I,A.s=-A.s),x=(y=K.length)-(S=U.length),x>0)for(;x--;U[S++]=0);for(x=Rr-1;y>N;){if(U[--y]<K[y]){for(S=y;S&&!U[--S];U[S]=x);--U[S],U[y]+=Rr}U[y]-=K[y]}for(;U[0]==0;U.splice(0,1),--P);return U[0]?j(A,U,P):(A.s=a==3?-1:1,A.c=[A.e=0],A)},i.modulo=i.mod=function(A,x){var S,y,I=this;return A=new L(A,x),!I.c||!A.s||A.c&&!A.c[0]?new L(NaN):!A.c||I.c&&!I.c[0]?new L(I):(E==9?(y=A.s,A.s=1,S=e(I,A,0,3),A.s=y,S.s*=y):S=e(I,A,0,E),A=I.minus(S.times(A)),!A.c[0]&&E==1&&(A.s=I.s),A)},i.multipliedBy=i.times=function(A,x){var S,y,I,w,R,N,O,P,U,K,W,J,de,ke,He,fe=this,Ne=fe.c,at=(A=new L(A,x)).c;if(!Ne||!at||!Ne[0]||!at[0])return!fe.s||!A.s||Ne&&!Ne[0]&&!at||at&&!at[0]&&!Ne?A.c=A.e=A.s=null:(A.s*=fe.s,!Ne||!at?A.c=A.e=null:(A.c=[0],A.e=0)),A;for(y=fr(fe.e/ue)+fr(A.e/ue),A.s*=fe.s,O=Ne.length,K=at.length,O<K&&(de=Ne,Ne=at,at=de,I=O,O=K,K=I),I=O+K,de=[];I--;de.push(0));for(ke=Rr,He=Bn,I=K;--I>=0;){for(S=0,W=at[I]%He,J=at[I]/He|0,R=O,w=I+R;w>I;)P=Ne[--R]%He,U=Ne[R]/He|0,N=J*P+U*W,P=W*P+N%He*He+de[w]+S,S=(P/ke|0)+(N/He|0)+J*U,de[w--]=P%ke;de[w]=S}return S?++y:de.splice(0,1),j(A,de,y)},i.negated=function(){var A=new L(this);return A.s=-A.s||null,A},i.plus=function(A,x){var S,y=this,I=y.s;if(A=new L(A,x),x=A.s,!I||!x)return new L(NaN);if(I!=x)return A.s=-x,y.minus(A);var w=y.e/ue,R=A.e/ue,N=y.c,O=A.c;if(!w||!R){if(!N||!O)return new L(I/0);if(!N[0]||!O[0])return O[0]?A:new L(N[0]?y:I*0)}if(w=fr(w),R=fr(R),N=N.slice(),I=w-R){for(I>0?(R=w,S=O):(I=-I,S=N),S.reverse();I--;S.push(0));S.reverse()}for(I=N.length,x=O.length,I-x<0&&(S=O,O=N,N=S,x=I),I=0;x;)I=(N[--x]=N[x]+O[x]+I)/Rr|0,N[x]=Rr===N[x]?0:N[x]%Rr;return I&&(N=[I].concat(N),++R),j(A,N,R)},i.precision=i.sd=function(A,x){var S,y,I,w=this;if(A!=null&&A!==!!A)return We(A,1,vt),x==null?x=a:We(x,0,8),$(new L(w),A,x);if(!(S=w.c))return null;if(I=S.length-1,y=I*ue+1,I=S[I]){for(;I%10==0;I/=10,y--);for(I=S[0];I>=10;I/=10,y++);}return A&&w.e+1>y&&(y=w.e+1),y},i.shiftedBy=function(A){return We(A,-mf,mf),this.times("1e"+A)},i.squareRoot=i.sqrt=function(){var A,x,S,y,I,w=this,R=w.c,N=w.s,O=w.e,P=o+4,U=new L("0.5");if(N!==1||!R||!R[0])return new L(!N||N<0&&(!R||R[0])?NaN:R?w:1/0);if(N=Math.sqrt(+te(w)),N==0||N==1/0?(x=dr(R),(x.length+O)%2==0&&(x+="0"),N=Math.sqrt(+x),O=fr((O+1)/2)-(O<0||O%2),N==1/0?x="5e"+O:(x=N.toExponential(),x=x.slice(0,x.indexOf("e")+1)+O),S=new L(x)):S=new L(N+""),S.c[0]){for(O=S.e,N=O+P,N<3&&(N=0);;)if(I=S,S=U.times(I.plus(e(w,I,P,1))),dr(I.c).slice(0,N)===(x=dr(S.c)).slice(0,N))if(S.e<O&&--N,x=x.slice(N-3,N+1),x=="9999"||!y&&x=="4999"){if(!y&&($(I,I.e+o+2,0),I.times(I).eq(w))){S=I;break}P+=4,N+=4,y=1}else{(!+x||!+x.slice(1)&&x.charAt(0)=="5")&&($(S,S.e+o+2,1),A=!S.times(S).eq(w));break}}return $(S,S.e+o+1,a,A)},i.toExponential=function(A,x){return A!=null&&(We(A,0,vt),A++),B(this,A,x,1)},i.toFixed=function(A,x){return A!=null&&(We(A,0,vt),A=A+this.e+1),B(this,A,x)},i.toFormat=function(A,x,S){var y,I=this;if(S==null)A!=null&&x&&typeof x=="object"?(S=x,x=null):A&&typeof A=="object"?(S=A,A=x=null):S=b;else if(typeof S!="object")throw Error(Gt+"Argument not an object: "+S);if(y=I.toFixed(A,x),I.c){var w,R=y.split("."),N=+S.groupSize,O=+S.secondaryGroupSize,P=S.groupSeparator||"",U=R[0],K=R[1],W=I.s<0,J=W?U.slice(1):U,de=J.length;if(O&&(w=N,N=O,O=w,de-=w),N>0&&de>0){for(w=de%N||N,U=J.substr(0,w);w<de;w+=N)U+=P+J.substr(w,N);O>0&&(U+=P+J.slice(w)),W&&(U="-"+U)}y=K?U+(S.decimalSeparator||"")+((O=+S.fractionGroupSize)?K.replace(new RegExp("\\d{"+O+"}\\B","g"),"$&"+(S.fractionGroupSeparator||"")):K):U}return(S.prefix||"")+y+(S.suffix||"")},i.toFraction=function(A){var x,S,y,I,w,R,N,O,P,U,K,W,J=this,de=J.c;if(A!=null&&(N=new L(A),!N.isInteger()&&(N.c||N.s!==1)||N.lt(s)))throw Error(Gt+"Argument "+(N.isInteger()?"out of range: ":"not an integer: ")+te(N));if(!de)return new L(J);for(x=new L(s),P=S=new L(s),y=O=new L(s),W=dr(de),w=x.e=W.length-J.e-1,x.c[0]=hf[(R=w%ue)<0?ue+R:R],A=!A||N.comparedTo(x)>0?w>0?x:P:N,R=p,p=1/0,N=new L(W),O.c[0]=0;U=e(N,x,0,1),I=S.plus(U.times(y)),I.comparedTo(A)!=1;)S=y,y=I,P=O.plus(U.times(I=P)),O=I,x=N.minus(U.times(I=x)),N=I;return I=e(A.minus(S),y,0,1),O=O.plus(I.times(P)),S=S.plus(I.times(y)),O.s=P.s=J.s,w=w*2,K=e(P,y,w,a).minus(J).abs().comparedTo(e(O,S,w,a).minus(J).abs())<1?[P,y]:[O,S],p=R,K},i.toNumber=function(){return+te(this)},i.toPrecision=function(A,x){return A!=null&&We(A,1,vt),B(this,A,x,2)},i.toString=function(A){var x,S=this,y=S.s,I=S.e;return I===null?y?(x="Infinity",y<0&&(x="-"+x)):x="NaN":(A==null?x=I<=c||I>=l?Gl(dr(S.c),I):yn(dr(S.c),I,"0"):A===10&&C?(S=$(new L(S),o+I+1,a),x=yn(dr(S.c),S.e,"0")):(We(A,2,k.length,"Base"),x=r(yn(dr(S.c),I,"0"),10,A,y,!0)),y<0&&S.c[0]&&(x="-"+x)),x},i.valueOf=i.toJSON=function(){return te(this)},i._isBigNumber=!0,i[Symbol.toStringTag]="BigNumber",i[Symbol.for("nodejs.util.inspect.custom")]=i.valueOf,t!=null&&L.set(t),L}function fr(t){var e=t|0;return t>0||t===e?e:e-1}function dr(t){for(var e,r,n=1,i=t.length,s=t[0]+"";n<i;){for(e=t[n++]+"",r=ue-e.length;r--;e="0"+e);s+=e}for(i=s.length;s.charCodeAt(--i)===48;);return s.slice(0,i+1||1)}function Si(t,e){var r,n,i=t.c,s=e.c,o=t.s,a=e.s,c=t.e,l=e.e;if(!o||!a)return null;if(r=i&&!i[0],n=s&&!s[0],r||n)return r?n?0:-a:o;if(o!=a)return o;if(r=o<0,n=c==l,!i||!s)return n?0:!i^r?1:-1;if(!n)return c>l^r?1:-1;for(a=(c=i.length)<(l=s.length)?c:l,o=0;o<a;o++)if(i[o]!=s[o])return i[o]>s[o]^r?1:-1;return c==l?0:c>l^r?1:-1}function We(t,e,r,n){if(t<e||t>r||t!==pr(t))throw Error(Gt+(n||"Argument")+(typeof t=="number"?t<e||t>r?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function jl(t){var e=t.c.length-1;return fr(t.e/ue)==e&&t.c[e]%2!=0}function Gl(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function yn(t,e,r){var n,i;if(e<0){for(i=r+".";++e;i+=r);t=i+t}else if(n=t.length,++e>n){for(i=r,e-=n;--e;i+=r);t+=i}else e<n&&(t=t.slice(0,e)+"."+t.slice(e));return t}var Yw=EA(),yA=Yw;var Xw=24,va=32,Qw=()=>typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.getRandomValues=="function"?()=>{let t=new Uint32Array(1);return globalThis.crypto.getRandomValues(t),t[0]/4294967296}:Math.random,yf=Qw(),Ef=(t=4,e=yf)=>{let r="";for(;r.length<t;)r=r+Math.floor(e()*36).toString(36);return r};function Zw(t){let e=new yA(0);for(let r of t.values())e=e.multipliedBy(256).plus(r);return e}var vA=(t="")=>{let e=new TextEncoder;return Zw(mA(e.encode(t))).toString(36).slice(1)},gA=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),eR=t=>gA[Math.floor(t()*gA.length)],tR=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=yf}={})=>{let r=Object.keys(t).toString(),n=r.length?r+Ef(va,e):Ef(va,e);return vA(n).substring(0,va)},rR=t=>()=>t++,nR=476782367,AA=({random:t=yf,counter:e=rR(Math.floor(t()*nR)),length:r=Xw,fingerprint:n=tR({random:t})}={})=>{if(r>va)throw new Error(`Length must be between 2 and ${va}. Received: ${r}`);return function(){let s=eR(t),o=Date.now().toString(36),a=e().toString(36),c=Ef(r,t),l=`${o+c+a+n}`;return`${s+vA(l).substring(1,r)}`}},At=iR(AA);function iR(t){let e;return()=>(e||(e=t()),e())}function Aa(t){if(typeof t=="object"&&t!==null&&"name"in t){let{name:e}=t;return typeof e=="string"?e:void 0}}function Pe(t){return Aa(t)==="ConditionalCheckFailedException"}var Ta=class{docClient;tableName;ttlGracePeriod;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||3600*1e3}generateChallengeId(){return At()}async get(e){try{let r=await this.docClient.send(new oR({TableName:this.tableName,Key:{[f.PK]:D.CHALLENGE_PK(e),[f.SK]:D.CHALLENGE_SK()}}));if(!r.Item)return g(null);let n=this.unmarshall(r.Item);return lf(ne(n.expiresAt))?g(null):g(n)}catch{return u(M.DatabaseQueryError({query:"get challenge"}))}}async create(e){try{let r=ae(),n=e.id||this.generateChallengeId(),i={...e,id:n,createdAt:z(r)},s=ne(e.expiresAt),o=Math.floor((s+this.ttlGracePeriod)/1e3);return await this.docClient.send(new aR({TableName:this.tableName,Item:this.marshall(i,o)})),g(i)}catch{return u(M.DatabaseQueryError({query:"create challenge"}))}}async update(e,r){try{let n=[],i={},s={};return r.method!==void 0&&(n.push("#method = :method"),i["#method"]=f.METHOD,s[":method"]=r.method),r.phase!==void 0&&(n.push("#phase = :phase"),i["#phase"]=f.PHASE,s[":phase"]=r.phase),r.codeHash!==void 0&&(n.push("#codeHash = :codeHash"),i["#codeHash"]=f.CODE_HASH,s[":codeHash"]=r.codeHash),r.status!==void 0&&(n.push("#challengeStatus = :challengeStatus"),i["#challengeStatus"]=f.CHALLENGE_STATUS,s[":challengeStatus"]=r.status),n.length===0?g(void 0):(await this.docClient.send(new TA({TableName:this.tableName,Key:{[f.PK]:D.CHALLENGE_PK(e),[f.SK]:D.CHALLENGE_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:i,ExpressionAttributeValues:s})),g(void 0))}catch{return u(M.DatabaseQueryError({query:"update challenge"}))}}async incrementAttempts(e,r){let n={":zero":0,":inc":1},i;r!==void 0&&(i="attribute_not_exists(#attempts) OR #attempts < :max",n[":max"]=r);try{let o=(await this.docClient.send(new TA({TableName:this.tableName,Key:{[f.PK]:D.CHALLENGE_PK(e),[f.SK]:D.CHALLENGE_SK()},UpdateExpression:"SET #attempts = if_not_exists(#attempts, :zero) + :inc",...i?{ConditionExpression:i}:{},ExpressionAttributeNames:{"#attempts":f.ATTEMPTS},ExpressionAttributeValues:n,ReturnValues:"UPDATED_NEW"}))).Attributes?.[f.ATTEMPTS]??0;return g(o)}catch(s){return Pe(s)?u(M.AttemptsExceeded()):u(M.DatabaseQueryError({query:"increment challenge attempts"}))}}async remove(e){try{return await this.docClient.send(new sR({TableName:this.tableName,Key:{[f.PK]:D.CHALLENGE_PK(e),[f.SK]:D.CHALLENGE_SK()},ConditionExpression:"attribute_exists(#pk)",ExpressionAttributeNames:{"#pk":f.PK}})),g(void 0)}catch(r){return Pe(r)?g(void 0):u(M.DatabaseQueryError({query:"remove challenge"}))}}marshall(e,r){let n={[f.PK]:D.CHALLENGE_PK(e.id),[f.SK]:D.CHALLENGE_SK(),[f.USER_ID]:e.userId,[f.PURPOSE]:e.purpose,[f.CHALLENGE_STATUS]:e.status,[f.EXPIRES_AT]:ne(e.expiresAt),[f.CREATED_AT]:ne(e.createdAt),[f.TTL]:r};return e.tenantId&&(n[f.TENANT_ID]=e.tenantId),e.phase&&(n[f.PHASE]=e.phase),e.allowedMethods&&e.allowedMethods.length>0&&(n[f.ALLOWED_METHODS]=e.allowedMethods),e.method&&(n[f.METHOD]=e.method),e.codeHash&&(n[f.CODE_HASH]=e.codeHash),e.attempts!==void 0&&(n[f.ATTEMPTS]=e.attempts),e.maxAttempts!==void 0&&(n[f.MAX_ATTEMPTS]=e.maxAttempts),e.identityType&&(n[f.IDENTITY_TYPE]=e.identityType),e.identityValue&&(n[f.IDENTITY_VALUE]=e.identityValue),e.deviceLabel&&(n[f.DEVICE_LABEL]=e.deviceLabel),e.country&&(n[f.COUNTRY]=e.country),e.city&&(n[f.CITY]=e.city),e.metadata&&(n[f.METADATA]=e.metadata),e.flowKey&&(n[f.FLOW_KEY]=e.flowKey),n}unmarshall(e){let n={id:le.challengeIdFromPK(e[f.PK]),userId:e[f.USER_ID],purpose:e[f.PURPOSE],status:e[f.CHALLENGE_STATUS],expiresAt:z(e[f.EXPIRES_AT]),createdAt:z(e[f.CREATED_AT])};return e[f.TENANT_ID]&&(n.tenantId=e[f.TENANT_ID]),e[f.PHASE]&&(n.phase=e[f.PHASE]),e[f.ALLOWED_METHODS]&&(n.allowedMethods=e[f.ALLOWED_METHODS]),e[f.METHOD]&&(n.method=e[f.METHOD]),e[f.CODE_HASH]&&(n.codeHash=e[f.CODE_HASH]),e[f.ATTEMPTS]!==void 0&&(n.attempts=e[f.ATTEMPTS]),e[f.MAX_ATTEMPTS]!==void 0&&(n.maxAttempts=e[f.MAX_ATTEMPTS]),e[f.IDENTITY_TYPE]&&(n.identityType=e[f.IDENTITY_TYPE]),e[f.IDENTITY_VALUE]&&(n.identityValue=e[f.IDENTITY_VALUE]),e[f.DEVICE_LABEL]&&(n.deviceLabel=e[f.DEVICE_LABEL]),e[f.COUNTRY]&&(n.country=e[f.COUNTRY]),e[f.CITY]&&(n.city=e[f.CITY]),e[f.METADATA]&&(n.metadata=e[f.METADATA]),e[f.FLOW_KEY]&&(n.flowKey=e[f.FLOW_KEY]),n}};import{BatchGetCommand as cR,DeleteCommand as lR,GetCommand as uR,PutCommand as dR,QueryCommand as $l,UpdateCommand as pR}from"@aws-sdk/lib-dynamodb";var Ia=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateCredentialId(){return At()}async get(e){try{let r=await this.docClient.send(new uR({TableName:this.tableName,Key:{[f.PK]:D.CREDENTIAL_PK(e),[f.SK]:D.CREDENTIAL_SK()}}));return r.Item?g(this.unmarshall(r.Item)):g(null)}catch{return u(M.DatabaseQueryError({query:"get credential"}))}}async getByUserIdAndType(e,r){try{let n=await this.docClient.send(new $l({TableName:this.tableName,IndexName:Se.USER_CREDENTIALS,KeyConditionExpression:`${f.CREDENTIAL_USER_PK} = :userPk AND begins_with(${f.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":D.USER_PK(e),":typePrefix":D.CREDENTIAL_TYPE_PREFIX(r)},Limit:1}));if(!n.Items||n.Items.length===0)return g(null);let i=n.Items[0];if(!i)return g(null);let s=le.credentialId(i[f.PK]);return this.get(s)}catch{return u(M.DatabaseQueryError({query:"get credential by user and type"}))}}async getByUserId(e){try{let r=await this.docClient.send(new $l({TableName:this.tableName,IndexName:Se.USER_CREDENTIALS,KeyConditionExpression:`${f.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":D.USER_PK(e)}}));if(!r.Items||r.Items.length===0)return g([]);let n=r.Items.map(o=>le.credentialId(o[f.PK])),i=await this.batchGet(n);if(i.ok===!1)return u(i.errors,i.meta);if(!i.data)return g([]);let s=i.data.filter(o=>o!==null);return g(s)}catch{return u(M.DatabaseQueryError({query:"get credentials by user"}))}}async create(e){try{let r=ae(),n=this.generateCredentialId(),i={revokedAt:null,lastUsedAt:null,...e,id:n,createdAt:new Date(r),updatedAt:new Date(r)};return await this.docClient.send(new dR({TableName:this.tableName,Item:this.marshall(i),ConditionExpression:`attribute_not_exists(${f.PK})`})),g(i)}catch(r){return Pe(r)?u(M.UniqueConstraintViolation({field:"credential"})):u(M.DatabaseQueryError({query:"create credential"}))}}async update(e,r){try{let n=ae(),i=[],s={},o={};return i.push(`#${f.UPDATED_AT} = :updatedAt`),s[`#${f.UPDATED_AT}`]=f.UPDATED_AT,o[":updatedAt"]=n,r.value!==void 0&&(i.push(`#${f.CREDENTIAL_VALUE} = :value`),s[`#${f.CREDENTIAL_VALUE}`]=f.CREDENTIAL_VALUE,o[":value"]=r.value),r.data!==void 0&&(i.push(`#${f.METADATA} = :data`),s[`#${f.METADATA}`]=f.METADATA,o[":data"]=r.data),r.revokedAt!==void 0&&(i.push(`#${f.REVOKED_AT} = :revokedAt`),s[`#${f.REVOKED_AT}`]=f.REVOKED_AT,o[":revokedAt"]=r.revokedAt?ne(r.revokedAt):null),r.lastUsedAt!==void 0&&(i.push(`#${f.LAST_USED_AT} = :lastUsedAt`),s[`#${f.LAST_USED_AT}`]=f.LAST_USED_AT,o[":lastUsedAt"]=r.lastUsedAt?ne(r.lastUsedAt):null),await this.docClient.send(new pR({TableName:this.tableName,Key:{[f.PK]:D.CREDENTIAL_PK(e),[f.SK]:D.CREDENTIAL_SK()},UpdateExpression:`SET ${i.join(", ")}`,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:`attribute_exists(${f.PK})`})),g(void 0)}catch(n){return Pe(n)?u(M.NotFound({entity:"credential",id:e})):u(M.DatabaseQueryError({query:"update credential"}))}}async remove(e){try{return await this.docClient.send(new lR({TableName:this.tableName,Key:{[f.PK]:D.CREDENTIAL_PK(e),[f.SK]:D.CREDENTIAL_SK()},ConditionExpression:`attribute_exists(${f.PK})`})),g(void 0)}catch(r){return Pe(r)?u(M.NotFound({entity:"credential",id:e})):u(M.DatabaseQueryError({query:"delete credential"}))}}async hasType(e,r){try{let n=await this.docClient.send(new $l({TableName:this.tableName,IndexName:Se.USER_CREDENTIALS,KeyConditionExpression:`${f.CREDENTIAL_USER_PK} = :userPk AND begins_with(${f.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":D.USER_PK(e),":typePrefix":D.CREDENTIAL_TYPE_PREFIX(r)},Select:"COUNT",Limit:1}));return g((n.Count||0)>0)}catch{return u(M.DatabaseQueryError({query:"check credential type"}))}}async countByUserId(e){try{let r=await this.docClient.send(new $l({TableName:this.tableName,IndexName:Se.USER_CREDENTIALS,KeyConditionExpression:`${f.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":D.USER_PK(e)},Select:"COUNT"}));return g(r.Count||0)}catch{return u(M.DatabaseQueryError({query:"count credentials"}))}}async batchGet(e){if(e.length===0)return g([]);try{let r=[];for(let i=0;i<e.length;i+=100)r.push(e.slice(i,i+100));let n=[];for(let i of r){let o=(await this.docClient.send(new cR({RequestItems:{[this.tableName]:{Keys:i.map(c=>({[f.PK]:D.CREDENTIAL_PK(c),[f.SK]:D.CREDENTIAL_SK()}))}}}))).Responses?.[this.tableName]||[],a=new Map;for(let c of o){let l=this.unmarshall(c);a.set(l.id,l)}for(let c of i)n.push(a.get(c)||null)}return g(n)}catch{return u(M.DatabaseQueryError({query:"batch get credentials"}))}}marshall(e){let r={[f.PK]:D.CREDENTIAL_PK(e.id),[f.SK]:D.CREDENTIAL_SK(),[f.CREDENTIAL_USER_PK]:D.USER_PK(e.userId),[f.CREDENTIAL_USER_SK]:D.CREDENTIAL_USER_SK(e.type,e.id),[f.USER_ID]:e.userId,[f.CREDENTIAL_VALUE]:e.value,[f.METADATA]:e.data,[f.REVOKED_AT]:e.revokedAt?ne(e.revokedAt):null,[f.CREATED_AT]:ne(e.createdAt),[f.UPDATED_AT]:ne(e.updatedAt)};return e.lastUsedAt&&(r[f.LAST_USED_AT]=ne(e.lastUsedAt)),r}unmarshall(e){let r=le.credentialId(e[f.PK]),n=le.credentialTypeFromUserSK(e[f.CREDENTIAL_USER_SK]);return{id:r,userId:e[f.USER_ID],type:n,value:e[f.CREDENTIAL_VALUE],data:e[f.METADATA]||{},revokedAt:Ht(e[f.REVOKED_AT]),createdAt:z(e[f.CREATED_AT]),updatedAt:z(e[f.UPDATED_AT]),lastUsedAt:Ht(e[f.LAST_USED_AT])}}};import{BatchGetCommand as fR,DeleteCommand as mR,GetCommand as hR,PutCommand as ER,QueryCommand as yR,UpdateCommand as gf}from"@aws-sdk/lib-dynamodb";function vf(t){return{failedAttempts:t.failedAttempts,lastFailedAt:Nr(t.lastFailedAt),lockedUntil:Nr(t.lockedUntil)}}function IA(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t))e[r]={failedAttempts:n.failedAttempts??0,lastFailedAt:Ht(n.lastFailedAt),lockedUntil:Ht(n.lockedUntil)};return e}function _A(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t))n&&(e[r]=vf(n));return e}var _a=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async get(e,r){try{let n=await this.docClient.send(new hR({TableName:this.tableName,Key:{[f.PK]:D.IDENTITY_PK(e,r),[f.SK]:D.IDENTITY_SK()}}));if(!n.Item)return g(null);let i=this.unmarshall(n.Item);return g(i)}catch(n){return console.error("[DynamoDB] identities.get error:",n),u(M.DatabaseQueryError({query:"get identity"}))}}async getByUserId(e){try{let r=await this.docClient.send(new yR({TableName:this.tableName,IndexName:Se.USER_IDENTITIES,KeyConditionExpression:`${f.IDENTITY_USER_PK} = :pk`,ExpressionAttributeValues:{":pk":D.USER_INDEX_PK(e)}})),n=[];for(let i of r.Items||[]){let s=this.unmarshall(i);s!==null&&n.push(s)}return g(n)}catch{return u(M.DatabaseQueryError({query:"get identities by userId"}))}}async create(e){try{let r=ae(),n={...e,createdAt:z(r),updatedAt:z(r)};return await this.docClient.send(new ER({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:"attribute_not_exists(PK)"})),g(n)}catch(r){return Pe(r)?u(M.UniqueConstraintViolation({field:"identity"})):u(M.DatabaseQueryError({query:"create identity"}))}}async update(e,r,n){try{let i=[],s=[],o={},a={};if(n.loginEnabled!==void 0&&(i.push("#loginEnabled = :loginEnabled"),o["#loginEnabled"]=f.LOGIN_ENABLED,a[":loginEnabled"]=n.loginEnabled),n.verifiedAt!==void 0){let l=Nr(n.verifiedAt);l===null?(s.push("#verifiedAt"),o["#verifiedAt"]=f.VERIFIED_AT):(i.push("#verifiedAt = :verifiedAt"),o["#verifiedAt"]=f.VERIFIED_AT,a[":verifiedAt"]=l)}n.guards!==void 0&&(i.push("#guards = :guards"),o["#guards"]=f.GUARDS,a[":guards"]=_A(n.guards)),n.pendingVerification!==void 0&&(o["#pendingVerification"]=f.PENDING_VERIFICATION,n.pendingVerification===null?s.push("#pendingVerification"):(i.push("#pendingVerification = :pendingVerification"),a[":pendingVerification"]=Ft({...n.pendingVerification,expiresAt:ne(n.pendingVerification.expiresAt),resendAvailableAt:Nr(n.pendingVerification.resendAvailableAt)}))),i.push("#updatedAt = :updatedAt"),o["#updatedAt"]=f.UPDATED_AT,a[":updatedAt"]=ae();let c=[];return i.length>0&&c.push(`SET ${i.join(", ")}`),s.length>0&&c.push(`REMOVE ${s.join(", ")}`),await this.docClient.send(new gf({TableName:this.tableName,Key:{[f.PK]:D.IDENTITY_PK(e,r),[f.SK]:D.IDENTITY_SK()},UpdateExpression:c.join(" "),ExpressionAttributeNames:o,ExpressionAttributeValues:a})),g(void 0)}catch{return u(M.DatabaseQueryError({query:"update identity"}))}}async remove(e,r){try{return await this.docClient.send(new mR({TableName:this.tableName,Key:{[f.PK]:D.IDENTITY_PK(e,r),[f.SK]:D.IDENTITY_SK()}})),g(void 0)}catch{return u(M.DatabaseQueryError({query:"remove identity"}))}}async updateGuard(e,r,n,i){let s={[f.PK]:D.IDENTITY_PK(e,r),[f.SK]:D.IDENTITY_SK()};try{return await this.docClient.send(new gf({TableName:this.tableName,Key:s,UpdateExpression:"SET #guards.#guardKey = :guard, #updatedAt = :updatedAt",ConditionExpression:"attribute_exists(#guards)",ExpressionAttributeNames:{"#guards":f.GUARDS,"#guardKey":n,"#updatedAt":f.UPDATED_AT},ExpressionAttributeValues:{":guard":vf(i),":updatedAt":ae()}})),g(void 0)}catch(o){if(Pe(o))try{return await this.docClient.send(new gf({TableName:this.tableName,Key:s,UpdateExpression:"SET #guards = :guards, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#guards":f.GUARDS,"#updatedAt":f.UPDATED_AT},ExpressionAttributeValues:{":guards":{[n]:vf(i)},":updatedAt":ae()}})),g(void 0)}catch{return u(M.DatabaseQueryError({query:"update guard"}))}return u(M.DatabaseQueryError({query:"update guard"}))}}async batchGet(e){try{if(e.length===0)return g([]);let n=(await this.docClient.send(new fR({RequestItems:{[this.tableName]:{Keys:e.map(({type:o,value:a})=>({[f.PK]:D.IDENTITY_PK(o,a),[f.SK]:D.IDENTITY_SK()}))}}}))).Responses?.[this.tableName]||[],i=new Map;for(let o of n){let a=this.unmarshall(o);if(a!==null){let c=`${a.type}#${a.value}`;i.set(c,a)}}let s=e.map(({type:o,value:a})=>{let c=`${o}#${a}`;return i.get(c)||null});return g(s)}catch{return u(M.DatabaseQueryError({query:"batch get identities"}))}}marshall(e){let r={[f.PK]:D.IDENTITY_PK(e.type,e.value),[f.SK]:D.IDENTITY_SK(),[f.IDENTITY_USER_PK]:D.USER_INDEX_PK(e.userId),[f.IDENTITY_USER_SK]:D.USER_INDEX_SK(e.type,e.value),[f.USER_ID]:e.userId,[f.LOGIN_ENABLED]:e.loginEnabled,[f.CREATED_AT]:ne(e.createdAt),[f.UPDATED_AT]:ne(e.updatedAt)},n=Nr(e.verifiedAt);return n!==null&&(r[f.VERIFIED_AT]=n),r[f.GUARDS]=_A(e.guards),e.pendingVerification&&(r[f.PENDING_VERIFICATION]=Ft({...e.pendingVerification,expiresAt:ne(e.pendingVerification.expiresAt),resendAvailableAt:Nr(e.pendingVerification.resendAvailableAt)})),r}unmarshall(e){let r=le.identityPKInfo(e[f.PK]);if(!r){let n=e[f.IDENTITY_USER_SK]?le.userIndexSKInfo(e[f.IDENTITY_USER_SK]):null;return n?{type:n.type,value:n.value,userId:e[f.USER_ID],loginEnabled:e[f.LOGIN_ENABLED],verifiedAt:Ht(e[f.VERIFIED_AT]),guards:IA(e[f.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[f.PENDING_VERIFICATION]),createdAt:z(e[f.CREATED_AT]),updatedAt:z(e[f.UPDATED_AT])}:(console.warn("Invalid identity item format, skipping:",{PK:e[f.PK],GSI1SK:e[f.IDENTITY_USER_SK]}),null)}return{type:r.type,value:r.value,userId:e[f.USER_ID],loginEnabled:e[f.LOGIN_ENABLED],verifiedAt:Ht(e[f.VERIFIED_AT]),guards:IA(e[f.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[f.PENDING_VERIFICATION]),createdAt:z(e[f.CREATED_AT]),updatedAt:z(e[f.UPDATED_AT])}}unmarshallPendingVerification(e){if(!e||typeof e!="object")return null;let r=e;return{challengeId:r.challengeId,purpose:r.purpose,channel:r.channel,expiresAt:z(r.expiresAt),resendAvailableAt:Ht(r.resendAvailableAt)}}};import{TransactWriteCommand as gR}from"@aws-sdk/lib-dynamodb";var xa=class{docClient;tableName;ttlGracePeriod;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||3600*1e3}async createEmailVerificationRegistration(e){try{let r=ae(),n=At(),i=ne(e.challenge.expiresAt),s=Math.floor((i+this.ttlGracePeriod)/1e3);return await this.docClient.send(new gR({TransactItems:[this.putItem(this.marshallProfile(e,r)),this.putItem(this.marshallUserAuth(e,r)),this.putItem(this.marshallIdentity(e,r)),this.putItem(this.marshallCredential(e,n,r)),this.putItem(this.marshallChallenge(e,r,s))]})),g(void 0)}catch(r){return Aa(r)==="TransactionCanceledException"||Pe(r)?u(M.UniqueConstraintViolation({field:"registration"})):u(M.DatabaseQueryError({query:"create email verification registration transaction"}))}}putItem(e){return{Put:{TableName:this.tableName,Item:Ft(e),ConditionExpression:`attribute_not_exists(${f.PK})`}}}marshallProfile(e,r){let n=e.profile.status,i={[f.PK]:D.USER_PK(e.profile.id),[f.SK]:D.USER_PROFILE_SK(),userStatus:n,[f.CREATED_AT]:r,[f.UPDATED_AT]:r,[f.USER_STATUS_PK]:Ae.USER_STATUS_PK(n),[f.USER_STATUS_SK]:Ae.USER_STATUS_SK(e.profile.id)};return e.profile.contactEmail&&(i.contactEmail=e.profile.contactEmail),e.profile.contactPhone&&(i.contactPhone=e.profile.contactPhone),e.profile.username&&(i.username=e.profile.username),e.profile.displayName&&(i.displayName=e.profile.displayName),e.profile.givenName&&(i.givenName=e.profile.givenName),e.profile.familyName&&(i.familyName=e.profile.familyName),e.profile.avatarUrl&&(i.avatarUrl=e.profile.avatarUrl),e.profile.locale&&(i.locale=e.profile.locale),e.profile.metadata&&(i.metadata=JSON.stringify(e.profile.metadata)),i}marshallUserAuth(e,r){return{[f.PK]:D.USER_PK(e.userAuth.userId),[f.SK]:D.USER_AUTH_SK(),userStatus:e.userAuth.userStatus,mfaRequired:e.userAuth.mfaRequired,mfaMethods:e.userAuth.mfaMethods,[f.CREATED_AT]:r,[f.UPDATED_AT]:r}}marshallIdentity(e,r){let n=e.identity,i={[f.PK]:D.IDENTITY_PK(n.type,n.value),[f.SK]:D.IDENTITY_SK(),[f.IDENTITY_USER_PK]:D.USER_INDEX_PK(n.userId),[f.IDENTITY_USER_SK]:D.USER_INDEX_SK(n.type,n.value),[f.USER_ID]:n.userId,[f.LOGIN_ENABLED]:n.loginEnabled,[f.CREATED_AT]:r,[f.UPDATED_AT]:r,[f.PENDING_VERIFICATION]:Ft({...n.pendingVerification,expiresAt:ne(n.pendingVerification.expiresAt),resendAvailableAt:Nr(n.pendingVerification.resendAvailableAt)})},s=Nr(n.verifiedAt);return s!==null&&(i[f.VERIFIED_AT]=s),i[f.GUARDS]=n.guards??{},i}marshallCredential(e,r,n){let i=e.credential,s={[f.PK]:D.CREDENTIAL_PK(r),[f.SK]:D.CREDENTIAL_SK(),[f.CREDENTIAL_USER_PK]:D.USER_PK(i.userId),[f.CREDENTIAL_USER_SK]:D.CREDENTIAL_USER_SK(i.type,r),[f.USER_ID]:i.userId,[f.CREDENTIAL_VALUE]:i.value,[f.METADATA]:i.data,[f.REVOKED_AT]:i.revokedAt?ne(i.revokedAt):null,[f.CREATED_AT]:n,[f.UPDATED_AT]:n};return i.lastUsedAt&&(s[f.LAST_USED_AT]=ne(i.lastUsedAt)),s}marshallChallenge(e,r,n){let i=e.challenge,s={[f.PK]:D.CHALLENGE_PK(i.id),[f.SK]:D.CHALLENGE_SK(),[f.USER_ID]:i.userId,[f.PURPOSE]:i.purpose,[f.CHALLENGE_STATUS]:i.status,[f.EXPIRES_AT]:ne(i.expiresAt),[f.CREATED_AT]:r,[f.TTL]:n};return i.tenantId&&(s[f.TENANT_ID]=i.tenantId),i.phase&&(s[f.PHASE]=i.phase),i.allowedMethods&&i.allowedMethods.length>0&&(s[f.ALLOWED_METHODS]=i.allowedMethods),i.method&&(s[f.METHOD]=i.method),i.codeHash&&(s[f.CODE_HASH]=i.codeHash),i.attempts!==void 0&&(s[f.ATTEMPTS]=i.attempts),i.maxAttempts!==void 0&&(s[f.MAX_ATTEMPTS]=i.maxAttempts),i.identityType&&(s[f.IDENTITY_TYPE]=i.identityType),i.identityValue&&(s[f.IDENTITY_VALUE]=i.identityValue),i.deviceLabel&&(s[f.DEVICE_LABEL]=i.deviceLabel),i.country&&(s[f.COUNTRY]=i.country),i.city&&(s[f.CITY]=i.city),i.metadata&&(s[f.METADATA]=i.metadata),i.flowKey&&(s[f.FLOW_KEY]=i.flowKey),s}};import{DynamoDBClient as TR}from"@aws-sdk/client-dynamodb";import{DynamoDBDocumentClient as IR,GetCommand as SA,PutCommand as _R,QueryCommand as ba,UpdateCommand as js}from"@aws-sdk/lib-dynamodb";import{BatchGetCommand as vR}from"@aws-sdk/lib-dynamodb";var xA=100,bA=5;function AR(t){return new Promise(e=>setTimeout(e,t))}async function qs(t,e,r){if(r.length===0)return[];let n=[];for(let i=0;i<r.length;i+=xA){let s=r.slice(i,i+xA),o=0;for(;s.length>0;){let a=await t.send(new vR({RequestItems:{[e]:{Keys:s}}})),c=a.Responses?.[e];c&&n.push(...c);let l=a.UnprocessedKeys?.[e]?.Keys;if(!l||l.length===0)break;if(o+=1,o>bA)throw new Error(`BatchGet left ${l.length} unprocessed keys after ${bA} retries`);s=l,await AR(2**o*25)}}return n}var Sa=class{docClient;tableName;ttlGracePeriod;constructor(e){let r=e.client||new TR({});this.docClient=e.docClient||IR.from(r),this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||10080*60*1e3}generateSessionId(){return At()}generateTokenId(){return At()}async get(e){try{let r=await this.docClient.send(new SA({TableName:this.tableName,Key:{[f.PK]:D.SESSION_PK(e),[f.SK]:D.SESSION_SK()}}));return r.Item?g(this.unmarshall(r.Item)):g(null)}catch{return u(M.DatabaseQueryError({query:"get session"}))}}async create(e){try{let r=ae(),n=e.id||this.generateSessionId(),i=e.tokenId||this.generateTokenId(),s={...e,id:n,tokenId:i,revokedAt:null,createdAt:new Date(r),lastUsedAt:new Date(r)},o=ya(ne(e.expiresAt)+this.ttlGracePeriod),a=ql.sessionSK(r,n);return await this.docClient.send(new _R({TableName:this.tableName,Item:this.marshall(s,o,a)})),g(s)}catch{return u(M.DatabaseQueryError({query:"create session"}))}}async update(e,r){try{let n=[],i={},s={};if(r.tokenId!==void 0&&(n.push(`#${f.TOKEN_ID} = :tokenId`),i[`#${f.TOKEN_ID}`]=f.TOKEN_ID,s[":tokenId"]=r.tokenId),r.expiresAt!==void 0){n.push(`#${f.EXPIRES_AT} = :expiresAt`),i[`#${f.EXPIRES_AT}`]=f.EXPIRES_AT,s[":expiresAt"]=ne(r.expiresAt);let o=ya(ne(r.expiresAt)+this.ttlGracePeriod);n.push(`#${f.TTL} = :ttl`),i[`#${f.TTL}`]=f.TTL,s[":ttl"]=o}return r.lastUsedAt!==void 0&&(n.push(`#${f.LAST_USED_AT} = :lastUsedAt`),i[`#${f.LAST_USED_AT}`]=f.LAST_USED_AT,s[":lastUsedAt"]=ne(r.lastUsedAt)),r.metadata!==void 0&&(n.push(`#${f.METADATA} = :metadata`),i[`#${f.METADATA}`]=f.METADATA,s[":metadata"]=r.metadata),r.previousTokenId!==void 0&&(n.push(`#${f.PREVIOUS_TOKEN_ID} = :previousTokenId`),i[`#${f.PREVIOUS_TOKEN_ID}`]=f.PREVIOUS_TOKEN_ID,s[":previousTokenId"]=r.previousTokenId),r.rotatedAt!==void 0&&(n.push(`#${f.ROTATED_AT} = :rotatedAt`),i[`#${f.ROTATED_AT}`]=f.ROTATED_AT,s[":rotatedAt"]=r.rotatedAt),n.length===0?g():(await this.docClient.send(new js({TableName:this.tableName,Key:{[f.PK]:D.SESSION_PK(e),[f.SK]:D.SESSION_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:i,ExpressionAttributeValues:s})),g())}catch{return u(M.DatabaseQueryError({query:"update session"}))}}async rotateToken(e,r,n){try{let i=ya(ne(n.expiresAt)+this.ttlGracePeriod);return await this.docClient.send(new js({TableName:this.tableName,Key:{[f.PK]:D.SESSION_PK(e),[f.SK]:D.SESSION_SK()},UpdateExpression:`SET #${f.TOKEN_ID} = :tokenId, #${f.PREVIOUS_TOKEN_ID} = :previousTokenId, #${f.ROTATED_AT} = :rotatedAt, #${f.EXPIRES_AT} = :expiresAt, #${f.LAST_USED_AT} = :lastUsedAt, #${f.TTL} = :ttl`,ConditionExpression:`#${f.TOKEN_ID} = :expectedCurrentTokenId`,ExpressionAttributeNames:{[`#${f.TOKEN_ID}`]:f.TOKEN_ID,[`#${f.PREVIOUS_TOKEN_ID}`]:f.PREVIOUS_TOKEN_ID,[`#${f.ROTATED_AT}`]:f.ROTATED_AT,[`#${f.EXPIRES_AT}`]:f.EXPIRES_AT,[`#${f.LAST_USED_AT}`]:f.LAST_USED_AT,[`#${f.TTL}`]:f.TTL},ExpressionAttributeValues:{":tokenId":n.tokenId,":previousTokenId":n.previousTokenId,":rotatedAt":n.rotatedAt,":expiresAt":ne(n.expiresAt),":lastUsedAt":ne(n.lastUsedAt),":ttl":i,":expectedCurrentTokenId":r}})),g(!0)}catch(i){return Pe(i)?g(!1):u(M.DatabaseQueryError({query:"rotate session token"}))}}async switchTenant(e,r){try{let n=[`#${f.TENANT_ID} = :tenantId`,`#${f.TOKEN_ID} = :tokenId`,`#${f.LAST_USED_AT} = :lastUsedAt`],i=[],s={[`#${f.TENANT_ID}`]:f.TENANT_ID,[`#${f.TOKEN_ID}`]:f.TOKEN_ID,[`#${f.LAST_USED_AT}`]:f.LAST_USED_AT},o={":tenantId":r.tenantId,":tokenId":r.tokenId,":lastUsedAt":ae()};s[`#${f.TENANT_TYPE}`]=f.TENANT_TYPE,r.tenantType!==void 0?(n.push(`#${f.TENANT_TYPE} = :tenantType`),o[":tenantType"]=r.tenantType):i.push(`#${f.TENANT_TYPE}`),s[`#${f.PERM}`]=f.PERM,r.perms!==void 0?(n.push(`#${f.PERM} = :perms`),o[":perms"]=JSON.stringify(r.perms)):i.push(`#${f.PERM}`),s[`#${f.ROLES}`]=f.ROLES,r.roles!==void 0?(n.push(`#${f.ROLES} = :roles`),o[":roles"]=r.roles):i.push(`#${f.ROLES}`),s["#revokedAt"]=f.REVOKED_AT;let a=`SET ${n.join(", ")}${i.length>0?` REMOVE ${i.join(", ")}`:""}`;return await this.docClient.send(new js({TableName:this.tableName,Key:{[f.PK]:D.SESSION_PK(e),[f.SK]:D.SESSION_SK()},UpdateExpression:a,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:`attribute_exists(${f.PK}) AND attribute_not_exists(#revokedAt)`})),g()}catch(n){return Pe(n)?u(M.DatabaseQueryError({query:"switch tenant - session not found or revoked"})):u(M.DatabaseQueryError({query:"switch tenant"}))}}async revoke(e){try{return await this.docClient.send(new js({TableName:this.tableName,Key:{[f.PK]:D.SESSION_PK(e),[f.SK]:D.SESSION_SK()},UpdateExpression:`SET #${f.REVOKED_AT} = :revokedAt REMOVE #${f.ACTIVE_SESSION_PK}, #${f.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${f.REVOKED_AT}`]:f.REVOKED_AT,[`#${f.ACTIVE_SESSION_PK}`]:f.ACTIVE_SESSION_PK,[`#${f.ACTIVE_SESSION_SK}`]:f.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":ne(new Date)},ConditionExpression:`attribute_exists(${f.PK})`})),g()}catch(r){return Pe(r)?g():u(M.DatabaseQueryError({query:"revoke session"}))}}async revokeByIdAndUserId(e,r){try{return await this.docClient.send(new js({TableName:this.tableName,Key:{[f.PK]:D.SESSION_PK(e),[f.SK]:D.SESSION_SK()},UpdateExpression:`SET #${f.REVOKED_AT} = :revokedAt REMOVE #${f.ACTIVE_SESSION_PK}, #${f.ACTIVE_SESSION_SK}`,ConditionExpression:`#${f.USER_ID} = :userId AND attribute_not_exists(#${f.REVOKED_AT})`,ExpressionAttributeNames:{[`#${f.REVOKED_AT}`]:f.REVOKED_AT,[`#${f.USER_ID}`]:f.USER_ID,[`#${f.ACTIVE_SESSION_PK}`]:f.ACTIVE_SESSION_PK,[`#${f.ACTIVE_SESSION_SK}`]:f.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":ne(new Date),":userId":r}})),g()}catch(n){return Pe(n)?g():u(M.DatabaseQueryError({query:"revoke session by user"}))}}async findByUserId(e,r){try{let n=Math.min(r?.limit||50,100),i;if(r?.cursor)try{i=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))}catch{return u(M.DatabaseQueryError({query:"invalid pagination cursor"}))}let s=await this.docClient.send(new ba({TableName:this.tableName,IndexName:Se.USER_SESSIONS,KeyConditionExpression:`${f.USER_SESSION_PK} = :userPk`,ExpressionAttributeValues:{":userPk":D.USER_PK(e)},Limit:n,ExclusiveStartKey:i,ScanIndexForward:!1}));if(!s.Items||s.Items.length===0){let E={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!r?.cursor,cursor:null};return g([],{pagination:E})}let a=s.Items.map(E=>le.sessionId(E[f.PK])).map(E=>({[f.PK]:D.SESSION_PK(E),[f.SK]:D.SESSION_SK()})),l=(await qs(this.docClient,this.tableName,a)).map(E=>this.unmarshall(E)),d=!!s.LastEvaluatedKey,p=d?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null,m={type:"cursor",limit:n,count:l.length,hasNext:d,hasPrev:!!r?.cursor,cursor:p};return g(l,{pagination:m})}catch{return u(M.DatabaseQueryError({query:"find sessions by user"}))}}async findActiveByUserId(e,r){try{let n=Math.min(r?.limit||50,100),i;if(r?.cursor)try{i=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))}catch{return u(M.DatabaseQueryError({query:"invalid pagination cursor"}))}let s=await this.docClient.send(new ba({TableName:this.tableName,IndexName:Se.ACTIVE_SESSIONS,KeyConditionExpression:`${f.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Ae.ACTIVE_SESSION_PK(e)},Limit:n,ExclusiveStartKey:i,ScanIndexForward:!1}));if(!s.Items||s.Items.length===0){let E={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!r?.cursor,cursor:null};return g([],{pagination:E})}let a=s.Items.map(E=>le.sessionId(E[f.PK])).map(E=>({[f.PK]:D.SESSION_PK(E),[f.SK]:D.SESSION_SK()})),l=(await qs(this.docClient,this.tableName,a)).map(E=>this.unmarshall(E)),d=!!s.LastEvaluatedKey,p=d?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null,m={type:"cursor",limit:n,count:l.length,hasNext:d,hasPrev:!!r?.cursor,cursor:p};return g(l,{pagination:m})}catch{return u(M.DatabaseQueryError({query:"find active sessions by user"}))}}async getActiveSessionsForLimit(e){try{let r=await this.docClient.send(new ba({TableName:this.tableName,IndexName:Se.ACTIVE_SESSIONS,KeyConditionExpression:`${f.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Ae.ACTIVE_SESSION_PK(e)},ScanIndexForward:!0}));if(!r.Items||r.Items.length===0)return g([]);let n=r.Items.map(i=>{let s=le.sessionId(i[f.PK]),o=ql.extractCreatedAt(i[f.ACTIVE_SESSION_SK]);return{id:s,createdAt:new Date(o)}});return g(n)}catch{return u(M.DatabaseQueryError({query:"get active sessions for limit"}))}}async revokeSessionsByIds(e,r){if(e.length===0)return 0;let n=ne(new Date),i=await Promise.allSettled(e.map(o=>this.docClient.send(new js({TableName:this.tableName,Key:{[f.PK]:D.SESSION_PK(o),[f.SK]:D.SESSION_SK()},UpdateExpression:`SET #${f.REVOKED_AT} = :revokedAt REMOVE #${f.ACTIVE_SESSION_PK}, #${f.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${f.REVOKED_AT}`]:f.REVOKED_AT,[`#${f.ACTIVE_SESSION_PK}`]:f.ACTIVE_SESSION_PK,[`#${f.ACTIVE_SESSION_SK}`]:f.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":n}})))),s=0;for(let o of i)o.status==="fulfilled"?s+=1:console.error(`[session-repo] ${r}: session revoke failed (may remain active):`,{name:Aa(o.reason)});return s}async revokeAllByUserId(e,r){try{let n=await this.docClient.send(new ba({TableName:this.tableName,IndexName:Se.ACTIVE_SESSIONS,KeyConditionExpression:`${f.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Ae.ACTIVE_SESSION_PK(e)}}));if(!n.Items||n.Items.length===0)return g(0);let i=n.Items.map(o=>le.sessionId(o[f.PK])).filter(o=>!r||o!==r),s=await this.revokeSessionsByIds(i,"revokeAllByUserId");return g(s)}catch{return u(M.DatabaseQueryError({query:"revoke all sessions by user"}))}}async revokeBatch(e){try{let r=await this.revokeSessionsByIds(e,"revokeBatch");return g(r)}catch{return u(M.DatabaseQueryError({query:"revoke batch sessions"}))}}async countByUserId(e){try{let r=await this.docClient.send(new ba({TableName:this.tableName,IndexName:Se.ACTIVE_SESSIONS,KeyConditionExpression:`${f.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Ae.ACTIVE_SESSION_PK(e)},Select:"COUNT"}));return g(r.Count||0)}catch{return u(M.DatabaseQueryError({query:"count active sessions by user"}))}}async isTokenActive(e,r){try{let n=await this.docClient.send(new SA({TableName:this.tableName,Key:{[f.PK]:D.SESSION_PK(r),[f.SK]:D.SESSION_SK()},ProjectionExpression:`${f.TOKEN_ID}, ${f.REVOKED_AT}, ${f.EXPIRES_AT}`}));if(!n.Item)return g(!1);let i=n.Item,s=i[f.TOKEN_ID]===e&&!i[f.REVOKED_AT]&&z(i[f.EXPIRES_AT])>new Date;return g(s)}catch{return u(M.DatabaseQueryError({query:"check token active"}))}}marshall(e,r,n){let i={[f.PK]:D.SESSION_PK(e.id),[f.SK]:D.SESSION_SK(),[f.USER_SESSION_PK]:D.USER_PK(e.userId),[f.USER_SESSION_SK]:n,...!e.revokedAt&&{[f.ACTIVE_SESSION_PK]:Ae.ACTIVE_SESSION_PK(e.userId),[f.ACTIVE_SESSION_SK]:n},[f.USER_ID]:e.userId,[f.TOKEN_ID]:e.tokenId,[f.EXPIRES_AT]:ne(e.expiresAt),[f.CREATED_AT]:ne(e.createdAt),[f.LAST_USED_AT]:ne(e.lastUsedAt),[f.TTL]:r};return e.tenantId&&(i[f.TENANT_ID]=e.tenantId),e.tenantType&&(i[f.TENANT_TYPE]=e.tenantType),e.perms!==void 0&&(i[f.PERM]=JSON.stringify(e.perms)),e.roles!==void 0&&(i[f.ROLES]=e.roles),e.deviceLabel&&(i[f.DEVICE_LABEL]=e.deviceLabel),e.country&&(i[f.COUNTRY]=e.country),e.city&&(i[f.CITY]=e.city),e.metadata&&(i[f.METADATA]=e.metadata),e.revokedAt&&(i[f.REVOKED_AT]=ne(e.revokedAt)),e.previousTokenId&&(i[f.PREVIOUS_TOKEN_ID]=e.previousTokenId),e.rotatedAt!==void 0&&(i[f.ROTATED_AT]=e.rotatedAt),i}unmarshall(e){let n={id:le.sessionId(e[f.PK]),userId:e[f.USER_ID],tokenId:e[f.TOKEN_ID],expiresAt:z(e[f.EXPIRES_AT]),createdAt:z(e[f.CREATED_AT]),lastUsedAt:z(e[f.LAST_USED_AT]),revokedAt:e[f.REVOKED_AT]?z(e[f.REVOKED_AT]):null};return e[f.TENANT_ID]&&(n.tenantId=e[f.TENANT_ID]),e[f.TENANT_TYPE]&&(n.tenantType=e[f.TENANT_TYPE]),e[f.PERM]!==void 0&&(n.perms=JSON.parse(e[f.PERM])),e[f.ROLES]!==void 0&&(n.roles=e[f.ROLES]),e[f.DEVICE_LABEL]&&(n.deviceLabel=e[f.DEVICE_LABEL]),e[f.COUNTRY]&&(n.country=e[f.COUNTRY]),e[f.CITY]&&(n.city=e[f.CITY]),e[f.METADATA]&&(n.metadata=e[f.METADATA]),e[f.PREVIOUS_TOKEN_ID]&&(n.previousTokenId=e[f.PREVIOUS_TOKEN_ID]),e[f.ROTATED_AT]!==void 0&&(n.rotatedAt=e[f.ROTATED_AT]),n}};import{QueryCommand as xR}from"@aws-sdk/lib-dynamodb";var Na=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={"#pk":f.INVITE_TENANT_PK},s={":pk":Ae.INVITE_TENANT_PK(e)},o={TableName:this.tableName,IndexName:Se.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:i,ExpressionAttributeValues:s,ScanIndexForward:!1,Limit:n};r?.cursor&&(o.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))),r?.status&&(o.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",i["#sk"]=f.INVITE_TENANT_SK,s[":statusPrefix"]=Ae.INVITE_TENANT_STATUS_PREFIX(r.status));let a=await this.docClient.send(new xR(o)),c=(a.Items||[]).map(p=>this.toListItem(p)),l=!!a.LastEvaluatedKey,d=l?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return mr(c,{limit:n,hasNext:l,cursor:d,prevCursor:r?.cursor??null})}catch(n){return console.error("[DynamoDBTenantInviteQuery.listByTenant] Error:",n instanceof Error?n.message:n),u(M.DatabaseQueryError({query:"listByTenant query"}))}}toListItem(e){let r=le.inviteId(e.PK),n={id:e.invitedById};e.invitedByInfo&&(e.invitedByInfo.name&&(n.name=e.invitedByInfo.name),e.invitedByInfo.email&&(n.email=e.invitedByInfo.email),e.invitedByInfo.jobTitle&&(n.jobTitle=e.invitedByInfo.jobTitle));let i={id:r,tenantId:e.tenantId,invitedBy:n,status:e.inviteStatus,expiresAt:z(e.expiresAt),createdAt:z(e.createdAt),updatedAt:z(e.updatedAt)};return e.inviteeUserId&&(i.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(i.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(i.inviteePhone=e.inviteePhone),e.roles!==void 0&&(i.roles=e.roles),e.perms!==void 0&&(i.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(i.authPerm=e.authPerm),e.displayName&&(i.displayName=e.displayName),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.jobTitle&&(i.jobTitle=e.jobTitle),e.acceptedAt&&(i.acceptedAt=z(e.acceptedAt)),e.declinedAt&&(i.declinedAt=z(e.declinedAt)),e.revokedAt&&(i.revokedAt=z(e.revokedAt)),i}};import{GetCommand as NA,PutCommand as bR,QueryCommand as qn,UpdateCommand as SR}from"@aws-sdk/lib-dynamodb";var NR=10080*60*1e3,wa=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}mapItemToEntity(e){let n={id:le.inviteId(e.PK),tenantId:e.tenantId,invitedById:e.invitedById,tenantType:e.tenantType,status:e.inviteStatus,inviteToken:e.inviteToken,expiresAt:z(e.expiresAt),createdAt:z(e.createdAt),updatedAt:z(e.updatedAt)};e.inviteeUserId&&(n.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(n.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(n.inviteePhone=e.inviteePhone),e.roles!==void 0&&(n.roles=e.roles);let i=e[f.PERM];return i!==void 0&&(n.perms=JSON.parse(i)),e.authPerm!==void 0&&(n.authPerm=e.authPerm),e.displayName&&(n.displayName=e.displayName),e.givenName&&(n.givenName=e.givenName),e.familyName&&(n.familyName=e.familyName),e.jobTitle&&(n.jobTitle=e.jobTitle),e.acceptedAt&&(n.acceptedAt=z(e.acceptedAt)),e.declinedAt&&(n.declinedAt=z(e.declinedAt)),e.revokedAt&&(n.revokedAt=z(e.revokedAt)),n}generateInviteId(){return At()}async getById(e){try{let r=await this.docClient.send(new NA({TableName:this.tableName,Key:{PK:D.INVITE_PK(e),SK:D.INVITE_SK()}}));return r.Item?g(this.mapItemToEntity(r.Item)):g(null)}catch{return u(M.DatabaseQueryError({query:"getById invite"}))}}async getByToken(e){try{let n=(await this.docClient.send(new qn({TableName:this.tableName,IndexName:Se.INVITE_TOKEN,KeyConditionExpression:"#inviteTokenGsi = :token",ExpressionAttributeNames:{"#inviteTokenGsi":f.INVITE_TOKEN_GSI},ExpressionAttributeValues:{":token":e},Limit:1}))).Items;if(!n||n.length===0)return g(null);let i=n[0],s=await this.docClient.send(new NA({TableName:this.tableName,Key:{PK:i.PK,SK:i.SK}}));return s.Item?g(this.mapItemToEntity(s.Item)):g(null)}catch{return u(M.DatabaseQueryError({query:"getByToken invite"}))}}async create(e){try{let r=ae(),n=ne(e.expiresAt),i=Math.floor((n+NR)/1e3),s={PK:D.INVITE_PK(e.id),SK:D.INVITE_SK(),[f.TENANT_ID]:e.tenantId,tenantType:e.tenantType,[f.INVITED_BY_ID]:e.invitedById,[f.INVITE_STATUS]:e.status,[f.INVITE_TOKEN]:e.inviteToken,[f.EXPIRES_AT]:n,[f.CREATED_AT]:r,[f.UPDATED_AT]:r,[f.TTL]:i,[f.INVITE_TENANT_PK]:Ae.INVITE_TENANT_PK(e.tenantId),[f.INVITE_TENANT_SK]:Ae.INVITE_TENANT_SK(e.status,r,e.id),[f.INVITE_TOKEN_GSI]:e.inviteToken},o={};e.invitedByName&&(o.name=e.invitedByName),e.invitedByEmail&&(o.email=e.invitedByEmail),e.invitedByJobTitle&&(o.jobTitle=e.invitedByJobTitle),Object.keys(o).length>0&&(s[f.INVITED_BY_INFO]=o),e.inviteeUserId&&(s[f.INVITEE_USER_ID]=e.inviteeUserId),e.inviteeEmail&&(s[f.INVITEE_EMAIL]=e.inviteeEmail,s[f.INVITEE_EMAIL_GSI]=e.inviteeEmail,s[f.INVITEE_EMAIL_TENANT_SK]=`${ce.TENANT}${e.tenantId}`),e.inviteePhone&&(s[f.INVITEE_PHONE]=e.inviteePhone,s[f.INVITEE_PHONE_GSI]=e.inviteePhone,s[f.INVITEE_PHONE_TENANT_SK]=`${ce.TENANT}${e.tenantId}`),e.roles!==void 0&&(s[f.ROLES]=e.roles),e.perms!==void 0&&(s[f.PERM]=JSON.stringify(e.perms)),e.authPerm!==void 0&&(s[f.AUTH_PERM]=e.authPerm),e.displayName&&(s[f.DISPLAY_NAME]=e.displayName),e.givenName&&(s.givenName=e.givenName),e.familyName&&(s.familyName=e.familyName),e.jobTitle&&(s.jobTitle=e.jobTitle),await this.docClient.send(new bR({TableName:this.tableName,Item:s,ConditionExpression:"attribute_not_exists(PK)"}));let a={id:e.id,tenantId:e.tenantId,invitedById:e.invitedById,tenantType:e.tenantType,status:e.status,inviteToken:e.inviteToken,expiresAt:e.expiresAt,createdAt:z(r),updatedAt:z(r)};return e.inviteeUserId&&(a.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(a.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(a.inviteePhone=e.inviteePhone),e.roles!==void 0&&(a.roles=e.roles),e.perms!==void 0&&(a.perms=e.perms),e.authPerm!==void 0&&(a.authPerm=e.authPerm),e.displayName&&(a.displayName=e.displayName),e.givenName&&(a.givenName=e.givenName),e.familyName&&(a.familyName=e.familyName),e.jobTitle&&(a.jobTitle=e.jobTitle),g(a)}catch(r){return r.name==="ConditionalCheckFailedException"?u(M.UniqueConstraintViolation({field:"invite id"})):u(M.UnknownError({message:r.message}))}}async updateStatus(e,r){try{let n=ae(),i=["#inviteStatus = :inviteStatus","#inviteTenantSk = :inviteTenantSk","#updatedAt = :updatedAt"],s={"#inviteStatus":f.INVITE_STATUS,"#inviteTenantSk":f.INVITE_TENANT_SK,"#updatedAt":f.UPDATED_AT},o={":inviteStatus":r.status,":inviteTenantSk":Ae.INVITE_TENANT_SK(r.status,n,e),":updatedAt":n};r.acceptedAt&&(i.push("#acceptedAt = :acceptedAt"),s["#acceptedAt"]=f.ACCEPTED_AT,o[":acceptedAt"]=ne(r.acceptedAt)),r.declinedAt&&(i.push("#declinedAt = :declinedAt"),s["#declinedAt"]=f.DECLINED_AT,o[":declinedAt"]=ne(r.declinedAt)),r.revokedAt&&(i.push("#revokedAt = :revokedAt"),s["#revokedAt"]=f.REVOKED_AT,o[":revokedAt"]=ne(r.revokedAt));let a=[];r.status!=="pending"&&(a.push("#inviteTokenGsi","#inviteeEmailGsi","#inviteeEmailTenantSk","#inviteePhoneGsi","#inviteePhoneTenantSk"),s["#inviteTokenGsi"]=f.INVITE_TOKEN_GSI,s["#inviteeEmailGsi"]=f.INVITEE_EMAIL_GSI,s["#inviteeEmailTenantSk"]=f.INVITEE_EMAIL_TENANT_SK,s["#inviteePhoneGsi"]=f.INVITEE_PHONE_GSI,s["#inviteePhoneTenantSk"]=f.INVITEE_PHONE_TENANT_SK);let c=`SET ${i.join(", ")}`;return a.length>0&&(c+=` REMOVE ${a.join(", ")}`),await this.docClient.send(new SR({TableName:this.tableName,Key:{PK:D.INVITE_PK(e),SK:D.INVITE_SK()},UpdateExpression:c,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:"attribute_exists(PK)"})),g(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?u(M.NotFound({entity:"TenantInvite",id:e})):u(M.UnknownError({message:n.message}))}}async findByTenantAndEmail(e,r){try{let i=(await this.docClient.send(new qn({TableName:this.tableName,IndexName:Se.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email AND #inviteeEmailTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteeEmailGsi":f.INVITEE_EMAIL_GSI,"#inviteeEmailTenantSk":f.INVITEE_EMAIL_TENANT_SK},ExpressionAttributeValues:{":email":r,":tenantSk":`${ce.TENANT}${e}`},Limit:1}))).Items;return!i||i.length===0?g(null):g(this.mapItemToEntity(i[0]))}catch{return u(M.DatabaseQueryError({query:"findByTenantAndEmail"}))}}async findByTenantAndPhone(e,r){try{let i=(await this.docClient.send(new qn({TableName:this.tableName,IndexName:Se.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone AND #inviteePhoneTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteePhoneGsi":f.INVITEE_PHONE_GSI,"#inviteePhoneTenantSk":f.INVITEE_PHONE_TENANT_SK},ExpressionAttributeValues:{":phone":r,":tenantSk":`${ce.TENANT}${e}`},Limit:1}))).Items;return!i||i.length===0?g(null):g(this.mapItemToEntity(i[0]))}catch{return u(M.DatabaseQueryError({query:"findByTenantAndPhone"}))}}async findByTenantAndUserId(e,r){try{let i=(await this.docClient.send(new qn({TableName:this.tableName,IndexName:Se.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",FilterExpression:"#inviteeUserId = :userId",ExpressionAttributeNames:{"#pk":f.INVITE_TENANT_PK,"#sk":f.INVITE_TENANT_SK,"#inviteeUserId":f.INVITEE_USER_ID},ExpressionAttributeValues:{":pk":Ae.INVITE_TENANT_PK(e),":pendingPrefix":Ae.INVITE_TENANT_STATUS_PREFIX("pending"),":userId":r},Limit:1}))).Items;return!i||i.length===0?g(null):g(this.mapItemToEntity(i[0]))}catch{return u(M.DatabaseQueryError({query:"findByTenantAndUserId"}))}}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={"#pk":f.INVITE_TENANT_PK},s={":pk":Ae.INVITE_TENANT_PK(e)},o={TableName:this.tableName,IndexName:Se.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:i,ExpressionAttributeValues:s,ScanIndexForward:!1,Limit:n};r?.cursor&&(o.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))),r?.status&&(o.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",i["#sk"]=f.INVITE_TENANT_SK,s[":statusPrefix"]=Ae.INVITE_TENANT_STATUS_PREFIX(r.status));let a=await this.docClient.send(new qn(o)),c=(a.Items||[]).map(p=>this.mapItemToEntity(p)),l=!!a.LastEvaluatedKey,d=l?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return mr(c,{limit:n,hasNext:l,cursor:d,prevCursor:r?.cursor??null})}catch{return u(M.DatabaseQueryError({query:"listByTenant"}))}}async findPendingByEmail(e){try{let r=ae(),i=(await this.docClient.send(new qn({TableName:this.tableName,IndexName:Se.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteeEmailGsi":f.INVITEE_EMAIL_GSI,"#expiresAt":f.EXPIRES_AT},ExpressionAttributeValues:{":email":e,":now":r}}))).Items||[];if(i.length===0)return g([]);let s=i.map(c=>({PK:c.PK,SK:c.SK})),a=(await qs(this.docClient,this.tableName,s)).map(c=>this.mapItemToEntity(c));return g(a)}catch{return u(M.DatabaseQueryError({query:"findPendingByEmail"}))}}async findPendingByPhone(e){try{let r=ae(),i=(await this.docClient.send(new qn({TableName:this.tableName,IndexName:Se.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteePhoneGsi":f.INVITEE_PHONE_GSI,"#expiresAt":f.EXPIRES_AT},ExpressionAttributeValues:{":phone":e,":now":r}}))).Items||[];if(i.length===0)return g([]);let s=i.map(c=>({PK:c.PK,SK:c.SK})),a=(await qs(this.docClient,this.tableName,s)).map(c=>this.mapItemToEntity(c));return g(a)}catch{return u(M.DatabaseQueryError({query:"findPendingByPhone"}))}}async countPendingByTenant(e){try{let r=await this.docClient.send(new qn({TableName:this.tableName,IndexName:Se.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",ExpressionAttributeNames:{"#pk":f.INVITE_TENANT_PK,"#sk":f.INVITE_TENANT_SK},ExpressionAttributeValues:{":pk":Ae.INVITE_TENANT_PK(e),":pendingPrefix":Ae.INVITE_TENANT_STATUS_PREFIX("pending")},Select:"COUNT"}));return g(r.Count??0)}catch{return u(M.DatabaseQueryError({query:"countPendingByTenant"}))}}async expireOld(e){return g(0)}};import{QueryCommand as wR}from"@aws-sdk/lib-dynamodb";var Ra=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={TableName:this.tableName,KeyConditionExpression:"PK = :pk",ExpressionAttributeValues:{":pk":D.TENANT_MEMBER_PK(e)}};r?.cursor&&(i.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let o=(await this.docClient.send(new wR(i))).Items||[],a=[],c=new Map;for(let E of o){let v=E.SK;if(v.startsWith(Ve.TENANT_PROFILE)){let b=le.tenantProfileUserId(v);c.set(b,E)}else v.startsWith(ce.USER)&&a.push(E)}a.sort((E,v)=>v.createdAt-E.createdAt);let l=a.slice(0,n),d=a.length>n,p=l.map(E=>{let v=le.tenantMemberUserId(E.SK),b=c.get(v);return this.toListItem(E,e,v,b)}),m=d&&l.length>0?Buffer.from(JSON.stringify({PK:l[l.length-1].PK,SK:l[l.length-1].SK})).toString("base64url"):null;return mr(p,{limit:n,hasNext:d,cursor:m,prevCursor:r?.cursor??null})}catch{return u(M.DatabaseQueryError({query:"listByTenant query"}))}}toListItem(e,r,n,i){let s={tenantId:r,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:z(e.createdAt),updatedAt:z(e.updatedAt)};if(e.roles!==void 0&&(s.roles=e.roles),e.perms!==void 0&&(s.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(s.authPerm=e.authPerm),i){let o={tenantId:r,userId:n,createdAt:z(i.createdAt),updatedAt:z(i.updatedAt)};i.contactEmail&&(o.contactEmail=i.contactEmail),i.contactPhone&&(o.contactPhone=i.contactPhone),i.displayName&&(o.displayName=i.displayName),i.displayNameSource&&(o.displayNameSource=i.displayNameSource),i.givenName&&(o.givenName=i.givenName),i.familyName&&(o.familyName=i.familyName),i.avatarUrl&&(o.avatarUrl=i.avatarUrl),i.locale&&(o.locale=i.locale),i.jobTitle&&(o.jobTitle=i.jobTitle),i.bio&&(o.bio=i.bio),i.metadata&&(o.metadata=JSON.parse(i.metadata)),s.tenantProfile=o}return s}};import{DeleteCommand as RR,DynamoDBDocumentClient as OR,GetCommand as wA,PutCommand as kR,QueryCommand as CR,TransactWriteCommand as DR,UpdateCommand as RA}from"@aws-sdk/lib-dynamodb";var Oa=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=OR.from(e)}mapItemToEntity(e){let r=le.tenantId(e.PK),n=le.tenantMemberUserId(e.SK),i={tenantId:r,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:z(e.createdAt),updatedAt:z(e.updatedAt)};return e.roles!==void 0&&(i.roles=e.roles),e.perms!==void 0&&(i.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(i.authPerm=e.authPerm),i}async get(e,r){try{let n=await this.docClient.send(new wA({TableName:this.tableName,Key:{PK:D.TENANT_MEMBER_PK(e),SK:D.TENANT_MEMBER_SK(r)}}));if(!n.Item)return g(null);let i=this.mapItemToEntity(n.Item);return g(i)}catch{return u(M.DatabaseQueryError({query:"get"}))}}async create(e){try{let r=ae(),n=e.isOwner?void 0:e.authPerm,i=Ft({PK:D.TENANT_MEMBER_PK(e.tenantId),SK:D.TENANT_MEMBER_SK(e.userId),userStatus:e.status,roles:e.roles,perms:e.perms!==void 0?JSON.stringify(e.perms):void 0,authPerm:n,isOwner:e.isOwner,createdAt:r,updatedAt:r,userTenantPk:Ae.USER_TENANT_PK(e.userId),userTenantSk:Ae.USER_TENANT_SK(e.tenantType??"org",e.parentTenantId,r,e.tenantId),parentTenantId:e.parentTenantId});return e.isOwner?await this.docClient.send(new DR({TransactItems:[{Put:{TableName:this.tableName,Item:{PK:D.TENANT_MEMBER_PK(e.tenantId),SK:D.TENANT_OWNER_MARKER_SK(),createdAt:r},ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}},{Put:{TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}}]})):await this.docClient.send(new kR({TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),g(void 0)}catch(r){return r.name==="TransactionCanceledException"?r.CancellationReasons?.[0]?.Code==="ConditionalCheckFailed"?u(M.UniqueConstraintViolation({field:"tenant owner"})):u(M.UniqueConstraintViolation({field:"tenant member"})):r.name==="ConditionalCheckFailedException"?u(M.UniqueConstraintViolation({field:"tenant member"})):u(M.UnknownError({message:r.message}))}}async updatePermissions(e,r,n){try{let i={...n,updatedAt:ae()},{UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=wr(i);return await this.docClient.send(new RA({TableName:this.tableName,Key:{PK:D.TENANT_MEMBER_PK(e),SK:D.TENANT_MEMBER_SK(r)},UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),g(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?u(M.NotFound({entity:"TenantMember",id:`${e}:${r}`})):u(M.UnknownError({message:i.message}))}}async updateStatus(e,r,n){try{return await this.docClient.send(new RA({TableName:this.tableName,Key:{PK:D.TENANT_MEMBER_PK(e),SK:D.TENANT_MEMBER_SK(r)},UpdateExpression:"SET #userStatus = :userStatus, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#userStatus":"userStatus","#updatedAt":"updatedAt"},ExpressionAttributeValues:{":userStatus":n,":updatedAt":ae()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),g(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?u(M.NotFound({entity:"TenantMember",id:`${e}:${r}`})):u(M.UnknownError({message:i.message}))}}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":D.TENANT_MEMBER_PK(e),":skPrefix":ce.USER},Limit:n};r?.cursor&&(i.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let s=await this.docClient.send(new CR(i)),o=(s.Items||[]).map(l=>this.mapItemToEntity(l)),a=!!s.LastEvaluatedKey,c=a?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null;return mr(o,{limit:n,hasNext:a,cursor:c,prevCursor:r?.cursor??null})}catch{return u(M.DatabaseQueryError({query:"listByTenant"}))}}async hasOwner(e){try{let r=await this.docClient.send(new wA({TableName:this.tableName,Key:{PK:D.TENANT_MEMBER_PK(e),SK:D.TENANT_OWNER_MARKER_SK()}}));return g(!!r.Item)}catch{return u(M.DatabaseQueryError({query:"hasOwner"}))}}async remove(e,r){try{return await this.docClient.send(new RR({TableName:this.tableName,Key:{PK:D.TENANT_MEMBER_PK(e),SK:D.TENANT_MEMBER_SK(r)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),g(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?u(M.NotFound({entity:"TenantMember",id:`${e}:${r}`})):u(M.UnknownError({message:n.message}))}}};import{BatchGetCommand as PR,QueryCommand as UR}from"@aws-sdk/lib-dynamodb";var ka=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByUser(e,r){try{let n=Math.min(r?.limit??50,100),i=r?.tenantType??Zt.DEFAULT,s=r?.parentTenantId,o=s?`${i}#${s}#`:`${i}#`,a={TableName:this.tableName,IndexName:Se.USER_TENANTS,KeyConditionExpression:"userTenantPk = :pk AND begins_with(userTenantSk, :skPrefix)",ExpressionAttributeValues:{":pk":Ae.USER_TENANT_PK(e),":skPrefix":o},ScanIndexForward:!1,Limit:n};r?.cursor&&(a.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let c=await this.docClient.send(new UR(a)),l=c.Items??[],d=await this.fetchProfileMap(e,l),p=l.map(v=>this.toListItem(v,e,d)),m=!!c.LastEvaluatedKey,E=m?Buffer.from(JSON.stringify(c.LastEvaluatedKey)).toString("base64url"):null;return mr(p,{limit:n,hasNext:m,cursor:E,prevCursor:r?.cursor??null})}catch{return u(M.DatabaseQueryError({query:"listByUser query"}))}}async fetchProfileMap(e,r){let n=new Map;if(r.length===0)return n;let i=r.map(o=>({PK:D.TENANT_PROFILE_PK(le.tenantId(o.PK)),SK:D.TENANT_PROFILE_SK(e)})),s=await this.docClient.send(new PR({RequestItems:{[this.tableName]:{Keys:i}}}));for(let o of s.Responses?.[this.tableName]??[]){let a=o,c=le.tenantId(a.PK);n.set(c,a)}return n}toListItem(e,r,n){let i=le.tenantId(e.PK),s={tenantId:i,userId:r,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:z(e.createdAt),updatedAt:z(e.updatedAt)};e.roles!==void 0&&(s.roles=e.roles),e.perms!==void 0&&(s.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(s.authPerm=e.authPerm);let o=n.get(i);return o&&(o.contactEmail&&(s.contactEmail=o.contactEmail),o.contactPhone&&(s.contactPhone=o.contactPhone),o.displayName&&(s.displayName=o.displayName),o.displayNameSource&&(s.displayNameSource=o.displayNameSource),o.givenName&&(s.givenName=o.givenName),o.familyName&&(s.familyName=o.familyName),o.avatarUrl&&(s.avatarUrl=o.avatarUrl),o.locale&&(s.locale=o.locale),o.jobTitle&&(s.jobTitle=o.jobTitle),o.bio&&(s.bio=o.bio),o.metadata&&(s.metadata=JSON.parse(o.metadata))),s}};import{DeleteCommand as LR,GetCommand as MR,PutCommand as KR,UpdateCommand as HR}from"@aws-sdk/lib-dynamodb";var Ca=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateTenantId(){return At()}toEntity(e){let n={id:le.tenantId(e.PK),type:e.tenantType,ownerId:e.ownerId,createdAt:z(e.createdAt),updatedAt:z(e.updatedAt)};return e.parentTenantId&&(n.parentTenantId=e.parentTenantId),n}async get(e){try{let r=await this.docClient.send(new MR({TableName:this.tableName,Key:{PK:D.TENANT_PK(e),SK:D.TENANT_SK()}}));return r.Item?g(this.toEntity(r.Item)):g(null)}catch{return u(M.DatabaseQueryError({query:"get tenant"}))}}async create(e){try{let r=e.id??this.generateTenantId(),n=ae(),i=Ft({PK:D.TENANT_PK(r),SK:D.TENANT_SK(),tenantType:e.type,parentTenantId:e.parentTenantId,ownerId:e.ownerId,createdAt:n,updatedAt:n});return await this.docClient.send(new KR({TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),g(void 0)}catch(r){return r.name==="ConditionalCheckFailedException"?u(M.UniqueConstraintViolation({field:"tenant"})):u(M.UnknownError({message:r.message}))}}async update(e,r){try{let n={updatedAt:ae()};r.type!==void 0&&(n.tenantType=r.type),r.ownerId!==void 0&&(n.ownerId=r.ownerId),r.parentTenantId!==void 0&&(n.parentTenantId=r.parentTenantId===null?void 0:r.parentTenantId);let{UpdateExpression:i,ExpressionAttributeNames:s,ExpressionAttributeValues:o}=wr(n);return await this.docClient.send(new HR({TableName:this.tableName,Key:{PK:D.TENANT_PK(e),SK:D.TENANT_SK()},UpdateExpression:i,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),g(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?u(M.NotFound({entity:"Tenant",id:e})):u(M.UnknownError({message:n.message}))}}async delete(e){try{return await this.docClient.send(new LR({TableName:this.tableName,Key:{PK:D.TENANT_PK(e),SK:D.TENANT_SK()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),g(void 0)}catch(r){return r.name==="ConditionalCheckFailedException"?u(M.NotFound({entity:"Tenant",id:e})):u(M.UnknownError({message:r.message}))}}async list(){return u(M.InvalidData({reason:"DynamoDB tenant list requires a dedicated GSI; scan is disabled"}))}async listByParent(e){return u(M.InvalidData({reason:`DynamoDB tenant listByParent(${e}) requires a dedicated GSI; scan is disabled`}))}async listRoots(){return u(M.InvalidData({reason:"DynamoDB tenant listRoots requires a dedicated GSI; scan is disabled"}))}};import{DeleteCommand as FR,GetCommand as VR,PutCommand as BR,UpdateCommand as Wl}from"@aws-sdk/lib-dynamodb";var Da=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async get(e){try{let r=await this.docClient.send(new VR({TableName:this.tableName,Key:{[f.PK]:D.USER_PK(e),[f.SK]:D.USER_AUTH_SK()}}));return r.Item?g(this.unmarshall(r.Item,e)):g(null)}catch{return u(M.DatabaseQueryError({query:"get user auth"}))}}async create(e){try{let r=ae(),n={...e,createdAt:new Date(r),updatedAt:new Date(r)};return await this.docClient.send(new BR({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:`attribute_not_exists(${f.PK})`})),g(n)}catch(r){return Pe(r)?u(M.UniqueConstraintViolation({field:"userAuth"})):u(M.DatabaseQueryError({query:"create user auth"}))}}async updateStatus(e,r){try{let n=ae();return await this.docClient.send(new Wl({TableName:this.tableName,Key:{[f.PK]:D.USER_PK(e),[f.SK]:D.USER_AUTH_SK()},UpdateExpression:`SET #userStatus = :userStatus, #${f.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#userStatus":"userStatus",[`#${f.UPDATED_AT}`]:f.UPDATED_AT},ExpressionAttributeValues:{":userStatus":r,":updatedAt":n},ConditionExpression:`attribute_exists(${f.PK})`})),g(void 0)}catch(n){return Pe(n)?u(M.NotFound({entity:"userAuth",id:e})):u(M.DatabaseQueryError({query:"update user auth status"}))}}async updateMfaRequired(e,r){try{let n=ae();return await this.docClient.send(new Wl({TableName:this.tableName,Key:{[f.PK]:D.USER_PK(e),[f.SK]:D.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #${f.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired",[`#${f.UPDATED_AT}`]:f.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":r,":updatedAt":n},ConditionExpression:`attribute_exists(${f.PK})`})),g(void 0)}catch(n){return Pe(n)?u(M.NotFound({entity:"userAuth",id:e})):u(M.DatabaseQueryError({query:"update mfa required"}))}}async updateMfaMethods(e,r){try{let n=ae();return await this.docClient.send(new Wl({TableName:this.tableName,Key:{[f.PK]:D.USER_PK(e),[f.SK]:D.USER_AUTH_SK()},UpdateExpression:`SET #mfaMethods = :mfaMethods, #${f.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaMethods":"mfaMethods",[`#${f.UPDATED_AT}`]:f.UPDATED_AT},ExpressionAttributeValues:{":mfaMethods":r,":updatedAt":n},ConditionExpression:`attribute_exists(${f.PK})`})),g(void 0)}catch(n){return Pe(n)?u(M.NotFound({entity:"userAuth",id:e})):u(M.DatabaseQueryError({query:"update mfa methods"}))}}async updateMfaSettings(e,r){try{let n=ae();return await this.docClient.send(new Wl({TableName:this.tableName,Key:{[f.PK]:D.USER_PK(e),[f.SK]:D.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #mfaMethods = :mfaMethods, #${f.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired","#mfaMethods":"mfaMethods",[`#${f.UPDATED_AT}`]:f.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":r.mfaRequired,":mfaMethods":r.mfaMethods,":updatedAt":n},ConditionExpression:`attribute_exists(${f.PK})`})),g(void 0)}catch(n){return Pe(n)?u(M.NotFound({entity:"userAuth",id:e})):u(M.DatabaseQueryError({query:"update mfa settings"}))}}async remove(e){try{return await this.docClient.send(new FR({TableName:this.tableName,Key:{[f.PK]:D.USER_PK(e),[f.SK]:D.USER_AUTH_SK()}})),g(void 0)}catch{return u(M.DatabaseQueryError({query:"remove user auth"}))}}marshall(e){return{[f.PK]:D.USER_PK(e.userId),[f.SK]:D.USER_AUTH_SK(),userStatus:e.userStatus,mfaRequired:e.mfaRequired,mfaMethods:e.mfaMethods,[f.CREATED_AT]:ne(e.createdAt),[f.UPDATED_AT]:ne(e.updatedAt)}}unmarshall(e,r){return{userId:r,userStatus:e.userStatus,mfaRequired:e.mfaRequired||!1,mfaMethods:e.mfaMethods||null,createdAt:z(e[f.CREATED_AT]),updatedAt:z(e[f.UPDATED_AT])}}};import{DynamoDBDocumentClient as qR,DeleteCommand as jR,GetCommand as GR,PutCommand as $R,QueryCommand as OA,UpdateCommand as Af}from"@aws-sdk/lib-dynamodb";function Gs(t,e){return e?D.USER_MFA_WITH_ID_SK(t,e):D.USER_MFA_SK(t)}var Pa=class{client;tableName;docClient;constructor(e,r){this.client=e,this.tableName=r,this.docClient=qR.from(e)}toDynamoDBItem(e){let r={PK:D.USER_PK(e.userId),SK:Gs(e.method,e.id),method:e.method,data:JSON.stringify(e.data),createdAt:Date.now(),failedAttempts:0};return e.label&&(r.label=e.label),e.verifiedAt&&(r.verifiedAt=e.verifiedAt.getTime()),e.metadata&&(r.metadata=JSON.stringify(e.metadata)),r}fromDynamoDBItem(e,r){let n=le.mfaSKInfo(e.SK),i={userId:r,method:e.method,data:JSON.parse(e.data),createdAt:z(e.createdAt),verifiedAt:Ht(e.verifiedAt)??null};return n?.id&&(i.id=n.id),e.label&&(i.label=e.label),e.failedAttempts!==void 0&&(i.failedAttempts=e.failedAttempts),e.lastFailedAt!==void 0&&(i.lastFailedAt=Ht(e.lastFailedAt)),e.lockedUntil!==void 0&&(i.lockedUntil=Ht(e.lockedUntil)),e.lastUsedAt!==void 0&&(i.lastUsedAt=Ht(e.lastUsedAt)),e.metadata&&(i.metadata=JSON.parse(e.metadata)),i}async get(e,r,n){try{let i=Gs(r,n),s=await this.docClient.send(new GR({TableName:this.tableName,Key:{PK:D.USER_PK(e),SK:i}}));return s.Item?g(this.fromDynamoDBItem(s.Item,e)):g(null)}catch(i){return console.error("DynamoDBUserMFAAuthenticatorRepository.get error:",i),u(M.DatabaseQueryError({query:"get MFA authenticator"}))}}async findByUserId(e){try{let r={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":D.USER_PK(e),":skPrefix":Ve.MFA}},s=((await this.docClient.send(new OA(r))).Items??[]).map(o=>this.fromDynamoDBItem(o,e));return g(s)}catch(r){return console.error("DynamoDBUserMFAAuthenticatorRepository.findByUserId error:",r),u(M.DatabaseQueryError({query:"find MFA authenticators by user"}))}}async findByUserIdAndMethod(e,r){try{let n={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":D.USER_PK(e),":skPrefix":`${Ve.MFA}${r}`}},o=((await this.docClient.send(new OA(n))).Items??[]).filter(a=>a.method===r).map(a=>this.fromDynamoDBItem(a,e));return g(o)}catch(n){return console.error("DynamoDBUserMFAAuthenticatorRepository.findByUserIdAndMethod error:",n),u(M.DatabaseQueryError({query:"find MFA authenticators by method"}))}}async create(e){try{let r={...e};e.id===void 0&&this.isMultiInstanceMethod(e.method)&&(r.id=At());let n=this.toDynamoDBItem(r);return await this.docClient.send(new $R({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),g(this.fromDynamoDBItem(n,e.userId))}catch(r){return Pe(r)?u(M.UniqueConstraintViolation({field:"MFA authenticator"})):(console.error("DynamoDBUserMFAAuthenticatorRepository.create error:",r),u(M.DatabaseQueryError({query:"create MFA authenticator"})))}}async update(e,r,n,i){try{let s=Gs(r,n),o=[],a={},c={};if(i.label!==void 0&&(o.push("#label = :label"),a["#label"]="label",c[":label"]=i.label),i.data!==void 0&&(o.push("#data = :data"),a["#data"]="data",c[":data"]=JSON.stringify(i.data)),i.verifiedAt!==void 0&&(o.push("#verifiedAt = :verifiedAt"),a["#verifiedAt"]="verifiedAt",c[":verifiedAt"]=i.verifiedAt instanceof Date?i.verifiedAt.getTime():i.verifiedAt===null?void 0:i.verifiedAt),i.lastUsedAt!==void 0&&(o.push("#lastUsedAt = :lastUsedAt"),a["#lastUsedAt"]="lastUsedAt",c[":lastUsedAt"]=i.lastUsedAt instanceof Date?i.lastUsedAt.getTime():i.lastUsedAt===null?void 0:i.lastUsedAt),i.failedAttempts!==void 0&&(o.push("#failedAttempts = :failedAttempts"),a["#failedAttempts"]="failedAttempts",c[":failedAttempts"]=i.failedAttempts),i.lastFailedAt!==void 0&&(o.push("#lastFailedAt = :lastFailedAt"),a["#lastFailedAt"]="lastFailedAt",c[":lastFailedAt"]=i.lastFailedAt instanceof Date?i.lastFailedAt.getTime():i.lastFailedAt===null?void 0:i.lastFailedAt),i.lockedUntil!==void 0&&(o.push("#lockedUntil = :lockedUntil"),a["#lockedUntil"]="lockedUntil",c[":lockedUntil"]=i.lockedUntil instanceof Date?i.lockedUntil.getTime():i.lockedUntil===null?void 0:i.lockedUntil),i.metadata!==void 0&&(o.push("#metadata = :metadata"),a["#metadata"]="metadata",c[":metadata"]=JSON.stringify(i.metadata)),o.length===0)return g(void 0);let l={TableName:this.tableName,Key:{PK:D.USER_PK(e),SK:s},UpdateExpression:`SET ${o.join(", ")}`,ExpressionAttributeNames:a,ExpressionAttributeValues:c};return await this.docClient.send(new Af(l)),g(void 0)}catch(s){return console.error("DynamoDBUserMFAAuthenticatorRepository.update error:",s),u(M.DatabaseQueryError({query:"update MFA authenticator"}))}}async remove(e,r,n){try{let i=Gs(r,n);return await this.docClient.send(new jR({TableName:this.tableName,Key:{PK:D.USER_PK(e),SK:i}})),g(void 0)}catch(i){return console.error("DynamoDBUserMFAAuthenticatorRepository.remove error:",i),u(M.DatabaseQueryError({query:"remove MFA authenticator"}))}}async incrementFailedAttempts(e,r,n,i,s){try{let o=Gs(r,n),a=Date.now(),c=["#failedAttempts = if_not_exists(#failedAttempts, :zero) + :inc","#lastFailedAt = :lastFailedAt"],l={"#failedAttempts":"failedAttempts","#lastFailedAt":"lastFailedAt"},d={":zero":0,":inc":1,":lastFailedAt":a};s!==null&&(c.push("#lockedUntil = if_not_exists(#lockedUntil, :lockedUntil)"),l["#lockedUntil"]="lockedUntil",d[":lockedUntil"]=a+s*60*1e3,d[":maxAttempts"]=i);let p={TableName:this.tableName,Key:{PK:D.USER_PK(e),SK:o},UpdateExpression:`SET ${c.join(", ")}`,ExpressionAttributeNames:l,ExpressionAttributeValues:d};return await this.docClient.send(new Af(p)),g(void 0)}catch(o){return console.error("DynamoDBUserMFAAuthenticatorRepository.incrementFailedAttempts error:",o),u(M.DatabaseQueryError({query:"increment failed attempts"}))}}async resetFailedAttempts(e,r,n){try{let i=Gs(r,n),s={TableName:this.tableName,Key:{PK:D.USER_PK(e),SK:i},UpdateExpression:"SET #failedAttempts = :zero REMOVE #lastFailedAt, #lockedUntil",ExpressionAttributeNames:{"#failedAttempts":"failedAttempts","#lastFailedAt":"lastFailedAt","#lockedUntil":"lockedUntil"},ExpressionAttributeValues:{":zero":0}};return await this.docClient.send(new Af(s)),g(void 0)}catch(i){return console.error("DynamoDBUserMFAAuthenticatorRepository.resetFailedAttempts error:",i),u(M.DatabaseQueryError({query:"reset failed attempts"}))}}async unlock(e,r,n){return this.resetFailedAttempts(e,r,n)}isMultiInstanceMethod(e){return["webauthn","passkey","hardware","backup"].includes(e)}};import{DeleteCommand as WR,DynamoDBDocumentClient as zR,GetCommand as JR,PutCommand as YR,QueryCommand as kA,UpdateCommand as CA}from"@aws-sdk/lib-dynamodb";var Ua=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=zR.from(e)}generateUserId(){return At()}async getById(e){try{let r=await this.docClient.send(new JR({TableName:this.tableName,Key:{PK:D.USER_PK(e),SK:D.USER_PROFILE_SK()}}));if(!r.Item)return g(null);let n=r.Item;if(n.deletedAt)return g(null);let s={id:le.userId(n.PK),status:n.userStatus,createdAt:z(n.createdAt),updatedAt:z(n.updatedAt),...n.deletedAt!==void 0&&{deletedAt:z(n.deletedAt)},...n.contactEmail!==void 0&&{contactEmail:n.contactEmail},...n.contactPhone!==void 0&&{contactPhone:n.contactPhone},...n.username!==void 0&&{username:n.username},...n.displayName!==void 0&&{displayName:n.displayName},...n.givenName!==void 0&&{givenName:n.givenName},...n.familyName!==void 0&&{familyName:n.familyName},...n.avatarUrl!==void 0&&{avatarUrl:n.avatarUrl},...n.locale!==void 0&&{locale:n.locale},...n.metadata!==void 0&&{metadata:JSON.parse(n.metadata)}};return g(s)}catch{return u(M.DatabaseQueryError({query:"getById user"}))}}async create(e){try{let r=ae(),n=e.id||this.generateUserId(),i=e.status||"pending",s={PK:D.USER_PK(n),SK:D.USER_PROFILE_SK(),userStatus:i,createdAt:r,updatedAt:r};e.contactEmail&&(s.contactEmail=e.contactEmail),e.contactPhone&&(s.contactPhone=e.contactPhone),e.username&&(s.username=e.username),e.displayName&&(s.displayName=e.displayName),e.givenName&&(s.givenName=e.givenName),e.familyName&&(s.familyName=e.familyName),e.avatarUrl&&(s.avatarUrl=e.avatarUrl),e.locale&&(s.locale=e.locale),e.metadata&&(s.metadata=JSON.stringify(e.metadata)),s[f.USER_STATUS_PK]=Ae.USER_STATUS_PK(i),s[f.USER_STATUS_SK]=Ae.USER_STATUS_SK(n),await this.docClient.send(new YR({TableName:this.tableName,Item:Ft(s),ConditionExpression:uf("PK")}));let o={id:n,status:i,createdAt:z(r),updatedAt:z(r),...e.contactEmail&&{contactEmail:e.contactEmail},...e.contactPhone&&{contactPhone:e.contactPhone},...e.username&&{username:e.username},...e.displayName&&{displayName:e.displayName},...e.givenName&&{givenName:e.givenName},...e.familyName&&{familyName:e.familyName},...e.avatarUrl&&{avatarUrl:e.avatarUrl},...e.locale&&{locale:e.locale},...e.metadata&&{metadata:e.metadata}};return g(o)}catch{return u(M.DatabaseQueryError({query:"create user"}))}}async updateProfile(e,r){try{let n=ae(),i={};if(r.contactEmail!==void 0&&(i.contactEmail=r.contactEmail),r.contactPhone!==void 0&&(i.contactPhone=r.contactPhone),r.displayName!==void 0&&(i.displayName=r.displayName),r.givenName!==void 0&&(i.givenName=r.givenName),r.familyName!==void 0&&(i.familyName=r.familyName),r.avatarUrl!==void 0&&(i.avatarUrl=r.avatarUrl),r.locale!==void 0&&(i.locale=r.locale),r.metadata!==void 0&&(i.metadata=JSON.stringify(r.metadata)),Object.keys(i).length===0)return g(void 0);i.updatedAt=n;let s=wr(i);return await this.docClient.send(new CA({TableName:this.tableName,Key:{PK:D.USER_PK(e),SK:D.USER_PROFILE_SK()},UpdateExpression:s.UpdateExpression,ExpressionAttributeNames:s.ExpressionAttributeNames,ExpressionAttributeValues:s.ExpressionAttributeValues})),g(void 0)}catch{return u(M.DatabaseQueryError({query:"updateProfile"}))}}async getByStatus(e,r){try{let n=Math.min(r?.limit||50,100),i;if(r?.cursor)try{i=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))}catch{return u(M.DatabaseQueryError({query:"invalid pagination cursor"}))}let s=Ae.USER_STATUS_PK(e),o=await this.docClient.send(new kA({TableName:this.tableName,IndexName:Se.USERS_BY_STATUS,KeyConditionExpression:`${f.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":s},Limit:n,ExclusiveStartKey:i})),a=[];if(o.Items&&o.Items.length>0)for(let d of o.Items){let p=le.userId(d.PK);a.push(p)}let c=!!o.LastEvaluatedKey,l=c?Buffer.from(JSON.stringify(o.LastEvaluatedKey)).toString("base64url"):null;return g(a,{pagination:{type:"cursor",limit:n,count:a.length,hasNext:c,hasPrev:!!r?.cursor,cursor:l}})}catch{return u(M.DatabaseQueryError({query:"get users by status"}))}}async countByStatus(e){try{let r=Ae.USER_STATUS_PK(e),n=await this.docClient.send(new kA({TableName:this.tableName,IndexName:Se.USERS_BY_STATUS,KeyConditionExpression:`${f.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":r},Select:"COUNT"}));return g(n.Count||0)}catch{return u(M.DatabaseQueryError({query:"count users by status"}))}}async syncAuthStatus(e,r){try{let n=ae(),i=`SET userStatus = :userStatus, #${f.UPDATED_AT} = :updatedAt, #${f.USER_STATUS_PK} = :statusPk, #${f.USER_STATUS_SK} = :statusSk`,s={":userStatus":r,":updatedAt":n,":statusPk":Ae.USER_STATUS_PK(r),":statusSk":Ae.USER_STATUS_SK(e)};return r===ye.DELETED?(i+=", deletedAt = :deletedAt",s[":deletedAt"]=n):i+=" REMOVE deletedAt",await this.docClient.send(new CA({TableName:this.tableName,Key:{PK:D.USER_PK(e),SK:D.USER_PROFILE_SK()},UpdateExpression:i,ExpressionAttributeNames:{[`#${f.UPDATED_AT}`]:f.UPDATED_AT,[`#${f.USER_STATUS_PK}`]:f.USER_STATUS_PK,[`#${f.USER_STATUS_SK}`]:f.USER_STATUS_SK},ExpressionAttributeValues:s,ConditionExpression:"attribute_exists(PK)"})),g(void 0)}catch(n){return Pe(n)?u(M.NotFound({entity:"userProfile",id:e})):u(M.DatabaseQueryError({query:"sync auth status"}))}}async remove(e){try{return await this.docClient.send(new WR({TableName:this.tableName,Key:{PK:D.USER_PK(e),SK:D.USER_PROFILE_SK()}})),g(void 0)}catch{return u(M.DatabaseQueryError({query:"remove user profile"}))}}};import{DeleteCommand as XR,DynamoDBDocumentClient as QR,GetCommand as ZR,PutCommand as e0,QueryCommand as t0,UpdateCommand as r0}from"@aws-sdk/lib-dynamodb";var La=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=QR.from(e)}mapItemToUserProviderLink(e){let r=le.providerPKInfo(e.PK);if(!r)throw new Error(`Invalid provider PK: ${e.PK}`);let n={userId:e.userId,provider:r.provider,externalId:r.externalId,createdAt:z(e.createdAt)};if(e.externalUsername&&(n.externalUsername=e.externalUsername),e.externalEmail&&(n.externalEmail=e.externalEmail),e.externalPhone&&(n.externalPhone=e.externalPhone),e.externalName&&(n.externalName=e.externalName),e.externalAvatarUrl&&(n.externalAvatarUrl=e.externalAvatarUrl),e.metadata)try{n.metadata=JSON.parse(e.metadata)}catch{}return n}mapUserProviderLinkToItem(e){let r=ae(),n={PK:D.PROVIDER_PK(e.provider,e.externalId),SK:D.PROVIDER_METADATA_SK(),userProviderPk:D.USER_PK(e.userId),userProviderSk:D.PROVIDER_PK(e.provider,e.externalId),userId:e.userId,createdAt:e.createdAt?ne(e.createdAt):r};return e.externalUsername&&(n.externalUsername=e.externalUsername),e.externalEmail&&(n.externalEmail=e.externalEmail),e.externalPhone&&(n.externalPhone=e.externalPhone),e.externalName&&(n.externalName=e.externalName),e.externalAvatarUrl&&(n.externalAvatarUrl=e.externalAvatarUrl),e.metadata&&(n.metadata=JSON.stringify(e.metadata)),Ft(n)}async findByProviderAndExternalId(e,r){try{let n=await this.docClient.send(new ZR({TableName:this.tableName,Key:{PK:D.PROVIDER_PK(e,r),SK:D.PROVIDER_METADATA_SK()}}));return n.Item?g(this.mapItemToUserProviderLink(n.Item)):g(null)}catch{return u(M.DatabaseQueryError({query:"find provider by external id"}))}}async findByUserId(e){try{let r=await this.docClient.send(new t0({TableName:this.tableName,IndexName:Se.USER_PROVIDERS,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:{"#pk":f.USER_PROVIDER_PK},ExpressionAttributeValues:{":pk":D.USER_PK(e)}}));return!r.Items||r.Items.length===0?g([]):g(r.Items.map(n=>this.mapItemToUserProviderLink(n)))}catch{return u(M.DatabaseQueryError({query:"find providers by user id"}))}}async create(e){try{let r={...e,createdAt:new Date},n=this.mapUserProviderLinkToItem(r);return await this.docClient.send(new e0({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK)"})),g(this.mapItemToUserProviderLink(n))}catch(r){return Pe(r)?u(M.UniqueConstraintViolation({field:"provider connection",message:"Provider connection already exists"})):u(M.DatabaseQueryError({query:"create user provider"}))}}async update(e,r,n){try{let i={};if(n.externalUsername!==void 0&&(i.externalUsername=n.externalUsername),n.externalEmail!==void 0&&(i.externalEmail=n.externalEmail),n.externalPhone!==void 0&&(i.externalPhone=n.externalPhone),n.externalName!==void 0&&(i.externalName=n.externalName),n.externalAvatarUrl!==void 0&&(i.externalAvatarUrl=n.externalAvatarUrl),n.metadata!==void 0&&(i.metadata=JSON.stringify(n.metadata)),Object.keys(i).length===0)return g(void 0);let{UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=wr(i);return await this.docClient.send(new r0({TableName:this.tableName,Key:{PK:D.PROVIDER_PK(e,r),SK:D.PROVIDER_METADATA_SK()},UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a})),g(void 0)}catch{return u(M.DatabaseQueryError({query:"update user provider"}))}}async remove(e,r){try{return await this.docClient.send(new XR({TableName:this.tableName,Key:{PK:D.PROVIDER_PK(e,r),SK:D.PROVIDER_METADATA_SK()}})),g(void 0)}catch{return u(M.DatabaseQueryError({query:"delete user provider"}))}}};import{DeleteCommand as n0,GetCommand as i0,PutCommand as s0,UpdateCommand as o0}from"@aws-sdk/lib-dynamodb";var Ma=class{docClient;tableName;constructor(e,r){this.docClient=e,this.tableName=r}mapItemToEntity(e){let r=le.tenantId(e.PK),n=le.tenantProfileUserId(e.SK),i={tenantId:r,userId:n,createdAt:z(e.createdAt),updatedAt:z(e.updatedAt)};return e.contactEmail&&(i.contactEmail=e.contactEmail),e.contactPhone&&(i.contactPhone=e.contactPhone),e.displayName&&(i.displayName=e.displayName),e.displayNameSource&&(i.displayNameSource=e.displayNameSource),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.avatarUrl&&(i.avatarUrl=e.avatarUrl),e.locale&&(i.locale=e.locale),e.jobTitle&&(i.jobTitle=e.jobTitle),e.bio&&(i.bio=e.bio),e.metadata&&(i.metadata=JSON.parse(e.metadata)),i}async get(e,r){try{let n=await this.docClient.send(new i0({TableName:this.tableName,Key:{PK:D.TENANT_PROFILE_PK(e),SK:D.TENANT_PROFILE_SK(r)}}));return n.Item?g(this.mapItemToEntity(n.Item)):g(null)}catch{return u(M.DatabaseQueryError({query:"get user tenant profile"}))}}async create(e){try{let r=ae(),n={PK:D.TENANT_PROFILE_PK(e.tenantId),SK:D.TENANT_PROFILE_SK(e.userId),createdAt:r,updatedAt:r};e.contactEmail&&(n.contactEmail=e.contactEmail),e.contactPhone&&(n.contactPhone=e.contactPhone),e.displayName&&(n.displayName=e.displayName),e.displayNameSource&&(n.displayNameSource=e.displayNameSource),e.givenName&&(n.givenName=e.givenName),e.familyName&&(n.familyName=e.familyName),e.avatarUrl&&(n.avatarUrl=e.avatarUrl),e.locale&&(n.locale=e.locale),e.jobTitle&&(n.jobTitle=e.jobTitle),e.bio&&(n.bio=e.bio),e.metadata&&(n.metadata=JSON.stringify(e.metadata)),await this.docClient.send(new s0({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}));let i={tenantId:e.tenantId,userId:e.userId,createdAt:z(r),updatedAt:z(r)};return e.contactEmail&&(i.contactEmail=e.contactEmail),e.contactPhone&&(i.contactPhone=e.contactPhone),e.displayName&&(i.displayName=e.displayName),e.displayNameSource&&(i.displayNameSource=e.displayNameSource),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.avatarUrl&&(i.avatarUrl=e.avatarUrl),e.locale&&(i.locale=e.locale),e.jobTitle&&(i.jobTitle=e.jobTitle),e.bio&&(i.bio=e.bio),e.metadata&&(i.metadata=e.metadata),g(i)}catch(r){return r.name==="ConditionalCheckFailedException"?u(M.UniqueConstraintViolation({field:"user tenant profile"})):u(M.UnknownError({message:r.message}))}}async update(e,r,n){try{let i={updatedAt:ae()};n.contactEmail!==void 0&&(i.contactEmail=n.contactEmail),n.contactPhone!==void 0&&(i.contactPhone=n.contactPhone),n.displayName!==void 0&&(i.displayName=n.displayName),n.displayNameSource!==void 0&&(i.displayNameSource=n.displayNameSource),n.givenName!==void 0&&(i.givenName=n.givenName),n.familyName!==void 0&&(i.familyName=n.familyName),n.avatarUrl!==void 0&&(i.avatarUrl=n.avatarUrl),n.locale!==void 0&&(i.locale=n.locale),n.jobTitle!==void 0&&(i.jobTitle=n.jobTitle),n.bio!==void 0&&(i.bio=n.bio),n.metadata!==void 0&&(i.metadata=n.metadata?JSON.stringify(n.metadata):null);let{UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=wr(i);return await this.docClient.send(new o0({TableName:this.tableName,Key:{PK:D.TENANT_PROFILE_PK(e),SK:D.TENANT_PROFILE_SK(r)},UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),g(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?u(M.NotFound({entity:"UserTenantProfile",id:`${e}:${r}`})):u(M.UnknownError({message:i.message}))}}async remove(e,r){try{return await this.docClient.send(new n0({TableName:this.tableName,Key:{PK:D.TENANT_PROFILE_PK(e),SK:D.TENANT_PROFILE_SK(r)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),g(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?u(M.NotFound({entity:"UserTenantProfile",id:`${e}:${r}`})):u(M.UnknownError({message:n.message}))}}};var Tf=class{name="database-dynamodb";version="1.0.0";users;sessions;userProviders;userMfaAuthenticators;challenges;identities;credentials;registration;userAuths;tenantMembers;tenantInvites;userTenantProfiles;tenants;queries;client;tableName;constructor(e){this.tableName=e.tableName,this.client=e.client||new c0(e.clientConfig||{});let r=l0.from(this.client,{marshallOptions:{removeUndefinedValues:!0,convertClassInstanceToMap:!0}});this.users=new Ua(this.client,this.tableName),this.sessions=new Sa({client:this.client,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userProviders=new La(this.client,this.tableName),this.userMfaAuthenticators=new Pa(this.client,this.tableName),this.challenges=new Ta({docClient:r,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.identities=new _a({docClient:r,tableName:this.tableName}),this.credentials=new Ia({docClient:r,tableName:this.tableName}),this.registration=new xa({docClient:r,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userAuths=new Da({docClient:r,tableName:this.tableName}),this.tenantMembers=new Oa(this.client,this.tableName),this.tenantInvites=new wa({docClient:r,tableName:this.tableName}),this.userTenantProfiles=new Ma(r,this.tableName),this.tenants=new Ca({docClient:r,tableName:this.tableName}),this.queries={tenantInvites:new Na({docClient:r,tableName:this.tableName}),tenantMembers:new Ra({docClient:r,tableName:this.tableName}),tenants:new ka({docClient:r,tableName:this.tableName})}}async initialize(){}async health(){try{return await this.client.send(new a0({TableName:this.tableName})),!0}catch(e){return console.error("DynamoDB health check failed:",e),!1}}async cleanup(){this.client.destroy()}};function DA(t){return new Tf(t)}ho();var If=1,PA=2,UA=3,LA="auth-craft:internal";async function u0(t){let e=t.replace(/^0x/,""),r=KA(e),n=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length);let s=`-----BEGIN PRIVATE KEY-----
|
|
128
|
+
`}};var Ea=class t{static createDirectSmtp(e){return new Ll(e)}static create(e){return t.createDirectSmtp(e.smtp)}};var Rw={allowPlusAddressing:!0,allowDots:!0,requireTLD:!0};function Zv(t={}){let e={...Rw,...t},n=(()=>{if(t.customRegex)return t.customRegex;let i="[a-zA-Z0-9_\\-]";e.allowDots?(i+="+",i=`(${i}\\.?)+`):i+="+",e.allowPlusAddressing&&(i=`${i}(\\+[a-zA-Z0-9_\\-]+)?`);let s=e.requireTLD?"[a-zA-Z0-9][a-zA-Z0-9\\-]*\\.[a-zA-Z]{2,}":"[a-zA-Z0-9][a-zA-Z0-9\\-\\.]*";return new RegExp(`^${i}@${s}$`)})();return{name:"email-identity",version:"1.0.0",identityType:"email",normalize(i){return i.toLowerCase().trim()},validate(i){if(!i||i.trim().length===0)return u([{code:"EMAIL_REQUIRED",message:"Email address is required"}]);if(i.length>254)return u([{code:"EMAIL_TOO_LONG",message:"Email address is too long (max 254 characters)"}]);if(!n.test(i))return u([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);if(i.includes(".."))return u([{code:"INVALID_EMAIL_FORMAT",message:"Email address cannot contain consecutive dots"}]);let s=i.split("@");if(s.length!==2)return u([{code:"INVALID_EMAIL_FORMAT",message:"Invalid email address format"}]);let[o,a]=s;return!o||o.length>64?u([{code:"EMAIL_LOCAL_PART_TOO_LONG",message:"Email local part is too long (max 64 characters)"}]):a&&a.length>253?u([{code:"EMAIL_DOMAIN_TOO_LONG",message:"Email domain is too long (max 253 characters)"}]):g()}}}function Zp(t=6){let e="";for(;e.length<t;){let r=new Uint8Array(t);crypto.getRandomValues(r);for(let n=0;n<r.length&&e.length<t;n++){let i=r[n];i>=250||(e+=(i%10).toString())}}return e}function Ow(t){return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}async function ef(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Ow(r)}var tf="email",Ml={EMAIL_SYSTEM_NOT_AVAILABLE:T("MFA_EMAIL_SYSTEM_NOT_AVAILABLE","Email system is not configured"),RECIPIENT_NOT_FOUND:T("MFA_EMAIL_RECIPIENT_NOT_FOUND","No email address on file for this user"),SEND_FAILED:T("MFA_EMAIL_SEND_FAILED","Failed to send the verification email"),USE_CHALLENGE_CODE_HASH:T("MFA_EMAIL_USE_CHALLENGE_CODE_HASH","Email MFA codes are verified against the challenge code hash, not stored credentials")};function kw(t){let[e,r]=t.split("@");return!e||!r?"***":`${e.slice(0,1)}***@${r}`}function eA(t={}){let e=t.codeLength??6,r=t.template??"mfa-email-code";return{name:"email-mfa",version:"1.0.0",method:tf,requiresServerDelivery:!0,async sendCode(n,i){if(!i.plugins.emailSystem)return u(Ml.EMAIL_SYSTEM_NOT_AVAILABLE());let s=await i.plugins.database.users.getById(n.userId),o=s.ok&&s.data?s.data.contactEmail:void 0;if(!o)return u(Ml.RECIPIENT_NOT_FOUND());let a=Zp(e),c=await ef(a);return(await i.plugins.emailSystem.send({to:o,template:r,variables:{code:a,purpose:"mfa"}})).ok===!1?u(Ml.SEND_FAILED()):g({codeHash:c,maskedRecipient:kw(o)})},async issueChallenge(n){return g({challengeId:`email_${Date.now()}`,methods:n.availableMethods.includes(tf)?[tf]:n.availableMethods,expiresAt:new Date(Date.now()+300*1e3)})},async verify(){return u(Ml.USE_CHALLENGE_CODE_HASH())}}}var tA="ABCDEFGHIJKLMNPQRSTUVWXYZ23456789";function Kl(t=10,e=10){let r=[];for(let n=0;n<t;n++){let i=new Uint8Array(e);crypto.getRandomValues(i);let s="";for(let o of i)s+=tA[o%tA.length];r.push(s)}return r}function Cw(t){return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,"0")).join("")}async function Hl(t){let e=new TextEncoder().encode(t.toUpperCase().trim()),r=await crypto.subtle.digest("SHA-256",e);return Cw(r)}function Dw(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t.charCodeAt(n)^e.charCodeAt(n);return r===0}async function rf(t,e){let r=await Hl(t),n=null;for(let i of e)Dw(r,i)&&(n=i);return n}var nf="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function rA(t){let e=t.toUpperCase().replace(/=+$/u,"").replace(/\s+/gu,""),r=0,n=0,i=[];for(let s of e){let o=nf.indexOf(s);if(o===-1)throw new Error("Invalid base32 character in TOTP secret");n=n<<5|o,r+=5,r>=8&&(r-=8,i.push(n>>>r&255))}return new Uint8Array(i)}function nA(t){let e=0,r=0,n="";for(let i of t)for(r=r<<8|i,e+=8;e>=5;)e-=5,n+=nf[r>>>e&31];return e>0&&(n+=nf[r<<5-e&31]),n}function Fl(t=20){let e=new Uint8Array(t);return crypto.getRandomValues(e),nA(e)}function Pw(t){let e=new Uint8Array(8),r=t;for(let n=7;n>=0;n--)e[n]=r&255,r=Math.floor(r/256);return e}async function Uw(t,e,r){let n=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-1"},!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign("HMAC",n,Pw(e))),s=i[i.length-1]&15;return(((i[s]&127)<<24|(i[s+1]&255)<<16|(i[s+2]&255)<<8|i[s+3]&255)%10**r).toString().padStart(r,"0")}async function Vl(t,e,r=Date.now(),n={}){let i=n.period??30,s=n.digits??6,o=n.window??1,a=e.trim();if(a.length!==s||!/^\d+$/u.test(a))return!1;let c=rA(t),l=Math.floor(r/1e3/i),d=!1;for(let p=-o;p<=o;p++){let m=await Uw(c,l+p,s);Lw(m,a)&&(d=!0)}return d}function Lw(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t.charCodeAt(n)^e.charCodeAt(n);return r===0}function iA(t){let e=encodeURIComponent(`${t.issuer}:${t.accountName}`),r=new URLSearchParams({secret:t.secretBase32,issuer:t.issuer,algorithm:"SHA1",digits:String(t.digits??6),period:String(t.period??30)});return`otpauth://totp/${e}?${r.toString()}`}var sf="totp",Mw={USE_VERIFY_WITH_CREDENTIALS:{code:"TOTP_USE_VERIFY_WITH_CREDENTIALS",message:"TOTP verification requires credential data; call verifyWithCredentials()"}};function sA(t={}){let e=t.issuer??"Auth Craft",r=t.backupCodeCount??10,n=t.window??1;return{name:"totp-mfa",version:"1.0.0",method:sf,requiresServerDelivery:!1,generateSecret(){return Fl()},generateBackupCodes(i){return Kl(i||r)},async issueChallenge(i){return g({challengeId:`totp_${Date.now()}`,methods:i.availableMethods.includes(sf)?[sf]:i.availableMethods,expiresAt:new Date(Date.now()+300*1e3)})},async verify(){return u(Mw.USE_VERIFY_WITH_CREDENTIALS)},async setup(i){let s=Fl(),o=Kl(r),a=await Promise.all(o.map(p=>Hl(p))),c=i.data.accountName??i.userId,l=iA({secretBase32:s,accountName:c,issuer:e});return g({secret:s,otpauthUri:l,backupCodes:o,credentialData:{secret:s,backupCodeHashes:a}})},async verifyWithCredentials(i){let s=i.credentialData,o=i.data.code?.trim();if(!o||!s?.secret)return g({verified:!1,data:{}});if(await Vl(s.secret,o,Date.now(),{window:n}))return g({verified:!0,data:{}});let c=s.backupCodeHashes??[];if(c.length>0){let l=await rf(o,c);if(l)return g({verified:!0,data:{usedBackupCodeHash:l}})}return g({verified:!1,data:{}})},async verifyCredential(i,s){let o=i.data.code,a=i.data.secret;if(!o||!a)return g({verified:!1,data:{}});let c=await Vl(a,o,Date.now(),{window:n});return g({verified:c,data:{}})}}}var of={scopes:["email","public_profile"],apiVersion:"v18.0"};var Yr={INVALID_CODE:T("FACEBOOK_INVALID_CODE","Invalid authorization code"),TOKEN_EXCHANGE_FAILED:T("FACEBOOK_TOKEN_EXCHANGE_FAILED","Failed to exchange code for token"),USER_PROFILE_FAILED:T("FACEBOOK_USER_PROFILE_FAILED","Failed to fetch user profile"),INVALID_TOKEN:T("FACEBOOK_INVALID_TOKEN","Invalid access token"),MISSING_CONFIG:T("FACEBOOK_MISSING_CONFIG","Missing required Facebook OAuth configuration")};function af(t={}){let{scopes:e=of.scopes,apiVersion:r=of.apiVersion}=t,n={AUTHORIZATION:`https://www.facebook.com/${r}/dialog/oauth`,TOKEN:`https://graph.facebook.com/${r}/oauth/access_token`,USER_INFO:`https://graph.facebook.com/${r}/me`,DEBUG_TOKEN:`https://graph.facebook.com/${r}/debug_token`};return{name:"facebook-oauth-provider",version:"1.0.0",getAuthorizationUrl(i,s){let o=new URLSearchParams({client_id:i.clientId,redirect_uri:i.redirectUri,scope:(i.scopes??e).join(","),response_type:"code",...s&&{state:s}});return`${n.AUTHORIZATION}?${o.toString()}`},async exchangeCodeForToken(i,s){try{if(!i)return u(Yr.INVALID_CODE());let o=new URLSearchParams({client_id:s.clientId,client_secret:s.clientSecret,code:i,redirect_uri:s.redirectUri}),a=await fetch(`${n.TOKEN}?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!a.ok)return u(Yr.TOKEN_EXCHANGE_FAILED());let c=await a.json();return g({accessToken:c.access_token,...c.expires_in&&{expiresIn:c.expires_in}})}catch(o){return console.error("Facebook token exchange error:",o),u(Yr.TOKEN_EXCHANGE_FAILED())}},async getUserProfile(i){try{if(!i)return u(Yr.INVALID_TOKEN());let s=["id","email","name","first_name","last_name","picture","locale"],o=new URLSearchParams({fields:s.join(","),access_token:i}),a=await fetch(`${n.USER_INFO}?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!a.ok)return u(Yr.USER_PROFILE_FAILED());let c=await a.json(),l={id:c.id,...c.email&&{email:c.email},...c.email&&{emailVerified:!1},...c.name&&{name:c.name},...c.first_name&&{givenName:c.first_name},...c.last_name&&{familyName:c.last_name},...c.picture?.data?.url&&{avatarUrl:c.picture.data.url},...c.locale&&{locale:c.locale},provider:"facebook"};return g(l)}catch(s){return console.error("Facebook user profile error:",s),u(Yr.USER_PROFILE_FAILED())}},async verifyAccessToken(i){try{if(!i)return u(Yr.INVALID_TOKEN());let s=`${t.appId}|${t.appSecret}`,o=new URLSearchParams({input_token:i,access_token:s}),a=await fetch(`${n.DEBUG_TOKEN}?${o.toString()}`,{method:"GET",headers:{Accept:"application/json"}});return a.ok?(await a.json()).data.is_valid?this.getUserProfile(i):u(Yr.INVALID_TOKEN()):u(Yr.INVALID_TOKEN())}catch(s){return console.error("Facebook token verification error:",s),u(Yr.INVALID_TOKEN())}}}}var Bl={scopes:["openid","email","profile"],accessType:"online",includeGrantedScopes:!1},bi={AUTHORIZATION:"https://accounts.google.com/o/oauth2/v2/auth",TOKEN:"https://oauth2.googleapis.com/token",USER_INFO:"https://www.googleapis.com/oauth2/v2/userinfo",TOKEN_INFO:"https://oauth2.googleapis.com/tokeninfo",REVOKE:"https://oauth2.googleapis.com/revoke"};var et={INVALID_CODE:T("GOOGLE_INVALID_CODE","Invalid authorization code"),TOKEN_EXCHANGE_FAILED:T("GOOGLE_TOKEN_EXCHANGE_FAILED","Failed to exchange code for token"),USER_PROFILE_FAILED:T("GOOGLE_USER_PROFILE_FAILED","Failed to fetch user profile"),INVALID_TOKEN:T("GOOGLE_INVALID_TOKEN","Invalid access token"),INVALID_CREDENTIAL:T("GOOGLE_INVALID_CREDENTIAL","Invalid ID token or credential"),CREDENTIAL_VERIFICATION_FAILED:T("GOOGLE_CREDENTIAL_VERIFICATION_FAILED","Failed to verify credential"),REFRESH_TOKEN_FAILED:T("GOOGLE_REFRESH_TOKEN_FAILED","Failed to refresh access token"),MISSING_CONFIG:T("GOOGLE_MISSING_CONFIG","Missing required Google OAuth configuration")};function Kw(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4;if(r){if(r===1)throw new Error("Invalid base64url string");e+=new Array(5-r).join("=")}try{return decodeURIComponent(atob(e).split("").map(n=>`%${`00${n.charCodeAt(0).toString(16)}`.slice(-2)}`).join(""))}catch{throw new Error("Failed to decode base64url")}}function Hw(t){try{let e=t.split(".");if(e.length!==3)return null;let r=e[1];if(!r)return null;let n=Kw(r);return JSON.parse(n)}catch(e){return console.error("Failed to decode JWT:",e),null}}function cf(t={}){let{clientId:e,clientSecret:r,redirectUri:n,scopes:i=Bl.scopes,accessType:s=Bl.accessType,includeGrantedScopes:o=Bl.includeGrantedScopes,prompt:a}=t;return{name:"google-oauth-provider",version:"1.0.0",getAuthorizationUrl(c,l){let d=c?.clientId??e,p=c?.redirectUri??n;if(!d||!p)throw new Error("Google OAuth: clientId and redirectUri are required");let m=new URLSearchParams({client_id:d,redirect_uri:p,response_type:"code",scope:(c?.scopes??i).join(" "),access_type:s,...l&&{state:l},...a&&{prompt:a},...o&&{include_granted_scopes:"true"}});return`${bi.AUTHORIZATION}?${m.toString()}`},async exchangeCodeForToken(c,l){let d=l?.clientId??e,p=l?.clientSecret??r,m=l?.redirectUri??n;try{if(!c)return u(et.INVALID_CODE());if(!d||!p||!m)return u(et.MISSING_CONFIG());let E=new URLSearchParams({client_id:d,client_secret:p,code:c,redirect_uri:m,grant_type:"authorization_code"}),v=await fetch(bi.TOKEN,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:E.toString()});if(!v.ok)return console.error("Google token exchange failed with status:",v.status),u(et.TOKEN_EXCHANGE_FAILED());let b=await v.json();return g({accessToken:b.access_token,...b.refresh_token&&{refreshToken:b.refresh_token},...b.expires_in&&{expiresIn:b.expires_in}})}catch(E){return console.error("Google token exchange error:",E),u(et.TOKEN_EXCHANGE_FAILED())}},async getUserProfile(c){try{if(!c)return u(et.INVALID_TOKEN());let l=await fetch(bi.USER_INFO,{method:"GET",headers:{Authorization:`Bearer ${c}`,Accept:"application/json"}});if(!l.ok)return console.error("Google user profile failed with status:",l.status),u(et.USER_PROFILE_FAILED());let d=await l.json(),p={id:d.id,...d.email&&{email:d.email},...d.verified_email!==void 0&&{emailVerified:d.verified_email},...d.name&&{name:d.name},...d.given_name&&{givenName:d.given_name},...d.family_name&&{familyName:d.family_name},...d.picture&&{avatarUrl:d.picture},...d.locale&&{locale:d.locale},provider:"google"};return g(p)}catch(l){return console.error("Google user profile error:",l),u(et.USER_PROFILE_FAILED())}},async verifyAccessToken(c){try{if(!c)return u(et.INVALID_TOKEN());let l=await fetch(`${bi.TOKEN_INFO}?access_token=${c}`,{method:"GET",headers:{Accept:"application/json"}});if(!l.ok)return u(et.INVALID_TOKEN());let d=await l.json();return parseInt(d.expires_in,10)<=0?u(et.INVALID_TOKEN()):this.getUserProfile(c)}catch(l){return console.error("Google token verification error:",l),u(et.INVALID_TOKEN())}},async verifyCredential(c){try{if(!c)return u(et.INVALID_CREDENTIAL());let l=await fetch(`${bi.TOKEN_INFO}?id_token=${encodeURIComponent(c)}`,{method:"GET",headers:{Accept:"application/json"}});if(!l.ok)return console.error("Google credential verification failed with status:",l.status),u(et.INVALID_CREDENTIAL());let d=await l.json();if(!e)return u(et.MISSING_CONFIG());if(d.aud!==e)return u(et.INVALID_CREDENTIAL());if(parseInt(d.expires_in,10)<=0)return u(et.INVALID_CREDENTIAL());let m=d.email_verified==="true",E=Hw(c),v={id:d.sub,...d.email&&{email:d.email},...d.email&&{emailVerified:m},...E?.name&&{name:E.name},...E?.given_name&&{givenName:E.given_name},...E?.family_name&&{familyName:E.family_name},...E?.picture&&{avatarUrl:E.picture},...E?.locale&&{locale:E.locale},provider:"google"};return g(v)}catch(l){return console.error("Google credential verification error:",l),u(et.CREDENTIAL_VERIFICATION_FAILED())}},async refreshAccessToken(c,l){let d=l?.clientId??e,p=l?.clientSecret??r;try{if(!c)return u(et.INVALID_TOKEN());if(!d||!p)return u(et.MISSING_CONFIG());let m=new URLSearchParams({client_id:d,client_secret:p,refresh_token:c,grant_type:"refresh_token"}),E=await fetch(bi.TOKEN,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:m.toString()});if(!E.ok)return console.error("Google refresh token failed with status:",E.status),u(et.REFRESH_TOKEN_FAILED());let v=await E.json();return g({accessToken:v.access_token,...v.expires_in&&{expiresIn:v.expires_in}})}catch(m){return console.error("Google refresh token error:",m),u(et.REFRESH_TOKEN_FAILED())}}}}function oA(t={}){let e=new Map,r=t.sweepIntervalMs??6e4,n=0,i;function s(){if(n===0)return;let o=Date.now()-n;for(let[a,c]of e){let l=c.hits.filter(d=>d>o);l.length===0?e.delete(a):c.hits=l}}return r>0&&(i=setInterval(s,r),i.unref?.()),{name:"rate-limiter-memory",version:"1.0.0",async consume(o,a){let{limit:c,windowMs:l}=a;l>n&&(n=l);let d=Date.now(),p=d-l,m=e.get(o)??{hits:[]},E=m.hits.filter(v=>v>p);if(E.length>=c){let v=E[0]??d,b=Math.max(0,v+l-d);return m.hits=E,e.set(o,m),{allowed:!1,remaining:0,retryAfterMs:b,limit:c}}return E.push(d),m.hits=E,e.set(o,m),{allowed:!0,remaining:c-E.length,retryAfterMs:0,limit:c}},async reset(o){e.delete(o)},async cleanup(){i&&clearInterval(i),e.clear()}}}import{DescribeTableCommand as a0,DynamoDBClient as c0}from"@aws-sdk/client-dynamodb";import{DynamoDBDocumentClient as l0}from"@aws-sdk/lib-dynamodb";var M={DatabaseConnectionError:T("DATABASE_CONNECTION_ERROR","Failed to connect to database"),DatabaseQueryError:X("DATABASE_QUERY_ERROR","Database query execution failed: {query}"),NotFound:X("REPOSITORY_NOT_FOUND","{entity} with {id} not found"),UniqueConstraintViolation:X("UNIQUE_CONSTRAINT_VIOLATION","Record with this {field} already exists"),ForeignKeyViolation:X("FOREIGN_KEY_VIOLATION","Referenced {field} does not exist"),RecordLocked:T("RECORD_LOCKED","Record is currently locked by another operation"),DeadlockDetected:T("DEADLOCK_DETECTED","Transaction deadlock detected"),InvalidData:X("INVALID_DATA","Invalid data: {reason}"),Timeout:T("REPOSITORY_TIMEOUT","Database operation timed out"),AttemptsExceeded:T("ATTEMPTS_EXCEEDED","Attempt limit reached"),TransactionFailed:X("TRANSACTION_FAILED","Transaction failed: {reason}"),UnknownError:X("REPOSITORY_UNKNOWN_ERROR","Unexpected database error: {message}")};function ne(t){return t.getTime()}function z(t){return new Date(t)}function aA(t){return Math.floor(t/1e3)}function ae(){return Date.now()}function ya(t){return t instanceof Date?aA(t.getTime()):aA(t)}function lf(t){return t<Date.now()}function Nr(t){return t?ne(t):null}function Ht(t){return t==null?null:z(t)}function Ft(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}function wr(t){let e=[],r=[],n={},i={},s=0;for(let[c,l]of Object.entries(t)){if(c==="PK"||c==="SK")continue;let d=`#${c}`;if(n[d]=c,l==null)r.push(d);else{let p=`:val${s}`;e.push(`${d} = ${p}`),i[p]=l,s++}}let o=[];return e.length>0&&o.push(`SET ${e.join(", ")}`),r.length>0&&o.push(`REMOVE ${r.join(", ")}`),{UpdateExpression:o.join(" "),ExpressionAttributeNames:n,ExpressionAttributeValues:i}}function uf(t="PK"){return`attribute_not_exists(${t})`}var df={USER:"USR"},ce={USER:`${df.USER}#`,SESSION:"SES#",PROVIDER:"PRV#",CHALLENGE:"CHL#",IDENTITY:"IDT#",CREDENTIAL:"CRD#",TENANT:"TNT#",INVITE:"INV#"},Ve={METADATA:"MD",AUTH:"AUTH",PROFILE:"PROF",PROVIDER:"PRV#",MFA:"MFA#",TENANT_PROFILE:"TPRF#",OWNER:"OWNER"},St="#",D={USER_PK:t=>`${ce.USER}${t}`,USER_AUTH_SK:()=>Ve.AUTH,USER_PROFILE_SK:()=>Ve.PROFILE,USER_MFA_SK:t=>`${Ve.MFA}${t}`,USER_MFA_WITH_ID_SK:(t,e)=>`${Ve.MFA}${t}${St}${e}`,TENANT_MEMBER_PK:t=>`${ce.TENANT}${t}`,TENANT_MEMBER_SK:t=>`${ce.USER}${t}`,TENANT_OWNER_MARKER_SK:()=>Ve.OWNER,TENANT_PK:t=>`${ce.TENANT}${t}`,TENANT_SK:()=>Ve.METADATA,INVITE_PK:t=>`${ce.INVITE}${t}`,INVITE_SK:()=>Ve.METADATA,TENANT_PROFILE_PK:t=>`${ce.TENANT}${t}`,TENANT_PROFILE_SK:t=>`${Ve.TENANT_PROFILE}${ce.USER}${t}`,SESSION_PK:t=>`${ce.SESSION}${t}`,SESSION_METADATA_SK:()=>Ve.METADATA,SESSION_SK:()=>Ve.METADATA,PROVIDER_SK:(t,e)=>`${Ve.PROVIDER}${t}${St}${e}`,PROVIDER_PK:(t,e)=>`${ce.PROVIDER}${t}${St}${e}`,PROVIDER_METADATA_SK:()=>Ve.METADATA,CHALLENGE_PK:t=>`${ce.CHALLENGE}${t}`,CHALLENGE_SK:()=>Ve.METADATA,IDENTITY_PK:(t,e)=>`${ce.IDENTITY}${t}#${e}`,IDENTITY_SK:()=>Ve.METADATA,CREDENTIAL_PK:t=>`${ce.CREDENTIAL}${t}`,CREDENTIAL_SK:()=>Ve.METADATA,CREDENTIAL_TYPE_PREFIX:t=>`${ce.CREDENTIAL}${t}#`,CREDENTIAL_USER_SK:(t,e)=>`${ce.CREDENTIAL}${t}#${e}`,USER_INDEX_PK:t=>`${ce.USER}${t}`,USER_INDEX_SK:(t,e)=>`${ce.IDENTITY}${t}#${e}`},le={userId:t=>t.slice(ce.USER.length),sessionId:t=>t.slice(ce.SESSION.length),providerPKInfo:t=>{let e=t.slice(ce.PROVIDER.length),r=e.indexOf("#");if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{provider:n,externalId:i}},providerInfo:t=>{let e=t.slice(Ve.PROVIDER.length),r=e.indexOf(St);if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{provider:n,externalId:i}},mfaSKInfo:t=>{let e=t.slice(Ve.MFA.length),r=e.indexOf(St);if(r===-1)return{method:e};let n=e.slice(0,r),i=e.slice(r+1);return{method:n,id:i}},tenantId:t=>t.slice(ce.TENANT.length),tenantMemberUserId:t=>t.slice(ce.USER.length),challengeIdFromPK:t=>t.slice(ce.CHALLENGE.length),inviteId:t=>t.slice(ce.INVITE.length),tenantProfileUserId:t=>t.slice(Ve.TENANT_PROFILE.length+ce.USER.length),identityPKInfo:t=>{let e=t.slice(ce.IDENTITY.length),r=e.indexOf("#");if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{type:n,value:i}},credentialId:t=>t.slice(ce.CREDENTIAL.length),credentialTypeFromUserSK:t=>{let e=t.slice(ce.CREDENTIAL.length),r=e.indexOf("#");return r===-1?"":e.slice(0,r)},userIndexSKInfo:t=>{let e=t.slice(ce.IDENTITY.length),r=e.indexOf("#");if(r===-1)return null;let n=e.slice(0,r),i=e.slice(r+1);return{type:n,value:i}}};var Ae={ACTIVE_SESSION_PK:t=>`${ce.USER}${t}`,ACTIVE_SESSION_SK:(t,e)=>`${t}${St}${e}`,USER_SESSION_PK:t=>`${ce.USER}${t}`,USER_SESSION_SK:(t,e)=>`${t}${St}${e}`,USER_STATUS_PK:t=>{let e=t===ye.ACTIVE?"ACTIVE":"INACTIVE";return`${df.USER}${St}${e}`},USER_STATUS_SK:t=>t,USER_PROVIDER_PK:t=>`${ce.USER}${t}`,USER_PROVIDER_SK:(t,e)=>`${Ve.PROVIDER}${t}${St}${e}`,INVITE_TENANT_PK:t=>`${ce.TENANT}${t}`,INVITE_TENANT_SK:(t,e,r)=>`${t}${St}${e}${St}${r}`,INVITE_TENANT_STATUS_PREFIX:t=>`${t}${St}`,USER_TENANT_PK:t=>`${ce.USER}${t}`,USER_TENANT_SK:(t,e,r,n)=>`${t}${St}${e??"ROOT"}${St}${r}${St}${n}`},f={PK:"PK",SK:"SK",TTL:"TTL",ACTIVE_SESSION_PK:"activeSessionPk",ACTIVE_SESSION_SK:"activeSessionSk",USER_SESSION_PK:"userSessionPk",USER_SESSION_SK:"userSessionSk",USER_STATUS_PK:"userStatusPk",USER_STATUS_SK:"userStatusSk",USER_PROVIDER_PK:"userProviderPk",USER_PROVIDER_SK:"userProviderSk",USER_ID:"userId",TENANT_ID:"tenantId",TENANT_TYPE:"tenantType",AUDIENCE:"audience",PURPOSE:"purpose",CHALLENGE_STATUS:"challengeStatus",PHASE:"phase",ALLOWED_METHODS:"allowedMethods",METHOD:"method",IDENTITY_TYPE:"identityType",IDENTITY_VALUE:"identityValue",CODE_HASH:"codeHash",ATTEMPTS:"attempts",MAX_ATTEMPTS:"maxAttempts",METADATA:"metadata",FLOW_KEY:"flowKey",EXPIRES_AT:"expiresAt",CREATED_AT:"createdAt",TOKEN_ID:"tokenId",PREVIOUS_TOKEN_ID:"previousTokenId",ROTATED_AT:"rotatedAt",LAST_USED_AT:"lastUsedAt",REVOKED_AT:"revokedAt",ROLE:"role",ROLES:"roles",PERM:"perm",AUTH_PERM:"authPerm",IS_OWNER:"isOwner",DEVICE_LABEL:"deviceLabel",COUNTRY:"country",CITY:"city",IDENTITY_USER_PK:"identityUserPk",IDENTITY_USER_SK:"identityUserSk",LOGIN_ENABLED:"loginEnabled",VERIFIED_AT:"verifiedAt",GUARDS:"guards",PENDING_VERIFICATION:"pendingVerification",UPDATED_AT:"updatedAt",CREDENTIAL_USER_PK:"credentialUserPk",CREDENTIAL_USER_SK:"credentialUserSk",CREDENTIAL_VALUE:"value",INVITE_STATUS:"inviteStatus",INVITE_TOKEN:"inviteToken",INVITED_BY_ID:"invitedById",INVITED_BY_INFO:"invitedByInfo",INVITEE_USER_ID:"inviteeUserId",INVITEE_EMAIL:"inviteeEmail",INVITEE_PHONE:"inviteePhone",ACCEPTED_AT:"acceptedAt",DECLINED_AT:"declinedAt",INVITE_TENANT_PK:"inviteTenantPk",INVITE_TENANT_SK:"inviteTenantSk",INVITE_TOKEN_GSI:"inviteTokenGsi",INVITEE_EMAIL_GSI:"inviteeEmailGsi",INVITEE_EMAIL_TENANT_SK:"inviteeEmailTenantSk",INVITEE_PHONE_GSI:"inviteePhoneGsi",INVITEE_PHONE_TENANT_SK:"inviteePhoneTenantSk",USER_TENANT_PK:"userTenantPk",USER_TENANT_SK:"userTenantSk",DISPLAY_NAME:"displayName",AVATAR_URL:"avatarUrl",TITLE:"title",BIO:"bio"},Se={ACTIVE_SESSIONS:"GSI_ActiveSessions",USER_SESSIONS:"GSI_UserSessions",USERS_BY_STATUS:"GSI_UsersByStatus",USER_PROVIDERS:"GSI_UserProviders",USER_IDENTITIES:"GSI_UserIdentities",USER_CREDENTIALS:"GSI_UserCredentials",TENANT_INVITES:"GSI_TenantInvites",INVITE_TOKEN:"GSI_InviteToken",INVITEE_EMAIL:"GSI_InviteeEmail",INVITEE_PHONE:"GSI_InviteePhone",USER_TENANTS:"GSI_UserTenants"},ql={sessionSK:(t,e)=>`${t instanceof Date?t.getTime():t}${St}${e}`,extractCreatedAt:t=>{let e=t.indexOf(St),r=e===-1?t:t.slice(0,e);return Number(r)}};import{DeleteCommand as sR,GetCommand as oR,PutCommand as aR,UpdateCommand as TA}from"@aws-sdk/lib-dynamodb";var Fw=BigInt(0),ga=BigInt(1),Vw=BigInt(2),Bw=BigInt(7),qw=BigInt(256),jw=BigInt(113),uA=[],dA=[],pA=[];for(let t=0,e=ga,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],uA.push(2*(5*n+r)),dA.push((t+1)*(t+2)/2%64);let i=Fw;for(let s=0;s<7;s++)e=(e<<ga^(e>>Bw)*jw)%qw,e&Vw&&(i^=ga<<(ga<<BigInt(s))-ga);pA.push(i)}var fA=Gy(pA,!0),Gw=fA[0],$w=fA[1],cA=(t,e,r)=>r>32?zy(t,e,r):$y(t,e,r),lA=(t,e,r)=>r>32?Jy(t,e,r):Wy(t,e,r);function Ww(t,e=24){if(yt(e,"rounds"),e<1||e>24)throw new Error('"rounds" expected integer 1..24');let r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){let a=(o+8)%10,c=(o+2)%10,l=r[c],d=r[c+1],p=cA(l,d,1)^r[a],m=lA(l,d,1)^r[a+1];for(let E=0;E<50;E+=10)t[o+E]^=p,t[o+E+1]^=m}let i=t[2],s=t[3];for(let o=0;o<24;o++){let a=dA[o],c=cA(i,s,a),l=lA(i,s,a),d=uA[o];i=t[d],s=t[d+1],t[d]=c,t[d+1]=l}for(let o=0;o<50;o+=10){let a=t[o],c=t[o+1],l=t[o+2],d=t[o+3];t[o]^=~t[o+2]&t[o+4],t[o+1]^=~t[o+3]&t[o+5],t[o+2]^=~t[o+4]&t[o+6],t[o+3]^=~t[o+5]&t[o+7],t[o+4]^=~t[o+6]&t[o+8],t[o+5]^=~t[o+7]&t[o+9],t[o+6]^=~t[o+8]&a,t[o+7]^=~t[o+9]&c,t[o+8]^=~a&l,t[o+9]^=~c&d}t[0]^=Gw[n],t[1]^=$w[n]}jt(r)}var pf=class t{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;canXOF;enableXOF=!1;rounds;constructor(e,r,n,i=!1,s=24){if(this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.canXOF=i,this.rounds=s,yt(n,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Ks(this.state)}clone(){return this._cloneInto()}keccak(){Fs(this.state32),Ww(this.state32,this.rounds),Fs(this.state32),this.posOut=0,this.pos=0}update(e){hn(this),mn(e);let{blockLen:r,state:n}=this,i=e.length;for(let s=0;s<i;){let o=Math.min(r-this.pos,i-s);for(let a=0;a<o;a++)n[this.pos++]^=e[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:r,pos:n,blockLen:i}=this;e[n]^=r,(r&128)!==0&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){hn(this,!1),mn(e),this.finish();let r=this.state,{blockLen:n}=this;for(let i=0,s=e.length;i<s;){this.posOut>=n&&this.keccak();let o=Math.min(n-this.posOut,s-i);e.set(r.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return yt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ms(e,this),this.finished)throw new Error("digest() was already called");this.writeInto(e.subarray(0,this.outputLen)),this.destroy()}digest(){let e=new Uint8Array(this.outputLen);return this.digestInto(e),e}destroy(){this.destroyed=!0,jt(this.state)}_cloneInto(e){let{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return e||=new t(r,n,i,o,s),e.blockLen=r,e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=i,e.enableXOF=o,e.canXOF=this.canXOF,e.destroyed=this.destroyed,e}},zw=(t,e,r,n={})=>Tl(()=>new pf(e,t,r),n);var mA=zw(6,72,64,Il(10));var Jw=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,ff=Math.ceil,pr=Math.floor,Gt="[BigNumber Error] ",hA=Gt+"Number primitive has more than 15 significant digits: ",Rr=1e14,ue=14,mf=9007199254740991,hf=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Bn=1e7,vt=1e9;function EA(t){var e,r,n,i=L.prototype={constructor:L,toString:null,valueOf:null},s=new L(1),o=20,a=4,c=-7,l=21,d=-1e7,p=1e7,m=!1,E=1,v=0,b={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},k="0123456789abcdefghijklmnopqrstuvwxyz",C=!0;function L(A,x){var S,y,I,w,R,N,O,P,U=this;if(!(U instanceof L))return new L(A,x);if(x==null){if(A&&A._isBigNumber===!0){U.s=A.s,!A.c||A.e>p?U.c=U.e=null:A.e<d?U.c=[U.e=0]:(U.e=A.e,U.c=A.c.slice());return}if((N=typeof A=="number")&&A*0==0){if(U.s=1/A<0?(A=-A,-1):1,A===~~A){for(w=0,R=A;R>=10;R/=10,w++);w>p?U.c=U.e=null:(U.e=w,U.c=[A]);return}P=String(A)}else{if(!Jw.test(P=String(A)))return n(U,P,N);U.s=P.charCodeAt(0)==45?(P=P.slice(1),-1):1}(w=P.indexOf("."))>-1&&(P=P.replace(".","")),(R=P.search(/e/i))>0?(w<0&&(w=R),w+=+P.slice(R+1),P=P.substring(0,R)):w<0&&(w=P.length)}else{if(We(x,2,k.length,"Base"),x==10&&C)return U=new L(A),$(U,o+U.e+1,a);if(P=String(A),N=typeof A=="number"){if(A*0!=0)return n(U,P,N,x);if(U.s=1/A<0?(P=P.slice(1),-1):1,L.DEBUG&&P.replace(/^0\.0*|\./,"").length>15)throw Error(hA+A)}else U.s=P.charCodeAt(0)===45?(P=P.slice(1),-1):1;for(S=k.slice(0,x),w=R=0,O=P.length;R<O;R++)if(S.indexOf(y=P.charAt(R))<0){if(y=="."){if(R>w){w=O;continue}}else if(!I&&(P==P.toUpperCase()&&(P=P.toLowerCase())||P==P.toLowerCase()&&(P=P.toUpperCase()))){I=!0,R=-1,w=0;continue}return n(U,String(A),N,x)}N=!1,P=r(P,x,10,U.s),(w=P.indexOf("."))>-1?P=P.replace(".",""):w=P.length}for(R=0;P.charCodeAt(R)===48;R++);for(O=P.length;P.charCodeAt(--O)===48;);if(P=P.slice(R,++O)){if(O-=R,N&&L.DEBUG&&O>15&&(A>mf||A!==pr(A)))throw Error(hA+U.s*A);if((w=w-R-1)>p)U.c=U.e=null;else if(w<d)U.c=[U.e=0];else{if(U.e=w,U.c=[],R=(w+1)%ue,w<0&&(R+=ue),R<O){for(R&&U.c.push(+P.slice(0,R)),O-=ue;R<O;)U.c.push(+P.slice(R,R+=ue));R=ue-(P=P.slice(R)).length}else R-=O;for(;R--;P+="0");U.c.push(+P)}}else U.c=[U.e=0]}L.clone=EA,L.ROUND_UP=0,L.ROUND_DOWN=1,L.ROUND_CEIL=2,L.ROUND_FLOOR=3,L.ROUND_HALF_UP=4,L.ROUND_HALF_DOWN=5,L.ROUND_HALF_EVEN=6,L.ROUND_HALF_CEIL=7,L.ROUND_HALF_FLOOR=8,L.EUCLID=9,L.config=L.set=function(A){var x,S;if(A!=null)if(typeof A=="object"){if(A.hasOwnProperty(x="DECIMAL_PLACES")&&(S=A[x],We(S,0,vt,x),o=S),A.hasOwnProperty(x="ROUNDING_MODE")&&(S=A[x],We(S,0,8,x),a=S),A.hasOwnProperty(x="EXPONENTIAL_AT")&&(S=A[x],S&&S.pop?(We(S[0],-vt,0,x),We(S[1],0,vt,x),c=S[0],l=S[1]):(We(S,-vt,vt,x),c=-(l=S<0?-S:S))),A.hasOwnProperty(x="RANGE"))if(S=A[x],S&&S.pop)We(S[0],-vt,-1,x),We(S[1],1,vt,x),d=S[0],p=S[1];else if(We(S,-vt,vt,x),S)d=-(p=S<0?-S:S);else throw Error(Gt+x+" cannot be zero: "+S);if(A.hasOwnProperty(x="CRYPTO"))if(S=A[x],S===!!S)if(S)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))m=S;else throw m=!S,Error(Gt+"crypto unavailable");else m=S;else throw Error(Gt+x+" not true or false: "+S);if(A.hasOwnProperty(x="MODULO_MODE")&&(S=A[x],We(S,0,9,x),E=S),A.hasOwnProperty(x="POW_PRECISION")&&(S=A[x],We(S,0,vt,x),v=S),A.hasOwnProperty(x="FORMAT"))if(S=A[x],typeof S=="object")b=S;else throw Error(Gt+x+" not an object: "+S);if(A.hasOwnProperty(x="ALPHABET"))if(S=A[x],typeof S=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(S))C=S.slice(0,10)=="0123456789",k=S;else throw Error(Gt+x+" invalid: "+S)}else throw Error(Gt+"Object expected: "+A);return{DECIMAL_PLACES:o,ROUNDING_MODE:a,EXPONENTIAL_AT:[c,l],RANGE:[d,p],CRYPTO:m,MODULO_MODE:E,POW_PRECISION:v,FORMAT:b,ALPHABET:k}},L.isBigNumber=function(A){if(!A||A._isBigNumber!==!0)return!1;if(!L.DEBUG)return!0;var x,S,y=A.c,I=A.e,w=A.s;e:if({}.toString.call(y)=="[object Array]"){if((w===1||w===-1)&&I>=-vt&&I<=vt&&I===pr(I)){if(y[0]===0){if(I===0&&y.length===1)return!0;break e}if(x=(I+1)%ue,x<1&&(x+=ue),String(y[0]).length==x){for(x=0;x<y.length;x++)if(S=y[x],S<0||S>=Rr||S!==pr(S))break e;if(S!==0)return!0}}}else if(y===null&&I===null&&(w===null||w===1||w===-1))return!0;throw Error(Gt+"Invalid BigNumber: "+A)},L.maximum=L.max=function(){return G(arguments,-1)},L.minimum=L.min=function(){return G(arguments,1)},L.random=(function(){var A=9007199254740992,x=Math.random()*A&2097151?function(){return pr(Math.random()*A)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(S){var y,I,w,R,N,O=0,P=[],U=new L(s);if(S==null?S=o:We(S,0,vt),R=ff(S/ue),m)if(crypto.getRandomValues){for(y=crypto.getRandomValues(new Uint32Array(R*=2));O<R;)N=y[O]*131072+(y[O+1]>>>11),N>=9e15?(I=crypto.getRandomValues(new Uint32Array(2)),y[O]=I[0],y[O+1]=I[1]):(P.push(N%1e14),O+=2);O=R/2}else if(crypto.randomBytes){for(y=crypto.randomBytes(R*=7);O<R;)N=(y[O]&31)*281474976710656+y[O+1]*1099511627776+y[O+2]*4294967296+y[O+3]*16777216+(y[O+4]<<16)+(y[O+5]<<8)+y[O+6],N>=9e15?crypto.randomBytes(7).copy(y,O):(P.push(N%1e14),O+=7);O=R/7}else throw m=!1,Error(Gt+"crypto unavailable");if(!m)for(;O<R;)N=x(),N<9e15&&(P[O++]=N%1e14);for(R=P[--O],S%=ue,R&&S&&(N=hf[ue-S],P[O]=pr(R/N)*N);P[O]===0;P.pop(),O--);if(O<0)P=[w=0];else{for(w=-1;P[0]===0;P.splice(0,1),w-=ue);for(O=1,N=P[0];N>=10;N/=10,O++);O<ue&&(w-=ue-O)}return U.e=w,U.c=P,U}})(),L.sum=function(){for(var A=1,x=arguments,S=new L(x[0]);A<x.length;)S=S.plus(x[A++]);return S},r=(function(){var A="0123456789";function x(S,y,I,w){for(var R,N=[0],O,P=0,U=S.length;P<U;){for(O=N.length;O--;N[O]*=y);for(N[0]+=w.indexOf(S.charAt(P++)),R=0;R<N.length;R++)N[R]>I-1&&(N[R+1]==null&&(N[R+1]=0),N[R+1]+=N[R]/I|0,N[R]%=I)}return N.reverse()}return function(S,y,I,w,R){var N,O,P,U,K,W,J,de,ke=S.indexOf("."),He=o,fe=a;for(ke>=0&&(U=v,v=0,S=S.replace(".",""),de=new L(y),W=de.pow(S.length-ke),v=U,de.c=x(yn(dr(W.c),W.e,"0"),10,I,A),de.e=de.c.length),J=x(S,y,I,R?(N=k,A):(N=A,k)),P=U=J.length;J[--U]==0;J.pop());if(!J[0])return N.charAt(0);if(ke<0?--P:(W.c=J,W.e=P,W.s=w,W=e(W,de,He,fe,I),J=W.c,K=W.r,P=W.e),O=P+He+1,ke=J[O],U=I/2,K=K||O<0||J[O+1]!=null,K=fe<4?(ke!=null||K)&&(fe==0||fe==(W.s<0?3:2)):ke>U||ke==U&&(fe==4||K||fe==6&&J[O-1]&1||fe==(W.s<0?8:7)),O<1||!J[0])S=K?yn(N.charAt(1),-He,N.charAt(0)):N.charAt(0);else{if(J.length=O,K)for(--I;++J[--O]>I;)J[O]=0,O||(++P,J=[1].concat(J));for(U=J.length;!J[--U];);for(ke=0,S="";ke<=U;S+=N.charAt(J[ke++]));S=yn(S,P,N.charAt(0))}return S}})(),e=(function(){function A(y,I,w){var R,N,O,P,U=0,K=y.length,W=I%Bn,J=I/Bn|0;for(y=y.slice();K--;)O=y[K]%Bn,P=y[K]/Bn|0,R=J*O+P*W,N=W*O+R%Bn*Bn+U,U=(N/w|0)+(R/Bn|0)+J*P,y[K]=N%w;return U&&(y=[U].concat(y)),y}function x(y,I,w,R){var N,O;if(w!=R)O=w>R?1:-1;else for(N=O=0;N<w;N++)if(y[N]!=I[N]){O=y[N]>I[N]?1:-1;break}return O}function S(y,I,w,R){for(var N=0;w--;)y[w]-=N,N=y[w]<I[w]?1:0,y[w]=N*R+y[w]-I[w];for(;!y[0]&&y.length>1;y.splice(0,1));}return function(y,I,w,R,N){var O,P,U,K,W,J,de,ke,He,fe,Ne,at,Ri,gn,Oi,Nt,Gn,wt=y.s==I.s?1:-1,Ye=y.c,Me=I.c;if(!Ye||!Ye[0]||!Me||!Me[0])return new L(!y.s||!I.s||(Ye?Me&&Ye[0]==Me[0]:!Me)?NaN:Ye&&Ye[0]==0||!Me?wt*0:wt/0);for(ke=new L(wt),He=ke.c=[],P=y.e-I.e,wt=w+P+1,N||(N=Rr,P=fr(y.e/ue)-fr(I.e/ue),wt=wt/ue|0),U=0;Me[U]==(Ye[U]||0);U++);if(Me[U]>(Ye[U]||0)&&P--,wt<0)He.push(1),K=!0;else{for(gn=Ye.length,Nt=Me.length,U=0,wt+=2,W=pr(N/(Me[0]+1)),W>1&&(Me=A(Me,W,N),Ye=A(Ye,W,N),Nt=Me.length,gn=Ye.length),Ri=Nt,fe=Ye.slice(0,Nt),Ne=fe.length;Ne<Nt;fe[Ne++]=0);Gn=Me.slice(),Gn=[0].concat(Gn),Oi=Me[0],Me[1]>=N/2&&Oi++;do{if(W=0,O=x(Me,fe,Nt,Ne),O<0){if(at=fe[0],Nt!=Ne&&(at=at*N+(fe[1]||0)),W=pr(at/Oi),W>1)for(W>=N&&(W=N-1),J=A(Me,W,N),de=J.length,Ne=fe.length;x(J,fe,de,Ne)==1;)W--,S(J,Nt<de?Gn:Me,de,N),de=J.length,O=1;else W==0&&(O=W=1),J=Me.slice(),de=J.length;if(de<Ne&&(J=[0].concat(J)),S(fe,J,Ne,N),Ne=fe.length,O==-1)for(;x(Me,fe,Nt,Ne)<1;)W++,S(fe,Nt<Ne?Gn:Me,Ne,N),Ne=fe.length}else O===0&&(W++,fe=[0]);He[U++]=W,fe[0]?fe[Ne++]=Ye[Ri]||0:(fe=[Ye[Ri]],Ne=1)}while((Ri++<gn||fe[0]!=null)&&wt--);K=fe[0]!=null,He[0]||He.splice(0,1)}if(N==Rr){for(U=1,wt=He[0];wt>=10;wt/=10,U++);$(ke,w+(ke.e=U+P*ue-1)+1,R,K)}else ke.e=P,ke.r=+K;return ke}})();function B(A,x,S,y){var I,w,R,N,O;if(S==null?S=a:We(S,0,8),!A.c)return A.toString();if(I=A.c[0],R=A.e,x==null)O=dr(A.c),O=y==1||y==2&&(R<=c||R>=l)?Gl(O,R):yn(O,R,"0");else if(A=$(new L(A),x,S),w=A.e,O=dr(A.c),N=O.length,y==1||y==2&&(x<=w||w<=c)){for(;N<x;O+="0",N++);O=Gl(O,w)}else if(x-=R+(y===2&&w>R),O=yn(O,w,"0"),w+1>N){if(--x>0)for(O+=".";x--;O+="0");}else if(x+=w-N,x>0)for(w+1==N&&(O+=".");x--;O+="0");return A.s<0&&I?"-"+O:O}function G(A,x){for(var S,y,I=1,w=new L(A[0]);I<A.length;I++)y=new L(A[I]),(!y.s||(S=Si(w,y))===x||S===0&&w.s===x)&&(w=y);return w}function j(A,x,S){for(var y=1,I=x.length;!x[--I];x.pop());for(I=x[0];I>=10;I/=10,y++);return(S=y+S*ue-1)>p?A.c=A.e=null:S<d?A.c=[A.e=0]:(A.e=S,A.c=x),A}n=(function(){var A=/^(-?)0([xbo])(?=\w[\w.]*$)/i,x=/^([^.]+)\.$/,S=/^\.([^.]+)$/,y=/^-?(Infinity|NaN)$/,I=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(w,R,N,O){var P,U=N?R:R.replace(I,"");if(y.test(U))w.s=isNaN(U)?null:U<0?-1:1;else{if(!N&&(U=U.replace(A,function(K,W,J){return P=(J=J.toLowerCase())=="x"?16:J=="b"?2:8,!O||O==P?W:K}),O&&(P=O,U=U.replace(x,"$1").replace(S,"0.$1")),R!=U))return new L(U,P);if(L.DEBUG)throw Error(Gt+"Not a"+(O?" base "+O:"")+" number: "+R);w.s=null}w.c=w.e=null}})();function $(A,x,S,y){var I,w,R,N,O,P,U,K=A.c,W=hf;if(K){e:{for(I=1,N=K[0];N>=10;N/=10,I++);if(w=x-I,w<0)w+=ue,R=x,O=K[P=0],U=pr(O/W[I-R-1]%10);else if(P=ff((w+1)/ue),P>=K.length)if(y){for(;K.length<=P;K.push(0));O=U=0,I=1,w%=ue,R=w-ue+1}else break e;else{for(O=N=K[P],I=1;N>=10;N/=10,I++);w%=ue,R=w-ue+I,U=R<0?0:pr(O/W[I-R-1]%10)}if(y=y||x<0||K[P+1]!=null||(R<0?O:O%W[I-R-1]),y=S<4?(U||y)&&(S==0||S==(A.s<0?3:2)):U>5||U==5&&(S==4||y||S==6&&(w>0?R>0?O/W[I-R]:0:K[P-1])%10&1||S==(A.s<0?8:7)),x<1||!K[0])return K.length=0,y?(x-=A.e+1,K[0]=W[(ue-x%ue)%ue],A.e=-x||0):K[0]=A.e=0,A;if(w==0?(K.length=P,N=1,P--):(K.length=P+1,N=W[ue-w],K[P]=R>0?pr(O/W[I-R]%W[R])*N:0),y)for(;;)if(P==0){for(w=1,R=K[0];R>=10;R/=10,w++);for(R=K[0]+=N,N=1;R>=10;R/=10,N++);w!=N&&(A.e++,K[0]==Rr&&(K[0]=1));break}else{if(K[P]+=N,K[P]!=Rr)break;K[P--]=0,N=1}for(w=K.length;K[--w]===0;K.pop());}A.e>p?A.c=A.e=null:A.e<d&&(A.c=[A.e=0])}return A}function te(A){var x,S=A.e;return S===null?A.toString():(x=dr(A.c),x=S<=c||S>=l?Gl(x,S):yn(x,S,"0"),A.s<0?"-"+x:x)}return i.absoluteValue=i.abs=function(){var A=new L(this);return A.s<0&&(A.s=1),A},i.comparedTo=function(A,x){return Si(this,new L(A,x))},i.decimalPlaces=i.dp=function(A,x){var S,y,I,w=this;if(A!=null)return We(A,0,vt),x==null?x=a:We(x,0,8),$(new L(w),A+w.e+1,x);if(!(S=w.c))return null;if(y=((I=S.length-1)-fr(this.e/ue))*ue,I=S[I])for(;I%10==0;I/=10,y--);return y<0&&(y=0),y},i.dividedBy=i.div=function(A,x){return e(this,new L(A,x),o,a)},i.dividedToIntegerBy=i.idiv=function(A,x){return e(this,new L(A,x),0,1)},i.exponentiatedBy=i.pow=function(A,x){var S,y,I,w,R,N,O,P,U,K=this;if(A=new L(A),A.c&&!A.isInteger())throw Error(Gt+"Exponent not an integer: "+te(A));if(x!=null&&(x=new L(x)),N=A.e>14,!K.c||!K.c[0]||K.c[0]==1&&!K.e&&K.c.length==1||!A.c||!A.c[0])return U=new L(Math.pow(+te(K),N?A.s*(2-jl(A)):+te(A))),x?U.mod(x):U;if(O=A.s<0,x){if(x.c?!x.c[0]:!x.s)return new L(NaN);y=!O&&K.isInteger()&&x.isInteger(),y&&(K=K.mod(x))}else{if(A.e>9&&(K.e>0||K.e<-1||(K.e==0?K.c[0]>1||N&&K.c[1]>=24e7:K.c[0]<8e13||N&&K.c[0]<=9999975e7)))return w=K.s<0&&jl(A)?-0:0,K.e>-1&&(w=1/w),new L(O?1/w:w);v&&(w=ff(v/ue+2))}for(N?(S=new L(.5),O&&(A.s=1),P=jl(A)):(I=Math.abs(+te(A)),P=I%2),U=new L(s);;){if(P){if(U=U.times(K),!U.c)break;w?U.c.length>w&&(U.c.length=w):y&&(U=U.mod(x))}if(I){if(I=pr(I/2),I===0)break;P=I%2}else if(A=A.times(S),$(A,A.e+1,1),A.e>14)P=jl(A);else{if(I=+te(A),I===0)break;P=I%2}K=K.times(K),w?K.c&&K.c.length>w&&(K.c.length=w):y&&(K=K.mod(x))}return y?U:(O&&(U=s.div(U)),x?U.mod(x):w?$(U,v,a,R):U)},i.integerValue=function(A){var x=new L(this);return A==null?A=a:We(A,0,8),$(x,x.e+1,A)},i.isEqualTo=i.eq=function(A,x){return Si(this,new L(A,x))===0},i.isFinite=function(){return!!this.c},i.isGreaterThan=i.gt=function(A,x){return Si(this,new L(A,x))>0},i.isGreaterThanOrEqualTo=i.gte=function(A,x){return(x=Si(this,new L(A,x)))===1||x===0},i.isInteger=function(){return!!this.c&&fr(this.e/ue)>this.c.length-2},i.isLessThan=i.lt=function(A,x){return Si(this,new L(A,x))<0},i.isLessThanOrEqualTo=i.lte=function(A,x){return(x=Si(this,new L(A,x)))===-1||x===0},i.isNaN=function(){return!this.s},i.isNegative=function(){return this.s<0},i.isPositive=function(){return this.s>0},i.isZero=function(){return!!this.c&&this.c[0]==0},i.minus=function(A,x){var S,y,I,w,R=this,N=R.s;if(A=new L(A,x),x=A.s,!N||!x)return new L(NaN);if(N!=x)return A.s=-x,R.plus(A);var O=R.e/ue,P=A.e/ue,U=R.c,K=A.c;if(!O||!P){if(!U||!K)return U?(A.s=-x,A):new L(K?R:NaN);if(!U[0]||!K[0])return K[0]?(A.s=-x,A):new L(U[0]?R:a==3?-0:0)}if(O=fr(O),P=fr(P),U=U.slice(),N=O-P){for((w=N<0)?(N=-N,I=U):(P=O,I=K),I.reverse(),x=N;x--;I.push(0));I.reverse()}else for(y=(w=(N=U.length)<(x=K.length))?N:x,N=x=0;x<y;x++)if(U[x]!=K[x]){w=U[x]<K[x];break}if(w&&(I=U,U=K,K=I,A.s=-A.s),x=(y=K.length)-(S=U.length),x>0)for(;x--;U[S++]=0);for(x=Rr-1;y>N;){if(U[--y]<K[y]){for(S=y;S&&!U[--S];U[S]=x);--U[S],U[y]+=Rr}U[y]-=K[y]}for(;U[0]==0;U.splice(0,1),--P);return U[0]?j(A,U,P):(A.s=a==3?-1:1,A.c=[A.e=0],A)},i.modulo=i.mod=function(A,x){var S,y,I=this;return A=new L(A,x),!I.c||!A.s||A.c&&!A.c[0]?new L(NaN):!A.c||I.c&&!I.c[0]?new L(I):(E==9?(y=A.s,A.s=1,S=e(I,A,0,3),A.s=y,S.s*=y):S=e(I,A,0,E),A=I.minus(S.times(A)),!A.c[0]&&E==1&&(A.s=I.s),A)},i.multipliedBy=i.times=function(A,x){var S,y,I,w,R,N,O,P,U,K,W,J,de,ke,He,fe=this,Ne=fe.c,at=(A=new L(A,x)).c;if(!Ne||!at||!Ne[0]||!at[0])return!fe.s||!A.s||Ne&&!Ne[0]&&!at||at&&!at[0]&&!Ne?A.c=A.e=A.s=null:(A.s*=fe.s,!Ne||!at?A.c=A.e=null:(A.c=[0],A.e=0)),A;for(y=fr(fe.e/ue)+fr(A.e/ue),A.s*=fe.s,O=Ne.length,K=at.length,O<K&&(de=Ne,Ne=at,at=de,I=O,O=K,K=I),I=O+K,de=[];I--;de.push(0));for(ke=Rr,He=Bn,I=K;--I>=0;){for(S=0,W=at[I]%He,J=at[I]/He|0,R=O,w=I+R;w>I;)P=Ne[--R]%He,U=Ne[R]/He|0,N=J*P+U*W,P=W*P+N%He*He+de[w]+S,S=(P/ke|0)+(N/He|0)+J*U,de[w--]=P%ke;de[w]=S}return S?++y:de.splice(0,1),j(A,de,y)},i.negated=function(){var A=new L(this);return A.s=-A.s||null,A},i.plus=function(A,x){var S,y=this,I=y.s;if(A=new L(A,x),x=A.s,!I||!x)return new L(NaN);if(I!=x)return A.s=-x,y.minus(A);var w=y.e/ue,R=A.e/ue,N=y.c,O=A.c;if(!w||!R){if(!N||!O)return new L(I/0);if(!N[0]||!O[0])return O[0]?A:new L(N[0]?y:I*0)}if(w=fr(w),R=fr(R),N=N.slice(),I=w-R){for(I>0?(R=w,S=O):(I=-I,S=N),S.reverse();I--;S.push(0));S.reverse()}for(I=N.length,x=O.length,I-x<0&&(S=O,O=N,N=S,x=I),I=0;x;)I=(N[--x]=N[x]+O[x]+I)/Rr|0,N[x]=Rr===N[x]?0:N[x]%Rr;return I&&(N=[I].concat(N),++R),j(A,N,R)},i.precision=i.sd=function(A,x){var S,y,I,w=this;if(A!=null&&A!==!!A)return We(A,1,vt),x==null?x=a:We(x,0,8),$(new L(w),A,x);if(!(S=w.c))return null;if(I=S.length-1,y=I*ue+1,I=S[I]){for(;I%10==0;I/=10,y--);for(I=S[0];I>=10;I/=10,y++);}return A&&w.e+1>y&&(y=w.e+1),y},i.shiftedBy=function(A){return We(A,-mf,mf),this.times("1e"+A)},i.squareRoot=i.sqrt=function(){var A,x,S,y,I,w=this,R=w.c,N=w.s,O=w.e,P=o+4,U=new L("0.5");if(N!==1||!R||!R[0])return new L(!N||N<0&&(!R||R[0])?NaN:R?w:1/0);if(N=Math.sqrt(+te(w)),N==0||N==1/0?(x=dr(R),(x.length+O)%2==0&&(x+="0"),N=Math.sqrt(+x),O=fr((O+1)/2)-(O<0||O%2),N==1/0?x="5e"+O:(x=N.toExponential(),x=x.slice(0,x.indexOf("e")+1)+O),S=new L(x)):S=new L(N+""),S.c[0]){for(O=S.e,N=O+P,N<3&&(N=0);;)if(I=S,S=U.times(I.plus(e(w,I,P,1))),dr(I.c).slice(0,N)===(x=dr(S.c)).slice(0,N))if(S.e<O&&--N,x=x.slice(N-3,N+1),x=="9999"||!y&&x=="4999"){if(!y&&($(I,I.e+o+2,0),I.times(I).eq(w))){S=I;break}P+=4,N+=4,y=1}else{(!+x||!+x.slice(1)&&x.charAt(0)=="5")&&($(S,S.e+o+2,1),A=!S.times(S).eq(w));break}}return $(S,S.e+o+1,a,A)},i.toExponential=function(A,x){return A!=null&&(We(A,0,vt),A++),B(this,A,x,1)},i.toFixed=function(A,x){return A!=null&&(We(A,0,vt),A=A+this.e+1),B(this,A,x)},i.toFormat=function(A,x,S){var y,I=this;if(S==null)A!=null&&x&&typeof x=="object"?(S=x,x=null):A&&typeof A=="object"?(S=A,A=x=null):S=b;else if(typeof S!="object")throw Error(Gt+"Argument not an object: "+S);if(y=I.toFixed(A,x),I.c){var w,R=y.split("."),N=+S.groupSize,O=+S.secondaryGroupSize,P=S.groupSeparator||"",U=R[0],K=R[1],W=I.s<0,J=W?U.slice(1):U,de=J.length;if(O&&(w=N,N=O,O=w,de-=w),N>0&&de>0){for(w=de%N||N,U=J.substr(0,w);w<de;w+=N)U+=P+J.substr(w,N);O>0&&(U+=P+J.slice(w)),W&&(U="-"+U)}y=K?U+(S.decimalSeparator||"")+((O=+S.fractionGroupSize)?K.replace(new RegExp("\\d{"+O+"}\\B","g"),"$&"+(S.fractionGroupSeparator||"")):K):U}return(S.prefix||"")+y+(S.suffix||"")},i.toFraction=function(A){var x,S,y,I,w,R,N,O,P,U,K,W,J=this,de=J.c;if(A!=null&&(N=new L(A),!N.isInteger()&&(N.c||N.s!==1)||N.lt(s)))throw Error(Gt+"Argument "+(N.isInteger()?"out of range: ":"not an integer: ")+te(N));if(!de)return new L(J);for(x=new L(s),P=S=new L(s),y=O=new L(s),W=dr(de),w=x.e=W.length-J.e-1,x.c[0]=hf[(R=w%ue)<0?ue+R:R],A=!A||N.comparedTo(x)>0?w>0?x:P:N,R=p,p=1/0,N=new L(W),O.c[0]=0;U=e(N,x,0,1),I=S.plus(U.times(y)),I.comparedTo(A)!=1;)S=y,y=I,P=O.plus(U.times(I=P)),O=I,x=N.minus(U.times(I=x)),N=I;return I=e(A.minus(S),y,0,1),O=O.plus(I.times(P)),S=S.plus(I.times(y)),O.s=P.s=J.s,w=w*2,K=e(P,y,w,a).minus(J).abs().comparedTo(e(O,S,w,a).minus(J).abs())<1?[P,y]:[O,S],p=R,K},i.toNumber=function(){return+te(this)},i.toPrecision=function(A,x){return A!=null&&We(A,1,vt),B(this,A,x,2)},i.toString=function(A){var x,S=this,y=S.s,I=S.e;return I===null?y?(x="Infinity",y<0&&(x="-"+x)):x="NaN":(A==null?x=I<=c||I>=l?Gl(dr(S.c),I):yn(dr(S.c),I,"0"):A===10&&C?(S=$(new L(S),o+I+1,a),x=yn(dr(S.c),S.e,"0")):(We(A,2,k.length,"Base"),x=r(yn(dr(S.c),I,"0"),10,A,y,!0)),y<0&&S.c[0]&&(x="-"+x)),x},i.valueOf=i.toJSON=function(){return te(this)},i._isBigNumber=!0,i[Symbol.toStringTag]="BigNumber",i[Symbol.for("nodejs.util.inspect.custom")]=i.valueOf,t!=null&&L.set(t),L}function fr(t){var e=t|0;return t>0||t===e?e:e-1}function dr(t){for(var e,r,n=1,i=t.length,s=t[0]+"";n<i;){for(e=t[n++]+"",r=ue-e.length;r--;e="0"+e);s+=e}for(i=s.length;s.charCodeAt(--i)===48;);return s.slice(0,i+1||1)}function Si(t,e){var r,n,i=t.c,s=e.c,o=t.s,a=e.s,c=t.e,l=e.e;if(!o||!a)return null;if(r=i&&!i[0],n=s&&!s[0],r||n)return r?n?0:-a:o;if(o!=a)return o;if(r=o<0,n=c==l,!i||!s)return n?0:!i^r?1:-1;if(!n)return c>l^r?1:-1;for(a=(c=i.length)<(l=s.length)?c:l,o=0;o<a;o++)if(i[o]!=s[o])return i[o]>s[o]^r?1:-1;return c==l?0:c>l^r?1:-1}function We(t,e,r,n){if(t<e||t>r||t!==pr(t))throw Error(Gt+(n||"Argument")+(typeof t=="number"?t<e||t>r?" out of range: ":" not an integer: ":" not a primitive number: ")+String(t))}function jl(t){var e=t.c.length-1;return fr(t.e/ue)==e&&t.c[e]%2!=0}function Gl(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(e<0?"e":"e+")+e}function yn(t,e,r){var n,i;if(e<0){for(i=r+".";++e;i+=r);t=i+t}else if(n=t.length,++e>n){for(i=r,e-=n;--e;i+=r);t+=i}else e<n&&(t=t.slice(0,e)+"."+t.slice(e));return t}var Yw=EA(),yA=Yw;var Xw=24,va=32,Qw=()=>typeof globalThis<"u"&&globalThis.crypto&&typeof globalThis.crypto.getRandomValues=="function"?()=>{let t=new Uint32Array(1);return globalThis.crypto.getRandomValues(t),t[0]/4294967296}:Math.random,yf=Qw(),Ef=(t=4,e=yf)=>{let r="";for(;r.length<t;)r=r+Math.floor(e()*36).toString(36);return r};function Zw(t){let e=new yA(0);for(let r of t.values())e=e.multipliedBy(256).plus(r);return e}var vA=(t="")=>{let e=new TextEncoder;return Zw(mA(e.encode(t))).toString(36).slice(1)},gA=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),eR=t=>gA[Math.floor(t()*gA.length)],tR=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=yf}={})=>{let r=Object.keys(t).toString(),n=r.length?r+Ef(va,e):Ef(va,e);return vA(n).substring(0,va)},rR=t=>()=>t++,nR=476782367,AA=({random:t=yf,counter:e=rR(Math.floor(t()*nR)),length:r=Xw,fingerprint:n=tR({random:t})}={})=>{if(r>va)throw new Error(`Length must be between 2 and ${va}. Received: ${r}`);return function(){let s=eR(t),o=Date.now().toString(36),a=e().toString(36),c=Ef(r,t),l=`${o+c+a+n}`;return`${s+vA(l).substring(1,r)}`}},At=iR(AA);function iR(t){let e;return()=>(e||(e=t()),e())}function Aa(t){if(typeof t=="object"&&t!==null&&"name"in t){let{name:e}=t;return typeof e=="string"?e:void 0}}function Pe(t){return Aa(t)==="ConditionalCheckFailedException"}var Ta=class{docClient;tableName;ttlGracePeriod;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||3600*1e3}generateChallengeId(){return At()}async get(e){try{let r=await this.docClient.send(new oR({TableName:this.tableName,Key:{[f.PK]:D.CHALLENGE_PK(e),[f.SK]:D.CHALLENGE_SK()}}));if(!r.Item)return g(null);let n=this.unmarshall(r.Item);return lf(ne(n.expiresAt))?g(null):g(n)}catch{return u(M.DatabaseQueryError({query:"get challenge"}))}}async create(e){try{let r=ae(),n=e.id||this.generateChallengeId(),i={...e,id:n,createdAt:z(r)},s=ne(e.expiresAt),o=Math.floor((s+this.ttlGracePeriod)/1e3);return await this.docClient.send(new aR({TableName:this.tableName,Item:this.marshall(i,o)})),g(i)}catch{return u(M.DatabaseQueryError({query:"create challenge"}))}}async update(e,r){try{let n=[],i={},s={};return r.method!==void 0&&(n.push("#method = :method"),i["#method"]=f.METHOD,s[":method"]=r.method),r.phase!==void 0&&(n.push("#phase = :phase"),i["#phase"]=f.PHASE,s[":phase"]=r.phase),r.codeHash!==void 0&&(n.push("#codeHash = :codeHash"),i["#codeHash"]=f.CODE_HASH,s[":codeHash"]=r.codeHash),r.status!==void 0&&(n.push("#challengeStatus = :challengeStatus"),i["#challengeStatus"]=f.CHALLENGE_STATUS,s[":challengeStatus"]=r.status),n.length===0?g(void 0):(await this.docClient.send(new TA({TableName:this.tableName,Key:{[f.PK]:D.CHALLENGE_PK(e),[f.SK]:D.CHALLENGE_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:i,ExpressionAttributeValues:s})),g(void 0))}catch{return u(M.DatabaseQueryError({query:"update challenge"}))}}async incrementAttempts(e,r){let n={":zero":0,":inc":1},i;r!==void 0&&(i="attribute_not_exists(#attempts) OR #attempts < :max",n[":max"]=r);try{let o=(await this.docClient.send(new TA({TableName:this.tableName,Key:{[f.PK]:D.CHALLENGE_PK(e),[f.SK]:D.CHALLENGE_SK()},UpdateExpression:"SET #attempts = if_not_exists(#attempts, :zero) + :inc",...i?{ConditionExpression:i}:{},ExpressionAttributeNames:{"#attempts":f.ATTEMPTS},ExpressionAttributeValues:n,ReturnValues:"UPDATED_NEW"}))).Attributes?.[f.ATTEMPTS]??0;return g(o)}catch(s){return Pe(s)?u(M.AttemptsExceeded()):u(M.DatabaseQueryError({query:"increment challenge attempts"}))}}async remove(e){try{return await this.docClient.send(new sR({TableName:this.tableName,Key:{[f.PK]:D.CHALLENGE_PK(e),[f.SK]:D.CHALLENGE_SK()},ConditionExpression:"attribute_exists(#pk)",ExpressionAttributeNames:{"#pk":f.PK}})),g(void 0)}catch(r){return Pe(r)?g(void 0):u(M.DatabaseQueryError({query:"remove challenge"}))}}marshall(e,r){let n={[f.PK]:D.CHALLENGE_PK(e.id),[f.SK]:D.CHALLENGE_SK(),[f.USER_ID]:e.userId,[f.PURPOSE]:e.purpose,[f.CHALLENGE_STATUS]:e.status,[f.EXPIRES_AT]:ne(e.expiresAt),[f.CREATED_AT]:ne(e.createdAt),[f.TTL]:r};return e.tenantId&&(n[f.TENANT_ID]=e.tenantId),e.phase&&(n[f.PHASE]=e.phase),e.allowedMethods&&e.allowedMethods.length>0&&(n[f.ALLOWED_METHODS]=e.allowedMethods),e.method&&(n[f.METHOD]=e.method),e.codeHash&&(n[f.CODE_HASH]=e.codeHash),e.attempts!==void 0&&(n[f.ATTEMPTS]=e.attempts),e.maxAttempts!==void 0&&(n[f.MAX_ATTEMPTS]=e.maxAttempts),e.identityType&&(n[f.IDENTITY_TYPE]=e.identityType),e.identityValue&&(n[f.IDENTITY_VALUE]=e.identityValue),e.deviceLabel&&(n[f.DEVICE_LABEL]=e.deviceLabel),e.country&&(n[f.COUNTRY]=e.country),e.city&&(n[f.CITY]=e.city),e.metadata&&(n[f.METADATA]=e.metadata),e.flowKey&&(n[f.FLOW_KEY]=e.flowKey),n}unmarshall(e){let n={id:le.challengeIdFromPK(e[f.PK]),userId:e[f.USER_ID],purpose:e[f.PURPOSE],status:e[f.CHALLENGE_STATUS],expiresAt:z(e[f.EXPIRES_AT]),createdAt:z(e[f.CREATED_AT])};return e[f.TENANT_ID]&&(n.tenantId=e[f.TENANT_ID]),e[f.PHASE]&&(n.phase=e[f.PHASE]),e[f.ALLOWED_METHODS]&&(n.allowedMethods=e[f.ALLOWED_METHODS]),e[f.METHOD]&&(n.method=e[f.METHOD]),e[f.CODE_HASH]&&(n.codeHash=e[f.CODE_HASH]),e[f.ATTEMPTS]!==void 0&&(n.attempts=e[f.ATTEMPTS]),e[f.MAX_ATTEMPTS]!==void 0&&(n.maxAttempts=e[f.MAX_ATTEMPTS]),e[f.IDENTITY_TYPE]&&(n.identityType=e[f.IDENTITY_TYPE]),e[f.IDENTITY_VALUE]&&(n.identityValue=e[f.IDENTITY_VALUE]),e[f.DEVICE_LABEL]&&(n.deviceLabel=e[f.DEVICE_LABEL]),e[f.COUNTRY]&&(n.country=e[f.COUNTRY]),e[f.CITY]&&(n.city=e[f.CITY]),e[f.METADATA]&&(n.metadata=e[f.METADATA]),e[f.FLOW_KEY]&&(n.flowKey=e[f.FLOW_KEY]),n}};import{BatchGetCommand as cR,DeleteCommand as lR,GetCommand as uR,PutCommand as dR,QueryCommand as $l,UpdateCommand as pR}from"@aws-sdk/lib-dynamodb";var Ia=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateCredentialId(){return At()}async get(e){try{let r=await this.docClient.send(new uR({TableName:this.tableName,Key:{[f.PK]:D.CREDENTIAL_PK(e),[f.SK]:D.CREDENTIAL_SK()}}));return r.Item?g(this.unmarshall(r.Item)):g(null)}catch{return u(M.DatabaseQueryError({query:"get credential"}))}}async getByUserIdAndType(e,r){try{let n=await this.docClient.send(new $l({TableName:this.tableName,IndexName:Se.USER_CREDENTIALS,KeyConditionExpression:`${f.CREDENTIAL_USER_PK} = :userPk AND begins_with(${f.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":D.USER_PK(e),":typePrefix":D.CREDENTIAL_TYPE_PREFIX(r)},Limit:1}));if(!n.Items||n.Items.length===0)return g(null);let i=n.Items[0];if(!i)return g(null);let s=le.credentialId(i[f.PK]);return this.get(s)}catch{return u(M.DatabaseQueryError({query:"get credential by user and type"}))}}async getByUserId(e){try{let r=await this.docClient.send(new $l({TableName:this.tableName,IndexName:Se.USER_CREDENTIALS,KeyConditionExpression:`${f.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":D.USER_PK(e)}}));if(!r.Items||r.Items.length===0)return g([]);let n=r.Items.map(o=>le.credentialId(o[f.PK])),i=await this.batchGet(n);if(i.ok===!1)return u(i.errors,i.meta);if(!i.data)return g([]);let s=i.data.filter(o=>o!==null);return g(s)}catch{return u(M.DatabaseQueryError({query:"get credentials by user"}))}}async create(e){try{let r=ae(),n=this.generateCredentialId(),i={revokedAt:null,lastUsedAt:null,...e,id:n,createdAt:new Date(r),updatedAt:new Date(r)};return await this.docClient.send(new dR({TableName:this.tableName,Item:this.marshall(i),ConditionExpression:`attribute_not_exists(${f.PK})`})),g(i)}catch(r){return Pe(r)?u(M.UniqueConstraintViolation({field:"credential"})):u(M.DatabaseQueryError({query:"create credential"}))}}async update(e,r){try{let n=ae(),i=[],s={},o={};return i.push(`#${f.UPDATED_AT} = :updatedAt`),s[`#${f.UPDATED_AT}`]=f.UPDATED_AT,o[":updatedAt"]=n,r.value!==void 0&&(i.push(`#${f.CREDENTIAL_VALUE} = :value`),s[`#${f.CREDENTIAL_VALUE}`]=f.CREDENTIAL_VALUE,o[":value"]=r.value),r.data!==void 0&&(i.push(`#${f.METADATA} = :data`),s[`#${f.METADATA}`]=f.METADATA,o[":data"]=r.data),r.revokedAt!==void 0&&(i.push(`#${f.REVOKED_AT} = :revokedAt`),s[`#${f.REVOKED_AT}`]=f.REVOKED_AT,o[":revokedAt"]=r.revokedAt?ne(r.revokedAt):null),r.lastUsedAt!==void 0&&(i.push(`#${f.LAST_USED_AT} = :lastUsedAt`),s[`#${f.LAST_USED_AT}`]=f.LAST_USED_AT,o[":lastUsedAt"]=r.lastUsedAt?ne(r.lastUsedAt):null),await this.docClient.send(new pR({TableName:this.tableName,Key:{[f.PK]:D.CREDENTIAL_PK(e),[f.SK]:D.CREDENTIAL_SK()},UpdateExpression:`SET ${i.join(", ")}`,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:`attribute_exists(${f.PK})`})),g(void 0)}catch(n){return Pe(n)?u(M.NotFound({entity:"credential",id:e})):u(M.DatabaseQueryError({query:"update credential"}))}}async remove(e){try{return await this.docClient.send(new lR({TableName:this.tableName,Key:{[f.PK]:D.CREDENTIAL_PK(e),[f.SK]:D.CREDENTIAL_SK()},ConditionExpression:`attribute_exists(${f.PK})`})),g(void 0)}catch(r){return Pe(r)?u(M.NotFound({entity:"credential",id:e})):u(M.DatabaseQueryError({query:"delete credential"}))}}async hasType(e,r){try{let n=await this.docClient.send(new $l({TableName:this.tableName,IndexName:Se.USER_CREDENTIALS,KeyConditionExpression:`${f.CREDENTIAL_USER_PK} = :userPk AND begins_with(${f.CREDENTIAL_USER_SK}, :typePrefix)`,ExpressionAttributeValues:{":userPk":D.USER_PK(e),":typePrefix":D.CREDENTIAL_TYPE_PREFIX(r)},Select:"COUNT",Limit:1}));return g((n.Count||0)>0)}catch{return u(M.DatabaseQueryError({query:"check credential type"}))}}async countByUserId(e){try{let r=await this.docClient.send(new $l({TableName:this.tableName,IndexName:Se.USER_CREDENTIALS,KeyConditionExpression:`${f.CREDENTIAL_USER_PK} = :userPk`,ExpressionAttributeValues:{":userPk":D.USER_PK(e)},Select:"COUNT"}));return g(r.Count||0)}catch{return u(M.DatabaseQueryError({query:"count credentials"}))}}async batchGet(e){if(e.length===0)return g([]);try{let r=[];for(let i=0;i<e.length;i+=100)r.push(e.slice(i,i+100));let n=[];for(let i of r){let o=(await this.docClient.send(new cR({RequestItems:{[this.tableName]:{Keys:i.map(c=>({[f.PK]:D.CREDENTIAL_PK(c),[f.SK]:D.CREDENTIAL_SK()}))}}}))).Responses?.[this.tableName]||[],a=new Map;for(let c of o){let l=this.unmarshall(c);a.set(l.id,l)}for(let c of i)n.push(a.get(c)||null)}return g(n)}catch{return u(M.DatabaseQueryError({query:"batch get credentials"}))}}marshall(e){let r={[f.PK]:D.CREDENTIAL_PK(e.id),[f.SK]:D.CREDENTIAL_SK(),[f.CREDENTIAL_USER_PK]:D.USER_PK(e.userId),[f.CREDENTIAL_USER_SK]:D.CREDENTIAL_USER_SK(e.type,e.id),[f.USER_ID]:e.userId,[f.CREDENTIAL_VALUE]:e.value,[f.METADATA]:e.data,[f.REVOKED_AT]:e.revokedAt?ne(e.revokedAt):null,[f.CREATED_AT]:ne(e.createdAt),[f.UPDATED_AT]:ne(e.updatedAt)};return e.lastUsedAt&&(r[f.LAST_USED_AT]=ne(e.lastUsedAt)),r}unmarshall(e){let r=le.credentialId(e[f.PK]),n=le.credentialTypeFromUserSK(e[f.CREDENTIAL_USER_SK]);return{id:r,userId:e[f.USER_ID],type:n,value:e[f.CREDENTIAL_VALUE],data:e[f.METADATA]||{},revokedAt:Ht(e[f.REVOKED_AT]),createdAt:z(e[f.CREATED_AT]),updatedAt:z(e[f.UPDATED_AT]),lastUsedAt:Ht(e[f.LAST_USED_AT])}}};import{BatchGetCommand as fR,DeleteCommand as mR,GetCommand as hR,PutCommand as ER,QueryCommand as yR,UpdateCommand as gf}from"@aws-sdk/lib-dynamodb";function vf(t){return{failedAttempts:t.failedAttempts,lastFailedAt:Nr(t.lastFailedAt),lockedUntil:Nr(t.lockedUntil)}}function IA(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t))e[r]={failedAttempts:n.failedAttempts??0,lastFailedAt:Ht(n.lastFailedAt),lockedUntil:Ht(n.lockedUntil)};return e}function _A(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t))n&&(e[r]=vf(n));return e}var _a=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async get(e,r){try{let n=await this.docClient.send(new hR({TableName:this.tableName,Key:{[f.PK]:D.IDENTITY_PK(e,r),[f.SK]:D.IDENTITY_SK()}}));if(!n.Item)return g(null);let i=this.unmarshall(n.Item);return g(i)}catch(n){return console.error("[DynamoDB] identities.get error:",n),u(M.DatabaseQueryError({query:"get identity"}))}}async getByUserId(e){try{let r=await this.docClient.send(new yR({TableName:this.tableName,IndexName:Se.USER_IDENTITIES,KeyConditionExpression:`${f.IDENTITY_USER_PK} = :pk`,ExpressionAttributeValues:{":pk":D.USER_INDEX_PK(e)}})),n=[];for(let i of r.Items||[]){let s=this.unmarshall(i);s!==null&&n.push(s)}return g(n)}catch{return u(M.DatabaseQueryError({query:"get identities by userId"}))}}async create(e){try{let r=ae(),n={...e,createdAt:z(r),updatedAt:z(r)};return await this.docClient.send(new ER({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:"attribute_not_exists(PK)"})),g(n)}catch(r){return Pe(r)?u(M.UniqueConstraintViolation({field:"identity"})):u(M.DatabaseQueryError({query:"create identity"}))}}async update(e,r,n){try{let i=[],s=[],o={},a={};if(n.loginEnabled!==void 0&&(i.push("#loginEnabled = :loginEnabled"),o["#loginEnabled"]=f.LOGIN_ENABLED,a[":loginEnabled"]=n.loginEnabled),n.verifiedAt!==void 0){let l=Nr(n.verifiedAt);l===null?(s.push("#verifiedAt"),o["#verifiedAt"]=f.VERIFIED_AT):(i.push("#verifiedAt = :verifiedAt"),o["#verifiedAt"]=f.VERIFIED_AT,a[":verifiedAt"]=l)}n.guards!==void 0&&(i.push("#guards = :guards"),o["#guards"]=f.GUARDS,a[":guards"]=_A(n.guards)),n.pendingVerification!==void 0&&(o["#pendingVerification"]=f.PENDING_VERIFICATION,n.pendingVerification===null?s.push("#pendingVerification"):(i.push("#pendingVerification = :pendingVerification"),a[":pendingVerification"]=Ft({...n.pendingVerification,expiresAt:ne(n.pendingVerification.expiresAt),resendAvailableAt:Nr(n.pendingVerification.resendAvailableAt)}))),i.push("#updatedAt = :updatedAt"),o["#updatedAt"]=f.UPDATED_AT,a[":updatedAt"]=ae();let c=[];return i.length>0&&c.push(`SET ${i.join(", ")}`),s.length>0&&c.push(`REMOVE ${s.join(", ")}`),await this.docClient.send(new gf({TableName:this.tableName,Key:{[f.PK]:D.IDENTITY_PK(e,r),[f.SK]:D.IDENTITY_SK()},UpdateExpression:c.join(" "),ExpressionAttributeNames:o,ExpressionAttributeValues:a})),g(void 0)}catch{return u(M.DatabaseQueryError({query:"update identity"}))}}async remove(e,r){try{return await this.docClient.send(new mR({TableName:this.tableName,Key:{[f.PK]:D.IDENTITY_PK(e,r),[f.SK]:D.IDENTITY_SK()}})),g(void 0)}catch{return u(M.DatabaseQueryError({query:"remove identity"}))}}async updateGuard(e,r,n,i){let s={[f.PK]:D.IDENTITY_PK(e,r),[f.SK]:D.IDENTITY_SK()};try{return await this.docClient.send(new gf({TableName:this.tableName,Key:s,UpdateExpression:"SET #guards.#guardKey = :guard, #updatedAt = :updatedAt",ConditionExpression:"attribute_exists(#guards)",ExpressionAttributeNames:{"#guards":f.GUARDS,"#guardKey":n,"#updatedAt":f.UPDATED_AT},ExpressionAttributeValues:{":guard":vf(i),":updatedAt":ae()}})),g(void 0)}catch(o){if(Pe(o))try{return await this.docClient.send(new gf({TableName:this.tableName,Key:s,UpdateExpression:"SET #guards = :guards, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#guards":f.GUARDS,"#updatedAt":f.UPDATED_AT},ExpressionAttributeValues:{":guards":{[n]:vf(i)},":updatedAt":ae()}})),g(void 0)}catch{return u(M.DatabaseQueryError({query:"update guard"}))}return u(M.DatabaseQueryError({query:"update guard"}))}}async batchGet(e){try{if(e.length===0)return g([]);let n=(await this.docClient.send(new fR({RequestItems:{[this.tableName]:{Keys:e.map(({type:o,value:a})=>({[f.PK]:D.IDENTITY_PK(o,a),[f.SK]:D.IDENTITY_SK()}))}}}))).Responses?.[this.tableName]||[],i=new Map;for(let o of n){let a=this.unmarshall(o);if(a!==null){let c=`${a.type}#${a.value}`;i.set(c,a)}}let s=e.map(({type:o,value:a})=>{let c=`${o}#${a}`;return i.get(c)||null});return g(s)}catch{return u(M.DatabaseQueryError({query:"batch get identities"}))}}marshall(e){let r={[f.PK]:D.IDENTITY_PK(e.type,e.value),[f.SK]:D.IDENTITY_SK(),[f.IDENTITY_USER_PK]:D.USER_INDEX_PK(e.userId),[f.IDENTITY_USER_SK]:D.USER_INDEX_SK(e.type,e.value),[f.USER_ID]:e.userId,[f.LOGIN_ENABLED]:e.loginEnabled,[f.CREATED_AT]:ne(e.createdAt),[f.UPDATED_AT]:ne(e.updatedAt)},n=Nr(e.verifiedAt);return n!==null&&(r[f.VERIFIED_AT]=n),r[f.GUARDS]=_A(e.guards),e.pendingVerification&&(r[f.PENDING_VERIFICATION]=Ft({...e.pendingVerification,expiresAt:ne(e.pendingVerification.expiresAt),resendAvailableAt:Nr(e.pendingVerification.resendAvailableAt)})),r}unmarshall(e){let r=le.identityPKInfo(e[f.PK]);if(!r){let n=e[f.IDENTITY_USER_SK]?le.userIndexSKInfo(e[f.IDENTITY_USER_SK]):null;return n?{type:n.type,value:n.value,userId:e[f.USER_ID],loginEnabled:e[f.LOGIN_ENABLED],verifiedAt:Ht(e[f.VERIFIED_AT]),guards:IA(e[f.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[f.PENDING_VERIFICATION]),createdAt:z(e[f.CREATED_AT]),updatedAt:z(e[f.UPDATED_AT])}:(console.warn("Invalid identity item format, skipping:",{PK:e[f.PK],GSI1SK:e[f.IDENTITY_USER_SK]}),null)}return{type:r.type,value:r.value,userId:e[f.USER_ID],loginEnabled:e[f.LOGIN_ENABLED],verifiedAt:Ht(e[f.VERIFIED_AT]),guards:IA(e[f.GUARDS]),pendingVerification:this.unmarshallPendingVerification(e[f.PENDING_VERIFICATION]),createdAt:z(e[f.CREATED_AT]),updatedAt:z(e[f.UPDATED_AT])}}unmarshallPendingVerification(e){if(!e||typeof e!="object")return null;let r=e;return{challengeId:r.challengeId,purpose:r.purpose,channel:r.channel,expiresAt:z(r.expiresAt),resendAvailableAt:Ht(r.resendAvailableAt)}}};import{TransactWriteCommand as gR}from"@aws-sdk/lib-dynamodb";var xa=class{docClient;tableName;ttlGracePeriod;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||3600*1e3}async createEmailVerificationRegistration(e){try{let r=ae(),n=At(),i=ne(e.challenge.expiresAt),s=Math.floor((i+this.ttlGracePeriod)/1e3);return await this.docClient.send(new gR({TransactItems:[this.putItem(this.marshallProfile(e,r)),this.putItem(this.marshallUserAuth(e,r)),this.putItem(this.marshallIdentity(e,r)),this.putItem(this.marshallCredential(e,n,r)),this.putItem(this.marshallChallenge(e,r,s))]})),g(void 0)}catch(r){return Aa(r)==="TransactionCanceledException"||Pe(r)?u(M.UniqueConstraintViolation({field:"registration"})):u(M.DatabaseQueryError({query:"create email verification registration transaction"}))}}putItem(e){return{Put:{TableName:this.tableName,Item:Ft(e),ConditionExpression:`attribute_not_exists(${f.PK})`}}}marshallProfile(e,r){let n=e.profile.status,i={[f.PK]:D.USER_PK(e.profile.id),[f.SK]:D.USER_PROFILE_SK(),userStatus:n,[f.CREATED_AT]:r,[f.UPDATED_AT]:r,[f.USER_STATUS_PK]:Ae.USER_STATUS_PK(n),[f.USER_STATUS_SK]:Ae.USER_STATUS_SK(e.profile.id)};return e.profile.contactEmail&&(i.contactEmail=e.profile.contactEmail),e.profile.contactPhone&&(i.contactPhone=e.profile.contactPhone),e.profile.username&&(i.username=e.profile.username),e.profile.displayName&&(i.displayName=e.profile.displayName),e.profile.givenName&&(i.givenName=e.profile.givenName),e.profile.familyName&&(i.familyName=e.profile.familyName),e.profile.avatarUrl&&(i.avatarUrl=e.profile.avatarUrl),e.profile.locale&&(i.locale=e.profile.locale),e.profile.metadata&&(i.metadata=JSON.stringify(e.profile.metadata)),i}marshallUserAuth(e,r){return{[f.PK]:D.USER_PK(e.userAuth.userId),[f.SK]:D.USER_AUTH_SK(),userStatus:e.userAuth.userStatus,mfaRequired:e.userAuth.mfaRequired,mfaMethods:e.userAuth.mfaMethods,[f.CREATED_AT]:r,[f.UPDATED_AT]:r}}marshallIdentity(e,r){let n=e.identity,i={[f.PK]:D.IDENTITY_PK(n.type,n.value),[f.SK]:D.IDENTITY_SK(),[f.IDENTITY_USER_PK]:D.USER_INDEX_PK(n.userId),[f.IDENTITY_USER_SK]:D.USER_INDEX_SK(n.type,n.value),[f.USER_ID]:n.userId,[f.LOGIN_ENABLED]:n.loginEnabled,[f.CREATED_AT]:r,[f.UPDATED_AT]:r,[f.PENDING_VERIFICATION]:Ft({...n.pendingVerification,expiresAt:ne(n.pendingVerification.expiresAt),resendAvailableAt:Nr(n.pendingVerification.resendAvailableAt)})},s=Nr(n.verifiedAt);return s!==null&&(i[f.VERIFIED_AT]=s),i[f.GUARDS]=n.guards??{},i}marshallCredential(e,r,n){let i=e.credential,s={[f.PK]:D.CREDENTIAL_PK(r),[f.SK]:D.CREDENTIAL_SK(),[f.CREDENTIAL_USER_PK]:D.USER_PK(i.userId),[f.CREDENTIAL_USER_SK]:D.CREDENTIAL_USER_SK(i.type,r),[f.USER_ID]:i.userId,[f.CREDENTIAL_VALUE]:i.value,[f.METADATA]:i.data,[f.REVOKED_AT]:i.revokedAt?ne(i.revokedAt):null,[f.CREATED_AT]:n,[f.UPDATED_AT]:n};return i.lastUsedAt&&(s[f.LAST_USED_AT]=ne(i.lastUsedAt)),s}marshallChallenge(e,r,n){let i=e.challenge,s={[f.PK]:D.CHALLENGE_PK(i.id),[f.SK]:D.CHALLENGE_SK(),[f.USER_ID]:i.userId,[f.PURPOSE]:i.purpose,[f.CHALLENGE_STATUS]:i.status,[f.EXPIRES_AT]:ne(i.expiresAt),[f.CREATED_AT]:r,[f.TTL]:n};return i.tenantId&&(s[f.TENANT_ID]=i.tenantId),i.phase&&(s[f.PHASE]=i.phase),i.allowedMethods&&i.allowedMethods.length>0&&(s[f.ALLOWED_METHODS]=i.allowedMethods),i.method&&(s[f.METHOD]=i.method),i.codeHash&&(s[f.CODE_HASH]=i.codeHash),i.attempts!==void 0&&(s[f.ATTEMPTS]=i.attempts),i.maxAttempts!==void 0&&(s[f.MAX_ATTEMPTS]=i.maxAttempts),i.identityType&&(s[f.IDENTITY_TYPE]=i.identityType),i.identityValue&&(s[f.IDENTITY_VALUE]=i.identityValue),i.deviceLabel&&(s[f.DEVICE_LABEL]=i.deviceLabel),i.country&&(s[f.COUNTRY]=i.country),i.city&&(s[f.CITY]=i.city),i.metadata&&(s[f.METADATA]=i.metadata),i.flowKey&&(s[f.FLOW_KEY]=i.flowKey),s}};import{DynamoDBClient as TR}from"@aws-sdk/client-dynamodb";import{DynamoDBDocumentClient as IR,GetCommand as SA,PutCommand as _R,QueryCommand as ba,UpdateCommand as js}from"@aws-sdk/lib-dynamodb";import{BatchGetCommand as vR}from"@aws-sdk/lib-dynamodb";var xA=100,bA=5;function AR(t){return new Promise(e=>setTimeout(e,t))}async function qs(t,e,r){if(r.length===0)return[];let n=[];for(let i=0;i<r.length;i+=xA){let s=r.slice(i,i+xA),o=0;for(;s.length>0;){let a=await t.send(new vR({RequestItems:{[e]:{Keys:s}}})),c=a.Responses?.[e];c&&n.push(...c);let l=a.UnprocessedKeys?.[e]?.Keys;if(!l||l.length===0)break;if(o+=1,o>bA)throw new Error(`BatchGet left ${l.length} unprocessed keys after ${bA} retries`);s=l,await AR(2**o*25)}}return n}var Sa=class{docClient;tableName;ttlGracePeriod;constructor(e){let r=e.client||new TR({});this.docClient=e.docClient||IR.from(r),this.tableName=e.tableName,this.ttlGracePeriod=e.ttlGracePeriod||10080*60*1e3}generateSessionId(){return At()}generateTokenId(){return At()}async get(e){try{let r=await this.docClient.send(new SA({TableName:this.tableName,Key:{[f.PK]:D.SESSION_PK(e),[f.SK]:D.SESSION_SK()}}));return r.Item?g(this.unmarshall(r.Item)):g(null)}catch{return u(M.DatabaseQueryError({query:"get session"}))}}async create(e){try{let r=ae(),n=e.id||this.generateSessionId(),i=e.tokenId||this.generateTokenId(),s={...e,id:n,tokenId:i,revokedAt:null,createdAt:new Date(r),lastUsedAt:new Date(r)},o=ya(ne(e.expiresAt)+this.ttlGracePeriod),a=ql.sessionSK(r,n);return await this.docClient.send(new _R({TableName:this.tableName,Item:this.marshall(s,o,a)})),g(s)}catch{return u(M.DatabaseQueryError({query:"create session"}))}}async update(e,r){try{let n=[],i={},s={};if(r.tokenId!==void 0&&(n.push(`#${f.TOKEN_ID} = :tokenId`),i[`#${f.TOKEN_ID}`]=f.TOKEN_ID,s[":tokenId"]=r.tokenId),r.expiresAt!==void 0){n.push(`#${f.EXPIRES_AT} = :expiresAt`),i[`#${f.EXPIRES_AT}`]=f.EXPIRES_AT,s[":expiresAt"]=ne(r.expiresAt);let o=ya(ne(r.expiresAt)+this.ttlGracePeriod);n.push(`#${f.TTL} = :ttl`),i[`#${f.TTL}`]=f.TTL,s[":ttl"]=o}return r.lastUsedAt!==void 0&&(n.push(`#${f.LAST_USED_AT} = :lastUsedAt`),i[`#${f.LAST_USED_AT}`]=f.LAST_USED_AT,s[":lastUsedAt"]=ne(r.lastUsedAt)),r.metadata!==void 0&&(n.push(`#${f.METADATA} = :metadata`),i[`#${f.METADATA}`]=f.METADATA,s[":metadata"]=r.metadata),r.previousTokenId!==void 0&&(n.push(`#${f.PREVIOUS_TOKEN_ID} = :previousTokenId`),i[`#${f.PREVIOUS_TOKEN_ID}`]=f.PREVIOUS_TOKEN_ID,s[":previousTokenId"]=r.previousTokenId),r.rotatedAt!==void 0&&(n.push(`#${f.ROTATED_AT} = :rotatedAt`),i[`#${f.ROTATED_AT}`]=f.ROTATED_AT,s[":rotatedAt"]=r.rotatedAt),n.length===0?g():(await this.docClient.send(new js({TableName:this.tableName,Key:{[f.PK]:D.SESSION_PK(e),[f.SK]:D.SESSION_SK()},UpdateExpression:`SET ${n.join(", ")}`,ExpressionAttributeNames:i,ExpressionAttributeValues:s})),g())}catch{return u(M.DatabaseQueryError({query:"update session"}))}}async rotateToken(e,r,n){try{let i=ya(ne(n.expiresAt)+this.ttlGracePeriod);return await this.docClient.send(new js({TableName:this.tableName,Key:{[f.PK]:D.SESSION_PK(e),[f.SK]:D.SESSION_SK()},UpdateExpression:`SET #${f.TOKEN_ID} = :tokenId, #${f.PREVIOUS_TOKEN_ID} = :previousTokenId, #${f.ROTATED_AT} = :rotatedAt, #${f.EXPIRES_AT} = :expiresAt, #${f.LAST_USED_AT} = :lastUsedAt, #${f.TTL} = :ttl`,ConditionExpression:`#${f.TOKEN_ID} = :expectedCurrentTokenId`,ExpressionAttributeNames:{[`#${f.TOKEN_ID}`]:f.TOKEN_ID,[`#${f.PREVIOUS_TOKEN_ID}`]:f.PREVIOUS_TOKEN_ID,[`#${f.ROTATED_AT}`]:f.ROTATED_AT,[`#${f.EXPIRES_AT}`]:f.EXPIRES_AT,[`#${f.LAST_USED_AT}`]:f.LAST_USED_AT,[`#${f.TTL}`]:f.TTL},ExpressionAttributeValues:{":tokenId":n.tokenId,":previousTokenId":n.previousTokenId,":rotatedAt":n.rotatedAt,":expiresAt":ne(n.expiresAt),":lastUsedAt":ne(n.lastUsedAt),":ttl":i,":expectedCurrentTokenId":r}})),g(!0)}catch(i){return Pe(i)?g(!1):u(M.DatabaseQueryError({query:"rotate session token"}))}}async switchTenant(e,r){try{let n=[`#${f.TENANT_ID} = :tenantId`,`#${f.TOKEN_ID} = :tokenId`,`#${f.LAST_USED_AT} = :lastUsedAt`],i=[],s={[`#${f.TENANT_ID}`]:f.TENANT_ID,[`#${f.TOKEN_ID}`]:f.TOKEN_ID,[`#${f.LAST_USED_AT}`]:f.LAST_USED_AT},o={":tenantId":r.tenantId,":tokenId":r.tokenId,":lastUsedAt":ae()};s[`#${f.TENANT_TYPE}`]=f.TENANT_TYPE,r.tenantType!==void 0?(n.push(`#${f.TENANT_TYPE} = :tenantType`),o[":tenantType"]=r.tenantType):i.push(`#${f.TENANT_TYPE}`),s[`#${f.PERM}`]=f.PERM,r.perms!==void 0?(n.push(`#${f.PERM} = :perms`),o[":perms"]=JSON.stringify(r.perms)):i.push(`#${f.PERM}`),s[`#${f.ROLES}`]=f.ROLES,r.roles!==void 0?(n.push(`#${f.ROLES} = :roles`),o[":roles"]=r.roles):i.push(`#${f.ROLES}`),s["#revokedAt"]=f.REVOKED_AT;let a=`SET ${n.join(", ")}${i.length>0?` REMOVE ${i.join(", ")}`:""}`;return await this.docClient.send(new js({TableName:this.tableName,Key:{[f.PK]:D.SESSION_PK(e),[f.SK]:D.SESSION_SK()},UpdateExpression:a,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:`attribute_exists(${f.PK}) AND attribute_not_exists(#revokedAt)`})),g()}catch(n){return Pe(n)?u(M.DatabaseQueryError({query:"switch tenant - session not found or revoked"})):u(M.DatabaseQueryError({query:"switch tenant"}))}}async revoke(e){try{return await this.docClient.send(new js({TableName:this.tableName,Key:{[f.PK]:D.SESSION_PK(e),[f.SK]:D.SESSION_SK()},UpdateExpression:`SET #${f.REVOKED_AT} = :revokedAt REMOVE #${f.ACTIVE_SESSION_PK}, #${f.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${f.REVOKED_AT}`]:f.REVOKED_AT,[`#${f.ACTIVE_SESSION_PK}`]:f.ACTIVE_SESSION_PK,[`#${f.ACTIVE_SESSION_SK}`]:f.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":ne(new Date)},ConditionExpression:`attribute_exists(${f.PK})`})),g()}catch(r){return Pe(r)?g():u(M.DatabaseQueryError({query:"revoke session"}))}}async revokeByIdAndUserId(e,r){try{return await this.docClient.send(new js({TableName:this.tableName,Key:{[f.PK]:D.SESSION_PK(e),[f.SK]:D.SESSION_SK()},UpdateExpression:`SET #${f.REVOKED_AT} = :revokedAt REMOVE #${f.ACTIVE_SESSION_PK}, #${f.ACTIVE_SESSION_SK}`,ConditionExpression:`#${f.USER_ID} = :userId AND attribute_not_exists(#${f.REVOKED_AT})`,ExpressionAttributeNames:{[`#${f.REVOKED_AT}`]:f.REVOKED_AT,[`#${f.USER_ID}`]:f.USER_ID,[`#${f.ACTIVE_SESSION_PK}`]:f.ACTIVE_SESSION_PK,[`#${f.ACTIVE_SESSION_SK}`]:f.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":ne(new Date),":userId":r}})),g()}catch(n){return Pe(n)?g():u(M.DatabaseQueryError({query:"revoke session by user"}))}}async findByUserId(e,r){try{let n=Math.min(r?.limit||50,100),i;if(r?.cursor)try{i=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))}catch{return u(M.DatabaseQueryError({query:"invalid pagination cursor"}))}let s=await this.docClient.send(new ba({TableName:this.tableName,IndexName:Se.USER_SESSIONS,KeyConditionExpression:`${f.USER_SESSION_PK} = :userPk`,ExpressionAttributeValues:{":userPk":D.USER_PK(e)},Limit:n,ExclusiveStartKey:i,ScanIndexForward:!1}));if(!s.Items||s.Items.length===0){let E={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!r?.cursor,cursor:null};return g([],{pagination:E})}let a=s.Items.map(E=>le.sessionId(E[f.PK])).map(E=>({[f.PK]:D.SESSION_PK(E),[f.SK]:D.SESSION_SK()})),l=(await qs(this.docClient,this.tableName,a)).map(E=>this.unmarshall(E)),d=!!s.LastEvaluatedKey,p=d?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null,m={type:"cursor",limit:n,count:l.length,hasNext:d,hasPrev:!!r?.cursor,cursor:p};return g(l,{pagination:m})}catch{return u(M.DatabaseQueryError({query:"find sessions by user"}))}}async findActiveByUserId(e,r){try{let n=Math.min(r?.limit||50,100),i;if(r?.cursor)try{i=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))}catch{return u(M.DatabaseQueryError({query:"invalid pagination cursor"}))}let s=await this.docClient.send(new ba({TableName:this.tableName,IndexName:Se.ACTIVE_SESSIONS,KeyConditionExpression:`${f.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Ae.ACTIVE_SESSION_PK(e)},Limit:n,ExclusiveStartKey:i,ScanIndexForward:!1}));if(!s.Items||s.Items.length===0){let E={type:"cursor",limit:n,count:0,hasNext:!1,hasPrev:!!r?.cursor,cursor:null};return g([],{pagination:E})}let a=s.Items.map(E=>le.sessionId(E[f.PK])).map(E=>({[f.PK]:D.SESSION_PK(E),[f.SK]:D.SESSION_SK()})),l=(await qs(this.docClient,this.tableName,a)).map(E=>this.unmarshall(E)),d=!!s.LastEvaluatedKey,p=d?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null,m={type:"cursor",limit:n,count:l.length,hasNext:d,hasPrev:!!r?.cursor,cursor:p};return g(l,{pagination:m})}catch{return u(M.DatabaseQueryError({query:"find active sessions by user"}))}}async getActiveSessionsForLimit(e){try{let r=await this.docClient.send(new ba({TableName:this.tableName,IndexName:Se.ACTIVE_SESSIONS,KeyConditionExpression:`${f.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Ae.ACTIVE_SESSION_PK(e)},ScanIndexForward:!0}));if(!r.Items||r.Items.length===0)return g([]);let n=r.Items.map(i=>{let s=le.sessionId(i[f.PK]),o=ql.extractCreatedAt(i[f.ACTIVE_SESSION_SK]);return{id:s,createdAt:new Date(o)}});return g(n)}catch{return u(M.DatabaseQueryError({query:"get active sessions for limit"}))}}async revokeSessionsByIds(e,r){if(e.length===0)return 0;let n=ne(new Date),i=await Promise.allSettled(e.map(o=>this.docClient.send(new js({TableName:this.tableName,Key:{[f.PK]:D.SESSION_PK(o),[f.SK]:D.SESSION_SK()},UpdateExpression:`SET #${f.REVOKED_AT} = :revokedAt REMOVE #${f.ACTIVE_SESSION_PK}, #${f.ACTIVE_SESSION_SK}`,ExpressionAttributeNames:{[`#${f.REVOKED_AT}`]:f.REVOKED_AT,[`#${f.ACTIVE_SESSION_PK}`]:f.ACTIVE_SESSION_PK,[`#${f.ACTIVE_SESSION_SK}`]:f.ACTIVE_SESSION_SK},ExpressionAttributeValues:{":revokedAt":n}})))),s=0;for(let o of i)o.status==="fulfilled"?s+=1:console.error(`[session-repo] ${r}: session revoke failed (may remain active):`,{name:Aa(o.reason)});return s}async revokeAllByUserId(e,r){try{let n=await this.docClient.send(new ba({TableName:this.tableName,IndexName:Se.ACTIVE_SESSIONS,KeyConditionExpression:`${f.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Ae.ACTIVE_SESSION_PK(e)}}));if(!n.Items||n.Items.length===0)return g(0);let i=n.Items.map(o=>le.sessionId(o[f.PK])).filter(o=>!r||o!==r),s=await this.revokeSessionsByIds(i,"revokeAllByUserId");return g(s)}catch{return u(M.DatabaseQueryError({query:"revoke all sessions by user"}))}}async revokeBatch(e){try{let r=await this.revokeSessionsByIds(e,"revokeBatch");return g(r)}catch{return u(M.DatabaseQueryError({query:"revoke batch sessions"}))}}async countByUserId(e){try{let r=await this.docClient.send(new ba({TableName:this.tableName,IndexName:Se.ACTIVE_SESSIONS,KeyConditionExpression:`${f.ACTIVE_SESSION_PK} = :activePk`,ExpressionAttributeValues:{":activePk":Ae.ACTIVE_SESSION_PK(e)},Select:"COUNT"}));return g(r.Count||0)}catch{return u(M.DatabaseQueryError({query:"count active sessions by user"}))}}async isTokenActive(e,r){try{let n=await this.docClient.send(new SA({TableName:this.tableName,Key:{[f.PK]:D.SESSION_PK(r),[f.SK]:D.SESSION_SK()},ProjectionExpression:`${f.TOKEN_ID}, ${f.REVOKED_AT}, ${f.EXPIRES_AT}`}));if(!n.Item)return g(!1);let i=n.Item,s=i[f.TOKEN_ID]===e&&!i[f.REVOKED_AT]&&z(i[f.EXPIRES_AT])>new Date;return g(s)}catch{return u(M.DatabaseQueryError({query:"check token active"}))}}marshall(e,r,n){let i={[f.PK]:D.SESSION_PK(e.id),[f.SK]:D.SESSION_SK(),[f.USER_SESSION_PK]:D.USER_PK(e.userId),[f.USER_SESSION_SK]:n,...!e.revokedAt&&{[f.ACTIVE_SESSION_PK]:Ae.ACTIVE_SESSION_PK(e.userId),[f.ACTIVE_SESSION_SK]:n},[f.USER_ID]:e.userId,[f.TOKEN_ID]:e.tokenId,[f.EXPIRES_AT]:ne(e.expiresAt),[f.CREATED_AT]:ne(e.createdAt),[f.LAST_USED_AT]:ne(e.lastUsedAt),[f.TTL]:r};return e.tenantId&&(i[f.TENANT_ID]=e.tenantId),e.tenantType&&(i[f.TENANT_TYPE]=e.tenantType),e.perms!==void 0&&(i[f.PERM]=JSON.stringify(e.perms)),e.roles!==void 0&&(i[f.ROLES]=e.roles),e.deviceLabel&&(i[f.DEVICE_LABEL]=e.deviceLabel),e.country&&(i[f.COUNTRY]=e.country),e.city&&(i[f.CITY]=e.city),e.metadata&&(i[f.METADATA]=e.metadata),e.revokedAt&&(i[f.REVOKED_AT]=ne(e.revokedAt)),e.previousTokenId&&(i[f.PREVIOUS_TOKEN_ID]=e.previousTokenId),e.rotatedAt!==void 0&&(i[f.ROTATED_AT]=e.rotatedAt),i}unmarshall(e){let n={id:le.sessionId(e[f.PK]),userId:e[f.USER_ID],tokenId:e[f.TOKEN_ID],expiresAt:z(e[f.EXPIRES_AT]),createdAt:z(e[f.CREATED_AT]),lastUsedAt:z(e[f.LAST_USED_AT]),revokedAt:e[f.REVOKED_AT]?z(e[f.REVOKED_AT]):null};return e[f.TENANT_ID]&&(n.tenantId=e[f.TENANT_ID]),e[f.TENANT_TYPE]&&(n.tenantType=e[f.TENANT_TYPE]),e[f.PERM]!==void 0&&(n.perms=JSON.parse(e[f.PERM])),e[f.ROLES]!==void 0&&(n.roles=e[f.ROLES]),e[f.DEVICE_LABEL]&&(n.deviceLabel=e[f.DEVICE_LABEL]),e[f.COUNTRY]&&(n.country=e[f.COUNTRY]),e[f.CITY]&&(n.city=e[f.CITY]),e[f.METADATA]&&(n.metadata=e[f.METADATA]),e[f.PREVIOUS_TOKEN_ID]&&(n.previousTokenId=e[f.PREVIOUS_TOKEN_ID]),e[f.ROTATED_AT]!==void 0&&(n.rotatedAt=e[f.ROTATED_AT]),n}};import{QueryCommand as xR}from"@aws-sdk/lib-dynamodb";var Na=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={"#pk":f.INVITE_TENANT_PK},s={":pk":Ae.INVITE_TENANT_PK(e)},o={TableName:this.tableName,IndexName:Se.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:i,ExpressionAttributeValues:s,ScanIndexForward:!1,Limit:n};r?.cursor&&(o.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))),r?.status&&(o.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",i["#sk"]=f.INVITE_TENANT_SK,s[":statusPrefix"]=Ae.INVITE_TENANT_STATUS_PREFIX(r.status));let a=await this.docClient.send(new xR(o)),c=(a.Items||[]).map(p=>this.toListItem(p)),l=!!a.LastEvaluatedKey,d=l?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return mr(c,{limit:n,hasNext:l,cursor:d,prevCursor:r?.cursor??null})}catch(n){return console.error("[DynamoDBTenantInviteQuery.listByTenant] Error:",n instanceof Error?n.message:n),u(M.DatabaseQueryError({query:"listByTenant query"}))}}toListItem(e){let r=le.inviteId(e.PK),n={id:e.invitedById};e.invitedByInfo&&(e.invitedByInfo.name&&(n.name=e.invitedByInfo.name),e.invitedByInfo.email&&(n.email=e.invitedByInfo.email),e.invitedByInfo.jobTitle&&(n.jobTitle=e.invitedByInfo.jobTitle));let i={id:r,tenantId:e.tenantId,invitedBy:n,status:e.inviteStatus,expiresAt:z(e.expiresAt),createdAt:z(e.createdAt),updatedAt:z(e.updatedAt)};return e.inviteeUserId&&(i.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(i.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(i.inviteePhone=e.inviteePhone),e.roles!==void 0&&(i.roles=e.roles),e.perms!==void 0&&(i.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(i.authPerm=e.authPerm),e.displayName&&(i.displayName=e.displayName),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.jobTitle&&(i.jobTitle=e.jobTitle),e.acceptedAt&&(i.acceptedAt=z(e.acceptedAt)),e.declinedAt&&(i.declinedAt=z(e.declinedAt)),e.revokedAt&&(i.revokedAt=z(e.revokedAt)),i}};import{GetCommand as NA,PutCommand as bR,QueryCommand as qn,UpdateCommand as SR}from"@aws-sdk/lib-dynamodb";var NR=10080*60*1e3,wa=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}mapItemToEntity(e){let n={id:le.inviteId(e.PK),tenantId:e.tenantId,invitedById:e.invitedById,tenantType:e.tenantType,status:e.inviteStatus,inviteToken:e.inviteToken,expiresAt:z(e.expiresAt),createdAt:z(e.createdAt),updatedAt:z(e.updatedAt)};e.inviteeUserId&&(n.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(n.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(n.inviteePhone=e.inviteePhone),e.roles!==void 0&&(n.roles=e.roles);let i=e[f.PERM];return i!==void 0&&(n.perms=JSON.parse(i)),e.authPerm!==void 0&&(n.authPerm=e.authPerm),e.displayName&&(n.displayName=e.displayName),e.givenName&&(n.givenName=e.givenName),e.familyName&&(n.familyName=e.familyName),e.jobTitle&&(n.jobTitle=e.jobTitle),e.acceptedAt&&(n.acceptedAt=z(e.acceptedAt)),e.declinedAt&&(n.declinedAt=z(e.declinedAt)),e.revokedAt&&(n.revokedAt=z(e.revokedAt)),n}generateInviteId(){return At()}async getById(e){try{let r=await this.docClient.send(new NA({TableName:this.tableName,Key:{PK:D.INVITE_PK(e),SK:D.INVITE_SK()}}));return r.Item?g(this.mapItemToEntity(r.Item)):g(null)}catch{return u(M.DatabaseQueryError({query:"getById invite"}))}}async getByToken(e){try{let n=(await this.docClient.send(new qn({TableName:this.tableName,IndexName:Se.INVITE_TOKEN,KeyConditionExpression:"#inviteTokenGsi = :token",ExpressionAttributeNames:{"#inviteTokenGsi":f.INVITE_TOKEN_GSI},ExpressionAttributeValues:{":token":e},Limit:1}))).Items;if(!n||n.length===0)return g(null);let i=n[0],s=await this.docClient.send(new NA({TableName:this.tableName,Key:{PK:i.PK,SK:i.SK}}));return s.Item?g(this.mapItemToEntity(s.Item)):g(null)}catch{return u(M.DatabaseQueryError({query:"getByToken invite"}))}}async create(e){try{let r=ae(),n=ne(e.expiresAt),i=Math.floor((n+NR)/1e3),s={PK:D.INVITE_PK(e.id),SK:D.INVITE_SK(),[f.TENANT_ID]:e.tenantId,tenantType:e.tenantType,[f.INVITED_BY_ID]:e.invitedById,[f.INVITE_STATUS]:e.status,[f.INVITE_TOKEN]:e.inviteToken,[f.EXPIRES_AT]:n,[f.CREATED_AT]:r,[f.UPDATED_AT]:r,[f.TTL]:i,[f.INVITE_TENANT_PK]:Ae.INVITE_TENANT_PK(e.tenantId),[f.INVITE_TENANT_SK]:Ae.INVITE_TENANT_SK(e.status,r,e.id),[f.INVITE_TOKEN_GSI]:e.inviteToken},o={};e.invitedByName&&(o.name=e.invitedByName),e.invitedByEmail&&(o.email=e.invitedByEmail),e.invitedByJobTitle&&(o.jobTitle=e.invitedByJobTitle),Object.keys(o).length>0&&(s[f.INVITED_BY_INFO]=o),e.inviteeUserId&&(s[f.INVITEE_USER_ID]=e.inviteeUserId),e.inviteeEmail&&(s[f.INVITEE_EMAIL]=e.inviteeEmail,s[f.INVITEE_EMAIL_GSI]=e.inviteeEmail,s[f.INVITEE_EMAIL_TENANT_SK]=`${ce.TENANT}${e.tenantId}`),e.inviteePhone&&(s[f.INVITEE_PHONE]=e.inviteePhone,s[f.INVITEE_PHONE_GSI]=e.inviteePhone,s[f.INVITEE_PHONE_TENANT_SK]=`${ce.TENANT}${e.tenantId}`),e.roles!==void 0&&(s[f.ROLES]=e.roles),e.perms!==void 0&&(s[f.PERM]=JSON.stringify(e.perms)),e.authPerm!==void 0&&(s[f.AUTH_PERM]=e.authPerm),e.displayName&&(s[f.DISPLAY_NAME]=e.displayName),e.givenName&&(s.givenName=e.givenName),e.familyName&&(s.familyName=e.familyName),e.jobTitle&&(s.jobTitle=e.jobTitle),await this.docClient.send(new bR({TableName:this.tableName,Item:s,ConditionExpression:"attribute_not_exists(PK)"}));let a={id:e.id,tenantId:e.tenantId,invitedById:e.invitedById,tenantType:e.tenantType,status:e.status,inviteToken:e.inviteToken,expiresAt:e.expiresAt,createdAt:z(r),updatedAt:z(r)};return e.inviteeUserId&&(a.inviteeUserId=e.inviteeUserId),e.inviteeEmail&&(a.inviteeEmail=e.inviteeEmail),e.inviteePhone&&(a.inviteePhone=e.inviteePhone),e.roles!==void 0&&(a.roles=e.roles),e.perms!==void 0&&(a.perms=e.perms),e.authPerm!==void 0&&(a.authPerm=e.authPerm),e.displayName&&(a.displayName=e.displayName),e.givenName&&(a.givenName=e.givenName),e.familyName&&(a.familyName=e.familyName),e.jobTitle&&(a.jobTitle=e.jobTitle),g(a)}catch(r){return r.name==="ConditionalCheckFailedException"?u(M.UniqueConstraintViolation({field:"invite id"})):u(M.UnknownError({message:r.message}))}}async updateStatus(e,r){try{let n=ae(),i=["#inviteStatus = :inviteStatus","#inviteTenantSk = :inviteTenantSk","#updatedAt = :updatedAt"],s={"#inviteStatus":f.INVITE_STATUS,"#inviteTenantSk":f.INVITE_TENANT_SK,"#updatedAt":f.UPDATED_AT},o={":inviteStatus":r.status,":inviteTenantSk":Ae.INVITE_TENANT_SK(r.status,n,e),":updatedAt":n};r.acceptedAt&&(i.push("#acceptedAt = :acceptedAt"),s["#acceptedAt"]=f.ACCEPTED_AT,o[":acceptedAt"]=ne(r.acceptedAt)),r.declinedAt&&(i.push("#declinedAt = :declinedAt"),s["#declinedAt"]=f.DECLINED_AT,o[":declinedAt"]=ne(r.declinedAt)),r.revokedAt&&(i.push("#revokedAt = :revokedAt"),s["#revokedAt"]=f.REVOKED_AT,o[":revokedAt"]=ne(r.revokedAt));let a=[];r.status!=="pending"&&(a.push("#inviteTokenGsi","#inviteeEmailGsi","#inviteeEmailTenantSk","#inviteePhoneGsi","#inviteePhoneTenantSk"),s["#inviteTokenGsi"]=f.INVITE_TOKEN_GSI,s["#inviteeEmailGsi"]=f.INVITEE_EMAIL_GSI,s["#inviteeEmailTenantSk"]=f.INVITEE_EMAIL_TENANT_SK,s["#inviteePhoneGsi"]=f.INVITEE_PHONE_GSI,s["#inviteePhoneTenantSk"]=f.INVITEE_PHONE_TENANT_SK);let c=`SET ${i.join(", ")}`;return a.length>0&&(c+=` REMOVE ${a.join(", ")}`),await this.docClient.send(new SR({TableName:this.tableName,Key:{PK:D.INVITE_PK(e),SK:D.INVITE_SK()},UpdateExpression:c,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:"attribute_exists(PK)"})),g(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?u(M.NotFound({entity:"TenantInvite",id:e})):u(M.UnknownError({message:n.message}))}}async findByTenantAndEmail(e,r){try{let i=(await this.docClient.send(new qn({TableName:this.tableName,IndexName:Se.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email AND #inviteeEmailTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteeEmailGsi":f.INVITEE_EMAIL_GSI,"#inviteeEmailTenantSk":f.INVITEE_EMAIL_TENANT_SK},ExpressionAttributeValues:{":email":r,":tenantSk":`${ce.TENANT}${e}`},Limit:1}))).Items;return!i||i.length===0?g(null):g(this.mapItemToEntity(i[0]))}catch{return u(M.DatabaseQueryError({query:"findByTenantAndEmail"}))}}async findByTenantAndPhone(e,r){try{let i=(await this.docClient.send(new qn({TableName:this.tableName,IndexName:Se.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone AND #inviteePhoneTenantSk = :tenantSk",ExpressionAttributeNames:{"#inviteePhoneGsi":f.INVITEE_PHONE_GSI,"#inviteePhoneTenantSk":f.INVITEE_PHONE_TENANT_SK},ExpressionAttributeValues:{":phone":r,":tenantSk":`${ce.TENANT}${e}`},Limit:1}))).Items;return!i||i.length===0?g(null):g(this.mapItemToEntity(i[0]))}catch{return u(M.DatabaseQueryError({query:"findByTenantAndPhone"}))}}async findByTenantAndUserId(e,r){try{let i=(await this.docClient.send(new qn({TableName:this.tableName,IndexName:Se.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",FilterExpression:"#inviteeUserId = :userId",ExpressionAttributeNames:{"#pk":f.INVITE_TENANT_PK,"#sk":f.INVITE_TENANT_SK,"#inviteeUserId":f.INVITEE_USER_ID},ExpressionAttributeValues:{":pk":Ae.INVITE_TENANT_PK(e),":pendingPrefix":Ae.INVITE_TENANT_STATUS_PREFIX("pending"),":userId":r},Limit:1}))).Items;return!i||i.length===0?g(null):g(this.mapItemToEntity(i[0]))}catch{return u(M.DatabaseQueryError({query:"findByTenantAndUserId"}))}}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={"#pk":f.INVITE_TENANT_PK},s={":pk":Ae.INVITE_TENANT_PK(e)},o={TableName:this.tableName,IndexName:Se.TENANT_INVITES,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:i,ExpressionAttributeValues:s,ScanIndexForward:!1,Limit:n};r?.cursor&&(o.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))),r?.status&&(o.KeyConditionExpression="#pk = :pk AND begins_with(#sk, :statusPrefix)",i["#sk"]=f.INVITE_TENANT_SK,s[":statusPrefix"]=Ae.INVITE_TENANT_STATUS_PREFIX(r.status));let a=await this.docClient.send(new qn(o)),c=(a.Items||[]).map(p=>this.mapItemToEntity(p)),l=!!a.LastEvaluatedKey,d=l?Buffer.from(JSON.stringify(a.LastEvaluatedKey)).toString("base64url"):null;return mr(c,{limit:n,hasNext:l,cursor:d,prevCursor:r?.cursor??null})}catch{return u(M.DatabaseQueryError({query:"listByTenant"}))}}async findPendingByEmail(e){try{let r=ae(),i=(await this.docClient.send(new qn({TableName:this.tableName,IndexName:Se.INVITEE_EMAIL,KeyConditionExpression:"#inviteeEmailGsi = :email",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteeEmailGsi":f.INVITEE_EMAIL_GSI,"#expiresAt":f.EXPIRES_AT},ExpressionAttributeValues:{":email":e,":now":r}}))).Items||[];if(i.length===0)return g([]);let s=i.map(c=>({PK:c.PK,SK:c.SK})),a=(await qs(this.docClient,this.tableName,s)).map(c=>this.mapItemToEntity(c));return g(a)}catch{return u(M.DatabaseQueryError({query:"findPendingByEmail"}))}}async findPendingByPhone(e){try{let r=ae(),i=(await this.docClient.send(new qn({TableName:this.tableName,IndexName:Se.INVITEE_PHONE,KeyConditionExpression:"#inviteePhoneGsi = :phone",FilterExpression:"#expiresAt > :now",ProjectionExpression:"PK, SK",ExpressionAttributeNames:{"#inviteePhoneGsi":f.INVITEE_PHONE_GSI,"#expiresAt":f.EXPIRES_AT},ExpressionAttributeValues:{":phone":e,":now":r}}))).Items||[];if(i.length===0)return g([]);let s=i.map(c=>({PK:c.PK,SK:c.SK})),a=(await qs(this.docClient,this.tableName,s)).map(c=>this.mapItemToEntity(c));return g(a)}catch{return u(M.DatabaseQueryError({query:"findPendingByPhone"}))}}async countPendingByTenant(e){try{let r=await this.docClient.send(new qn({TableName:this.tableName,IndexName:Se.TENANT_INVITES,KeyConditionExpression:"#pk = :pk AND begins_with(#sk, :pendingPrefix)",ExpressionAttributeNames:{"#pk":f.INVITE_TENANT_PK,"#sk":f.INVITE_TENANT_SK},ExpressionAttributeValues:{":pk":Ae.INVITE_TENANT_PK(e),":pendingPrefix":Ae.INVITE_TENANT_STATUS_PREFIX("pending")},Select:"COUNT"}));return g(r.Count??0)}catch{return u(M.DatabaseQueryError({query:"countPendingByTenant"}))}}async expireOld(e){return g(0)}};import{QueryCommand as wR}from"@aws-sdk/lib-dynamodb";var Ra=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={TableName:this.tableName,KeyConditionExpression:"PK = :pk",ExpressionAttributeValues:{":pk":D.TENANT_MEMBER_PK(e)}};r?.cursor&&(i.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let o=(await this.docClient.send(new wR(i))).Items||[],a=[],c=new Map;for(let E of o){let v=E.SK;if(v.startsWith(Ve.TENANT_PROFILE)){let b=le.tenantProfileUserId(v);c.set(b,E)}else v.startsWith(ce.USER)&&a.push(E)}a.sort((E,v)=>v.createdAt-E.createdAt);let l=a.slice(0,n),d=a.length>n,p=l.map(E=>{let v=le.tenantMemberUserId(E.SK),b=c.get(v);return this.toListItem(E,e,v,b)}),m=d&&l.length>0?Buffer.from(JSON.stringify({PK:l[l.length-1].PK,SK:l[l.length-1].SK})).toString("base64url"):null;return mr(p,{limit:n,hasNext:d,cursor:m,prevCursor:r?.cursor??null})}catch{return u(M.DatabaseQueryError({query:"listByTenant query"}))}}toListItem(e,r,n,i){let s={tenantId:r,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:z(e.createdAt),updatedAt:z(e.updatedAt)};if(e.roles!==void 0&&(s.roles=e.roles),e.perms!==void 0&&(s.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(s.authPerm=e.authPerm),i){let o={tenantId:r,userId:n,createdAt:z(i.createdAt),updatedAt:z(i.updatedAt)};i.contactEmail&&(o.contactEmail=i.contactEmail),i.contactPhone&&(o.contactPhone=i.contactPhone),i.displayName&&(o.displayName=i.displayName),i.displayNameSource&&(o.displayNameSource=i.displayNameSource),i.givenName&&(o.givenName=i.givenName),i.familyName&&(o.familyName=i.familyName),i.avatarUrl&&(o.avatarUrl=i.avatarUrl),i.locale&&(o.locale=i.locale),i.jobTitle&&(o.jobTitle=i.jobTitle),i.bio&&(o.bio=i.bio),i.metadata&&(o.metadata=JSON.parse(i.metadata)),s.tenantProfile=o}return s}};import{DeleteCommand as RR,DynamoDBDocumentClient as OR,GetCommand as wA,PutCommand as kR,QueryCommand as CR,TransactWriteCommand as DR,UpdateCommand as RA}from"@aws-sdk/lib-dynamodb";var Oa=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=OR.from(e)}mapItemToEntity(e){let r=le.tenantId(e.PK),n=le.tenantMemberUserId(e.SK),i={tenantId:r,userId:n,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:z(e.createdAt),updatedAt:z(e.updatedAt)};return e.roles!==void 0&&(i.roles=e.roles),e.perms!==void 0&&(i.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(i.authPerm=e.authPerm),i}async get(e,r){try{let n=await this.docClient.send(new wA({TableName:this.tableName,Key:{PK:D.TENANT_MEMBER_PK(e),SK:D.TENANT_MEMBER_SK(r)}}));if(!n.Item)return g(null);let i=this.mapItemToEntity(n.Item);return g(i)}catch{return u(M.DatabaseQueryError({query:"get"}))}}async create(e){try{let r=ae(),n=e.isOwner?void 0:e.authPerm,i=Ft({PK:D.TENANT_MEMBER_PK(e.tenantId),SK:D.TENANT_MEMBER_SK(e.userId),userStatus:e.status,roles:e.roles,perms:e.perms!==void 0?JSON.stringify(e.perms):void 0,authPerm:n,isOwner:e.isOwner,createdAt:r,updatedAt:r,userTenantPk:Ae.USER_TENANT_PK(e.userId),userTenantSk:Ae.USER_TENANT_SK(e.tenantType??"org",e.parentTenantId,r,e.tenantId),parentTenantId:e.parentTenantId});return e.isOwner?await this.docClient.send(new DR({TransactItems:[{Put:{TableName:this.tableName,Item:{PK:D.TENANT_MEMBER_PK(e.tenantId),SK:D.TENANT_OWNER_MARKER_SK(),createdAt:r},ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}},{Put:{TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}}]})):await this.docClient.send(new kR({TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),g(void 0)}catch(r){return r.name==="TransactionCanceledException"?r.CancellationReasons?.[0]?.Code==="ConditionalCheckFailed"?u(M.UniqueConstraintViolation({field:"tenant owner"})):u(M.UniqueConstraintViolation({field:"tenant member"})):r.name==="ConditionalCheckFailedException"?u(M.UniqueConstraintViolation({field:"tenant member"})):u(M.UnknownError({message:r.message}))}}async updatePermissions(e,r,n){try{let i={...n,updatedAt:ae()},{UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=wr(i);return await this.docClient.send(new RA({TableName:this.tableName,Key:{PK:D.TENANT_MEMBER_PK(e),SK:D.TENANT_MEMBER_SK(r)},UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),g(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?u(M.NotFound({entity:"TenantMember",id:`${e}:${r}`})):u(M.UnknownError({message:i.message}))}}async updateStatus(e,r,n){try{return await this.docClient.send(new RA({TableName:this.tableName,Key:{PK:D.TENANT_MEMBER_PK(e),SK:D.TENANT_MEMBER_SK(r)},UpdateExpression:"SET #userStatus = :userStatus, #updatedAt = :updatedAt",ExpressionAttributeNames:{"#userStatus":"userStatus","#updatedAt":"updatedAt"},ExpressionAttributeValues:{":userStatus":n,":updatedAt":ae()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),g(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?u(M.NotFound({entity:"TenantMember",id:`${e}:${r}`})):u(M.UnknownError({message:i.message}))}}async listByTenant(e,r){try{let n=Math.min(r?.limit||50,100),i={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":D.TENANT_MEMBER_PK(e),":skPrefix":ce.USER},Limit:n};r?.cursor&&(i.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let s=await this.docClient.send(new CR(i)),o=(s.Items||[]).map(l=>this.mapItemToEntity(l)),a=!!s.LastEvaluatedKey,c=a?Buffer.from(JSON.stringify(s.LastEvaluatedKey)).toString("base64url"):null;return mr(o,{limit:n,hasNext:a,cursor:c,prevCursor:r?.cursor??null})}catch(n){let i=n instanceof Error?`${n.name}: ${n.message}`:String(n);return console.error("[DynamoDBTenantMemberRepository.listByTenant] Error:",i),u(M.DatabaseQueryError({query:`listByTenant \u2014 ${i}`}))}}async hasOwner(e){try{let r=await this.docClient.send(new wA({TableName:this.tableName,Key:{PK:D.TENANT_MEMBER_PK(e),SK:D.TENANT_OWNER_MARKER_SK()}}));return g(!!r.Item)}catch{return u(M.DatabaseQueryError({query:"hasOwner"}))}}async remove(e,r){try{return await this.docClient.send(new RR({TableName:this.tableName,Key:{PK:D.TENANT_MEMBER_PK(e),SK:D.TENANT_MEMBER_SK(r)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),g(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?u(M.NotFound({entity:"TenantMember",id:`${e}:${r}`})):u(M.UnknownError({message:n.message}))}}};import{BatchGetCommand as PR,QueryCommand as UR}from"@aws-sdk/lib-dynamodb";var ka=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async listByUser(e,r){try{let n=Math.min(r?.limit??50,100),i=r?.tenantType??Zt.DEFAULT,s=r?.parentTenantId,o=s?`${i}#${s}#`:`${i}#`,a={TableName:this.tableName,IndexName:Se.USER_TENANTS,KeyConditionExpression:"userTenantPk = :pk AND begins_with(userTenantSk, :skPrefix)",ExpressionAttributeValues:{":pk":Ae.USER_TENANT_PK(e),":skPrefix":o},ScanIndexForward:!1,Limit:n};r?.cursor&&(a.ExclusiveStartKey=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8")));let c=await this.docClient.send(new UR(a)),l=c.Items??[],d=await this.fetchProfileMap(e,l),p=l.map(v=>this.toListItem(v,e,d)),m=!!c.LastEvaluatedKey,E=m?Buffer.from(JSON.stringify(c.LastEvaluatedKey)).toString("base64url"):null;return mr(p,{limit:n,hasNext:m,cursor:E,prevCursor:r?.cursor??null})}catch{return u(M.DatabaseQueryError({query:"listByUser query"}))}}async fetchProfileMap(e,r){let n=new Map;if(r.length===0)return n;let i=r.map(o=>({PK:D.TENANT_PROFILE_PK(le.tenantId(o.PK)),SK:D.TENANT_PROFILE_SK(e)})),s=await this.docClient.send(new PR({RequestItems:{[this.tableName]:{Keys:i}}}));for(let o of s.Responses?.[this.tableName]??[]){let a=o,c=le.tenantId(a.PK);n.set(c,a)}return n}toListItem(e,r,n){let i=le.tenantId(e.PK),s={tenantId:i,userId:r,status:e.userStatus,isOwner:e.isOwner===!0,createdAt:z(e.createdAt),updatedAt:z(e.updatedAt)};e.roles!==void 0&&(s.roles=e.roles),e.perms!==void 0&&(s.perms=JSON.parse(e.perms)),e.authPerm!==void 0&&(s.authPerm=e.authPerm);let o=n.get(i);return o&&(o.contactEmail&&(s.contactEmail=o.contactEmail),o.contactPhone&&(s.contactPhone=o.contactPhone),o.displayName&&(s.displayName=o.displayName),o.displayNameSource&&(s.displayNameSource=o.displayNameSource),o.givenName&&(s.givenName=o.givenName),o.familyName&&(s.familyName=o.familyName),o.avatarUrl&&(s.avatarUrl=o.avatarUrl),o.locale&&(s.locale=o.locale),o.jobTitle&&(s.jobTitle=o.jobTitle),o.bio&&(s.bio=o.bio),o.metadata&&(s.metadata=JSON.parse(o.metadata))),s}};import{DeleteCommand as LR,GetCommand as MR,PutCommand as KR,UpdateCommand as HR}from"@aws-sdk/lib-dynamodb";var Ca=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}generateTenantId(){return At()}toEntity(e){let n={id:le.tenantId(e.PK),type:e.tenantType,ownerId:e.ownerId,createdAt:z(e.createdAt),updatedAt:z(e.updatedAt)};return e.parentTenantId&&(n.parentTenantId=e.parentTenantId),n}async get(e){try{let r=await this.docClient.send(new MR({TableName:this.tableName,Key:{PK:D.TENANT_PK(e),SK:D.TENANT_SK()}}));return r.Item?g(this.toEntity(r.Item)):g(null)}catch{return u(M.DatabaseQueryError({query:"get tenant"}))}}async create(e){try{let r=e.id??this.generateTenantId(),n=ae(),i=Ft({PK:D.TENANT_PK(r),SK:D.TENANT_SK(),tenantType:e.type,parentTenantId:e.parentTenantId,ownerId:e.ownerId,createdAt:n,updatedAt:n});return await this.docClient.send(new KR({TableName:this.tableName,Item:i,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),g(void 0)}catch(r){return r.name==="ConditionalCheckFailedException"?u(M.UniqueConstraintViolation({field:"tenant"})):u(M.UnknownError({message:r.message}))}}async update(e,r){try{let n={updatedAt:ae()};r.type!==void 0&&(n.tenantType=r.type),r.ownerId!==void 0&&(n.ownerId=r.ownerId),r.parentTenantId!==void 0&&(n.parentTenantId=r.parentTenantId===null?void 0:r.parentTenantId);let{UpdateExpression:i,ExpressionAttributeNames:s,ExpressionAttributeValues:o}=wr(n);return await this.docClient.send(new HR({TableName:this.tableName,Key:{PK:D.TENANT_PK(e),SK:D.TENANT_SK()},UpdateExpression:i,ExpressionAttributeNames:s,ExpressionAttributeValues:o,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),g(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?u(M.NotFound({entity:"Tenant",id:e})):u(M.UnknownError({message:n.message}))}}async delete(e){try{return await this.docClient.send(new LR({TableName:this.tableName,Key:{PK:D.TENANT_PK(e),SK:D.TENANT_SK()},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),g(void 0)}catch(r){return r.name==="ConditionalCheckFailedException"?u(M.NotFound({entity:"Tenant",id:e})):u(M.UnknownError({message:r.message}))}}async list(){return u(M.InvalidData({reason:"DynamoDB tenant list requires a dedicated GSI; scan is disabled"}))}async listByParent(e){return u(M.InvalidData({reason:`DynamoDB tenant listByParent(${e}) requires a dedicated GSI; scan is disabled`}))}async listRoots(){return u(M.InvalidData({reason:"DynamoDB tenant listRoots requires a dedicated GSI; scan is disabled"}))}};import{DeleteCommand as FR,GetCommand as VR,PutCommand as BR,UpdateCommand as Wl}from"@aws-sdk/lib-dynamodb";var Da=class{docClient;tableName;constructor(e){this.docClient=e.docClient,this.tableName=e.tableName}async get(e){try{let r=await this.docClient.send(new VR({TableName:this.tableName,Key:{[f.PK]:D.USER_PK(e),[f.SK]:D.USER_AUTH_SK()}}));return r.Item?g(this.unmarshall(r.Item,e)):g(null)}catch{return u(M.DatabaseQueryError({query:"get user auth"}))}}async create(e){try{let r=ae(),n={...e,createdAt:new Date(r),updatedAt:new Date(r)};return await this.docClient.send(new BR({TableName:this.tableName,Item:this.marshall(n),ConditionExpression:`attribute_not_exists(${f.PK})`})),g(n)}catch(r){return Pe(r)?u(M.UniqueConstraintViolation({field:"userAuth"})):u(M.DatabaseQueryError({query:"create user auth"}))}}async updateStatus(e,r){try{let n=ae();return await this.docClient.send(new Wl({TableName:this.tableName,Key:{[f.PK]:D.USER_PK(e),[f.SK]:D.USER_AUTH_SK()},UpdateExpression:`SET #userStatus = :userStatus, #${f.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#userStatus":"userStatus",[`#${f.UPDATED_AT}`]:f.UPDATED_AT},ExpressionAttributeValues:{":userStatus":r,":updatedAt":n},ConditionExpression:`attribute_exists(${f.PK})`})),g(void 0)}catch(n){return Pe(n)?u(M.NotFound({entity:"userAuth",id:e})):u(M.DatabaseQueryError({query:"update user auth status"}))}}async updateMfaRequired(e,r){try{let n=ae();return await this.docClient.send(new Wl({TableName:this.tableName,Key:{[f.PK]:D.USER_PK(e),[f.SK]:D.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #${f.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired",[`#${f.UPDATED_AT}`]:f.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":r,":updatedAt":n},ConditionExpression:`attribute_exists(${f.PK})`})),g(void 0)}catch(n){return Pe(n)?u(M.NotFound({entity:"userAuth",id:e})):u(M.DatabaseQueryError({query:"update mfa required"}))}}async updateMfaMethods(e,r){try{let n=ae();return await this.docClient.send(new Wl({TableName:this.tableName,Key:{[f.PK]:D.USER_PK(e),[f.SK]:D.USER_AUTH_SK()},UpdateExpression:`SET #mfaMethods = :mfaMethods, #${f.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaMethods":"mfaMethods",[`#${f.UPDATED_AT}`]:f.UPDATED_AT},ExpressionAttributeValues:{":mfaMethods":r,":updatedAt":n},ConditionExpression:`attribute_exists(${f.PK})`})),g(void 0)}catch(n){return Pe(n)?u(M.NotFound({entity:"userAuth",id:e})):u(M.DatabaseQueryError({query:"update mfa methods"}))}}async updateMfaSettings(e,r){try{let n=ae();return await this.docClient.send(new Wl({TableName:this.tableName,Key:{[f.PK]:D.USER_PK(e),[f.SK]:D.USER_AUTH_SK()},UpdateExpression:`SET #mfaRequired = :mfaRequired, #mfaMethods = :mfaMethods, #${f.UPDATED_AT} = :updatedAt`,ExpressionAttributeNames:{"#mfaRequired":"mfaRequired","#mfaMethods":"mfaMethods",[`#${f.UPDATED_AT}`]:f.UPDATED_AT},ExpressionAttributeValues:{":mfaRequired":r.mfaRequired,":mfaMethods":r.mfaMethods,":updatedAt":n},ConditionExpression:`attribute_exists(${f.PK})`})),g(void 0)}catch(n){return Pe(n)?u(M.NotFound({entity:"userAuth",id:e})):u(M.DatabaseQueryError({query:"update mfa settings"}))}}async remove(e){try{return await this.docClient.send(new FR({TableName:this.tableName,Key:{[f.PK]:D.USER_PK(e),[f.SK]:D.USER_AUTH_SK()}})),g(void 0)}catch{return u(M.DatabaseQueryError({query:"remove user auth"}))}}marshall(e){return{[f.PK]:D.USER_PK(e.userId),[f.SK]:D.USER_AUTH_SK(),userStatus:e.userStatus,mfaRequired:e.mfaRequired,mfaMethods:e.mfaMethods,[f.CREATED_AT]:ne(e.createdAt),[f.UPDATED_AT]:ne(e.updatedAt)}}unmarshall(e,r){return{userId:r,userStatus:e.userStatus,mfaRequired:e.mfaRequired||!1,mfaMethods:e.mfaMethods||null,createdAt:z(e[f.CREATED_AT]),updatedAt:z(e[f.UPDATED_AT])}}};import{DynamoDBDocumentClient as qR,DeleteCommand as jR,GetCommand as GR,PutCommand as $R,QueryCommand as OA,UpdateCommand as Af}from"@aws-sdk/lib-dynamodb";function Gs(t,e){return e?D.USER_MFA_WITH_ID_SK(t,e):D.USER_MFA_SK(t)}var Pa=class{client;tableName;docClient;constructor(e,r){this.client=e,this.tableName=r,this.docClient=qR.from(e)}toDynamoDBItem(e){let r={PK:D.USER_PK(e.userId),SK:Gs(e.method,e.id),method:e.method,data:JSON.stringify(e.data),createdAt:Date.now(),failedAttempts:0};return e.label&&(r.label=e.label),e.verifiedAt&&(r.verifiedAt=e.verifiedAt.getTime()),e.metadata&&(r.metadata=JSON.stringify(e.metadata)),r}fromDynamoDBItem(e,r){let n=le.mfaSKInfo(e.SK),i={userId:r,method:e.method,data:JSON.parse(e.data),createdAt:z(e.createdAt),verifiedAt:Ht(e.verifiedAt)??null};return n?.id&&(i.id=n.id),e.label&&(i.label=e.label),e.failedAttempts!==void 0&&(i.failedAttempts=e.failedAttempts),e.lastFailedAt!==void 0&&(i.lastFailedAt=Ht(e.lastFailedAt)),e.lockedUntil!==void 0&&(i.lockedUntil=Ht(e.lockedUntil)),e.lastUsedAt!==void 0&&(i.lastUsedAt=Ht(e.lastUsedAt)),e.metadata&&(i.metadata=JSON.parse(e.metadata)),i}async get(e,r,n){try{let i=Gs(r,n),s=await this.docClient.send(new GR({TableName:this.tableName,Key:{PK:D.USER_PK(e),SK:i}}));return s.Item?g(this.fromDynamoDBItem(s.Item,e)):g(null)}catch(i){return console.error("DynamoDBUserMFAAuthenticatorRepository.get error:",i),u(M.DatabaseQueryError({query:"get MFA authenticator"}))}}async findByUserId(e){try{let r={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":D.USER_PK(e),":skPrefix":Ve.MFA}},s=((await this.docClient.send(new OA(r))).Items??[]).map(o=>this.fromDynamoDBItem(o,e));return g(s)}catch(r){return console.error("DynamoDBUserMFAAuthenticatorRepository.findByUserId error:",r),u(M.DatabaseQueryError({query:"find MFA authenticators by user"}))}}async findByUserIdAndMethod(e,r){try{let n={TableName:this.tableName,KeyConditionExpression:"PK = :pk AND begins_with(SK, :skPrefix)",ExpressionAttributeValues:{":pk":D.USER_PK(e),":skPrefix":`${Ve.MFA}${r}`}},o=((await this.docClient.send(new OA(n))).Items??[]).filter(a=>a.method===r).map(a=>this.fromDynamoDBItem(a,e));return g(o)}catch(n){return console.error("DynamoDBUserMFAAuthenticatorRepository.findByUserIdAndMethod error:",n),u(M.DatabaseQueryError({query:"find MFA authenticators by method"}))}}async create(e){try{let r={...e};e.id===void 0&&this.isMultiInstanceMethod(e.method)&&(r.id=At());let n=this.toDynamoDBItem(r);return await this.docClient.send(new $R({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"})),g(this.fromDynamoDBItem(n,e.userId))}catch(r){return Pe(r)?u(M.UniqueConstraintViolation({field:"MFA authenticator"})):(console.error("DynamoDBUserMFAAuthenticatorRepository.create error:",r),u(M.DatabaseQueryError({query:"create MFA authenticator"})))}}async update(e,r,n,i){try{let s=Gs(r,n),o=[],a={},c={};if(i.label!==void 0&&(o.push("#label = :label"),a["#label"]="label",c[":label"]=i.label),i.data!==void 0&&(o.push("#data = :data"),a["#data"]="data",c[":data"]=JSON.stringify(i.data)),i.verifiedAt!==void 0&&(o.push("#verifiedAt = :verifiedAt"),a["#verifiedAt"]="verifiedAt",c[":verifiedAt"]=i.verifiedAt instanceof Date?i.verifiedAt.getTime():i.verifiedAt===null?void 0:i.verifiedAt),i.lastUsedAt!==void 0&&(o.push("#lastUsedAt = :lastUsedAt"),a["#lastUsedAt"]="lastUsedAt",c[":lastUsedAt"]=i.lastUsedAt instanceof Date?i.lastUsedAt.getTime():i.lastUsedAt===null?void 0:i.lastUsedAt),i.failedAttempts!==void 0&&(o.push("#failedAttempts = :failedAttempts"),a["#failedAttempts"]="failedAttempts",c[":failedAttempts"]=i.failedAttempts),i.lastFailedAt!==void 0&&(o.push("#lastFailedAt = :lastFailedAt"),a["#lastFailedAt"]="lastFailedAt",c[":lastFailedAt"]=i.lastFailedAt instanceof Date?i.lastFailedAt.getTime():i.lastFailedAt===null?void 0:i.lastFailedAt),i.lockedUntil!==void 0&&(o.push("#lockedUntil = :lockedUntil"),a["#lockedUntil"]="lockedUntil",c[":lockedUntil"]=i.lockedUntil instanceof Date?i.lockedUntil.getTime():i.lockedUntil===null?void 0:i.lockedUntil),i.metadata!==void 0&&(o.push("#metadata = :metadata"),a["#metadata"]="metadata",c[":metadata"]=JSON.stringify(i.metadata)),o.length===0)return g(void 0);let l={TableName:this.tableName,Key:{PK:D.USER_PK(e),SK:s},UpdateExpression:`SET ${o.join(", ")}`,ExpressionAttributeNames:a,ExpressionAttributeValues:c};return await this.docClient.send(new Af(l)),g(void 0)}catch(s){return console.error("DynamoDBUserMFAAuthenticatorRepository.update error:",s),u(M.DatabaseQueryError({query:"update MFA authenticator"}))}}async remove(e,r,n){try{let i=Gs(r,n);return await this.docClient.send(new jR({TableName:this.tableName,Key:{PK:D.USER_PK(e),SK:i}})),g(void 0)}catch(i){return console.error("DynamoDBUserMFAAuthenticatorRepository.remove error:",i),u(M.DatabaseQueryError({query:"remove MFA authenticator"}))}}async incrementFailedAttempts(e,r,n,i,s){try{let o=Gs(r,n),a=Date.now(),c=["#failedAttempts = if_not_exists(#failedAttempts, :zero) + :inc","#lastFailedAt = :lastFailedAt"],l={"#failedAttempts":"failedAttempts","#lastFailedAt":"lastFailedAt"},d={":zero":0,":inc":1,":lastFailedAt":a};s!==null&&(c.push("#lockedUntil = if_not_exists(#lockedUntil, :lockedUntil)"),l["#lockedUntil"]="lockedUntil",d[":lockedUntil"]=a+s*60*1e3,d[":maxAttempts"]=i);let p={TableName:this.tableName,Key:{PK:D.USER_PK(e),SK:o},UpdateExpression:`SET ${c.join(", ")}`,ExpressionAttributeNames:l,ExpressionAttributeValues:d};return await this.docClient.send(new Af(p)),g(void 0)}catch(o){return console.error("DynamoDBUserMFAAuthenticatorRepository.incrementFailedAttempts error:",o),u(M.DatabaseQueryError({query:"increment failed attempts"}))}}async resetFailedAttempts(e,r,n){try{let i=Gs(r,n),s={TableName:this.tableName,Key:{PK:D.USER_PK(e),SK:i},UpdateExpression:"SET #failedAttempts = :zero REMOVE #lastFailedAt, #lockedUntil",ExpressionAttributeNames:{"#failedAttempts":"failedAttempts","#lastFailedAt":"lastFailedAt","#lockedUntil":"lockedUntil"},ExpressionAttributeValues:{":zero":0}};return await this.docClient.send(new Af(s)),g(void 0)}catch(i){return console.error("DynamoDBUserMFAAuthenticatorRepository.resetFailedAttempts error:",i),u(M.DatabaseQueryError({query:"reset failed attempts"}))}}async unlock(e,r,n){return this.resetFailedAttempts(e,r,n)}isMultiInstanceMethod(e){return["webauthn","passkey","hardware","backup"].includes(e)}};import{DeleteCommand as WR,DynamoDBDocumentClient as zR,GetCommand as JR,PutCommand as YR,QueryCommand as kA,UpdateCommand as CA}from"@aws-sdk/lib-dynamodb";var Ua=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=zR.from(e)}generateUserId(){return At()}async getById(e){try{let r=await this.docClient.send(new JR({TableName:this.tableName,Key:{PK:D.USER_PK(e),SK:D.USER_PROFILE_SK()}}));if(!r.Item)return g(null);let n=r.Item;if(n.deletedAt)return g(null);let s={id:le.userId(n.PK),status:n.userStatus,createdAt:z(n.createdAt),updatedAt:z(n.updatedAt),...n.deletedAt!==void 0&&{deletedAt:z(n.deletedAt)},...n.contactEmail!==void 0&&{contactEmail:n.contactEmail},...n.contactPhone!==void 0&&{contactPhone:n.contactPhone},...n.username!==void 0&&{username:n.username},...n.displayName!==void 0&&{displayName:n.displayName},...n.givenName!==void 0&&{givenName:n.givenName},...n.familyName!==void 0&&{familyName:n.familyName},...n.avatarUrl!==void 0&&{avatarUrl:n.avatarUrl},...n.locale!==void 0&&{locale:n.locale},...n.metadata!==void 0&&{metadata:JSON.parse(n.metadata)}};return g(s)}catch{return u(M.DatabaseQueryError({query:"getById user"}))}}async create(e){try{let r=ae(),n=e.id||this.generateUserId(),i=e.status||"pending",s={PK:D.USER_PK(n),SK:D.USER_PROFILE_SK(),userStatus:i,createdAt:r,updatedAt:r};e.contactEmail&&(s.contactEmail=e.contactEmail),e.contactPhone&&(s.contactPhone=e.contactPhone),e.username&&(s.username=e.username),e.displayName&&(s.displayName=e.displayName),e.givenName&&(s.givenName=e.givenName),e.familyName&&(s.familyName=e.familyName),e.avatarUrl&&(s.avatarUrl=e.avatarUrl),e.locale&&(s.locale=e.locale),e.metadata&&(s.metadata=JSON.stringify(e.metadata)),s[f.USER_STATUS_PK]=Ae.USER_STATUS_PK(i),s[f.USER_STATUS_SK]=Ae.USER_STATUS_SK(n),await this.docClient.send(new YR({TableName:this.tableName,Item:Ft(s),ConditionExpression:uf("PK")}));let o={id:n,status:i,createdAt:z(r),updatedAt:z(r),...e.contactEmail&&{contactEmail:e.contactEmail},...e.contactPhone&&{contactPhone:e.contactPhone},...e.username&&{username:e.username},...e.displayName&&{displayName:e.displayName},...e.givenName&&{givenName:e.givenName},...e.familyName&&{familyName:e.familyName},...e.avatarUrl&&{avatarUrl:e.avatarUrl},...e.locale&&{locale:e.locale},...e.metadata&&{metadata:e.metadata}};return g(o)}catch{return u(M.DatabaseQueryError({query:"create user"}))}}async updateProfile(e,r){try{let n=ae(),i={};if(r.contactEmail!==void 0&&(i.contactEmail=r.contactEmail),r.contactPhone!==void 0&&(i.contactPhone=r.contactPhone),r.displayName!==void 0&&(i.displayName=r.displayName),r.givenName!==void 0&&(i.givenName=r.givenName),r.familyName!==void 0&&(i.familyName=r.familyName),r.avatarUrl!==void 0&&(i.avatarUrl=r.avatarUrl),r.locale!==void 0&&(i.locale=r.locale),r.metadata!==void 0&&(i.metadata=JSON.stringify(r.metadata)),Object.keys(i).length===0)return g(void 0);i.updatedAt=n;let s=wr(i);return await this.docClient.send(new CA({TableName:this.tableName,Key:{PK:D.USER_PK(e),SK:D.USER_PROFILE_SK()},UpdateExpression:s.UpdateExpression,ExpressionAttributeNames:s.ExpressionAttributeNames,ExpressionAttributeValues:s.ExpressionAttributeValues})),g(void 0)}catch{return u(M.DatabaseQueryError({query:"updateProfile"}))}}async getByStatus(e,r){try{let n=Math.min(r?.limit||50,100),i;if(r?.cursor)try{i=JSON.parse(Buffer.from(r.cursor,"base64url").toString("utf-8"))}catch{return u(M.DatabaseQueryError({query:"invalid pagination cursor"}))}let s=Ae.USER_STATUS_PK(e),o=await this.docClient.send(new kA({TableName:this.tableName,IndexName:Se.USERS_BY_STATUS,KeyConditionExpression:`${f.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":s},Limit:n,ExclusiveStartKey:i})),a=[];if(o.Items&&o.Items.length>0)for(let d of o.Items){let p=le.userId(d.PK);a.push(p)}let c=!!o.LastEvaluatedKey,l=c?Buffer.from(JSON.stringify(o.LastEvaluatedKey)).toString("base64url"):null;return g(a,{pagination:{type:"cursor",limit:n,count:a.length,hasNext:c,hasPrev:!!r?.cursor,cursor:l}})}catch{return u(M.DatabaseQueryError({query:"get users by status"}))}}async countByStatus(e){try{let r=Ae.USER_STATUS_PK(e),n=await this.docClient.send(new kA({TableName:this.tableName,IndexName:Se.USERS_BY_STATUS,KeyConditionExpression:`${f.USER_STATUS_PK} = :statusPk`,ExpressionAttributeValues:{":statusPk":r},Select:"COUNT"}));return g(n.Count||0)}catch{return u(M.DatabaseQueryError({query:"count users by status"}))}}async syncAuthStatus(e,r){try{let n=ae(),i=`SET userStatus = :userStatus, #${f.UPDATED_AT} = :updatedAt, #${f.USER_STATUS_PK} = :statusPk, #${f.USER_STATUS_SK} = :statusSk`,s={":userStatus":r,":updatedAt":n,":statusPk":Ae.USER_STATUS_PK(r),":statusSk":Ae.USER_STATUS_SK(e)};return r===ye.DELETED?(i+=", deletedAt = :deletedAt",s[":deletedAt"]=n):i+=" REMOVE deletedAt",await this.docClient.send(new CA({TableName:this.tableName,Key:{PK:D.USER_PK(e),SK:D.USER_PROFILE_SK()},UpdateExpression:i,ExpressionAttributeNames:{[`#${f.UPDATED_AT}`]:f.UPDATED_AT,[`#${f.USER_STATUS_PK}`]:f.USER_STATUS_PK,[`#${f.USER_STATUS_SK}`]:f.USER_STATUS_SK},ExpressionAttributeValues:s,ConditionExpression:"attribute_exists(PK)"})),g(void 0)}catch(n){return Pe(n)?u(M.NotFound({entity:"userProfile",id:e})):u(M.DatabaseQueryError({query:"sync auth status"}))}}async remove(e){try{return await this.docClient.send(new WR({TableName:this.tableName,Key:{PK:D.USER_PK(e),SK:D.USER_PROFILE_SK()}})),g(void 0)}catch{return u(M.DatabaseQueryError({query:"remove user profile"}))}}};import{DeleteCommand as XR,DynamoDBDocumentClient as QR,GetCommand as ZR,PutCommand as e0,QueryCommand as t0,UpdateCommand as r0}from"@aws-sdk/lib-dynamodb";var La=class{tableName;docClient;constructor(e,r){this.tableName=r,this.docClient=QR.from(e)}mapItemToUserProviderLink(e){let r=le.providerPKInfo(e.PK);if(!r)throw new Error(`Invalid provider PK: ${e.PK}`);let n={userId:e.userId,provider:r.provider,externalId:r.externalId,createdAt:z(e.createdAt)};if(e.externalUsername&&(n.externalUsername=e.externalUsername),e.externalEmail&&(n.externalEmail=e.externalEmail),e.externalPhone&&(n.externalPhone=e.externalPhone),e.externalName&&(n.externalName=e.externalName),e.externalAvatarUrl&&(n.externalAvatarUrl=e.externalAvatarUrl),e.metadata)try{n.metadata=JSON.parse(e.metadata)}catch{}return n}mapUserProviderLinkToItem(e){let r=ae(),n={PK:D.PROVIDER_PK(e.provider,e.externalId),SK:D.PROVIDER_METADATA_SK(),userProviderPk:D.USER_PK(e.userId),userProviderSk:D.PROVIDER_PK(e.provider,e.externalId),userId:e.userId,createdAt:e.createdAt?ne(e.createdAt):r};return e.externalUsername&&(n.externalUsername=e.externalUsername),e.externalEmail&&(n.externalEmail=e.externalEmail),e.externalPhone&&(n.externalPhone=e.externalPhone),e.externalName&&(n.externalName=e.externalName),e.externalAvatarUrl&&(n.externalAvatarUrl=e.externalAvatarUrl),e.metadata&&(n.metadata=JSON.stringify(e.metadata)),Ft(n)}async findByProviderAndExternalId(e,r){try{let n=await this.docClient.send(new ZR({TableName:this.tableName,Key:{PK:D.PROVIDER_PK(e,r),SK:D.PROVIDER_METADATA_SK()}}));return n.Item?g(this.mapItemToUserProviderLink(n.Item)):g(null)}catch{return u(M.DatabaseQueryError({query:"find provider by external id"}))}}async findByUserId(e){try{let r=await this.docClient.send(new t0({TableName:this.tableName,IndexName:Se.USER_PROVIDERS,KeyConditionExpression:"#pk = :pk",ExpressionAttributeNames:{"#pk":f.USER_PROVIDER_PK},ExpressionAttributeValues:{":pk":D.USER_PK(e)}}));return!r.Items||r.Items.length===0?g([]):g(r.Items.map(n=>this.mapItemToUserProviderLink(n)))}catch{return u(M.DatabaseQueryError({query:"find providers by user id"}))}}async create(e){try{let r={...e,createdAt:new Date},n=this.mapUserProviderLinkToItem(r);return await this.docClient.send(new e0({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK)"})),g(this.mapItemToUserProviderLink(n))}catch(r){return Pe(r)?u(M.UniqueConstraintViolation({field:"provider connection",message:"Provider connection already exists"})):u(M.DatabaseQueryError({query:"create user provider"}))}}async update(e,r,n){try{let i={};if(n.externalUsername!==void 0&&(i.externalUsername=n.externalUsername),n.externalEmail!==void 0&&(i.externalEmail=n.externalEmail),n.externalPhone!==void 0&&(i.externalPhone=n.externalPhone),n.externalName!==void 0&&(i.externalName=n.externalName),n.externalAvatarUrl!==void 0&&(i.externalAvatarUrl=n.externalAvatarUrl),n.metadata!==void 0&&(i.metadata=JSON.stringify(n.metadata)),Object.keys(i).length===0)return g(void 0);let{UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=wr(i);return await this.docClient.send(new r0({TableName:this.tableName,Key:{PK:D.PROVIDER_PK(e,r),SK:D.PROVIDER_METADATA_SK()},UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a})),g(void 0)}catch{return u(M.DatabaseQueryError({query:"update user provider"}))}}async remove(e,r){try{return await this.docClient.send(new XR({TableName:this.tableName,Key:{PK:D.PROVIDER_PK(e,r),SK:D.PROVIDER_METADATA_SK()}})),g(void 0)}catch{return u(M.DatabaseQueryError({query:"delete user provider"}))}}};import{DeleteCommand as n0,GetCommand as i0,PutCommand as s0,UpdateCommand as o0}from"@aws-sdk/lib-dynamodb";var Ma=class{docClient;tableName;constructor(e,r){this.docClient=e,this.tableName=r}mapItemToEntity(e){let r=le.tenantId(e.PK),n=le.tenantProfileUserId(e.SK),i={tenantId:r,userId:n,createdAt:z(e.createdAt),updatedAt:z(e.updatedAt)};return e.contactEmail&&(i.contactEmail=e.contactEmail),e.contactPhone&&(i.contactPhone=e.contactPhone),e.displayName&&(i.displayName=e.displayName),e.displayNameSource&&(i.displayNameSource=e.displayNameSource),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.avatarUrl&&(i.avatarUrl=e.avatarUrl),e.locale&&(i.locale=e.locale),e.jobTitle&&(i.jobTitle=e.jobTitle),e.bio&&(i.bio=e.bio),e.metadata&&(i.metadata=JSON.parse(e.metadata)),i}async get(e,r){try{let n=await this.docClient.send(new i0({TableName:this.tableName,Key:{PK:D.TENANT_PROFILE_PK(e),SK:D.TENANT_PROFILE_SK(r)}}));return n.Item?g(this.mapItemToEntity(n.Item)):g(null)}catch{return u(M.DatabaseQueryError({query:"get user tenant profile"}))}}async create(e){try{let r=ae(),n={PK:D.TENANT_PROFILE_PK(e.tenantId),SK:D.TENANT_PROFILE_SK(e.userId),createdAt:r,updatedAt:r};e.contactEmail&&(n.contactEmail=e.contactEmail),e.contactPhone&&(n.contactPhone=e.contactPhone),e.displayName&&(n.displayName=e.displayName),e.displayNameSource&&(n.displayNameSource=e.displayNameSource),e.givenName&&(n.givenName=e.givenName),e.familyName&&(n.familyName=e.familyName),e.avatarUrl&&(n.avatarUrl=e.avatarUrl),e.locale&&(n.locale=e.locale),e.jobTitle&&(n.jobTitle=e.jobTitle),e.bio&&(n.bio=e.bio),e.metadata&&(n.metadata=JSON.stringify(e.metadata)),await this.docClient.send(new s0({TableName:this.tableName,Item:n,ConditionExpression:"attribute_not_exists(PK) AND attribute_not_exists(SK)"}));let i={tenantId:e.tenantId,userId:e.userId,createdAt:z(r),updatedAt:z(r)};return e.contactEmail&&(i.contactEmail=e.contactEmail),e.contactPhone&&(i.contactPhone=e.contactPhone),e.displayName&&(i.displayName=e.displayName),e.displayNameSource&&(i.displayNameSource=e.displayNameSource),e.givenName&&(i.givenName=e.givenName),e.familyName&&(i.familyName=e.familyName),e.avatarUrl&&(i.avatarUrl=e.avatarUrl),e.locale&&(i.locale=e.locale),e.jobTitle&&(i.jobTitle=e.jobTitle),e.bio&&(i.bio=e.bio),e.metadata&&(i.metadata=e.metadata),g(i)}catch(r){return r.name==="ConditionalCheckFailedException"?u(M.UniqueConstraintViolation({field:"user tenant profile"})):u(M.UnknownError({message:r.message}))}}async update(e,r,n){try{let i={updatedAt:ae()};n.contactEmail!==void 0&&(i.contactEmail=n.contactEmail),n.contactPhone!==void 0&&(i.contactPhone=n.contactPhone),n.displayName!==void 0&&(i.displayName=n.displayName),n.displayNameSource!==void 0&&(i.displayNameSource=n.displayNameSource),n.givenName!==void 0&&(i.givenName=n.givenName),n.familyName!==void 0&&(i.familyName=n.familyName),n.avatarUrl!==void 0&&(i.avatarUrl=n.avatarUrl),n.locale!==void 0&&(i.locale=n.locale),n.jobTitle!==void 0&&(i.jobTitle=n.jobTitle),n.bio!==void 0&&(i.bio=n.bio),n.metadata!==void 0&&(i.metadata=n.metadata?JSON.stringify(n.metadata):null);let{UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a}=wr(i);return await this.docClient.send(new o0({TableName:this.tableName,Key:{PK:D.TENANT_PROFILE_PK(e),SK:D.TENANT_PROFILE_SK(r)},UpdateExpression:s,ExpressionAttributeNames:o,ExpressionAttributeValues:a,ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),g(void 0)}catch(i){return i.name==="ConditionalCheckFailedException"?u(M.NotFound({entity:"UserTenantProfile",id:`${e}:${r}`})):u(M.UnknownError({message:i.message}))}}async remove(e,r){try{return await this.docClient.send(new n0({TableName:this.tableName,Key:{PK:D.TENANT_PROFILE_PK(e),SK:D.TENANT_PROFILE_SK(r)},ConditionExpression:"attribute_exists(PK) AND attribute_exists(SK)"})),g(void 0)}catch(n){return n.name==="ConditionalCheckFailedException"?u(M.NotFound({entity:"UserTenantProfile",id:`${e}:${r}`})):u(M.UnknownError({message:n.message}))}}};var Tf=class{name="database-dynamodb";version="1.0.0";users;sessions;userProviders;userMfaAuthenticators;challenges;identities;credentials;registration;userAuths;tenantMembers;tenantInvites;userTenantProfiles;tenants;queries;client;tableName;constructor(e){this.tableName=e.tableName,this.client=e.client||new c0(e.clientConfig||{});let r=l0.from(this.client,{marshallOptions:{removeUndefinedValues:!0,convertClassInstanceToMap:!0}});this.users=new Ua(this.client,this.tableName),this.sessions=new Sa({client:this.client,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userProviders=new La(this.client,this.tableName),this.userMfaAuthenticators=new Pa(this.client,this.tableName),this.challenges=new Ta({docClient:r,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.identities=new _a({docClient:r,tableName:this.tableName}),this.credentials=new Ia({docClient:r,tableName:this.tableName}),this.registration=new xa({docClient:r,tableName:this.tableName,ttlGracePeriod:3600*1e3}),this.userAuths=new Da({docClient:r,tableName:this.tableName}),this.tenantMembers=new Oa(this.client,this.tableName),this.tenantInvites=new wa({docClient:r,tableName:this.tableName}),this.userTenantProfiles=new Ma(r,this.tableName),this.tenants=new Ca({docClient:r,tableName:this.tableName}),this.queries={tenantInvites:new Na({docClient:r,tableName:this.tableName}),tenantMembers:new Ra({docClient:r,tableName:this.tableName}),tenants:new ka({docClient:r,tableName:this.tableName})}}async initialize(){}async health(){try{return await this.client.send(new a0({TableName:this.tableName})),!0}catch(e){return console.error("DynamoDB health check failed:",e),!1}}async cleanup(){this.client.destroy()}};function DA(t){return new Tf(t)}ho();var If=1,PA=2,UA=3,LA="auth-craft:internal";async function u0(t){let e=t.replace(/^0x/,""),r=KA(e),n=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length);let s=`-----BEGIN PRIVATE KEY-----
|
|
129
129
|
`+btoa(String.fromCharCode(...i)).match(/.{1,64}/g).join(`
|
|
130
130
|
`)+`
|
|
131
131
|
-----END PRIVATE KEY-----`;return ao(s,"EdDSA")}async function d0(t){let e=t.replace(/^0x/,""),r=KA(e),n=f0(r);return it({kty:"OKP",crv:"Ed25519",x:n},"EdDSA")}async function _f(t,e){if(e==="EdDSA"){let r=t.trim();if(r.startsWith("{"))return it(JSON.parse(r),e);if(!r.includes(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@auth-craft/aws-cf-stack",
|
|
3
|
-
"version": "1.6.
|
|
3
|
+
"version": "1.6.2",
|
|
4
4
|
"description": "Self-contained, versioned distribution of the Auth Craft AWS (DynamoDB + Lambda) + Cloudflare gateway stack. Bundles prebuilt Lambda/worker artifacts + CDK app so consumers deploy without cloning auth-craft.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|