API at a glance
Every public type of CrmSdk 0.2.0, one line each. Types marked main actor are used from the main actor. The package’s sources hold each one’s full comment.
The facade
Section titled “The facade”Crm (main actor): make one at launch and keep it.
| Member | What it is |
|---|---|
init(config:auth:host:) | Makes the facade for the app config names. |
config, auth | What it was made with. |
host | Your hooks (CrmHost); may be changed at any time. |
start() async | Reads the public face, restores events, records app_opened, follows the life cycle, looks for a deferred link. Once. |
session(_:) | Who is signed in: a CrmSession, or nil. |
setReady(_:) | Whether the app may show PurrCRM‘s places and in-app messages now. |
currentSession | The session now. |
features, has(_:) | The parts the user signed in has. |
mayOpen(_:) | Whether a destination may be opened now. |
productName, isTestMode, languages | The product’s name, test mode, the app’s languages. |
unread | CrmValue<Int>: the messenger’s unread count. |
ready | CrmValue<Bool>: what setReady said. |
publicApp | CrmValue<CrmPublicApp?>: the app’s public face. |
appFeatures | CrmValue<Set<CrmFeature>>: the parts the app has on. |
sessionValue | CrmValue<CrmSession?>: the session, with its features. |
testPhone | CrmValue<Bool>: the user is a test phone. |
messenger | MessengerController. |
tickets | CrmTickets. |
help | CrmHelp. |
inApp | CrmInApp. |
notices | CrmValue<CrmNotices>: the inbox. |
track(_:_:) | Records your own event. |
screen(_:) | Records the screen shown. |
permissionChanged(_:allowed:) async | The user’s answer about "push" or "location". |
flushEvents() async | Sends the queued events now. |
appPaused() async, appResumed() | The life cycle, when you follow it yourself. |
dispose() async | Stops everything. |
conversation(_:parts:) | A ConversationSession for a conversation. |
newConversation() | A ConversationSession for a new one. |
ticketConversation(_:parts:) | A ConversationSession for a ticket. |
isOnScreen(_:) | Whether a conversation or ticket is on screen. |
uploadPicture(_:type:name:progress:) async throws | Uploads a picture; answers its attachment id. |
registerPushToken(_: String, platform:) async | Registers the push token (Firebase’s). |
forgetPushToken() async | Lets go of the token for the user signed in. |
handlePushArrival(_:) | A push arrived; answers a CrmPushResult. |
handlePushTap(_:) | A push was tapped; answers whether it was PurrCRM‘s. |
refreshNotices() async, moreNotices() async | Reads the inbox again, or its next page. |
markNoticesRead(_:all:) async | Marks notices read. |
offersByPush() async, setOffersByPush(_:) async | The consent to offers by push. |
preferences(wording:) | A CrmPreferencesKeeper for one screen, keeping each choice with your screen’s wording id (crmPreferencesWording when left out). |
handleLink(_: URL) async, handleLink(_: String) async | A link the phone handed you; answers whether it was PurrCRM‘s. |
createLink(_:data:channel:) async | A link the user shares (CrmSharedLink?). |
referralLink() async | The user’s referral link (CrmReferralLink?). |
open(_:) async | Opens a destination through navigate. |
showMessage(_:) async | Shows the in-app message with that id. |
openLink(_:) | Follows a link from content. |
targetOf(_:) | Where a link from content goes (LinkTarget?). |
checkNow() async | Checks in at once; answers how many tests came. |
showSetupCheck() | Shows the setup check. |
runSetupChecks() async | The setup check’s rows. |
setupFacts() async | What the checks look at (SetupFacts). |
setupReportText() async | The report, as text. |
sendTestEvent() async, checkInForSetup() async, testPush() async | The setup check’s test actions; each answers what it did. |
testLinks() async, tryLink(_:) | Test links ([CrmTestLink]), and where one would go (CrmLinkTry). |
Setting up
Section titled “Setting up”| Type | What it is |
|---|---|
CrmConfig | apiBase, appKey, appVersion, productName, storagePrefix, initialFeatures, customEvents, followLifecycle, languageTag, flushEvery, store, httpClient, clock, debug, releaseBuild, logger, clipboard; phoneLanguage(). |
CrmHost | navigate, followable, openInApp, openExternal, timeZone, askPermission, onUnreadChanged, links, linkOpened, installReferrer, deferredLinksFromClipboard. |
CrmAuth | .tokens(_:tokenFailure:), .unverified(_:); tokens, tokenFailure, userId. |
CrmTokens | Protocol: current() async throws -> String?, expired(_:) async. |
CrmFetchedTokens | Actor over your backend: init(earlier:now:fetch:), earlier, current(), expired(_:), forget(). |
CrmFetchedToken | init(_:expiresAt:), token, expiresAt, expiry. |
CrmNoTokens | No token, for unverified sign-in. |
CrmSession | init(guestId:displayName:productEventsOff:features:), has(_:), withFeatures(_:). |
crmFeaturesFor(_:_:) | The features a session has of the app’s. |
CrmFeature | .messenger, .helpCenter, .inAppMessages. |
Watching
Section titled “Watching”| Type | What it is |
|---|---|
CrmValue<T> (main actor) | value, observe(_:) (answers a CrmCancellable), stream, observerCount. |
CrmCancellable | cancel(); watching also stops when it is let go. |
Places and links
Section titled “Places and links”| Type | What it is |
|---|---|
CrmPlace | .messenger, .newConversation, .conversation, .tickets, .ticket, .helpCenter, .collection, .article, .message, .preferences. |
CrmDestination | place, id, feature, gated, link; .conversation(_:), .ticket(_:), .collection(_:), .article(_:), .message(_:), .messenger, .newConversation, .tickets, .helpCenter, .preferences. |
CrmLinks | PurrCRM‘s paths (messages, newConversation, tickets, helpCenter, helpCollections, messageShow, preferences) and parse(_:), a path to a CrmDestination?. |
CrmLink | A place you declare: name, path, webUrl, screen. |
CrmLinkContext | A link followed: path, from, saved, data, campaign, channel. |
CrmLinkSpace | The link space’s words and readers: prefix, clickParam, slugParam, shortRoot, claimReferrerParam, claimClipboardPrefix, shortSlug(_:), claimFromReferrer(_:), claimFromClipboard(_:), inAppPath(_:base:apiBase:). |
LinkTarget | .inApp(location) or .web(URL). |
linkTarget(_:_:) | Where a content link goes, by its rules. |
CrmSharedLink, CrmReferralLink | slug, shortUrl, url. |
SavedLinkOpen | A saved link’s answer: path, saved, data, campaign, channel. |
crmLinksDigest(_:) | The digest of the places you declare. |
CrmClipboard | Protocol (main actor methods): hasStrings(), string(), clear(ifStill:). CrmPasteboard (UIPasteboard, a main-actor class) and CrmNoClipboard implement it. |
Pushes and the inbox
Section titled “Pushes and the inbox”| Type | What it is |
|---|---|
CrmPushResult | isCrm, replyOnScreen, noticeId, silent. |
CrmPushData | init(_ userInfo:), type, noticeId, link, silent, isCrm. |
CrmPushType | .supportReply, .crmMessage. |
CrmPushPlatform | .ios, .android, .web. |
CrmNotices | notices, unread, loaded, loading, failure, nextBefore, hasMore. |
CrmNotice | id, type, title, body, link, createdAt, readAt, unread, readOn(_:). |
CrmNoticePage, CrmConsent | A page of notices; the consent (offersByPush). |
| Limits | crmMaxPushTokenBytes, crmDefaultNoticePage, crmMaxNoticePage, crmMaxNoticesRead. |
The messenger
Section titled “The messenger”| Type | What it is |
|---|---|
MessengerController (main actor) | state, load(), refresh(), loadMore(). |
MessengerState | home, earlier, nextBefore, hasMore, unread, loading, loadingMore, message, opening. |
MessengerHome | open, unread, reply, articles, tickets, opening, layout, picturesAllowed. |
MessengerLayout | greeting, intro, faces, team, names, replyText, awayText, cards, newConversation, attachments, helpCenter. |
HomeCard, HomeCardKind | id, kind (.send, .searchHelp, .articles, .conversations, .tickets, .link, .status), title, text, link, articles. |
MessengerOpening | The help bot’s opening: workflow, version, parts, awaiting, question. |
NewConversations, TeamFaces | .always, .whenNoneOpen, .never; .auto, .chosen, .none. |
ConversationSession (main actor) | state, onScreen(_:), retry(), markReadNow(), addPicture(_:name:type:), removePicture(_:), send(_:), resend(_:), answerBot(_:button:value:), clearBotNote(), rate(_:remark:), close(). |
ChatState | id, ticketId, parts, thread, status, closed, lastSeq, reply, assignee, loading, loaded, gone, message, troubled, sending, sendMessage, sentSerial, pictures, uploading, note, rating, ratingMessage, ratingRequest, shown, awaiting, bot, botNote, botMessage, outgoing, opening, openingKnown, isNew. |
PendingPicture, PictureStatus | key, bytes, contentType, name, status, progress, attachmentId; .uploading, .ready, .failed. |
OutgoingMessage, OutgoingStatus | key, text, pictures, at, status, message, failed; .sending, .failed. |
ComposerNote | .tooLong, .tooManyPictures, .pictureTooLarge, .pictureWrongType, .waitForPictures. |
RatingPhase, BotPhase, BotNote | .open, .sending, .sent, .closed; .idle, .sending; .notEmail, .notOrderRef, .notText, .refused. |
Conversation, ConversationSummary, ConversationPage, ConversationUpdate | A conversation, a row of the list, a page of rows, what a wait brought. |
ConversationState | .open, .snoozed, .closed; isClosed. |
Part | id, seq, kind, author, text, blocks, attachments, state, rating, bot, createdAt. |
PartKind | .message, .reply, .note, .bot, .assignment, .state, .ratingRequest; guestSees. |
Author, AuthorKind | kind, name, isGuest; .guest, .teammate, .bot, .system. |
Attachment | id, contentType, bytes, url, expiresAt. |
BotPart, BotKind, BotButton, CollectField | kind, buttons, collect, articles, reply, orderRef; .says, .asks, .collects, .suggests, .handsOff, .resolves; id, label; .text, .email, .orderRef. |
CrmOrderRef | An order number’s shape: label, pattern, example, prop, upper, hint, check(_:). |
ReplyExpectation, ReplyTime, ReplyLine | within, open, opensAt; .minutes, .hours, .day; .within(_), .backAt(_:today:). |
replyLine(_:_:calendar:) | What to say about a reply. |
isBubble(_:), placeParts(_:gap:calendar:), PartPlace | Bubbles, and where each part sits (firstOfRun, newDay, timed). |
shownToGuest(_:), fromStaff(_:), mergeParts(_:_:), unreadAfter(_:_:), newestStaffSeq(_:), openRatingRequest(_:), teammatesOf(_:most:) | Rules about parts. |
checkMessage(_:_:), MessageProblem | A message’s check: .empty, .tooLong, .tooManyPictures. |
checkPicture(_:_:), PictureProblem, pictureTypeOf(_:), pictureTypeOf(bytes:) | A picture’s check (.wrongType, .tooLarge) and its type. |
remarkFits(_:), checkCollected(_:_:_:), validEmail(_:) | A rating’s remark; what the bot collects. |
CrmPictureRefused | uploadPicture refused it: problem. |
Backoff | The wait between failed tries: first, most, failures, next(), reset(), delayAfter(_:). |
| Limits | maxMessageRunes (4000), maxAttachments (4), maxAttachmentBytes (5 MB), maxRemarkRunes (500), maxRating (5), maxCollectRunes, messengerWait, attachmentTypes. |
Tickets
Section titled “Tickets”| Type | What it is |
|---|---|
CrmTickets (main actor) | list(), get(_:), write(_:text:attachmentIds:idempotencyKey:). |
SupportTicketPage, SupportTicketSummary | items; id, ref, title, type, state, updatedAt. |
SupportTicket | id, ref, title, type, state, description, fields, conversationId, parts, createdAt, updatedAt, resolvedAt. |
TicketField, FieldType | key, label, type, text, number, boolean, date, hasValue; .text, .list, .number, .boolean, .date. |
TicketState | .submitted, .inProgress, .waitingOnGuest, .resolved. |
The help center
Section titled “The help center”| Type | What it is |
|---|---|
CrmHelp (main actor) | collections(), collection(_:), featured(), search(_:), article(_:), rate(_:helpful:). |
Collection, Collections | id, slug, title, description, articles; items. |
CollectionArticles | collection, articles. |
ArticleSummary, Articles | id, slug, title, summary, collection, updatedAt; items. |
Article | id, slug, title, summary, blocks, collection, related, updatedAt, language, languages. |
In-app messages
Section titled “In-app messages”| Type | What it is |
|---|---|
CrmInApp (main actor) | state (the queue, ready or not), next and banner (nil until setReady(true)), shown(_:path:), clicked(_:link:screen:button:path:), answered(_:screen:answers:path:), dismissed(_:screen:path:), completed(_:screen:path:), closed(_:), openLink(_:_:screen:path:), survey(_:), carousel(_:). |
InAppState | banner, waiting, showing, testPhone, next. |
InAppMessage | id, variant, kind, banner, post, carousel, survey, test, screens, large, drawable. |
MessageKind | .banner, .post, .carousel, .survey (and .chat, .push, .email, which are not drawn in the app). |
InAppBanner, BannerStyle | style, blocks, dismissible, link; .inline, .floating. |
InAppPost | blocks, sender. |
ReceiptAction | .seen, .clicked, .dismissed, .completed, .answered. |
SurveySession (main actor) | message, survey, state, shown(), answer(_:), fits(_:_:), next(), back(), dismiss(), finish(), openLink(_:). |
SurveyState | step, answers, missing, sending, failed, done, over, path, canGoBack. |
SurveyMove | .moved, .missing(ids), .submitted, .failed, .closed, .stayed. |
SubmitOutcome | .sent, .closed, .failed. |
Survey, SurveyFormat | format, intro, steps; .small, .large. |
SurveyStep, SurveyStepKind | id, kind, questions, blocks, branches; .questions, .thankYou. |
SurveyQuestion | id, type, title, description, required, options, other, min, max, minLabel, maxLabel, placeholder, range. |
QuestionType | .nps, .numeric, .stars, .emoji, .dropdown, .shortText, .longText, .singleChoice, .multiChoice; scaled, choice. |
SurveyOption, SurveyBranch | id, label; questionId, values, min, max, next. |
SurveyAnswer | init(questionId:number:choices:other:text:), answered. |
branchMatches, nextStep, surveyPath, unansweredRequired, answersOnPath, answerFits, checkSubmit, surveyPathIds | A survey’s rules, as PurrCRM keeps them. |
| Limits | otherOption ("other"), maxShortAnswerRunes (200), maxLongAnswerRunes (2000), maxOtherRunes (200), maxReceiptPath, checkinEvery. |
CarouselSession (main actor) | message, flow, state, screen, buttons, progress, seen(), tap(_:), choose(_:), swipeForward(), back(), close(), openLink(_:), done(). |
CarouselState | at, picked, frozen, busy, over, progress, dot, canGoBack, endedOnLink. |
Carousel | screens, start, progress, skip, presentation, locked, style. |
CarouselScreen | id, layout, image, blocks, align, valign, background, buttons, choice, next, style. |
CarouselImage, CarouselBackground | url, alt, size, aspect, fit, shape; kind, color, color2, angle, imageUrl, scrim. |
CarouselButton, CarouselButtonAction | id, label, style, action, screen, link, permission; .next, .screen, .back, .end, .link, .permission. |
CarouselChoice, CarouselOption | multiple, options; id, label, emoji, next. |
CarouselStyle | accent, corner, buttonShape, textScale. |
CarouselLayout, BackgroundKind, CarouselScrim, CarouselProgress, CarouselPresentation, CarouselCorner, CarouselButtonShape, CarouselTextScale, CarouselPermission | .centred, .imageTop, .imageFull, .text; .plain, .color, .gradient, .image; .none, .light, .dark; .dots, .bar, .none; .sheet, .card, .full; .soft, .round, .square; .pill, .rounded; .compact, .regular, .large; .notifications, .location. |
CarouselFlow, CarouselWalk, CarouselLead, carouselEndIndex, carouselEnd, maxCarouselScreens | A carousel’s rules: where each screen and button leads, the way taken, and the screens’ order. |
Content
Section titled “Content”| Type | What it is |
|---|---|
ContentBlock | type, level, spans, items, imageUrl, alt, label, link, size, color, align, weight, tone, emoji, aspect, fit, shape, style, textSize, imageSize, spacerSize. |
BlockType | .paragraph, .heading, .bullets, .numbers, .image, .button, .divider, .eyebrow, .callout, .checklist, .spacer, .emoji. |
Span, ListItem | text, bold, italic, link, underline, strike, highlight, color; spans. |
ColorToken | .accent, .ink, .muted, .surface, .wash, .good, .warn, .bad. |
TextSize, TextWeight, ContentAlign, ContentVAlign, CalloutTone, SpacerSize, ImageSize, ImageAspect, ImageFit, ImageShape, ContentButtonStyle | How a block is drawn. |
drawnBlocks(_:), plainText(_:), maxBlockLinkBytes | The blocks to draw, their text, the longest link. |
Preferences
Section titled “Preferences”| Type | What it is |
|---|---|
CrmPreferencesKeeper (main actor) | state, wording, load(), choose(_:_:_:), turnAllOff(). |
PreferencesState | preferences, loading, message, saving, saveMessage, kept. |
CrmPreferences, CrmPreferenceTopic, CrmPreferenceState | topics, allOff; id, name, description, channels; channel, subscribed. |
CrmPreferenceChannel | .email, .push, .inApp, .chat. |
CrmPreferenceChoice, CrmPreferencesBody, CrmPublicPreferences | A choice sent, the body it goes in, the web page’s preferences. |
withChoice(_:_:_:_:), allTurnedOff(_:) | Preferences with a choice made, or all off. |
crmPreferencesWording, crmMaxPreferenceChoices, crmMaxPreferenceWording | The wording version kept with each choice, and limits. |
Events
Section titled “Events”| Type | What it is |
|---|---|
CrmEvent | .appOpened, .sessionEnded, .screenViewed, .appUpdated, .pushPermissionChanged, .locationPermissionChanged, .pushOpened, .linkOpened. |
CrmFlushResult | How a batch went: .nothing, .accepted(_), .refused(_), .failed(_). |
EventBody, EventsBody, EventsAccepted, EventRejected | An event, a batch, and PurrCRM‘s answer. |
| Limits | maxEventBatch (50), maxEventProps (10), maxEventPropRunes (120), maxEventAge (7 days). |
Failures
Section titled “Failures”| Type | What it is |
|---|---|
CrmFailure | Why a request did not succeed; one of the four below. |
CrmProblem | PurrCRM said no: problem, status, code, error, detail, requestId, retryAfter; init(status:code:title:detail:scope:retryAfterSeconds:requestId:) for a fake. |
CrmAppUnavailable | The app is archived or deleted: final. |
CrmOffline | No answer: cause, timedOut. |
CrmContractError | An answer the SDK cannot read: message. |
CrmTimedOut | An attempt past its deadline. |
Problem, CrmErrorCode, CrmLimitScope | The refusal (status, code, title, detail, scope, retryAfterSeconds, requestId, error, isTokenExpired, isAppUnavailable), its code, and whose limit. |
CrmSentence | .offline, .unavailable, .rateLimited, .rateLimitedGuest, .signInAgain, .badRequest, .notFound, .conversationGone, .ticketGone, .articleGone, .ratingClosed, .surveyClosed, .botMovedOn, .answerInvalid, .attachmentInvalid, .refused, .somethingWentWrong. |
CrmAttempt | .messenger, .ticket, .help, .other: what the user was doing. |
CrmFailureMessage | sentence, detail, retry, fromService. |
CrmRetryHint | at, after, soon, leftAt(_:), passedAt(_:). |
tellCrmFailure(_:attempt:now:), tellCrmProblem(_:attempt:now:), crmSentenceFor(_:attempt:), shownCrmDetail(_:), crmRetryHint(_:now:) | What to tell the user. |
The app and test mode
Section titled “The app and test mode”| Type | What it is |
|---|---|
CrmPublicApp | key, mode, brand, features, currency, orderRef, minSdkVersion, linkBase, languages, isTest. |
CrmPublicBrand | name, accent, logoUrl, supportEmail. |
CrmPublicLinkApp, CrmPublicRatingBody | The link page’s app, and a web page’s article rating. |
isTestAppKey(_:) | Whether a key is a test app’s. |
testKeyInReleaseWarning, debugInReleaseWarning | The warnings a release build logs. |
crmSdkVersion, crmSdkKind, CrmSdkKind | "0.2.0", "ios"; .flutter, .android, .ios, .web. |
CrmPlatform | .ios, .android, .web. |
The setup check
Section titled “The setup check”| Type | What it is |
|---|---|
CrmSetupCheck | A row: id, section, title, status, summary, detail, fix. |
CrmCheckStatus | .ok, .warning, .failure, .skipped. |
SetupFacts | Everything the checks look at. |
setupChecks(_:) | The rows for some facts. |
setupReport(_:facts:at:) | The report, as text. |
CrmProbe | How a request went: status, milliseconds, requestId, failure, detail, ok. |
CrmPushPermission | .authorized, .provisional, .ephemeral, .denied, .notDetermined, .unknown. |
CrmTestLink, CrmLinkTry | name, url; ours, goes. |
aasaCovers(_:bundleId:path:), associatedDomains(inProvision:) | Reads the apple-app-site-association file, and a provision’s Associated Domains. |
Plumbing
Section titled “Plumbing”For tests, and for an app that hands the SDK its own storage or HTTP.
| Type | What it is |
|---|---|
CrmStore | Protocol: prefix, read(_:), write(_:_:), remove(_:). |
DefaultsCrmStore, MemoryCrmStore | UserDefaults; memory (values, set(_:_:)). |
crmStoreKey(_:_:), CrmStoreName | A key’s name, and the names the SDK keeps. |
EventQueueStore, UsageStore | The stores the event queue and the usage events keep. |
CrmHttpClient | Protocol: send(_:timeout:progress:), and send(_:timeout:). |
CrmHttpRequest, CrmHttpResponse | method, url, headers, body; status, headers, body. |
URLSessionHttpClient | The SDK’s own, over URLSession. |
CrmClock, SystemClock | now(), sleep(_:). |
CrmTransport, HttpCrmTransport, CrmBody, CrmResponse, CrmRequestLog | The requests to PurrCRM, their bodies, answers and log lines. |
MessengerApi, HelpApi, DeliveryApi, PreferencesApi | The guest routes over a CrmTransport, one call each, as the facade’s parts use them. |
newIdempotencyKey() | A fresh key for a send. |
JsonValue, JsonError, Fields, FormatError, CrmTime, formatTime(_:) | Reading and writing PurrCRM‘s JSON and times. |
CrmWord | The vocabularies’ protocol: init(word:), word, unknown. |
crmAppKeyHeader, crmUserIdHeader, crmSdkVersionHeader, crmSdkKindHeader, crmTestAppKeyPrefix | The headers and the test key’s prefix. |
The request bodies (CheckinBody, ReceiptBody, MessageBody, StartBody, OpeningRef, ReadBody, RatingBody, AttachmentBody, AttachmentUpload, BotReplyBody, ArticleRatingBody, SurveyAnswerBody, SurveySubmit, OpenMessageBody, ShareLinkBody, LinkClaimBody, AppLinksReport, DeclaredLink, CrmDeviceBody, CrmForgetDeviceBody, CrmNoticesReadBody, CrmConsentBody, CrmUnreadCount, Checkin, CrmProblemBody, CrmRateLimited) and the data export’s models (ExportContact and the Export… and CrmExport… types) are public too, for tests against PurrCRM‘s contract; an app does not need them.