opscms-meta-plugin 0.5.0 → 0.6.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,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0
4
+
5
+ ### Added
6
+
7
+ - **The host can give the plugin the platform's Meta app.** `metaPlugin({ app: () => ({ appId, appSecret, webhookVerifyToken }) })`: the plugin asks
8
+ for it when it needs it, so a host that keeps the app in its own settings needs nothing set on the server, and a change is used at once. What the host
9
+ gives wins; `META_APP_ID`, `META_APP_SECRET` and `META_WEBHOOK_VERIFY_TOKEN` stay as the fallback, so a host that passes nothing works as before.
10
+ (`META_ENCRYPTION_KEY` is not part of this: it is the key that protects what is stored, so it stays on the server.)
11
+
3
12
  ## 0.4.2
4
13
 
5
14
  ### Fixed
@@ -70,7 +70,7 @@ function useMetaAppInfo() {
70
70
  var MetaAppInfoBadge = ({ appInfo }) => {
71
71
  if (appInfo.loading) return null;
72
72
  if (!appInfo.configured) {
73
- return /* @__PURE__ */ jsx(ErrorState, { message: "Meta App not configured on this deployment \u2014 an admin needs to set META_APP_ID and META_APP_SECRET." });
73
+ return /* @__PURE__ */ jsx(ErrorState, { message: "Meta App not configured on this deployment \u2014 the platform owner needs to enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET)." });
74
74
  }
75
75
  return /* @__PURE__ */ jsxs("div", { style: { ...messageBoxStyle("info"), display: "flex", justifyContent: "space-between", alignItems: "center" }, children: [
76
76
  /* @__PURE__ */ jsx("span", { children: "Platform Meta App" }),
@@ -6,7 +6,7 @@ import {
6
6
  FieldWrapper,
7
7
  StyledSelect,
8
8
  SuccessState
9
- } from "../../chunk-HCQSD757.mjs";
9
+ } from "../../chunk-TSCTFPN2.mjs";
10
10
 
11
11
  // src/components/MetaCatalogSync/index.tsx
12
12
  import { useCallback, useState } from "react";
@@ -110,7 +110,7 @@ function useMetaAppInfo() {
110
110
  var MetaAppInfoBadge = ({ appInfo }) => {
111
111
  if (appInfo.loading) return null;
112
112
  if (!appInfo.configured) {
113
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErrorState, { message: "Meta App not configured on this deployment \u2014 an admin needs to set META_APP_ID and META_APP_SECRET." });
113
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErrorState, { message: "Meta App not configured on this deployment \u2014 the platform owner needs to enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET)." });
114
114
  }
115
115
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { ...messageBoxStyle("info"), display: "flex", justifyContent: "space-between", alignItems: "center" }, children: [
116
116
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: "Platform Meta App" }),
@@ -15,7 +15,7 @@ import {
15
15
  openMetaOAuthPopup,
16
16
  useMetaAppInfo,
17
17
  useOAuthRedirectMessage
18
- } from "../../chunk-HCQSD757.mjs";
18
+ } from "../../chunk-TSCTFPN2.mjs";
19
19
 
20
20
  // src/components/MetaConnectPanel/index.tsx
21
21
  import { useCallback as useCallback2, useEffect as useEffect2, useRef as useRef2, useState } from "react";
@@ -6,7 +6,7 @@ import {
6
6
  FieldWrapper,
7
7
  LoadingState,
8
8
  StyledSelect
9
- } from "../../chunk-HCQSD757.mjs";
9
+ } from "../../chunk-TSCTFPN2.mjs";
10
10
 
11
11
  // src/components/MetaPixelSelect/index.tsx
12
12
  import { useState } from "react";
@@ -89,7 +89,7 @@ function useMetaAppInfo() {
89
89
  var MetaAppInfoBadge = ({ appInfo }) => {
90
90
  if (appInfo.loading) return null;
91
91
  if (!appInfo.configured) {
92
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErrorState, { message: "Meta App not configured on this deployment \u2014 an admin needs to set META_APP_ID and META_APP_SECRET." });
92
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErrorState, { message: "Meta App not configured on this deployment \u2014 the platform owner needs to enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET)." });
93
93
  }
94
94
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { ...messageBoxStyle("info"), display: "flex", justifyContent: "space-between", alignItems: "center" }, children: [
95
95
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: "Platform Meta App" }),
@@ -9,7 +9,7 @@ import {
9
9
  SuccessState,
10
10
  useMetaAppInfo,
11
11
  useOAuthRedirectMessage
12
- } from "../../chunk-HCQSD757.mjs";
12
+ } from "../../chunk-TSCTFPN2.mjs";
13
13
 
14
14
  // src/components/ThreadsConnectPanel/index.tsx
15
15
  import { useCallback, useEffect, useState } from "react";
package/dist/index.d.mts CHANGED
@@ -40,6 +40,23 @@ interface MetaHost {
40
40
  };
41
41
  }
42
42
 
43
+ /**
44
+ * Encrypt a plain-text credential. Returns a string prefixed with "enc:".
45
+ * If encryption key is not configured, returns the value as-is.
46
+ */
47
+ declare function encryptCredential(plaintext: string): string;
48
+ /**
49
+ * Decrypt an encrypted credential. If the value doesn't have the "enc:" prefix,
50
+ * it's assumed to be plain text (backward compatible).
51
+ */
52
+ declare function decryptCredential(stored: string): string;
53
+ /** What a host CMS says the platform's Meta app is (typed into its own settings, not set on the server). Any part may be missing. */
54
+ interface MetaAppSettings {
55
+ appId?: string | null;
56
+ appSecret?: string | null;
57
+ webhookVerifyToken?: string | null;
58
+ }
59
+
43
60
  /**
44
61
  * Cloud API send failures that are about the template a message names.
45
62
  *
@@ -52,17 +69,6 @@ declare function explainTemplateSendError(body: string): {
52
69
  error: string;
53
70
  } | null;
54
71
 
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
72
  /** 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
73
  interface MetaCredentials {
68
74
  accessToken: string;
@@ -223,7 +229,7 @@ declare const metaWhatsAppChannel: NotificationChannelProvider<MetaCloudGateway>
223
229
  * The plugin's webhook: the address Meta calls to report what happens on its side.
224
230
  *
225
231
  * 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
232
+ * topic, with the verify token set in the host's Meta app settings (or `META_WEBHOOK_VERIFY_TOKEN`). Each site's business account is subscribed to the app when
227
233
  * the site connects (see utils/wabaSubscription.ts), so its events arrive here.
228
234
  *
229
235
  * - GET answers Meta's handshake.
@@ -342,6 +348,12 @@ interface MetaPluginOptions {
342
348
  * accepts Meta's deliveries, but nobody is told.
343
349
  */
344
350
  host?: MetaHost;
351
+ /**
352
+ * The platform's Meta app (App ID, secret, webhook verify token), as the host keeps it in its own settings. Called whenever the plugin needs it, so
353
+ * keep it quick (answer from memory). What it returns wins over the `META_APP_ID`, `META_APP_SECRET` and `META_WEBHOOK_VERIFY_TOKEN`
354
+ * environment variables, which remain the fallback; a host that gives nothing here keeps working from the environment as before.
355
+ */
356
+ app?: () => MetaAppSettings | null | undefined;
345
357
  }
346
358
  /**
347
359
  * Meta Network Plugin for Payload CMS
@@ -373,4 +385,4 @@ interface MetaPluginOptions {
373
385
  */
374
386
  declare function metaPlugin(options?: MetaPluginOptions): Plugin;
375
387
 
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 };
388
+ export { type ActionRegistryRef, type ConversionEventInput, type ConversionEventResult, type FacebookLoginFailure, type FacebookProfile, type HostEventOutcome, type MetaAppSettings, 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 };
package/dist/index.d.ts CHANGED
@@ -40,6 +40,23 @@ interface MetaHost {
40
40
  };
41
41
  }
42
42
 
43
+ /**
44
+ * Encrypt a plain-text credential. Returns a string prefixed with "enc:".
45
+ * If encryption key is not configured, returns the value as-is.
46
+ */
47
+ declare function encryptCredential(plaintext: string): string;
48
+ /**
49
+ * Decrypt an encrypted credential. If the value doesn't have the "enc:" prefix,
50
+ * it's assumed to be plain text (backward compatible).
51
+ */
52
+ declare function decryptCredential(stored: string): string;
53
+ /** What a host CMS says the platform's Meta app is (typed into its own settings, not set on the server). Any part may be missing. */
54
+ interface MetaAppSettings {
55
+ appId?: string | null;
56
+ appSecret?: string | null;
57
+ webhookVerifyToken?: string | null;
58
+ }
59
+
43
60
  /**
44
61
  * Cloud API send failures that are about the template a message names.
45
62
  *
@@ -52,17 +69,6 @@ declare function explainTemplateSendError(body: string): {
52
69
  error: string;
53
70
  } | null;
54
71
 
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
72
  /** 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
73
  interface MetaCredentials {
68
74
  accessToken: string;
@@ -223,7 +229,7 @@ declare const metaWhatsAppChannel: NotificationChannelProvider<MetaCloudGateway>
223
229
  * The plugin's webhook: the address Meta calls to report what happens on its side.
224
230
  *
225
231
  * 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
232
+ * topic, with the verify token set in the host's Meta app settings (or `META_WEBHOOK_VERIFY_TOKEN`). Each site's business account is subscribed to the app when
227
233
  * the site connects (see utils/wabaSubscription.ts), so its events arrive here.
228
234
  *
229
235
  * - GET answers Meta's handshake.
@@ -342,6 +348,12 @@ interface MetaPluginOptions {
342
348
  * accepts Meta's deliveries, but nobody is told.
343
349
  */
344
350
  host?: MetaHost;
351
+ /**
352
+ * The platform's Meta app (App ID, secret, webhook verify token), as the host keeps it in its own settings. Called whenever the plugin needs it, so
353
+ * keep it quick (answer from memory). What it returns wins over the `META_APP_ID`, `META_APP_SECRET` and `META_WEBHOOK_VERIFY_TOKEN`
354
+ * environment variables, which remain the fallback; a host that gives nothing here keeps working from the environment as before.
355
+ */
356
+ app?: () => MetaAppSettings | null | undefined;
345
357
  }
346
358
  /**
347
359
  * Meta Network Plugin for Payload CMS
@@ -373,4 +385,4 @@ interface MetaPluginOptions {
373
385
  */
374
386
  declare function metaPlugin(options?: MetaPluginOptions): Plugin;
375
387
 
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 };
388
+ export { type ActionRegistryRef, type ConversionEventInput, type ConversionEventResult, type FacebookLoginFailure, type FacebookProfile, type HostEventOutcome, type MetaAppSettings, 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 };
package/dist/index.js CHANGED
@@ -296,12 +296,32 @@ function decryptCredential(stored) {
296
296
  return stored;
297
297
  }
298
298
  }
299
+ var appProvider = null;
300
+ function setMetaAppProvider(provider) {
301
+ appProvider = provider ?? null;
302
+ }
303
+ var text = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
304
+ function metaAppSettings() {
305
+ let given;
306
+ try {
307
+ given = appProvider?.();
308
+ } catch {
309
+ given = null;
310
+ }
311
+ return {
312
+ appId: text(given?.appId) ?? text(process.env.META_APP_ID),
313
+ appSecret: text(given?.appSecret) ?? text(process.env.META_APP_SECRET),
314
+ webhookVerifyToken: text(given?.webhookVerifyToken) ?? text(process.env.META_WEBHOOK_VERIFY_TOKEN)
315
+ };
316
+ }
299
317
  function getMetaAppCredentials() {
300
- const appId = process.env.META_APP_ID;
301
- const appSecret = process.env.META_APP_SECRET;
318
+ const { appId, appSecret } = metaAppSettings();
302
319
  if (!appId || !appSecret) return null;
303
320
  return { appId, appSecret };
304
321
  }
322
+ function getMetaWebhookVerifyToken() {
323
+ return metaAppSettings().webhookVerifyToken;
324
+ }
305
325
  function getMaskedMetaAppId() {
306
326
  const creds = getMetaAppCredentials();
307
327
  if (!creds) return null;
@@ -432,7 +452,7 @@ var MetaConfig = {
432
452
  admin: {
433
453
  useAsTitle: "label",
434
454
  defaultColumns: ["label", "site", "connectionStatus", "isActive", "updatedAt"],
435
- group: "Integrations",
455
+ group: "Meta Business Suite",
436
456
  description: "Connect this site to Meta (Facebook/Instagram/WhatsApp). Enable only the channels this site needs."
437
457
  },
438
458
  access: {
@@ -1246,9 +1266,9 @@ async function graphPostJson(path, body, accessToken) {
1246
1266
  return { ok: true, status: res.status, data: await readGraphJson(res) };
1247
1267
  }
1248
1268
  async function readGraphJson(res) {
1249
- const text2 = await res.text();
1250
- if (!text2) return {};
1251
- return JSON.parse(text2);
1269
+ const text3 = await res.text();
1270
+ if (!text3) return {};
1271
+ return JSON.parse(text3);
1252
1272
  }
1253
1273
  async function graphDelete(path, accessToken) {
1254
1274
  const res = await callWithRetry(`${GRAPH_BASE}${path}`, {
@@ -1611,7 +1631,7 @@ var metaOAuthStartEndpoint = {
1611
1631
  }
1612
1632
  const appCreds = getMetaAppCredentials();
1613
1633
  if (!appCreds) {
1614
- return Response.json({ error: "Meta App not configured on this deployment \u2014 set META_APP_ID and META_APP_SECRET." }, { status: 400 });
1634
+ return Response.json({ error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET)." }, { status: 400 });
1615
1635
  }
1616
1636
  const state = signOAuthState(configId);
1617
1637
  const params = new URLSearchParams({
@@ -1649,7 +1669,7 @@ var metaOAuthCallbackEndpoint = {
1649
1669
  }
1650
1670
  const appCreds = getMetaAppCredentials();
1651
1671
  if (!appCreds) {
1652
- return oauthFinished({ ok: false, configId, error: "Meta App not configured on this deployment \u2014 set META_APP_ID and META_APP_SECRET." });
1672
+ return oauthFinished({ ok: false, configId, error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET)." });
1653
1673
  }
1654
1674
  const shortLived = await graphGet("/oauth/access_token", {
1655
1675
  client_id: appCreds.appId,
@@ -1932,7 +1952,7 @@ var threadsOAuthStartEndpoint = {
1932
1952
  }
1933
1953
  const appCreds = getMetaAppCredentials();
1934
1954
  if (!appCreds) {
1935
- return Response.json({ error: "Meta App not configured on this deployment \u2014 set META_APP_ID and META_APP_SECRET." }, { status: 400 });
1955
+ return Response.json({ error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET)." }, { status: 400 });
1936
1956
  }
1937
1957
  const state = signOAuthState(configId);
1938
1958
  const params = new URLSearchParams({
@@ -1970,7 +1990,7 @@ var threadsOAuthCallbackEndpoint = {
1970
1990
  }
1971
1991
  const appCreds = getMetaAppCredentials();
1972
1992
  if (!appCreds) {
1973
- return Response.redirect(`${adminBase}/${configId}?threads_oauth_error=${encodeURIComponent("Meta App not configured on this deployment \u2014 set META_APP_ID and META_APP_SECRET.")}`, 302);
1993
+ return Response.redirect(`${adminBase}/${configId}?threads_oauth_error=${encodeURIComponent("Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET).")}`, 302);
1974
1994
  }
1975
1995
  const shortLived = await threadsPost("/oauth/access_token", {
1976
1996
  client_id: appCreds.appId,
@@ -2199,7 +2219,7 @@ function toMetaBody(message) {
2199
2219
  if (!normalised) return { ok: false, problems: ["The message is empty."] };
2200
2220
  const taken = /* @__PURE__ */ new Set();
2201
2221
  const byPath = /* @__PURE__ */ new Map();
2202
- const text2 = normalised.replace(PLACEHOLDER, (_whole, path) => {
2222
+ const text3 = normalised.replace(PLACEHOLDER, (_whole, path) => {
2203
2223
  let parameter = byPath.get(path);
2204
2224
  if (!parameter) {
2205
2225
  parameter = { name: nameFor(path, taken), path, example: sampleFor(path) };
@@ -2208,16 +2228,16 @@ function toMetaBody(message) {
2208
2228
  return `{{${parameter.name}}}`;
2209
2229
  });
2210
2230
  const problems = [];
2211
- if (text2.length > MAX_BODY) problems.push(`The message is longer than ${MAX_BODY} characters.`);
2212
- if (/^\s*\{\{[^}]+\}\}/.test(text2)) problems.push("The message cannot start with a variable. Put some words before it.");
2213
- if (/\{\{[^}]+\}\}\s*$/.test(text2)) problems.push("The message cannot end with a variable. Put some words after it.");
2214
- if (/\}\}[\s.,;:!?\-–—()]*\{\{/.test(text2)) problems.push("Two variables cannot sit next to each other. Put words between them.");
2215
- const withoutVariables = text2.replace(/\{\{[^}]+\}\}/g, "").replace(/\s+/g, "");
2231
+ if (text3.length > MAX_BODY) problems.push(`The message is longer than ${MAX_BODY} characters.`);
2232
+ if (/^\s*\{\{[^}]+\}\}/.test(text3)) problems.push("The message cannot start with a variable. Put some words before it.");
2233
+ if (/\{\{[^}]+\}\}\s*$/.test(text3)) problems.push("The message cannot end with a variable. Put some words after it.");
2234
+ if (/\}\}[\s.,;:!?\-–—()]*\{\{/.test(text3)) problems.push("Two variables cannot sit next to each other. Put words between them.");
2235
+ const withoutVariables = text3.replace(/\{\{[^}]+\}\}/g, "").replace(/\s+/g, "");
2216
2236
  if (byPath.size > 0 && withoutVariables.length === 0) problems.push("The message cannot be only variables.");
2217
- const words = text2.replace(/\{\{[^}]+\}\}/g, " ").split(/\s+/).filter(Boolean).length;
2237
+ const words = text3.replace(/\{\{[^}]+\}\}/g, " ").split(/\s+/).filter(Boolean).length;
2218
2238
  if (byPath.size > 0 && words < byPath.size * 3) problems.push("The message has too many variables for its length. Meta wants about three words for every variable.");
2219
- if ((text2.match(EMOJI) ?? []).length > MAX_EMOJI) problems.push(`The message has more than ${MAX_EMOJI} emoji.`);
2220
- return problems.length ? { ok: false, problems } : { ok: true, body: { text: text2, parameters: [...byPath.values()] } };
2239
+ if ((text3.match(EMOJI) ?? []).length > MAX_EMOJI) problems.push(`The message has more than ${MAX_EMOJI} emoji.`);
2240
+ return problems.length ? { ok: false, problems } : { ok: true, body: { text: text3, parameters: [...byPath.values()] } };
2221
2241
  }
2222
2242
  function contentHash(message) {
2223
2243
  return (0, import_node_crypto3.createHash)("sha256").update(message.replace(/\r\n/g, "\n").trim()).digest("hex").slice(0, 12);
@@ -2683,7 +2703,7 @@ function toE164Digits(phone, defaultCountryCode) {
2683
2703
 
2684
2704
  // src/channels/whatsapp.ts
2685
2705
  var WHATSAPP_TIMEOUT_MS = 1e4;
2686
- async function sendViaMetaCloud(to, text2, cfg, log, template) {
2706
+ async function sendViaMetaCloud(to, text3, cfg, log, template) {
2687
2707
  const payload = template ? {
2688
2708
  messaging_product: "whatsapp",
2689
2709
  to,
@@ -2702,7 +2722,7 @@ async function sendViaMetaCloud(to, text2, cfg, log, template) {
2702
2722
  messaging_product: "whatsapp",
2703
2723
  to,
2704
2724
  type: "text",
2705
- text: { body: text2 }
2725
+ text: { body: text3 }
2706
2726
  };
2707
2727
  try {
2708
2728
  const res = await fetch(
@@ -2867,22 +2887,22 @@ var TEMPLATE_EVENT_BY_FIELD = {
2867
2887
  message_template_quality_update: "meta.template.quality_changed",
2868
2888
  message_template_components_update: "meta.template.components_changed"
2869
2889
  };
2870
- var text = (value) => typeof value === "string" && value.trim() ? value.trim() : typeof value === "number" ? String(value) : null;
2890
+ var text2 = (value) => typeof value === "string" && value.trim() ? value.trim() : typeof value === "number" ? String(value) : null;
2871
2891
  function templateEventsFrom(body) {
2872
2892
  const delivery = body;
2873
2893
  if (!delivery || delivery.object !== "whatsapp_business_account" || !Array.isArray(delivery.entry)) return [];
2874
2894
  const events = [];
2875
2895
  for (const entry of delivery.entry) {
2876
- const wabaId = text(entry?.id);
2896
+ const wabaId = text2(entry?.id);
2877
2897
  if (!wabaId || !Array.isArray(entry.changes)) continue;
2878
2898
  for (const change of entry.changes) {
2879
2899
  const field = typeof change?.field === "string" ? change.field : "";
2880
2900
  const eventName = TEMPLATE_EVENT_BY_FIELD[field];
2881
2901
  if (!eventName) continue;
2882
2902
  const value = change.value ?? {};
2883
- const templateId = text(value.message_template_id);
2884
- const status = text(value.event) ?? text(value.new_category) ?? text(value.new_quality_score) ?? text(value.correct_category);
2885
- const reason = text(value.reason) ?? text(value.disable_info?.disable_date);
2903
+ const templateId = text2(value.message_template_id);
2904
+ const status = text2(value.event) ?? text2(value.new_category) ?? text2(value.new_quality_score) ?? text2(value.correct_category);
2905
+ const reason = text2(value.reason) ?? text2(value.disable_info?.disable_date);
2886
2906
  const eventId = (0, import_node_crypto5.createHash)("sha256").update(JSON.stringify([wabaId, field, entry.time ?? null, templateId, status, reason])).digest("hex").slice(0, 32);
2887
2907
  events.push({
2888
2908
  eventName,
@@ -2892,8 +2912,8 @@ function templateEventsFrom(body) {
2892
2912
  eventId,
2893
2913
  wabaId,
2894
2914
  templateId,
2895
- templateName: text(value.message_template_name),
2896
- language: text(value.message_template_language),
2915
+ templateName: text2(value.message_template_name),
2916
+ language: text2(value.message_template_language),
2897
2917
  status,
2898
2918
  reason
2899
2919
  }
@@ -2909,7 +2929,7 @@ function createMetaWebhookEndpoints(host) {
2909
2929
  path: "/meta-webhook",
2910
2930
  method: "get",
2911
2931
  handler: async (req) => {
2912
- const challenge = handshakeChallenge(req.query, process.env.META_WEBHOOK_VERIFY_TOKEN);
2932
+ const challenge = handshakeChallenge(req.query, getMetaWebhookVerifyToken());
2913
2933
  if (challenge === null) return Response.json({ error: "Verification failed" }, { status: 403 });
2914
2934
  return new Response(challenge, { status: 200, headers: { "content-type": "text/plain" } });
2915
2935
  }
@@ -3226,7 +3246,7 @@ var MetaApprovals = {
3226
3246
  admin: {
3227
3247
  useAsTitle: "templateKey",
3228
3248
  defaultColumns: ["templateKey", "site", "status", "rejectionReason", "updatedAt"],
3229
- group: "Integrations",
3249
+ group: "Meta Business Suite",
3230
3250
  // Internal bookkeeping. The status shows on the notification template.
3231
3251
  hidden: true
3232
3252
  },
@@ -3415,6 +3435,7 @@ function registerNotificationChannel(provider) {
3415
3435
 
3416
3436
  // src/index.ts
3417
3437
  function metaPlugin(options = {}) {
3438
+ setMetaAppProvider(options.app);
3418
3439
  if (options.registry) {
3419
3440
  options.registry.register("meta-conversion-event", metaConversionEventHandler);
3420
3441
  }
package/dist/index.mjs CHANGED
@@ -260,12 +260,32 @@ function decryptCredential(stored) {
260
260
  return stored;
261
261
  }
262
262
  }
263
+ var appProvider = null;
264
+ function setMetaAppProvider(provider) {
265
+ appProvider = provider ?? null;
266
+ }
267
+ var text = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
268
+ function metaAppSettings() {
269
+ let given;
270
+ try {
271
+ given = appProvider?.();
272
+ } catch {
273
+ given = null;
274
+ }
275
+ return {
276
+ appId: text(given?.appId) ?? text(process.env.META_APP_ID),
277
+ appSecret: text(given?.appSecret) ?? text(process.env.META_APP_SECRET),
278
+ webhookVerifyToken: text(given?.webhookVerifyToken) ?? text(process.env.META_WEBHOOK_VERIFY_TOKEN)
279
+ };
280
+ }
263
281
  function getMetaAppCredentials() {
264
- const appId = process.env.META_APP_ID;
265
- const appSecret = process.env.META_APP_SECRET;
282
+ const { appId, appSecret } = metaAppSettings();
266
283
  if (!appId || !appSecret) return null;
267
284
  return { appId, appSecret };
268
285
  }
286
+ function getMetaWebhookVerifyToken() {
287
+ return metaAppSettings().webhookVerifyToken;
288
+ }
269
289
  function getMaskedMetaAppId() {
270
290
  const creds = getMetaAppCredentials();
271
291
  if (!creds) return null;
@@ -396,7 +416,7 @@ var MetaConfig = {
396
416
  admin: {
397
417
  useAsTitle: "label",
398
418
  defaultColumns: ["label", "site", "connectionStatus", "isActive", "updatedAt"],
399
- group: "Integrations",
419
+ group: "Meta Business Suite",
400
420
  description: "Connect this site to Meta (Facebook/Instagram/WhatsApp). Enable only the channels this site needs."
401
421
  },
402
422
  access: {
@@ -1210,9 +1230,9 @@ async function graphPostJson(path, body, accessToken) {
1210
1230
  return { ok: true, status: res.status, data: await readGraphJson(res) };
1211
1231
  }
1212
1232
  async function readGraphJson(res) {
1213
- const text2 = await res.text();
1214
- if (!text2) return {};
1215
- return JSON.parse(text2);
1233
+ const text3 = await res.text();
1234
+ if (!text3) return {};
1235
+ return JSON.parse(text3);
1216
1236
  }
1217
1237
  async function graphDelete(path, accessToken) {
1218
1238
  const res = await callWithRetry(`${GRAPH_BASE}${path}`, {
@@ -1552,7 +1572,7 @@ var metaOAuthStartEndpoint = {
1552
1572
  }
1553
1573
  const appCreds = getMetaAppCredentials();
1554
1574
  if (!appCreds) {
1555
- return Response.json({ error: "Meta App not configured on this deployment \u2014 set META_APP_ID and META_APP_SECRET." }, { status: 400 });
1575
+ return Response.json({ error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET)." }, { status: 400 });
1556
1576
  }
1557
1577
  const state = signOAuthState(configId);
1558
1578
  const params = new URLSearchParams({
@@ -1590,7 +1610,7 @@ var metaOAuthCallbackEndpoint = {
1590
1610
  }
1591
1611
  const appCreds = getMetaAppCredentials();
1592
1612
  if (!appCreds) {
1593
- return oauthFinished({ ok: false, configId, error: "Meta App not configured on this deployment \u2014 set META_APP_ID and META_APP_SECRET." });
1613
+ return oauthFinished({ ok: false, configId, error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET)." });
1594
1614
  }
1595
1615
  const shortLived = await graphGet("/oauth/access_token", {
1596
1616
  client_id: appCreds.appId,
@@ -1873,7 +1893,7 @@ var threadsOAuthStartEndpoint = {
1873
1893
  }
1874
1894
  const appCreds = getMetaAppCredentials();
1875
1895
  if (!appCreds) {
1876
- return Response.json({ error: "Meta App not configured on this deployment \u2014 set META_APP_ID and META_APP_SECRET." }, { status: 400 });
1896
+ return Response.json({ error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET)." }, { status: 400 });
1877
1897
  }
1878
1898
  const state = signOAuthState(configId);
1879
1899
  const params = new URLSearchParams({
@@ -1911,7 +1931,7 @@ var threadsOAuthCallbackEndpoint = {
1911
1931
  }
1912
1932
  const appCreds = getMetaAppCredentials();
1913
1933
  if (!appCreds) {
1914
- return Response.redirect(`${adminBase}/${configId}?threads_oauth_error=${encodeURIComponent("Meta App not configured on this deployment \u2014 set META_APP_ID and META_APP_SECRET.")}`, 302);
1934
+ return Response.redirect(`${adminBase}/${configId}?threads_oauth_error=${encodeURIComponent("Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET).")}`, 302);
1915
1935
  }
1916
1936
  const shortLived = await threadsPost("/oauth/access_token", {
1917
1937
  client_id: appCreds.appId,
@@ -2140,7 +2160,7 @@ function toMetaBody(message) {
2140
2160
  if (!normalised) return { ok: false, problems: ["The message is empty."] };
2141
2161
  const taken = /* @__PURE__ */ new Set();
2142
2162
  const byPath = /* @__PURE__ */ new Map();
2143
- const text2 = normalised.replace(PLACEHOLDER, (_whole, path) => {
2163
+ const text3 = normalised.replace(PLACEHOLDER, (_whole, path) => {
2144
2164
  let parameter = byPath.get(path);
2145
2165
  if (!parameter) {
2146
2166
  parameter = { name: nameFor(path, taken), path, example: sampleFor(path) };
@@ -2149,16 +2169,16 @@ function toMetaBody(message) {
2149
2169
  return `{{${parameter.name}}}`;
2150
2170
  });
2151
2171
  const problems = [];
2152
- if (text2.length > MAX_BODY) problems.push(`The message is longer than ${MAX_BODY} characters.`);
2153
- if (/^\s*\{\{[^}]+\}\}/.test(text2)) problems.push("The message cannot start with a variable. Put some words before it.");
2154
- if (/\{\{[^}]+\}\}\s*$/.test(text2)) problems.push("The message cannot end with a variable. Put some words after it.");
2155
- if (/\}\}[\s.,;:!?\-–—()]*\{\{/.test(text2)) problems.push("Two variables cannot sit next to each other. Put words between them.");
2156
- const withoutVariables = text2.replace(/\{\{[^}]+\}\}/g, "").replace(/\s+/g, "");
2172
+ if (text3.length > MAX_BODY) problems.push(`The message is longer than ${MAX_BODY} characters.`);
2173
+ if (/^\s*\{\{[^}]+\}\}/.test(text3)) problems.push("The message cannot start with a variable. Put some words before it.");
2174
+ if (/\{\{[^}]+\}\}\s*$/.test(text3)) problems.push("The message cannot end with a variable. Put some words after it.");
2175
+ if (/\}\}[\s.,;:!?\-–—()]*\{\{/.test(text3)) problems.push("Two variables cannot sit next to each other. Put words between them.");
2176
+ const withoutVariables = text3.replace(/\{\{[^}]+\}\}/g, "").replace(/\s+/g, "");
2157
2177
  if (byPath.size > 0 && withoutVariables.length === 0) problems.push("The message cannot be only variables.");
2158
- const words = text2.replace(/\{\{[^}]+\}\}/g, " ").split(/\s+/).filter(Boolean).length;
2178
+ const words = text3.replace(/\{\{[^}]+\}\}/g, " ").split(/\s+/).filter(Boolean).length;
2159
2179
  if (byPath.size > 0 && words < byPath.size * 3) problems.push("The message has too many variables for its length. Meta wants about three words for every variable.");
2160
- if ((text2.match(EMOJI) ?? []).length > MAX_EMOJI) problems.push(`The message has more than ${MAX_EMOJI} emoji.`);
2161
- return problems.length ? { ok: false, problems } : { ok: true, body: { text: text2, parameters: [...byPath.values()] } };
2180
+ if ((text3.match(EMOJI) ?? []).length > MAX_EMOJI) problems.push(`The message has more than ${MAX_EMOJI} emoji.`);
2181
+ return problems.length ? { ok: false, problems } : { ok: true, body: { text: text3, parameters: [...byPath.values()] } };
2162
2182
  }
2163
2183
  function contentHash(message) {
2164
2184
  return createHash2("sha256").update(message.replace(/\r\n/g, "\n").trim()).digest("hex").slice(0, 12);
@@ -2624,7 +2644,7 @@ function toE164Digits(phone, defaultCountryCode) {
2624
2644
 
2625
2645
  // src/channels/whatsapp.ts
2626
2646
  var WHATSAPP_TIMEOUT_MS = 1e4;
2627
- async function sendViaMetaCloud(to, text2, cfg, log, template) {
2647
+ async function sendViaMetaCloud(to, text3, cfg, log, template) {
2628
2648
  const payload = template ? {
2629
2649
  messaging_product: "whatsapp",
2630
2650
  to,
@@ -2643,7 +2663,7 @@ async function sendViaMetaCloud(to, text2, cfg, log, template) {
2643
2663
  messaging_product: "whatsapp",
2644
2664
  to,
2645
2665
  type: "text",
2646
- text: { body: text2 }
2666
+ text: { body: text3 }
2647
2667
  };
2648
2668
  try {
2649
2669
  const res = await fetch(
@@ -2808,22 +2828,22 @@ var TEMPLATE_EVENT_BY_FIELD = {
2808
2828
  message_template_quality_update: "meta.template.quality_changed",
2809
2829
  message_template_components_update: "meta.template.components_changed"
2810
2830
  };
2811
- var text = (value) => typeof value === "string" && value.trim() ? value.trim() : typeof value === "number" ? String(value) : null;
2831
+ var text2 = (value) => typeof value === "string" && value.trim() ? value.trim() : typeof value === "number" ? String(value) : null;
2812
2832
  function templateEventsFrom(body) {
2813
2833
  const delivery = body;
2814
2834
  if (!delivery || delivery.object !== "whatsapp_business_account" || !Array.isArray(delivery.entry)) return [];
2815
2835
  const events = [];
2816
2836
  for (const entry of delivery.entry) {
2817
- const wabaId = text(entry?.id);
2837
+ const wabaId = text2(entry?.id);
2818
2838
  if (!wabaId || !Array.isArray(entry.changes)) continue;
2819
2839
  for (const change of entry.changes) {
2820
2840
  const field = typeof change?.field === "string" ? change.field : "";
2821
2841
  const eventName = TEMPLATE_EVENT_BY_FIELD[field];
2822
2842
  if (!eventName) continue;
2823
2843
  const value = change.value ?? {};
2824
- const templateId = text(value.message_template_id);
2825
- const status = text(value.event) ?? text(value.new_category) ?? text(value.new_quality_score) ?? text(value.correct_category);
2826
- const reason = text(value.reason) ?? text(value.disable_info?.disable_date);
2844
+ const templateId = text2(value.message_template_id);
2845
+ const status = text2(value.event) ?? text2(value.new_category) ?? text2(value.new_quality_score) ?? text2(value.correct_category);
2846
+ const reason = text2(value.reason) ?? text2(value.disable_info?.disable_date);
2827
2847
  const eventId = createHash3("sha256").update(JSON.stringify([wabaId, field, entry.time ?? null, templateId, status, reason])).digest("hex").slice(0, 32);
2828
2848
  events.push({
2829
2849
  eventName,
@@ -2833,8 +2853,8 @@ function templateEventsFrom(body) {
2833
2853
  eventId,
2834
2854
  wabaId,
2835
2855
  templateId,
2836
- templateName: text(value.message_template_name),
2837
- language: text(value.message_template_language),
2856
+ templateName: text2(value.message_template_name),
2857
+ language: text2(value.message_template_language),
2838
2858
  status,
2839
2859
  reason
2840
2860
  }
@@ -2850,7 +2870,7 @@ function createMetaWebhookEndpoints(host) {
2850
2870
  path: "/meta-webhook",
2851
2871
  method: "get",
2852
2872
  handler: async (req) => {
2853
- const challenge = handshakeChallenge(req.query, process.env.META_WEBHOOK_VERIFY_TOKEN);
2873
+ const challenge = handshakeChallenge(req.query, getMetaWebhookVerifyToken());
2854
2874
  if (challenge === null) return Response.json({ error: "Verification failed" }, { status: 403 });
2855
2875
  return new Response(challenge, { status: 200, headers: { "content-type": "text/plain" } });
2856
2876
  }
@@ -3167,7 +3187,7 @@ var MetaApprovals = {
3167
3187
  admin: {
3168
3188
  useAsTitle: "templateKey",
3169
3189
  defaultColumns: ["templateKey", "site", "status", "rejectionReason", "updatedAt"],
3170
- group: "Integrations",
3190
+ group: "Meta Business Suite",
3171
3191
  // Internal bookkeeping. The status shows on the notification template.
3172
3192
  hidden: true
3173
3193
  },
@@ -3356,6 +3376,7 @@ function registerNotificationChannel(provider) {
3356
3376
 
3357
3377
  // src/index.ts
3358
3378
  function metaPlugin(options = {}) {
3379
+ setMetaAppProvider(options.app);
3359
3380
  if (options.registry) {
3360
3381
  options.registry.register("meta-conversion-event", metaConversionEventHandler);
3361
3382
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opscms-meta-plugin",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Payload CMS plugin for connecting multi-tenant sites to Meta's network (Facebook Pixel + Conversions API, Facebook/Instagram Commerce Catalog, WhatsApp Business Cloud API). Modular per-channel, per-site — nothing hardcoded to one product line.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -102,7 +102,7 @@
102
102
  "devDependencies": {
103
103
  "@types/node": "^22.0.0",
104
104
  "@types/react": "^19.0.0",
105
- "next": "16.2.6",
105
+ "next": "16.4.5",
106
106
  "payload": "^3.0.0",
107
107
  "tsup": "^8.0.0",
108
108
  "tsx": "^4.0.0",