opscms-meta-plugin 0.0.0-stage → 0.4.2

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 (31) hide show
  1. package/CHANGELOG.md +189 -0
  2. package/LICENSE +21 -0
  3. package/README.md +338 -2
  4. package/dist/chunk-HCQSD757.mjs +142 -0
  5. package/dist/chunk-QEVRQKSQ.mjs +26 -0
  6. package/dist/components/MetaCatalogSync/index.d.mts +10 -0
  7. package/dist/components/MetaCatalogSync/index.d.ts +10 -0
  8. package/dist/components/MetaCatalogSync/index.js +195 -0
  9. package/dist/components/MetaCatalogSync/index.mjs +108 -0
  10. package/dist/components/MetaConnectPanel/index.d.mts +20 -0
  11. package/dist/components/MetaConnectPanel/index.d.ts +20 -0
  12. package/dist/components/MetaConnectPanel/index.js +723 -0
  13. package/dist/components/MetaConnectPanel/index.mjs +554 -0
  14. package/dist/components/MetaLoginButton/index.d.mts +5 -0
  15. package/dist/components/MetaLoginButton/index.d.ts +5 -0
  16. package/dist/components/MetaLoginButton/index.js +82 -0
  17. package/dist/components/MetaLoginButton/index.mjs +58 -0
  18. package/dist/components/MetaPixelSelect/index.d.mts +11 -0
  19. package/dist/components/MetaPixelSelect/index.d.ts +11 -0
  20. package/dist/components/MetaPixelSelect/index.js +202 -0
  21. package/dist/components/MetaPixelSelect/index.mjs +115 -0
  22. package/dist/components/ThreadsConnectPanel/index.d.mts +10 -0
  23. package/dist/components/ThreadsConnectPanel/index.d.ts +10 -0
  24. package/dist/components/ThreadsConnectPanel/index.js +163 -0
  25. package/dist/components/ThreadsConnectPanel/index.mjs +56 -0
  26. package/dist/index.d.mts +376 -0
  27. package/dist/index.d.ts +376 -0
  28. package/dist/index.js +3563 -0
  29. package/dist/index.mjs +3503 -0
  30. package/icon.svg +1 -0
  31. package/package.json +109 -4
@@ -0,0 +1,376 @@
1
+ import * as payload from 'payload';
2
+ import { Payload, PayloadRequest, Endpoint, CollectionConfig, Plugin } from 'payload';
3
+
4
+ /**
5
+ * What the plugin asks of the host CMS, beyond Payload itself.
6
+ *
7
+ * The host passes this to `metaPlugin({ host })`. The plugin never owns a workflow or a message template: both belong to the
8
+ * host's automation. When something happens on Meta's side (a template is approved, rejected or recategorised) the plugin
9
+ * tells the host with an event, and the host's workflows decide what to do about it. Without a host the plugin still connects
10
+ * sites to Meta and sends WhatsApp; it just has nobody to tell.
11
+ */
12
+ /** What happened when the host fired a system event. */
13
+ interface HostEventOutcome {
14
+ enqueued: number;
15
+ failed: number;
16
+ }
17
+ interface MetaHost {
18
+ /** Fire a named system event for a site, so the workflows listening for it run. */
19
+ emitSystemEvent(payload: Payload, eventName: string, event: {
20
+ siteSlug: string;
21
+ data: Record<string, unknown>;
22
+ }, req: PayloadRequest): Promise<HostEventOutcome>;
23
+ /**
24
+ * Make sure the site has a workflow in the host's automation that handles this event. The workflow, and the message the
25
+ * owner receives, are the host's: it decides how the event becomes an action. Does nothing when one already exists.
26
+ */
27
+ ensureEventHandler(payload: Payload, eventName: string, site: {
28
+ id: string | number;
29
+ organizationId: string | number;
30
+ }): Promise<void>;
31
+ /**
32
+ * Throttling for the sign-in endpoints, from the host's own limiter. Without it they are not throttled by the plugin (a
33
+ * sign-in needs a code Facebook has just issued, so there is little to guess).
34
+ */
35
+ rateLimit?: {
36
+ check(key: string, maxRequests: number, windowMs: number): Promise<{
37
+ allowed: boolean;
38
+ }>;
39
+ clientIp(req: PayloadRequest): string;
40
+ };
41
+ }
42
+
43
+ /**
44
+ * Cloud API send failures that are about the template a message names.
45
+ *
46
+ * Returns null when the failure is something else, so the caller keeps its own wording. A template that is still with Meta
47
+ * for review is retryable: the message stays queued and goes out once it is approved. A template that is missing, paused or
48
+ * rejected is reported the same way, because from the sender's side it is "not usable yet".
49
+ */
50
+ declare function explainTemplateSendError(body: string): {
51
+ retryable: boolean;
52
+ error: string;
53
+ } | null;
54
+
55
+ /**
56
+ * Encrypt a plain-text credential. Returns a string prefixed with "enc:".
57
+ * If encryption key is not configured, returns the value as-is.
58
+ */
59
+ declare function encryptCredential(plaintext: string): string;
60
+ /**
61
+ * Decrypt an encrypted credential. If the value doesn't have the "enc:" prefix,
62
+ * it's assumed to be plain text (backward compatible).
63
+ */
64
+ declare function decryptCredential(stored: string): string;
65
+
66
+ /** Resolved Meta API credentials for a single site, decrypted and ready to use. appId/appSecret are deployment-wide (META_APP_ID/META_APP_SECRET, see utils/metaCrypto.ts), not part of a site's credentials. */
67
+ interface MetaCredentials {
68
+ accessToken: string;
69
+ businessManagerId?: string;
70
+ pixelId?: string;
71
+ catalogId?: string;
72
+ whatsappPhoneNumberId?: string;
73
+ whatsappBusinessAccountId?: string;
74
+ }
75
+ interface MetaConfigDoc {
76
+ id: string | number;
77
+ label: string;
78
+ site: string | number | {
79
+ id: string | number;
80
+ };
81
+ isActive: boolean;
82
+ connectionStatus?: 'connected' | 'disconnected' | 'untested';
83
+ authMethod?: 'manual' | 'oauth';
84
+ accessToken?: string;
85
+ businessManagerId?: string;
86
+ oauthUserAccessToken?: string;
87
+ facebookPageId?: string;
88
+ facebookPageName?: string;
89
+ instagramBusinessAccountId?: string;
90
+ instagramUsername?: string;
91
+ pixelEnabled?: boolean;
92
+ pixelId?: string;
93
+ catalogEnabled?: boolean;
94
+ catalogId?: string;
95
+ catalogSourceCollection?: string;
96
+ catalogItemUrlTemplate?: string;
97
+ whatsappEnabled?: boolean;
98
+ whatsappPhoneNumberId?: string;
99
+ whatsappBusinessAccountId?: string;
100
+ threadsEnabled?: boolean;
101
+ threadsUserId?: string;
102
+ threadsUsername?: string;
103
+ threadsAccessToken?: string;
104
+ }
105
+ /** Structured logger signature used across the plugin. */
106
+ type LogFn = (level: 'info' | 'warn' | 'error', msg: string, meta?: Record<string, unknown>) => void;
107
+
108
+ /**
109
+ * Resolve a site's active Meta credentials from the meta-config collection.
110
+ * Mirrors opscms-erpnext-plugin's getCredentials() exactly: per-site lookup
111
+ * (never falls back to another site's config — that would leak data across
112
+ * tenants), decrypts the masking-safety-net way (re-decrypt if an "enc:"
113
+ * prefix leaked through afterRead), fails closed on any inconsistency.
114
+ */
115
+ declare function getMetaCredentials(payload: Parameters<Endpoint['handler']>[0]['payload'], siteSlug?: string | null, _req?: PayloadRequest): Promise<MetaCredentials | null>;
116
+
117
+ interface ConversionEventUserData {
118
+ /** SHA-256 hashed by the caller before this reaches here — never send raw PII to Meta. */
119
+ emailHash?: string;
120
+ phoneHash?: string;
121
+ clientIpAddress?: string;
122
+ clientUserAgent?: string;
123
+ }
124
+ interface ConversionEventInput {
125
+ /** Standard Meta event name — e.g. "Lead", "Purchase", "AddToCart", "CompleteRegistration". */
126
+ eventName: string;
127
+ /** Unix seconds. Defaults to now if omitted. */
128
+ eventTime?: number;
129
+ /** Dedup key — set the same value on a client Pixel event and this CAPI event to avoid double-counting. Optional: this plugin fires CAPI-only by design (no client fbq() calls), so most callers can omit it. */
130
+ eventId?: string;
131
+ eventSourceUrl?: string;
132
+ userData?: ConversionEventUserData;
133
+ customData?: Record<string, unknown>;
134
+ actionSource?: 'website' | 'system_generated' | 'other';
135
+ }
136
+ interface ConversionEventResult {
137
+ ok: boolean;
138
+ status?: number;
139
+ error?: string;
140
+ eventsReceived?: number;
141
+ }
142
+ /**
143
+ * Send a single event to Meta's Conversions API.
144
+ * https://graph.facebook.com/v21.0/{pixel_id}/events
145
+ *
146
+ * Requires creds.pixelId and creds.accessToken — callers should check both
147
+ * are present (via getMetaCredentials, which only returns pixelId when the
148
+ * site's meta-config has pixelEnabled: true) before calling this.
149
+ */
150
+ declare function sendConversionEvent(creds: MetaCredentials, input: ConversionEventInput, log?: LogFn): Promise<ConversionEventResult>;
151
+
152
+ declare function metaConversionEventHandler(ctx: any): Promise<any>;
153
+
154
+ /**
155
+ * The notification channel protocol of the host CMS.
156
+ *
157
+ * A host that sends notifications keeps a registry of services that deliver channels it does not send itself (WhatsApp, SMS).
158
+ * This is the shape of one entry, declared here so the plugin needs nothing from the host to register. The host's own
159
+ * declaration is the same shape (payload-cms: src/types/notificationChannels.ts).
160
+ */
161
+ type PluggableChannel = 'whatsapp' | 'sms';
162
+ interface ChannelSendOutcome {
163
+ success: boolean;
164
+ /** The channel was not set up for this site: a configuration state, not a delivery failure. */
165
+ skipped?: boolean;
166
+ /** A transient condition (5xx, timeout): the same message is worth sending again shortly. */
167
+ deferred?: boolean;
168
+ error?: string;
169
+ }
170
+ interface ChannelResolveInput {
171
+ payload: Payload;
172
+ siteSlug?: string;
173
+ /** The channel's own group of the host's notification settings that apply to the site, if any. */
174
+ settings?: Record<string, unknown>;
175
+ platformSettings: boolean;
176
+ }
177
+ /**
178
+ * A template Meta has already approved, named with the values for its numbered slots. Building this from the user's template
179
+ * and the workflow's data is the host automation's job; the plugin only sends it.
180
+ */
181
+ interface ApprovedTemplateReference {
182
+ name: string;
183
+ languageCode: string;
184
+ /** The values for the template's placeholders, by name when the template uses named placeholders. */
185
+ bodyParameters: Array<{
186
+ name?: string;
187
+ text: string;
188
+ }>;
189
+ }
190
+ interface ChannelSendInput<Config> {
191
+ payload: Payload;
192
+ config: Config;
193
+ to: string;
194
+ message: string;
195
+ /** Set when the message must go out as an approved template. Without it the message is sent as free text. */
196
+ template?: ApprovedTemplateReference | null;
197
+ templateKey?: string;
198
+ variables: Record<string, unknown>;
199
+ }
200
+ interface NotificationChannelProvider<Config = unknown> {
201
+ id: string;
202
+ channel: PluggableChannel;
203
+ /** Order among providers of the same channel when settings are read. Lower goes first. */
204
+ priority: number;
205
+ /** Order among providers when nothing is set in the settings and the environment is read. */
206
+ environmentPriority?: number;
207
+ isEnabled(settings?: Record<string, unknown>): boolean;
208
+ resolve(input: ChannelResolveInput): Promise<Config | null>;
209
+ resolveFromEnvironment?(): Config | null;
210
+ send(input: ChannelSendInput<Config>): Promise<ChannelSendOutcome>;
211
+ }
212
+ /** A WhatsApp Business number to send from, and the token that may use it. */
213
+ interface MetaCloudGateway {
214
+ phoneNumberId: string;
215
+ accessToken: string;
216
+ /** The site the number belongs to, when it comes from a site's connection. Its approved templates are looked up by it. */
217
+ siteId?: string | number;
218
+ }
219
+
220
+ declare const metaWhatsAppChannel: NotificationChannelProvider<MetaCloudGateway>;
221
+
222
+ /**
223
+ * The plugin's webhook: the address Meta calls to report what happens on its side.
224
+ *
225
+ * Register `https://<your CMS>/api/meta-webhook` as the callback of the platform's Meta app, for the WhatsApp business account
226
+ * topic, with the verify token set in `META_WEBHOOK_VERIFY_TOKEN`. Each site's business account is subscribed to the app when
227
+ * the site connects (see utils/wabaSubscription.ts), so its events arrive here.
228
+ *
229
+ * - GET answers Meta's handshake.
230
+ * - POST checks the signature (HMAC of the raw body under the app secret), reads the template changes, finds the sites that
231
+ * connected that business account, and tells the host about each one. The workflow that turns it into a notice to the site's
232
+ * owner is the host's.
233
+ *
234
+ * A delivery with a bad or missing signature is refused with 401 before its body is parsed. A good one is answered 200 once
235
+ * every event has been handed over; if the host fails, the answer is 500 so Meta sends it again.
236
+ */
237
+ declare function createMetaWebhookEndpoints(host?: MetaHost): Endpoint[];
238
+
239
+ declare function createMetaLoginEndpoints(host?: MetaHost): Endpoint[];
240
+
241
+ /**
242
+ * The link between a platform account and a Facebook account: Facebook's own id for the person.
243
+ *
244
+ * Only the sign-in code writes it (a person's own request cannot set it: that would let anyone claim another Facebook account), and
245
+ * only the account's owner or the platform owner can read it. One Facebook account can belong to one platform account (unique).
246
+ */
247
+ declare const facebookIdField: {
248
+ name: string;
249
+ type: "text";
250
+ unique: true;
251
+ index: true;
252
+ access: {
253
+ create: () => false;
254
+ update: () => false;
255
+ read: ({ req, doc }: payload.FieldAccessArgs<any, any>) => boolean;
256
+ };
257
+ admin: {
258
+ readOnly: true;
259
+ position: "sidebar";
260
+ description: string;
261
+ };
262
+ };
263
+ /** Adds the Facebook link to the collection people sign in to. Any other collection is returned as it was. */
264
+ declare function attachFacebookLogin(collection: CollectionConfig, usersSlug: string): CollectionConfig;
265
+
266
+ /**
267
+ * Signing in to the platform with a Facebook account (src/login, src/endpoints/metaLogin.ts).
268
+ */
269
+ /** What Facebook tells the platform about the person who just signed in. */
270
+ interface FacebookProfile {
271
+ id: string;
272
+ name?: string;
273
+ email?: string;
274
+ }
275
+ /** Why a Facebook sign-in did not become a platform sign-in. Each is a fixed code the login page turns into a sentence. */
276
+ type FacebookLoginFailure =
277
+ /** The person said no on Facebook's screen. */
278
+ 'denied'
279
+ /** The sign-in did not start here, or took too long (the safety check against forged sign-ins failed). */
280
+ | 'state'
281
+ /** Facebook did not give an email, and the account is not already linked. */
282
+ | 'no_email'
283
+ /** No platform account has that email. Accounts are made by invitation, never by signing in. */
284
+ | 'no_account'
285
+ /** The account is suspended. */
286
+ | 'suspended'
287
+ /** The platform owner (super-admin) signs in with email, password and, if switched on, a two-factor code. Never through Facebook. */
288
+ | 'not_allowed'
289
+ /** The account has two-factor sign-in switched on, which Facebook sign-in cannot satisfy: use the password and the code. */
290
+ | 'two_factor'
291
+ /** The platform account is already linked to a different Facebook account. */
292
+ | 'conflict'
293
+ /** Meta is not set up on this server. */
294
+ | 'not_configured'
295
+ /** Anything else: Facebook or the platform could not complete it. */
296
+ | 'failed';
297
+ type LoginResolution = {
298
+ ok: true;
299
+ user: Record<string, unknown>;
300
+ linked: boolean;
301
+ } | {
302
+ ok: false;
303
+ code: Extract<FacebookLoginFailure, 'no_email' | 'no_account' | 'suspended' | 'not_allowed' | 'two_factor' | 'conflict' | 'failed'>;
304
+ };
305
+
306
+ declare function resolveLoginUser(payload: Payload, usersSlug: string, profile: FacebookProfile): Promise<LoginResolution>;
307
+
308
+ /**
309
+ * Subscribing a customer's WhatsApp business account to the platform's Meta app.
310
+ *
311
+ * Meta only delivers a business account's events (template approvals, quality changes, account alerts) to an app that account
312
+ * has subscribed. The customer's own token, from their Facebook login, is what authorises the subscription; it is made when
313
+ * they choose their number and removed when they disconnect.
314
+ */
315
+ interface SubscriptionResult {
316
+ ok: boolean;
317
+ error?: string;
318
+ }
319
+ /** Subscribe the business account to the app that owns the token. Safe to repeat. */
320
+ declare function subscribeWabaToApp(token: string, wabaId: string): Promise<SubscriptionResult>;
321
+ /** Remove the subscription, so Meta stops sending that business account's events here. */
322
+ declare function unsubscribeWabaFromApp(token: string, wabaId: string): Promise<SubscriptionResult>;
323
+
324
+ /** Minimal interface for the CMS action registry — same shape opscms-erpnext-plugin uses. */
325
+ interface ActionRegistryRef {
326
+ register: (slug: string, handler: (ctx: any) => Promise<{
327
+ success: boolean;
328
+ data?: Record<string, unknown>;
329
+ error?: string;
330
+ }>) => void;
331
+ }
332
+ interface MetaPluginOptions {
333
+ /**
334
+ * CMS action registry — pass `actionRegistry` from `payload-cms/src/lib/actionRegistry`.
335
+ * When provided, the plugin registers `meta-conversion-event` so it can be
336
+ * invoked by the workflow engine's "Trigger Meta Conversion Event" step.
337
+ */
338
+ registry?: ActionRegistryRef;
339
+ /**
340
+ * The host CMS's workflow engine. With it, what Meta reports to the plugin's webhook (a template approved, rejected or
341
+ * recategorised) is handed to the host as an event for its workflows to act on. Without it the webhook still checks and
342
+ * accepts Meta's deliveries, but nobody is told.
343
+ */
344
+ host?: MetaHost;
345
+ }
346
+ /**
347
+ * Meta Network Plugin for Payload CMS
348
+ *
349
+ * Lets an admin/superadmin connect any site in the multi-tenant platform to
350
+ * Meta's network. Modular per-channel (Pixel/Conversions API, Commerce Catalog,
351
+ * WhatsApp Business Cloud API) and per-site — a site enables only what it needs.
352
+ *
353
+ * Provides:
354
+ * - `meta-config` collection — per-site connection + per-channel config,
355
+ * credentials encrypted at rest, Graph API connection-health check.
356
+ * - "Connect to Meta Business" OAuth flow (same UX as the official Meta for
357
+ * WordPress plugin): authorize, pick a Facebook Page you manage, its linked
358
+ * Instagram Business account is auto-detected, then select or create a
359
+ * Pixel — plus a separate Threads connect flow. Manual credential entry
360
+ * stays fully available side by side; OAuth just populates the same
361
+ * fields.
362
+ * - Server-side Conversions API dispatch (`sendConversionEvent`), wired into
363
+ * the CMS workflow engine as a `meta-conversion-event` action (requires
364
+ * `registry`) so any Workflow can fire a "Trigger Meta Conversion Event"
365
+ * step — order creation → Purchase, contact-form submit → Lead, etc.
366
+ * - `GET /api/meta-catalog/feed?site=<slug>` — Commerce Catalog CSV feed,
367
+ * generated from whichever collection the site's meta-config designates.
368
+ *
369
+ * Deliberately does not yet include the WhatsApp webhook verify-token
370
+ * handshake — that belongs on the host CMS's existing generic `webhooks`
371
+ * collection + `webhookReceiver.ts`, not duplicated here. See
372
+ * payload-cms/docs/future-features.md and this package's README.md.
373
+ */
374
+ declare function metaPlugin(options?: MetaPluginOptions): Plugin;
375
+
376
+ export { type ActionRegistryRef, type ConversionEventInput, type ConversionEventResult, type FacebookLoginFailure, type FacebookProfile, type HostEventOutcome, type MetaConfigDoc, type MetaCredentials, type MetaHost, type MetaPluginOptions, type NotificationChannelProvider, attachFacebookLogin, createMetaLoginEndpoints, createMetaWebhookEndpoints, decryptCredential, encryptCredential, explainTemplateSendError, facebookIdField, getMetaCredentials, metaConversionEventHandler, metaPlugin, metaWhatsAppChannel, resolveLoginUser, sendConversionEvent, subscribeWabaToApp, unsubscribeWabaFromApp };