planvortex 0.1.0 → 0.2.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.
@@ -1,6 +1,6 @@
1
1
  // src/core/errors.ts
2
2
  var PLANVORTEX_ERROR_RANGES = [
3
- { from: 500, to: 542, family: "auth" },
3
+ { from: 500, to: 544, family: "auth" },
4
4
  { from: 601, to: 612, family: "user" },
5
5
  { from: 700, to: 715, family: "account" },
6
6
  { from: 800, to: 810, family: "file" },
@@ -136,5 +136,5 @@ function isTokenError(error) {
136
136
  }
137
137
 
138
138
  export { AccountError, AiPlanError, AuthError, ContactError, FileError, IntegrationError, MessagingError, NO_ERROR_CODE, OrganizationError, PLANVORTEX_ERROR_RANGES, PlanLimitError, PlanVortexAuthenticationError, PlanVortexConfigError, PlanVortexConnectionError, PlanVortexError, ProductError, PublicationError, TOKEN_ERROR_CODES, UserError, createErrorFromResponse, errorFamilyForCode, isPlanVortexError, isTokenError };
139
- //# sourceMappingURL=chunk-HSMIRBF3.js.map
140
- //# sourceMappingURL=chunk-HSMIRBF3.js.map
139
+ //# sourceMappingURL=chunk-GUYS6XTO.js.map
140
+ //# sourceMappingURL=chunk-GUYS6XTO.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/errors.ts"],"names":[],"mappings":";AAuBO,IAAM,uBAAA,GAA2D;AAAA,EACpE,EAAE,IAAA,EAAM,GAAA,EAAK,EAAA,EAAI,GAAA,EAAK,QAAQ,MAAA,EAAO;AAAA,EACrC,EAAE,IAAA,EAAM,GAAA,EAAK,EAAA,EAAI,GAAA,EAAK,QAAQ,MAAA,EAAO;AAAA,EACrC,EAAE,IAAA,EAAM,GAAA,EAAK,EAAA,EAAI,GAAA,EAAK,QAAQ,SAAA,EAAU;AAAA,EACxC,EAAE,IAAA,EAAM,GAAA,EAAK,EAAA,EAAI,GAAA,EAAK,QAAQ,MAAA,EAAO;AAAA,EACrC,EAAE,IAAA,EAAM,GAAA,EAAK,EAA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;AAAA,IACR,IAAA,EACI,OAAO,KAAA,CAAM,IAAA,KAAS,QAAA,IAAY,KAAA,CAAM,IAAA,KAAS,IAAA,GAC1C,KAAA,CAAM,IAAA,GACP,EAAE,IAAA,EAAM,MAAM,IAAA;AAAK,GAChC,CAAA;AACL;AAGO,SAAS,kBAAkB,KAAA,EAA0C;AACxE,EAAA,OAAO,KAAA,YAAiB,eAAA;AAC5B;AAOO,SAAS,aAAa,KAAA,EAAyB;AAClD,EAAA,OAAO,kBAAkB,KAAK,CAAA,IAAK,iBAAA,CAAkB,QAAA,CAAS,MAAM,IAAI,CAAA;AAC5E","file":"chunk-HSMIRBF3.js","sourcesContent":["/**\n * El catálogo de errores de PlanVortex, por rangos, y las clases que salen de él.\n *\n * LA REGLA, y no es negociable: **los errores se clasifican por `body.code`, nunca por el status\n * HTTP.** Todo error de dominio viaja con un 400 — un token caducado, una cuenta desconectada, el\n * cupo del plan agotado y un texto demasiado largo son los cuatro un 400. Sólo el 520 (permisos)\n * sale 401 y un fallo inesperado sale 500. Un `if (response.status === 401) refreshToken()` sería\n * un bug silencioso: los códigos de token, 501 y 522, viajan dentro de un 400.\n *\n * El catálogo del servidor crece cada mes, así que un código fuera de estos rangos NO es un error\n * del cliente: cae en la clase base con su `code` y su `message` intactos. Nunca se traga y nunca\n * se renombra.\n */\n\nexport type PlanVortexErrorRange = {\n /** Primer código del rango, incluido */\n from: number;\n /** Último código del rango, incluido */\n to: number;\n /** Qué familia de problemas es */\n family: string;\n};\n\nexport const PLANVORTEX_ERROR_RANGES: readonly PlanVortexErrorRange[] = [\n { from: 500, to: 542, family: \"auth\" },\n { from: 601, to: 612, family: \"user\" },\n { from: 700, to: 715, family: \"account\" },\n { from: 800, to: 810, family: \"file\" },\n { from: 900, to: 960, family: \"publication\" },\n { from: 1000, to: 1003, family: \"general\" },\n { from: 1100, to: 1111, family: \"organization\" },\n { from: 1200, to: 1207, family: \"role\" },\n { from: 1300, to: 1307, family: \"plan_limit\" },\n { from: 1400, to: 1408, family: \"plan_limit\" },\n { from: 1500, to: 1512, family: \"messaging\" },\n { from: 1600, to: 1601, family: \"contact\" },\n { from: 1900, to: 1906, family: \"payment\" },\n { from: 2000, to: 2099, family: \"product\" },\n { from: 2100, to: 2199, family: \"ai_plan\" },\n { from: 2200, to: 2299, family: \"integration\" },\n] as const;\n\n/**\n * El `code` que lleva un error que **no** trae código del servidor: un fallo de red, un timeout, un\n * 502 de un proxy con cuerpo HTML, o el propio constructor quejándose de la configuración.\n *\n * El servidor no emite nunca el 0, así que sirve de centinela sin pisar el catálogo. Cuál de esos\n * casos es se distingue por `family`: `connection`, `http`, `oauth`, `config` o `webhook`.\n */\nexport const NO_ERROR_CODE = 0;\n\n/**\n * Los dos códigos que significan \"tu token ya no sirve\". Los dos llegan **dentro de un 400**, que es\n * justo por lo que existe esta constante: quien mire el status no los va a encontrar.\n *\n * El 520 (permisos) NO está aquí a propósito: sale 401, pero pedir un token nuevo no lo arregla — a\n * la app le faltan permisos, y con un token recién emitido le seguirán faltando.\n */\nexport const TOKEN_ERROR_CODES: readonly number[] = [501, 522];\n\n/** Opciones de construcción de un error. Todas opcionales: un error siempre se puede construir. */\nexport interface PlanVortexErrorOptions {\n /** El `data` del cuerpo — lo que el servidor adjuntó con `.withData({...})`. `{}` si no vino nada. */\n data?: Record<string, unknown>;\n /** Status HTTP. `undefined` cuando la petición no llegó a tener respuesta. */\n status?: number;\n /** `x-request-id` de la respuesta, si el despliegue lo pone delante. */\n requestId?: string;\n /** Segundos de la cabecera `Retry-After`, cuando la hay. */\n retryAfter?: number;\n /** El error original (un `TypeError` de `fetch`, por ejemplo). */\n cause?: unknown;\n /**\n * Familia, sólo para los errores que NO salen del catálogo: `connection`, `http`, `oauth`,\n * `config` y `webhook`. Los de dominio la deducen de su `code` y no la pasan nunca.\n */\n family?: string;\n}\n\n/**\n * La base de todo lo que lanza esta librería.\n *\n * Un `catch (e) { if (e instanceof PlanVortexError) }` los coge todos: los de dominio, los de red y\n * los de configuración. Para afinar están las subclases y el `code`.\n */\nexport class PlanVortexError extends Error {\n /** El `code` del cuerpo, tal cual. {@link NO_ERROR_CODE} si el error no viene del catálogo. */\n readonly code: number;\n /** La familia del rango: `auth`, `publication`, `plan_limit`... Ver {@link PLANVORTEX_ERROR_RANGES}. */\n readonly family: string;\n /** El `data` del cuerpo. */\n readonly data: Record<string, unknown>;\n /** Status HTTP, o `undefined` si nunca hubo respuesta. */\n readonly status: number | undefined;\n /** `x-request-id`, si el despliegue lo pone. Hoy el servidor no lo emite; un proxy delante sí. */\n readonly requestId: string | undefined;\n /** Segundos que pidió esperar la cabecera `Retry-After`, si llegó. */\n readonly retryAfter: number | undefined;\n\n constructor(code: number, message: string, options: PlanVortexErrorOptions = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = new.target.name;\n this.code = code;\n this.family = options.family ?? errorFamilyForCode(code) ?? \"unknown\";\n this.data = options.data ?? {};\n this.status = options.status;\n this.requestId = options.requestId;\n this.retryAfter = options.retryAfter;\n }\n}\n\n/** 500-542 — tokens, apps de cliente, permisos. Incluye el 501 y el 522, los de token caducado. */\nexport class AuthError extends PlanVortexError {}\n/** 601-612 — el usuario final. */\nexport class UserError extends PlanVortexError {}\n/** 700-715 — cuentas sociales: desconectada, sin permisos en la red, sin refrescar. */\nexport class AccountError extends PlanVortexError {}\n/** 800-810 — ficheros: formato no admitido, demasiado grande, conversión fallida. */\nexport class FileError extends PlanVortexError {}\n/** 900-960 — publicaciones, incluidos los límites por red (caracteres, imágenes, duración). */\nexport class PublicationError extends PlanVortexError {}\n/** 1100-1111 — organizaciones, y el token temporal atado a una sola de ellas (1101). */\nexport class OrganizationError extends PlanVortexError {}\n/**\n * 1300-1307 y 1400-1408 — el cupo del plan, del cliente o de la organización.\n *\n * Es el error que un integrador **sí** quiere distinguir: no se arregla reintentando, se arregla\n * cambiando de plan. Por eso los dos rangos comparten clase.\n */\nexport class PlanLimitError extends PlanVortexError {}\n/** 1500-1512 — conversaciones, mensajes y plantillas. Exige plan de pago. */\nexport class MessagingError extends PlanVortexError {}\n/** 1600-1601 — contactos. */\nexport class ContactError extends PlanVortexError {}\n/** 2000-2099 — catálogos y productos (sólo Facebook e Instagram). */\nexport class ProductError extends PlanVortexError {}\n/** 2100-2199 — planes de publicaciones generados con IA. */\nexport class AiPlanError extends PlanVortexError {}\n/** 2200-2299 — integraciones: Google Drive, RSS. */\nexport class IntegrationError extends PlanVortexError {}\n\n/**\n * La petición no llegó a tener respuesta: DNS, conexión rechazada, socket cortado o timeout.\n *\n * No lleva código del catálogo porque el servidor nunca llegó a opinar.\n */\nexport class PlanVortexConnectionError extends PlanVortexError {\n /** `true` si lo que se agotó fue nuestro propio timeout, no la red. */\n readonly timeout: boolean;\n\n constructor(message: string, options: PlanVortexErrorOptions & { timeout?: boolean } = {}) {\n super(NO_ERROR_CODE, message, { ...options, family: \"connection\" });\n this.timeout = options.timeout ?? false;\n }\n}\n\n/**\n * `POST /oauth/token` rechazó las credenciales.\n *\n * Es el ÚNICO sitio del API con forma de error distinta: `{error, error_description}` de OAuth2, no\n * el `{code, message, data}` de todo lo demás. Y por eso el `code` es {@link NO_ERROR_CODE}: el\n * servidor tiene códigos para esto (538-541) pero **no los manda en el cuerpo**, así que ponerlos\n * aquí sería inventarse algo que nadie dijo. Lo que sí viaja es `oauthError`.\n */\nexport class PlanVortexAuthenticationError extends PlanVortexError {\n /** `invalid_client`, `invalid_request`, `unsupported_grant_type`, `slow_down` o `server_error`. */\n readonly oauthError: string;\n\n constructor(oauthError: string, description: string, options: PlanVortexErrorOptions = {}) {\n super(NO_ERROR_CODE, description, { ...options, family: \"oauth\" });\n this.oauthError = oauthError;\n }\n}\n\n/**\n * La librería está mal configurada y no ha llegado a salir de casa: sin credenciales, o instanciada\n * en un navegador (§ trampa 9 del roadmap).\n */\nexport class PlanVortexConfigError extends PlanVortexError {\n constructor(message: string) {\n super(NO_ERROR_CODE, message, { family: \"config\" });\n }\n}\n\n/** La familia a la que pertenece un código, o `undefined` si cae fuera del catálogo conocido. */\nexport function errorFamilyForCode(code: number): string | undefined {\n return PLANVORTEX_ERROR_RANGES.find((range) => code >= range.from && code <= range.to)?.family;\n}\n\n/**\n * Familia -> clase. Las que faltan —`general`, `role`, `payment` y cualquier rango nuevo— caen a\n * propósito en la clase base: existen en el servidor pero no son superficie de integración, y darles\n * clase propia sería prometer un `instanceof` que luego habría que mantener.\n */\nconst FAMILY_CLASSES: Record<string, typeof PlanVortexError> = {\n auth: AuthError,\n user: UserError,\n account: AccountError,\n file: FileError,\n publication: PublicationError,\n organization: OrganizationError,\n plan_limit: PlanLimitError,\n messaging: MessagingError,\n contact: ContactError,\n product: ProductError,\n ai_plan: AiPlanError,\n integration: IntegrationError,\n};\n\n/** El cuerpo de error del API: `{code, message, data}`. */\nexport interface ApiErrorBody {\n code: number;\n message?: string;\n data?: Record<string, unknown>;\n}\n\nfunction isApiErrorBody(body: unknown): body is ApiErrorBody {\n return typeof body === \"object\" && body !== null && typeof (body as ApiErrorBody).code === \"number\";\n}\n\n/**\n * Convierte una respuesta de error en la clase que le toca.\n *\n * Un cuerpo sin `code` —un 502 de un proxy, la página HTML de un balanceador— no es un error de\n * dominio: sale como clase base con `family: \"http\"` y el cuerpo entero en `data`, que es además lo\n * que necesita `auth.ts` para reconocer el `{error, error_description}` de OAuth2.\n */\nexport function createErrorFromResponse(input: {\n body: unknown;\n status: number;\n requestId?: string | undefined;\n retryAfter?: number | undefined;\n}): PlanVortexError {\n const options: PlanVortexErrorOptions = {\n status: input.status,\n ...(input.requestId === undefined ? {} : { requestId: input.requestId }),\n ...(input.retryAfter === undefined ? {} : { retryAfter: input.retryAfter }),\n };\n\n if (isApiErrorBody(input.body)) {\n const family = errorFamilyForCode(input.body.code);\n const ErrorClass = (family === undefined ? undefined : FAMILY_CLASSES[family]) ?? PlanVortexError;\n return new ErrorClass(input.body.code, input.body.message ?? \"PlanVortex error\", {\n ...options,\n data: input.body.data ?? {},\n });\n }\n\n return new PlanVortexError(NO_ERROR_CODE, `HTTP ${input.status}`, {\n ...options,\n family: \"http\",\n data:\n typeof input.body === \"object\" && input.body !== null\n ? (input.body as Record<string, unknown>)\n : { body: input.body },\n });\n}\n\n/** ¿Es un error de esta librería? Útil en un `catch` donde no apetece importar la clase. */\nexport function isPlanVortexError(error: unknown): error is PlanVortexError {\n return error instanceof PlanVortexError;\n}\n\n/**\n * ¿Dice este error que el token ya no sirve? (los códigos 501 y 522, los dos dentro de un 400).\n *\n * Es lo que dispara el único reintento con token nuevo del cliente.\n */\nexport function isTokenError(error: unknown): boolean {\n return isPlanVortexError(error) && TOKEN_ERROR_CODES.includes(error.code);\n}\n"]}
1
+ {"version":3,"sources":["../src/core/errors.ts"],"names":[],"mappings":";AAuBO,IAAM,uBAAA,GAA2D;AAAA,EACpE,EAAE,IAAA,EAAM,GAAA,EAAK,EAAA,EAAI,GAAA,EAAK,QAAQ,MAAA,EAAO;AAAA,EACrC,EAAE,IAAA,EAAM,GAAA,EAAK,EAAA,EAAI,GAAA,EAAK,QAAQ,MAAA,EAAO;AAAA,EACrC,EAAE,IAAA,EAAM,GAAA,EAAK,EAAA,EAAI,GAAA,EAAK,QAAQ,SAAA,EAAU;AAAA,EACxC,EAAE,IAAA,EAAM,GAAA,EAAK,EAAA,EAAI,GAAA,EAAK,QAAQ,MAAA,EAAO;AAAA,EACrC,EAAE,IAAA,EAAM,GAAA,EAAK,EAAA,EAAI,GAAA,EAAK,QAAQ,aAAA,EAAc;AAAA,EAC5C,EAAE,IAAA,EAAM,GAAA,EAAM,EAAA,EAAI,IAAA,EAAM,QAAQ,SAAA,EAAU;AAAA,EAC1C,EAAE,IAAA,EAAM,IAAA,EAAM,EAAA,EAAI,IAAA,EAAM,QAAQ,cAAA,EAAe;AAAA,EAC/C,EAAE,IAAA,EAAM,IAAA,EAAM,EAAA,EAAI,IAAA,EAAM,QAAQ,MAAA,EAAO;AAAA,EACvC,EAAE,IAAA,EAAM,IAAA,EAAM,EAAA,EAAI,IAAA,E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AM,IAAI,CAAA;AAC5E","file":"chunk-GUYS6XTO.js","sourcesContent":["/**\n * El catálogo de errores de PlanVortex, por rangos, y las clases que salen de él.\n *\n * LA REGLA, y no es negociable: **los errores se clasifican por `body.code`, nunca por el status\n * HTTP.** Todo error de dominio viaja con un 400 — un token caducado, una cuenta desconectada, el\n * cupo del plan agotado y un texto demasiado largo son los cuatro un 400. Sólo el 520 (permisos)\n * sale 401 y un fallo inesperado sale 500. Un `if (response.status === 401) refreshToken()` sería\n * un bug silencioso: los códigos de token, 501 y 522, viajan dentro de un 400.\n *\n * El catálogo del servidor crece cada mes, así que un código fuera de estos rangos NO es un error\n * del cliente: cae en la clase base con su `code` y su `message` intactos. Nunca se traga y nunca\n * se renombra.\n */\n\nexport type PlanVortexErrorRange = {\n /** Primer código del rango, incluido */\n from: number;\n /** Último código del rango, incluido */\n to: number;\n /** Qué familia de problemas es */\n family: string;\n};\n\nexport const PLANVORTEX_ERROR_RANGES: readonly PlanVortexErrorRange[] = [\n { from: 500, to: 544, family: \"auth\" },\n { from: 601, to: 612, family: \"user\" },\n { from: 700, to: 715, family: \"account\" },\n { from: 800, to: 810, family: \"file\" },\n { from: 900, to: 960, family: \"publication\" },\n { from: 1000, to: 1003, family: \"general\" },\n { from: 1100, to: 1111, family: \"organization\" },\n { from: 1200, to: 1207, family: \"role\" },\n { from: 1300, to: 1307, family: \"plan_limit\" },\n { from: 1400, to: 1408, family: \"plan_limit\" },\n { from: 1500, to: 1512, family: \"messaging\" },\n { from: 1600, to: 1601, family: \"contact\" },\n { from: 1900, to: 1906, family: \"payment\" },\n { from: 2000, to: 2099, family: \"product\" },\n { from: 2100, to: 2199, family: \"ai_plan\" },\n { from: 2200, to: 2299, family: \"integration\" },\n] as const;\n\n/**\n * El `code` que lleva un error que **no** trae código del servidor: un fallo de red, un timeout, un\n * 502 de un proxy con cuerpo HTML, o el propio constructor quejándose de la configuración.\n *\n * El servidor no emite nunca el 0, así que sirve de centinela sin pisar el catálogo. Cuál de esos\n * casos es se distingue por `family`: `connection`, `http`, `oauth`, `config` o `webhook`.\n */\nexport const NO_ERROR_CODE = 0;\n\n/**\n * Los dos códigos que significan \"tu token ya no sirve\". Los dos llegan **dentro de un 400**, que es\n * justo por lo que existe esta constante: quien mire el status no los va a encontrar.\n *\n * El 520 (permisos) NO está aquí a propósito: sale 401, pero pedir un token nuevo no lo arregla — a\n * la app le faltan permisos, y con un token recién emitido le seguirán faltando.\n */\nexport const TOKEN_ERROR_CODES: readonly number[] = [501, 522];\n\n/** Opciones de construcción de un error. Todas opcionales: un error siempre se puede construir. */\nexport interface PlanVortexErrorOptions {\n /** El `data` del cuerpo — lo que el servidor adjuntó con `.withData({...})`. `{}` si no vino nada. */\n data?: Record<string, unknown>;\n /** Status HTTP. `undefined` cuando la petición no llegó a tener respuesta. */\n status?: number;\n /** `x-request-id` de la respuesta, si el despliegue lo pone delante. */\n requestId?: string;\n /** Segundos de la cabecera `Retry-After`, cuando la hay. */\n retryAfter?: number;\n /** El error original (un `TypeError` de `fetch`, por ejemplo). */\n cause?: unknown;\n /**\n * Familia, sólo para los errores que NO salen del catálogo: `connection`, `http`, `oauth`,\n * `config` y `webhook`. Los de dominio la deducen de su `code` y no la pasan nunca.\n */\n family?: string;\n}\n\n/**\n * La base de todo lo que lanza esta librería.\n *\n * Un `catch (e) { if (e instanceof PlanVortexError) }` los coge todos: los de dominio, los de red y\n * los de configuración. Para afinar están las subclases y el `code`.\n */\nexport class PlanVortexError extends Error {\n /** El `code` del cuerpo, tal cual. {@link NO_ERROR_CODE} si el error no viene del catálogo. */\n readonly code: number;\n /** La familia del rango: `auth`, `publication`, `plan_limit`... Ver {@link PLANVORTEX_ERROR_RANGES}. */\n readonly family: string;\n /** El `data` del cuerpo. */\n readonly data: Record<string, unknown>;\n /** Status HTTP, o `undefined` si nunca hubo respuesta. */\n readonly status: number | undefined;\n /** `x-request-id`, si el despliegue lo pone. Hoy el servidor no lo emite; un proxy delante sí. */\n readonly requestId: string | undefined;\n /** Segundos que pidió esperar la cabecera `Retry-After`, si llegó. */\n readonly retryAfter: number | undefined;\n\n constructor(code: number, message: string, options: PlanVortexErrorOptions = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = new.target.name;\n this.code = code;\n this.family = options.family ?? errorFamilyForCode(code) ?? \"unknown\";\n this.data = options.data ?? {};\n this.status = options.status;\n this.requestId = options.requestId;\n this.retryAfter = options.retryAfter;\n }\n}\n\n/** 500-544 — tokens, apps de cliente, permisos. Incluye el 501 y el 522, los de token caducado. */\nexport class AuthError extends PlanVortexError {}\n/** 601-612 — el usuario final. */\nexport class UserError extends PlanVortexError {}\n/** 700-715 — cuentas sociales: desconectada, sin permisos en la red, sin refrescar. */\nexport class AccountError extends PlanVortexError {}\n/** 800-810 — ficheros: formato no admitido, demasiado grande, conversión fallida. */\nexport class FileError extends PlanVortexError {}\n/** 900-960 — publicaciones, incluidos los límites por red (caracteres, imágenes, duración). */\nexport class PublicationError extends PlanVortexError {}\n/** 1100-1111 — organizaciones, y el token temporal atado a una sola de ellas (1101). */\nexport class OrganizationError extends PlanVortexError {}\n/**\n * 1300-1307 y 1400-1408 — el cupo del plan, del cliente o de la organización.\n *\n * Es el error que un integrador **sí** quiere distinguir: no se arregla reintentando, se arregla\n * cambiando de plan. Por eso los dos rangos comparten clase.\n */\nexport class PlanLimitError extends PlanVortexError {}\n/** 1500-1512 — conversaciones, mensajes y plantillas. Exige plan de pago. */\nexport class MessagingError extends PlanVortexError {}\n/** 1600-1601 — contactos. */\nexport class ContactError extends PlanVortexError {}\n/** 2000-2099 — catálogos y productos (sólo Facebook e Instagram). */\nexport class ProductError extends PlanVortexError {}\n/** 2100-2199 — planes de publicaciones generados con IA. */\nexport class AiPlanError extends PlanVortexError {}\n/** 2200-2299 — integraciones: Google Drive, RSS. */\nexport class IntegrationError extends PlanVortexError {}\n\n/**\n * La petición no llegó a tener respuesta: DNS, conexión rechazada, socket cortado o timeout.\n *\n * No lleva código del catálogo porque el servidor nunca llegó a opinar.\n */\nexport class PlanVortexConnectionError extends PlanVortexError {\n /** `true` si lo que se agotó fue nuestro propio timeout, no la red. */\n readonly timeout: boolean;\n\n constructor(message: string, options: PlanVortexErrorOptions & { timeout?: boolean } = {}) {\n super(NO_ERROR_CODE, message, { ...options, family: \"connection\" });\n this.timeout = options.timeout ?? false;\n }\n}\n\n/**\n * `POST /oauth/token` rechazó las credenciales.\n *\n * Es el ÚNICO sitio del API con forma de error distinta: `{error, error_description}` de OAuth2, no\n * el `{code, message, data}` de todo lo demás. Y por eso el `code` es {@link NO_ERROR_CODE}: el\n * servidor tiene códigos para esto (538-541) pero **no los manda en el cuerpo**, así que ponerlos\n * aquí sería inventarse algo que nadie dijo. Lo que sí viaja es `oauthError`.\n */\nexport class PlanVortexAuthenticationError extends PlanVortexError {\n /** `invalid_client`, `invalid_request`, `unsupported_grant_type`, `slow_down` o `server_error`. */\n readonly oauthError: string;\n\n constructor(oauthError: string, description: string, options: PlanVortexErrorOptions = {}) {\n super(NO_ERROR_CODE, description, { ...options, family: \"oauth\" });\n this.oauthError = oauthError;\n }\n}\n\n/**\n * La librería está mal configurada y no ha llegado a salir de casa: sin credenciales, o instanciada\n * en un navegador (§ trampa 9 del roadmap).\n */\nexport class PlanVortexConfigError extends PlanVortexError {\n constructor(message: string) {\n super(NO_ERROR_CODE, message, { family: \"config\" });\n }\n}\n\n/** La familia a la que pertenece un código, o `undefined` si cae fuera del catálogo conocido. */\nexport function errorFamilyForCode(code: number): string | undefined {\n return PLANVORTEX_ERROR_RANGES.find((range) => code >= range.from && code <= range.to)?.family;\n}\n\n/**\n * Familia -> clase. Las que faltan —`general`, `role`, `payment` y cualquier rango nuevo— caen a\n * propósito en la clase base: existen en el servidor pero no son superficie de integración, y darles\n * clase propia sería prometer un `instanceof` que luego habría que mantener.\n */\nconst FAMILY_CLASSES: Record<string, typeof PlanVortexError> = {\n auth: AuthError,\n user: UserError,\n account: AccountError,\n file: FileError,\n publication: PublicationError,\n organization: OrganizationError,\n plan_limit: PlanLimitError,\n messaging: MessagingError,\n contact: ContactError,\n product: ProductError,\n ai_plan: AiPlanError,\n integration: IntegrationError,\n};\n\n/** El cuerpo de error del API: `{code, message, data}`. */\nexport interface ApiErrorBody {\n code: number;\n message?: string;\n data?: Record<string, unknown>;\n}\n\nfunction isApiErrorBody(body: unknown): body is ApiErrorBody {\n return typeof body === \"object\" && body !== null && typeof (body as ApiErrorBody).code === \"number\";\n}\n\n/**\n * Convierte una respuesta de error en la clase que le toca.\n *\n * Un cuerpo sin `code` —un 502 de un proxy, la página HTML de un balanceador— no es un error de\n * dominio: sale como clase base con `family: \"http\"` y el cuerpo entero en `data`, que es además lo\n * que necesita `auth.ts` para reconocer el `{error, error_description}` de OAuth2.\n */\nexport function createErrorFromResponse(input: {\n body: unknown;\n status: number;\n requestId?: string | undefined;\n retryAfter?: number | undefined;\n}): PlanVortexError {\n const options: PlanVortexErrorOptions = {\n status: input.status,\n ...(input.requestId === undefined ? {} : { requestId: input.requestId }),\n ...(input.retryAfter === undefined ? {} : { retryAfter: input.retryAfter }),\n };\n\n if (isApiErrorBody(input.body)) {\n const family = errorFamilyForCode(input.body.code);\n const ErrorClass = (family === undefined ? undefined : FAMILY_CLASSES[family]) ?? PlanVortexError;\n return new ErrorClass(input.body.code, input.body.message ?? \"PlanVortex error\", {\n ...options,\n data: input.body.data ?? {},\n });\n }\n\n return new PlanVortexError(NO_ERROR_CODE, `HTTP ${input.status}`, {\n ...options,\n family: \"http\",\n data:\n typeof input.body === \"object\" && input.body !== null\n ? (input.body as Record<string, unknown>)\n : { body: input.body },\n });\n}\n\n/** ¿Es un error de esta librería? Útil en un `catch` donde no apetece importar la clase. */\nexport function isPlanVortexError(error: unknown): error is PlanVortexError {\n return error instanceof PlanVortexError;\n}\n\n/**\n * ¿Dice este error que el token ya no sirve? (los códigos 501 y 522, los dos dentro de un 400).\n *\n * Es lo que dispara el único reintento con token nuevo del cliente.\n */\nexport function isTokenError(error: unknown): boolean {\n return isPlanVortexError(error) && TOKEN_ERROR_CODES.includes(error.code);\n}\n"]}
@@ -698,6 +698,8 @@ interface paths {
698
698
  * **It answers 200 even when it fails.** The result carries `errorCode` and `errorMsg` instead of an error body, because the browser lands here from a redirect and a raw 400 would be a broken page. Check `errorCode`: empty means everything went well.
699
699
  *
700
700
  * **An app cannot call this** — it needs a user token or a temporal connect token (error 519 otherwise). See `GET /organizations/{id_organization}/temporal_connect_token`.
701
+ *
702
+ * **A temporal connect token is spent here.** Once this call succeeds, that token cannot connect anything else and answers error 543; the `enable` calls that finish the same connection still work until it expires. And if the token was issued for one network, calling this for another answers error 544.
701
703
  */
702
704
  get: operations["connectAccount"];
703
705
  put?: never;
@@ -1297,6 +1299,8 @@ interface paths {
1297
1299
  * **A network that cannot produce a link simply does not appear.** That is a legitimate answer, not a failure: it is what happens with `discord` in an organization that has not saved its own bot credentials yet (see `PUT /organizations/{id_organization}/social_credentials/{social_network}`).
1298
1300
  *
1299
1301
  * **An app cannot call this.** Connecting a social account is an OAuth flow with a person in front of it, so this endpoint only accepts a user token or a temporal connect token; with app credentials it answers error 519. The way an integration does it is to issue a temporal connect token with `GET /organizations/{id_organization}/temporal_connect_token` and hand it to its end user.
1302
+ *
1303
+ * **Read `authorization`, not `link`.** Nine of the ten networks are `redirect` and you send the person to `link`. **WhatsApp is not a URL at all**: its sign-up is Meta's Embedded Signup, a popup you raise with the Facebook JavaScript SDK, so its `link` is an empty string and everything you need to open that popup travels in `authorization`. A client that loops over the list and redirects to `link` sends its user to its own page.
1300
1304
  */
1301
1305
  get: operations["getConnectLinks"];
1302
1306
  put?: never;
@@ -2028,13 +2032,17 @@ interface paths {
2028
2032
  *
2029
2033
  * It exists because **an app cannot connect accounts**: `connect_links` and `account-connect` refuse app credentials with error 519, since authorizing Instagram is an OAuth flow with a human in front of it. The shape of the integration is therefore:
2030
2034
  *
2031
- * 1. Your server asks for this token — **this endpoint is the one that requires app credentials**, and a user token is refused. So is a temporal connect token: it cannot renew itself, which is what keeps the one-hour life a real limit rather than the first link of a chain.
2035
+ * 1. Your server asks for this token — **this endpoint is the one that requires app credentials**, and a user token is refused. So is a temporal connect token: it cannot renew itself, which is what keeps its life a real limit rather than the first link of a chain.
2032
2036
  * 2. You send your end user to the `url` that comes back, by redirect or in an iframe. The bare
2033
2037
  * `token` comes back too, so a server-side client can authenticate with it directly instead of
2034
2038
  * parsing it out of that URL.
2035
2039
  * 3. With that token the browser completes `connect_links` and `account-connect`.
2036
2040
  *
2037
- * The token lasts **one hour**, is tied to **this** organization — using it against another answers error 1101 — and carries only two permissions: create accounts and read the organization. It is the piece designed for a browser, and the only credential of ours that belongs there.
2041
+ * The token lasts **fifteen minutes**, is tied to **this** organization — using it against another answers error 1101 — and carries only two permissions: create accounts and read the organization. It is the piece designed for a browser, and the only credential of ours that belongs there.
2042
+ *
2043
+ * **It connects once.** As soon as an `account-connect` succeeds, the token stops being able to connect anything else and answers error 543; the `enable` calls that finish that same connection keep working until it expires. Issue a new one per connection — they are free and immediate.
2044
+ *
2045
+ * **If you pass `social_network`, the token is bound to that network** and will not connect any other (error 544). Leave it out to let the person pick.
2038
2046
  *
2039
2047
  * If you send `redirect_uri` it has to be one of the app's `redirect_urls`, or the call answers error 532.
2040
2048
  */
@@ -2471,10 +2479,35 @@ interface components {
2471
2479
  /** @description `default`, or a locale such as `es_ES`. */
2472
2480
  locale?: string;
2473
2481
  }[];
2482
+ /**
2483
+ * @description **How** an account of this network is authorized, which is not always "send the user to this URL".
2484
+ *
2485
+ * Nine of the ten networks are `redirect`: open `link` and the network sends the person back to PlanVortex with a code. **WhatsApp is not.** Its sign-up is Meta's *Embedded Signup*: a popup raised by the Facebook JavaScript SDK from your own page, which returns — over `postMessage` — session data (`waba_id`, `phone_number_id`) that no query string carries. Its `link` is therefore an empty string.
2486
+ *
2487
+ * Branch on `authorization.type`, never on whether `link` is empty.
2488
+ */
2489
+ AccountsSocialAuthorizationMethod: {
2490
+ /** @description `meta_embedded_signup` only. Goes to `FB.init({appId})`. It is the same Meta app whose secret PlanVortex uses to exchange the code afterwards. */
2491
+ app_id?: string;
2492
+ /** @description `meta_embedded_signup` only. Goes to `FB.login(cb, {config_id})` — the Embedded Signup configuration. */
2493
+ config_id?: string;
2494
+ /** @description `meta_embedded_signup` only. Goes to `extras.featureType`. */
2495
+ feature_type?: string;
2496
+ /** @description `meta_embedded_signup` only. Goes to `FB.init({version})`. This is the JavaScript SDK version, not the Graph version PlanVortex calls server-side: they move independently. */
2497
+ graph_version?: string;
2498
+ /** @description `meta_embedded_signup` only. Goes to `extras.sessionInfoVersion`. */
2499
+ session_info_version?: string;
2500
+ /**
2501
+ * @description `redirect`: send the user to `link`. `meta_embedded_signup`: open the Meta popup with the fields below.
2502
+ * @enum {string}
2503
+ */
2504
+ type: "redirect" | "meta_embedded_signup";
2505
+ };
2474
2506
  AccountsSocialLinksList: {
2475
2507
  /** @description One entry per network that can be connected right now. */
2476
2508
  links: {
2477
- /** @description The network's authorization URL. Send the user there. */
2509
+ authorization: components["schemas"]["AccountsSocialAuthorizationMethod"];
2510
+ /** @description The network's authorization URL. Send the user there. **Empty when `authorization.type` is not `redirect`** — WhatsApp has no URL to give. */
2478
2511
  link: string;
2479
2512
  social_network: components["schemas"]["SocialNetwork"];
2480
2513
  }[];
@@ -3328,7 +3361,7 @@ interface components {
3328
3361
  * The catalogue grows with the product, so treat an unknown `code` as a generic failure instead of rejecting it.
3329
3362
  */
3330
3363
  Error: {
3331
- /** @description PlanVortex error code. Ranges: 500-542 auth, tokens and client apps · 601-612 user · 700-715 social accounts · 800-810 files · 900-960 publications · 1000-1003 general · 1100-1111 organizations · 1200-1207 roles · 1300-1307 client plan · 1400-1408 organization plan · 1500-1512 messaging · 1600-1601 contacts · 1900-1906 payments · 2000-2099 products · 2100-2199 AI plans · 2200-2299 integrations. */
3364
+ /** @description PlanVortex error code. Ranges: 500-544 auth, tokens and client apps · 601-612 user · 700-715 social accounts · 800-810 files · 900-960 publications · 1000-1003 general · 1100-1111 organizations · 1200-1207 roles · 1300-1307 client plan · 1400-1408 organization plan · 1500-1512 messaging · 1600-1601 contacts · 1900-1906 payments · 2000-2099 products · 2100-2199 AI plans · 2200-2299 integrations. */
3332
3365
  code: number;
3333
3366
  /** @description Extra context attached to the error, when there is any. */
3334
3367
  data?: {
@@ -6245,6 +6278,8 @@ interface operations {
6245
6278
  * | Code | Meaning |
6246
6279
  * | --- | --- |
6247
6280
  * | `519` | This endpoint does not accept app credentials |
6281
+ * | `543` | This temporal connect token has already connected an account. Issue a new one |
6282
+ * | `544` | This temporal connect token was issued for a different social network |
6248
6283
  * | `1101` | Invalid organization, or a temporal token for a different one |
6249
6284
  */
6250
6285
  400: {
@@ -6610,6 +6645,7 @@ interface operations {
6610
6645
  * | `700` | The account has no usable token: it has to be connected again |
6611
6646
  * | `706` | The organization has no account slots left in its plan |
6612
6647
  * | `519` | This endpoint does not accept app credentials |
6648
+ * | `544` | This temporal connect token was issued for a different social network |
6613
6649
  */
6614
6650
  400: {
6615
6651
  headers: {
@@ -9683,7 +9719,7 @@ interface operations {
9683
9719
  query?: {
9684
9720
  /** @description Where the user comes back after connecting. Has to be one of the app's `redirect_urls` (error 532). */
9685
9721
  redirect_uri?: string;
9686
- /** @description Network the user is going to connect. It travels inside the returned URL. */
9722
+ /** @description Network the user is going to connect. It travels inside the returned URL **and inside the token itself**, so the token will only connect that network (error 544 otherwise). A network outside the allowed list is rejected here with error 702. */
9687
9723
  social_network?: components["schemas"]["SocialNetwork"];
9688
9724
  };
9689
9725
  header?: never;
@@ -9704,7 +9740,7 @@ interface operations {
9704
9740
  "application/json": {
9705
9741
  /**
9706
9742
  * Format: date-time
9707
- * @description When the token stops working. One hour after it was issued.
9743
+ * @description When the token stops working. Fifteen minutes after it was issued.
9708
9744
  */
9709
9745
  expires_at: string;
9710
9746
  /** @description The same token, on its own. This is what you pass to a client that authenticates with a temporal token; do not parse it out of `url`. */
@@ -9721,6 +9757,7 @@ interface operations {
9721
9757
  * | --- | --- |
9722
9758
  * | `514` | This endpoint needs app credentials: neither a user token nor a temporal connect token can issue one |
9723
9759
  * | `532` | `redirect_uri` is not one of the app's registered `redirect_urls` |
9760
+ * | `702` | `social_network` is not one of the networks PlanVortex supports |
9724
9761
  * | `1101` | Invalid organization |
9725
9762
  */
9726
9763
  400: {
@@ -10663,15 +10700,26 @@ type PersistentMenu = Schemas["AccountsPersistentMenu"];
10663
10700
  *
10664
10701
  * Las dos cosas valen: `url` es el camino alojado —se redirige al usuario y PlanVortex se encarga
10665
10702
  * de todo—, y `token` es el mismo credencial suelto, para pasarselo a `pv.asTemporalToken(token)`
10666
- * y conducir el flujo desde el front propio. Caduca a la hora (`expires_at`) y sirve para UNA
10667
- * organizacion.
10703
+ * y conducir el flujo desde el front propio. Caduca a los quince minutos (`expires_at`), sirve para
10704
+ * UNA organizacion y se gasta en cuanto conecta una cuenta.
10668
10705
  */
10669
10706
  type ConnectToken = Operations["createTemporalConnectToken"]["responses"][200]["content"]["application/json"];
10670
10707
  /**
10671
- * El enlace de autorizacion de UNA red. Se manda al usuario ahi y la red lo devuelve al panel de
10672
- * PlanVortex, que es quien completa la conexion.
10708
+ * Como se conecta UNA red. Casi siempre es un enlace: se manda al usuario ahi y la red lo devuelve
10709
+ * al panel de PlanVortex, que es quien completa la conexion.
10710
+ *
10711
+ * **Casi. Mira `authorization.type` y no si `link` esta vacio.** WhatsApp no tiene URL de
10712
+ * autorizacion: su alta es el Embedded Signup de Meta, un popup que levanta el SDK de JavaScript de
10713
+ * Facebook desde tu pagina y que devuelve por `postMessage` datos —el `waba_id`, el
10714
+ * `phone_number_id`— que no caben en una query string. Su `link` es cadena vacia y los parametros
10715
+ * del popup (`app_id`, `config_id`, `graph_version`...) viajan en `authorization`.
10673
10716
  */
10674
10717
  type ConnectLink = Schemas["AccountsSocialLinksList"]["links"][number];
10718
+ /**
10719
+ * Con que se autoriza una red: `redirect` (las otras nueve) o `meta_embedded_signup` (WhatsApp).
10720
+ * Se saca de {@link ConnectLink} y esta aqui para poder nombrarlo en un `switch`.
10721
+ */
10722
+ type SocialAuthorizationMethod = ConnectLink["authorization"];
10675
10723
  /**
10676
10724
  * Lo que dejo una autorizacion: las cuentas que se pueden dar de alta.
10677
10725
  *
@@ -11181,7 +11229,7 @@ declare class PlanVortexError extends Error {
11181
11229
  readonly retryAfter: number | undefined;
11182
11230
  constructor(code: number, message: string, options?: PlanVortexErrorOptions);
11183
11231
  }
11184
- /** 500-542 — tokens, apps de cliente, permisos. Incluye el 501 y el 522, los de token caducado. */
11232
+ /** 500-544 — tokens, apps de cliente, permisos. Incluye el 501 y el 522, los de token caducado. */
11185
11233
  declare class AuthError extends PlanVortexError {
11186
11234
  }
11187
11235
  /** 601-612 — el usuario final. */
@@ -11523,4 +11571,4 @@ interface PlanVortexWebhooksOptions {
11523
11571
  */
11524
11572
  declare function planvortexWebhooks(options: PlanVortexWebhooksOptions): (request: WebhookRequestLike, response: WebhookResponseLike, next: (error?: unknown) => void) => void;
11525
11573
 
11526
- export { type Product as $, type Account as A, type IntegrationProvider as B, type ConnectLink as C, type Dashboard as D, type EnableResult as E, type Integration as F, type IntegrationConnectRequest as G, type IntegrationUpdate as H, type IntegrationProviderName as I, type IntegrationPickerConfig as J, type MessageTemplate as K, type Conversation as L, type MetricName as M, type ConversationTotals as N, type Message as O, type Paginated as P, type MessageInput as Q, type Client as R, type SocialNetwork as S, type TopPublicationsResult as T, type Organization as U, type AiSettings as V, type ClientWithOrganizations as W, type PlanData as X, type ConnectToken as Y, type AiContext as Z, type SocialCredentialsInput as _, type ConnectResult as a, type RssConfig as a$, type ProductInput as a0, type ProductCatalog as a1, type ProductCatalogInput as a2, type PublicationInput as a3, type PublicationState as a4, type PublicationStats as a5, type PublicationStatsHistory as a6, type Upload as a7, AccountError as a8, type AccountMetricRow as a9, type MessageChange as aA, type MessageOptions as aB, type MessageType as aC, MessagingError as aD, type MetricRow as aE, NO_ERROR_CODE as aF, type components as aG, type operations as aH, type paths as aI, type webhooks as aJ, type OpenEnum as aK, OrganizationError as aL, PLANVORTEX_ERROR_RANGES as aM, PlanLimitError as aN, PlanVortexAuthenticationError as aO, PlanVortexConfigError as aP, PlanVortexConnectionError as aQ, PlanVortexError as aR, type PlanVortexErrorOptions as aS, type PlanVortexErrorRange as aT, ProductError as aU, PublicationError as aV, type PublicationErrorDetail as aW, type PublicationMetrics as aX, type PublicationStatsPoint as aY, type PublicationType as aZ, type PublicationsSummary as a_, type AccountStateChange as aa, type AccountWebhookChangeBase as ab, type AccountWithError as ac, type AiPlanCostEstimate as ad, AiPlanError as ae, type AiPlanOptions as af, type AiPlanOptionsInput as ag, type AiPlanState as ah, type ApiErrorBody as ai, type AspectRatios as aj, AuthError as ak, type ClientPlan as al, type CommentAuthor as am, type CommentChange as an, type ContactChannel as ao, ContactError as ap, type DashboardAiPlanRef as aq, type DashboardPublicationRef as ar, type DashboardRange as as, type EngagementBase as at, FileError as au, type FileFormat as av, type FileProperties as aw, type FileType as ax, IntegrationError as ay, type IntegrationErrorChange as az, type AccountMetrics as b, type SocialCredentials as b0, type SocialIdentifier as b1, type SocialIdentifierInput as b2, type SocialLimitsMap as b3, TOKEN_ERROR_CODES as b4, type TopPublication as b5, type UnknownWebhookChange as b6, UserError as b7, type WebhookAlgorithm as b8, type WebhookChange as b9, handleWebhookRequest as bA, isAccountStateChange as bB, isCommentChange as bC, isIntegrationErrorChange as bD, isMessageChange as bE, parseWebhookPayload as bF, planvortexWebhooks as bG, verifyWebhookSignature as bH, type WebhookEvent as ba, type WithAccount as bb, type WithPublication as bc, account as bd, accountId as be, errorFamilyForCode as bf, isPlanVortexError as bg, isTokenError as bh, messageContact as bi, messageContactId as bj, messageDirection as bk, messageFileIds as bl, messageFiles as bm, publication as bn, publicationId as bo, type HandleWebhookRequestOptions as bp, type PlanVortexWebhooksOptions as bq, type RawWebhookBody as br, type VerifyWebhookSignatureOptions as bs, WEBHOOK_EVENTS as bt, WEBHOOK_SIGNATURE_HEADERS as bu, WebhookBodyError as bv, type WebhookHeaders as bw, type WebhookRequestLike as bx, type WebhookResponseLike as by, WebhookSignatureError as bz, type PersistentMenu as c, type Publication as d, type AiPlanCreateRequest as e, type AiPlanCreateResult as f, type AiPlan as g, type ClientApp as h, type ClientAppInput as i, type SocialCapabilities as j, type CommentActions as k, type SocialLimits as l, type PublicationLimits as m, type AspectRatiosByNetwork as n, type CommentNetwork as o, type Comment as p, type CommentThread as q, type CommentReplyResult as r, type ContactExtraData as s, type Contact as t, type ContactCreate as u, type ContactUpdate as v, type DashboardMetricsResult as w, type PublicationsSummaryResult as x, type PublicationsStatsResult as y, type PlanUse as z };
11574
+ export { type Product as $, type Account as A, type IntegrationProvider as B, type ConnectLink as C, type Dashboard as D, type EnableResult as E, type Integration as F, type IntegrationConnectRequest as G, type IntegrationUpdate as H, type IntegrationProviderName as I, type IntegrationPickerConfig as J, type MessageTemplate as K, type Conversation as L, type MetricName as M, type ConversationTotals as N, type Message as O, type Paginated as P, type MessageInput as Q, type Client as R, type SocialNetwork as S, type TopPublicationsResult as T, type Organization as U, type AiSettings as V, type ClientWithOrganizations as W, type PlanData as X, type ConnectToken as Y, type AiContext as Z, type SocialCredentialsInput as _, type ConnectResult as a, type RssConfig as a$, type ProductInput as a0, type ProductCatalog as a1, type ProductCatalogInput as a2, type PublicationInput as a3, type PublicationState as a4, type PublicationStats as a5, type PublicationStatsHistory as a6, type Upload as a7, AccountError as a8, type AccountMetricRow as a9, type MessageChange as aA, type MessageOptions as aB, type MessageType as aC, MessagingError as aD, type MetricRow as aE, NO_ERROR_CODE as aF, type components as aG, type operations as aH, type paths as aI, type webhooks as aJ, type OpenEnum as aK, OrganizationError as aL, PLANVORTEX_ERROR_RANGES as aM, PlanLimitError as aN, PlanVortexAuthenticationError as aO, PlanVortexConfigError as aP, PlanVortexConnectionError as aQ, PlanVortexError as aR, type PlanVortexErrorOptions as aS, type PlanVortexErrorRange as aT, ProductError as aU, PublicationError as aV, type PublicationErrorDetail as aW, type PublicationMetrics as aX, type PublicationStatsPoint as aY, type PublicationType as aZ, type PublicationsSummary as a_, type AccountStateChange as aa, type AccountWebhookChangeBase as ab, type AccountWithError as ac, type AiPlanCostEstimate as ad, AiPlanError as ae, type AiPlanOptions as af, type AiPlanOptionsInput as ag, type AiPlanState as ah, type ApiErrorBody as ai, type AspectRatios as aj, AuthError as ak, type ClientPlan as al, type CommentAuthor as am, type CommentChange as an, type ContactChannel as ao, ContactError as ap, type DashboardAiPlanRef as aq, type DashboardPublicationRef as ar, type DashboardRange as as, type EngagementBase as at, FileError as au, type FileFormat as av, type FileProperties as aw, type FileType as ax, IntegrationError as ay, type IntegrationErrorChange as az, type AccountMetrics as b, type SocialAuthorizationMethod as b0, type SocialCredentials as b1, type SocialIdentifier as b2, type SocialIdentifierInput as b3, type SocialLimitsMap as b4, TOKEN_ERROR_CODES as b5, type TopPublication as b6, type UnknownWebhookChange as b7, UserError as b8, type WebhookAlgorithm as b9, WebhookSignatureError as bA, handleWebhookRequest as bB, isAccountStateChange as bC, isCommentChange as bD, isIntegrationErrorChange as bE, isMessageChange as bF, parseWebhookPayload as bG, planvortexWebhooks as bH, verifyWebhookSignature as bI, type WebhookChange as ba, type WebhookEvent as bb, type WithAccount as bc, type WithPublication as bd, account as be, accountId as bf, errorFamilyForCode as bg, isPlanVortexError as bh, isTokenError as bi, messageContact as bj, messageContactId as bk, messageDirection as bl, messageFileIds as bm, messageFiles as bn, publication as bo, publicationId as bp, type HandleWebhookRequestOptions as bq, type PlanVortexWebhooksOptions as br, type RawWebhookBody as bs, type VerifyWebhookSignatureOptions as bt, WEBHOOK_EVENTS as bu, WEBHOOK_SIGNATURE_HEADERS as bv, WebhookBodyError as bw, type WebhookHeaders as bx, type WebhookRequestLike as by, type WebhookResponseLike as bz, type PersistentMenu as c, type Publication as d, type AiPlanCreateRequest as e, type AiPlanCreateResult as f, type AiPlan as g, type ClientApp as h, type ClientAppInput as i, type SocialCapabilities as j, type CommentActions as k, type SocialLimits as l, type PublicationLimits as m, type AspectRatiosByNetwork as n, type CommentNetwork as o, type Comment as p, type CommentThread as q, type CommentReplyResult as r, type ContactExtraData as s, type Contact as t, type ContactCreate as u, type ContactUpdate as v, type DashboardMetricsResult as w, type PublicationsSummaryResult as x, type PublicationsStatsResult as y, type PlanUse as z };
@@ -698,6 +698,8 @@ interface paths {
698
698
  * **It answers 200 even when it fails.** The result carries `errorCode` and `errorMsg` instead of an error body, because the browser lands here from a redirect and a raw 400 would be a broken page. Check `errorCode`: empty means everything went well.
699
699
  *
700
700
  * **An app cannot call this** — it needs a user token or a temporal connect token (error 519 otherwise). See `GET /organizations/{id_organization}/temporal_connect_token`.
701
+ *
702
+ * **A temporal connect token is spent here.** Once this call succeeds, that token cannot connect anything else and answers error 543; the `enable` calls that finish the same connection still work until it expires. And if the token was issued for one network, calling this for another answers error 544.
701
703
  */
702
704
  get: operations["connectAccount"];
703
705
  put?: never;
@@ -1297,6 +1299,8 @@ interface paths {
1297
1299
  * **A network that cannot produce a link simply does not appear.** That is a legitimate answer, not a failure: it is what happens with `discord` in an organization that has not saved its own bot credentials yet (see `PUT /organizations/{id_organization}/social_credentials/{social_network}`).
1298
1300
  *
1299
1301
  * **An app cannot call this.** Connecting a social account is an OAuth flow with a person in front of it, so this endpoint only accepts a user token or a temporal connect token; with app credentials it answers error 519. The way an integration does it is to issue a temporal connect token with `GET /organizations/{id_organization}/temporal_connect_token` and hand it to its end user.
1302
+ *
1303
+ * **Read `authorization`, not `link`.** Nine of the ten networks are `redirect` and you send the person to `link`. **WhatsApp is not a URL at all**: its sign-up is Meta's Embedded Signup, a popup you raise with the Facebook JavaScript SDK, so its `link` is an empty string and everything you need to open that popup travels in `authorization`. A client that loops over the list and redirects to `link` sends its user to its own page.
1300
1304
  */
1301
1305
  get: operations["getConnectLinks"];
1302
1306
  put?: never;
@@ -2028,13 +2032,17 @@ interface paths {
2028
2032
  *
2029
2033
  * It exists because **an app cannot connect accounts**: `connect_links` and `account-connect` refuse app credentials with error 519, since authorizing Instagram is an OAuth flow with a human in front of it. The shape of the integration is therefore:
2030
2034
  *
2031
- * 1. Your server asks for this token — **this endpoint is the one that requires app credentials**, and a user token is refused. So is a temporal connect token: it cannot renew itself, which is what keeps the one-hour life a real limit rather than the first link of a chain.
2035
+ * 1. Your server asks for this token — **this endpoint is the one that requires app credentials**, and a user token is refused. So is a temporal connect token: it cannot renew itself, which is what keeps its life a real limit rather than the first link of a chain.
2032
2036
  * 2. You send your end user to the `url` that comes back, by redirect or in an iframe. The bare
2033
2037
  * `token` comes back too, so a server-side client can authenticate with it directly instead of
2034
2038
  * parsing it out of that URL.
2035
2039
  * 3. With that token the browser completes `connect_links` and `account-connect`.
2036
2040
  *
2037
- * The token lasts **one hour**, is tied to **this** organization — using it against another answers error 1101 — and carries only two permissions: create accounts and read the organization. It is the piece designed for a browser, and the only credential of ours that belongs there.
2041
+ * The token lasts **fifteen minutes**, is tied to **this** organization — using it against another answers error 1101 — and carries only two permissions: create accounts and read the organization. It is the piece designed for a browser, and the only credential of ours that belongs there.
2042
+ *
2043
+ * **It connects once.** As soon as an `account-connect` succeeds, the token stops being able to connect anything else and answers error 543; the `enable` calls that finish that same connection keep working until it expires. Issue a new one per connection — they are free and immediate.
2044
+ *
2045
+ * **If you pass `social_network`, the token is bound to that network** and will not connect any other (error 544). Leave it out to let the person pick.
2038
2046
  *
2039
2047
  * If you send `redirect_uri` it has to be one of the app's `redirect_urls`, or the call answers error 532.
2040
2048
  */
@@ -2471,10 +2479,35 @@ interface components {
2471
2479
  /** @description `default`, or a locale such as `es_ES`. */
2472
2480
  locale?: string;
2473
2481
  }[];
2482
+ /**
2483
+ * @description **How** an account of this network is authorized, which is not always "send the user to this URL".
2484
+ *
2485
+ * Nine of the ten networks are `redirect`: open `link` and the network sends the person back to PlanVortex with a code. **WhatsApp is not.** Its sign-up is Meta's *Embedded Signup*: a popup raised by the Facebook JavaScript SDK from your own page, which returns — over `postMessage` — session data (`waba_id`, `phone_number_id`) that no query string carries. Its `link` is therefore an empty string.
2486
+ *
2487
+ * Branch on `authorization.type`, never on whether `link` is empty.
2488
+ */
2489
+ AccountsSocialAuthorizationMethod: {
2490
+ /** @description `meta_embedded_signup` only. Goes to `FB.init({appId})`. It is the same Meta app whose secret PlanVortex uses to exchange the code afterwards. */
2491
+ app_id?: string;
2492
+ /** @description `meta_embedded_signup` only. Goes to `FB.login(cb, {config_id})` — the Embedded Signup configuration. */
2493
+ config_id?: string;
2494
+ /** @description `meta_embedded_signup` only. Goes to `extras.featureType`. */
2495
+ feature_type?: string;
2496
+ /** @description `meta_embedded_signup` only. Goes to `FB.init({version})`. This is the JavaScript SDK version, not the Graph version PlanVortex calls server-side: they move independently. */
2497
+ graph_version?: string;
2498
+ /** @description `meta_embedded_signup` only. Goes to `extras.sessionInfoVersion`. */
2499
+ session_info_version?: string;
2500
+ /**
2501
+ * @description `redirect`: send the user to `link`. `meta_embedded_signup`: open the Meta popup with the fields below.
2502
+ * @enum {string}
2503
+ */
2504
+ type: "redirect" | "meta_embedded_signup";
2505
+ };
2474
2506
  AccountsSocialLinksList: {
2475
2507
  /** @description One entry per network that can be connected right now. */
2476
2508
  links: {
2477
- /** @description The network's authorization URL. Send the user there. */
2509
+ authorization: components["schemas"]["AccountsSocialAuthorizationMethod"];
2510
+ /** @description The network's authorization URL. Send the user there. **Empty when `authorization.type` is not `redirect`** — WhatsApp has no URL to give. */
2478
2511
  link: string;
2479
2512
  social_network: components["schemas"]["SocialNetwork"];
2480
2513
  }[];
@@ -3328,7 +3361,7 @@ interface components {
3328
3361
  * The catalogue grows with the product, so treat an unknown `code` as a generic failure instead of rejecting it.
3329
3362
  */
3330
3363
  Error: {
3331
- /** @description PlanVortex error code. Ranges: 500-542 auth, tokens and client apps · 601-612 user · 700-715 social accounts · 800-810 files · 900-960 publications · 1000-1003 general · 1100-1111 organizations · 1200-1207 roles · 1300-1307 client plan · 1400-1408 organization plan · 1500-1512 messaging · 1600-1601 contacts · 1900-1906 payments · 2000-2099 products · 2100-2199 AI plans · 2200-2299 integrations. */
3364
+ /** @description PlanVortex error code. Ranges: 500-544 auth, tokens and client apps · 601-612 user · 700-715 social accounts · 800-810 files · 900-960 publications · 1000-1003 general · 1100-1111 organizations · 1200-1207 roles · 1300-1307 client plan · 1400-1408 organization plan · 1500-1512 messaging · 1600-1601 contacts · 1900-1906 payments · 2000-2099 products · 2100-2199 AI plans · 2200-2299 integrations. */
3332
3365
  code: number;
3333
3366
  /** @description Extra context attached to the error, when there is any. */
3334
3367
  data?: {
@@ -6245,6 +6278,8 @@ interface operations {
6245
6278
  * | Code | Meaning |
6246
6279
  * | --- | --- |
6247
6280
  * | `519` | This endpoint does not accept app credentials |
6281
+ * | `543` | This temporal connect token has already connected an account. Issue a new one |
6282
+ * | `544` | This temporal connect token was issued for a different social network |
6248
6283
  * | `1101` | Invalid organization, or a temporal token for a different one |
6249
6284
  */
6250
6285
  400: {
@@ -6610,6 +6645,7 @@ interface operations {
6610
6645
  * | `700` | The account has no usable token: it has to be connected again |
6611
6646
  * | `706` | The organization has no account slots left in its plan |
6612
6647
  * | `519` | This endpoint does not accept app credentials |
6648
+ * | `544` | This temporal connect token was issued for a different social network |
6613
6649
  */
6614
6650
  400: {
6615
6651
  headers: {
@@ -9683,7 +9719,7 @@ interface operations {
9683
9719
  query?: {
9684
9720
  /** @description Where the user comes back after connecting. Has to be one of the app's `redirect_urls` (error 532). */
9685
9721
  redirect_uri?: string;
9686
- /** @description Network the user is going to connect. It travels inside the returned URL. */
9722
+ /** @description Network the user is going to connect. It travels inside the returned URL **and inside the token itself**, so the token will only connect that network (error 544 otherwise). A network outside the allowed list is rejected here with error 702. */
9687
9723
  social_network?: components["schemas"]["SocialNetwork"];
9688
9724
  };
9689
9725
  header?: never;
@@ -9704,7 +9740,7 @@ interface operations {
9704
9740
  "application/json": {
9705
9741
  /**
9706
9742
  * Format: date-time
9707
- * @description When the token stops working. One hour after it was issued.
9743
+ * @description When the token stops working. Fifteen minutes after it was issued.
9708
9744
  */
9709
9745
  expires_at: string;
9710
9746
  /** @description The same token, on its own. This is what you pass to a client that authenticates with a temporal token; do not parse it out of `url`. */
@@ -9721,6 +9757,7 @@ interface operations {
9721
9757
  * | --- | --- |
9722
9758
  * | `514` | This endpoint needs app credentials: neither a user token nor a temporal connect token can issue one |
9723
9759
  * | `532` | `redirect_uri` is not one of the app's registered `redirect_urls` |
9760
+ * | `702` | `social_network` is not one of the networks PlanVortex supports |
9724
9761
  * | `1101` | Invalid organization |
9725
9762
  */
9726
9763
  400: {
@@ -10663,15 +10700,26 @@ type PersistentMenu = Schemas["AccountsPersistentMenu"];
10663
10700
  *
10664
10701
  * Las dos cosas valen: `url` es el camino alojado —se redirige al usuario y PlanVortex se encarga
10665
10702
  * de todo—, y `token` es el mismo credencial suelto, para pasarselo a `pv.asTemporalToken(token)`
10666
- * y conducir el flujo desde el front propio. Caduca a la hora (`expires_at`) y sirve para UNA
10667
- * organizacion.
10703
+ * y conducir el flujo desde el front propio. Caduca a los quince minutos (`expires_at`), sirve para
10704
+ * UNA organizacion y se gasta en cuanto conecta una cuenta.
10668
10705
  */
10669
10706
  type ConnectToken = Operations["createTemporalConnectToken"]["responses"][200]["content"]["application/json"];
10670
10707
  /**
10671
- * El enlace de autorizacion de UNA red. Se manda al usuario ahi y la red lo devuelve al panel de
10672
- * PlanVortex, que es quien completa la conexion.
10708
+ * Como se conecta UNA red. Casi siempre es un enlace: se manda al usuario ahi y la red lo devuelve
10709
+ * al panel de PlanVortex, que es quien completa la conexion.
10710
+ *
10711
+ * **Casi. Mira `authorization.type` y no si `link` esta vacio.** WhatsApp no tiene URL de
10712
+ * autorizacion: su alta es el Embedded Signup de Meta, un popup que levanta el SDK de JavaScript de
10713
+ * Facebook desde tu pagina y que devuelve por `postMessage` datos —el `waba_id`, el
10714
+ * `phone_number_id`— que no caben en una query string. Su `link` es cadena vacia y los parametros
10715
+ * del popup (`app_id`, `config_id`, `graph_version`...) viajan en `authorization`.
10673
10716
  */
10674
10717
  type ConnectLink = Schemas["AccountsSocialLinksList"]["links"][number];
10718
+ /**
10719
+ * Con que se autoriza una red: `redirect` (las otras nueve) o `meta_embedded_signup` (WhatsApp).
10720
+ * Se saca de {@link ConnectLink} y esta aqui para poder nombrarlo en un `switch`.
10721
+ */
10722
+ type SocialAuthorizationMethod = ConnectLink["authorization"];
10675
10723
  /**
10676
10724
  * Lo que dejo una autorizacion: las cuentas que se pueden dar de alta.
10677
10725
  *
@@ -11181,7 +11229,7 @@ declare class PlanVortexError extends Error {
11181
11229
  readonly retryAfter: number | undefined;
11182
11230
  constructor(code: number, message: string, options?: PlanVortexErrorOptions);
11183
11231
  }
11184
- /** 500-542 — tokens, apps de cliente, permisos. Incluye el 501 y el 522, los de token caducado. */
11232
+ /** 500-544 — tokens, apps de cliente, permisos. Incluye el 501 y el 522, los de token caducado. */
11185
11233
  declare class AuthError extends PlanVortexError {
11186
11234
  }
11187
11235
  /** 601-612 — el usuario final. */
@@ -11523,4 +11571,4 @@ interface PlanVortexWebhooksOptions {
11523
11571
  */
11524
11572
  declare function planvortexWebhooks(options: PlanVortexWebhooksOptions): (request: WebhookRequestLike, response: WebhookResponseLike, next: (error?: unknown) => void) => void;
11525
11573
 
11526
- export { type Product as $, type Account as A, type IntegrationProvider as B, type ConnectLink as C, type Dashboard as D, type EnableResult as E, type Integration as F, type IntegrationConnectRequest as G, type IntegrationUpdate as H, type IntegrationProviderName as I, type IntegrationPickerConfig as J, type MessageTemplate as K, type Conversation as L, type MetricName as M, type ConversationTotals as N, type Message as O, type Paginated as P, type MessageInput as Q, type Client as R, type SocialNetwork as S, type TopPublicationsResult as T, type Organization as U, type AiSettings as V, type ClientWithOrganizations as W, type PlanData as X, type ConnectToken as Y, type AiContext as Z, type SocialCredentialsInput as _, type ConnectResult as a, type RssConfig as a$, type ProductInput as a0, type ProductCatalog as a1, type ProductCatalogInput as a2, type PublicationInput as a3, type PublicationState as a4, type PublicationStats as a5, type PublicationStatsHistory as a6, type Upload as a7, AccountError as a8, type AccountMetricRow as a9, type MessageChange as aA, type MessageOptions as aB, type MessageType as aC, MessagingError as aD, type MetricRow as aE, NO_ERROR_CODE as aF, type components as aG, type operations as aH, type paths as aI, type webhooks as aJ, type OpenEnum as aK, OrganizationError as aL, PLANVORTEX_ERROR_RANGES as aM, PlanLimitError as aN, PlanVortexAuthenticationError as aO, PlanVortexConfigError as aP, PlanVortexConnectionError as aQ, PlanVortexError as aR, type PlanVortexErrorOptions as aS, type PlanVortexErrorRange as aT, ProductError as aU, PublicationError as aV, type PublicationErrorDetail as aW, type PublicationMetrics as aX, type PublicationStatsPoint as aY, type PublicationType as aZ, type PublicationsSummary as a_, type AccountStateChange as aa, type AccountWebhookChangeBase as ab, type AccountWithError as ac, type AiPlanCostEstimate as ad, AiPlanError as ae, type AiPlanOptions as af, type AiPlanOptionsInput as ag, type AiPlanState as ah, type ApiErrorBody as ai, type AspectRatios as aj, AuthError as ak, type ClientPlan as al, type CommentAuthor as am, type CommentChange as an, type ContactChannel as ao, ContactError as ap, type DashboardAiPlanRef as aq, type DashboardPublicationRef as ar, type DashboardRange as as, type EngagementBase as at, FileError as au, type FileFormat as av, type FileProperties as aw, type FileType as ax, IntegrationError as ay, type IntegrationErrorChange as az, type AccountMetrics as b, type SocialCredentials as b0, type SocialIdentifier as b1, type SocialIdentifierInput as b2, type SocialLimitsMap as b3, TOKEN_ERROR_CODES as b4, type TopPublication as b5, type UnknownWebhookChange as b6, UserError as b7, type WebhookAlgorithm as b8, type WebhookChange as b9, handleWebhookRequest as bA, isAccountStateChange as bB, isCommentChange as bC, isIntegrationErrorChange as bD, isMessageChange as bE, parseWebhookPayload as bF, planvortexWebhooks as bG, verifyWebhookSignature as bH, type WebhookEvent as ba, type WithAccount as bb, type WithPublication as bc, account as bd, accountId as be, errorFamilyForCode as bf, isPlanVortexError as bg, isTokenError as bh, messageContact as bi, messageContactId as bj, messageDirection as bk, messageFileIds as bl, messageFiles as bm, publication as bn, publicationId as bo, type HandleWebhookRequestOptions as bp, type PlanVortexWebhooksOptions as bq, type RawWebhookBody as br, type VerifyWebhookSignatureOptions as bs, WEBHOOK_EVENTS as bt, WEBHOOK_SIGNATURE_HEADERS as bu, WebhookBodyError as bv, type WebhookHeaders as bw, type WebhookRequestLike as bx, type WebhookResponseLike as by, WebhookSignatureError as bz, type PersistentMenu as c, type Publication as d, type AiPlanCreateRequest as e, type AiPlanCreateResult as f, type AiPlan as g, type ClientApp as h, type ClientAppInput as i, type SocialCapabilities as j, type CommentActions as k, type SocialLimits as l, type PublicationLimits as m, type AspectRatiosByNetwork as n, type CommentNetwork as o, type Comment as p, type CommentThread as q, type CommentReplyResult as r, type ContactExtraData as s, type Contact as t, type ContactCreate as u, type ContactUpdate as v, type DashboardMetricsResult as w, type PublicationsSummaryResult as x, type PublicationsStatsResult as y, type PlanUse as z };
11574
+ export { type Product as $, type Account as A, type IntegrationProvider as B, type ConnectLink as C, type Dashboard as D, type EnableResult as E, type Integration as F, type IntegrationConnectRequest as G, type IntegrationUpdate as H, type IntegrationProviderName as I, type IntegrationPickerConfig as J, type MessageTemplate as K, type Conversation as L, type MetricName as M, type ConversationTotals as N, type Message as O, type Paginated as P, type MessageInput as Q, type Client as R, type SocialNetwork as S, type TopPublicationsResult as T, type Organization as U, type AiSettings as V, type ClientWithOrganizations as W, type PlanData as X, type ConnectToken as Y, type AiContext as Z, type SocialCredentialsInput as _, type ConnectResult as a, type RssConfig as a$, type ProductInput as a0, type ProductCatalog as a1, type ProductCatalogInput as a2, type PublicationInput as a3, type PublicationState as a4, type PublicationStats as a5, type PublicationStatsHistory as a6, type Upload as a7, AccountError as a8, type AccountMetricRow as a9, type MessageChange as aA, type MessageOptions as aB, type MessageType as aC, MessagingError as aD, type MetricRow as aE, NO_ERROR_CODE as aF, type components as aG, type operations as aH, type paths as aI, type webhooks as aJ, type OpenEnum as aK, OrganizationError as aL, PLANVORTEX_ERROR_RANGES as aM, PlanLimitError as aN, PlanVortexAuthenticationError as aO, PlanVortexConfigError as aP, PlanVortexConnectionError as aQ, PlanVortexError as aR, type PlanVortexErrorOptions as aS, type PlanVortexErrorRange as aT, ProductError as aU, PublicationError as aV, type PublicationErrorDetail as aW, type PublicationMetrics as aX, type PublicationStatsPoint as aY, type PublicationType as aZ, type PublicationsSummary as a_, type AccountStateChange as aa, type AccountWebhookChangeBase as ab, type AccountWithError as ac, type AiPlanCostEstimate as ad, AiPlanError as ae, type AiPlanOptions as af, type AiPlanOptionsInput as ag, type AiPlanState as ah, type ApiErrorBody as ai, type AspectRatios as aj, AuthError as ak, type ClientPlan as al, type CommentAuthor as am, type CommentChange as an, type ContactChannel as ao, ContactError as ap, type DashboardAiPlanRef as aq, type DashboardPublicationRef as ar, type DashboardRange as as, type EngagementBase as at, FileError as au, type FileFormat as av, type FileProperties as aw, type FileType as ax, IntegrationError as ay, type IntegrationErrorChange as az, type AccountMetrics as b, type SocialAuthorizationMethod as b0, type SocialCredentials as b1, type SocialIdentifier as b2, type SocialIdentifierInput as b3, type SocialLimitsMap as b4, TOKEN_ERROR_CODES as b5, type TopPublication as b6, type UnknownWebhookChange as b7, UserError as b8, type WebhookAlgorithm as b9, WebhookSignatureError as bA, handleWebhookRequest as bB, isAccountStateChange as bC, isCommentChange as bD, isIntegrationErrorChange as bE, isMessageChange as bF, parseWebhookPayload as bG, planvortexWebhooks as bH, verifyWebhookSignature as bI, type WebhookChange as ba, type WebhookEvent as bb, type WithAccount as bc, type WithPublication as bd, account as be, accountId as bf, errorFamilyForCode as bg, isPlanVortexError as bh, isTokenError as bi, messageContact as bj, messageContactId as bk, messageDirection as bl, messageFileIds as bm, messageFiles as bn, publication as bo, publicationId as bp, type HandleWebhookRequestOptions as bq, type PlanVortexWebhooksOptions as br, type RawWebhookBody as bs, type VerifyWebhookSignatureOptions as bt, WEBHOOK_EVENTS as bu, WEBHOOK_SIGNATURE_HEADERS as bv, WebhookBodyError as bw, type WebhookHeaders as bx, type WebhookRequestLike as by, type WebhookResponseLike as bz, type PersistentMenu as c, type Publication as d, type AiPlanCreateRequest as e, type AiPlanCreateResult as f, type AiPlan as g, type ClientApp as h, type ClientAppInput as i, type SocialCapabilities as j, type CommentActions as k, type SocialLimits as l, type PublicationLimits as m, type AspectRatiosByNetwork as n, type CommentNetwork as o, type Comment as p, type CommentThread as q, type CommentReplyResult as r, type ContactExtraData as s, type Contact as t, type ContactCreate as u, type ContactUpdate as v, type DashboardMetricsResult as w, type PublicationsSummaryResult as x, type PublicationsStatsResult as y, type PlanUse as z };
package/dist/index.cjs CHANGED
@@ -4,11 +4,11 @@ var path = require('path');
4
4
 
5
5
  // src/version.ts
6
6
  var PLANVORTEX_API_URL = "https://api.planvortex.com/v1.0.0";
7
- var VERSION = "0.1.0";
7
+ var VERSION = "0.2.0";
8
8
 
9
9
  // src/core/errors.ts
10
10
  var PLANVORTEX_ERROR_RANGES = [
11
- { from: 500, to: 542, family: "auth" },
11
+ { from: 500, to: 544, family: "auth" },
12
12
  { from: 601, to: 612, family: "user" },
13
13
  { from: 700, to: 715, family: "account" },
14
14
  { from: 800, to: 810, family: "file" },
@@ -609,6 +609,12 @@ var AccountsResource = class extends Resource {
609
609
  * no un fallo: es lo que pasa con Discord en una organización que todavía no ha guardado sus
610
610
  * propias credenciales de bot.
611
611
  *
612
+ * **MIRA `authorization`, NO si `link` está vacío.** Nueve de las diez redes son `redirect` y se
613
+ * manda a la persona a `link`. **WhatsApp no es una URL**: su alta es el Embedded Signup de
614
+ * Meta, un popup que levantas tú con el SDK de JavaScript de Facebook, así que su `link` es
615
+ * cadena vacía y lo que necesitas para abrirlo viaja en `authorization` — ver {@link ConnectLink}.
616
+ * Recorrer la lista redirigiendo a `link` manda a tu usuario a tu propia página.
617
+ *
612
618
  * OJO: la red devuelve al usuario a un front de PlanVortex, no a una URL tuya — ver
613
619
  * `redirect_uri` en {@link ConnectLinksOptions}.
614
620
  */
@@ -2007,7 +2013,15 @@ var OrganizationsResource = class extends Resource {
2007
2013
  * - **`token`** — el credencial suelto, para `pv.asTemporalToken(token)` cuando la interfaz la
2008
2014
  * pone el integrador.
2009
2015
  *
2010
- * Caduca en una hora y **sólo vale para esta organización**: usarlo contra otra contesta 1101.
2016
+ * Caduca en **quince minutos** y **sólo vale para esta organización**: usarlo contra otra
2017
+ * contesta 1101.
2018
+ *
2019
+ * **Y conecta una vez.** En cuanto un `accounts.connect` sale bien, ese token deja de poder
2020
+ * conectar y contesta 543; los `accounts.enable` que rematan esa misma conexión siguen valiendo
2021
+ * hasta que caduque. Emite uno por conexión: son gratis e inmediatos.
2022
+ *
2023
+ * **Si pasas `social_network`, el token queda atado a esa red** y no conecta ninguna otra (544).
2024
+ * Sin ella, el token abre cualquiera y es la persona quien elige.
2011
2025
  */
2012
2026
  async createConnectToken(idOrganization, options = {}) {
2013
2027
  return this.httpGet(