API at a glance
Every public type of the library, package com.crm.sdk and the packages under it, one line each. suspend marks a call to make from a coroutine; a StateFlow may be collected on any thread. The pages before this one say how to use them.
The facade
Section titled “The facade”Crm (com.crm.sdk): one for the life of the app.
Crm(context, config, auth, host = CrmHost()): makes it, for the app theContextbelongs to.config: CrmConfig,auth: CrmAuth: as given.host: CrmHost: replaceable at any time.start(): Job: starts it, once (Initialise).suspend dispose(): sends what it can of the queue, and lets go of everything.session(session: CrmSession?): who is signed in, or null on sign-out.setReady(ready: Boolean): whether the app can show PurrCRM‘s screens.session: StateFlow<CrmSession?>: the user signed in, with the parts they have.ready: StateFlow<Boolean>: assetReadysaid.publicApp: StateFlow<CrmPublicApp?>: the app as PurrCRM describes it, kept on the phone.appFeatures: StateFlow<Set<CrmFeature>>: the parts the app has on.features: Set<CrmFeature>,has(feature): the parts the signed-in user has.mayOpen(where: CrmDestination): Boolean: someone is signed in and the page’s part is on; with nobody signed in, the messenger and a new conversation also while a visitor may still be made.visitorId: String?: the visitor kept on the phone while nobody is signed in, else null (People who haven’t signed in).suspend endVisitor(): ends the visitor and forgets it; nothing while a user is signed in.productName: String:CrmConfig.productName, else the brand’s name.isTestMode: Boolean: whether this build talks to the test app.languages: List<String>: the help center’s languages.testPhone: Boolean: whether PurrCRM treats this phone as a test phone.track(name, props = emptyMap()): records one of the SDK’s events or one ofcustomEvents.screen(name): recordsscreen_viewed, and shows a message held for that screen.permissionChanged(permission: String, granted: Boolean?):pushorlocation, recorded when it changed.suspend flush(): sends the queued events now.suspend checkNow(): Int?: checks in now; how many test messages came, or null.suspend showMessage(id): Boolean: shows the in-app message a link names.suspend registerPushToken(token, platform: CrmPushPlatform? = null): Boolean: keeps Firebase’s token for the user.suspend forgetPushToken(): Boolean: forgets it with PurrCRM; call it before the user’s token is forgotten andsession(null).handlePushArrival(data: Map<String, Any?>): CrmPushResult: a push arrived.handlePushTap(data: Map<String, Any?>): Boolean: a notification was tapped (call it only for an Intent a notification opened);push_openedis recorded for a push only; true when it was PurrCRM‘s.notices: StateFlow<CrmNotices>,noticesKeeper: NoticesKeeper: the inbox.suspend refreshNotices(),suspend moreNotices(): the inbox’s first page again, its next page.suspend markNoticesRead(ids, all = false): Boolean: marks notices read.suspend openNotice(notice: CrmNotice): String: marks it read and answers its link.suspend offersByPush(): Boolean?,suspend setOffersByPush(on): Boolean?: offers by push.preferencesState: Preferences: a preferences screen’s state.suspend preferences(): CrmPreferences?: the user’s preferences.suspend setPreferences(choices, allOff = false, wording = …): CrmPreferences?: keeps choices.openLink(link: String): Boolean: follows a link as a message’s button would.suspend open(where: CrmDestination): Boolean: shows one of PurrCRM‘s pages throughnavigate.suspend handleLink(uri: String),suspend handleLink(uri: android.net.Uri): Boolean: a link that opened the app.handleLinkNow(uri: String): Boolean: the same without waiting.suspend createLink(path, data = emptyMap(), channel = ""): CrmSharedLink?: a link of the user’s own to share.suspend referralLink(): CrmReferralLink?: the user’s referral link.appPaused(),appResumed(): the app went to the back, came to the front (withfollowLifecycleoff).messenger: MessengerController,conversation(id = ""): ConversationSession,uploadPicture(bytes, contentType = "", name = "picture"): CrmUpload,unread: StateFlow<Int>: the messenger.tickets: Tickets: the user’s tickets, and new ones.help: Help: the help center.inApp: InAppPresenter: in-app messages.
Beside it in com.crm.sdk: two const vals, the SDK’s version ("0.5.0") and kind ("android"), as every request sends them; isTestAppKey(key): Boolean; and crmFeaturesFor(session, app): Set<CrmFeature>, the parts a session has of the words the app has on.
Configuration and sign-in
Section titled “Configuration and sign-in”CrmConfig(apiBase, appKey, appVersion, productName = null, storagePrefix = "crm", initialFeatures = emptySet(), customEvents = emptySet(), followLifecycle = true, autoScreenViews = false, languageTag = null, flushEveryMs = 30_000, store = null, now = null, debug = false, releaseBuild = null, pushChannels = emptyList(), logger = null, preferencesWording = "crm_sdk/preferences-1"): Initialise.CrmConfig.DEFAULT_STORAGE_PREFIX("crm"),CrmConfig.DEFAULT_PUSH_CHANNEL("messages").CrmHost(followable, openInApp, navigate, openExternal, timeZone, askPermission, onUnreadChanged, links = emptyList(), linkOpened, installReferrer): every hook nullable, called on the main thread (Host hooks).CrmAuth.tokens(tokens: CrmTokens, tokenFailure: ((Throwable) -> CrmFailure)? = null): sign-in with tokens.CrmAuth.unverified(userId: () -> String?): no token, the user’s id; prototypes only.CrmAuth:tokens,tokenFailure,userId,isUnverified.CrmSession(guestId, displayName = "", productEventsOff = false, features: Set<CrmFeature>? = null):has(feature),withFeatures(features).CrmTokens(com.crm.sdk.api): interface,suspend current(): String?andsuspend expired(token).CrmTokens.fetched(now, earlierMs = 60_000, fetch: suspend () -> CrmFetchedToken?): CrmFetchedTokens.CrmFetchedTokens:earlierMs,fetch,forget(); aCrmTokens.CrmFetchedToken(token, expiresAt: Long? = null):expiry;CrmFetchedToken.secondsClaim(token, name)reads a JWT time claim, unchecked.CrmNoTokens: theCrmTokensof an unverified app.
Pages and links to them
Section titled “Pages and links to them”CrmPlace:Messenger,NewConversation,Conversation,Tickets,Ticket,HelpCenter,Collection,Article,Message,Preferences.CrmDestination(place, id = ""):feature,gated,link;CrmDestination.messenger,.newConversation,.tickets,.helpCenter,.preferences,.conversation(id),.ticket(id),.collection(slug),.article(slug),.message(id).CrmLinks: the pathsMESSAGES,NEW_CONVERSATION,TICKETS,HELP_CENTER,HELP_COLLECTIONS,MESSAGE_SHOW,PREFERENCES;parse(link): CrmDestination?.
Failures
Section titled “Failures”CrmFailure: sealed, anException; one of the four below.CrmProblem(problem: Problem): PurrCRM said no:status,code,detail,requestId,retryAfter;CrmProblem.of(status, code, title, detail, scope, retryAfterSeconds, requestId)makes one (for tests and your ownCrmTokens).CrmAppUnavailable: aCrmProblem; the app is archived or deleted, final.CrmOffline(cause): not reached, or no answer in time (timedOut).CrmContractError(message): an answer the SDK cannot read.CrmMessage(sentence, detail = "", retry = null): what to tell the user;fromService.CrmSentence:Offline,Unavailable,RateLimited,RateLimitedGuest,SignInAgain,BadRequest,NotFound,ConversationGone,TicketGone,TicketFormGone,ArticleGone,RatingClosed,SurveyClosed,BotMovedOn,AnswerInvalid,AttachmentInvalid,Refused,SomethingWentWrong.CrmAttempt:Messenger,Ticket,Help,Other: what the user was doing, which words a 404 gets.CrmRetryHint(at, afterMs):soon,leftAt(now),passedAt(now).tellCrmFailure(failure, attempt, now),tellCrmProblem(problem, attempt, now): aCrmMessagefor a failure of your own calls.shownCrmDetail(problem),crmRetryHint(...),crmSentenceFor(...): the parts of it.
Messenger
Section titled “Messenger”MessengerController:state: StateFlow<MessengerState>,unread: StateFlow<Int>,suspend load(),suspend refresh(),suspend loadMore(),conversation(id = "", ticketId = "", parts = emptyList()): ConversationSession,uploadPicture(bytes, contentType, name): CrmUpload,onScreen(conversationId): Boolean; and, used by the SDK itself,suspend homeIs(home),suspend unreadIs(n),suspend signedOut(),appForeground(inFront).MessengerState:home,earlier,nextBefore,unread,loading,loadingMore,message;hasMore,opening.ConversationSession:state: StateFlow<ConversationSessionState>,isOnScreen,onScreen(shown),appForeground(front),close(),suspend open(),suspend retry(),suspend send(text): Boolean,suspend resend(key): Boolean,suspend addPicture(bytes, name, type = ""),suspend addFile(bytes, name, type = ""),suspend removePicture(key),suspend answerBot(part, button = "", value = ""): Boolean,suspend clearBotNote(),suspend rate(stars, remark = ""),suspend markRead().ConversationSessionState:id,ticketId,parts,status,lastSeq,reply,assignee,loading,loaded,gone,message,troubled,sending,sendMessage,sentSerial,pictures,note,rating,ratingMessage,shown,awaiting,bot,botNote,botMessage,outgoing,opening,openingKnown,typing,seenSeq;isNew,thread,closed,ratingRequest,uploading.OutgoingMessage(key, text, at, pictures, status, message):failed,body.OutgoingStatus:Sending,Failed.PendingPicture(key, bytes, contentType, name, status, attachmentId, upload, refused):isFile.ComposerNote:TooLong,TooManyPictures,PictureTooLarge,PictureWrongType,WaitForPictures,TooManyFiles,FileTooLarge,FileWrongType,FileBadName.RatingPhase:Open,Sending,Sent,Closed.BotPhase:Idle,Sending.BotNote:NotEmail,NotOrderRef,NotText,Refused.CrmUpload:name,contentType,size,state: StateFlow<CrmUploadState>,attachmentId,cancel(),suspend await(): String?.CrmUploadState(status, sent, total, attachmentId, problem, failure, cancelled):refused,progress.PictureStatus:Uploading,Ready,Failed.PictureStorage: where a picture’s bytes go;AttachmentUploader.asPictureStorage().
Tickets
Section titled “Tickets”Tickets:list: Fetcher<SupportTicketPage>,suspend load(),suspend refresh(),ticket(id): Fetcher<SupportTicket>,suspend get(id): SupportTicket,suspend write(id, text, attachmentIds = emptyList(), idempotencyKey = newIdempotencyKey()): TicketWrite,forms: Fetcher<TicketForms>,newTicket(forms = null): NewTicket.NewTicket:state: StateFlow<NewTicketState>,suspend load(),choose(form),unchoose(): Boolean,title(title),text(text),setValue(key, value: TicketFieldValue),suspend send(),close().NewTicketState(forms, loading, loadMessage, form, draft, problems, tried, sending, message, ticket):picking.TicketDraft(title, text, values),TicketFieldValue(text, boolean, date),TicketDay(year, month, day),TicketDraftProblem(problem, max, detail);TicketProblem:Missing,TooLong,NotANumber,Refused.checkTicketDraft(...),ticketBody(...),ticketProblemFrom(...),ticketNumberOf(words),ticketFieldTarget(key),TICKET_TITLE_TARGET,TICKET_TEXT_TARGET: a new ticket’s rules, asNewTicketkeeps them.Fetcher<T>:attempt,state: StateFlow<Fetched<T>>,suspend load(),close().Fetched<T>(value, loading, message).TicketWrite:Sent(part),Refused(problem: MessageProblem),Failed(failure, message, idempotencyKey).
Help center
Section titled “Help center”Help:state: StateFlow<HelpCenterState>,suspend load(),suspend search(query),articleSession(slug): ArticleSession,collectionFetcher(slug): Fetcher<CollectionArticles>,suspend collections(),suspend collection(slug),suspend featured(),suspend find(query),suspend article(slug),suspend rate(slug, helpful),close().HelpCenterState:collections,featured,loaded,loading,message,query,results,searching,searched,searchMessage;isSearch.ArticleSession:slug,state: StateFlow<ArticleState>,suspend load(),suspend rate(helpful),close().ArticleState:article,loading,message,helpful,rating,rateMessage,answer.
In-app messages
Section titled “In-app messages”InAppPresenter:banner: StateFlow<InAppMessage?>,next: StateFlow<InAppMessage?>,hasSubscriber,shown(id),clicked(id, link): Boolean,dismissed(id),completed(id),closed(id),screenIs(name),survey(id): SurveySession?,carousel(id): CarouselSession?.SurveySession:message,survey,state: StateFlow<SurveyState>,answer(answer): Boolean,next(),back(): Boolean,dismiss().SurveyState(step, path, answers, missing, sending, failed, done, over, progress):answered.CarouselSession:message,carousel,flow: CarouselFlow,state: StateFlow<CarouselState>,path,seen(),button(b),option(o),swipeForward(): Boolean,back(): Boolean,close(),openLink(link): Boolean.CarouselState(at, screen, picked, frozen, busy, canGoBack, progress, dot, over, completed).CarouselFlow(carousel):screens,startIndex,screenIndex(id),nextOf(i),resolve(...),targets(i),backs(i),reachable(),deadEnds(),buttonsOf(i),leadOf(...),leadOfOption(...),leadOfNext(i),endsAtNext(i),swipesForward(i),pathAhead(i),linear,line,progress(dotsUpTo),picturesOf(i);IMPLICIT_NEXT,IMPLICIT_CONTINUE.CarouselWalk(flow):at,screen,behind,canGoBack,path,go(index),back(),progress,dot.CarouselLead:CarouselToScreen(index),CarouselToEnd,CarouselToBack,CarouselToLink(link);CAROUSEL_END_INDEX.CarouselStyleSpec: the carousel look’s defaults and limits (presentation, corners, button shape, layout, accent, spacing, radii, text factors, contrast).InApp,InAppState(banner, waiting, showing, testPhone),SubmitOutcome(Sent,Closed,Failed): the scheduling undercrm.inApp, which the SDK drives.
Pushes, notices and preferences
Section titled “Pushes, notices and preferences”CrmPushResult(isCrm, replyOnScreen, noticeId, silent)(com.crm.sdk.push).CrmPush(type, noticeId, link, silent, typeWord):isCrm,destination.CrmPushKeys:TYPE,NOTICE_ID,LINK,NUDGE,FIREBASE_MESSAGE_ID(google.message_id).readPush(data): CrmPush,isPushData(data): Boolean,tappedDestination(push): CrmDestination?,pushOpenedProps(push).NoticesKeeper:state: StateFlow<CrmNotices>,value,suspend refresh(),suspend more(),suspend markRead(ids, all): Boolean,suspend open(notice): String,close().CrmNotices(notices, unread, loaded, loading, failure, nextBefore):hasMore.CrmNotice(id, type, title, body, createdAt, link, readAt):unread,readOn(at).Preferences:wording,state: StateFlow<PreferencesState>,suspend load(),suspend choose(topicId, channel, on, wording = this.wording),suspend turnAllOff(wording = this.wording),suspend fetch(),suspend set(choices, allOff, wording),close().PreferencesState(preferences, loading, message, saving, saveMessage, kept).withChoice(p, topicId, channel, on),allTurnedOff(p): preferences as they will be.CrmPreferences(topics, allOff),CrmPreferenceTopic(id, name, description, channels),CrmPreferenceState(channel, subscribed),CrmPreferenceChoice(topicId, channel, subscribed).CrmConsent(offersByPush).
CrmLink(name, path, webUrl = "", screen = "")(com.crm.sdk.links): a declared place;toJson().CrmLinkContext(path, from, saved, data, campaign, channel): a link followed, aslinkOpenedhears it.CrmIncomingLink(path, from, emailToken, saved):isShort.readIncomingLink(href, base, apiBase).CrmLinkSpace:PREFIX,CLICK_PARAM,SLUG_PARAM,SHORT_ROOT,CLAIM_REFERRER_PARAM,CLAIM_CLIPBOARD_PREFIX,shortSlug(path),claimFromReferrer(referrer),claimFromClipboard(text),inAppPath(link, base, apiBase): CrmInAppPath?.CrmInAppPath(path, token, saved).linkOpenedProps(path, from, saved),crmLinksDigest(links).RawUri.parse(text): a URI read as written (scheme,hasAuthority,userInfo,host,port,path,query,fragment);RawUri.decodeComponent,decodeQueryComponent.CrmSharedLink(slug, shortUrl, url),CrmReferralLink(slug, shortUrl, url),SavedLinkOpen(path, saved, data, campaign, channel).
Events, storage and the setup check
Section titled “Events, storage and the setup check”CrmEvent:AppOpened,SessionEnded,ScreenViewed,AppUpdated,PushPermissionChanged,LocationPermissionChanged,PushOpened,LinkOpened(each with itsword, such asapp_opened).TrackerStatus(recording, queued, lastFlushAt, lastFlushResult, lastFailure, failures, retryAt): the queue, as the setup check reads it.tidyProps(props): props as PurrCRM takes them.MAX_EVENT_BATCH(50),MAX_EVENT_PROPS(10),MAX_EVENT_PROP_RUNES(120),MAX_EVENT_AGE_MS(a week).CrmStore(com.crm.sdk.storage):prefix,suspend read(name),suspend write(name, value),suspend remove(name).PrefsCrmStore(context, prefix = "crm"):SharedPreferencesnamed<prefix>.crm.MemoryCrmStore(prefix): in memory,values.CrmStoreNames:QUEUE,LAST_VERSION,PERMISSION,PUBLIC_APP,LINK_CLAIM,LINK_CLAIM_DUE,PUSH_SEEN.crmStoreKey(prefix, name).SetupStatus(com.crm.sdk.debug):Ok,Warning,Failure,Skipped.SetupCheck(id, section, title, status, summary, detail, fix): one row.
Models
Section titled “Models”What PurrCRM answers, as data classes in com.crm.sdk.wire. Times are epoch milliseconds.
The app
CrmPublicApp(key, mode, brand, features, currency, orderRef, minSdkVersion, linkBase, languages):isTest.CrmPublicBrand(name, accent, logoUrl, supportEmail).CrmPublicLinkApp(key, name, brand, linkBase, appStoreUrl, playStoreUrl),CrmPublicRatingBody(helpful, visitor),CrmPublicPreferences(product, accent, logoUrl, email, preferences): public pages’ shapes.
The messenger and tickets
MessengerHome(open, unread, reply, articles, tickets, opening, layout):picturesAllowed,filesAllowed.MessengerLayout(greeting, intro, faces, team, names, replyText, awayText, cards, newConversation, attachments, helpCenter, files).HomeCard(id, kind, title, text, link, articles).MessengerOpening(workflow, version, parts, awaiting):question.OpeningRef(workflow, version):OpeningRef.of(opening).Conversation(id, state, parts, lastSeq, unread, reply, createdAt, updatedAt, assignee, ticketId, awaiting).ConversationSummary(id, state, preview, previewAuthor, unread, createdAt, updatedAt),ConversationPage(items, nextBefore),ConversationUpdate(parts, state, lastSeq, unread, awaiting, typing, seenSeq, live).Conversationalso hasseenSeq.Part(id, seq, kind, author, createdAt, text, blocks, attachments, state, rating, bot, files):attachmentsare pictures,filesthe rest.Author(kind, name):isGuest.Attachment(id, contentType, bytes, url, expiresAt, name).ReplyExpectation(within, open, opensAt).BotPart(kind, buttons, collect, articles, reply, orderRef),BotButton(id, label),CrmOrderRef(label, pattern, example, prop, upper):hint,check(value).SupportTicketSummary(id, ref, title, type, state, updatedAt),SupportTicketPage(items).SupportTicket(id, ref, title, type, state, createdAt, updatedAt, description, fields, conversationId, parts, resolvedAt).TicketField(key, label, type, text, number, boolean, date):hasValue.TicketForms(items),TicketForm(id, name, fields, description),TicketFormField(key, label, type, options, required),NewTicketBody(typeId, title, text, fields).CrmUnreadCount(unread),AttachmentUpload(id, url, fields, maxBytes, expiresAt).- Request bodies:
MessageBody(text, attachmentIds),StartBody(text, attachmentIds, opening, button),ReadBody(seq),RatingBody(rating, remark),AttachmentBody(contentType, bytes),BotReplyBody(partId, button, value). - Limits:
MAX_MESSAGE_RUNES(4000),MAX_ATTACHMENTS(4, pictures and files together),MAX_ATTACHMENT_BYTES(5 MiB),ATTACHMENT_TYPES,MAX_FILE_BYTES(20 MiB),MAX_FILE_NAME_RUNES(200),FILE_TYPES,TYPING_LAPSE_MS(8 s),MAX_NEW_TICKET_TITLE(150),MAX_NEW_TICKET_TEXT(5000),MAX_NEW_TICKET_FIELDS(30),MAX_FIELD_TEXT(2000),MAX_REMARK_RUNES(500),MAX_RATING(5),MAX_COLLECT_RUNES(500),MESSENGER_WAIT_MS.
The help center
Collection(id, slug, title, articles, description),Collections(items),CollectionArticles(collection, articles).ArticleSummary(id, slug, title, updatedAt, summary, collection),Articles(items).Article(id, slug, title, blocks, updatedAt, summary, collection, related, language, languages),ArticleRatingBody(helpful).
Content
ContentBlock(type, level, spans, items, imageUrl, alt, label, link, size, color, align, weight, tone, emoji, aspect, fit, shape, style):textSize,imageSize,spacerSize.Span(text, bold, italic, link, underline, strike, highlight, color),ListItem(spans).
In-app messages
InAppMessage(id, variant, kind, banner, post, carousel, survey, test, screens):large,drawable.InAppBanner(style, blocks, dismissible, link),InAppPost(blocks, sender).Carousel(screens, start, progress, skip, presentation, locked, style).CarouselScreen(id, blocks, layout, image, align, valign, background, buttons, choice, next, style).CarouselImage(url, alt, size, aspect, fit, shape),CarouselBackground(kind, color, color2, angle, imageUrl, scrim).CarouselButton(id, label, action, style, screen, link, permission),CarouselChoice(options, multiple),CarouselOption(id, label, emoji, next).CarouselStyle(accent, corner, buttonShape, textScale):over(base).Survey(format, steps, intro):question(id).SurveyStep(id, kind, questions, blocks, branches).SurveyQuestion(id, type, title, description, required, options, other, min, max, minLabel, maxLabel, placeholder):range.SurveyOption(id, label),SurveyBranch(questionId, next, values, min, max).SurveyAnswer(questionId, number, choices, other, text):answered.Checkin(messages, unread, nextCheckinSeconds, throttled, testPhone, unreadNotices, sendLinks).- Request bodies:
CheckinBody,ReceiptBody,SurveyAnswerBody,SurveySubmit,OpenMessageBody. - Limits:
CHECKIN_EVERY_MS,OTHER_OPTION,MAX_SHORT_ANSWER_RUNES(200),MAX_LONG_ANSWER_RUNES(2000),MAX_OTHER_RUNES(200),MAX_CAROUSEL_SCREENS(50),MAX_RECEIPT_PATH(200),CAROUSEL_END.
Pushes, notices, links and events
CrmNoticePage(notices, unread, nextBefore),CrmNoticesReadBody(ids, all),CrmConsentBody(offersByPush),CrmDeviceBody(token, platform, appVersion, locale),CrmForgetDeviceBody(token).CrmPreferencesBody(choices, allOff, wording).LinkClaimBody(token),ShareLinkBody(path, data, channel),DeclaredLink(name, path, webUrl, screen),AppLinksReport(appVersion, digest, links).EventBody(id, name, occurredAt, props),EventsBody(events, appVersion, platform, timeZone, sentAt),EventsAccepted(accepted, rejected),EventRejected(index, id, reason).- Limits on notices, push tokens and preference choices, as
const vals inDelivery.ktandPreferences.kt, and the request headers’ names inCrm.kt.
Refusals
Problem(status, code, title, detail, scope, retryAfterSeconds, requestId):error,isTokenExpired,isAppUnavailable;Problem.fromJson(...),retryAfterSecondsFrom(header).CrmProblemBody(title, status, detail, code, requestId),CrmRateLimited(scope, retryAfterSeconds).
The data export
ExportContact and the types it holds (ExportAttribute, ExportNote, ExportEvent, ExportWorkflowRun, ExportCollected, ExportConversation, ExportPart, ExportTicket, ExportArticleRating, ExportReceipt, ExportSurveyResponse, ExportSurveyAnswer, ExportTestPhone, ExportTestSend, CrmExportDevice, CrmExportNotice, CrmExportSubscription, CrmExportConsentChange) are the shapes of a contact’s data export, which the library reads in its contract tests. An app has no use for them.
Each is an enum of the words PurrCRM sends, with its word and parse(word), and Unknown for a word this version does not know.
CrmFeature:Messenger,HelpCenter,InAppMessages.CrmPlatform,CrmPushPlatform:Android,Ios,Web.CrmPushType:SupportReply,CrmMessage.CrmPreferenceChannel:Email,Push,InApp,Chat.CrmErrorCode:BadRequest,Unauthorized,TokenExpired,NotFound,RateLimited,Unavailable,InternalError,AppKeyRequired,AppUnavailable,Refused,RatingClosed,AttachmentInvalid,SurveyClosed,BotMovedOn,AnswerInvalid,VisitorsOff,VisitorEnded,VisitorMergedElsewhere.CrmLimitScope:Guest.ConversationState:Open,Snoozed,Closed.PartKind:Message,Reply,Note,Bot,Assignment,State,RatingRequest.AuthorKind:Guest,Teammate,Bot,System.BotKind:Says,Asks,Collects,Suggests,HandsOff,Resolves.CollectField:Text,Email,OrderRef.ReplyTime:Minutes,Hours,Day.HomeCardKind:Send,SearchHelp,Articles,Conversations,Tickets,Link,Status.NewConversations:Always,WhenNoneOpen,Never.TeamFaces:Auto,Chosen,None.TicketState:Submitted,InProgress,WaitingOnGuest,Resolved.FieldType:Text,List,Number,Boolean,Date.MessageKind:Chat,Post,Banner,Carousel,Survey,Push,Email.BannerStyle:Inline,Floating.ReceiptAction:Seen,Clicked,Dismissed,Completed,Answered.SurveyFormat:Small,Large.SurveyStepKind:Questions,ThankYou.QuestionType:Nps,Numeric,Stars,Emoji,Dropdown,ShortText,LongText,SingleChoice,MultiChoice.CarouselPermission:Notifications,Location.CarouselButtonAction:Next,Screen,Back,End,Link,Permission.CarouselLayout:Centred,ImageTop,ImageFull,Text.CarouselPresentation:Sheet,Card,Full.CarouselProgress:Dots,Bar,None.CarouselCorner:Soft,Round,Square.CarouselButtonShape:Pill,Rounded.CarouselTextScale:Compact,Regular,Large.BackgroundKind:Plain,Color,Gradient,Image.CarouselScrim:None,Light,Dark.BlockType:Paragraph,Heading,Bullets,Numbers,Image,Button,Divider,Eyebrow,Callout,Checklist,Spacer,Emoji.TextSize:Display,Title,Body,Small.TextWeight:Regular,Medium,Bold.ContentAlign:Start,Center,End.ContentVAlign:Top,Center,Bottom.CalloutTone:Info,Good,Warn.SpacerSize:Small,Medium,Large.ImageSize:Small,Medium,Large,Full.ImageAspect:Auto,Square,FourByThree,Wide,Portrait.ImageFit:Cover,Contain.ImageShape:Rounded,Circle,Square.ContentButtonStyle:Primary,Secondary,Text.ColorToken:Accent,Ink,Muted,Surface,Wash,Good,Warn,Bad.WireWord: the interface each of them implements (word).
Helpers
Section titled “Helpers”Pure functions the SDK’s state is built from, for a screen that does more of its own:
shownToGuest(part),fromStaff(part),isBubble(part): what a part is.mergeParts(known, arrived),unreadAfter(parts, readSeq),newestStaffSeq(parts),openRatingRequest(parts).placeParts(parts, gapMs = 10 min, zone): List<PartPlace>,PartPlace(firstOfRun, newDay, timed): runs of bubbles and day lines.teammatesOf(conversations, most = 2): the names of the teammates who wrote last.replyLine(reply, now, zone): ReplyLine:ReplyWithin(within)orReplyBackAt(at, today), for “We usually reply in…”.checkMessage(text, pictures): MessageProblem?(Empty,TooLong,TooManyPictures),checkPicture(contentType, bytes): PictureProblem?(WrongType,TooLarge),pictureTypeOf(fileName),remarkFits(remark).checkFile(contentType, bytes, name): FileProblem?(WrongType,TooLarge,BadName),fileTypeOf(fileName),fileKindOf(contentType): FileKind(Pdf,Text,Table,Archive,Document,Spreadsheet,Slides,Other),fileSizeOf(bytes): FileSize(amount, megabytes).seenUnder(parts, seenSeq): String?: the id of the user’s message to show Seen under, or null.validEmail(s),checkCollected(field, value, orderRef): what the help bot’s box takes.linkTarget(link, follow): LinkTarget?:InAppLink(location)orWebLink(url);MAX_BLOCK_LINK_BYTES.drawnBlocks(blocks),plainText(blocks).branchMatches,nextStep,surveyPath,unansweredRequired,answersOnPath,answerFits: a survey’s way.Backoff(firstMs, mostMs):failures,next(),reset(),delayAfter(failures).runeCount(s),takeRunes(s, most): lengths as PurrCRM counts them (code points).CrmTime.parse(text),CrmTime.format(epochMillis): RFC 3339 times.
Lower layers
Section titled “Lower layers”The parts the facade is built on, public for tests and for an app that needs a call the facade does not make:
CrmTransport(com.crm.sdk.api):get,post,put,delete(suspend),url(path, query).HttpCrmTransport(apiBase, tokens, appVersion, appKey, userId, languageTag, tokenFailure, timeoutMs = 10_000, getRetryDelaysMs = [500, 1500]):onTokenRefused,onExchange,close(),appUnavailable.CrmResponse(status, json, headers):obj,decode(owner, read).CrmExchange(method, path, status, requestId, millis, failure): one request, as the debug log writes it.newIdempotencyKey(),encodeComponent(s).MessengerApi,HelpApi,OutboundApi,DeliveryApi,PreferencesApi,EventsApi,PublicApi: PurrCRM‘s guest routes, onesuspendcall each, over aCrmTransport;MessengerApialso hasticketForms()andopenTicket(body, idempotencyKey).AttachmentUploader(timeoutMs = 60_000): a picture’s or file’s upload to storage.Json.parse(text),Json.parseObject(text),Json.write(value);Fields(json, owner): reads a model’s fields.