@joinskips/common 0.0.0-stage → 0.1.0-develop.144

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.
Files changed (131) hide show
  1. package/README.md +104 -2
  2. package/dist/chat/SkipsChat.d.ts +37 -0
  3. package/dist/chat/SkipsChat.js +103 -0
  4. package/dist/chat/client.d.ts +53 -0
  5. package/dist/chat/client.js +178 -0
  6. package/dist/chat/connection.d.ts +4 -0
  7. package/dist/chat/connection.js +6 -0
  8. package/dist/chat/generated/skips-app/index.d.ts +1 -0
  9. package/dist/chat/generated/skips-app/index.js +2 -0
  10. package/dist/chat/generated/skips-app/types.gen.d.ts +733 -0
  11. package/dist/chat/generated/skips-app/types.gen.js +2 -0
  12. package/dist/chat/index.d.ts +3 -0
  13. package/dist/chat/index.js +2 -0
  14. package/dist/chat/platform.d.ts +4 -0
  15. package/dist/chat/platform.js +46 -0
  16. package/dist/chat/session.d.ts +19 -0
  17. package/dist/chat/session.js +95 -0
  18. package/dist/chat/useSkipsChat.d.ts +79 -0
  19. package/dist/chat/useSkipsChat.js +507 -0
  20. package/dist/chat/verify.d.ts +35 -0
  21. package/dist/chat/verify.js +84 -0
  22. package/dist/elements/skips-elements.js +18521 -0
  23. package/dist/helpers/attachments.d.ts +12 -0
  24. package/dist/helpers/attachments.js +34 -0
  25. package/dist/helpers/cable.d.ts +34 -0
  26. package/dist/helpers/cable.js +88 -0
  27. package/dist/helpers/cableFrames.d.ts +40 -0
  28. package/dist/helpers/cableFrames.js +70 -0
  29. package/dist/helpers/cardNote.d.ts +79 -0
  30. package/dist/helpers/cardNote.js +152 -0
  31. package/dist/helpers/commandNote.d.ts +4 -0
  32. package/dist/helpers/commandNote.js +23 -0
  33. package/dist/helpers/index.d.ts +19 -0
  34. package/dist/helpers/index.js +19 -0
  35. package/dist/helpers/markdown.d.ts +47 -0
  36. package/dist/helpers/markdown.js +129 -0
  37. package/dist/helpers/medicationOrder.d.ts +333 -0
  38. package/dist/helpers/medicationOrder.js +383 -0
  39. package/dist/helpers/message.d.ts +46 -0
  40. package/dist/helpers/message.js +12 -0
  41. package/dist/helpers/noteView.d.ts +35 -0
  42. package/dist/helpers/noteView.js +65 -0
  43. package/dist/helpers/orderForm.d.ts +126 -0
  44. package/dist/helpers/orderForm.js +271 -0
  45. package/dist/helpers/ordersMenu.d.ts +56 -0
  46. package/dist/helpers/ordersMenu.js +129 -0
  47. package/dist/helpers/regimenChoice.d.ts +42 -0
  48. package/dist/helpers/regimenChoice.js +73 -0
  49. package/dist/helpers/scrollBox.d.ts +5 -0
  50. package/dist/helpers/scrollBox.js +15 -0
  51. package/dist/helpers/skipTyping.d.ts +26 -0
  52. package/dist/helpers/skipTyping.js +29 -0
  53. package/dist/helpers/skipsMessage.d.ts +55 -0
  54. package/dist/helpers/skipsMessage.js +130 -0
  55. package/dist/helpers/stageRefill.d.ts +33 -0
  56. package/dist/helpers/stageRefill.js +41 -0
  57. package/dist/helpers/thread.d.ts +54 -0
  58. package/dist/helpers/thread.js +122 -0
  59. package/dist/helpers/typing.d.ts +13 -0
  60. package/dist/helpers/typing.js +68 -0
  61. package/dist/helpers/usrxNote.d.ts +22 -0
  62. package/dist/helpers/usrxNote.js +26 -0
  63. package/dist/helpers/visibleArea.d.ts +15 -0
  64. package/dist/helpers/visibleArea.js +11 -0
  65. package/dist/helpers/welcome.d.ts +25 -0
  66. package/dist/helpers/welcome.js +51 -0
  67. package/dist/hooks/index.d.ts +8 -0
  68. package/dist/hooks/index.js +8 -0
  69. package/dist/hooks/useCardNoteActions.d.ts +82 -0
  70. package/dist/hooks/useCardNoteActions.js +210 -0
  71. package/dist/hooks/useCodeEntry.d.ts +6 -0
  72. package/dist/hooks/useCodeEntry.js +14 -0
  73. package/dist/hooks/useComposer.d.ts +20 -0
  74. package/dist/hooks/useComposer.js +40 -0
  75. package/dist/hooks/useOrderForm.d.ts +80 -0
  76. package/dist/hooks/useOrderForm.js +403 -0
  77. package/dist/hooks/useOrdersMenu.d.ts +114 -0
  78. package/dist/hooks/useOrdersMenu.js +337 -0
  79. package/dist/hooks/useRegimenChoice.d.ts +23 -0
  80. package/dist/hooks/useRegimenChoice.js +50 -0
  81. package/dist/hooks/useResendCountdown.d.ts +2 -0
  82. package/dist/hooks/useResendCountdown.js +19 -0
  83. package/dist/hooks/useStepField.d.ts +8 -0
  84. package/dist/hooks/useStepField.js +17 -0
  85. package/dist/hooks/useTypingCue.d.ts +11 -0
  86. package/dist/hooks/useTypingCue.js +41 -0
  87. package/dist/hooks/useWelcomeTyping.d.ts +2 -0
  88. package/dist/hooks/useWelcomeTyping.js +25 -0
  89. package/dist/index.d.ts +5 -0
  90. package/dist/index.js +5 -0
  91. package/dist/staff/CardNoteActions.d.ts +10 -0
  92. package/dist/staff/CardNoteActions.js +16 -0
  93. package/dist/staff/OrderFormNote.d.ts +8 -0
  94. package/dist/staff/OrderFormNote.js +8 -0
  95. package/dist/staff/OrdersMenuNote.d.ts +8 -0
  96. package/dist/staff/OrdersMenuNote.js +8 -0
  97. package/dist/staff/RegimenChoiceNote.d.ts +7 -0
  98. package/dist/staff/RegimenChoiceNote.js +8 -0
  99. package/dist/staff/features.d.ts +9 -0
  100. package/dist/staff/features.js +8 -0
  101. package/dist/staff/index.d.ts +11 -0
  102. package/dist/staff/index.js +7 -0
  103. package/dist/ui/Bubble.d.ts +5 -0
  104. package/dist/ui/Bubble.js +9 -0
  105. package/dist/ui/CardActions.d.ts +34 -0
  106. package/dist/ui/CardActions.js +28 -0
  107. package/dist/ui/Conversation.d.ts +69 -0
  108. package/dist/ui/Conversation.js +192 -0
  109. package/dist/ui/Markdown.d.ts +11 -0
  110. package/dist/ui/Markdown.js +51 -0
  111. package/dist/ui/NoteFold.d.ts +19 -0
  112. package/dist/ui/NoteFold.js +12 -0
  113. package/dist/ui/NoteViewControl.d.ts +19 -0
  114. package/dist/ui/NoteViewControl.js +20 -0
  115. package/dist/ui/OrderForm.d.ts +71 -0
  116. package/dist/ui/OrderForm.js +118 -0
  117. package/dist/ui/OrdersMenu.d.ts +71 -0
  118. package/dist/ui/OrdersMenu.js +128 -0
  119. package/dist/ui/RegimenChoice.d.ts +23 -0
  120. package/dist/ui/RegimenChoice.js +16 -0
  121. package/dist/ui/SkipAvatar.d.ts +7 -0
  122. package/dist/ui/SkipAvatar.js +8 -0
  123. package/dist/ui/StaffButton.d.ts +18 -0
  124. package/dist/ui/StaffButton.js +17 -0
  125. package/dist/ui/Welcome.d.ts +91 -0
  126. package/dist/ui/Welcome.js +128 -0
  127. package/dist/ui/index.d.ts +8 -0
  128. package/dist/ui/index.js +7 -0
  129. package/dist/ui/parts.d.ts +38 -0
  130. package/dist/ui/parts.js +6 -0
  131. package/package.json +115 -4
@@ -0,0 +1,12 @@
1
+ export declare const ATTACHMENT_TYPES: string[];
2
+ export declare const MAX_ATTACHMENT_BYTES: number;
3
+ /** A picked file's type: the picker's own, else the one its name says, else none. */
4
+ export declare function attachmentType(name: string, given?: string | null): string;
5
+ /** What attachmentProblem reads of a picked file. */
6
+ export interface FileFacts {
7
+ type: string;
8
+ size: number;
9
+ }
10
+ export type AttachmentProblem = 'type' | 'size';
11
+ /** Why a picked file cannot be sent, or null when it can. */
12
+ export declare function attachmentProblem(file: FileFacts): AttachmentProblem | null;
@@ -0,0 +1,34 @@
1
+ export const ATTACHMENT_TYPES = [
2
+ 'image/jpeg',
3
+ 'image/png',
4
+ 'image/gif',
5
+ 'image/webp',
6
+ 'image/heic',
7
+ 'image/heif',
8
+ 'application/pdf',
9
+ ];
10
+ export const MAX_ATTACHMENT_BYTES = 40 * 1024 * 1024;
11
+ // Pickers can leave the type out, so it comes from the name.
12
+ const TYPE_BY_EXTENSION = new Map([
13
+ ['jpg', 'image/jpeg'],
14
+ ['jpeg', 'image/jpeg'],
15
+ ['png', 'image/png'],
16
+ ['gif', 'image/gif'],
17
+ ['webp', 'image/webp'],
18
+ ['heic', 'image/heic'],
19
+ ['heif', 'image/heif'],
20
+ ['pdf', 'application/pdf'],
21
+ ]);
22
+ /** A picked file's type: the picker's own, else the one its name says, else none. */
23
+ export function attachmentType(name, given) {
24
+ if (given)
25
+ return given;
26
+ const dot = name.lastIndexOf('.');
27
+ return dot === -1 ? '' : (TYPE_BY_EXTENSION.get(name.slice(dot + 1).toLowerCase()) ?? '');
28
+ }
29
+ /** Why a picked file cannot be sent, or null when it can. */
30
+ export function attachmentProblem(file) {
31
+ if (!ATTACHMENT_TYPES.includes(file.type))
32
+ return 'type';
33
+ return file.size > MAX_ATTACHMENT_BYTES ? 'size' : null;
34
+ }
@@ -0,0 +1,34 @@
1
+ import { type ChatEvent } from './cableFrames.ts';
2
+ export declare const STALE_MS = 10000;
3
+ export declare const FIRST_RETRY_MS = 1000;
4
+ export declare const MAX_RETRY_MS = 30000;
5
+ export type CableState = 'connecting' | 'live' | 'down';
6
+ export interface CableOptions {
7
+ careTeamName: string;
8
+ createSocket: (url: string) => Socket;
9
+ now: () => number;
10
+ }
11
+ export interface CableHandlers {
12
+ onEvent: (event: ChatEvent) => void;
13
+ onState: (state: CableState) => void;
14
+ onKeysRefused: () => void;
15
+ }
16
+ /** The socket address for a Skips App origin, such as https://app.joinskips.com. */
17
+ export declare const cableUrl: (origin: string) => string;
18
+ /** The wait before the nth reconnect, doubling up to MAX_RETRY_MS. */
19
+ export declare const retryDelay: (attempt: number) => number;
20
+ export interface SocketMessage {
21
+ data: unknown;
22
+ }
23
+ export interface Socket extends Pick<WebSocket, 'send' | 'close'> {
24
+ onopen: ((event: unknown) => void) | null;
25
+ onmessage: ((event: SocketMessage) => void) | null;
26
+ onclose: ((event: unknown) => void) | null;
27
+ onerror: ((event: unknown) => void) | null;
28
+ }
29
+ /**
30
+ * Opens the feed for the member's keys, the Skips App's pubsub tokens, on sockets the app makes with createSocket.
31
+ * now is the app's clock, which the stale check reads.
32
+ * Returns a function that closes it for good.
33
+ */
34
+ export declare function openCable(url: string, keys: string[], handlers: CableHandlers, { careTeamName, createSocket, now }: CableOptions): () => void;
@@ -0,0 +1,88 @@
1
+ // A small ActionCable client for the Skips App's RoomChannel. It says when the feed is live or down, so a silent drop
2
+ // never goes unnoticed: no frame for STALE_MS counts as down, and it reconnects with backoff. The Skips App pings
3
+ // every 3 seconds.
4
+ import { readFrame } from "./cableFrames.js";
5
+ export const STALE_MS = 10_000;
6
+ export const FIRST_RETRY_MS = 1_000;
7
+ export const MAX_RETRY_MS = 30_000;
8
+ /** The socket address for a Skips App origin, such as https://app.joinskips.com. */
9
+ export const cableUrl = (origin) => `${origin.replace(/\/$/, '').replace(/^http/, 'ws')}/cable`;
10
+ /** The wait before the nth reconnect, doubling up to MAX_RETRY_MS. */
11
+ export const retryDelay = (attempt) => Math.min(MAX_RETRY_MS, FIRST_RETRY_MS * 2 ** attempt);
12
+ /**
13
+ * Opens the feed for the member's keys, the Skips App's pubsub tokens, on sockets the app makes with createSocket.
14
+ * now is the app's clock, which the stale check reads.
15
+ * Returns a function that closes it for good.
16
+ */
17
+ export function openCable(url, keys, handlers, { careTeamName, createSocket, now }) {
18
+ let socket = null;
19
+ let attempt = 0;
20
+ let lastFrameAt = now();
21
+ let closed = false;
22
+ let retry = null;
23
+ let state = null;
24
+ const setState = (next) => {
25
+ if (next !== state)
26
+ handlers.onState((state = next));
27
+ };
28
+ const drop = (reconnect) => {
29
+ if (socket) {
30
+ const old = socket;
31
+ socket = null;
32
+ old.onclose = old.onmessage = old.onerror = old.onopen = null;
33
+ old.close();
34
+ }
35
+ setState('down');
36
+ if (reconnect && !closed && !retry)
37
+ retry = setTimeout(connect, retryDelay(attempt++));
38
+ };
39
+ function connect() {
40
+ retry = null;
41
+ setState('connecting');
42
+ lastFrameAt = now();
43
+ const next = createSocket(url);
44
+ socket = next;
45
+ next.onmessage = ({ data }) => {
46
+ lastFrameAt = now();
47
+ const frame = readFrame(String(data), careTeamName);
48
+ if (frame.type === 'welcome') {
49
+ attempt = 0;
50
+ for (const key of keys) {
51
+ next.send(JSON.stringify({
52
+ command: 'subscribe',
53
+ identifier: JSON.stringify({ channel: 'RoomChannel', pubsub_token: key }),
54
+ }));
55
+ }
56
+ }
57
+ else if (frame.type === 'confirm_subscription')
58
+ setState('live');
59
+ else if (frame.type === 'event')
60
+ handlers.onEvent(frame.event);
61
+ else if (frame.type === 'reject_subscription' || (frame.type === 'disconnect' && !frame.reconnect)) {
62
+ drop(false);
63
+ handlers.onKeysRefused();
64
+ }
65
+ else if (frame.type === 'disconnect')
66
+ drop(true);
67
+ };
68
+ next.onclose = () => {
69
+ drop(true);
70
+ };
71
+ next.onerror = () => {
72
+ drop(true);
73
+ };
74
+ }
75
+ const watchdog = setInterval(() => {
76
+ if (socket && now() - lastFrameAt > STALE_MS)
77
+ drop(true);
78
+ }, STALE_MS / 2);
79
+ connect();
80
+ return () => {
81
+ closed = true;
82
+ clearInterval(watchdog);
83
+ if (retry)
84
+ clearTimeout(retry);
85
+ retry = null;
86
+ drop(false);
87
+ };
88
+ }
@@ -0,0 +1,40 @@
1
+ import type { ChatMessage } from './message.ts';
2
+ interface ChatMessageEvent {
3
+ kind: 'message';
4
+ conversationId: number;
5
+ message: ChatMessage;
6
+ }
7
+ interface TypingEvent {
8
+ kind: 'typing';
9
+ conversationId: number;
10
+ typing: boolean;
11
+ name: string;
12
+ }
13
+ interface ConversationEvent {
14
+ kind: 'conversation';
15
+ conversationId: number;
16
+ }
17
+ export type ChatEvent = ChatMessageEvent | TypingEvent | ConversationEvent;
18
+ type ControlType = 'welcome' | 'ping' | 'confirm_subscription' | 'reject_subscription';
19
+ interface ControlFrame {
20
+ type: ControlType;
21
+ }
22
+ interface DisconnectFrame {
23
+ type: 'disconnect';
24
+ reconnect: boolean;
25
+ }
26
+ interface EventFrame {
27
+ type: 'event';
28
+ event: ChatEvent;
29
+ }
30
+ interface IgnoredFrame {
31
+ type: 'ignored';
32
+ }
33
+ /** One ActionCable frame: a control frame the client handles, or a Skips App event. */
34
+ export type CableFrame = ControlFrame | DisconnectFrame | EventFrame | IgnoredFrame;
35
+ /**
36
+ * Reads one frame of text from the socket. A frame that is not JSON, or not one the app knows, is ignored.
37
+ * careTeamName is the app's name for a care team line with no named sender (toChatMessage).
38
+ */
39
+ export declare function readFrame(text: string, careTeamName: string): CableFrame;
40
+ export {};
@@ -0,0 +1,70 @@
1
+ // What the Skips App's live socket says, read into the few things an app acts on. Shapes come from the socket itself
2
+ // (message_type and created_at as numbers, the member's own typing never sent back), and anything else is ignored.
3
+ import { firstFilled, isNullableString, isObject, isRawMessage, optional, toChatMessage } from "./skipsMessage.js";
4
+ const CONTROL_TYPES = ['welcome', 'ping', 'confirm_subscription', 'reject_subscription'];
5
+ const IGNORED = { type: 'ignored' };
6
+ function isTypingData(value) {
7
+ if (!isObject(value) || !isObject(value.user) || !isObject(value.conversation))
8
+ return false;
9
+ const { user } = value;
10
+ return (optional(value.is_private, (flag) => typeof flag === 'boolean') &&
11
+ optional(user.type, (type) => typeof type === 'string') &&
12
+ optional(user.available_name, isNullableString) &&
13
+ optional(user.name, isNullableString) &&
14
+ typeof value.conversation.id === 'number');
15
+ }
16
+ const fieldIn = (value, key) => (isObject(value) ? value[key] : undefined);
17
+ function toEvent(message, careTeamName) {
18
+ const event = fieldIn(message, 'event');
19
+ const data = fieldIn(message, 'data');
20
+ switch (event) {
21
+ case 'message.created':
22
+ case 'message.updated': {
23
+ if (!isRawMessage(data))
24
+ return null;
25
+ const chatMessage = toChatMessage(data, careTeamName);
26
+ return chatMessage ? { kind: 'message', conversationId: data.conversation_id ?? 0, message: chatMessage } : null;
27
+ }
28
+ case 'conversation.typing_on':
29
+ case 'conversation.typing_off': {
30
+ // A private note's typing is the care team's own, and a contact's typing is the member's.
31
+ if (!isTypingData(data) || data.is_private || data.user.type === 'contact')
32
+ return null;
33
+ return {
34
+ kind: 'typing',
35
+ conversationId: data.conversation.id,
36
+ typing: event === 'conversation.typing_on',
37
+ name: firstFilled(data.user.available_name, data.user.name) ?? '',
38
+ };
39
+ }
40
+ // Only which conversation changed: its fields on the socket can be partial, so the app asks for them again.
41
+ case 'conversation.updated':
42
+ case 'conversation.status_changed': {
43
+ const id = fieldIn(data, 'id');
44
+ return typeof id === 'number' ? { kind: 'conversation', conversationId: id } : null;
45
+ }
46
+ default:
47
+ return null;
48
+ }
49
+ }
50
+ /**
51
+ * Reads one frame of text from the socket. A frame that is not JSON, or not one the app knows, is ignored.
52
+ * careTeamName is the app's name for a care team line with no named sender (toChatMessage).
53
+ */
54
+ export function readFrame(text, careTeamName) {
55
+ let frame;
56
+ try {
57
+ frame = JSON.parse(text);
58
+ }
59
+ catch {
60
+ return IGNORED;
61
+ }
62
+ const type = fieldIn(frame, 'type');
63
+ if (type === 'disconnect')
64
+ return { type: 'disconnect', reconnect: fieldIn(frame, 'reconnect') !== false };
65
+ const control = CONTROL_TYPES.find((each) => each === type);
66
+ if (control)
67
+ return { type: control };
68
+ const event = toEvent(fieldIn(frame, 'message'), careTeamName);
69
+ return event ? { type: 'event', event } : IGNORED;
70
+ }
@@ -0,0 +1,79 @@
1
+ import { type StaffMessage } from './usrxNote.ts';
2
+ export declare const SUBMIT_COMMAND = "/treat-submit";
3
+ export declare function submitCommand(uids: readonly string[]): string;
4
+ export declare const REASON_LABEL = "Reason:";
5
+ export declare const CANCEL_COMMAND = "/treat-cancel";
6
+ export declare function cancelCommand(uids: readonly string[], reason?: string | null): string;
7
+ export declare const DISCONTINUE_COMMAND = "/treat-discontinue";
8
+ export declare function discontinueCommand(uids: readonly string[], reason?: string | null): string;
9
+ export declare const PHARMACY_ROLES: readonly string[];
10
+ /** Whether a staff member's skips_role custom attribute lets them reach a pharmacy. */
11
+ export declare function reachesPharmacy(role: string | null | undefined): boolean;
12
+ export interface NoteCard {
13
+ name: string;
14
+ uid: string;
15
+ }
16
+ export interface CardNote {
17
+ pharmacy: string;
18
+ cards: NoteCard[];
19
+ createdBy: string | null;
20
+ editedBy: string | null;
21
+ }
22
+ /**
23
+ * A card note's pharmacy and its cards by name and Treat uid. A card without a uid cannot be sent or deleted by name, so
24
+ * it is left out, and a note with no pharmacy or no card left is no card note.
25
+ */
26
+ export declare function cardNote(contentAttributes: unknown): CardNote | null;
27
+ export declare const PHARMACY_FIELD = "pharmacy";
28
+ export interface CardNeed {
29
+ uid: string;
30
+ field: string;
31
+ noteId: number | string;
32
+ }
33
+ export interface NoteState {
34
+ submitted: boolean;
35
+ submittedBy: string | null;
36
+ editedBy: string | null;
37
+ /** The uids of this note's cards usrx deleted. */
38
+ deleted: string[];
39
+ /** A later card note holds some of these cards now, and none went to the pharmacy. */
40
+ replaced: boolean;
41
+ /** A Send naming these cards waits on usrx's answer. */
42
+ asked: boolean;
43
+ /** How many Sends named these cards. */
44
+ asks: number;
45
+ /** What usrx's refusal of the last Send asks for, or null. */
46
+ needs: CardNeed | null;
47
+ /** This note's cards usrx left unsigned for the ID.me code that no later note sent, or null. */
48
+ signing: string[] | null;
49
+ /** usrx's newest note answering these cards, whose change ends a wait on usrx. */
50
+ lastUsrxNoteId: number | string | null;
51
+ }
52
+ export declare function isIdMeCode(code: string): boolean;
53
+ /**
54
+ * What became of a note's cards. A send stays asked until usrx answers, and an answer it did not ask for is a refusal,
55
+ * so Send opens again. A later card note that holds any of these cards holds them now, unless they went to the pharmacy.
56
+ */
57
+ export declare function noteState(messages: readonly StaffMessage[] | undefined, noteId: number, uids: readonly string[]): NoteState;
58
+ export interface CardPeople {
59
+ createdBy: string | null;
60
+ editedBy: string | null;
61
+ submittedBy: string | null;
62
+ }
63
+ export interface CardNoteView {
64
+ /** The note's cards that neither usrx nor this screen has deleted. */
65
+ left: NoteCard[];
66
+ allDeleted: boolean;
67
+ /** Nothing on the note can be pressed: its cards went to the pharmacy, moved to a newer note, or were all deleted. */
68
+ closed: boolean;
69
+ /** Who made, changed and sent the cards, or null once a newer note holds them. */
70
+ people: CardPeople | null;
71
+ }
72
+ /** What a card note shows, from what became of its cards and the cards deleted here before usrx's note says so. */
73
+ export declare function cardNoteView(note: CardNote, state: NoteState, deletedHere: readonly string[]): CardNoteView;
74
+ /**
75
+ * Why usrx did not delete a card, from treat_lookups' answer, or null when it deleted it. usrx answers a delete with no
76
+ * data and a refusal with its reason (usrx's jobs/delete-card.ts), so any other answer leaves the card in place, with
77
+ * an empty reason when it gives none.
78
+ */
79
+ export declare function deleteRefusal(answer: unknown): string | null;
@@ -0,0 +1,152 @@
1
+ // The private notes usrx posts for its cards carry their actions (joinskips/skips-app#297, joinskips/usrx#98). Send posts
2
+ // usrx's submit command naming the note's cards, the way a provider types it, and Edit and Delete ask usrx through the
3
+ // treat_lookups endpoint. usrx answers each with a note, which is what a button waits for.
4
+ import { isObject, isString } from "./skipsMessage.js";
5
+ import { isUsrxNote, messagesAfter, noteAttribute, uidOf, withoutLeadingMarks, } from "./usrxNote.js";
6
+ export const SUBMIT_COMMAND = '/treat-submit';
7
+ export function submitCommand(uids) {
8
+ return [SUBMIT_COMMAND, ...uids].join(' ');
9
+ }
10
+ // A reason goes after the uids and "Reason:", on one line, as usrx's receiver reads it (lambda/receiver.ts reasonOf).
11
+ export const REASON_LABEL = 'Reason:';
12
+ function withReason(words, reason) {
13
+ const said = (reason ?? '').replace(/\s+/g, ' ').trim();
14
+ return (said ? [...words, REASON_LABEL, said] : words).join(' ');
15
+ }
16
+ // The Orders menu's actions on a sent prescription (commands/treat-cancel.md, commands/treat-discontinue.md).
17
+ export const CANCEL_COMMAND = '/treat-cancel';
18
+ export function cancelCommand(uids, reason) {
19
+ return withReason([CANCEL_COMMAND, ...uids], reason);
20
+ }
21
+ export const DISCONTINUE_COMMAND = '/treat-discontinue';
22
+ export function discontinueCommand(uids, reason) {
23
+ return withReason([DISCONTINUE_COMMAND, ...uids], reason);
24
+ }
25
+ // Only these Skips roles reach a pharmacy: usrx refuses a send or a cancel from anyone else (joinskips/usrx#11), so
26
+ // their buttons show only for them (joinskips/skips-app#322).
27
+ export const PHARMACY_ROLES = ['admin', 'provider'];
28
+ /** Whether a staff member's skips_role custom attribute lets them reach a pharmacy. */
29
+ export function reachesPharmacy(role) {
30
+ return role != null && PHARMACY_ROLES.includes(role);
31
+ }
32
+ function noteCard(value) {
33
+ if (!isObject(value) || !isString(value.name) || !value.name)
34
+ return [];
35
+ const uid = uidOf(value.uid);
36
+ return uid === null ? [] : [{ name: value.name, uid }];
37
+ }
38
+ const nameOf = (value) => (isString(value) && value ? value : null);
39
+ /**
40
+ * A card note's pharmacy and its cards by name and Treat uid. A card without a uid cannot be sent or deleted by name, so
41
+ * it is left out, and a note with no pharmacy or no card left is no card note.
42
+ */
43
+ export function cardNote(contentAttributes) {
44
+ const note = isObject(contentAttributes) ? contentAttributes.usrxCreatedCards : undefined;
45
+ if (!isObject(note) || !isString(note.pharmacy) || !note.pharmacy)
46
+ return null;
47
+ const cards = Array.isArray(note.cards) ? note.cards.flatMap(noteCard) : [];
48
+ if (cards.length === 0)
49
+ return null;
50
+ return { pharmacy: note.pharmacy, cards, createdBy: nameOf(note.createdBy), editedBy: nameOf(note.editedBy) };
51
+ }
52
+ // usrx's receiver reads a command the same way (lambda/receiver.ts), so a note it acts on is a note this counts.
53
+ const SUBMIT = new RegExp(`^${SUBMIT_COMMAND}[*_\`]*(?![\\w-])`, 'i');
54
+ const commandWords = (message) => withoutLeadingMarks(message.content).trim().split(/\s+/);
55
+ const isSubmit = (message) => Boolean(message.private) && SUBMIT.test(commandWords(message).join(' '));
56
+ const answersSubmit = (message) => Boolean(noteAttribute(message, 'usrxSubmitted')) || isUsrxNote(message.content);
57
+ function namesAny(uids, named) {
58
+ return [named].flat().some((value) => {
59
+ const uid = uidOf(value);
60
+ return uid !== null && uids.includes(uid);
61
+ });
62
+ }
63
+ /** One of a note's attributes when it is an object, such as usrxSubmitted, or null. */
64
+ function attributeObject(message, name) {
65
+ const found = noteAttribute(message, name);
66
+ return isObject(found) ? found : null;
67
+ }
68
+ const listOf = (value) => (Array.isArray(value) ? value : []);
69
+ // A Send usrx refuses names what each card lacks (joinskips/usrx#202): a pharmacy, or the first field the order left blank.
70
+ export const PHARMACY_FIELD = 'pharmacy';
71
+ function needed(message) {
72
+ const pharmacy = attributeObject(message, 'usrxPharmacyNeeded');
73
+ if (pharmacy) {
74
+ return listOf(pharmacy.cards).map((value) => ({ uid: String(value), field: PHARMACY_FIELD, noteId: message.id }));
75
+ }
76
+ return listOf(attributeObject(message, 'usrxCardIncomplete')?.cards).flatMap((card) => {
77
+ const uid = isObject(card) ? uidOf(card.uid) : null;
78
+ const field = isObject(card) ? listOf(card.missing)[0] : undefined;
79
+ return uid !== null && isString(field) && field ? [{ uid, field, noteId: message.id }] : [];
80
+ });
81
+ }
82
+ // The ID.me app shows a six-digit code, which signs the cards a Send left unsigned (joinskips/usrx#335).
83
+ const ID_ME_CODE = /^\d{6}$/;
84
+ export function isIdMeCode(code) {
85
+ return ID_ME_CODE.test(code);
86
+ }
87
+ /**
88
+ * What became of a note's cards. A send stays asked until usrx answers, and an answer it did not ask for is a refusal,
89
+ * so Send opens again. A later card note that holds any of these cards holds them now, unless they went to the pharmacy.
90
+ */
91
+ export function noteState(messages, noteId, uids) {
92
+ const later = messagesAfter(messages, noteId);
93
+ const next = later.findIndex((message) => namesAny(uids, listOf(attributeObject(message, 'usrxCreatedCards')?.cards).map((card) => (isObject(card) ? card.uid : undefined))));
94
+ const answering = next < 0 ? later : later.slice(0, next);
95
+ const naming = (name, of) => answering.flatMap((message) => {
96
+ const found = attributeObject(message, name);
97
+ return found && namesAny(uids, of(found)) ? [found] : [];
98
+ });
99
+ const sent = naming('usrxSubmitted', (found) => listOf(found.cards));
100
+ const deleted = naming('usrxCardDeleted', (found) => found.uid);
101
+ const asks = answering.filter((message) => isSubmit(message) && namesAny(uids, commandWords(message).slice(1)));
102
+ const lastAsk = asks.at(-1);
103
+ const sinceAsk = lastAsk ? answering.slice(answering.indexOf(lastAsk) + 1) : answering;
104
+ const needs = lastAsk ? sinceAsk.flatMap(needed).find((need) => uids.includes(need.uid)) : undefined;
105
+ const signingNote = answering.filter((message) => namesAny(uids, listOf(attributeObject(message, 'usrxSigningCode')?.cards))).at(-1);
106
+ const signingCards = signingNote
107
+ ? listOf(attributeObject(signingNote, 'usrxSigningCode')?.cards).flatMap((value) => {
108
+ const uid = uidOf(value);
109
+ return uid !== null && uids.includes(uid) ? [uid] : [];
110
+ })
111
+ : [];
112
+ const sentLater = answering
113
+ .slice(signingNote ? answering.indexOf(signingNote) + 1 : answering.length)
114
+ .flatMap((message) => listOf(attributeObject(message, 'usrxSubmitted')?.cards).map(uidOf));
115
+ const unsigned = signingCards.filter((uid) => !sentLater.includes(uid));
116
+ return {
117
+ submitted: sent.length > 0,
118
+ submittedBy: nameOf(sent.at(-1)?.by),
119
+ editedBy: nameOf(naming('usrxCardChanged', (found) => found.uid).at(-1)?.by),
120
+ deleted: uids.filter((uid) => deleted.some((found) => uidOf(found.uid) === uid)),
121
+ replaced: next >= 0 && sent.length === 0,
122
+ asked: asks.length > 0 && !sinceAsk.some(answersSubmit),
123
+ asks: asks.length,
124
+ needs: needs ?? null,
125
+ // A newer card note holds the cards once edited, and its own Send asks for the code again.
126
+ signing: next < 0 && unsigned.length > 0 ? unsigned : null,
127
+ lastUsrxNoteId: answering.filter(answersSubmit).at(-1)?.id ?? null,
128
+ };
129
+ }
130
+ /** What a card note shows, from what became of its cards and the cards deleted here before usrx's note says so. */
131
+ export function cardNoteView(note, state, deletedHere) {
132
+ const left = note.cards.filter((card) => !state.deleted.includes(card.uid) && !deletedHere.includes(card.uid));
133
+ const allDeleted = left.length === 0;
134
+ return {
135
+ left,
136
+ allDeleted,
137
+ closed: state.submitted || state.replaced || allDeleted,
138
+ people: state.replaced
139
+ ? null
140
+ : { createdBy: note.createdBy, editedBy: state.editedBy ?? note.editedBy, submittedBy: state.submittedBy },
141
+ };
142
+ }
143
+ /**
144
+ * Why usrx did not delete a card, from treat_lookups' answer, or null when it deleted it. usrx answers a delete with no
145
+ * data and a refusal with its reason (usrx's jobs/delete-card.ts), so any other answer leaves the card in place, with
146
+ * an empty reason when it gives none.
147
+ */
148
+ export function deleteRefusal(answer) {
149
+ if (answer === null)
150
+ return null;
151
+ return isObject(answer) && isString(answer.why) ? answer.why : '';
152
+ }
@@ -0,0 +1,4 @@
1
+ /** Whether a note folds to one line: a command, or usrx's answer, tagged or carrying a usrx attribute. */
2
+ export declare function isCommandNote(isPrivate: boolean | undefined, content: string | null | undefined, contentAttributes: unknown): boolean;
3
+ /** A folded note's line: its first line with words, without its markdown marks. */
4
+ export declare function summaryLine(content: string | null | undefined): string;
@@ -0,0 +1,23 @@
1
+ // A provider's command and what usrx answers it with show as one line in the thread until opened
2
+ // (joinskips/skips-app#88). n8n's answers carry no mark of their own, so they show in full.
3
+ import { isObject } from "./skipsMessage.js";
4
+ import { isUsrxNote, withoutLeadingMarks } from "./usrxNote.js";
5
+ // The first word as n8n's and usrx's parsers read it, through markdown around the command.
6
+ const COMMAND = /^\/[a-z][\w-]*(?![\w/])/i;
7
+ /** Whether a note folds to one line: a command, or usrx's answer, tagged or carrying a usrx attribute. */
8
+ export function isCommandNote(isPrivate, content, contentAttributes) {
9
+ if (!isPrivate)
10
+ return false;
11
+ const text = withoutLeadingMarks(content);
12
+ return (COMMAND.test(text) ||
13
+ isUsrxNote(text) ||
14
+ (isObject(contentAttributes) && Object.keys(contentAttributes).some((key) => key.startsWith('usrx'))));
15
+ }
16
+ /** A folded note's line: its first line with words, without its markdown marks. */
17
+ export function summaryLine(content) {
18
+ const first = (content ?? '')
19
+ .split('\n')
20
+ .map((line) => line.trim())
21
+ .find(Boolean) ?? '';
22
+ return first.replace(/[*`]+|(?<!\w)_+|_+(?!\w)/g, '');
23
+ }
@@ -0,0 +1,19 @@
1
+ export { ATTACHMENT_TYPES, MAX_ATTACHMENT_BYTES, attachmentProblem, attachmentType, type AttachmentProblem } from './attachments.ts';
2
+ export { isSkip, type ChatAttachment, type ChatAuthor, type ChatMessage, type ChoiceItem, type MessageChoice, type PickedFile, } from './message.ts';
3
+ export { CLUSTER_GAP_MS, EMPTY_THREAD, groupThread, openQuestion, pendingId, storedIds, withFailed, withoutMessage, withPending, withReceived, withReceivedAll, withSent, type Delivery, type OpenQuestion, type RunSender, type Thread, type ThreadItem, type ThreadMessage, } from './thread.ts';
4
+ export { TYPING_CLEAR_MS, TYPING_IDLE_MS, createTypingSignal, createTypingWatch } from './typing.ts';
5
+ export { DOT_CYCLE_MS, TYPING_IDLE, TYPING_TIMES, heldFrom, typingReducer, type TypingEvent, type TypingSignal, type TypingStarted, type TypingState, type TypingTimes, } from './skipTyping.ts';
6
+ export { fitVisibleArea, type Fit, type VisualViewportBox } from './visibleArea.ts';
7
+ export { FIRST_RETRY_MS, MAX_RETRY_MS, STALE_MS, cableUrl, openCable, retryDelay, type CableHandlers, type CableOptions, type CableState, type Socket, type SocketMessage, } from './cable.ts';
8
+ export { readFrame, type CableFrame, type ChatEvent } from './cableFrames.ts';
9
+ export { CHOICE_CONTENT_TYPE, choiceFrom, fileNameIn, firstFilled, fromContact, isRawMessage, toChatMessage, toMs, type RawMessage, type RawMessageFile, type RawSender, } from './skipsMessage.ts';
10
+ export { EMAIL_MAX_LENGTH, NAME_MAX_LENGTH, RESEND_AFTER_MS, WELCOME_TYPING_TIMES, givenEmail, givenName, isEmail, isName, typesBefore, typingMs, type WelcomeStep, type WelcomeTypingTimes, } from './welcome.ts';
11
+ export { USRX_NOTE_TAG, isUsrxNote, messagesAfter, noteAttribute, uidOf, withoutLeadingMarks, type StaffMessage, } from './usrxNote.ts';
12
+ export { FIRST_LINE_TAG, PICK_ANSWER_SECONDS, PICK_COMMAND, choiceState, choiceView, optionLabel, pickNote, regimenOptions, type ChoiceState, type ChoiceView, type PickPress, type RegimenOption, } from './regimenChoice.ts';
13
+ export { CANCEL_COMMAND, DISCONTINUE_COMMAND, PHARMACY_FIELD, PHARMACY_ROLES, REASON_LABEL, SUBMIT_COMMAND, cancelCommand, cardNote, discontinueCommand, isIdMeCode, noteState, reachesPharmacy, submitCommand, type CardNeed, type CardNote, type NoteCard, type NoteState, } from './cardNote.ts';
14
+ export { isCommandNote, summaryLine } from './commandNote.ts';
15
+ export { NOTE_VIEWS, NOTE_VIEW_KEY, needsEarlierPage, noteViewFiller, notesInView, rememberNoteView, rememberedNoteView, type FillSteps, type NoteView, type NoteViewMessage, type PanelSize, type ThreadLoad, type ViewStorage, } from './noteView.ts';
16
+ export { AS_NEEDED, CANCEL_BADGES, CARD_STATUS, LOOKUP_MESSAGES, OPEN_IN_TREAT, ORDER_STATUS, ORDER_VERSION, SHOWN_PHARMACIES, SHOWN_REF_LENGTH, buildOrder, cancelBadge, cancelOpen, cancellableUids, cardWords, changedFields, currentRound, dayWords, dispenseAmount, exactRate, frequencyCode, isComplete, isQueued, itemFromCard, localDay, lookupFailure, newestMessageId, newestUsrxNote, nextDispenseAmount, noteText, oneLine, orderRows, orderStatuses, pharmacyMatches, refusalParts, roundNote, setName, sigInputs, sigText, supplyRunning, type CardFields, type CardWordsSource, type DispenseFill, type DispenseParts, type Drug, type FieldValue, type LookupFailure, type OrderDrug, type OrderFrequency, type OrderInput, type OrderItem, type OrderMeasure, type OrderPharmacy, type OrderRow, type OrderSet, type PastOrder, type Pharmacy, type PharmacyWords, type Rate, type ReadyItem, type RefusalParts, type SigParts, type SigSource, type StagedCard, type SupplyEnd, type TreatOption, type UsrxOrder, type UsrxOrderItem, type OrderStop, type SentPharmacy, } from './medicationOrder.ts';
17
+ export { STATUS_LIST, actionCommand, actionReason, cardKey, firstOf, orderLists, pharmacyNameOf, pharmacyWords, rowStatuses, rowTags, shownOrder, stagedPharmacy, statusCount, tickedRows, type OrderAction, type OrderList, type OrderLists, type RowTag, type TagName, type TagTone, type TagValues, } from './ordersMenu.ts';
18
+ export { CAN_BE_BLANK, SHORTEST_TERM, TYPING_PAUSE_MS, cardOfOrder, chartsToPick, focusField, type ChartsToPick, type DrugChoices, type FocusField, type FormItem, type FrequencyOption, type Medicine, type PharmacyChange, type Picker, type TreatChart, } from './orderForm.ts';
19
+ export { LEFT, OPEN_FORM, PICK_CHART, POSTED, stageRefill, type StageOutcome, type StageRefillResult, type StageRefillSource, } from './stageRefill.ts';
@@ -0,0 +1,19 @@
1
+ export { ATTACHMENT_TYPES, MAX_ATTACHMENT_BYTES, attachmentProblem, attachmentType } from "./attachments.js";
2
+ export { isSkip, } from "./message.js";
3
+ export { CLUSTER_GAP_MS, EMPTY_THREAD, groupThread, openQuestion, pendingId, storedIds, withFailed, withoutMessage, withPending, withReceived, withReceivedAll, withSent, } from "./thread.js";
4
+ export { TYPING_CLEAR_MS, TYPING_IDLE_MS, createTypingSignal, createTypingWatch } from "./typing.js";
5
+ export { DOT_CYCLE_MS, TYPING_IDLE, TYPING_TIMES, heldFrom, typingReducer, } from "./skipTyping.js";
6
+ export { fitVisibleArea } from "./visibleArea.js";
7
+ export { FIRST_RETRY_MS, MAX_RETRY_MS, STALE_MS, cableUrl, openCable, retryDelay, } from "./cable.js";
8
+ export { readFrame } from "./cableFrames.js";
9
+ export { CHOICE_CONTENT_TYPE, choiceFrom, fileNameIn, firstFilled, fromContact, isRawMessage, toChatMessage, toMs, } from "./skipsMessage.js";
10
+ export { EMAIL_MAX_LENGTH, NAME_MAX_LENGTH, RESEND_AFTER_MS, WELCOME_TYPING_TIMES, givenEmail, givenName, isEmail, isName, typesBefore, typingMs, } from "./welcome.js";
11
+ export { USRX_NOTE_TAG, isUsrxNote, messagesAfter, noteAttribute, uidOf, withoutLeadingMarks, } from "./usrxNote.js";
12
+ export { FIRST_LINE_TAG, PICK_ANSWER_SECONDS, PICK_COMMAND, choiceState, choiceView, optionLabel, pickNote, regimenOptions, } from "./regimenChoice.js";
13
+ export { CANCEL_COMMAND, DISCONTINUE_COMMAND, PHARMACY_FIELD, PHARMACY_ROLES, REASON_LABEL, SUBMIT_COMMAND, cancelCommand, cardNote, discontinueCommand, isIdMeCode, noteState, reachesPharmacy, submitCommand, } from "./cardNote.js";
14
+ export { isCommandNote, summaryLine } from "./commandNote.js";
15
+ export { NOTE_VIEWS, NOTE_VIEW_KEY, needsEarlierPage, noteViewFiller, notesInView, rememberNoteView, rememberedNoteView, } from "./noteView.js";
16
+ export { AS_NEEDED, CANCEL_BADGES, CARD_STATUS, LOOKUP_MESSAGES, OPEN_IN_TREAT, ORDER_STATUS, ORDER_VERSION, SHOWN_PHARMACIES, SHOWN_REF_LENGTH, buildOrder, cancelBadge, cancelOpen, cancellableUids, cardWords, changedFields, currentRound, dayWords, dispenseAmount, exactRate, frequencyCode, isComplete, isQueued, itemFromCard, localDay, lookupFailure, newestMessageId, newestUsrxNote, nextDispenseAmount, noteText, oneLine, orderRows, orderStatuses, pharmacyMatches, refusalParts, roundNote, setName, sigInputs, sigText, supplyRunning, } from "./medicationOrder.js";
17
+ export { STATUS_LIST, actionCommand, actionReason, cardKey, firstOf, orderLists, pharmacyNameOf, pharmacyWords, rowStatuses, rowTags, shownOrder, stagedPharmacy, statusCount, tickedRows, } from "./ordersMenu.js";
18
+ export { CAN_BE_BLANK, SHORTEST_TERM, TYPING_PAUSE_MS, cardOfOrder, chartsToPick, focusField, } from "./orderForm.js";
19
+ export { LEFT, OPEN_FORM, PICK_CHART, POSTED, stageRefill, } from "./stageRefill.js";
@@ -0,0 +1,47 @@
1
+ import type { Token } from 'markdown-it';
2
+ export interface TextInline {
3
+ type: 'text';
4
+ text: string;
5
+ }
6
+ export interface BreakInline {
7
+ type: 'break';
8
+ }
9
+ export interface CodeInline {
10
+ type: 'code';
11
+ text: string;
12
+ }
13
+ export interface MarkInline {
14
+ type: 'strong' | 'em' | 'del';
15
+ children: Inline[];
16
+ }
17
+ export interface LinkInline {
18
+ type: 'link';
19
+ href: string;
20
+ children: Inline[];
21
+ }
22
+ export type Inline = TextInline | BreakInline | CodeInline | MarkInline | LinkInline;
23
+ export interface ParagraphBlock {
24
+ type: 'paragraph';
25
+ children: Inline[];
26
+ }
27
+ export interface ListBlock {
28
+ type: 'list';
29
+ ordered: boolean;
30
+ start: number;
31
+ items: Block[][];
32
+ }
33
+ export interface QuoteBlock {
34
+ type: 'quote';
35
+ children: Block[];
36
+ }
37
+ export interface CodeBlock {
38
+ type: 'code';
39
+ text: string;
40
+ }
41
+ export interface RuleBlock {
42
+ type: 'rule';
43
+ }
44
+ export type Block = ParagraphBlock | ListBlock | QuoteBlock | CodeBlock | RuleBlock;
45
+ export declare const LINK_PROTOCOLS: readonly string[];
46
+ export declare function inlinesOf(token: Token): Inline[];
47
+ export declare function readMarkdown(source: string): Block[];