@oddington/sdk 0.1.61 → 0.1.62
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.js +1 -1
- package/dist/index.js +1 -1
- package/dist/types/shared/connections.d.ts +1 -1
- package/package.json +1 -1
package/dist/browser.js
CHANGED
|
@@ -324,7 +324,7 @@ function validRecordRef(value) {
|
|
|
324
324
|
}
|
|
325
325
|
|
|
326
326
|
function validDropboxRootPath(value) {
|
|
327
|
-
return typeof value == "string" && value.length <= 2048 && value.startsWith("/") && !/[\\\x00-\x1f\x7f]/.test(value) && value.slice(1).split("/").every((segment) => segment.length > 0 && segment.trim() === segment && segment !== "." && segment !== "..");
|
|
327
|
+
return value === "" || typeof value == "string" && value.length <= 2048 && value.startsWith("/") && !/[\\\x00-\x1f\x7f]/.test(value) && value.slice(1).split("/").every((segment) => segment.length > 0 && segment.trim() === segment && segment !== "." && segment !== "..");
|
|
328
328
|
}
|
|
329
329
|
function validMicrosoftId(value) {
|
|
330
330
|
return typeof value == "string" && /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value);
|
package/dist/index.js
CHANGED
|
@@ -18,7 +18,7 @@ ${suffix}`}function identifyRegistrationError({error,options}){var _a,_b,_c;cons
|
|
|
18
18
|
`);const maybeSignature=await resolvedWallet.signMessage(new TextEncoder().encode(message),"utf8");if(!maybeSignature||!(maybeSignature instanceof Uint8Array)){throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value")}signature=maybeSignature}}try{const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message,signature:bytesToBase64URL(signature)},((_m=credentials.options)===null||_m===undefined?undefined:_m.captchaToken)?{gotrue_meta_security:{captcha_token:(_o=credentials.options)===null||_o===undefined?undefined:_o.captchaToken}}:null),xform:_sessionResponse});if(error){throw error}if(!data2||!data2.session||!data2.user){const invalidTokenError=new AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:invalidTokenError})}if(data2.session){await this._saveSession(data2.session);await this._notifyAllSubscribers("SIGNED_IN",data2.session)}return this._returnResult({data:Object.assign({},data2),error})}catch(error){if(isAuthError(error)){return this._returnResult({data:{user:null,session:null},error})}throw error}}async _exchangeCodeForSession(authCode,options){const hasExplicitFlowId=(options===null||options===undefined?undefined:options.flowId)!=null;const requestedFlowId=hasExplicitFlowId?validatePKCEFlowId(options===null||options===undefined?undefined:options.flowId):isBrowser()?validatePKCEFlowId(parseParametersFromURL(window.location.href)[PKCE_FLOW_ID_PARAM]):null;if(hasExplicitFlowId&&!requestedFlowId){this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",options===null||options===undefined?undefined:options.flowId)}const{verifier:storageItem,flowId}=hasExplicitFlowId&&!requestedFlowId?{verifier:null,flowId:null}:await retrievePKCEVerifier(this.storage,this.storageKey,requestedFlowId);const[codeVerifier,redirectType]=(storageItem!==null&&storageItem!==undefined?storageItem:"").split("/");try{if(!codeVerifier&&this.flowType==="pkce"){throw new AuthPKCECodeVerifierMissingError}const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:authCode,code_verifier:codeVerifier},xform:_sessionResponse});await removePKCEVerifier(this.storage,this.storageKey,flowId);if(error){throw error}if(!data2||!data2.session||!data2.user){const invalidTokenError=new AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null,redirectType:null},error:invalidTokenError})}if(data2.session){await this._saveSession(data2.session);await this._notifyAllSubscribers(redirectType==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",data2.session)}return this._returnResult({data:Object.assign(Object.assign({},data2),{redirectType:redirectType!==null&&redirectType!==undefined?redirectType:null}),error})}catch(error){await removePKCEVerifier(this.storage,this.storageKey,flowId);if(isAuthError(error)){return this._returnResult({data:{user:null,session:null,redirectType:null},error})}throw error}}async signInWithIdToken(credentials){try{const{options,provider,token,access_token,nonce}=credentials;const res=await _request(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider,id_token:token,access_token,nonce,gotrue_meta_security:{captcha_token:options===null||options===undefined?undefined:options.captchaToken}},xform:_sessionResponse});const{data:data2,error}=res;if(error){return this._returnResult({data:{user:null,session:null},error})}else if(!data2||!data2.session||!data2.user){const invalidTokenError=new AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:invalidTokenError})}if(data2.session){await this._saveSession(data2.session);await this._notifyAllSubscribers("SIGNED_IN",data2.session)}return this._returnResult({data:data2,error})}catch(error){if(isAuthError(error)){return this._returnResult({data:{user:null,session:null},error})}throw error}}async signInWithOtp(credentials){var _a,_b,_c,_d,_f;let flowId=null;try{if("email"in credentials){const{email,options}=credentials;let codeChallenge=null;let codeChallengeMethod=null;if(this.flowType==="pkce"){[codeChallenge,codeChallengeMethod,flowId]=await this._getCodeChallengeAndMethod()}const{error}=await _request(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email,data:(_a=options===null||options===undefined?undefined:options.data)!==null&&_a!==undefined?_a:{},create_user:(_b=options===null||options===undefined?undefined:options.shouldCreateUser)!==null&&_b!==undefined?_b:true,gotrue_meta_security:{captcha_token:options===null||options===undefined?undefined:options.captchaToken},code_challenge:codeChallenge,code_challenge_method:codeChallengeMethod},redirectTo:this._maybeAppendFlowIdToRedirect(options===null||options===undefined?undefined:options.emailRedirectTo,flowId)});return this._returnResult({data:{user:null,session:null},error})}if("phone"in credentials){const{phone,options}=credentials;const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone,data:(_c=options===null||options===undefined?undefined:options.data)!==null&&_c!==undefined?_c:{},create_user:(_d=options===null||options===undefined?undefined:options.shouldCreateUser)!==null&&_d!==undefined?_d:true,gotrue_meta_security:{captcha_token:options===null||options===undefined?undefined:options.captchaToken},channel:(_f=options===null||options===undefined?undefined:options.channel)!==null&&_f!==undefined?_f:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:data2===null||data2===undefined?undefined:data2.message_id},error})}throw new AuthInvalidCredentialsError("You must provide either an email or phone number.")}catch(error){await removePKCEVerifier(this.storage,this.storageKey,flowId);if(isAuthError(error)){return this._returnResult({data:{user:null,session:null},error})}throw error}}async verifyOtp(params){var _a,_b;try{let redirectTo=undefined;let captchaToken=undefined;if("options"in params){redirectTo=(_a=params.options)===null||_a===undefined?undefined:_a.redirectTo;captchaToken=(_b=params.options)===null||_b===undefined?undefined:_b.captchaToken}const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},params),{gotrue_meta_security:{captcha_token:captchaToken}}),redirectTo,xform:_sessionResponse});if(error){throw error}if(!data2){const tokenVerificationError=new Error("An error occurred on token verification.");throw tokenVerificationError}const session=data2.session;const user=data2.user;if(session===null||session===undefined?undefined:session.access_token){await this._saveSession(session);await this._notifyAllSubscribers(params.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",session)}return this._returnResult({data:{user,session},error:null})}catch(error){if(isAuthError(error)){return this._returnResult({data:{user:null,session:null},error})}throw error}}async signInWithSSO(params){var _a,_b,_c,_d;let flowId=null;try{let codeChallenge=null;let codeChallengeMethod=null;if(this.flowType==="pkce"){[codeChallenge,codeChallengeMethod,flowId]=await this._getCodeChallengeAndMethod()}const result2=await _request(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in params?{provider_id:params.providerId}:null),"domain"in params?{domain:params.domain}:null),{redirect_to:this._maybeAppendFlowIdToRedirect((_a=params.options)===null||_a===undefined?undefined:_a.redirectTo,flowId)}),((_b=params===null||params===undefined?undefined:params.options)===null||_b===undefined?undefined:_b.captchaToken)?{gotrue_meta_security:{captcha_token:params.options.captchaToken}}:null),{skip_http_redirect:true,code_challenge:codeChallenge,code_challenge_method:codeChallengeMethod}),headers:this.headers,xform:_ssoResponse});if(((_c=result2.data)===null||_c===undefined?undefined:_c.url)&&isBrowser()&&!((_d=params.options)===null||_d===undefined?undefined:_d.skipBrowserRedirect)){window.location.assign(result2.data.url)}return this._returnResult(result2)}catch(error){await removePKCEVerifier(this.storage,this.storageKey,flowId);if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async reauthenticate(){await this.initializePromise;if(this.lock!=null){return await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._reauthenticate()})}return await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError)throw sessionError;if(!session)throw new AuthSessionMissingError;const{error}=await _request(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:session.access_token});return this._returnResult({data:{user:null,session:null},error})})}catch(error){if(isAuthError(error)){return this._returnResult({data:{user:null,session:null},error})}throw error}}async resend(credentials){let flowId=null;try{const endpoint=`${this.url}/resend`;if("email"in credentials){const{email,type,options}=credentials;let codeChallenge=null;let codeChallengeMethod=null;if(this.flowType==="pkce"){[codeChallenge,codeChallengeMethod,flowId]=await this._getCodeChallengeAndMethod()}const{error}=await _request(this.fetch,"POST",endpoint,{headers:this.headers,body:{email,type,gotrue_meta_security:{captcha_token:options===null||options===undefined?undefined:options.captchaToken},code_challenge:codeChallenge,code_challenge_method:codeChallengeMethod},redirectTo:this._maybeAppendFlowIdToRedirect(options===null||options===undefined?undefined:options.emailRedirectTo,flowId)});if(error){await removePKCEVerifier(this.storage,this.storageKey,flowId)}return this._returnResult({data:{user:null,session:null},error})}else if("phone"in credentials){const{phone,type,options}=credentials;const{data:data2,error}=await _request(this.fetch,"POST",endpoint,{headers:this.headers,body:{phone,type,gotrue_meta_security:{captcha_token:options===null||options===undefined?undefined:options.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:data2===null||data2===undefined?undefined:data2.message_id},error})}throw new AuthInvalidCredentialsError("You must provide either an email or phone number and a type")}catch(error){await removePKCEVerifier(this.storage,this.storageKey,flowId);if(isAuthError(error)){return this._returnResult({data:{user:null,session:null},error})}throw error}}async getSession(){await this.initializePromise;if(this.lock!=null){return await this._acquireLock(this.lockAcquireTimeout,async()=>{return this._useSession(async(result2)=>{return result2})})}return await this._useSession(async(result2)=>{return result2})}async _acquireLock(acquireTimeout,fn){this._debug("#_acquireLock","begin",acquireTimeout);try{if(this.lockAcquired){const last=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve();const result2=(async()=>{await last;return await fn()})();this.pendingInLock.push((async()=>{try{await result2}catch(_e){}})());return result2}return await this.lock(`lock:${this.storageKey}`,acquireTimeout,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=true;const result2=fn();this.pendingInLock.push((async()=>{try{await result2}catch(e){}})());await result2;while(this.pendingInLock.length){const waitOn=[...this.pendingInLock];await Promise.all(waitOn);this.pendingInLock.splice(0,waitOn.length)}return await result2}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey);this.lockAcquired=false}})}finally{this._debug("#_acquireLock","end")}}async _useSession(fn){this._debug("#_useSession","begin");try{const result2=await this.__loadSession();return await fn(result2)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin");if(this.lock!=null&&!this.lockAcquired){this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack)}try{let currentSession=null;const maybeSession=await getItemAsync(this.storage,this.storageKey);this._debug("#getSession()","session from storage",maybeSession);if(maybeSession!==null){if(this._isValidSession(maybeSession)){currentSession=maybeSession}else{this._debug("#getSession()","session from storage is not valid");await this._removeSession()}}if(!currentSession){return{data:{session:null},error:null}}const hasExpired=currentSession.expires_at?currentSession.expires_at*1000-Date.now()<EXPIRY_MARGIN_MS:false;this._debug("#__loadSession()",`session has${hasExpired?"":" not"} expired`,"expires_at",currentSession.expires_at);if(!hasExpired){if(this.userStorage){const maybeUser=await getItemAsync(this.userStorage,this.storageKey+"-user");if(maybeUser===null||maybeUser===undefined?undefined:maybeUser.user){currentSession.user=maybeUser.user}else{currentSession.user=userNotAvailableProxy()}}if(this.storage.isServer&¤tSession.user&&!currentSession.user.__isUserNotAvailableProxy){const suppressWarningRef={value:this.suppressGetSessionWarning};currentSession.user=insecureUserWarningProxy(currentSession.user,suppressWarningRef);if(suppressWarningRef.value){this.suppressGetSessionWarning=true}}return{data:{session:currentSession},error:null}}const{data:session,error}=await this._callRefreshToken(currentSession.refresh_token);if(error){const accessTokenStillValid=!!(currentSession.expires_at&¤tSession.expires_at*1000>Date.now());if(accessTokenStillValid){const stillStored=await getItemAsync(this.storage,this.storageKey);if(stillStored&&stillStored.refresh_token===currentSession.refresh_token){return this._returnResult({data:{session:currentSession},error:null})}}return this._returnResult({data:{session:null},error})}return this._returnResult({data:{session},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(jwt){if(jwt){return await this._getUser(jwt)}await this.initializePromise;let result2;if(this.lock!=null){result2=await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._getUser()})}else{result2=await this._getUser()}if(result2.data.user){this.suppressGetSessionWarning=true}return result2}async _getUser(jwt){try{if(jwt){return await _request(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt,xform:_userResponse})}return await this._useSession(async(result2)=>{var _a,_b,_c;const{data:data2,error}=result2;if(error){throw error}if(!((_a=data2.session)===null||_a===undefined?undefined:_a.access_token)&&!this.hasCustomAuthorizationHeader){return{data:{user:null},error:new AuthSessionMissingError}}return await _request(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(_c=(_b=data2.session)===null||_b===undefined?undefined:_b.access_token)!==null&&_c!==undefined?_c:undefined,xform:_userResponse})})}catch(error){if(isAuthError(error)){if(isAuthSessionMissingError(error)){await this._removeSession()}return this._returnResult({data:{user:null},error})}throw error}}async updateUser(attributes,options={}){await this.initializePromise;if(this.lock!=null){return await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._updateUser(attributes,options)})}return await this._updateUser(attributes,options)}async _updateUser(attributes,options={}){let flowId=null;try{return await this._useSession(async(result2)=>{const{data:sessionData,error:sessionError}=result2;if(sessionError){throw sessionError}if(!sessionData.session){throw new AuthSessionMissingError}const session=sessionData.session;let codeChallenge=null;let codeChallengeMethod=null;if(this.flowType==="pkce"&&attributes.email!=null){[codeChallenge,codeChallengeMethod,flowId]=await this._getCodeChallengeAndMethod()}const{data:data2,error:userError}=await _request(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(options===null||options===undefined?undefined:options.emailRedirectTo,flowId),body:Object.assign(Object.assign({},attributes),{code_challenge:codeChallenge,code_challenge_method:codeChallengeMethod}),jwt:session.access_token,xform:_userResponse});if(userError){throw userError}session.user=data2.user;await this._saveSession(session);await this._notifyAllSubscribers("USER_UPDATED",session);return this._returnResult({data:{user:session.user},error:null})})}catch(error){await removePKCEVerifier(this.storage,this.storageKey,flowId);if(isAuthError(error)){return this._returnResult({data:{user:null},error})}throw error}}async setSession(currentSession){await this.initializePromise;if(this.lock!=null){return await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._setSession(currentSession)})}return await this._setSession(currentSession)}async _setSession(currentSession){try{if(!currentSession.access_token||!currentSession.refresh_token){throw new AuthSessionMissingError}const timeNow=Date.now()/1000;let expiresAt2=timeNow;let hasExpired=true;let session=null;const{payload}=decodeJWT(currentSession.access_token);if(payload.exp){expiresAt2=payload.exp;hasExpired=expiresAt2<=timeNow}if(hasExpired){const{data:refreshedSession,error}=await this._callRefreshToken(currentSession.refresh_token);if(error){return this._returnResult({data:{user:null,session:null},error})}if(!refreshedSession){return{data:{user:null,session:null},error:null}}session=refreshedSession}else{const{data:data2,error}=await this._getUser(currentSession.access_token);if(error){return this._returnResult({data:{user:null,session:null},error})}session={access_token:currentSession.access_token,refresh_token:currentSession.refresh_token,user:data2.user,token_type:"bearer",expires_in:expiresAt2-timeNow,expires_at:expiresAt2};await this._saveSession(session);await this._notifyAllSubscribers("SIGNED_IN",session)}return this._returnResult({data:{user:session.user,session},error:null})}catch(error){if(isAuthError(error)){return this._returnResult({data:{session:null,user:null},error})}throw error}}async refreshSession(currentSession){await this.initializePromise;if(this.lock!=null){return await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._refreshSession(currentSession)})}return await this._refreshSession(currentSession)}async _refreshSession(currentSession){try{return await this._useSession(async(result2)=>{var _a;if(!currentSession){const{data:data2,error:error2}=result2;if(error2){throw error2}currentSession=(_a=data2.session)!==null&&_a!==undefined?_a:undefined}if(!(currentSession===null||currentSession===undefined?undefined:currentSession.refresh_token)){throw new AuthSessionMissingError}const{data:session,error}=await this._callRefreshToken(currentSession.refresh_token);if(error){return this._returnResult({data:{user:null,session:null},error})}if(!session){return this._returnResult({data:{user:null,session:null},error:null})}return this._returnResult({data:{user:session.user,session},error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:{user:null,session:null},error})}throw error}}async _getSessionFromURL(params,callbackUrlType){var _a;try{if(!isBrowser())throw new AuthImplicitGrantRedirectError("No browser detected.");if(params.error||params.error_description||params.error_code){throw new AuthImplicitGrantRedirectError(params.error_description||"Error in URL with unspecified error_description",{error:params.error||"unspecified_error",code:params.error_code||"unspecified_code"})}switch(callbackUrlType){case"implicit":if(this.flowType==="pkce"){throw new AuthPKCEGrantCodeExchangeError("Not a valid PKCE flow url.")}break;case"pkce":if(this.flowType==="implicit"){throw new AuthImplicitGrantRedirectError("Not a valid implicit grant flow url.")}break;default:}if(callbackUrlType==="pkce"){this._debug("#_initialize()","begin","is PKCE flow",true);if(!params.code)throw new AuthPKCEGrantCodeExchangeError("No code detected.");const{data:data3,error:error2}=await this._exchangeCodeForSession(params.code,{flowId:params[PKCE_FLOW_ID_PARAM]});if(error2)throw error2;const url=new URL(window.location.href);url.searchParams.delete("code");url.searchParams.delete(PKCE_FLOW_ID_PARAM);window.history.replaceState(window.history.state,"",url.toString());return{data:{session:data3.session,redirectType:(_a=data3.redirectType)!==null&&_a!==undefined?_a:null},error:null}}const{provider_token,provider_refresh_token,access_token,refresh_token,expires_in,expires_at,token_type}=params;if(!access_token||!expires_in||!refresh_token||!token_type){throw new AuthImplicitGrantRedirectError("No session defined in URL")}const timeNow=Math.round(Date.now()/1000);const expiresIn=parseInt(expires_in);let expiresAt2=timeNow+expiresIn;if(expires_at){expiresAt2=parseInt(expires_at)}const actuallyExpiresIn=expiresAt2-timeNow;if(actuallyExpiresIn*1000<=AUTO_REFRESH_TICK_DURATION_MS){console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`)}const issuedAt=expiresAt2-expiresIn;if(timeNow-issuedAt>=120){console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",issuedAt,expiresAt2,timeNow)}else if(timeNow-issuedAt<0){console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",issuedAt,expiresAt2,timeNow)}const{data:data2,error}=await this._getUser(access_token);if(error)throw error;const session={provider_token,provider_refresh_token,access_token,expires_in:expiresIn,expires_at:expiresAt2,refresh_token,token_type,user:data2.user};window.location.hash="";this._debug("#_getSessionFromURL()","clearing window.location.hash");return this._returnResult({data:{session,redirectType:params.type},error:null})}catch(error){if(isAuthError(error)){return this._returnResult({data:{session:null,redirectType:null},error})}throw error}}_isImplicitGrantCallback(params){if(typeof this.detectSessionInUrl==="function"){return this.detectSessionInUrl(new URL(window.location.href),params)}return Boolean(params.access_token||params.error||params.error_description||params.error_code)}async _isPKCECallback(params){if(!params.code){return false}const flowId=validatePKCEFlowId(params[PKCE_FLOW_ID_PARAM]);if(flowId&&await getItemAsync(this.storage,pkceVerifierSlotKey(this.storageKey,flowId))){return true}const currentStorageContent=await getItemAsync(this.storage,`${this.storageKey}-code-verifier`);return!!currentStorageContent}async signOut(options={scope:"global"}){await this.initializePromise;if(this.lock!=null){return await this._acquireLock(this.lockAcquireTimeout,async()=>{return await this._signOut(options)})}return await this._signOut(options)}async _signOut({scope}={scope:"global"}){return await this._useSession(async(result2)=>{var _a;const removeCurrentSession=async()=>{await this._removeSession()};const{data:data2,error:sessionError}=result2;if(sessionError&&!isAuthSessionMissingError(sessionError)){return this._returnResult({error:sessionError})}const accessToken=(_a=data2.session)===null||_a===undefined?undefined:_a.access_token;if(accessToken){const{error}=await this.admin.signOut(accessToken,scope);if(error){if(!(isAuthApiError(error)&&(error.status===404||error.status===401||error.status===403)||isAuthSessionMissingError(error))){if(scope!=="others"){await removeCurrentSession()}return this._returnResult({error})}}}if(scope!=="others"){await removeCurrentSession()}return this._returnResult({error:null})})}onAuthStateChange(callback){const id3=generateCallbackId();const subscription={id:id3,callback,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",id3);this.stateChangeEmitters.delete(id3)}};this._debug("#onAuthStateChange()","registered callback with id",id3);this.stateChangeEmitters.set(id3,subscription);(async()=>{await this.initializePromise;if(this.lock!=null){await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(id3)})}else{await this._emitInitialSession(id3)}})();return{data:{subscription}}}async _emitInitialSession(id3){return await this._useSession(async(result2)=>{var _a,_b;try{const{data:{session},error}=result2;if(error)throw error;await((_a=this.stateChangeEmitters.get(id3))===null||_a===undefined?undefined:_a.callback("INITIAL_SESSION",session));this._debug("INITIAL_SESSION","callback id",id3,"session",session)}catch(err){await((_b=this.stateChangeEmitters.get(id3))===null||_b===undefined?undefined:_b.callback("INITIAL_SESSION",null));this._debug("INITIAL_SESSION","callback id",id3,"error",err);if(isAuthRefreshDiscardedError(err)){return}if(isAuthSessionMissingError(err)||isAuthRetryableFetchError(err)||isAuthApiError(err)&&(err.code==="refresh_token_not_found"||err.code==="refresh_token_already_used"||err.code==="session_expired")){console.warn(err)}else{console.error(err)}}})}async resetPasswordForEmail(email,options={}){let codeChallenge=null;let codeChallengeMethod=null;let flowId=null;if(this.flowType==="pkce"){[codeChallenge,codeChallengeMethod,flowId]=await this._getCodeChallengeAndMethod(true)}try{return await _request(this.fetch,"POST",`${this.url}/recover`,{body:{email,code_challenge:codeChallenge,code_challenge_method:codeChallengeMethod,gotrue_meta_security:{captcha_token:options.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(options.redirectTo,flowId)})}catch(error){await removePKCEVerifier(this.storage,this.storageKey,flowId);if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async getUserIdentities(){var _a;try{const{data:data2,error}=await this.getUser();if(error)throw error;return this._returnResult({data:{identities:(_a=data2.user.identities)!==null&&_a!==undefined?_a:[]},error:null})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async linkIdentity(credentials){if("token"in credentials){return this.linkIdentityIdToken(credentials)}return this.linkIdentityOAuth(credentials)}async linkIdentityOAuth(credentials){var _a;let flowId=null;try{const{data:data2,error}=await this._useSession(async(result2)=>{var _a2,_b,_c,_d,_f;const{data:data3,error:error2}=result2;if(error2)throw error2;const{url,flowId:urlFlowId}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,credentials.provider,{redirectTo:(_a2=credentials.options)===null||_a2===undefined?undefined:_a2.redirectTo,scopes:(_b=credentials.options)===null||_b===undefined?undefined:_b.scopes,queryParams:(_c=credentials.options)===null||_c===undefined?undefined:_c.queryParams,skipBrowserRedirect:true});flowId=urlFlowId;return await _request(this.fetch,"GET",url,{headers:this.headers,jwt:(_f=(_d=data3.session)===null||_d===undefined?undefined:_d.access_token)!==null&&_f!==undefined?_f:undefined})});if(error)throw error;if(isBrowser()&&!((_a=credentials.options)===null||_a===undefined?undefined:_a.skipBrowserRedirect)){window.location.assign(data2===null||data2===undefined?undefined:data2.url)}return this._returnResult({data:{provider:credentials.provider,url:data2===null||data2===undefined?undefined:data2.url,flowId},error:null})}catch(error){if(isAuthError(error)){return this._returnResult({data:{provider:credentials.provider,url:null,flowId},error})}throw error}}async linkIdentityIdToken(credentials){return await this._useSession(async(result2)=>{var _a;try{const{error:sessionError,data:{session}}=result2;if(sessionError)throw sessionError;const{options,provider,token,access_token,nonce}=credentials;const res=await _request(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(_a=session===null||session===undefined?undefined:session.access_token)!==null&&_a!==undefined?_a:undefined,body:{provider,id_token:token,access_token,nonce,link_identity:true,gotrue_meta_security:{captcha_token:options===null||options===undefined?undefined:options.captchaToken}},xform:_sessionResponse});const{data:data2,error}=res;if(error){return this._returnResult({data:{user:null,session:null},error})}else if(!data2||!data2.session||!data2.user){return this._returnResult({data:{user:null,session:null},error:new AuthInvalidTokenResponseError})}if(data2.session){await this._saveSession(data2.session);await this._notifyAllSubscribers("USER_UPDATED",data2.session)}return this._returnResult({data:data2,error})}catch(error){await removePKCEVerifier(this.storage,this.storageKey,null);if(isAuthError(error)){return this._returnResult({data:{user:null,session:null},error})}throw error}})}async unlinkIdentity(identity){try{return await this._useSession(async(result2)=>{var _a,_b;const{data:data2,error}=result2;if(error){throw error}return await _request(this.fetch,"DELETE",`${this.url}/user/identities/${identity.identity_id}`,{headers:this.headers,jwt:(_b=(_a=data2.session)===null||_a===undefined?undefined:_a.access_token)!==null&&_b!==undefined?_b:undefined})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _refreshAccessToken(refreshToken){const debugName=`#_refreshAccessToken()`;this._debug(debugName,"begin");try{const startedAt=Date.now();return await retryable(async(attempt)=>{if(attempt>0){await sleep(200*Math.pow(2,attempt-1))}this._debug(debugName,"refreshing attempt",attempt);return await _request(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:refreshToken},headers:this.headers,xform:_sessionResponse})},(attempt,error)=>{const nextBackOffInterval=200*Math.pow(2,attempt);return error&&isAuthRetryableFetchError(error)&&Date.now()+nextBackOffInterval-startedAt<AUTO_REFRESH_TICK_DURATION_MS})}catch(error){this._debug(debugName,"error",error);if(isAuthError(error)){return this._returnResult({data:{session:null,user:null},error})}throw error}finally{this._debug(debugName,"end")}}_isValidSession(maybeSession){const isValidSession=typeof maybeSession==="object"&&maybeSession!==null&&"access_token"in maybeSession&&"refresh_token"in maybeSession&&"expires_at"in maybeSession;return isValidSession}async _handleProviderSignIn(provider,options){const{url,flowId}=await this._getUrlForProvider(`${this.url}/authorize`,provider,{redirectTo:options.redirectTo,scopes:options.scopes,queryParams:options.queryParams});this._debug("#_handleProviderSignIn()","provider",provider,"options",options,"url",url);if(isBrowser()&&!options.skipBrowserRedirect){window.location.assign(url)}return{data:{provider,url,flowId},error:null}}async _recoverAndRefresh(){var _a,_b;const debugName="#_recoverAndRefresh()";this._debug(debugName,"begin");try{const currentSession=await getItemAsync(this.storage,this.storageKey);if(currentSession&&this.userStorage){let maybeUser=await getItemAsync(this.userStorage,this.storageKey+"-user");if(!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!maybeUser){maybeUser={user:currentSession.user};await setItemAsync(this.userStorage,this.storageKey+"-user",maybeUser)}currentSession.user=(_a=maybeUser===null||maybeUser===undefined?undefined:maybeUser.user)!==null&&_a!==undefined?_a:userNotAvailableProxy()}else if(currentSession&&!currentSession.user){if(!currentSession.user){const separateUser=await getItemAsync(this.storage,this.storageKey+"-user");if(separateUser&&(separateUser===null||separateUser===undefined?undefined:separateUser.user)){currentSession.user=separateUser.user;await removeItemAsync(this.storage,this.storageKey+"-user");await setItemAsync(this.storage,this.storageKey,currentSession)}else{currentSession.user=userNotAvailableProxy()}}}this._debug(debugName,"session from storage",currentSession);if(!this._isValidSession(currentSession)){this._debug(debugName,"session is not valid");if(currentSession!==null){await this._removeSession()}return}const expiresWithMargin=((_b=currentSession.expires_at)!==null&&_b!==undefined?_b:Infinity)*1000-Date.now()<EXPIRY_MARGIN_MS;this._debug(debugName,`session has${expiresWithMargin?"":" not"} expired with margin of ${EXPIRY_MARGIN_MS}s`);if(expiresWithMargin){if(this.autoRefreshToken&¤tSession.refresh_token){const{error}=await this._callRefreshToken(currentSession.refresh_token);if(error){if(isAuthRefreshDiscardedError(error)){this._debug(debugName,"refresh discarded by commit guard",error)}else{this._debug(debugName,"refresh failed",error)}}}}else if(currentSession.user&¤tSession.user.__isUserNotAvailableProxy===true){try{const{data:data2,error:userError}=await this._getUser(currentSession.access_token);if(!userError&&(data2===null||data2===undefined?undefined:data2.user)){currentSession.user=data2.user;await this._saveSession(currentSession);await this._notifyAllSubscribers("SIGNED_IN",currentSession)}else{this._debug(debugName,"could not get user data, skipping SIGNED_IN notification")}}catch(getUserError){console.error("Error getting user data:",getUserError);this._debug(debugName,"error getting user data, skipping SIGNED_IN notification",getUserError)}}else{await this._notifyAllSubscribers("SIGNED_IN",currentSession)}}catch(err){this._debug(debugName,"error",err);if(isAuthRetryableFetchError(err)){console.warn(err)}else{console.error(err)}return}finally{this._debug(debugName,"end")}}async _callRefreshToken(refreshToken){var _a,_b;if(!refreshToken){throw new AuthSessionMissingError}if(this.refreshingDeferred){return this.refreshingDeferred.promise}if(this.lastRefreshFailure&&this.lastRefreshFailure.refreshToken===refreshToken&&Date.now()<this.lastRefreshFailure.expiresAt){this._debug("#_callRefreshToken()","returning cached failure (cooldown active)");return this.lastRefreshFailure.result}const debugName=`#_callRefreshToken()`;this._debug(debugName,"begin");try{this.refreshingDeferred=new Deferred;this.refreshingDeferred.promise.then(undefined,()=>{});const storedAtStart=await getItemAsync(this.storage,this.storageKey);const{data:data2,error}=await this._refreshAccessToken(refreshToken);if(error)throw error;if(!data2.session)throw new AuthSessionMissingError;const storedAfter=await getItemAsync(this.storage,this.storageKey);const storageChangedUnderUs=storedAtStart!==null&&(storedAfter===null||storedAfter.refresh_token!==storedAtStart.refresh_token);if(storageChangedUnderUs){this._debug(debugName,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:storedAfter?"replaced":"cleared"});const discarded={data:null,error:new AuthRefreshDiscardedError};this.refreshingDeferred.resolve(discarded);return discarded}const epochBeforeSave=this._sessionRemovalEpoch;await this._saveSession(data2.session);if(this._sessionRemovalEpoch!==epochBeforeSave){this._debug(debugName,"commit guard (post-save): _removeSession ran during _saveSession, undoing write");await removeItemAsync(this.storage,this.storageKey);if(this.userStorage){await removeItemAsync(this.userStorage,this.storageKey+"-user")}const discarded={data:null,error:new AuthRefreshDiscardedError};this.refreshingDeferred.resolve(discarded);return discarded}await this._notifyAllSubscribers("TOKEN_REFRESHED",data2.session);const result2={data:data2.session,error:null};this.lastRefreshFailure=null;this.refreshingDeferred.resolve(result2);return result2}catch(error){this._debug(debugName,"error",error);if(isAuthError(error)){const result2={data:null,error};if(!isAuthRetryableFetchError(error)){const storedNow=await getItemAsync(this.storage,this.storageKey);const accessTokenStillValid=!!((storedNow===null||storedNow===undefined?undefined:storedNow.expires_at)&&storedNow.expires_at*1000>Date.now());if(accessTokenStillValid){this._debug(debugName,"proactive refresh failed, access token still valid — preserving session")}else{await this._removeSession()}}this.lastRefreshFailure={refreshToken,result:result2,expiresAt:Date.now()+REFRESH_FAILURE_COOLDOWN_MS};(_a=this.refreshingDeferred)===null||_a===undefined||_a.resolve(result2);return result2}(_b=this.refreshingDeferred)===null||_b===undefined||_b.reject(error);throw error}finally{this.refreshingDeferred=null;this._debug(debugName,"end")}}async _notifyAllSubscribers(event,session,broadcast=true){if(this._pendingInitNotifications!==null&&broadcast){this._pendingInitNotifications.push({event,session,broadcast});return}const debugName=`#_notifyAllSubscribers(${event})`;this._debug(debugName,"begin",session,`broadcast = ${broadcast}`);try{if(this.broadcastChannel&&broadcast){this.broadcastChannel.postMessage({event,session})}const errors=[];const promises=Array.from(this.stateChangeEmitters.values()).map(async(x)=>{try{await x.callback(event,session)}catch(e){errors.push(e)}});await Promise.all(promises);if(errors.length>0){for(let i=0;i<errors.length;i+=1){console.error(errors[i])}throw errors[0]}}finally{this._debug(debugName,"end")}}async _saveSession(session){this._debug("#_saveSession()",session);this.suppressGetSessionWarning=true;const sessionToProcess=Object.assign({},session);const userIsProxy=sessionToProcess.user&&sessionToProcess.user.__isUserNotAvailableProxy===true;if(this.userStorage){if(!userIsProxy&&sessionToProcess.user){await setItemAsync(this.userStorage,this.storageKey+"-user",{user:sessionToProcess.user})}else if(userIsProxy){}const mainSessionData=Object.assign({},sessionToProcess);delete mainSessionData.user;const clonedMainSessionData=deepClone(mainSessionData);await setItemAsync(this.storage,this.storageKey,clonedMainSessionData)}else{const clonedSession=deepClone(sessionToProcess);await setItemAsync(this.storage,this.storageKey,clonedSession)}}async _removeSession(){this._sessionRemovalEpoch+=1;this._debug("#_removeSession()");this.lastRefreshFailure=null;this.suppressGetSessionWarning=false;await removeItemAsync(this.storage,this.storageKey);await removeAllPKCEVerifiers(this.storage,this.storageKey);await removeItemAsync(this.storage,this.storageKey+"-user");if(this.userStorage){await removeItemAsync(this.userStorage,this.storageKey+"-user")}await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const callback=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{if(callback&&isBrowser()&&(window===null||window===undefined?undefined:window.removeEventListener)){window.removeEventListener("visibilitychange",callback)}}catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh();this._debug("#_startAutoRefresh()");const ticker=setInterval(()=>this._autoRefreshTokenTick(),AUTO_REFRESH_TICK_DURATION_MS);this.autoRefreshTicker=ticker;if(ticker&&typeof ticker==="object"&&typeof ticker.unref==="function"){ticker.unref()}else if(typeof Deno!=="undefined"&&typeof Deno.unrefTimer==="function"){Deno.unrefTimer(ticker)}const timeout=setTimeout(async()=>{await this.initializePromise;await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=timeout;if(timeout&&typeof timeout==="object"&&typeof timeout.unref==="function"){timeout.unref()}else if(typeof Deno!=="undefined"&&typeof Deno.unrefTimer==="function"){Deno.unrefTimer(timeout)}}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const ticker=this.autoRefreshTicker;this.autoRefreshTicker=null;if(ticker){clearInterval(ticker)}const timeout=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null;if(timeout){clearTimeout(timeout)}}async startAutoRefresh(){this._removeVisibilityChangedCallback();await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback();await this._stopAutoRefresh()}async dispose(){var _a;this._removeVisibilityChangedCallback();await this._stopAutoRefresh();(_a=this.broadcastChannel)===null||_a===undefined||_a.close();this.broadcastChannel=null;this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");if(this.lock!=null){try{await this._acquireLock(0,async()=>{try{const now=Date.now();try{return await this._useSession(async(result2)=>{const{data:{session}}=result2;if(!session||!session.refresh_token||!session.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const expiresInTicks=Math.floor((session.expires_at*1000-now)/AUTO_REFRESH_TICK_DURATION_MS);this._debug("#_autoRefreshTokenTick()",`access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`);if(expiresInTicks<=AUTO_REFRESH_TICK_THRESHOLD){await this._callRefreshToken(session.refresh_token)}})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof LockAcquireTimeoutError){this._debug("auto refresh token tick lock not available")}else{throw e}}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{const now=Date.now();try{await this._useSession(async(result2)=>{const{data:{session}}=result2;if(!session||!session.refresh_token||!session.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const expiresInTicks=Math.floor((session.expires_at*1000-now)/AUTO_REFRESH_TICK_DURATION_MS);this._debug("#_autoRefreshTokenTick()",`access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`);if(expiresInTicks<=AUTO_REFRESH_TICK_THRESHOLD){await this._callRefreshToken(session.refresh_token)}})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){this._debug("#_handleVisibilityChange()");if(!isBrowser()||!(window===null||window===undefined?undefined:window.addEventListener)){if(this.autoRefreshToken){this.startAutoRefresh()}return false}try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(false)}catch(error){this._debug("#visibilityChangedCallback","error",error)}};window===null||window===undefined||window.addEventListener("visibilitychange",this.visibilityChangedCallback);await this._onVisibilityChanged(true)}catch(error){console.error("_handleVisibilityChange",error)}}async _onVisibilityChanged(calledFromInitialize){const methodName=`#_onVisibilityChanged(${calledFromInitialize})`;this._debug(methodName,"visibilityState",document.visibilityState);if(document.visibilityState==="visible"){if(this.autoRefreshToken){this._startAutoRefresh()}if(!calledFromInitialize){await this.initializePromise;if(this.lock!=null){await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(methodName,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()})}else{if(document.visibilityState!=="visible"){this._debug(methodName,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}}else if(document.visibilityState==="hidden"){if(this.autoRefreshToken){this._stopAutoRefresh()}}}async _getUrlForProvider(url,provider,options){let redirectTo=options===null||options===undefined?undefined:options.redirectTo;let codeChallenge=null;let codeChallengeMethod=null;let flowId=null;if(this.flowType==="pkce"){[codeChallenge,codeChallengeMethod,flowId]=await this._getCodeChallengeAndMethod();redirectTo=this._maybeAppendFlowIdToRedirect(redirectTo,flowId)}const urlParams=[`provider=${encodeURIComponent(provider)}`];if(redirectTo){urlParams.push(`redirect_to=${encodeURIComponent(redirectTo)}`)}if(options===null||options===undefined?undefined:options.scopes){urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`)}if(codeChallenge!=null&&codeChallengeMethod!=null){const flowParams=new URLSearchParams({code_challenge:`${encodeURIComponent(codeChallenge)}`,code_challenge_method:`${encodeURIComponent(codeChallengeMethod)}`});urlParams.push(flowParams.toString())}if(options===null||options===undefined?undefined:options.queryParams){const query=new URLSearchParams(options.queryParams);urlParams.push(query.toString())}if(options===null||options===undefined?undefined:options.skipBrowserRedirect){urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`)}return{url:`${url}?${urlParams.join("&")}`,flowId}}_maybeAppendFlowIdToRedirect(redirectTo,flowId){if(!redirectTo||!flowId||!this.experimental.appendPkceFlowIdToRedirects){return redirectTo!==null&&redirectTo!==undefined?redirectTo:undefined}return appendFlowIdToRedirectTo(redirectTo,flowId)}async _getCodeChallengeAndMethod(isPasswordRecovery=false){return getCodeChallengeAndMethod(this.storage,this.storageKey,isPasswordRecovery,(evictedFlowId)=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",evictedFlowId))}async _unenroll(params){try{return await this._useSession(async(result2)=>{var _a;const{data:sessionData,error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}return await _request(this.fetch,"DELETE",`${this.url}/factors/${params.factorId}`,{headers:this.headers,jwt:(_a=sessionData===null||sessionData===undefined?undefined:sessionData.session)===null||_a===undefined?undefined:_a.access_token})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _enroll(params){try{return await this._useSession(async(result2)=>{var _a,_b;const{data:sessionData,error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}const body=Object.assign({friendly_name:params.friendlyName,factor_type:params.factorType},params.factorType==="phone"?{phone:params.phone}:params.factorType==="totp"?{issuer:params.issuer}:{});const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/factors`,{body,headers:this.headers,jwt:(_a=sessionData===null||sessionData===undefined?undefined:sessionData.session)===null||_a===undefined?undefined:_a.access_token});if(error){return this._returnResult({data:null,error})}if(params.factorType==="totp"&&data2.type==="totp"&&((_b=data2===null||data2===undefined?undefined:data2.totp)===null||_b===undefined?undefined:_b.qr_code)){data2.totp.qr_code=`data:image/svg+xml;utf-8,${data2.totp.qr_code}`}return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _verify(params){const run=async()=>{try{return await this._useSession(async(result2)=>{var _a;const{data:sessionData,error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}const body=Object.assign({challenge_id:params.challengeId},"webauthn"in params?{webauthn:Object.assign(Object.assign({},params.webauthn),{credential_response:params.webauthn.type==="create"?serializeCredentialCreationResponse(params.webauthn.credential_response):serializeCredentialRequestResponse(params.webauthn.credential_response)})}:{code:params.code});const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/factors/${params.factorId}/verify`,{body,headers:this.headers,jwt:(_a=sessionData===null||sessionData===undefined?undefined:sessionData.session)===null||_a===undefined?undefined:_a.access_token});if(error){return this._returnResult({data:null,error})}await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1000)+data2.expires_in},data2));await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",data2);return this._returnResult({data:data2,error})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}};if(this.lock!=null){return this._acquireLock(this.lockAcquireTimeout,run)}return run()}async _challenge(params){const run=async()=>{try{return await this._useSession(async(result2)=>{var _a;const{data:sessionData,error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}const response2=await _request(this.fetch,"POST",`${this.url}/factors/${params.factorId}/challenge`,{body:params,headers:this.headers,jwt:(_a=sessionData===null||sessionData===undefined?undefined:sessionData.session)===null||_a===undefined?undefined:_a.access_token});if(response2.error){return response2}const{data:data2}=response2;if(data2.type!=="webauthn"){return{data:data2,error:null}}switch(data2.webauthn.type){case"create":return{data:Object.assign(Object.assign({},data2),{webauthn:Object.assign(Object.assign({},data2.webauthn),{credential_options:Object.assign(Object.assign({},data2.webauthn.credential_options),{publicKey:deserializeCredentialCreationOptions(data2.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},data2),{webauthn:Object.assign(Object.assign({},data2.webauthn),{credential_options:Object.assign(Object.assign({},data2.webauthn.credential_options),{publicKey:deserializeCredentialRequestOptions(data2.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}};if(this.lock!=null){return this._acquireLock(this.lockAcquireTimeout,run)}return run()}async _challengeAndVerify(params){const{data:challengeData,error:challengeError}=await this._challenge({factorId:params.factorId});if(challengeError){return this._returnResult({data:null,error:challengeError})}return await this._verify({factorId:params.factorId,challengeId:challengeData.id,code:params.code})}async _listFactors(){var _a;const{data:{user},error:userError}=await this.getUser();if(userError){return{data:null,error:userError}}const data2={all:[],phone:[],totp:[],webauthn:[],recovery_code:[]};for(const factor of(_a=user===null||user===undefined?undefined:user.factors)!==null&&_a!==undefined?_a:[]){data2.all.push(factor);if(factor.status==="verified"&&factor.factor_type in data2&&Array.isArray(data2[factor.factor_type])){data2[factor.factor_type].push(factor)}}return{data:data2,error:null}}async _getAuthenticatorAssuranceLevel(jwt){var _a,_b,_c,_d;if(jwt){try{const{payload:payload2}=decodeJWT(jwt);let currentLevel2=null;if(payload2.aal){currentLevel2=payload2.aal}let nextLevel2=currentLevel2;const{data:{user},error:userError}=await this.getUser(jwt);if(userError){return this._returnResult({data:null,error:userError})}const verifiedFactors2=(_b=(_a=user===null||user===undefined?undefined:user.factors)===null||_a===undefined?undefined:_a.filter((factor)=>factor.status==="verified"))!==null&&_b!==undefined?_b:[];if(verifiedFactors2.length>0){nextLevel2="aal2"}const currentAuthenticationMethods2=payload2.amr||[];return{data:{currentLevel:currentLevel2,nextLevel:nextLevel2,currentAuthenticationMethods:currentAuthenticationMethods2},error:null}}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}const{data:{session},error:sessionError}=await this.getSession();if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null}}const{payload}=decodeJWT(session.access_token);let currentLevel=null;if(payload.aal){currentLevel=payload.aal}let nextLevel=currentLevel;const verifiedFactors=(_d=(_c=session.user.factors)===null||_c===undefined?undefined:_c.filter((factor)=>factor.status==="verified"))!==null&&_d!==undefined?_d:[];if(verifiedFactors.length>0){nextLevel="aal2"}const currentAuthenticationMethods=payload.amr||[];return{data:{currentLevel,nextLevel,currentAuthenticationMethods},error:null}}async _getRecoveryCodesStatus(){assertRecoveryCodesExperimentalEnabled(this.experimental);try{return await this._useSession(async(result2)=>{var _a;const{data:sessionData,error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}const{data:data2,error}=await _request(this.fetch,"GET",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(_a=sessionData===null||sessionData===undefined?undefined:sessionData.session)===null||_a===undefined?undefined:_a.access_token});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _generateRecoveryCodes(params){assertRecoveryCodesExperimentalEnabled(this.experimental);try{return await this._useSession(async(result2)=>{var _a;const{data:sessionData,error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/factors/recovery-codes`,{body:(params===null||params===undefined?undefined:params.friendlyName)?{friendly_name:params.friendlyName}:undefined,headers:this.headers,jwt:(_a=sessionData===null||sessionData===undefined?undefined:sessionData.session)===null||_a===undefined?undefined:_a.access_token});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _verifyRecoveryCode(params){assertRecoveryCodesExperimentalEnabled(this.experimental);const run=async()=>{try{return await this._useSession(async(result2)=>{var _a;const{data:sessionData,error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/factors/recovery-codes/verify`,{body:{code:params.code},headers:this.headers,jwt:(_a=sessionData===null||sessionData===undefined?undefined:sessionData.session)===null||_a===undefined?undefined:_a.access_token});if(error){return this._returnResult({data:null,error})}const session=Object.assign({expires_at:expiresAt(data2.expires_in)},data2);await this._saveSession(session);await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",session);return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}};if(this.lock!=null){return this._acquireLock(this.lockAcquireTimeout,run)}return run()}async _regenerateRecoveryCodes(){assertRecoveryCodesExperimentalEnabled(this.experimental);try{return await this._useSession(async(result2)=>{var _a;const{data:sessionData,error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/factors/recovery-codes/regenerate`,{headers:this.headers,jwt:(_a=sessionData===null||sessionData===undefined?undefined:sessionData.session)===null||_a===undefined?undefined:_a.access_token});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _unenrollRecoveryCodes(){assertRecoveryCodesExperimentalEnabled(this.experimental);try{return await this._useSession(async(result2)=>{var _a;const{data:sessionData,error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}const{data:data2,error}=await _request(this.fetch,"DELETE",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:(_a=sessionData===null||sessionData===undefined?undefined:sessionData.session)===null||_a===undefined?undefined:_a.access_token});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _getAuthorizationDetails(authorizationId){try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}return await _request(this.fetch,"GET",`${this.url}/oauth/authorizations/${authorizationId}`,{headers:this.headers,jwt:session.access_token,xform:(data2)=>({data:data2,error:null})})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _approveAuthorization(authorizationId,options){try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}const response2=await _request(this.fetch,"POST",`${this.url}/oauth/authorizations/${authorizationId}/consent`,{headers:this.headers,jwt:session.access_token,body:{action:"approve"},xform:(data2)=>({data:data2,error:null})});if(response2.data&&response2.data.redirect_url){if(isBrowser()&&!(options===null||options===undefined?undefined:options.skipBrowserRedirect)){window.location.assign(response2.data.redirect_url)}}return response2})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _denyAuthorization(authorizationId,options){try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}const response2=await _request(this.fetch,"POST",`${this.url}/oauth/authorizations/${authorizationId}/consent`,{headers:this.headers,jwt:session.access_token,body:{action:"deny"},xform:(data2)=>({data:data2,error:null})});if(response2.data&&response2.data.redirect_url){if(isBrowser()&&!(options===null||options===undefined?undefined:options.skipBrowserRedirect)){window.location.assign(response2.data.redirect_url)}}return response2})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _listOAuthGrants(){try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}return await _request(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:session.access_token,xform:(data2)=>({data:data2,error:null})})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _revokeOAuthGrant(options){try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}await _request(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:session.access_token,query:{client_id:options.clientId},noResolveJson:true});return{data:{},error:null}})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async fetchJwk(kid,jwks={keys:[]}){let jwk=jwks.keys.find((key)=>key.kid===kid);if(jwk){return jwk}const now=Date.now();jwk=this.jwks.keys.find((key)=>key.kid===kid);if(jwk&&this.jwks_cached_at+JWKS_TTL>now){return jwk}const{data:data2,error}=await _request(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(error){throw error}if(!data2.keys||data2.keys.length===0){return null}this.jwks=data2;this.jwks_cached_at=now;jwk=data2.keys.find((key)=>key.kid===kid);if(!jwk){return null}return jwk}async getClaims(jwt,options={}){try{let token=jwt;if(!token){const{data:data2,error}=await this.getSession();if(error||!data2.session){return this._returnResult({data:null,error})}token=data2.session.access_token}const{header,payload,signature,raw:{header:rawHeader,payload:rawPayload}}=decodeJWT(token);if(!(options===null||options===undefined?undefined:options.allowExpired)){try{validateExp(payload.exp)}catch(e){throw new AuthInvalidJwtError(e instanceof Error?e.message:"JWT validation failed")}}const signingKey=!header.alg||header.alg.startsWith("HS")||!header.kid||!(("crypto"in globalThis)&&("subtle"in globalThis.crypto))?null:await this.fetchJwk(header.kid,(options===null||options===undefined?undefined:options.keys)?{keys:options.keys}:options===null||options===undefined?undefined:options.jwks);if(!signingKey){const{error}=await this.getUser(token);if(error){throw error}return{data:{claims:payload,header,signature},error:null}}const algorithm=getAlgorithm(header.alg);const publicKey=await crypto.subtle.importKey("jwk",signingKey,algorithm,true,["verify"]);const isValid=await crypto.subtle.verify(algorithm,publicKey,signature,stringToUint8Array(`${rawHeader}.${rawPayload}`));if(!isValid){throw new AuthInvalidJwtError("Invalid JWT signature")}return{data:{claims:payload,header,signature},error:null}}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async signInWithPasskey(credentials){var _a,_b,_c;assertPasskeyExperimentalEnabled(this.experimental);try{if(!browserSupportsWebAuthn()){return this._returnResult({data:null,error:new AuthUnknownError("Browser does not support WebAuthn",null)})}const{data:options,error:optionsError}=await this._startPasskeyAuthentication({options:{captchaToken:(_a=credentials===null||credentials===undefined?undefined:credentials.options)===null||_a===undefined?undefined:_a.captchaToken}});if(optionsError||!options){return this._returnResult({data:null,error:optionsError})}const publicKeyOptions=deserializeCredentialRequestOptions(options.options);const signal=(_c=(_b=credentials===null||credentials===undefined?undefined:credentials.options)===null||_b===undefined?undefined:_b.signal)!==null&&_c!==undefined?_c:webAuthnAbortService.createNewAbortSignal();const{data:credential,error:credentialError}=await getCredential({publicKey:publicKeyOptions,signal});if(credentialError||!credential){return this._returnResult({data:null,error:credentialError!==null&&credentialError!==undefined?credentialError:new AuthUnknownError("WebAuthn ceremony failed",null)})}const serialized=serializeCredentialRequestResponse(credential);return this._verifyPasskeyAuthentication({challengeId:options.challenge_id,credential:serialized})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async registerPasskey(credentials){var _a,_b;assertPasskeyExperimentalEnabled(this.experimental);try{if(!browserSupportsWebAuthn()){return this._returnResult({data:null,error:new AuthUnknownError("Browser does not support WebAuthn",null)})}const{data:options,error:optionsError}=await this._startPasskeyRegistration();if(optionsError||!options){return this._returnResult({data:null,error:optionsError})}const publicKeyOptions=deserializeCredentialCreationOptions(options.options);const signal=(_b=(_a=credentials===null||credentials===undefined?undefined:credentials.options)===null||_a===undefined?undefined:_a.signal)!==null&&_b!==undefined?_b:webAuthnAbortService.createNewAbortSignal();const{data:credential,error:credentialError}=await createCredential({publicKey:publicKeyOptions,signal});if(credentialError||!credential){return this._returnResult({data:null,error:credentialError!==null&&credentialError!==undefined?credentialError:new AuthUnknownError("WebAuthn ceremony failed",null)})}const serialized=serializeCredentialCreationResponse(credential);return this._verifyPasskeyRegistration({challengeId:options.challenge_id,credential:serialized})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _startPasskeyRegistration(){assertPasskeyExperimentalEnabled(this.experimental);try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:session.access_token,body:{}});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _verifyPasskeyRegistration(params){assertPasskeyExperimentalEnabled(this.experimental);try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:session.access_token,body:{challenge_id:params.challengeId,credential:params.credential}});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _startPasskeyAuthentication(params){var _a;assertPasskeyExperimentalEnabled(this.experimental);try{const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(_a=params===null||params===undefined?undefined:params.options)===null||_a===undefined?undefined:_a.captchaToken}}});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:data2,error:null})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _verifyPasskeyAuthentication(params){assertPasskeyExperimentalEnabled(this.experimental);try{const{data:data2,error}=await _request(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:params.challengeId,credential:params.credential},xform:_sessionResponse});if(error){return this._returnResult({data:null,error})}if(data2.session){await this._saveSession(data2.session);await this._notifyAllSubscribers("SIGNED_IN",data2.session)}return this._returnResult({data:data2,error:null})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _listPasskeys(){assertPasskeyExperimentalEnabled(this.experimental);try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}const{data:data2,error}=await _request(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:session.access_token,xform:(data3)=>({data:data3,error:null})});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _updatePasskey(params){assertPasskeyExperimentalEnabled(this.experimental);try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}const{data:data2,error}=await _request(this.fetch,"PATCH",`${this.url}/passkeys/${params.passkeyId}`,{headers:this.headers,jwt:session.access_token,body:{friendly_name:params.friendlyName}});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:data2,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}async _deletePasskey(params){assertPasskeyExperimentalEnabled(this.experimental);try{return await this._useSession(async(result2)=>{const{data:{session},error:sessionError}=result2;if(sessionError){return this._returnResult({data:null,error:sessionError})}if(!session){return this._returnResult({data:null,error:new AuthSessionMissingError})}const{error}=await _request(this.fetch,"DELETE",`${this.url}/passkeys/${params.passkeyId}`,{headers:this.headers,jwt:session.access_token,noResolveJson:true});if(error){return this._returnResult({data:null,error})}return this._returnResult({data:null,error:null})})}catch(error){if(isAuthError(error)){return this._returnResult({data:null,error})}throw error}}}var DEFAULT_OPTIONS,GLOBAL_JWKS,deprecatedLockWarned=false,GoTrueClient_default;var init_GoTrueClient=__esm(()=>{init_GoTrueAdminApi();init_constants();init_errors();init_fetch();init_helpers();init_locks();init_base64url();init_webauthn();polyfillGlobalThis();DEFAULT_OPTIONS={url:GOTRUE_URL,storageKey:STORAGE_KEY,autoRefreshToken:true,persistSession:true,detectSessionInUrl:true,headers:DEFAULT_HEADERS,flowType:"implicit",debug:false,hasCustomAuthorizationHeader:false,throwOnError:false,lockAcquireTimeout:5000,skipAutoInitialize:false,experimental:{}};GLOBAL_JWKS={};GoTrueClient.nextInstanceID={};GoTrueClient_default=GoTrueClient});var init_AuthAdminApi=__esm(()=>{init_GoTrueAdminApi()});var AuthClient,AuthClient_default;var init_AuthClient=__esm(()=>{init_GoTrueClient();AuthClient=GoTrueClient_default;AuthClient_default=AuthClient});var init_module=__esm(()=>{init_GoTrueAdminApi();init_GoTrueClient();init_AuthAdminApi();init_AuthClient();init_locks();init_types();init_errors()});var exports_auth_provider={};__export(exports_auth_provider,{AuthClient:()=>AuthClient_default});var init_auth_provider=__esm(()=>{init_module()});var fileValidationReasons={invalid_metadata:"File metadata must contain only the supported fields.",invalid_name:"File name must be 1–255 characters, with no reserved names, path separators, control characters or trailing spaces/dots.",invalid_path:"File path must contain safe relative folder names and cannot start with .os.",invalid_storage:"File storage must be local or remote.",invalid_media_type:"The media type must use a value such as text/markdown or application/json.",invalid_size:"File size must be a non-negative safe integer byte count.",invalid_request_key:"File request key must contain 1–256 characters, with no surrounding whitespace or control characters.",invalid_enrichment_name:"The enrichment name must be a filename without folders, such as read.md. Names such as original and original.pdf are reserved.",invalid_enrichment_request:"The save request has invalid content or metadata.",invalid_replacement:"To replace an enrichment, pass its current SHA-256 value as replace.",invalid_bytes:"File content must contain byte chunks.",original_changed:"The selected file changed while OS was reading it. Wait for it to finish saving, then try again."};var localStorageReasons={local_storage_legacy:`OS found an older local file storage layout: the internal metadata folder is still named .oddington-files.
|
|
19
19
|
|
|
20
20
|
Stop any OS routines using this workspace, then rename .oddington-files to .os in the same directory and rerun your command. Keep the folder’s contents intact.`,local_storage_ambiguous:"OS found both .oddington-files and .os metadata folders in local file storage and could not safely choose one. Reconcile their metadata before continuing; do not overwrite either folder. Your stored files have been left in place.",local_storage_unrecognized:"OS could not open its local file storage because the folder contains files but has no recognized metadata. The storage folder needs to be checked before continuing. Your stored files have been left in place.",local_storage_tracked:"OS could not use its local file storage because it contains Git-tracked files. Local file storage must be outside tracked repository content. Your stored files have been left in place."};function parseFileErrorDetail(value){if(!value||typeof value!=="object"||Array.isArray(value))return;const v=value;if(typeof v.reason!=="string")return;if(Object.hasOwn(fileValidationReasons,v.reason)||Object.hasOwn(localStorageReasons,v.reason))return Object.keys(v).length===1?{reason:v.reason}:undefined;if(v.reason!=="size_mismatch"&&v.reason!=="size_limit")return;const count=v.reason==="size_mismatch"?"expectedBytes":"limitBytes";if(Object.keys(v).some((key)=>!["reason",count,"receivedBytes","receivedAtLeast"].includes(key))||!Number.isSafeInteger(v[count])||v[count]<0||!Number.isSafeInteger(v.receivedBytes)||v.receivedBytes<0||v.receivedAtLeast!==undefined&&v.receivedAtLeast!==true)return;return{reason:v.reason,[count]:v[count],receivedBytes:v.receivedBytes,...v.receivedAtLeast?{receivedAtLeast:true}:{}}}function fileErrorExplanation(detail){if(detail.reason==="size_mismatch")return`The request declared ${detail.expectedBytes} bytes, but contained ${detail.receivedAtLeast?"at least ":""}${detail.receivedBytes} bytes.`;if(detail.reason==="size_limit")return`The file content exceeds the ${fileSizeLabel(detail.limitBytes)} limit; received ${detail.receivedAtLeast?"at least ":""}${fileSizeLabel(detail.receivedBytes)}.`;return Object.hasOwn(localStorageReasons,detail.reason)?localStorageReasons[detail.reason]:fileValidationReasons[detail.reason]}function fileSizeLabel(bytes){for(const[unit,size]of[["GiB",1024**3],["MiB",1024**2],["KiB",1024]])if(bytes>=size&&bytes%size===0)return`${bytes/size} ${unit}`;return`${bytes} bytes`}function fileErrorDetailForCode(code,detail){const parsed=parseFileErrorDetail(detail);if(!parsed)return;const storage=Object.hasOwn(localStorageReasons,parsed.reason);if(storage?code==="unavailable":["invalid_input","request_too_large"].includes(code))return parsed}var FILE_CAPACITY_MESSAGE="OS reached its file-processing limit. Try again in a moment. "+"If this keeps happening with a large batch, split the files into smaller groups.";var FILE_INTEGRITY_MESSAGE="OS could not verify this File against its saved record. Try again. "+"If the problem continues, add the original file again.";function fileErrorMessage(error){const detail=fileErrorDetailForCode(error.code,error.detail);if(detail){const enrichment=["invalid_enrichment_name","invalid_enrichment_request","invalid_replacement"].includes(detail.reason);return`${enrichment?`Couldn’t save the file’s enrichment.
|
|
21
|
-
`:""}${fileErrorExplanation(detail)}`}switch(error.code){case"invalid_input":return"The file request is invalid.";case"unsupported_context":return"This environment does not support this file operation.";case"unauthenticated":return"Sign in to OS before accessing files.";case"access_denied":return"You don’t have access to this file operation.";case"not_found":return"This file isn’t available in this workspace.";case"request_too_large":return"The file request exceeds the size limit.";case"conflict":return"The saved file or enrichment doesn’t match this request. Reload it before trying again.";case"local_only":return"This file is stored on a computer and isn’t available through remote storage.";case"integrity":return FILE_INTEGRITY_MESSAGE;case"capacity":return FILE_CAPACITY_MESSAGE;case"method_not_allowed":return"This request uses an unsupported file operation.";case"unavailable":return`OS couldn’t complete the file operation.${error.retryable?" Try again.":""}`}}class FileOperationError extends Error{code;status;retryable;detail;constructor(code,status,retryable=false,detail){const safe=fileErrorDetailForCode(code,detail);super(fileErrorMessage({code,retryable,detail:safe}));this.code=code;this.status=status;this.retryable=retryable;if(safe)this.detail=Object.freeze(safe);if(safe&&Object.hasOwn(localStorageReasons,safe.reason))this.retryable=false}}var FILE_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;var FILE_ORIGINAL_MAX_BYTES=5*1024**3;function parseFileDescriptor(value){const invalid=()=>{throw new FileOperationError("unavailable",503,true)};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const f=value;if(Object.keys(f).sort().join(",")!=="enrichments,id,mediaType,name,path,sha256,size"||typeof f.id!=="string"||!FILE_ID_PATTERN.test(f.id)||!safeFileName(f.name)||!safeFilePath(f.path)||!Number.isSafeInteger(f.size)||f.size<0||f.size>FILE_ORIGINAL_MAX_BYTES||typeof f.sha256!=="string"||!/^[0-9a-f]{64}$/.test(f.sha256)||!f.enrichments||typeof f.enrichments!=="object"||Array.isArray(f.enrichments)||!isCanonicalOriginalMediaType(f.mediaType))return invalid();for(const[name,descriptor]of Object.entries(f.enrichments)){if(!safeEnrichmentName(name))return invalid();parseEnrichmentDescriptor(descriptor)}if(new TextEncoder().encode(JSON.stringify(f)).byteLength>16*1024)return invalid();return f}function parseEnrichmentDescriptor(value){const invalid=()=>{throw new FileOperationError("unavailable",503,true)};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const d=value;if(Object.keys(d).sort().join(",")!=="mediaType,sha256,size"||!["application/octet-stream","text/plain","text/markdown","application/json"].includes(d.mediaType)||!Number.isSafeInteger(d.size)||d.size<0||d.size>16*1024*1024||typeof d.sha256!=="string"||!/^[0-9a-f]{64}$/.test(d.sha256))return invalid();return d}function safeEnrichmentName(value){return safeFileName(value)&&!/^original(?:\.|$)/i.test(value)}function parseFileEnrichMetadata(value,maxBytes){const invalid=(reason="invalid_metadata")=>{throw new FileOperationError("invalid_input",400,false,{reason})};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const d=value;if(Object.keys(d).some((key)=>!["name","size","mediaType","replace"].includes(key)))return invalid();if(!safeEnrichmentName(d.name))return invalid("invalid_enrichment_name");if(!Number.isSafeInteger(d.size)||d.size<0)return invalid("invalid_size");if(d.mediaType!==undefined&&(typeof d.mediaType!=="string"||d.mediaType.length>255||/[\u0000-\u001f\u007f]/.test(d.mediaType)))return invalid("invalid_media_type");if(d.replace!==undefined&&(typeof d.replace!=="string"||!/^[0-9a-f]{64}$/.test(d.replace)))return invalid("invalid_replacement");if(d.size>maxBytes)throw new FileOperationError("request_too_large",413,false,{reason:"size_limit",limitBytes:maxBytes,receivedBytes:d.size});return d}function safeFileName(value){return typeof value==="string"&&value.length>0&&value.length<=255&&value===value.trim()&&value!=="."&&value!==".."&&!/[\u0000-\u001f\u007f-\u009f/\\:*?"<>|]/u.test(value)&&!/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(value)&&!/[. ]$/.test(value)&&!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(value)}function safeFilePath(value){return typeof value==="string"&&value.length<=1024&&value.split("/").every(safeFileName)}function safeManagedFilePath(value){return safeFilePath(value)&&value.split("/")[0].toLowerCase()!==".os"}function declaredOriginalMediaType(value){if(typeof value!=="string"||value.length>255||/[\u0000-\u001f\u007f-\u009f]/.test(value))throw new FileOperationError("invalid_input",400,false,{reason:"invalid_media_type"});const normalized=value.split(";",1)[0].trim().toLowerCase();const token="[a-z0-9!#$%&'+.^_`|~-]+";if(!new RegExp(`^${token}/${token}$`).test(normalized))throw new FileOperationError("invalid_input",400,false,{reason:"invalid_media_type"});return normalized}function isCanonicalOriginalMediaType(value){try{return declaredOriginalMediaType(value)===value}catch{return false}}function parseFileCreateMetadata(value,maxBytes){const invalid=(reason="invalid_metadata")=>{throw new FileOperationError("invalid_input",400,false,{reason})};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const input=value;if(Object.keys(input).some((key)=>!["name","path","storage","mediaType","size","requestKey"].includes(key)))return invalid();const path=input.path===undefined?"Files":input.path;if(!safeFileName(input.name))return invalid("invalid_name");if(!safeManagedFilePath(path))return invalid("invalid_path");if(input.storage!==undefined&&input.storage!=="remote"&&input.storage!=="local")return invalid("invalid_storage");const mediaType=input.mediaType===undefined?"application/octet-stream":declaredOriginalMediaType(input.mediaType);if(!Number.isSafeInteger(input.size)||input.size<0)return invalid("invalid_size");if(input.size>maxBytes)throw new FileOperationError("request_too_large",413,false,{reason:"size_limit",limitBytes:maxBytes,receivedBytes:input.size});if(typeof input.requestKey!=="string"||input.requestKey.length<1||input.requestKey.length>256||input.requestKey!==input.requestKey.trim()||/[\u0000-\u001f\u007f]/.test(input.requestKey))return invalid("invalid_request_key");return{name:input.name,path,...input.storage?{storage:input.storage}:{},mediaType,size:input.size,requestKey:input.requestKey}}class AppRoutineContractError extends Error{code;constructor(code){super(code);this.code=code}}var propertyName=/^[a-z][A-Za-z0-9]*(?![\s\S])/;var stepId=/^[a-z0-9]+(?:-[a-z0-9]+)*(?![\s\S])/;var routineName=/^[a-z0-9][a-z0-9-]{0,62}(?![\s\S])/;function isAppRoutineName(value){return typeof value==="string"&&routineName.test(value)}var owns=(value,key)=>Object.hasOwn(value,key);var invalidContract=()=>{throw new AppRoutineContractError("invalid_contract")};var invalidValue=()=>{throw new AppRoutineContractError("invalid_value")};function record(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)&&(Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null)}function fields(value,required,optional=[]){return required.every((key)=>owns(value,key))&&Object.keys(value).every((key)=>required.includes(key)||optional.includes(key))}function denseArray(value){return Array.isArray(value)&&Object.keys(value).length===value.length&&Array.from({length:value.length},(_,index)=>owns(value,String(index))).every(Boolean)}function parseAppRoutineContract(value){let properties=0;function schema(value2,depth=1){if(depth>8||!record(value2))return invalidContract();switch(value2.type){case"object":{if(!fields(value2,["type","properties","additionalProperties"],["required"])||value2.additionalProperties!==false||!record(value2.properties))return invalidContract();const entries=Object.entries(value2.properties);properties+=entries.length;if(properties>64||entries.some(([key])=>!propertyName.test(key)))return invalidContract();let required;if(owns(value2,"required")){if(!denseArray(value2.required)||value2.required.some((key)=>typeof key!=="string"||!owns(value2.properties,key))||new Set(value2.required).size!==value2.required.length)return invalidContract();required=[...value2.required]}return{type:"object",properties:Object.fromEntries(entries.map(([key,child])=>[key,schema(child,depth+1)])),...required===undefined?{}:{required},additionalProperties:false}}case"array":if(!fields(value2,["type","items"],["maxItems"])||owns(value2,"maxItems")&&(!Number.isSafeInteger(value2.maxItems)||value2.maxItems<1))return invalidContract();return{type:"array",items:schema(value2.items,depth+1),...owns(value2,"maxItems")?{maxItems:value2.maxItems}:{}};case"boolean":if(!fields(value2,["type"]))return invalidContract();return{type:value2.type};case"file":if(!fields(value2,["type"],["storage","path"])||owns(value2,"storage")&&value2.storage!=="local"&&value2.storage!=="remote"||owns(value2,"path")&&!safeManagedFilePath(value2.path))return invalidContract();return{type:"file",...owns(value2,"storage")?{storage:value2.storage}:{},...owns(value2,"path")?{path:value2.path}:{}};case"string":if(!fields(value2,["type"],["maxLength"])||owns(value2,"maxLength")&&(!Number.isSafeInteger(value2.maxLength)||value2.maxLength<0||value2.maxLength>4096))return invalidContract();return{type:"string",...owns(value2,"maxLength")?{maxLength:value2.maxLength}:{}};case"integer":case"number":{const validNumber=value2.type==="integer"?Number.isSafeInteger:Number.isFinite;if(!fields(value2,["type"],["minimum","maximum"])||owns(value2,"minimum")&&!validNumber(value2.minimum)||owns(value2,"maximum")&&!validNumber(value2.maximum)||owns(value2,"minimum")&&owns(value2,"maximum")&&value2.minimum>value2.maximum)return invalidContract();return{type:value2.type,...owns(value2,"minimum")?{minimum:value2.minimum}:{},...owns(value2,"maximum")?{maximum:value2.maximum}:{}}}default:return invalidContract()}}if(!record(value)||!fields(value,["routine","input","steps"],["result"])||!isAppRoutineName(value.routine)||!denseArray(value.steps)||value.steps.length<1||value.steps.length>64)return invalidContract();const input=schema(value.input);const result=owns(value,"result")?schema(value.result):undefined;const ids=new Set;const steps=value.steps.map((step)=>{if(!record(step)||!fields(step,["id"],["summary"])||typeof step.id!=="string"||!stepId.test(step.id)||ids.has(step.id))return invalidContract();ids.add(step.id);return{id:step.id,...owns(step,"summary")?{summary:schema(step.summary)}:{}}});return{routine:value.routine,input,steps,...result===undefined?{}:{result}}}function jsonData(value,ancestors=new Set){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return;if(!record(value)&&!denseArray(value))return invalidValue();if(ancestors.has(value))return invalidValue();ancestors.add(value);for(const child of Object.values(value))jsonData(child,ancestors);ancestors.delete(value)}function validateRoutineSchemaValue(schema,value,rejected){const type=(value2)=>value2===null?"null":Array.isArray(value2)?"array":["object","boolean","string","number"].includes(typeof value2)?typeof value2:"other";function check(schema2,value2,path){const fail=(reason,extra={})=>{rejected?.({reason,path:path.length<=256?path:"$",expected:schema2.type,received:type(value2),...extra});return invalidValue()};switch(schema2.type){case"object":if(!record(value2))return fail("wrong_type");for(const key of schema2.required??[])if(!owns(value2,key))return fail("missing_field",{path:`${path}.${key}`.length<=256?`${path}.${key}`:"$",expected:schema2.properties[key].type,received:"missing"});if(Object.keys(value2).some((key)=>!owns(schema2.properties,key)))return fail("unexpected_field");for(const[key,child]of Object.entries(value2))check(schema2.properties[key],child,`${path}.${key}`);return;case"array":if(!denseArray(value2))return fail("wrong_type");if(schema2.maxItems!==undefined&&value2.length>schema2.maxItems)return fail("out_of_bounds",{constraint:"maxItems",limit:schema2.maxItems});value2.forEach((child,index)=>check(schema2.items,child,`${path}[${index}]`));return;case"boolean":if(typeof value2!=="boolean")return fail("wrong_type");return;case"string":if(typeof value2!=="string")return fail("wrong_type");if(Array.from(value2).length>(schema2.maxLength??4096))return fail("out_of_bounds",{constraint:"maxLength",limit:schema2.maxLength??4096});return;case"integer":case"number":if(typeof value2!=="number"||!(schema2.type==="integer"?Number.isSafeInteger(value2):Number.isFinite(value2)))return fail("wrong_type");if(schema2.minimum!==undefined&&value2<schema2.minimum)return fail("out_of_bounds",{constraint:"minimum",limit:schema2.minimum});if(schema2.maximum!==undefined&&value2>schema2.maximum)return fail("out_of_bounds",{constraint:"maximum",limit:schema2.maximum});return;case"file":{let file;try{jsonData(value2);file=parseFileDescriptor(value2)}catch{return fail("invalid_file")}if(schema2.path!==undefined&&file.path!==schema2.path)return fail("invalid_file")}}}check(schema,value,"$")}function validRecordRef(value){return typeof value==="string"&&value.length<=512&&/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(value)}function validDropboxRootPath(value){return typeof value==="string"&&value.length<=2048&&value.startsWith("/")&&!/[\\\x00-\x1f\x7f]/.test(value)&&value.slice(1).split("/").every((segment)=>segment.length>0&&segment.trim()===segment&&segment!=="."&&segment!=="..")}function validMicrosoftId(value){return typeof value==="string"&&/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value)}function validMicrosoftMailbox(value){return typeof value==="string"&&value.length<=254&&/^[^\s@/?#\\\x00-\x1f\x7f]+@[^\s@/?#\\\x00-\x1f\x7f]+\.[^\s@/?#\\\x00-\x1f\x7f]+$/.test(value)}function sharePointHost(value){return/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.sharepoint\.com$/.test(value)}function canonicalSharePointSiteUrl(value){if(typeof value!=="string"||value.length>2048||/[\s\\?#\x00-\x1f\x7f]/.test(value)||!/^https:\/\/[^/:@]+(?:\/|$)/i.test(value))return;try{const url=new URL(value);if(url.protocol!=="https:"||!sharePointHost(url.hostname)||url.username||url.password||url.port)return;const rawPath=value.replace(/^https:\/\/[^/]+/i,"")||"/";const path=rawPath.endsWith("/")?rawPath.slice(0,-1):rawPath;const segments=path.slice(1).split("/");if(path&&segments.some((segment)=>!segment))return;const encoded=path?segments.map((segment)=>{const decoded=decodeURIComponent(segment);if(decoded==="."||decoded===".."||/[/%\\?#\x00-\x1f\x7f]/.test(decoded))throw new Error;return encodeURIComponent(decoded)}).join("/"):"";const canonical=`https://${url.hostname}/${encoded}`;return canonical.length<=2048?canonical:undefined}catch{return}}function validSharePointSiteId(value,siteUrl){if(typeof value!=="string"||value.length>512)return false;const[host,collection,site,extra]=value.split(",");return extra===undefined&&host===new URL(siteUrl).hostname&&validMicrosoftId(collection)&&validMicrosoftId(site)}function validGoogleScopes(value){return Array.isArray(value)&&value.length>0&&value.length<=32&&value.every((scope)=>typeof scope==="string"&&scope.length<=256&&/^(https:\/\/www\.googleapis\.com\/auth\/[A-Za-z0-9._-]+|https:\/\/mail\.google\.com\/|openid|email|profile)$/.test(scope))&&new Set(value).size===value.length}var DROPBOX_FILE_SCOPES=["account_info.read","files.metadata.read","files.content.read","files.content.write"];function validDropboxFileScopes(value){return Array.isArray(value)&&value.length===DROPBOX_FILE_SCOPES.length&&new Set(value).size===value.length&&DROPBOX_FILE_SCOPES.every((scope)=>value.includes(scope))}function validDataRepositoryName(value){return typeof value==="string"&&/^[a-z0-9][a-z0-9._-]{0,127}$/.test(value)&&!value.includes("..")}class InboxContractError extends Error{constructor(message){super(message);this.name="InboxContractError"}}var INBOX_PUBLICATION_ITEM_BYTES=1024*1024;var INBOX_PUBLICATION_REQUEST_BYTES=INBOX_PUBLICATION_ITEM_BYTES+4096;var publicationAdvice="Trim the content, or attach long reports, data, and supporting materials as files instead. Then try again.";var INBOX_PUBLICATION_TOO_LARGE=`Your Inbox item failed to publish. Its content exceeds the 1 MB limit. ${publicationAdvice}`;class InboxPublicationSizeError extends InboxContractError{kind;bytes;constructor(kind,bytes){const label=kind==="ask"?"Ask":"Digest";const size=Math.ceil(bytes/INBOX_PUBLICATION_ITEM_BYTES*100)/100;super(`Your ${label} failed to publish. Its content is ${size} MB, which exceeds the 1 MB limit. ${publicationAdvice}`);this.kind=kind;this.bytes=bytes;this.name="InboxPublicationSizeError"}}function enforcePublicationSize(value){const bytes=new TextEncoder().encode(JSON.stringify(value)).byteLength;if(bytes>INBOX_PUBLICATION_ITEM_BYTES)throw new InboxPublicationSizeError(value.kind,bytes);return value}function fail(message){throw new InboxContractError(message)}function object(value,label){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))fail(`${label} must be a plain object`);return value}function keys(value,allowed,label){for(const key of Reflect.ownKeys(value)){if(typeof key!=="string"||!allowed.includes(key))fail(`${label} does not support ${String(key)}`);const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!descriptor.enumerable||!("value"in descriptor))fail(`${label} must contain only JSON data`)}}function text(value,label){if(typeof value!=="string"||!value.trim())fail(`${label} must be nonempty text`);return value}function id(value,label){const result=text(value,label);if(result!==result.trim())fail(`${label} cannot have surrounding whitespace`);return result}function array(value,label){if(!Array.isArray(value)||Object.getPrototypeOf(value)!==Array.prototype||Reflect.ownKeys(value).length!==value.length+1)fail(`${label} must be a dense array`);for(let index=0;index<value.length;index+=1){const descriptor=Object.getOwnPropertyDescriptor(value,String(index));if(!descriptor?.enumerable||!("value"in descriptor))fail(`${label} must contain only JSON data`)}return value}function distinctIds(value,label,nonempty=true){const result=array(value,label).map((entry)=>id(entry,label));if(nonempty&&!result.length)fail(`${label} must not be empty`);if(new Set(result).size!==result.length)fail(`${label} contains duplicate IDs`);return result}var memberEmail=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function personReference(value,label){const result=id(value,label);return memberEmail.test(result)?result.toLowerCase():result}function distinctPeople(value,label,nonempty=true){const result=array(value,label).map((entry)=>personReference(entry,label));if(nonempty&&!result.length)fail(`${label} must not be empty`);if(new Set(result).size!==result.length)fail(`${label} contains duplicate IDs`);return result}function serializable(value,ancestors=new Set){if(value===null||typeof value==="boolean"||typeof value==="string")return value;if(typeof value==="number"&&Number.isFinite(value))return value;if(!value||typeof value!=="object")fail("Input must be losslessly serializable JSON");if(ancestors.has(value))fail("Input cannot contain cycles");ancestors.add(value);try{if(Array.isArray(value)){array(value,"JSON array");return value.map((entry)=>serializable(entry,ancestors))}const source=object(value,"JSON input");keys(source,Object.keys(source),"JSON input");return Object.fromEntries(Object.entries(source).map(([key,entry])=>[key,serializable(entry,ancestors)]))}finally{ancestors.delete(value)}}function natural(value,label,minimum=0){if(!Number.isSafeInteger(value)||value<minimum)fail(`${label} must be an integer >= ${minimum}`);return value}function validateInboxFile(value){const v=object(serializable(value),"Inbox file");keys(v,["id","name","mediaType","size","sha256"],"Inbox file");const fileId=id(v.id,"Inbox file ID"),name=id(v.name,"filename"),mediaType=id(v.mediaType,"media type");if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(fileId)||/[\x00-\x1f\x7f/\\]/.test(name)||!isCanonicalOriginalMediaType(mediaType)||typeof v.sha256!=="string"||!/^[0-9a-f]{64}$/.test(v.sha256))fail("Invalid Inbox file identity or metadata");const size=natural(v.size,"file size");if(size>FILE_ORIGINAL_MAX_BYTES)fail("File exceeds supported size");return{id:fileId,name,mediaType,size,sha256:v.sha256}}function validateQualifiedRecordRef(value){const r=object(value,"Record reference");keys(r,["repository","ref"],"Record reference");if(!validDataRepositoryName(r.repository)||!validRecordRef(r.ref))fail("Invalid qualified Record reference");return{repository:r.repository,ref:r.ref}}function validateBlock(value){const b=object(serializable(value),"Block");if(b.kind==="rich-text"){keys(b,["kind","markdown"],"Rich text Block");return{kind:"rich-text",markdown:text(b.markdown,"Markdown")}}if(b.kind==="asks"){keys(b,["kind","problem","asks"],"Asks Block");const asks=distinctIds(b.asks,"Ask IDs");if(asks.some((ask)=>!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(ask)))fail("Invalid Ask ID");return{kind:"asks",problem:text(b.problem,"problem"),asks}}if(!["record","records","files"].includes(b.kind))fail("Unknown Block kind");keys(b,["kind","label","initiallyExpanded",...b.kind==="record"?["record"]:b.kind==="records"?["records"]:["files"]],"Block");const label=text(b.label,"Block label");if(b.initiallyExpanded!==undefined&&typeof b.initiallyExpanded!=="boolean")fail("Invalid initiallyExpanded");const expanded=b.initiallyExpanded===undefined?{}:{initiallyExpanded:b.initiallyExpanded};if(b.kind==="record")return{kind:"record",label,record:validateQualifiedRecordRef(b.record),...expanded};if(b.kind==="records"){const records=array(b.records,"records").map(validateQualifiedRecordRef);if(!records.length||new Set(records.map((r)=>JSON.stringify([r.repository,r.ref]))).size!==records.length)fail("Empty or duplicate records");return{kind:"records",label,records,...expanded}}const files=array(b.files,"files").map(validateInboxFile);if(!files.length||new Set(files.map((file)=>file.id)).size!==files.length)fail("Empty or duplicate files");return{kind:"files",label,files,...expanded}}function richTextBlock(value){return validateBlock({...value,kind:"rich-text"})}function recordBlock(value){return validateBlock({...value,kind:"record"})}function recordsBlock(value){return validateBlock({...value,kind:"records"})}function fileBlock(value){const input=object(serializable(value),"Files Block");const files=array(input.files,"files").map((entry)=>{const descriptor=object(entry,"File");if(!(("path"in descriptor)||("enrichments"in descriptor)))return validateInboxFile(descriptor);let file;try{file=parseFileDescriptor(descriptor)}catch{return fail("Invalid shared File descriptor")}const{id:id2,name,mediaType,size,sha256}=file;return{id:id2,name,mediaType,size,sha256}});return validateBlock({...input,kind:"files",files})}function asksBlock(value){return validateBlock({...value,kind:"asks"})}function selection(value){const input=object(value,"selection");keys(input,["source"],"selection");return validateResponseDefinition({type:"selection",source:input.source})}function validateAuthoredSource(value){const source=object(value,"response definition");keys(source,["type","options","suggestions","search"],"response definition");if(source.type!=="authored")fail("Expected authored options");const options=array(source.options,"options").map((entry)=>{const option=object(entry,"choice");keys(option,["value","label","description","note"],"choice");let note;if(option.note!==undefined){const declaration=object(option.note,"choice note");keys(declaration,["placeholder"],"choice note");note={placeholder:text(declaration.placeholder,"note placeholder")}}return{value:id(option.value,"choice value"),label:text(option.label,"choice label"),...option.description===undefined?{}:{description:text(option.description,"choice description")},...note?{note}:{}}});if(!options.length)fail("Choices require at least one option");if(new Set(options.map((option)=>option.value)).size!==options.length)fail("Duplicate choice value");if(Object.hasOwn(source,"search")||Object.hasOwn(source,"suggestions")){const labels=object(source.search,"choice search");keys(labels,["triggerLabel","placeholder","emptyLabel"],"choice search");const search={triggerLabel:text(labels.triggerLabel,"search trigger label"),placeholder:text(labels.placeholder,"search placeholder"),emptyLabel:text(labels.emptyLabel,"search empty label")};const suggestions=array(source.suggestions,"suggestions").map((value2)=>id(value2,"suggestion value"));if(suggestions.length>8||new Set(suggestions).size!==suggestions.length||suggestions.some((value2)=>!options.some((option)=>option.value===value2)))fail("Search permits at most eight unique published suggestions");return{type:"authored",options,suggestions,search}}if(options.length>9)fail("Choices require one to nine options");return{type:"authored",options}}function validateRecordReference(value){const row=object(value,"Record reference");keys(row,["repository","ref"],"Record reference");const repository=id(row.repository,"repository"),ref=id(row.ref,"Record reference");if(!/^[a-z0-9][a-z0-9._/-]{0,127}$/.test(repository)||/\.\.|\/\//.test(repository)||ref.length>512||!/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(ref))fail("Invalid Record identity");return{repository,ref}}function validateRecordSource(value){const source=object(value,"Record selection");keys(source,["type","collection","refPrefix","where","display","suggestions"],"Record selection");if(source.type!=="records")fail("Expected Record options");const collection=object(source.collection,"collection");keys(collection,["repository","name"],"collection");const repository=validateRecordReference({repository:collection.repository,ref:"records/example"}).repository;const name=id(collection.name,"collection name");if(!/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(name))fail("Invalid collection name");const refPrefix=source.refPrefix===undefined?undefined:id(source.refPrefix,"Record reference prefix");if(refPrefix!==undefined&&(!refPrefix.endsWith("/")||refPrefix.length>512||!/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)*\/$/.test(refPrefix)))fail("Invalid Record reference prefix");const where=object(source.where??{},"Record filter");const fieldName=(name2)=>/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name2)&&!["constructor","prototype"].includes(name2);for(const[name2,value2]of Object.entries(where)){if(!fieldName(name2)||!(value2===null||["string","number","boolean"].includes(typeof value2))||typeof value2==="number"&&!Number.isFinite(value2))fail("Record filters require scalar equality")}const display=object(source.display,"Record display");keys(display,["labelFields"],"Record display");const labelFields=distinctIds(display.labelFields,"label fields");if(labelFields.length>2||labelFields.some((name2)=>!fieldName(name2)))fail("Select one or two scalar label fields");const suggestions=array(source.suggestions??[],"suggestions").map((value2)=>{const entry=object(value2,"suggestion");keys(entry,["record","reason"],"suggestion");const record2=validateRecordReference(entry.record);if(record2.repository!==repository)fail("Suggestion belongs to another repository");return{record:record2,...entry.reason===undefined?{}:{reason:text(entry.reason,"suggestion reason")}}});if(suggestions.length>8||new Set(suggestions.map((entry)=>entry.record.ref)).size!==suggestions.length)fail("Record selection permits at most eight unique suggestions");return{type:"records",collection:{repository,name},...refPrefix?{refPrefix}:{},where:{...where},display:{labelFields},suggestions}}function validateResponseDefinition(value){const definition=object(value,"response definition");keys(definition,["type","source"],"response definition");if(definition.type!=="selection")fail("Expected a selection definition");const source=object(definition.source,"option source");switch(source.type){case"authored":return{type:"selection",source:validateAuthoredSource(source)};case"records":return{type:"selection",source:validateRecordSource(source)};default:return fail("Unsupported option source")}}function handlerReference(value){const source=object(value,"handler reference");keys(source,["id","input"],"handler reference");return{id:id(source.id,"handler ID"),input:serializable(source.input)}}function defineHandler(value){const source=object(value,"handler");keys(source,["id","results","run"],"handler");const stable=(value2)=>typeof value2==="string"&&/^[a-zA-Z0-9][a-zA-Z0-9_./-]{0,127}$/.test(value2);if(!stable(source.id))fail("Handler ID must be stable");const results=source.results===undefined?undefined:distinctIds(source.results,"handler results",false);if(results&&(results.length>64||results.some((result)=>!stable(result))))fail("Handler results must be stable IDs");if(typeof source.run!=="function")fail("Handler requires a run function");return Object.freeze({id:value.id,...results===undefined?{}:{results:Object.freeze(results.sort())},run:value.run})}function respond(handler,input){defineHandler(handler);return handlerReference({id:handler.id,input})}function question(value){const source=object(value,"question");keys(source,["id","to","allowedResponders","prompt","instructions","response","handler"],"question");const to=personReference(source.to,"question assignee");const allowedResponders=source.allowedResponders===undefined?[to]:distinctPeople(source.allowedResponders,"allowed responders");if(!allowedResponders.includes(to))fail("Allowed responders must include the assignee");return{id:id(source.id,"question ID"),to,allowedResponders,prompt:text(source.prompt,"question prompt"),...source.instructions===undefined?{}:{instructions:text(source.instructions,"instructions")},response:validateResponseDefinition(source.response),...Object.hasOwn(source,"handler")?{handler:handlerReference(source.handler)}:{}}}function presentation(source){const views=source.views===undefined?[]:array(source.views,"views").map((entry)=>{const view=object(entry,"view");keys(view,["id","view","input"],"view");return{id:id(view.id,"view ID"),view:id(view.view,"view name"),input:serializable(view.input)}});if(new Set(views.map((view)=>view.id)).size!==views.length)fail("Duplicate view ID");const body=source.body===undefined?[]:array(source.body,"body").map(validateBlock);return{title:text(source.title,"title"),description:text(source.description,"description"),views,body}}function validatePublication(value){const source=object(value,"publication");if(source.kind!=="ask"&&source.kind!=="digest")fail("Publication requires an explicit kind");keys(source,["kind","title","description","recipients","views","body","notifyImmediately",...source.kind==="ask"?["questions","tags","recordRefs"]:[]],"publication");if(source.notifyImmediately!==undefined&&typeof source.notifyImmediately!=="boolean")fail("notifyImmediately must be a boolean");const itemPresentation={...presentation(source),...source.notifyImmediately===undefined?{}:{notifyImmediately:source.notifyImmediately}};const linkedAsks=(itemPresentation.body??[]).flatMap((block)=>block.kind==="asks"?block.asks:[]);if(new Set(linkedAsks).size!==linkedAsks.length)fail("Ask belongs to more than one problem");if(source.kind==="digest")return{kind:"digest",...itemPresentation,recipients:distinctPeople(source.recipients,"digest recipients")};if(itemPresentation.body?.some((block)=>block.kind==="asks"))fail("Asks Blocks belong to Digests");const questions=array(source.questions===undefined?[]:source.questions,"questions").map((value2)=>question(value2));if(new Set(questions.map((entry)=>entry.id)).size!==questions.length)fail("Duplicate question ID");const extra=source.recipients===undefined?[]:distinctPeople(source.recipients,"recipients",false);if(!questions.length&&!extra.length)fail("Ask requires at least one recipient");const tags=array(source.tags===undefined?[]:source.tags,"Ask tags").map((value2)=>{const tag=text(value2,"Ask tag");if(new TextEncoder().encode(tag).byteLength>64)fail("Ask tag exceeds 64 UTF-8 bytes");return tag});if(tags.length>32||new Set(tags).size!==tags.length)fail("Ask tags exceed bounds or contain duplicates");const recordRefs=array(source.recordRefs===undefined?[]:source.recordRefs,"Ask Record references").map((value2)=>{const row=object(value2,"Ask Record reference");keys(row,["repository","id"],"Ask Record reference");const{repository,ref}=validateRecordReference({repository:row.repository,ref:row.id});return{repository,id:ref}});if(new Set(recordRefs.map((ref)=>JSON.stringify([ref.repository,ref.id]))).size!==recordRefs.length)fail("Ask Record references contain duplicates");return{kind:"ask",...itemPresentation,questions,tags,recordRefs,recipients:[...new Set([...extra,...questions.flatMap((entry)=>[entry.to,...entry.allowedResponders])])]}}function continueAsk(value){const source=object(value,"continueAsk");keys(source,[],"continueAsk");return{type:"continue"}}function resolution(value){const source=object(value,"resolution");keys(source,["outcome","evidence"],"resolution");return{outcome:text(source.outcome,"outcome"),...source.evidence===undefined?{}:{evidence:array(source.evidence,"evidence").map((entry)=>serializable(entry))}}}function resolveAsk(value){return{type:"resolve",...resolution(value)}}function validateResolution(value){const source=object(value,"published resolution");keys(source,["expectedRevision","outcome","evidence"],"published resolution");if(!Number.isSafeInteger(source.expectedRevision)||source.expectedRevision<1)fail("Expected revision must be a positive integer");return{expectedRevision:source.expectedRevision,...resolution({outcome:source.outcome,...source.evidence===undefined?{}:{evidence:source.evidence}})}}function publicationRequestKey(value){const options=object(value,"publication options");keys(options,["requestKey"],"publication options");return id(options.requestKey,"publication request key")}function createInboxPublisher(transport){return{async publishAsk(value,options){const source=object(value,"ask");keys(source,["title","description","recipients","views","body","questions","notifyImmediately","tags","recordRefs"],"ask");const result=await transport.publish({requestKey:publicationRequestKey(options),item:enforcePublicationSize(validatePublication({...source,kind:"ask"}))});id(result.id,"published ask ID");if(!("revision"in result)||!Number.isSafeInteger(result.revision)||result.revision!==1)fail("Initial ask publication must return revision 1");return{id:result.id,revision:result.revision}},async publishDigest(value,options){const source=object(value,"digest");keys(source,["title","description","recipients","views","body","notifyImmediately"],"digest");const result=await transport.publish({requestKey:publicationRequestKey(options),item:enforcePublicationSize(validatePublication({...source,kind:"digest"}))});return{id:id(result.id,"published digest ID")}},async publishResolution(askId,value){await transport.resolve({askId:id(askId,"ask ID"),resolution:validateResolution(value)})}}}var ROUTINE_DECLARATION_SCHEMA="https://schemas.oddington.ai/routine/v1.json";var ROUTINE_SOURCE_LIMITS={files:20000,bytes:256*1024*1024,declarationBytes:64*1024};var invalid=(field)=>{throw new Error(`Invalid routine declaration: ${field}`)};var object2=(value,fields2,field)=>{if(!value||typeof value!=="object"||Array.isArray(value)||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null||Reflect.ownKeys(value).some((key)=>typeof key!=="string"||!fields2.includes(key)||!Object.getOwnPropertyDescriptor(value,key).enumerable||!Object.hasOwn(Object.getOwnPropertyDescriptor(value,key),"value")))invalid(field);return value};var routineAlias=(value)=>typeof value==="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(value);var list=(value,field,allowed,qualified=false)=>{if(value===undefined)return[];if(!Array.isArray(value)||value.length>64||value.some((item)=>!(routineAlias(item)||qualified&&typeof item==="string"&&item.split("/").length===2&&item.split("/").every(routineAlias))||allowed&&!allowed.includes(item))||new Set(value).size!==value.length)invalid(field);return[...value].sort()};function routineAssetPattern(value){return typeof value==="string"&&value.length<=512&&!value.startsWith("/")&&!value.includes("\\")&&!value.includes(":")&&value.split("/").every((part)=>!!part&&part!=="."&&part!==".."&&/^[a-zA-Z0-9_.*-]+$/.test(part))}function parseRoutineDeclaration(value){const v=object2(value,["$schema","access","runtime","retry","assets"],"fields");if(v.$schema!==ROUTINE_DECLARATION_SCHEMA)invalid("$schema");const access=object2(v.access===undefined?{}:v.access,["repositories","connections","ai","files","publish"],"access");if(Object.hasOwn(access,"ai")&&access.ai!==true)invalid("access.ai");const rawRepositories=access.repositories===undefined?{}:access.repositories;const repositories=object2(rawRepositories,rawRepositories&&typeof rawRepositories==="object"?Object.keys(rawRepositories):[],"access.repositories");if(Object.keys(repositories).length>64)invalid("access.repositories");const grants={};for(const key of Object.keys(repositories).sort()){if(!routineAlias(key)||!["read","write"].includes(repositories[key]))invalid(`access.repositories.${key}`);grants[key]=repositories[key]}if(access.files!==undefined&&!["read","read-write"].includes(access.files))invalid("access.files");const runtime=object2(v.runtime===undefined?{}:v.runtime,["features","resources","maxDuration"],"runtime");if(runtime.features!==undefined&&(!Array.isArray(runtime.features)||runtime.features.length!==0))invalid("runtime.features");if(runtime.resources!==undefined&&runtime.resources!=="standard")invalid("runtime.resources");if(runtime.maxDuration!==undefined&&!["15m","60m"].includes(runtime.maxDuration))invalid("runtime.maxDuration");const retry=object2(v.retry===undefined?{}:v.retry,["maxAttempts"],"retry");if(retry.maxAttempts!==undefined&&retry.maxAttempts!==1)invalid("retry.maxAttempts");const assets=v.assets===undefined?[]:v.assets;if(!Array.isArray(assets)||assets.length>64||assets.some((item)=>!routineAssetPattern(item))||new Set(assets).size!==assets.length)invalid("assets");return{$schema:ROUTINE_DECLARATION_SCHEMA,access:{repositories:grants,connections:list(access.connections,"access.connections",undefined,true),...access.ai===true?{ai:true}:{},...access.files===undefined?{}:{files:access.files},publish:list(access.publish,"access.publish",["asks","digests"])},runtime:{features:[],resources:"standard",maxDuration:runtime.maxDuration??"60m"},retry:{maxAttempts:1},assets:[...assets].sort()}}var invalid2=()=>{throw new AppRoutineContractError("invalid_value")};var invalidContract2=()=>{throw new AppRoutineContractError("invalid_contract")};var routineTitle=(value)=>typeof value==="string"&&value.trim().length>0&&value.length<=256;function freezeRoutineMetadata(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))freezeRoutineMetadata(child);Object.freeze(value)}return value}function assertRoutineJson(value,ancestors=new Set){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return;if(!value||typeof value!=="object"||ancestors.has(value))return invalid2();const array2=Array.isArray(value);if(!array2&&Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null)return invalid2();const keys2=Reflect.ownKeys(value);if(array2&&(keys2.length!==value.length+1||!Array.from({length:value.length},(_,index)=>Object.hasOwn(value,index)).every(Boolean)))return invalid2();ancestors.add(value);for(const key of keys2){if(array2&&key==="length")continue;if(typeof key!=="string")return invalid2();const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!descriptor.enumerable||!Object.hasOwn(descriptor,"value"))return invalid2();assertRoutineJson(descriptor.value,ancestors)}ancestors.delete(value)}function assertRoutineFields(value,allowed){if(!value||typeof value!=="object"||Object.getPrototypeOf(value)!==Object.prototype||Reflect.ownKeys(value).some((key)=>typeof key!=="string"||allowed&&!allowed.includes(key)||!Object.getOwnPropertyDescriptor(value,key).enumerable||!Object.hasOwn(Object.getOwnPropertyDescriptor(value,key),"value")))return invalidContract2()}function parseRoutineAccess(value){try{if(value!==undefined)assertRoutineJson(value);assertRoutineFields(value??{},["repositories","connections","ai","files","publish"]);const access=value;const names=access?.connections??[];if(!Array.isArray(names)||names.length>64||new Set(names).size!==names.length||names.some((name)=>typeof name!=="string"||name.split("/").length!==2||name.split("/").some((part)=>!isAppRoutineName(part))))return invalidContract2();const parsed=parseRoutineDeclaration({$schema:ROUTINE_DECLARATION_SCHEMA,access:{...access,connections:[]}}).access;return freezeRoutineMetadata({...parsed,connections:[...names]})}catch{return invalidContract2()}}function parseRoutineAIOutputIssue(value){if(!value||typeof value!=="object"||Array.isArray(value))return;const v=value;if(["invalid_json","invalid_response","empty_text","structured_output_limit"].includes(String(v.reason)))return Object.keys(v).join(",")==="reason"?{reason:v.reason}:undefined;if(!["missing_field","unexpected_field","wrong_type","out_of_bounds","invalid_file"].includes(String(v.reason))||typeof v.path!=="string"||v.path.length>256||!/^\$(?:\.[a-z][A-Za-z0-9]*|\[(?:0|[1-9][0-9]*)\])*$/.test(v.path)||!["object","array","boolean","string","integer","number","file"].includes(String(v.expected))||!["missing","null","object","array","boolean","string","number","other"].includes(String(v.received))||Object.keys(v).some((key)=>!["reason","path","expected","received","constraint","limit"].includes(key)))return;if(v.reason==="out_of_bounds"){if(!["maxLength","maxItems","minimum","maximum"].includes(String(v.constraint))||typeof v.limit!=="number"||!Number.isFinite(v.limit))return}else if(Object.hasOwn(v,"constraint")||Object.hasOwn(v,"limit"))return;return{reason:v.reason,path:v.path,expected:v.expected,received:v.received,...v.reason==="out_of_bounds"?{constraint:v.constraint,limit:v.limit}:{}}}function routineAIOutputMessage(issue){if(issue.reason==="structured_output_limit")return"AI couldn’t produce an answer matching the requested format within its submission limit.";if(issue.reason==="invalid_json")return"AI replied, but its answer could not be read as JSON.";if(issue.reason==="invalid_response")return"AI returned a response OS could not read.";if(issue.reason==="empty_text")return"AI returned an empty answer.";const field=issue.path==="$"?"response":issue.path.slice(issue.path.startsWith("$.")?2:1);const expected={object:"an object",array:"a list",boolean:"true or false",string:"text",integer:"a whole number",number:"a number",file:"a File"}[issue.expected];const received={missing:"a missing field",null:"null",object:"an object",array:"a list",boolean:"true or false",string:"text",number:"a number",other:"an unsupported value"}[issue.received];if(issue.reason==="missing_field")return`AI response is missing a required field.
|
|
21
|
+
`:""}${fileErrorExplanation(detail)}`}switch(error.code){case"invalid_input":return"The file request is invalid.";case"unsupported_context":return"This environment does not support this file operation.";case"unauthenticated":return"Sign in to OS before accessing files.";case"access_denied":return"You don’t have access to this file operation.";case"not_found":return"This file isn’t available in this workspace.";case"request_too_large":return"The file request exceeds the size limit.";case"conflict":return"The saved file or enrichment doesn’t match this request. Reload it before trying again.";case"local_only":return"This file is stored on a computer and isn’t available through remote storage.";case"integrity":return FILE_INTEGRITY_MESSAGE;case"capacity":return FILE_CAPACITY_MESSAGE;case"method_not_allowed":return"This request uses an unsupported file operation.";case"unavailable":return`OS couldn’t complete the file operation.${error.retryable?" Try again.":""}`}}class FileOperationError extends Error{code;status;retryable;detail;constructor(code,status,retryable=false,detail){const safe=fileErrorDetailForCode(code,detail);super(fileErrorMessage({code,retryable,detail:safe}));this.code=code;this.status=status;this.retryable=retryable;if(safe)this.detail=Object.freeze(safe);if(safe&&Object.hasOwn(localStorageReasons,safe.reason))this.retryable=false}}var FILE_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;var FILE_ORIGINAL_MAX_BYTES=5*1024**3;function parseFileDescriptor(value){const invalid=()=>{throw new FileOperationError("unavailable",503,true)};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const f=value;if(Object.keys(f).sort().join(",")!=="enrichments,id,mediaType,name,path,sha256,size"||typeof f.id!=="string"||!FILE_ID_PATTERN.test(f.id)||!safeFileName(f.name)||!safeFilePath(f.path)||!Number.isSafeInteger(f.size)||f.size<0||f.size>FILE_ORIGINAL_MAX_BYTES||typeof f.sha256!=="string"||!/^[0-9a-f]{64}$/.test(f.sha256)||!f.enrichments||typeof f.enrichments!=="object"||Array.isArray(f.enrichments)||!isCanonicalOriginalMediaType(f.mediaType))return invalid();for(const[name,descriptor]of Object.entries(f.enrichments)){if(!safeEnrichmentName(name))return invalid();parseEnrichmentDescriptor(descriptor)}if(new TextEncoder().encode(JSON.stringify(f)).byteLength>16*1024)return invalid();return f}function parseEnrichmentDescriptor(value){const invalid=()=>{throw new FileOperationError("unavailable",503,true)};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const d=value;if(Object.keys(d).sort().join(",")!=="mediaType,sha256,size"||!["application/octet-stream","text/plain","text/markdown","application/json"].includes(d.mediaType)||!Number.isSafeInteger(d.size)||d.size<0||d.size>16*1024*1024||typeof d.sha256!=="string"||!/^[0-9a-f]{64}$/.test(d.sha256))return invalid();return d}function safeEnrichmentName(value){return safeFileName(value)&&!/^original(?:\.|$)/i.test(value)}function parseFileEnrichMetadata(value,maxBytes){const invalid=(reason="invalid_metadata")=>{throw new FileOperationError("invalid_input",400,false,{reason})};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const d=value;if(Object.keys(d).some((key)=>!["name","size","mediaType","replace"].includes(key)))return invalid();if(!safeEnrichmentName(d.name))return invalid("invalid_enrichment_name");if(!Number.isSafeInteger(d.size)||d.size<0)return invalid("invalid_size");if(d.mediaType!==undefined&&(typeof d.mediaType!=="string"||d.mediaType.length>255||/[\u0000-\u001f\u007f]/.test(d.mediaType)))return invalid("invalid_media_type");if(d.replace!==undefined&&(typeof d.replace!=="string"||!/^[0-9a-f]{64}$/.test(d.replace)))return invalid("invalid_replacement");if(d.size>maxBytes)throw new FileOperationError("request_too_large",413,false,{reason:"size_limit",limitBytes:maxBytes,receivedBytes:d.size});return d}function safeFileName(value){return typeof value==="string"&&value.length>0&&value.length<=255&&value===value.trim()&&value!=="."&&value!==".."&&!/[\u0000-\u001f\u007f-\u009f/\\:*?"<>|]/u.test(value)&&!/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(value)&&!/[. ]$/.test(value)&&!/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(value)}function safeFilePath(value){return typeof value==="string"&&value.length<=1024&&value.split("/").every(safeFileName)}function safeManagedFilePath(value){return safeFilePath(value)&&value.split("/")[0].toLowerCase()!==".os"}function declaredOriginalMediaType(value){if(typeof value!=="string"||value.length>255||/[\u0000-\u001f\u007f-\u009f]/.test(value))throw new FileOperationError("invalid_input",400,false,{reason:"invalid_media_type"});const normalized=value.split(";",1)[0].trim().toLowerCase();const token="[a-z0-9!#$%&'+.^_`|~-]+";if(!new RegExp(`^${token}/${token}$`).test(normalized))throw new FileOperationError("invalid_input",400,false,{reason:"invalid_media_type"});return normalized}function isCanonicalOriginalMediaType(value){try{return declaredOriginalMediaType(value)===value}catch{return false}}function parseFileCreateMetadata(value,maxBytes){const invalid=(reason="invalid_metadata")=>{throw new FileOperationError("invalid_input",400,false,{reason})};if(!value||typeof value!=="object"||Array.isArray(value))return invalid();const input=value;if(Object.keys(input).some((key)=>!["name","path","storage","mediaType","size","requestKey"].includes(key)))return invalid();const path=input.path===undefined?"Files":input.path;if(!safeFileName(input.name))return invalid("invalid_name");if(!safeManagedFilePath(path))return invalid("invalid_path");if(input.storage!==undefined&&input.storage!=="remote"&&input.storage!=="local")return invalid("invalid_storage");const mediaType=input.mediaType===undefined?"application/octet-stream":declaredOriginalMediaType(input.mediaType);if(!Number.isSafeInteger(input.size)||input.size<0)return invalid("invalid_size");if(input.size>maxBytes)throw new FileOperationError("request_too_large",413,false,{reason:"size_limit",limitBytes:maxBytes,receivedBytes:input.size});if(typeof input.requestKey!=="string"||input.requestKey.length<1||input.requestKey.length>256||input.requestKey!==input.requestKey.trim()||/[\u0000-\u001f\u007f]/.test(input.requestKey))return invalid("invalid_request_key");return{name:input.name,path,...input.storage?{storage:input.storage}:{},mediaType,size:input.size,requestKey:input.requestKey}}class AppRoutineContractError extends Error{code;constructor(code){super(code);this.code=code}}var propertyName=/^[a-z][A-Za-z0-9]*(?![\s\S])/;var stepId=/^[a-z0-9]+(?:-[a-z0-9]+)*(?![\s\S])/;var routineName=/^[a-z0-9][a-z0-9-]{0,62}(?![\s\S])/;function isAppRoutineName(value){return typeof value==="string"&&routineName.test(value)}var owns=(value,key)=>Object.hasOwn(value,key);var invalidContract=()=>{throw new AppRoutineContractError("invalid_contract")};var invalidValue=()=>{throw new AppRoutineContractError("invalid_value")};function record(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)&&(Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null)}function fields(value,required,optional=[]){return required.every((key)=>owns(value,key))&&Object.keys(value).every((key)=>required.includes(key)||optional.includes(key))}function denseArray(value){return Array.isArray(value)&&Object.keys(value).length===value.length&&Array.from({length:value.length},(_,index)=>owns(value,String(index))).every(Boolean)}function parseAppRoutineContract(value){let properties=0;function schema(value2,depth=1){if(depth>8||!record(value2))return invalidContract();switch(value2.type){case"object":{if(!fields(value2,["type","properties","additionalProperties"],["required"])||value2.additionalProperties!==false||!record(value2.properties))return invalidContract();const entries=Object.entries(value2.properties);properties+=entries.length;if(properties>64||entries.some(([key])=>!propertyName.test(key)))return invalidContract();let required;if(owns(value2,"required")){if(!denseArray(value2.required)||value2.required.some((key)=>typeof key!=="string"||!owns(value2.properties,key))||new Set(value2.required).size!==value2.required.length)return invalidContract();required=[...value2.required]}return{type:"object",properties:Object.fromEntries(entries.map(([key,child])=>[key,schema(child,depth+1)])),...required===undefined?{}:{required},additionalProperties:false}}case"array":if(!fields(value2,["type","items"],["maxItems"])||owns(value2,"maxItems")&&(!Number.isSafeInteger(value2.maxItems)||value2.maxItems<1))return invalidContract();return{type:"array",items:schema(value2.items,depth+1),...owns(value2,"maxItems")?{maxItems:value2.maxItems}:{}};case"boolean":if(!fields(value2,["type"]))return invalidContract();return{type:value2.type};case"file":if(!fields(value2,["type"],["storage","path"])||owns(value2,"storage")&&value2.storage!=="local"&&value2.storage!=="remote"||owns(value2,"path")&&!safeManagedFilePath(value2.path))return invalidContract();return{type:"file",...owns(value2,"storage")?{storage:value2.storage}:{},...owns(value2,"path")?{path:value2.path}:{}};case"string":if(!fields(value2,["type"],["maxLength"])||owns(value2,"maxLength")&&(!Number.isSafeInteger(value2.maxLength)||value2.maxLength<0||value2.maxLength>4096))return invalidContract();return{type:"string",...owns(value2,"maxLength")?{maxLength:value2.maxLength}:{}};case"integer":case"number":{const validNumber=value2.type==="integer"?Number.isSafeInteger:Number.isFinite;if(!fields(value2,["type"],["minimum","maximum"])||owns(value2,"minimum")&&!validNumber(value2.minimum)||owns(value2,"maximum")&&!validNumber(value2.maximum)||owns(value2,"minimum")&&owns(value2,"maximum")&&value2.minimum>value2.maximum)return invalidContract();return{type:value2.type,...owns(value2,"minimum")?{minimum:value2.minimum}:{},...owns(value2,"maximum")?{maximum:value2.maximum}:{}}}default:return invalidContract()}}if(!record(value)||!fields(value,["routine","input","steps"],["result"])||!isAppRoutineName(value.routine)||!denseArray(value.steps)||value.steps.length<1||value.steps.length>64)return invalidContract();const input=schema(value.input);const result=owns(value,"result")?schema(value.result):undefined;const ids=new Set;const steps=value.steps.map((step)=>{if(!record(step)||!fields(step,["id"],["summary"])||typeof step.id!=="string"||!stepId.test(step.id)||ids.has(step.id))return invalidContract();ids.add(step.id);return{id:step.id,...owns(step,"summary")?{summary:schema(step.summary)}:{}}});return{routine:value.routine,input,steps,...result===undefined?{}:{result}}}function jsonData(value,ancestors=new Set){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return;if(!record(value)&&!denseArray(value))return invalidValue();if(ancestors.has(value))return invalidValue();ancestors.add(value);for(const child of Object.values(value))jsonData(child,ancestors);ancestors.delete(value)}function validateRoutineSchemaValue(schema,value,rejected){const type=(value2)=>value2===null?"null":Array.isArray(value2)?"array":["object","boolean","string","number"].includes(typeof value2)?typeof value2:"other";function check(schema2,value2,path){const fail=(reason,extra={})=>{rejected?.({reason,path:path.length<=256?path:"$",expected:schema2.type,received:type(value2),...extra});return invalidValue()};switch(schema2.type){case"object":if(!record(value2))return fail("wrong_type");for(const key of schema2.required??[])if(!owns(value2,key))return fail("missing_field",{path:`${path}.${key}`.length<=256?`${path}.${key}`:"$",expected:schema2.properties[key].type,received:"missing"});if(Object.keys(value2).some((key)=>!owns(schema2.properties,key)))return fail("unexpected_field");for(const[key,child]of Object.entries(value2))check(schema2.properties[key],child,`${path}.${key}`);return;case"array":if(!denseArray(value2))return fail("wrong_type");if(schema2.maxItems!==undefined&&value2.length>schema2.maxItems)return fail("out_of_bounds",{constraint:"maxItems",limit:schema2.maxItems});value2.forEach((child,index)=>check(schema2.items,child,`${path}[${index}]`));return;case"boolean":if(typeof value2!=="boolean")return fail("wrong_type");return;case"string":if(typeof value2!=="string")return fail("wrong_type");if(Array.from(value2).length>(schema2.maxLength??4096))return fail("out_of_bounds",{constraint:"maxLength",limit:schema2.maxLength??4096});return;case"integer":case"number":if(typeof value2!=="number"||!(schema2.type==="integer"?Number.isSafeInteger(value2):Number.isFinite(value2)))return fail("wrong_type");if(schema2.minimum!==undefined&&value2<schema2.minimum)return fail("out_of_bounds",{constraint:"minimum",limit:schema2.minimum});if(schema2.maximum!==undefined&&value2>schema2.maximum)return fail("out_of_bounds",{constraint:"maximum",limit:schema2.maximum});return;case"file":{let file;try{jsonData(value2);file=parseFileDescriptor(value2)}catch{return fail("invalid_file")}if(schema2.path!==undefined&&file.path!==schema2.path)return fail("invalid_file")}}}check(schema,value,"$")}function validRecordRef(value){return typeof value==="string"&&value.length<=512&&/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(value)}function validDropboxRootPath(value){return value===""||typeof value==="string"&&value.length<=2048&&value.startsWith("/")&&!/[\\\x00-\x1f\x7f]/.test(value)&&value.slice(1).split("/").every((segment)=>segment.length>0&&segment.trim()===segment&&segment!=="."&&segment!=="..")}function validMicrosoftId(value){return typeof value==="string"&&/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value)}function validMicrosoftMailbox(value){return typeof value==="string"&&value.length<=254&&/^[^\s@/?#\\\x00-\x1f\x7f]+@[^\s@/?#\\\x00-\x1f\x7f]+\.[^\s@/?#\\\x00-\x1f\x7f]+$/.test(value)}function sharePointHost(value){return/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.sharepoint\.com$/.test(value)}function canonicalSharePointSiteUrl(value){if(typeof value!=="string"||value.length>2048||/[\s\\?#\x00-\x1f\x7f]/.test(value)||!/^https:\/\/[^/:@]+(?:\/|$)/i.test(value))return;try{const url=new URL(value);if(url.protocol!=="https:"||!sharePointHost(url.hostname)||url.username||url.password||url.port)return;const rawPath=value.replace(/^https:\/\/[^/]+/i,"")||"/";const path=rawPath.endsWith("/")?rawPath.slice(0,-1):rawPath;const segments=path.slice(1).split("/");if(path&&segments.some((segment)=>!segment))return;const encoded=path?segments.map((segment)=>{const decoded=decodeURIComponent(segment);if(decoded==="."||decoded===".."||/[/%\\?#\x00-\x1f\x7f]/.test(decoded))throw new Error;return encodeURIComponent(decoded)}).join("/"):"";const canonical=`https://${url.hostname}/${encoded}`;return canonical.length<=2048?canonical:undefined}catch{return}}function validSharePointSiteId(value,siteUrl){if(typeof value!=="string"||value.length>512)return false;const[host,collection,site,extra]=value.split(",");return extra===undefined&&host===new URL(siteUrl).hostname&&validMicrosoftId(collection)&&validMicrosoftId(site)}function validGoogleScopes(value){return Array.isArray(value)&&value.length>0&&value.length<=32&&value.every((scope)=>typeof scope==="string"&&scope.length<=256&&/^(https:\/\/www\.googleapis\.com\/auth\/[A-Za-z0-9._-]+|https:\/\/mail\.google\.com\/|openid|email|profile)$/.test(scope))&&new Set(value).size===value.length}var DROPBOX_FILE_SCOPES=["account_info.read","files.metadata.read","files.content.read","files.content.write"];function validDropboxFileScopes(value){return Array.isArray(value)&&value.length===DROPBOX_FILE_SCOPES.length&&new Set(value).size===value.length&&DROPBOX_FILE_SCOPES.every((scope)=>value.includes(scope))}function validDataRepositoryName(value){return typeof value==="string"&&/^[a-z0-9][a-z0-9._-]{0,127}$/.test(value)&&!value.includes("..")}class InboxContractError extends Error{constructor(message){super(message);this.name="InboxContractError"}}var INBOX_PUBLICATION_ITEM_BYTES=1024*1024;var INBOX_PUBLICATION_REQUEST_BYTES=INBOX_PUBLICATION_ITEM_BYTES+4096;var publicationAdvice="Trim the content, or attach long reports, data, and supporting materials as files instead. Then try again.";var INBOX_PUBLICATION_TOO_LARGE=`Your Inbox item failed to publish. Its content exceeds the 1 MB limit. ${publicationAdvice}`;class InboxPublicationSizeError extends InboxContractError{kind;bytes;constructor(kind,bytes){const label=kind==="ask"?"Ask":"Digest";const size=Math.ceil(bytes/INBOX_PUBLICATION_ITEM_BYTES*100)/100;super(`Your ${label} failed to publish. Its content is ${size} MB, which exceeds the 1 MB limit. ${publicationAdvice}`);this.kind=kind;this.bytes=bytes;this.name="InboxPublicationSizeError"}}function enforcePublicationSize(value){const bytes=new TextEncoder().encode(JSON.stringify(value)).byteLength;if(bytes>INBOX_PUBLICATION_ITEM_BYTES)throw new InboxPublicationSizeError(value.kind,bytes);return value}function fail(message){throw new InboxContractError(message)}function object(value,label){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))fail(`${label} must be a plain object`);return value}function keys(value,allowed,label){for(const key of Reflect.ownKeys(value)){if(typeof key!=="string"||!allowed.includes(key))fail(`${label} does not support ${String(key)}`);const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!descriptor.enumerable||!("value"in descriptor))fail(`${label} must contain only JSON data`)}}function text(value,label){if(typeof value!=="string"||!value.trim())fail(`${label} must be nonempty text`);return value}function id(value,label){const result=text(value,label);if(result!==result.trim())fail(`${label} cannot have surrounding whitespace`);return result}function array(value,label){if(!Array.isArray(value)||Object.getPrototypeOf(value)!==Array.prototype||Reflect.ownKeys(value).length!==value.length+1)fail(`${label} must be a dense array`);for(let index=0;index<value.length;index+=1){const descriptor=Object.getOwnPropertyDescriptor(value,String(index));if(!descriptor?.enumerable||!("value"in descriptor))fail(`${label} must contain only JSON data`)}return value}function distinctIds(value,label,nonempty=true){const result=array(value,label).map((entry)=>id(entry,label));if(nonempty&&!result.length)fail(`${label} must not be empty`);if(new Set(result).size!==result.length)fail(`${label} contains duplicate IDs`);return result}var memberEmail=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function personReference(value,label){const result=id(value,label);return memberEmail.test(result)?result.toLowerCase():result}function distinctPeople(value,label,nonempty=true){const result=array(value,label).map((entry)=>personReference(entry,label));if(nonempty&&!result.length)fail(`${label} must not be empty`);if(new Set(result).size!==result.length)fail(`${label} contains duplicate IDs`);return result}function serializable(value,ancestors=new Set){if(value===null||typeof value==="boolean"||typeof value==="string")return value;if(typeof value==="number"&&Number.isFinite(value))return value;if(!value||typeof value!=="object")fail("Input must be losslessly serializable JSON");if(ancestors.has(value))fail("Input cannot contain cycles");ancestors.add(value);try{if(Array.isArray(value)){array(value,"JSON array");return value.map((entry)=>serializable(entry,ancestors))}const source=object(value,"JSON input");keys(source,Object.keys(source),"JSON input");return Object.fromEntries(Object.entries(source).map(([key,entry])=>[key,serializable(entry,ancestors)]))}finally{ancestors.delete(value)}}function natural(value,label,minimum=0){if(!Number.isSafeInteger(value)||value<minimum)fail(`${label} must be an integer >= ${minimum}`);return value}function validateInboxFile(value){const v=object(serializable(value),"Inbox file");keys(v,["id","name","mediaType","size","sha256"],"Inbox file");const fileId=id(v.id,"Inbox file ID"),name=id(v.name,"filename"),mediaType=id(v.mediaType,"media type");if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(fileId)||/[\x00-\x1f\x7f/\\]/.test(name)||!isCanonicalOriginalMediaType(mediaType)||typeof v.sha256!=="string"||!/^[0-9a-f]{64}$/.test(v.sha256))fail("Invalid Inbox file identity or metadata");const size=natural(v.size,"file size");if(size>FILE_ORIGINAL_MAX_BYTES)fail("File exceeds supported size");return{id:fileId,name,mediaType,size,sha256:v.sha256}}function validateQualifiedRecordRef(value){const r=object(value,"Record reference");keys(r,["repository","ref"],"Record reference");if(!validDataRepositoryName(r.repository)||!validRecordRef(r.ref))fail("Invalid qualified Record reference");return{repository:r.repository,ref:r.ref}}function validateBlock(value){const b=object(serializable(value),"Block");if(b.kind==="rich-text"){keys(b,["kind","markdown"],"Rich text Block");return{kind:"rich-text",markdown:text(b.markdown,"Markdown")}}if(b.kind==="asks"){keys(b,["kind","problem","asks"],"Asks Block");const asks=distinctIds(b.asks,"Ask IDs");if(asks.some((ask)=>!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(ask)))fail("Invalid Ask ID");return{kind:"asks",problem:text(b.problem,"problem"),asks}}if(!["record","records","files"].includes(b.kind))fail("Unknown Block kind");keys(b,["kind","label","initiallyExpanded",...b.kind==="record"?["record"]:b.kind==="records"?["records"]:["files"]],"Block");const label=text(b.label,"Block label");if(b.initiallyExpanded!==undefined&&typeof b.initiallyExpanded!=="boolean")fail("Invalid initiallyExpanded");const expanded=b.initiallyExpanded===undefined?{}:{initiallyExpanded:b.initiallyExpanded};if(b.kind==="record")return{kind:"record",label,record:validateQualifiedRecordRef(b.record),...expanded};if(b.kind==="records"){const records=array(b.records,"records").map(validateQualifiedRecordRef);if(!records.length||new Set(records.map((r)=>JSON.stringify([r.repository,r.ref]))).size!==records.length)fail("Empty or duplicate records");return{kind:"records",label,records,...expanded}}const files=array(b.files,"files").map(validateInboxFile);if(!files.length||new Set(files.map((file)=>file.id)).size!==files.length)fail("Empty or duplicate files");return{kind:"files",label,files,...expanded}}function richTextBlock(value){return validateBlock({...value,kind:"rich-text"})}function recordBlock(value){return validateBlock({...value,kind:"record"})}function recordsBlock(value){return validateBlock({...value,kind:"records"})}function fileBlock(value){const input=object(serializable(value),"Files Block");const files=array(input.files,"files").map((entry)=>{const descriptor=object(entry,"File");if(!(("path"in descriptor)||("enrichments"in descriptor)))return validateInboxFile(descriptor);let file;try{file=parseFileDescriptor(descriptor)}catch{return fail("Invalid shared File descriptor")}const{id:id2,name,mediaType,size,sha256}=file;return{id:id2,name,mediaType,size,sha256}});return validateBlock({...input,kind:"files",files})}function asksBlock(value){return validateBlock({...value,kind:"asks"})}function selection(value){const input=object(value,"selection");keys(input,["source"],"selection");return validateResponseDefinition({type:"selection",source:input.source})}function validateAuthoredSource(value){const source=object(value,"response definition");keys(source,["type","options","suggestions","search"],"response definition");if(source.type!=="authored")fail("Expected authored options");const options=array(source.options,"options").map((entry)=>{const option=object(entry,"choice");keys(option,["value","label","description","note"],"choice");let note;if(option.note!==undefined){const declaration=object(option.note,"choice note");keys(declaration,["placeholder"],"choice note");note={placeholder:text(declaration.placeholder,"note placeholder")}}return{value:id(option.value,"choice value"),label:text(option.label,"choice label"),...option.description===undefined?{}:{description:text(option.description,"choice description")},...note?{note}:{}}});if(!options.length)fail("Choices require at least one option");if(new Set(options.map((option)=>option.value)).size!==options.length)fail("Duplicate choice value");if(Object.hasOwn(source,"search")||Object.hasOwn(source,"suggestions")){const labels=object(source.search,"choice search");keys(labels,["triggerLabel","placeholder","emptyLabel"],"choice search");const search={triggerLabel:text(labels.triggerLabel,"search trigger label"),placeholder:text(labels.placeholder,"search placeholder"),emptyLabel:text(labels.emptyLabel,"search empty label")};const suggestions=array(source.suggestions,"suggestions").map((value2)=>id(value2,"suggestion value"));if(suggestions.length>8||new Set(suggestions).size!==suggestions.length||suggestions.some((value2)=>!options.some((option)=>option.value===value2)))fail("Search permits at most eight unique published suggestions");return{type:"authored",options,suggestions,search}}if(options.length>9)fail("Choices require one to nine options");return{type:"authored",options}}function validateRecordReference(value){const row=object(value,"Record reference");keys(row,["repository","ref"],"Record reference");const repository=id(row.repository,"repository"),ref=id(row.ref,"Record reference");if(!/^[a-z0-9][a-z0-9._/-]{0,127}$/.test(repository)||/\.\.|\/\//.test(repository)||ref.length>512||!/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)+$/.test(ref))fail("Invalid Record identity");return{repository,ref}}function validateRecordSource(value){const source=object(value,"Record selection");keys(source,["type","collection","refPrefix","where","display","suggestions"],"Record selection");if(source.type!=="records")fail("Expected Record options");const collection=object(source.collection,"collection");keys(collection,["repository","name"],"collection");const repository=validateRecordReference({repository:collection.repository,ref:"records/example"}).repository;const name=id(collection.name,"collection name");if(!/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(name))fail("Invalid collection name");const refPrefix=source.refPrefix===undefined?undefined:id(source.refPrefix,"Record reference prefix");if(refPrefix!==undefined&&(!refPrefix.endsWith("/")||refPrefix.length>512||!/^[_a-zA-Z0-9][a-zA-Z0-9_-]*(\/[_a-zA-Z0-9][a-zA-Z0-9_-]*)*\/$/.test(refPrefix)))fail("Invalid Record reference prefix");const where=object(source.where??{},"Record filter");const fieldName=(name2)=>/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name2)&&!["constructor","prototype"].includes(name2);for(const[name2,value2]of Object.entries(where)){if(!fieldName(name2)||!(value2===null||["string","number","boolean"].includes(typeof value2))||typeof value2==="number"&&!Number.isFinite(value2))fail("Record filters require scalar equality")}const display=object(source.display,"Record display");keys(display,["labelFields"],"Record display");const labelFields=distinctIds(display.labelFields,"label fields");if(labelFields.length>2||labelFields.some((name2)=>!fieldName(name2)))fail("Select one or two scalar label fields");const suggestions=array(source.suggestions??[],"suggestions").map((value2)=>{const entry=object(value2,"suggestion");keys(entry,["record","reason"],"suggestion");const record2=validateRecordReference(entry.record);if(record2.repository!==repository)fail("Suggestion belongs to another repository");return{record:record2,...entry.reason===undefined?{}:{reason:text(entry.reason,"suggestion reason")}}});if(suggestions.length>8||new Set(suggestions.map((entry)=>entry.record.ref)).size!==suggestions.length)fail("Record selection permits at most eight unique suggestions");return{type:"records",collection:{repository,name},...refPrefix?{refPrefix}:{},where:{...where},display:{labelFields},suggestions}}function validateResponseDefinition(value){const definition=object(value,"response definition");keys(definition,["type","source"],"response definition");if(definition.type!=="selection")fail("Expected a selection definition");const source=object(definition.source,"option source");switch(source.type){case"authored":return{type:"selection",source:validateAuthoredSource(source)};case"records":return{type:"selection",source:validateRecordSource(source)};default:return fail("Unsupported option source")}}function handlerReference(value){const source=object(value,"handler reference");keys(source,["id","input"],"handler reference");return{id:id(source.id,"handler ID"),input:serializable(source.input)}}function defineHandler(value){const source=object(value,"handler");keys(source,["id","results","run"],"handler");const stable=(value2)=>typeof value2==="string"&&/^[a-zA-Z0-9][a-zA-Z0-9_./-]{0,127}$/.test(value2);if(!stable(source.id))fail("Handler ID must be stable");const results=source.results===undefined?undefined:distinctIds(source.results,"handler results",false);if(results&&(results.length>64||results.some((result)=>!stable(result))))fail("Handler results must be stable IDs");if(typeof source.run!=="function")fail("Handler requires a run function");return Object.freeze({id:value.id,...results===undefined?{}:{results:Object.freeze(results.sort())},run:value.run})}function respond(handler,input){defineHandler(handler);return handlerReference({id:handler.id,input})}function question(value){const source=object(value,"question");keys(source,["id","to","allowedResponders","prompt","instructions","response","handler"],"question");const to=personReference(source.to,"question assignee");const allowedResponders=source.allowedResponders===undefined?[to]:distinctPeople(source.allowedResponders,"allowed responders");if(!allowedResponders.includes(to))fail("Allowed responders must include the assignee");return{id:id(source.id,"question ID"),to,allowedResponders,prompt:text(source.prompt,"question prompt"),...source.instructions===undefined?{}:{instructions:text(source.instructions,"instructions")},response:validateResponseDefinition(source.response),...Object.hasOwn(source,"handler")?{handler:handlerReference(source.handler)}:{}}}function presentation(source){const views=source.views===undefined?[]:array(source.views,"views").map((entry)=>{const view=object(entry,"view");keys(view,["id","view","input"],"view");return{id:id(view.id,"view ID"),view:id(view.view,"view name"),input:serializable(view.input)}});if(new Set(views.map((view)=>view.id)).size!==views.length)fail("Duplicate view ID");const body=source.body===undefined?[]:array(source.body,"body").map(validateBlock);return{title:text(source.title,"title"),description:text(source.description,"description"),views,body}}function validatePublication(value){const source=object(value,"publication");if(source.kind!=="ask"&&source.kind!=="digest")fail("Publication requires an explicit kind");keys(source,["kind","title","description","recipients","views","body","notifyImmediately",...source.kind==="ask"?["questions","tags","recordRefs"]:[]],"publication");if(source.notifyImmediately!==undefined&&typeof source.notifyImmediately!=="boolean")fail("notifyImmediately must be a boolean");const itemPresentation={...presentation(source),...source.notifyImmediately===undefined?{}:{notifyImmediately:source.notifyImmediately}};const linkedAsks=(itemPresentation.body??[]).flatMap((block)=>block.kind==="asks"?block.asks:[]);if(new Set(linkedAsks).size!==linkedAsks.length)fail("Ask belongs to more than one problem");if(source.kind==="digest")return{kind:"digest",...itemPresentation,recipients:distinctPeople(source.recipients,"digest recipients")};if(itemPresentation.body?.some((block)=>block.kind==="asks"))fail("Asks Blocks belong to Digests");const questions=array(source.questions===undefined?[]:source.questions,"questions").map((value2)=>question(value2));if(new Set(questions.map((entry)=>entry.id)).size!==questions.length)fail("Duplicate question ID");const extra=source.recipients===undefined?[]:distinctPeople(source.recipients,"recipients",false);if(!questions.length&&!extra.length)fail("Ask requires at least one recipient");const tags=array(source.tags===undefined?[]:source.tags,"Ask tags").map((value2)=>{const tag=text(value2,"Ask tag");if(new TextEncoder().encode(tag).byteLength>64)fail("Ask tag exceeds 64 UTF-8 bytes");return tag});if(tags.length>32||new Set(tags).size!==tags.length)fail("Ask tags exceed bounds or contain duplicates");const recordRefs=array(source.recordRefs===undefined?[]:source.recordRefs,"Ask Record references").map((value2)=>{const row=object(value2,"Ask Record reference");keys(row,["repository","id"],"Ask Record reference");const{repository,ref}=validateRecordReference({repository:row.repository,ref:row.id});return{repository,id:ref}});if(new Set(recordRefs.map((ref)=>JSON.stringify([ref.repository,ref.id]))).size!==recordRefs.length)fail("Ask Record references contain duplicates");return{kind:"ask",...itemPresentation,questions,tags,recordRefs,recipients:[...new Set([...extra,...questions.flatMap((entry)=>[entry.to,...entry.allowedResponders])])]}}function continueAsk(value){const source=object(value,"continueAsk");keys(source,[],"continueAsk");return{type:"continue"}}function resolution(value){const source=object(value,"resolution");keys(source,["outcome","evidence"],"resolution");return{outcome:text(source.outcome,"outcome"),...source.evidence===undefined?{}:{evidence:array(source.evidence,"evidence").map((entry)=>serializable(entry))}}}function resolveAsk(value){return{type:"resolve",...resolution(value)}}function validateResolution(value){const source=object(value,"published resolution");keys(source,["expectedRevision","outcome","evidence"],"published resolution");if(!Number.isSafeInteger(source.expectedRevision)||source.expectedRevision<1)fail("Expected revision must be a positive integer");return{expectedRevision:source.expectedRevision,...resolution({outcome:source.outcome,...source.evidence===undefined?{}:{evidence:source.evidence}})}}function publicationRequestKey(value){const options=object(value,"publication options");keys(options,["requestKey"],"publication options");return id(options.requestKey,"publication request key")}function createInboxPublisher(transport){return{async publishAsk(value,options){const source=object(value,"ask");keys(source,["title","description","recipients","views","body","questions","notifyImmediately","tags","recordRefs"],"ask");const result=await transport.publish({requestKey:publicationRequestKey(options),item:enforcePublicationSize(validatePublication({...source,kind:"ask"}))});id(result.id,"published ask ID");if(!("revision"in result)||!Number.isSafeInteger(result.revision)||result.revision!==1)fail("Initial ask publication must return revision 1");return{id:result.id,revision:result.revision}},async publishDigest(value,options){const source=object(value,"digest");keys(source,["title","description","recipients","views","body","notifyImmediately"],"digest");const result=await transport.publish({requestKey:publicationRequestKey(options),item:enforcePublicationSize(validatePublication({...source,kind:"digest"}))});return{id:id(result.id,"published digest ID")}},async publishResolution(askId,value){await transport.resolve({askId:id(askId,"ask ID"),resolution:validateResolution(value)})}}}var ROUTINE_DECLARATION_SCHEMA="https://schemas.oddington.ai/routine/v1.json";var ROUTINE_SOURCE_LIMITS={files:20000,bytes:256*1024*1024,declarationBytes:64*1024};var invalid=(field)=>{throw new Error(`Invalid routine declaration: ${field}`)};var object2=(value,fields2,field)=>{if(!value||typeof value!=="object"||Array.isArray(value)||Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null||Reflect.ownKeys(value).some((key)=>typeof key!=="string"||!fields2.includes(key)||!Object.getOwnPropertyDescriptor(value,key).enumerable||!Object.hasOwn(Object.getOwnPropertyDescriptor(value,key),"value")))invalid(field);return value};var routineAlias=(value)=>typeof value==="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(value);var list=(value,field,allowed,qualified=false)=>{if(value===undefined)return[];if(!Array.isArray(value)||value.length>64||value.some((item)=>!(routineAlias(item)||qualified&&typeof item==="string"&&item.split("/").length===2&&item.split("/").every(routineAlias))||allowed&&!allowed.includes(item))||new Set(value).size!==value.length)invalid(field);return[...value].sort()};function routineAssetPattern(value){return typeof value==="string"&&value.length<=512&&!value.startsWith("/")&&!value.includes("\\")&&!value.includes(":")&&value.split("/").every((part)=>!!part&&part!=="."&&part!==".."&&/^[a-zA-Z0-9_.*-]+$/.test(part))}function parseRoutineDeclaration(value){const v=object2(value,["$schema","access","runtime","retry","assets"],"fields");if(v.$schema!==ROUTINE_DECLARATION_SCHEMA)invalid("$schema");const access=object2(v.access===undefined?{}:v.access,["repositories","connections","ai","files","publish"],"access");if(Object.hasOwn(access,"ai")&&access.ai!==true)invalid("access.ai");const rawRepositories=access.repositories===undefined?{}:access.repositories;const repositories=object2(rawRepositories,rawRepositories&&typeof rawRepositories==="object"?Object.keys(rawRepositories):[],"access.repositories");if(Object.keys(repositories).length>64)invalid("access.repositories");const grants={};for(const key of Object.keys(repositories).sort()){if(!routineAlias(key)||!["read","write"].includes(repositories[key]))invalid(`access.repositories.${key}`);grants[key]=repositories[key]}if(access.files!==undefined&&!["read","read-write"].includes(access.files))invalid("access.files");const runtime=object2(v.runtime===undefined?{}:v.runtime,["features","resources","maxDuration"],"runtime");if(runtime.features!==undefined&&(!Array.isArray(runtime.features)||runtime.features.length!==0))invalid("runtime.features");if(runtime.resources!==undefined&&runtime.resources!=="standard")invalid("runtime.resources");if(runtime.maxDuration!==undefined&&!["15m","60m"].includes(runtime.maxDuration))invalid("runtime.maxDuration");const retry=object2(v.retry===undefined?{}:v.retry,["maxAttempts"],"retry");if(retry.maxAttempts!==undefined&&retry.maxAttempts!==1)invalid("retry.maxAttempts");const assets=v.assets===undefined?[]:v.assets;if(!Array.isArray(assets)||assets.length>64||assets.some((item)=>!routineAssetPattern(item))||new Set(assets).size!==assets.length)invalid("assets");return{$schema:ROUTINE_DECLARATION_SCHEMA,access:{repositories:grants,connections:list(access.connections,"access.connections",undefined,true),...access.ai===true?{ai:true}:{},...access.files===undefined?{}:{files:access.files},publish:list(access.publish,"access.publish",["asks","digests"])},runtime:{features:[],resources:"standard",maxDuration:runtime.maxDuration??"60m"},retry:{maxAttempts:1},assets:[...assets].sort()}}var invalid2=()=>{throw new AppRoutineContractError("invalid_value")};var invalidContract2=()=>{throw new AppRoutineContractError("invalid_contract")};var routineTitle=(value)=>typeof value==="string"&&value.trim().length>0&&value.length<=256;function freezeRoutineMetadata(value){if(value!==null&&typeof value==="object"){for(const child of Object.values(value))freezeRoutineMetadata(child);Object.freeze(value)}return value}function assertRoutineJson(value,ancestors=new Set){if(value===null||typeof value==="string"||typeof value==="boolean"||typeof value==="number"&&Number.isFinite(value))return;if(!value||typeof value!=="object"||ancestors.has(value))return invalid2();const array2=Array.isArray(value);if(!array2&&Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null)return invalid2();const keys2=Reflect.ownKeys(value);if(array2&&(keys2.length!==value.length+1||!Array.from({length:value.length},(_,index)=>Object.hasOwn(value,index)).every(Boolean)))return invalid2();ancestors.add(value);for(const key of keys2){if(array2&&key==="length")continue;if(typeof key!=="string")return invalid2();const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!descriptor.enumerable||!Object.hasOwn(descriptor,"value"))return invalid2();assertRoutineJson(descriptor.value,ancestors)}ancestors.delete(value)}function assertRoutineFields(value,allowed){if(!value||typeof value!=="object"||Object.getPrototypeOf(value)!==Object.prototype||Reflect.ownKeys(value).some((key)=>typeof key!=="string"||allowed&&!allowed.includes(key)||!Object.getOwnPropertyDescriptor(value,key).enumerable||!Object.hasOwn(Object.getOwnPropertyDescriptor(value,key),"value")))return invalidContract2()}function parseRoutineAccess(value){try{if(value!==undefined)assertRoutineJson(value);assertRoutineFields(value??{},["repositories","connections","ai","files","publish"]);const access=value;const names=access?.connections??[];if(!Array.isArray(names)||names.length>64||new Set(names).size!==names.length||names.some((name)=>typeof name!=="string"||name.split("/").length!==2||name.split("/").some((part)=>!isAppRoutineName(part))))return invalidContract2();const parsed=parseRoutineDeclaration({$schema:ROUTINE_DECLARATION_SCHEMA,access:{...access,connections:[]}}).access;return freezeRoutineMetadata({...parsed,connections:[...names]})}catch{return invalidContract2()}}function parseRoutineAIOutputIssue(value){if(!value||typeof value!=="object"||Array.isArray(value))return;const v=value;if(["invalid_json","invalid_response","empty_text","structured_output_limit"].includes(String(v.reason)))return Object.keys(v).join(",")==="reason"?{reason:v.reason}:undefined;if(!["missing_field","unexpected_field","wrong_type","out_of_bounds","invalid_file"].includes(String(v.reason))||typeof v.path!=="string"||v.path.length>256||!/^\$(?:\.[a-z][A-Za-z0-9]*|\[(?:0|[1-9][0-9]*)\])*$/.test(v.path)||!["object","array","boolean","string","integer","number","file"].includes(String(v.expected))||!["missing","null","object","array","boolean","string","number","other"].includes(String(v.received))||Object.keys(v).some((key)=>!["reason","path","expected","received","constraint","limit"].includes(key)))return;if(v.reason==="out_of_bounds"){if(!["maxLength","maxItems","minimum","maximum"].includes(String(v.constraint))||typeof v.limit!=="number"||!Number.isFinite(v.limit))return}else if(Object.hasOwn(v,"constraint")||Object.hasOwn(v,"limit"))return;return{reason:v.reason,path:v.path,expected:v.expected,received:v.received,...v.reason==="out_of_bounds"?{constraint:v.constraint,limit:v.limit}:{}}}function routineAIOutputMessage(issue){if(issue.reason==="structured_output_limit")return"AI couldn’t produce an answer matching the requested format within its submission limit.";if(issue.reason==="invalid_json")return"AI replied, but its answer could not be read as JSON.";if(issue.reason==="invalid_response")return"AI returned a response OS could not read.";if(issue.reason==="empty_text")return"AI returned an empty answer.";const field=issue.path==="$"?"response":issue.path.slice(issue.path.startsWith("$.")?2:1);const expected={object:"an object",array:"a list",boolean:"true or false",string:"text",integer:"a whole number",number:"a number",file:"a File"}[issue.expected];const received={missing:"a missing field",null:"null",object:"an object",array:"a list",boolean:"true or false",string:"text",number:"a number",other:"an unsupported value"}[issue.received];if(issue.reason==="missing_field")return`AI response is missing a required field.
|
|
22
22
|
${field}: expected ${expected}; the field was missing.`;if(issue.reason==="unexpected_field")return`AI response includes an unexpected field.
|
|
23
23
|
${field}: only the fields declared by the routine are allowed.`;if(issue.reason==="invalid_file")return`AI response contains an invalid File.
|
|
24
24
|
${field}: expected a valid File matching the routine's requirements.`;if(issue.reason==="out_of_bounds"){const constraint={maxLength:`at most ${issue.limit} characters`,maxItems:`at most ${issue.limit} items`,minimum:`a value of at least ${issue.limit}`,maximum:`a value of at most ${issue.limit}`}[issue.constraint];return`AI response is outside a permitted limit.
|
|
@@ -46,7 +46,7 @@ export type DropboxAuthorization = {
|
|
|
46
46
|
access: 'full_dropbox';
|
|
47
47
|
rootPath: string;
|
|
48
48
|
};
|
|
49
|
-
/**
|
|
49
|
+
/** Dropbox's empty API root or one explicit absolute folder path. */
|
|
50
50
|
export declare function validDropboxRootPath(value: unknown): value is string;
|
|
51
51
|
export type Connection = {
|
|
52
52
|
[P in ConnectionProvider]: {
|