@segmentstream/ontology 0.137.1 → 0.138.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.138.0
4
+
5
+ `agent_chat.send` sends WhatsApp templates with a header and buttons: `header.parameters` for a text
6
+ header's variables, `header.media` for an image, video or document header's file, by an https `url`
7
+ or as a `file` stored in the ontology that the caller may read, and `buttons` for a link button's
8
+ variable, a copy-code button's code or a quick-reply button's payload, by the button's position.
9
+ Everything is checked against the approved template before anything is reserved, and the key binds
10
+ every value given. The archive keeps the buttons as the person reads them, and the delivery's
11
+ payload names a stored file by its reference, never by its link.
12
+
3
13
  ## 0.137.1
4
14
 
5
15
  The agent's built-in instructions and the descriptions builders' agents read use neutral examples
@@ -64,6 +64,19 @@ export declare const AgentChat: import("./entity.js").Entity<"agent_chat", {
64
64
  readonly name: Schema.String;
65
65
  readonly language: Schema.String;
66
66
  readonly parameters: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
67
+ readonly header: Schema.optionalKey<Schema.Struct<{
68
+ readonly parameters: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
69
+ readonly media: Schema.optionalKey<Schema.Struct<{
70
+ readonly url: Schema.optionalKey<Schema.String>;
71
+ readonly file: Schema.optionalKey<Schema.Struct<{
72
+ readonly entity: Schema.String;
73
+ readonly id: Schema.String;
74
+ readonly property: Schema.optionalKey<Schema.String>;
75
+ }>>;
76
+ readonly filename: Schema.optionalKey<Schema.String>;
77
+ }>>;
78
+ }>>;
79
+ readonly buttons: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
67
80
  }>>;
68
81
  readonly replyTo: Schema.optionalKey<Schema.String>;
69
82
  readonly idempotencyKey: Schema.String;
@@ -211,7 +211,8 @@ export const AgentChat = entity("agent_chat", {
211
211
  "message the provider refuses spends its key and says why in refusal: outside_reply_window " +
212
212
  "(on WhatsApp the person last wrote more than 24 hours ago), recipient_unreachable or " +
213
213
  "recipient_opted_out. On WhatsApp, template sends an approved template in place of text, " +
214
- "which reaches a person outside the 24 hours; give exactly one of text and template.",
214
+ "which reaches a person outside the 24 hours, with its body's, header's and buttons' " +
215
+ "values; give exactly one of text and template.",
215
216
  input: ChatSendInput,
216
217
  hints: { destructive: false, irreversible: true, idempotent: true },
217
218
  connections: [],
package/dist/chat.d.ts CHANGED
@@ -28,11 +28,35 @@ export declare const ChatPostInput: Schema.Struct<{
28
28
  readonly idempotencyKey: Schema.String;
29
29
  }>;
30
30
  export type ChatPostInput = typeof ChatPostInput.Type;
31
+ /** The file of a template's image, video or document header, where it is stored or served. */
32
+ export declare const ChatTemplateMedia: Schema.Struct<{
33
+ readonly url: Schema.optionalKey<Schema.String>;
34
+ readonly file: Schema.optionalKey<Schema.Struct<{
35
+ readonly entity: Schema.String;
36
+ readonly id: Schema.String;
37
+ readonly property: Schema.optionalKey<Schema.String>;
38
+ }>>;
39
+ readonly filename: Schema.optionalKey<Schema.String>;
40
+ }>;
41
+ export type ChatTemplateMedia = typeof ChatTemplateMedia.Type;
31
42
  /** A WhatsApp template message: an approved template by name and language, with its values. */
32
43
  export declare const ChatTemplate: Schema.Struct<{
33
44
  readonly name: Schema.String;
34
45
  readonly language: Schema.String;
35
46
  readonly parameters: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
47
+ readonly header: Schema.optionalKey<Schema.Struct<{
48
+ readonly parameters: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
49
+ readonly media: Schema.optionalKey<Schema.Struct<{
50
+ readonly url: Schema.optionalKey<Schema.String>;
51
+ readonly file: Schema.optionalKey<Schema.Struct<{
52
+ readonly entity: Schema.String;
53
+ readonly id: Schema.String;
54
+ readonly property: Schema.optionalKey<Schema.String>;
55
+ }>>;
56
+ readonly filename: Schema.optionalKey<Schema.String>;
57
+ }>>;
58
+ }>>;
59
+ readonly buttons: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
36
60
  }>;
37
61
  export type ChatTemplate = typeof ChatTemplate.Type;
38
62
  /** What `agent_chat.send` takes: a post's text, or on WhatsApp an approved template instead. */
@@ -43,6 +67,19 @@ export declare const ChatSendInput: Schema.Struct<{
43
67
  readonly name: Schema.String;
44
68
  readonly language: Schema.String;
45
69
  readonly parameters: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
70
+ readonly header: Schema.optionalKey<Schema.Struct<{
71
+ readonly parameters: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
72
+ readonly media: Schema.optionalKey<Schema.Struct<{
73
+ readonly url: Schema.optionalKey<Schema.String>;
74
+ readonly file: Schema.optionalKey<Schema.Struct<{
75
+ readonly entity: Schema.String;
76
+ readonly id: Schema.String;
77
+ readonly property: Schema.optionalKey<Schema.String>;
78
+ }>>;
79
+ readonly filename: Schema.optionalKey<Schema.String>;
80
+ }>>;
81
+ }>>;
82
+ readonly buttons: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
46
83
  }>>;
47
84
  readonly replyTo: Schema.optionalKey<Schema.String>;
48
85
  readonly idempotencyKey: Schema.String;
package/dist/chat.js CHANGED
@@ -9,6 +9,23 @@ export const ChatPostInput = Schema.Struct({
9
9
  replyTo: Schema.optionalKey(Identifier),
10
10
  idempotencyKey: Identifier,
11
11
  });
12
+ /** The file of a template's image, video or document header, where it is stored or served. */
13
+ export const ChatTemplateMedia = Schema.Struct({
14
+ url: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(2000)).annotate({
15
+ description: "An https link WhatsApp fetches the file from.",
16
+ })),
17
+ file: Schema.optionalKey(Schema.Struct({
18
+ entity: Identifier,
19
+ id: Identifier,
20
+ property: Schema.optionalKey(Identifier),
21
+ }).annotate({
22
+ description: "A file stored in the ontology, which the caller may read: the record and its file " +
23
+ "property, content by default.",
24
+ })),
25
+ filename: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(240)).annotate({
26
+ description: "A document's file name, as the person sees it.",
27
+ })),
28
+ });
12
29
  /** A WhatsApp template message: an approved template by name and language, with its values. */
13
30
  export const ChatTemplate = Schema.Struct({
14
31
  name: Identifier.annotate({ description: "The approved template's name in WhatsApp Manager." }),
@@ -19,6 +36,19 @@ export const ChatTemplate = Schema.Struct({
19
36
  description: 'The values of the template body\'s variables: "1", "2", … for numbered variables, the ' +
20
37
  "variables' names for named ones.",
21
38
  })),
39
+ header: Schema.optionalKey(Schema.Struct({
40
+ parameters: Schema.optionalKey(Schema.Record(Schema.String, Schema.String).annotate({
41
+ description: "A text header's variables' values, given as the body's are.",
42
+ })),
43
+ media: Schema.optionalKey(ChatTemplateMedia.annotate({
44
+ description: "An image, video or document header's file: by url or by file, not both.",
45
+ })),
46
+ }).annotate({ description: "The values of the template's header, when it takes any." })),
47
+ buttons: Schema.optionalKey(Schema.Record(Schema.String, Schema.String).annotate({
48
+ description: 'The values of the template\'s buttons by their position, "0" for the first: a link ' +
49
+ "button's variable, a copy-code button's code, or the payload a quick-reply button " +
50
+ "returns when tapped.",
51
+ })),
22
52
  });
23
53
  /** What `agent_chat.send` takes: a post's text, or on WhatsApp an approved template instead. */
24
54
  export const ChatSendInput = Schema.Struct({
package/dist/index.d.ts CHANGED
@@ -63,7 +63,7 @@ export { AgentReview, AGENT_REVIEW_MODES, AGENT_REVIEW_STATUSES, AGENT_REVIEW_TE
63
63
  export { ATTACHABLE_IDENTITY_PROVIDERS, UserIdentity, USER_IDENTITY_ORIGINS, } from "./user-identity.js";
64
64
  export type { AttachableIdentityProvider, UserIdentityOrigin } from "./user-identity.js";
65
65
  export { AppFeedback, AppFeedbackFile, APP_FEEDBACK_ENTITIES, APP_FEEDBACK_FILE_MAX_BYTES, } from "./app-feedback.js";
66
- export { ChatDelivery, ChatHistoryImportInput, ChatHistoryImportResult, ChatHistoryMessage, ChatPostInput, ChatSendInput, ChatTemplate, ChatPostResult, } from "./chat.js";
66
+ export { ChatDelivery, ChatHistoryImportInput, ChatHistoryImportResult, ChatHistoryMessage, ChatPostInput, ChatSendInput, ChatTemplate, ChatTemplateMedia, ChatPostResult, } from "./chat.js";
67
67
  export { CHAT_CHANNEL_KINDS, CHAT_CHANNEL_NAME, CHAT_KINDS, WORKSPACE_CHANNEL_KIND, channelIdentityProvider, } from "./chat-channel.js";
68
68
  export type { ChatChannelKind, ChatKind } from "./chat-channel.js";
69
69
  export type { InboxOptions, ReviewReviseInput, ReviewReviseResult, ReviewSendInput, ReviewSendResult, } from "./chat.js";
package/dist/index.js CHANGED
@@ -37,7 +37,7 @@ export { AgentChat } from "./agent-chat.js";
37
37
  export { AgentReview, AGENT_REVIEW_MODES, AGENT_REVIEW_STATUSES, AGENT_REVIEW_TEXT_LIMIT, } from "./agent-review.js";
38
38
  export { ATTACHABLE_IDENTITY_PROVIDERS, UserIdentity, USER_IDENTITY_ORIGINS, } from "./user-identity.js";
39
39
  export { AppFeedback, AppFeedbackFile, APP_FEEDBACK_ENTITIES, APP_FEEDBACK_FILE_MAX_BYTES, } from "./app-feedback.js";
40
- export { ChatDelivery, ChatHistoryImportInput, ChatHistoryImportResult, ChatHistoryMessage, ChatPostInput, ChatSendInput, ChatTemplate, ChatPostResult, } from "./chat.js";
40
+ export { ChatDelivery, ChatHistoryImportInput, ChatHistoryImportResult, ChatHistoryMessage, ChatPostInput, ChatSendInput, ChatTemplate, ChatTemplateMedia, ChatPostResult, } from "./chat.js";
41
41
  export { CHAT_CHANNEL_KINDS, CHAT_CHANNEL_NAME, CHAT_KINDS, WORKSPACE_CHANNEL_KIND, channelIdentityProvider, } from "./chat-channel.js";
42
42
  // The query language of `find` and of the service's list, query and traversal routes.
43
43
  export { DEFAULT_QUERY_LIMIT, entityQueryResultSchema, entityQuerySchema, entityQuerySchemas, entityRecordSchema, FILTER_OPERATORS, LIST_FILTER_OPERATORS, MANY_QUANTIFIERS, MAX_IN_VALUES, MAX_QUERY_LIMIT, OrderBy, Query, queryFields, queryJsonSchema, queryLinks, QueryResult, queryResultJsonSchema, queryResultSchema, SortDirection, WHERE_COMBINATORS, } from "./query.js";
@@ -1661,10 +1661,10 @@ export declare const OntologyManifest: Schema.declareConstructor<{
1661
1661
  readonly prefix?: string | undefined;
1662
1662
  } | undefined;
1663
1663
  readonly timestamp?: {
1664
+ readonly header?: string | undefined;
1664
1665
  readonly unit?: string | undefined;
1665
1666
  readonly entry?: string | undefined;
1666
1667
  readonly tolerance?: number | undefined;
1667
- readonly header?: string | undefined;
1668
1668
  } | undefined;
1669
1669
  readonly input?: string | undefined;
1670
1670
  readonly generated?: true | undefined;
@@ -2014,10 +2014,10 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2014
2014
  readonly prefix?: string | undefined;
2015
2015
  } | undefined;
2016
2016
  readonly timestamp?: {
2017
+ readonly header?: string | undefined;
2017
2018
  readonly unit?: string | undefined;
2018
2019
  readonly entry?: string | undefined;
2019
2020
  readonly tolerance?: number | undefined;
2020
- readonly header?: string | undefined;
2021
2021
  } | undefined;
2022
2022
  readonly input?: string | undefined;
2023
2023
  readonly generated?: true | undefined;
@@ -2369,10 +2369,10 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2369
2369
  readonly prefix?: string | undefined;
2370
2370
  } | undefined;
2371
2371
  readonly timestamp?: {
2372
+ readonly header?: string | undefined;
2372
2373
  readonly unit?: string | undefined;
2373
2374
  readonly entry?: string | undefined;
2374
2375
  readonly tolerance?: number | undefined;
2375
- readonly header?: string | undefined;
2376
2376
  } | undefined;
2377
2377
  readonly input?: string | undefined;
2378
2378
  readonly generated?: true | undefined;
@@ -2722,10 +2722,10 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2722
2722
  readonly prefix?: string | undefined;
2723
2723
  } | undefined;
2724
2724
  readonly timestamp?: {
2725
+ readonly header?: string | undefined;
2725
2726
  readonly unit?: string | undefined;
2726
2727
  readonly entry?: string | undefined;
2727
2728
  readonly tolerance?: number | undefined;
2728
- readonly header?: string | undefined;
2729
2729
  } | undefined;
2730
2730
  readonly input?: string | undefined;
2731
2731
  readonly generated?: true | undefined;
@@ -4030,10 +4030,10 @@ export declare const OntologyManifest: Schema.declareConstructor<{
4030
4030
  readonly prefix?: string | undefined;
4031
4031
  } | undefined;
4032
4032
  readonly timestamp?: {
4033
+ readonly header?: string | undefined;
4033
4034
  readonly unit?: string | undefined;
4034
4035
  readonly entry?: string | undefined;
4035
4036
  readonly tolerance?: number | undefined;
4036
- readonly header?: string | undefined;
4037
4037
  } | undefined;
4038
4038
  readonly input?: string | undefined;
4039
4039
  readonly generated?: true | undefined;
@@ -4383,10 +4383,10 @@ export declare const OntologyManifest: Schema.declareConstructor<{
4383
4383
  readonly prefix?: string | undefined;
4384
4384
  } | undefined;
4385
4385
  readonly timestamp?: {
4386
+ readonly header?: string | undefined;
4386
4387
  readonly unit?: string | undefined;
4387
4388
  readonly entry?: string | undefined;
4388
4389
  readonly tolerance?: number | undefined;
4389
- readonly header?: string | undefined;
4390
4390
  } | undefined;
4391
4391
  readonly input?: string | undefined;
4392
4392
  readonly generated?: true | undefined;
@@ -4742,10 +4742,10 @@ export declare const decodeManifestDocument: (value: unknown) => Effect.Effect<{
4742
4742
  readonly prefix?: string | undefined;
4743
4743
  } | undefined;
4744
4744
  readonly timestamp?: {
4745
+ readonly header?: string | undefined;
4745
4746
  readonly unit?: string | undefined;
4746
4747
  readonly entry?: string | undefined;
4747
4748
  readonly tolerance?: number | undefined;
4748
- readonly header?: string | undefined;
4749
4749
  } | undefined;
4750
4750
  readonly input?: string | undefined;
4751
4751
  readonly generated?: true | undefined;
@@ -5095,10 +5095,10 @@ export declare const decodeManifestDocument: (value: unknown) => Effect.Effect<{
5095
5095
  readonly prefix?: string | undefined;
5096
5096
  } | undefined;
5097
5097
  readonly timestamp?: {
5098
+ readonly header?: string | undefined;
5098
5099
  readonly unit?: string | undefined;
5099
5100
  readonly entry?: string | undefined;
5100
5101
  readonly tolerance?: number | undefined;
5101
- readonly header?: string | undefined;
5102
5102
  } | undefined;
5103
5103
  readonly input?: string | undefined;
5104
5104
  readonly generated?: true | undefined;
@@ -460,10 +460,10 @@ export declare const MigrationPlan: Schema.Struct<{
460
460
  readonly prefix?: string | undefined;
461
461
  } | undefined;
462
462
  readonly timestamp?: {
463
+ readonly header?: string | undefined;
463
464
  readonly unit?: string | undefined;
464
465
  readonly entry?: string | undefined;
465
466
  readonly tolerance?: number | undefined;
466
- readonly header?: string | undefined;
467
467
  } | undefined;
468
468
  readonly input?: string | undefined;
469
469
  readonly generated?: true | undefined;
@@ -813,10 +813,10 @@ export declare const MigrationPlan: Schema.Struct<{
813
813
  readonly prefix?: string | undefined;
814
814
  } | undefined;
815
815
  readonly timestamp?: {
816
+ readonly header?: string | undefined;
816
817
  readonly unit?: string | undefined;
817
818
  readonly entry?: string | undefined;
818
819
  readonly tolerance?: number | undefined;
819
- readonly header?: string | undefined;
820
820
  } | undefined;
821
821
  readonly input?: string | undefined;
822
822
  readonly generated?: true | undefined;
@@ -1168,10 +1168,10 @@ export declare const MigrationPlan: Schema.Struct<{
1168
1168
  readonly prefix?: string | undefined;
1169
1169
  } | undefined;
1170
1170
  readonly timestamp?: {
1171
+ readonly header?: string | undefined;
1171
1172
  readonly unit?: string | undefined;
1172
1173
  readonly entry?: string | undefined;
1173
1174
  readonly tolerance?: number | undefined;
1174
- readonly header?: string | undefined;
1175
1175
  } | undefined;
1176
1176
  readonly input?: string | undefined;
1177
1177
  readonly generated?: true | undefined;
@@ -1521,10 +1521,10 @@ export declare const MigrationPlan: Schema.Struct<{
1521
1521
  readonly prefix?: string | undefined;
1522
1522
  } | undefined;
1523
1523
  readonly timestamp?: {
1524
+ readonly header?: string | undefined;
1524
1525
  readonly unit?: string | undefined;
1525
1526
  readonly entry?: string | undefined;
1526
1527
  readonly tolerance?: number | undefined;
1527
- readonly header?: string | undefined;
1528
1528
  } | undefined;
1529
1529
  readonly input?: string | undefined;
1530
1530
  readonly generated?: true | undefined;
@@ -2583,10 +2583,10 @@ export declare const MigrationPlan: Schema.Struct<{
2583
2583
  readonly prefix?: string | undefined;
2584
2584
  } | undefined;
2585
2585
  readonly timestamp?: {
2586
+ readonly header?: string | undefined;
2586
2587
  readonly unit?: string | undefined;
2587
2588
  readonly entry?: string | undefined;
2588
2589
  readonly tolerance?: number | undefined;
2589
- readonly header?: string | undefined;
2590
2590
  } | undefined;
2591
2591
  readonly input?: string | undefined;
2592
2592
  readonly generated?: true | undefined;
@@ -2936,10 +2936,10 @@ export declare const MigrationPlan: Schema.Struct<{
2936
2936
  readonly prefix?: string | undefined;
2937
2937
  } | undefined;
2938
2938
  readonly timestamp?: {
2939
+ readonly header?: string | undefined;
2939
2940
  readonly unit?: string | undefined;
2940
2941
  readonly entry?: string | undefined;
2941
2942
  readonly tolerance?: number | undefined;
2942
- readonly header?: string | undefined;
2943
2943
  } | undefined;
2944
2944
  readonly input?: string | undefined;
2945
2945
  readonly generated?: true | undefined;
@@ -184,7 +184,28 @@ chats) {
184
184
  name: template.name,
185
185
  language: template.language,
186
186
  parameters: template.parameters ?? {},
187
+ ...(template.header === undefined ? {} : { header: template.header }),
188
+ ...(template.buttons === undefined ? {} : { buttons: template.buttons }),
187
189
  };
190
+ const blobs = context.backend.blobs;
191
+ // A header's stored file, read as the caller may read it, by a link WhatsApp fetches.
192
+ const file = (reference) => blobs === undefined
193
+ ? Effect.fail(new ActionRejected({ message: "File storage is unavailable." }))
194
+ : blobs
195
+ .downloadFile(reference.entity, reference.id, reference.property ?? "content", {}, context.principal)
196
+ .pipe(Effect.mapError((cause) => new ActionRejected({
197
+ message: "The header's file could not be read: it does not exist, or you may " +
198
+ "not read it.",
199
+ cause,
200
+ })), Effect.flatMap(({ file: stored, download }) => download.method !== "GET" || Object.keys(download.headers).length > 0
201
+ ? Effect.fail(new ActionRejected({
202
+ message: "The file's download link is not one WhatsApp can fetch.",
203
+ }))
204
+ : Effect.succeed({
205
+ url: download.url,
206
+ filename: stored.filename,
207
+ contentType: stored.content_type.toLowerCase(),
208
+ })));
188
209
  return {
189
210
  target,
190
211
  requester,
@@ -205,13 +226,17 @@ chats) {
205
226
  }),
206
227
  connection,
207
228
  template: request,
229
+ file,
208
230
  }).pipe(Effect.tapError((error) => error.cause === undefined ? Effect.void : report("template", error.cause)));
209
- if (!resolved.text.trim() || resolved.text.length > provider.limit) {
231
+ // WhatsApp bounds an approved template's parts itself; the text kept for the history,
232
+ // its buttons' links included, is no message the provider's length limit applies to.
233
+ if (!resolved.text.trim()) {
210
234
  return yield* invalid();
211
235
  }
212
236
  return {
213
237
  preview: { ...destination, text: resolved.text, finalText: resolved.text },
214
238
  payload: resolved.payload,
239
+ summary: resolved.summary,
215
240
  };
216
241
  }),
217
242
  };
@@ -258,6 +283,7 @@ chats) {
258
283
  compose: Effect.succeed({
259
284
  preview,
260
285
  payload: undefined,
286
+ summary: undefined,
261
287
  }),
262
288
  };
263
289
  });
@@ -486,7 +512,7 @@ chats) {
486
512
  return yield* replayed(found);
487
513
  }
488
514
  }
489
- const { preview, payload } = yield* compose;
515
+ const { preview, payload, summary } = yield* compose;
490
516
  // A member who answers in the inbox writes as themselves, not as the agent.
491
517
  const staff = inbox !== undefined && context.caller.kind === "member" && !asAgent;
492
518
  const place = inbox ?? (yield* personalChat(target));
@@ -514,7 +540,7 @@ chats) {
514
540
  reason: null,
515
541
  toolCallId: null,
516
542
  toolName: null,
517
- argsSummary: JSON.stringify(payload ?? provider.payload(preview.finalText)),
543
+ argsSummary: JSON.stringify(summary ?? payload ?? provider.payload(preview.finalText)),
518
544
  status: "requested",
519
545
  attachments: [],
520
546
  requestedBy: requester,
@@ -573,7 +599,8 @@ chats) {
573
599
  eventId: `chat-delivery:${operationId}:receipt`,
574
600
  status: outcome.status,
575
601
  reason: outcome.status === "failed" ? (outcome.refusal ?? null) : null,
576
- argsSummary: JSON.stringify(outcome.payload),
602
+ // A stored file is kept by its reference, never by the link WhatsApp fetched it by.
603
+ argsSummary: JSON.stringify(summary ?? outcome.payload),
577
604
  messageId: outcome.messageId,
578
605
  url: outcome.url,
579
606
  },
@@ -23,5 +23,18 @@ export declare function deliveryFingerprint(preview: Pick<ChatPreview, "chatId"
23
23
  readonly name: string;
24
24
  readonly language: string;
25
25
  readonly parameters: Readonly<Record<string, string>>;
26
+ readonly header?: {
27
+ readonly parameters?: Readonly<Record<string, string>>;
28
+ readonly media?: {
29
+ readonly url?: string;
30
+ readonly file?: {
31
+ readonly entity: string;
32
+ readonly id: string;
33
+ readonly property?: string;
34
+ };
35
+ readonly filename?: string;
36
+ };
37
+ };
38
+ readonly buttons?: Readonly<Record<string, string>>;
26
39
  }): string;
27
40
  export {};
@@ -21,6 +21,8 @@ export const deliveryKeyDigest = (idempotencyKey) => digest(JSON.stringify(idemp
21
21
  * WhatsApp when it is sent: a replay finds its receipt however the template has changed since.
22
22
  */
23
23
  export function deliveryFingerprint(preview, requester, template) {
24
+ const sorted = (values) => Object.entries(values).sort(([one], [other]) => (one < other ? -1 : one > other ? 1 : 0));
25
+ const media = template?.header?.media;
24
26
  return digest(JSON.stringify([
25
27
  preview.chatId,
26
28
  preview.provider,
@@ -31,7 +33,27 @@ export function deliveryFingerprint(preview, requester, template) {
31
33
  {
32
34
  template: template.name,
33
35
  language: template.language,
34
- parameters: Object.entries(template.parameters).sort(([one], [other]) => one < other ? -1 : one > other ? 1 : 0),
36
+ parameters: sorted(template.parameters),
37
+ // Bound only when given, so a body-only template's keys keep their binding.
38
+ ...(template.header === undefined
39
+ ? {}
40
+ : {
41
+ header: {
42
+ parameters: template.header.parameters === undefined
43
+ ? null
44
+ : sorted(template.header.parameters),
45
+ media: media === undefined
46
+ ? null
47
+ : {
48
+ url: media.url ?? null,
49
+ file: media.file === undefined
50
+ ? null
51
+ : [media.file.entity, media.file.id, media.file.property ?? null],
52
+ filename: media.filename ?? null,
53
+ },
54
+ },
55
+ }),
56
+ ...(template.buttons === undefined ? {} : { buttons: sorted(template.buttons) }),
35
57
  },
36
58
  ]),
37
59
  preview.replyTo,
@@ -3,7 +3,7 @@ import type { TelegramPreviewContext } from "../../../telegram.js";
3
3
  import { ConnectionError, type ConnectionReply, type ConnectionTransport } from "../../../connection.js";
4
4
  import type { ActionRejected } from "../../../errors.js";
5
5
  import type { Destination } from "../resolve.js";
6
- import type { ResolvedTemplate, TemplateRequest } from "./whatsapp-template.js";
6
+ import type { ResolvedTemplate, StoredFileLink, StoredFileReference, TemplateRequest } from "./whatsapp-template.js";
7
7
  /** One delivery attempt's result. A `failed` attempt definitely sent nothing; `uncertain` may have. */
8
8
  export interface ProviderOutcome {
9
9
  /** The text and its format as the provider received them, for the delivery's history. */
@@ -94,6 +94,8 @@ export interface ChatProvider {
94
94
  readonly transport: ConnectionTransport["Service"];
95
95
  readonly connection: string;
96
96
  readonly template: TemplateRequest;
97
+ /** A stored file a media header names, as a link the provider fetches it by. */
98
+ readonly file?: (file: StoredFileReference) => Effect.Effect<StoredFileLink, ActionRejected>;
97
99
  }) => Effect.Effect<ResolvedTemplate, ActionRejected>;
98
100
  }
99
101
  /**
@@ -1,6 +1,19 @@
1
1
  import { Effect } from "effect";
2
2
  import type { ConnectionTransport } from "../../../connection.js";
3
3
  import { ActionRejected } from "../../../errors.js";
4
+ /** A file stored in the ontology: a record and its file property. */
5
+ export interface StoredFileReference {
6
+ readonly entity: string;
7
+ readonly id: string;
8
+ readonly property?: string;
9
+ }
10
+ /** A stored file as a link the provider fetches it by, with what the storage knows of it. */
11
+ export interface StoredFileLink {
12
+ readonly url: string;
13
+ readonly filename: string;
14
+ /** Lower case. */
15
+ readonly contentType: string;
16
+ }
4
17
  /** A template message to send: an approved template by name and language, with its values. */
5
18
  export interface TemplateRequest {
6
19
  readonly name: string;
@@ -10,21 +23,41 @@ export interface TemplateRequest {
10
23
  * variables, the variables' names for one with named ones.
11
24
  */
12
25
  readonly parameters: Readonly<Record<string, string>>;
26
+ /** A text header's variables' values, or a media header's file. */
27
+ readonly header?: {
28
+ readonly parameters?: Readonly<Record<string, string>>;
29
+ readonly media?: {
30
+ readonly url?: string;
31
+ readonly file?: StoredFileReference;
32
+ readonly filename?: string;
33
+ };
34
+ };
35
+ /** The buttons' values by position, `"0"` for the first. */
36
+ readonly buttons?: Readonly<Record<string, string>>;
13
37
  }
14
38
  /** The template as WhatsApp sends it and as the person reads it, for the delivery's history. */
15
39
  export interface ResolvedTemplate {
16
40
  readonly text: string;
17
41
  readonly payload: Readonly<Record<string, unknown>>;
42
+ /**
43
+ * The payload as the delivery's history keeps it: a stored file by its reference, never by the
44
+ * short-lived link WhatsApp fetches it by.
45
+ */
46
+ readonly summary: Readonly<Record<string, unknown>>;
18
47
  }
19
48
  /**
20
49
  * Reads the approved template from the number's WhatsApp Business account, `GET
21
50
  * /account/message_templates` on the connection's `graph` API, checks the values against its
22
- * body's variables and renders it. Everything that can be checked is checked before anything is
23
- * sent: a template that is unknown, not approved in the language, takes a header or a button
24
- * value, or has values missing or extra is refused, and nothing is reserved.
51
+ * header's, body's and buttons' variables and renders it. Everything that can be checked is
52
+ * checked before anything is sent: a template that is unknown or not approved in the language, a
53
+ * value missing or extra, a header file missing, given twice or of a type the header does not
54
+ * take, and a value for a button that takes none are refused, and nothing is reserved. WhatsApp
55
+ * fetches a header's file after it accepts the message, and reports a file it could not fetch only
56
+ * in the message's delivery status.
25
57
  */
26
58
  export declare function whatsappTemplate(input: {
27
59
  readonly transport: ConnectionTransport["Service"];
28
60
  readonly connection: string;
29
61
  readonly template: TemplateRequest;
62
+ readonly file?: (file: StoredFileReference) => Effect.Effect<StoredFileLink, ActionRejected>;
30
63
  }): Effect.Effect<ResolvedTemplate, ActionRejected>;
@@ -5,10 +5,20 @@ import { record } from "./provider.js";
5
5
  const VARIABLE = /\{\{\s*([A-Za-z0-9_]+)\s*\}\}/gu;
6
6
  /** The most characters one variable's value may have. */
7
7
  const VALUE_LIMIT = 1024;
8
+ /** The most characters a copy-code button's code may have, as WhatsApp takes it. */
9
+ const CODE_LIMIT = 15;
10
+ /** The files each media header takes, by content type, where the storage knows the type. */
11
+ const MEDIA_TYPES = {
12
+ IMAGE: new Set(["image/jpeg", "image/png"]),
13
+ VIDEO: new Set(["video/mp4", "video/3gpp"]),
14
+ DOCUMENT: undefined,
15
+ };
8
16
  const rejected = (message) => new ActionRejected({ message });
9
17
  function variables(text) {
10
18
  return [...text.matchAll(VARIABLE)].map((match) => match[1]);
11
19
  }
20
+ /** The template's variables in the order WhatsApp takes their values. */
21
+ const ordered = (wanted, named) => named ? wanted : [...wanted].sort((first, second) => Number(first) - Number(second));
12
22
  /** Why the Graph API refused a request, as it explains it, for the operators' diagnostics. */
13
23
  function graphError(status, body) {
14
24
  let error = {};
@@ -25,12 +35,49 @@ function graphError(status, body) {
25
35
  (typeof error.message === "string" ? `: ${error.message}` : "") +
26
36
  (detail.length === 0 ? "" : ` (${detail.join(", ")})`));
27
37
  }
38
+ /** WhatsApp refuses a value with a new line, a tab or more than four spaces in a row. */
39
+ const invalidValue = (value) => value.trim() === "" ||
40
+ value.length > VALUE_LIMIT ||
41
+ /[\n\t]/u.test(value) ||
42
+ / {5,}/u.test(value);
43
+ /** The values a part of the template takes: exactly its variables, each one WhatsApp takes. */
44
+ function checkValues(template, part, wanted, values) {
45
+ const given = Object.keys(values);
46
+ const missing = wanted.filter((key) => !Object.hasOwn(values, key));
47
+ const extra = given.filter((key) => !wanted.includes(key));
48
+ if (missing.length > 0 || extra.length > 0) {
49
+ return rejected(`The template ${template}'s ${part} takes the values ${JSON.stringify(wanted)}` +
50
+ (missing.length > 0 ? `; missing ${JSON.stringify(missing)}` : "") +
51
+ (extra.length > 0 ? `; not in it ${JSON.stringify(extra)}` : "") +
52
+ ".");
53
+ }
54
+ const invalid = given.find((key) => invalidValue(values[key]));
55
+ return invalid === undefined
56
+ ? undefined
57
+ : rejected(`The ${part} value of ${invalid} is empty, longer than ${VALUE_LIMIT} characters, or has ` +
58
+ "a new line, a tab or more than four spaces in a row, which WhatsApp refuses.");
59
+ }
60
+ /** A variable's value as WhatsApp takes it, by name for a template with named variables. */
61
+ const textParameter = (named, key, text) => named ? { type: "text", parameter_name: key, text } : { type: "text", text };
62
+ /** An https link WhatsApp can fetch as it is: no credentials in it. */
63
+ function fetchable(url) {
64
+ try {
65
+ const parsed = new URL(url);
66
+ return parsed.protocol === "https:" && parsed.username === "" && parsed.password === "";
67
+ }
68
+ catch {
69
+ return false;
70
+ }
71
+ }
28
72
  /**
29
73
  * Reads the approved template from the number's WhatsApp Business account, `GET
30
74
  * /account/message_templates` on the connection's `graph` API, checks the values against its
31
- * body's variables and renders it. Everything that can be checked is checked before anything is
32
- * sent: a template that is unknown, not approved in the language, takes a header or a button
33
- * value, or has values missing or extra is refused, and nothing is reserved.
75
+ * header's, body's and buttons' variables and renders it. Everything that can be checked is
76
+ * checked before anything is sent: a template that is unknown or not approved in the language, a
77
+ * value missing or extra, a header file missing, given twice or of a type the header does not
78
+ * take, and a value for a button that takes none are refused, and nothing is reserved. WhatsApp
79
+ * fetches a header's file after it accepts the message, and reports a file it could not fetch only
80
+ * in the message's delivery status.
34
81
  */
35
82
  export function whatsappTemplate(input) {
36
83
  return Effect.gen(function* () {
@@ -83,71 +130,175 @@ export function whatsappTemplate(input) {
83
130
  const header = part("HEADER");
84
131
  const bodyPart = part("BODY");
85
132
  const footer = part("FOOTER");
86
- const buttons = part("BUTTONS");
87
- if (header !== undefined &&
88
- (String(header.format).toUpperCase() !== "TEXT" ||
89
- variables(String(header.text ?? "")).length > 0)) {
90
- return yield* rejected(`The template ${name} takes a header value or file, which send does not take yet.`);
133
+ const listed = part("BUTTONS")?.buttons;
134
+ const buttons = (Array.isArray(listed) ? listed : []).map(record);
135
+ const named = String(found.parameter_format ?? "").toUpperCase() === "NAMED";
136
+ // What WhatsApp is sent, and what the delivery's history keeps of it.
137
+ const sent = [];
138
+ const kept = [];
139
+ let headerText;
140
+ // The header: text, with or without variables, or a file of the type it declares.
141
+ const format = header === undefined ? undefined : String(header.format ?? "TEXT").toUpperCase();
142
+ const given = input.template.header;
143
+ if (format === undefined || format === "TEXT") {
144
+ const text = format === undefined ? "" : String(header.text ?? "");
145
+ const wanted = [...new Set(variables(text))];
146
+ if (given?.media !== undefined || (wanted.length === 0 && given !== undefined)) {
147
+ return yield* rejected(`The template ${name}'s header takes no value.`);
148
+ }
149
+ const values = given?.parameters ?? {};
150
+ const refused = checkValues(name, "header", wanted, values);
151
+ if (refused !== undefined) {
152
+ return yield* refused;
153
+ }
154
+ if (wanted.length > 0) {
155
+ const component = {
156
+ type: "header",
157
+ parameters: ordered(wanted, named).map((key) => textParameter(named, key, values[key])),
158
+ };
159
+ sent.push(component);
160
+ kept.push(component);
161
+ }
162
+ headerText =
163
+ text === "" ? undefined : text.replace(VARIABLE, (_, key) => values[key] ?? "");
91
164
  }
92
- if (buttons !== undefined &&
93
- (Array.isArray(buttons.buttons) ? buttons.buttons : [])
94
- .map(record)
95
- .some((button) => variables(String(button.url ?? "")).length > 0 ||
96
- String(button.type).toUpperCase() === "COPY_CODE")) {
97
- return yield* rejected(`The template ${name} takes a button value, which send does not take yet.`);
165
+ else if (Object.hasOwn(MEDIA_TYPES, format)) {
166
+ const media = given?.media;
167
+ if (given?.parameters !== undefined || media === undefined) {
168
+ return yield* rejected(`The template ${name}'s header is a ${format.toLowerCase()}: give its file in ` +
169
+ "header.media, by url or by file.");
170
+ }
171
+ if ((media.url === undefined) === (media.file === undefined)) {
172
+ return yield* rejected("Give a header's file by url or by file, not both.");
173
+ }
174
+ if (media.filename !== undefined && format !== "DOCUMENT") {
175
+ return yield* rejected("Only a document header takes a filename.");
176
+ }
177
+ const kind = format.toLowerCase();
178
+ let link;
179
+ let filename = media.filename;
180
+ if (media.url !== undefined) {
181
+ if (!fetchable(media.url)) {
182
+ return yield* rejected("A header's url is an https link WhatsApp can fetch as it is.");
183
+ }
184
+ link = media.url;
185
+ }
186
+ else {
187
+ if (input.file === undefined) {
188
+ return yield* rejected("Stored files cannot be sent here.");
189
+ }
190
+ const stored = yield* input.file(media.file);
191
+ const types = MEDIA_TYPES[format];
192
+ if (types !== undefined && !types.has(stored.contentType)) {
193
+ return yield* rejected(`The file is ${stored.contentType}, which a ${kind} header does not take.`);
194
+ }
195
+ if (!fetchable(stored.url)) {
196
+ return yield* rejected("The file's download link is not one WhatsApp can fetch.");
197
+ }
198
+ link = stored.url;
199
+ filename ??= format === "DOCUMENT" ? stored.filename : undefined;
200
+ }
201
+ const source = (reference) => ({
202
+ type: "header",
203
+ parameters: [
204
+ {
205
+ type: kind,
206
+ [kind]: { ...reference, ...(filename === undefined ? {} : { filename }) },
207
+ },
208
+ ],
209
+ });
210
+ sent.push(source({ link }));
211
+ kept.push(media.file === undefined ? source({ link }) : source({ file: media.file }));
212
+ }
213
+ else {
214
+ return yield* rejected(`The template ${name} takes a ${format.toLowerCase()} header, which send does not take.`);
98
215
  }
216
+ // The body: its variables' values, positional or named.
99
217
  const text = String(bodyPart?.text ?? "");
100
- const named = String(found.parameter_format ?? "").toUpperCase() === "NAMED";
101
218
  const wanted = [...new Set(variables(text))];
102
- const given = Object.keys(parameters);
103
- const missing = wanted.filter((key) => !Object.hasOwn(parameters, key));
104
- const extra = given.filter((key) => !wanted.includes(key));
105
- if (missing.length > 0 || extra.length > 0) {
106
- return yield* rejected(`The template ${name} takes the values ${JSON.stringify(wanted)}` +
107
- (missing.length > 0 ? `; missing ${JSON.stringify(missing)}` : "") +
108
- (extra.length > 0 ? `; not in it ${JSON.stringify(extra)}` : "") +
109
- ".");
219
+ const refused = checkValues(name, "body", wanted, parameters);
220
+ if (refused !== undefined) {
221
+ return yield* refused;
110
222
  }
111
- // WhatsApp refuses a value with a new line, a tab or more than four spaces in a row.
112
- const invalid = given.find((key) => {
113
- const value = parameters[key];
114
- return (value.trim() === "" ||
115
- value.length > VALUE_LIMIT ||
116
- /[\n\t]/u.test(value) ||
117
- / {5,}/u.test(value));
118
- });
119
- if (invalid !== undefined) {
120
- return yield* rejected(`The value of ${invalid} is empty, longer than ${VALUE_LIMIT} characters, or has a new ` +
121
- "line, a tab or more than four spaces in a row, which WhatsApp refuses.");
223
+ if (wanted.length > 0) {
224
+ const component = {
225
+ type: "body",
226
+ parameters: ordered(wanted, named).map((key) => textParameter(named, key, parameters[key])),
227
+ };
228
+ sent.push(component);
229
+ kept.push(component);
122
230
  }
123
- const ordered = named
124
- ? wanted
125
- : [...wanted].sort((first, second) => Number(first) - Number(second));
126
- const rendered = text.replace(VARIABLE, (_, key) => parameters[key] ?? "");
127
- const payload = {
231
+ // The buttons: a link's variable, a copy-code's code, a quick reply's payload; others none.
232
+ const values = input.template.buttons ?? {};
233
+ const unknown = Object.keys(values).find((key) => !/^(0|[1-9][0-9]?)$/u.test(key) || Number(key) >= buttons.length);
234
+ if (unknown !== undefined) {
235
+ return yield* rejected(`The template ${name} has ${buttons.length} buttons, by position from "0": it has no ` +
236
+ `button ${JSON.stringify(unknown)}.`);
237
+ }
238
+ const lines = [];
239
+ for (const [index, button] of buttons.entries()) {
240
+ const type = String(button.type).toUpperCase();
241
+ const key = String(index);
242
+ const value = Object.hasOwn(values, key) ? values[key] : undefined;
243
+ const label = typeof button.text === "string" ? button.text : "";
244
+ const linked = type === "URL" && variables(String(button.url ?? "")).length > 0;
245
+ const takes = linked || type === "COPY_CODE" ? "required" : type === "QUICK_REPLY" ? "optional" : "none";
246
+ if (takes === "none" && value !== undefined) {
247
+ return yield* rejected(`The template ${name}'s button ${key} takes no value.`);
248
+ }
249
+ if (takes === "required" && value === undefined) {
250
+ return yield* rejected(`The template ${name}'s button ${key} takes a value: give it.`);
251
+ }
252
+ if (value !== undefined &&
253
+ (invalidValue(value) || (type === "COPY_CODE" && value.length > CODE_LIMIT))) {
254
+ return yield* rejected(`The value of button ${key} is empty, too long, or has a new line, a tab or more than ` +
255
+ "four spaces in a row, which WhatsApp refuses.");
256
+ }
257
+ if (value !== undefined) {
258
+ const component = {
259
+ type: "button",
260
+ sub_type: type === "URL" ? "url" : type === "COPY_CODE" ? "copy_code" : "quick_reply",
261
+ index: key,
262
+ parameters: [
263
+ type === "URL"
264
+ ? textParameter(named, variables(String(button.url))[0], value)
265
+ : type === "COPY_CODE"
266
+ ? { type: "coupon_code", coupon_code: value }
267
+ : { type: "payload", payload: value },
268
+ ],
269
+ };
270
+ sent.push(component);
271
+ kept.push(component);
272
+ }
273
+ // As the person reads the button: a link where it leads, a code as it is, others by label.
274
+ const line = type === "URL" && typeof button.url === "string"
275
+ ? `[${label}](${button.url.replace(VARIABLE, () => value ?? "")})`
276
+ : type === "COPY_CODE"
277
+ ? (value ?? "")
278
+ : label;
279
+ if (line !== "") {
280
+ lines.push(line);
281
+ }
282
+ }
283
+ const message = (parts) => ({
128
284
  type: "template",
129
285
  template: {
130
286
  name,
131
287
  language: { code: language },
132
- ...(ordered.length === 0
133
- ? {}
134
- : {
135
- components: [
136
- {
137
- type: "body",
138
- parameters: ordered.map((key) => named
139
- ? { type: "text", parameter_name: key, text: parameters[key] }
140
- : { type: "text", text: parameters[key] }),
141
- },
142
- ],
143
- }),
288
+ ...(parts.length === 0 ? {} : { components: parts }),
144
289
  },
145
- };
290
+ });
146
291
  return {
147
- text: [header?.text, rendered, footer?.text]
292
+ text: [
293
+ headerText,
294
+ text.replace(VARIABLE, (_, key) => parameters[key] ?? ""),
295
+ typeof footer?.text === "string" ? footer.text : undefined,
296
+ lines.length === 0 ? undefined : lines.join("\n"),
297
+ ]
148
298
  .filter((value) => typeof value === "string" && value !== "")
149
299
  .join("\n\n"),
150
- payload,
300
+ payload: message(sent),
301
+ summary: message(kept),
151
302
  };
152
303
  });
153
304
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.137.1",
3
+ "version": "0.138.0",
4
4
  "description": "Define a SegmentStream workspace app's ontology: entities, relationships, roles and actions, written with Effect.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",