@commet/next 0.2.14 → 0.3.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/dist/index.d.mts +13 -2
- package/dist/index.d.ts +13 -2
- package/dist/index.js +233 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +232 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { NextRequest, NextResponse } from 'next/server';
|
|
2
|
-
import { WebhookPayload } from '@commet/node';
|
|
2
|
+
import { WebhookPayload, BillingInterval } from '@commet/node';
|
|
3
3
|
export { WebhookData, WebhookEvent, WebhookPayload } from '@commet/node';
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -184,4 +184,15 @@ interface CustomerPortalConfig {
|
|
|
184
184
|
*/
|
|
185
185
|
declare const CustomerPortal: ({ apiKey, environment, getCustomerId, onError, }: CustomerPortalConfig) => (req: NextRequest) => Promise<NextResponse<unknown>>;
|
|
186
186
|
|
|
187
|
-
|
|
187
|
+
interface PricingMarkdownConfig {
|
|
188
|
+
apiKey: string;
|
|
189
|
+
title: string;
|
|
190
|
+
description?: string;
|
|
191
|
+
includeCreditPacks?: boolean;
|
|
192
|
+
billingIntervals?: BillingInterval[];
|
|
193
|
+
cacheMaxAge?: number;
|
|
194
|
+
onError?: (error: Error) => void;
|
|
195
|
+
}
|
|
196
|
+
declare const PricingMarkdown: ({ apiKey, title, description, includeCreditPacks, billingIntervals, cacheMaxAge, onError, }: PricingMarkdownConfig) => (_req: NextRequest) => Promise<NextResponse<unknown>>;
|
|
197
|
+
|
|
198
|
+
export { CustomerPortal, type CustomerPortalConfig, PricingMarkdown, type PricingMarkdownConfig, Webhooks, type WebhooksConfig };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { NextRequest, NextResponse } from 'next/server';
|
|
2
|
-
import { WebhookPayload } from '@commet/node';
|
|
2
|
+
import { WebhookPayload, BillingInterval } from '@commet/node';
|
|
3
3
|
export { WebhookData, WebhookEvent, WebhookPayload } from '@commet/node';
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -184,4 +184,15 @@ interface CustomerPortalConfig {
|
|
|
184
184
|
*/
|
|
185
185
|
declare const CustomerPortal: ({ apiKey, environment, getCustomerId, onError, }: CustomerPortalConfig) => (req: NextRequest) => Promise<NextResponse<unknown>>;
|
|
186
186
|
|
|
187
|
-
|
|
187
|
+
interface PricingMarkdownConfig {
|
|
188
|
+
apiKey: string;
|
|
189
|
+
title: string;
|
|
190
|
+
description?: string;
|
|
191
|
+
includeCreditPacks?: boolean;
|
|
192
|
+
billingIntervals?: BillingInterval[];
|
|
193
|
+
cacheMaxAge?: number;
|
|
194
|
+
onError?: (error: Error) => void;
|
|
195
|
+
}
|
|
196
|
+
declare const PricingMarkdown: ({ apiKey, title, description, includeCreditPacks, billingIntervals, cacheMaxAge, onError, }: PricingMarkdownConfig) => (_req: NextRequest) => Promise<NextResponse<unknown>>;
|
|
197
|
+
|
|
198
|
+
export { CustomerPortal, type CustomerPortalConfig, PricingMarkdown, type PricingMarkdownConfig, Webhooks, type WebhooksConfig };
|
package/dist/index.js
CHANGED
|
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
21
21
|
var index_exports = {};
|
|
22
22
|
__export(index_exports, {
|
|
23
23
|
CustomerPortal: () => CustomerPortal,
|
|
24
|
+
PricingMarkdown: () => PricingMarkdown,
|
|
24
25
|
Webhooks: () => Webhooks
|
|
25
26
|
});
|
|
26
27
|
module.exports = __toCommonJS(index_exports);
|
|
@@ -167,7 +168,7 @@ var CustomerPortal = ({
|
|
|
167
168
|
externalId: customerId
|
|
168
169
|
});
|
|
169
170
|
if (!result.success || !result.data) {
|
|
170
|
-
throw new Error(result.
|
|
171
|
+
throw new Error(result.message || "Failed to create portal session");
|
|
171
172
|
}
|
|
172
173
|
return import_server2.NextResponse.redirect(result.data.portalUrl);
|
|
173
174
|
} catch (error) {
|
|
@@ -181,9 +182,240 @@ var CustomerPortal = ({
|
|
|
181
182
|
}
|
|
182
183
|
};
|
|
183
184
|
};
|
|
185
|
+
|
|
186
|
+
// src/pricing-markdown.ts
|
|
187
|
+
var import_node3 = require("@commet/node");
|
|
188
|
+
var import_server3 = require("next/server");
|
|
189
|
+
var INTERVAL_SHORT = {
|
|
190
|
+
monthly: "/mo",
|
|
191
|
+
quarterly: "/qtr",
|
|
192
|
+
yearly: "/yr"
|
|
193
|
+
};
|
|
194
|
+
var PricingMarkdown = ({
|
|
195
|
+
apiKey,
|
|
196
|
+
title,
|
|
197
|
+
description,
|
|
198
|
+
includeCreditPacks = false,
|
|
199
|
+
billingIntervals,
|
|
200
|
+
cacheMaxAge = 3600,
|
|
201
|
+
onError
|
|
202
|
+
}) => {
|
|
203
|
+
const commet = new import_node3.Commet({ apiKey });
|
|
204
|
+
return async (_req) => {
|
|
205
|
+
try {
|
|
206
|
+
const plansResult = await commet.plans.list();
|
|
207
|
+
if (!plansResult.success || !plansResult.data) {
|
|
208
|
+
throw new Error(plansResult.message ?? "Failed to fetch plans");
|
|
209
|
+
}
|
|
210
|
+
const publicPlans = plansResult.data.filter((plan) => plan.isPublic);
|
|
211
|
+
const creditPacks = includeCreditPacks ? await commet.creditPacks.list().then(
|
|
212
|
+
(result) => result.success && result.data ? result.data : []
|
|
213
|
+
) : [];
|
|
214
|
+
const markdown = generateMarkdown(
|
|
215
|
+
title,
|
|
216
|
+
description,
|
|
217
|
+
publicPlans,
|
|
218
|
+
creditPacks,
|
|
219
|
+
billingIntervals
|
|
220
|
+
);
|
|
221
|
+
return new import_server3.NextResponse(markdown, {
|
|
222
|
+
status: 200,
|
|
223
|
+
headers: {
|
|
224
|
+
"Content-Type": "text/markdown; charset=utf-8",
|
|
225
|
+
"Cache-Control": `public, s-maxage=${cacheMaxAge}, stale-while-revalidate=${cacheMaxAge * 2}`
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
} catch (error) {
|
|
229
|
+
const errorObj = error instanceof Error ? error : new Error(String(error));
|
|
230
|
+
onError?.(errorObj);
|
|
231
|
+
console.error("[Commet PricingMarkdown]", errorObj);
|
|
232
|
+
return import_server3.NextResponse.json(
|
|
233
|
+
{ error: "Failed to generate pricing markdown" },
|
|
234
|
+
{ status: 500 }
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
};
|
|
239
|
+
function generateMarkdown(title, description, plans, creditPacks, billingIntervals) {
|
|
240
|
+
const sections = [`# ${title}`];
|
|
241
|
+
if (description) {
|
|
242
|
+
sections.push(description);
|
|
243
|
+
}
|
|
244
|
+
if (plans.length > 0) {
|
|
245
|
+
sections.push(renderPlansTable(plans, billingIntervals));
|
|
246
|
+
const featuresSection = renderFeatures(plans);
|
|
247
|
+
if (featuresSection) {
|
|
248
|
+
sections.push(featuresSection);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (creditPacks.length > 0) {
|
|
252
|
+
sections.push(renderCreditPacks(creditPacks));
|
|
253
|
+
}
|
|
254
|
+
return sections.join("\n\n");
|
|
255
|
+
}
|
|
256
|
+
function renderPlansTable(plans, filterIntervals) {
|
|
257
|
+
const usageFeatures = collectUsageFeatures(plans);
|
|
258
|
+
const headerCols = ["Plan", "Price"];
|
|
259
|
+
for (const { name, unitName } of usageFeatures) {
|
|
260
|
+
headerCols.push(`${name}/${unitName ?? "unit"}`);
|
|
261
|
+
headerCols.push("Overage");
|
|
262
|
+
}
|
|
263
|
+
const rows = plans.map((plan) => {
|
|
264
|
+
const priceCell = renderPriceCell(plan, filterIntervals);
|
|
265
|
+
const cols = [plan.name, priceCell];
|
|
266
|
+
const featuresByCode = new Map(
|
|
267
|
+
plan.features.map((feature) => [feature.code, feature])
|
|
268
|
+
);
|
|
269
|
+
for (const { code } of usageFeatures) {
|
|
270
|
+
const feature = featuresByCode.get(code);
|
|
271
|
+
if (!feature) {
|
|
272
|
+
cols.push("\u2014", "\u2014");
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
if (feature.unlimited) {
|
|
276
|
+
cols.push("Unlimited", "\u2014");
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
const included = feature.includedAmount;
|
|
280
|
+
cols.push(included ? formatNumber(included) : "\u2014");
|
|
281
|
+
const overagePrice = feature.overageEnabled && feature.overageUnitPrice !== void 0 ? formatRatePrice(feature.overageUnitPrice) : "\u2014";
|
|
282
|
+
cols.push(overagePrice);
|
|
283
|
+
}
|
|
284
|
+
return cols;
|
|
285
|
+
});
|
|
286
|
+
const separator = headerCols.map(() => "---");
|
|
287
|
+
const lines = [
|
|
288
|
+
`| ${headerCols.join(" | ")} |`,
|
|
289
|
+
`| ${separator.join(" | ")} |`,
|
|
290
|
+
...rows.map((cols) => `| ${cols.join(" | ")} |`)
|
|
291
|
+
];
|
|
292
|
+
const footnotes = [];
|
|
293
|
+
const trialPlans = plans.filter(
|
|
294
|
+
(plan) => plan.prices.some((price) => price.trialDays > 0)
|
|
295
|
+
);
|
|
296
|
+
for (const plan of trialPlans) {
|
|
297
|
+
const trialPrice = plan.prices.find((price) => price.trialDays > 0);
|
|
298
|
+
footnotes.push(
|
|
299
|
+
`*${plan.name} plan includes a ${trialPrice.trialDays}-day free trial.*`
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
if (usageFeatures.length > 0) {
|
|
303
|
+
footnotes.push(
|
|
304
|
+
"The overage rate applies only to usage beyond the included volume."
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
return footnotes.length > 0 ? `## Plans
|
|
308
|
+
|
|
309
|
+
${lines.join("\n")}
|
|
310
|
+
|
|
311
|
+
${footnotes.join("\n\n")}` : `## Plans
|
|
312
|
+
|
|
313
|
+
${lines.join("\n")}`;
|
|
314
|
+
}
|
|
315
|
+
function renderPriceCell(plan, filterIntervals) {
|
|
316
|
+
if (plan.isFree) return "Free";
|
|
317
|
+
const prices = filterIntervals ? plan.prices.filter((price) => filterIntervals.includes(price.billingInterval)) : plan.prices;
|
|
318
|
+
if (prices.length === 0) return "\u2014";
|
|
319
|
+
return prices.map((price) => {
|
|
320
|
+
if (price.price === 0) return "Free";
|
|
321
|
+
return `${formatSettlementPrice(price.price)}${INTERVAL_SHORT[price.billingInterval]}`;
|
|
322
|
+
}).join(" / ");
|
|
323
|
+
}
|
|
324
|
+
function renderFeatures(plans) {
|
|
325
|
+
const allBooleanCodes = /* @__PURE__ */ new Set();
|
|
326
|
+
for (const plan of plans) {
|
|
327
|
+
for (const feature of plan.features) {
|
|
328
|
+
if (feature.type === "boolean") {
|
|
329
|
+
allBooleanCodes.add(feature.code);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
if (allBooleanCodes.size === 0) return null;
|
|
334
|
+
const enabledOnAll = /* @__PURE__ */ new Set();
|
|
335
|
+
for (const code of allBooleanCodes) {
|
|
336
|
+
const enabledOnEveryPlan = plans.every((plan) => {
|
|
337
|
+
const feature = plan.features.find((f) => f.code === code);
|
|
338
|
+
return feature?.enabled;
|
|
339
|
+
});
|
|
340
|
+
if (enabledOnEveryPlan) {
|
|
341
|
+
enabledOnAll.add(code);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
const perPlanLines = [];
|
|
345
|
+
for (const plan of plans) {
|
|
346
|
+
const uniqueFeatures = plan.features.filter(
|
|
347
|
+
(feature) => feature.type === "boolean" && feature.enabled && !enabledOnAll.has(feature.code)
|
|
348
|
+
).map((feature) => feature.name);
|
|
349
|
+
if (uniqueFeatures.length > 0) {
|
|
350
|
+
perPlanLines.push(`- **${plan.name}**: ${uniqueFeatures.join(", ")}`);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
const commonFeatures = plans[0]?.features.filter(
|
|
354
|
+
(feature) => feature.type === "boolean" && enabledOnAll.has(feature.code)
|
|
355
|
+
).map((feature) => feature.name);
|
|
356
|
+
const parts = [];
|
|
357
|
+
if (perPlanLines.length > 0) {
|
|
358
|
+
parts.push(perPlanLines.join("\n"));
|
|
359
|
+
}
|
|
360
|
+
if (commonFeatures && commonFeatures.length > 0) {
|
|
361
|
+
parts.push(`All plans include: ${commonFeatures.join(", ")}.`);
|
|
362
|
+
}
|
|
363
|
+
return parts.length > 0 ? `## Features
|
|
364
|
+
|
|
365
|
+
${parts.join("\n\n")}` : null;
|
|
366
|
+
}
|
|
367
|
+
function renderCreditPacks(packs) {
|
|
368
|
+
const lines = [
|
|
369
|
+
"| Pack | Credits | Price |",
|
|
370
|
+
"| --- | --- | --- |",
|
|
371
|
+
...packs.map(
|
|
372
|
+
(pack) => `| ${pack.name} | ${formatNumber(pack.credits)} credits | ${formatSettlementPrice(pack.price)} |`
|
|
373
|
+
)
|
|
374
|
+
];
|
|
375
|
+
return `## Credit Packs
|
|
376
|
+
|
|
377
|
+
${lines.join("\n")}`;
|
|
378
|
+
}
|
|
379
|
+
function collectUsageFeatures(plans) {
|
|
380
|
+
const seen = /* @__PURE__ */ new Map();
|
|
381
|
+
for (const plan of plans) {
|
|
382
|
+
for (const feature of plan.features) {
|
|
383
|
+
if ((feature.type === "metered" || feature.type === "seats") && !seen.has(feature.code)) {
|
|
384
|
+
seen.set(feature.code, {
|
|
385
|
+
code: feature.code,
|
|
386
|
+
name: feature.name,
|
|
387
|
+
unitName: feature.unitName
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
return Array.from(seen.values());
|
|
393
|
+
}
|
|
394
|
+
function formatSettlementPrice(cents) {
|
|
395
|
+
if (cents === 0) return "Free";
|
|
396
|
+
const dollars = cents / 100;
|
|
397
|
+
const [whole, decimal] = dollars.toFixed(2).split(".");
|
|
398
|
+
return `$${Number(whole).toLocaleString("en-US")}.${decimal}`;
|
|
399
|
+
}
|
|
400
|
+
function formatRatePrice(rate) {
|
|
401
|
+
const dollars = rate / 1e4;
|
|
402
|
+
if (dollars === Math.floor(dollars)) {
|
|
403
|
+
return `$${dollars.toFixed(2)}`;
|
|
404
|
+
}
|
|
405
|
+
const formatted = dollars.toFixed(4).replace(/0+$/, "");
|
|
406
|
+
const decimalPlaces = formatted.split(".")[1]?.length ?? 0;
|
|
407
|
+
if (decimalPlaces < 2) {
|
|
408
|
+
return `$${dollars.toFixed(2)}`;
|
|
409
|
+
}
|
|
410
|
+
return `$${formatted}`;
|
|
411
|
+
}
|
|
412
|
+
function formatNumber(n) {
|
|
413
|
+
return n.toLocaleString("en-US");
|
|
414
|
+
}
|
|
184
415
|
// Annotate the CommonJS export names for ESM import in node:
|
|
185
416
|
0 && (module.exports = {
|
|
186
417
|
CustomerPortal,
|
|
418
|
+
PricingMarkdown,
|
|
187
419
|
Webhooks
|
|
188
420
|
});
|
|
189
421
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/webhooks.ts","../src/portal.ts"],"sourcesContent":["/**\n * @commet/next - Next.js integration for Commet\n *\n * @example\n * Webhooks\n * ```typescript\n * import { Webhooks } from \"@commet/next\";\n *\n * export const POST = Webhooks({\n * webhookSecret: process.env.COMMET_WEBHOOK_SECRET!,\n * onSubscriptionActivated: async (payload) => {\n * // Handle activation\n * },\n * });\n * ```\n *\n * @example\n * Customer Portal\n * ```typescript\n * import { CustomerPortal } from \"@commet/next\";\n *\n * export const GET = CustomerPortal({\n * apiKey: process.env.COMMET_API_KEY!,\n * getCustomerId: async (req) => {\n * const session = await auth.api.getSession({ headers: req.headers });\n * return session?.user.id;\n * },\n * });\n * ```\n *\n * @packageDocumentation\n */\n\nexport { Webhooks } from \"./webhooks\";\nexport type {\n WebhooksConfig,\n WebhookPayload,\n WebhookData,\n WebhookEvent,\n} from \"./types\";\n\nexport { CustomerPortal } from \"./portal\";\nexport type { CustomerPortalConfig } from \"./portal\";\n","import { Webhooks as CommetWebhooks } from \"@commet/node\";\nimport type { WebhookPayload } from \"@commet/node\";\nimport { type NextRequest, NextResponse } from \"next/server\";\nimport type { WebhooksConfig } from \"./types\";\n\n/**\n * Create a Next.js webhook handler for Commet events\n *\n * Automatically verifies signatures, routes events to handlers, and returns proper responses.\n *\n * @param config - Webhook configuration with secret and event handlers\n * @returns Next.js route handler function\n *\n * @example\n * ```typescript\n * // app/api/webhooks/commet/route.ts\n * import { Webhooks } from \"@commet/next\";\n *\n * export const POST = Webhooks({\n * webhookSecret: process.env.COMMET_WEBHOOK_SECRET!,\n * onSubscriptionActivated: async (payload) => {\n * // Grant access to user\n * },\n * onSubscriptionCanceled: async (payload) => {\n * // Revoke access from user\n * },\n * });\n * ```\n */\nexport const Webhooks = (config: WebhooksConfig) => {\n const {\n webhookSecret,\n onSubscriptionActivated,\n onSubscriptionCanceled,\n onSubscriptionCreated,\n onSubscriptionUpdated,\n onPayload,\n onError,\n } = config;\n\n // Create webhook verifier instance\n const webhooks = new CommetWebhooks();\n\n return async (request: NextRequest) => {\n try {\n // 1. Read raw request body\n const rawBody = await request.text();\n\n // 2. Extract signature from headers\n const signature = request.headers.get(\"x-commet-signature\");\n\n // 3. Verify signature\n const isValid = webhooks.verify({\n payload: rawBody,\n signature,\n secret: webhookSecret,\n });\n\n if (!isValid) {\n console.error(\"[Commet Webhook] Invalid signature\");\n return NextResponse.json(\n { received: false, error: \"Invalid signature\" },\n { status: 403 },\n );\n }\n\n // 4. Parse payload\n let payload: WebhookPayload;\n try {\n payload = JSON.parse(rawBody) as WebhookPayload;\n } catch (parseError) {\n console.error(\"[Commet Webhook] Failed to parse payload:\", parseError);\n if (onError) {\n await onError(\n parseError instanceof Error\n ? parseError\n : new Error(\"Failed to parse webhook payload\"),\n rawBody,\n );\n }\n return NextResponse.json(\n { received: false, error: \"Invalid payload\" },\n { status: 400 },\n );\n }\n\n // 5. Collect promises for parallel execution\n const promises: Promise<void>[] = [];\n\n // Call catch-all handler if provided\n if (onPayload) {\n promises.push(onPayload(payload));\n }\n\n // 6. Route to specific event handler\n switch (payload.event) {\n case \"subscription.activated\":\n if (onSubscriptionActivated) {\n promises.push(onSubscriptionActivated(payload));\n }\n break;\n\n case \"subscription.canceled\":\n if (onSubscriptionCanceled) {\n promises.push(onSubscriptionCanceled(payload));\n }\n break;\n\n case \"subscription.created\":\n if (onSubscriptionCreated) {\n promises.push(onSubscriptionCreated(payload));\n }\n break;\n\n case \"subscription.updated\":\n if (onSubscriptionUpdated) {\n promises.push(onSubscriptionUpdated(payload));\n }\n break;\n\n default:\n console.log(`[Commet Webhook] Unhandled event: ${payload.event}`);\n }\n\n // 7. Execute all handlers in parallel\n try {\n await Promise.all(promises);\n } catch (handlerError) {\n console.error(\n \"[Commet Webhook] Handler error:\",\n handlerError instanceof Error ? handlerError.message : handlerError,\n );\n if (onError) {\n await onError(\n handlerError instanceof Error\n ? handlerError\n : new Error(\"Handler execution failed\"),\n payload,\n );\n }\n // Still return 200 to prevent retries for handler errors\n return NextResponse.json(\n { received: true, warning: \"Handler failed\" },\n { status: 200 },\n );\n }\n\n // 8. Success response\n return NextResponse.json({ received: true }, { status: 200 });\n } catch (error) {\n console.error(\"[Commet Webhook] Unexpected error:\", error);\n if (onError) {\n try {\n await onError(\n error instanceof Error ? error : new Error(\"Unexpected error\"),\n undefined,\n );\n } catch (errorHandlerError) {\n console.error(\n \"[Commet Webhook] Error handler failed:\",\n errorHandlerError,\n );\n }\n }\n return NextResponse.json(\n { received: false, error: \"Internal error\" },\n { status: 500 },\n );\n }\n };\n};\n","import { Commet } from \"@commet/node\";\nimport { type NextRequest, NextResponse } from \"next/server\";\n\nexport interface CustomerPortalConfig {\n apiKey: string;\n getCustomerId: (req: NextRequest) => Promise<string | null>;\n environment?: \"sandbox\" | \"production\";\n onError?: (error: Error) => void;\n}\n\n/**\n * Creates Next.js route handler for Customer Portal access\n *\n * @example\n * ```typescript\n * // app/api/commet/portal/route.ts\n * import { CustomerPortal } from \"@commet/next\";\n * import { auth } from \"@/lib/auth\";\n *\n * export const GET = CustomerPortal({\n * apiKey: process.env.COMMET_API_KEY!,\n * getCustomerId: async (req) => {\n * const session = await auth.api.getSession({ headers: req.headers });\n * return session?.user.id ?? null;\n * },\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Use in component\n * export function BillingButton() {\n * return (\n * <Button asChild>\n * <Link href=\"/api/commet/portal\">Manage Billing</Link>\n * </Button>\n * );\n * }\n * ```\n */\nexport const CustomerPortal = ({\n apiKey,\n environment = \"production\",\n getCustomerId,\n onError,\n}: CustomerPortalConfig) => {\n const commet = new Commet({\n apiKey,\n environment,\n });\n\n return async (req: NextRequest) => {\n try {\n // Get customer identifier from request\n const customerId = await getCustomerId(req);\n\n if (!customerId) {\n return NextResponse.json(\n { error: \"Customer not authenticated\" },\n { status: 401 },\n );\n }\n\n // Get portal URL from Commet\n const result = await commet.portal.getUrl({\n externalId: customerId,\n });\n\n if (!result.success || !result.data) {\n throw new Error(result.error || \"Failed to create portal session\");\n }\n\n // Redirect to customer portal\n return NextResponse.redirect(result.data.portalUrl);\n } catch (error) {\n const errorObj =\n error instanceof Error ? error : new Error(String(error));\n\n // Call custom error handler if provided\n onError?.(errorObj);\n\n // Log error\n console.error(\"[Commet Portal]\", errorObj);\n\n // Return error response\n return NextResponse.json(\n { error: \"Failed to access customer portal\" },\n { status: 500 },\n );\n }\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAA2C;AAE3C,oBAA+C;AA2BxC,IAAM,WAAW,CAAC,WAA2B;AAClD,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAGJ,QAAM,WAAW,IAAI,YAAAA,SAAe;AAEpC,SAAO,OAAO,YAAyB;AACrC,QAAI;AAEF,YAAM,UAAU,MAAM,QAAQ,KAAK;AAGnC,YAAM,YAAY,QAAQ,QAAQ,IAAI,oBAAoB;AA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AAM,SAAS,MAAM,OAAO,OAAO,OAAO;AAAA,QACxC,YAAY;AAAA,MACd,CAAC;AAED,UAAI,CAAC,OAAO,WAAW,CAAC,OAAO,MAAM;AACnC,cAAM,IAAI,MAAM,OAAO,SAAS,iCAAiC;AAAA,MACnE;AAGA,aAAO,4BAAa,SAAS,OAAO,KAAK,SAAS;AAAA,IACpD,SAAS,OAAO;AACd,YAAM,WACJ,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AAG1D,gBAAU,QAAQ;AAGlB,cAAQ,MAAM,mBAAmB,QAAQ;AAGzC,aAAO,4BAAa;AAAA,QAClB,EAAE,OAAO,mCAAmC;AAAA,QAC5C,EAAE,QAAQ,IAAI;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AACF;","names":["CommetWebhooks","import_node","import_server"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/webhooks.ts","../src/portal.ts","../src/pricing-markdown.ts"],"sourcesContent":["/**\n * @commet/next - Next.js integration for Commet\n *\n * @example\n * Webhooks\n * ```typescript\n * import { Webhooks } from \"@commet/next\";\n *\n * export const POST = Webhooks({\n * webhookSecret: process.env.COMMET_WEBHOOK_SECRET!,\n * onSubscriptionActivated: async (payload) => {\n * // Handle activation\n * },\n * });\n * ```\n *\n * @example\n * Customer Portal\n * ```typescript\n * import { CustomerPortal } from \"@commet/next\";\n *\n * export const GET = CustomerPortal({\n * apiKey: process.env.COMMET_API_KEY!,\n * getCustomerId: async (req) => {\n * const session = await auth.api.getSession({ headers: req.headers });\n * return session?.user.id;\n * },\n * });\n * ```\n *\n * @packageDocumentation\n */\n\nexport { Webhooks } from \"./webhooks\";\nexport type {\n WebhooksConfig,\n WebhookPayload,\n WebhookData,\n WebhookEvent,\n} from \"./types\";\n\nexport { CustomerPortal } from \"./portal\";\nexport type { CustomerPortalConfig } from \"./portal\";\n\nexport { PricingMarkdown } from \"./pricing-markdown\";\nexport type { PricingMarkdownConfig } from \"./pricing-markdown\";\n","import { Webhooks as CommetWebhooks } from \"@commet/node\";\nimport type { WebhookPayload } from \"@commet/node\";\nimport { type NextRequest, NextResponse } from \"next/server\";\nimport type { WebhooksConfig } from \"./types\";\n\n/**\n * Create a Next.js webhook handler for Commet events\n *\n * Automatically verifies signatures, routes events to handlers, and returns proper responses.\n *\n * @param config - Webhook configuration with secret and event handlers\n * @returns Next.js route handler function\n *\n * @example\n * ```typescript\n * // app/api/webhooks/commet/route.ts\n * import { Webhooks } from \"@commet/next\";\n *\n * export const POST = Webhooks({\n * webhookSecret: process.env.COMMET_WEBHOOK_SECRET!,\n * onSubscriptionActivated: async (payload) => {\n * // Grant access to user\n * },\n * onSubscriptionCanceled: async (payload) => {\n * // Revoke access from user\n * },\n * });\n * ```\n */\nexport const Webhooks = (config: WebhooksConfig) => {\n const {\n webhookSecret,\n onSubscriptionActivated,\n onSubscriptionCanceled,\n onSubscriptionCreated,\n onSubscriptionUpdated,\n onPayload,\n onError,\n } = config;\n\n // Create webhook verifier instance\n const webhooks = new CommetWebhooks();\n\n return async (request: NextRequest) => {\n try {\n // 1. Read raw request body\n const rawBody = await request.text();\n\n // 2. Extract signature from headers\n const signature = request.headers.get(\"x-commet-signature\");\n\n // 3. Verify signature\n const isValid = webhooks.verify({\n payload: rawBody,\n signature,\n secret: webhookSecret,\n });\n\n if (!isValid) {\n console.error(\"[Commet Webhook] Invalid signature\");\n return NextResponse.json(\n { received: false, error: \"Invalid signature\" },\n { status: 403 },\n );\n }\n\n // 4. Parse payload\n let payload: WebhookPayload;\n try {\n payload = JSON.parse(rawBody) as WebhookPayload;\n } catch (parseError) {\n console.error(\"[Commet Webhook] Failed to parse payload:\", parseError);\n if (onError) {\n await onError(\n parseError instanceof Error\n ? parseError\n : new Error(\"Failed to parse webhook payload\"),\n rawBody,\n );\n }\n return NextResponse.json(\n { received: false, error: \"Invalid payload\" },\n { status: 400 },\n );\n }\n\n // 5. Collect promises for parallel execution\n const promises: Promise<void>[] = [];\n\n // Call catch-all handler if provided\n if (onPayload) {\n promises.push(onPayload(payload));\n }\n\n // 6. Route to specific event handler\n switch (payload.event) {\n case \"subscription.activated\":\n if (onSubscriptionActivated) {\n promises.push(onSubscriptionActivated(payload));\n }\n break;\n\n case \"subscription.canceled\":\n if (onSubscriptionCanceled) {\n promises.push(onSubscriptionCanceled(payload));\n }\n break;\n\n case \"subscription.created\":\n if (onSubscriptionCreated) {\n promises.push(onSubscriptionCreated(payload));\n }\n break;\n\n case \"subscription.updated\":\n if (onSubscriptionUpdated) {\n promises.push(onSubscriptionUpdated(payload));\n }\n break;\n\n default:\n console.log(`[Commet Webhook] Unhandled event: ${payload.event}`);\n }\n\n // 7. Execute all handlers in parallel\n try {\n await Promise.all(promises);\n } catch (handlerError) {\n console.error(\n \"[Commet Webhook] Handler error:\",\n handlerError instanceof Error ? handlerError.message : handlerError,\n );\n if (onError) {\n await onError(\n handlerError instanceof Error\n ? handlerError\n : new Error(\"Handler execution failed\"),\n payload,\n );\n }\n // Still return 200 to prevent retries for handler errors\n return NextResponse.json(\n { received: true, warning: \"Handler failed\" },\n { status: 200 },\n );\n }\n\n // 8. Success response\n return NextResponse.json({ received: true }, { status: 200 });\n } catch (error) {\n console.error(\"[Commet Webhook] Unexpected error:\", error);\n if (onError) {\n try {\n await onError(\n error instanceof Error ? error : new Error(\"Unexpected error\"),\n undefined,\n );\n } catch (errorHandlerError) {\n console.error(\n \"[Commet Webhook] Error handler failed:\",\n errorHandlerError,\n );\n }\n }\n return NextResponse.json(\n { received: false, error: \"Internal error\" },\n { status: 500 },\n );\n }\n };\n};\n","import { Commet } from \"@commet/node\";\nimport { type NextRequest, NextResponse } from \"next/server\";\n\nexport interface CustomerPortalConfig {\n apiKey: string;\n getCustomerId: (req: NextRequest) => Promise<string | null>;\n environment?: \"sandbox\" | \"production\";\n onError?: (error: Error) => void;\n}\n\n/**\n * Creates Next.js route handler for Customer Portal access\n *\n * @example\n * ```typescript\n * // app/api/commet/portal/route.ts\n * import { CustomerPortal } from \"@commet/next\";\n * import { auth } from \"@/lib/auth\";\n *\n * export const GET = CustomerPortal({\n * apiKey: process.env.COMMET_API_KEY!,\n * getCustomerId: async (req) => {\n * const session = await auth.api.getSession({ headers: req.headers });\n * return session?.user.id ?? null;\n * },\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Use in component\n * export function BillingButton() {\n * return (\n * <Button asChild>\n * <Link href=\"/api/commet/portal\">Manage Billing</Link>\n * </Button>\n * );\n * }\n * ```\n */\nexport const CustomerPortal = ({\n apiKey,\n environment = \"production\",\n getCustomerId,\n onError,\n}: CustomerPortalConfig) => {\n const commet = new Commet({\n apiKey,\n environment,\n });\n\n return async (req: NextRequest) => {\n try {\n // Get customer identifier from request\n const customerId = await getCustomerId(req);\n\n if (!customerId) {\n return NextResponse.json(\n { error: \"Customer not authenticated\" },\n { status: 401 },\n );\n }\n\n // Get portal URL from Commet\n const result = await commet.portal.getUrl({\n externalId: customerId,\n });\n\n if (!result.success || !result.data) {\n throw new Error(result.message || \"Failed to create portal session\");\n }\n\n // Redirect to customer portal\n return NextResponse.redirect(result.data.portalUrl);\n } catch (error) {\n const errorObj =\n error instanceof Error ? error : new Error(String(error));\n\n // Call custom error handler if provided\n onError?.(errorObj);\n\n // Log error\n console.error(\"[Commet Portal]\", errorObj);\n\n // Return error response\n return NextResponse.json(\n { error: \"Failed to access customer portal\" },\n { status: 500 },\n );\n }\n };\n};\n","import { Commet } from \"@commet/node\";\nimport type { BillingInterval, CreditPack, Plan, PlanFeature } from \"@commet/node\";\nimport { type NextRequest, NextResponse } from \"next/server\";\n\nexport interface PricingMarkdownConfig {\n apiKey: string;\n title: string;\n description?: string;\n includeCreditPacks?: boolean;\n billingIntervals?: BillingInterval[];\n cacheMaxAge?: number;\n onError?: (error: Error) => void;\n}\n\nconst INTERVAL_SHORT: Record<BillingInterval, string> = {\n monthly: \"/mo\",\n quarterly: \"/qtr\",\n yearly: \"/yr\",\n};\n\nexport const PricingMarkdown = ({\n apiKey,\n title,\n description,\n includeCreditPacks = false,\n billingIntervals,\n cacheMaxAge = 3600,\n onError,\n}: PricingMarkdownConfig) => {\n const commet = new Commet({ apiKey });\n\n return async (_req: NextRequest) => {\n try {\n const plansResult = await commet.plans.list();\n\n if (!plansResult.success || !plansResult.data) {\n throw new Error(plansResult.message ?? \"Failed to fetch plans\");\n }\n\n const publicPlans = plansResult.data.filter((plan) => plan.isPublic);\n\n const creditPacks = includeCreditPacks\n ? await commet.creditPacks\n .list()\n .then((result) =>\n result.success && result.data ? result.data : [],\n )\n : [];\n\n const markdown = generateMarkdown(\n title,\n description,\n publicPlans,\n creditPacks,\n billingIntervals,\n );\n\n return new NextResponse(markdown, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/markdown; charset=utf-8\",\n \"Cache-Control\": `public, s-maxage=${cacheMaxAge}, stale-while-revalidate=${cacheMaxAge * 2}`,\n },\n });\n } catch (error) {\n const errorObj =\n error instanceof Error ? error : new Error(String(error));\n\n onError?.(errorObj);\n console.error(\"[Commet PricingMarkdown]\", errorObj);\n\n return NextResponse.json(\n { error: \"Failed to generate pricing markdown\" },\n { status: 500 },\n );\n }\n };\n};\n\nfunction generateMarkdown(\n title: string,\n description: string | undefined,\n plans: Plan[],\n creditPacks: CreditPack[],\n billingIntervals?: BillingInterval[],\n): string {\n const sections: string[] = [`# ${title}`];\n\n if (description) {\n sections.push(description);\n }\n\n if (plans.length > 0) {\n sections.push(renderPlansTable(plans, billingIntervals));\n\n const featuresSection = renderFeatures(plans);\n if (featuresSection) {\n sections.push(featuresSection);\n }\n }\n\n if (creditPacks.length > 0) {\n sections.push(renderCreditPacks(creditPacks));\n }\n\n return sections.join(\"\\n\\n\");\n}\n\nfunction renderPlansTable(plans: Plan[], filterIntervals?: BillingInterval[]): string {\n const usageFeatures = collectUsageFeatures(plans);\n\n const headerCols = [\"Plan\", \"Price\"];\n for (const { name, unitName } of usageFeatures) {\n headerCols.push(`${name}/${unitName ?? \"unit\"}`);\n headerCols.push(\"Overage\");\n }\n\n const rows = plans.map((plan) => {\n const priceCell = renderPriceCell(plan, filterIntervals);\n const cols = [plan.name, priceCell];\n\n const featuresByCode = new Map(\n plan.features.map((feature) => [feature.code, feature]),\n );\n\n for (const { code } of usageFeatures) {\n const feature = featuresByCode.get(code);\n\n if (!feature) {\n cols.push(\"—\", \"—\");\n continue;\n }\n\n if (feature.unlimited) {\n cols.push(\"Unlimited\", \"—\");\n continue;\n }\n\n const included = feature.includedAmount;\n cols.push(included ? formatNumber(included) : \"—\");\n\n const overagePrice =\n feature.overageEnabled && feature.overageUnitPrice !== undefined\n ? formatRatePrice(feature.overageUnitPrice)\n : \"—\";\n cols.push(overagePrice);\n }\n\n return cols;\n });\n\n const separator = headerCols.map(() => \"---\");\n const lines = [\n `| ${headerCols.join(\" | \")} |`,\n `| ${separator.join(\" | \")} |`,\n ...rows.map((cols) => `| ${cols.join(\" | \")} |`),\n ];\n\n const footnotes: string[] = [];\n\n const trialPlans = plans.filter((plan) =>\n plan.prices.some((price) => price.trialDays > 0),\n );\n for (const plan of trialPlans) {\n const trialPrice = plan.prices.find((price) => price.trialDays > 0)!;\n footnotes.push(\n `*${plan.name} plan includes a ${trialPrice.trialDays}-day free trial.*`,\n );\n }\n\n if (usageFeatures.length > 0) {\n footnotes.push(\n \"The overage rate applies only to usage beyond the included volume.\",\n );\n }\n\n return footnotes.length > 0\n ? `## Plans\\n\\n${lines.join(\"\\n\")}\\n\\n${footnotes.join(\"\\n\\n\")}`\n : `## Plans\\n\\n${lines.join(\"\\n\")}`;\n}\n\nfunction renderPriceCell(plan: Plan, filterIntervals?: BillingInterval[]): string {\n if (plan.isFree) return \"Free\";\n\n const prices = filterIntervals\n ? plan.prices.filter((price) => filterIntervals.includes(price.billingInterval))\n : plan.prices;\n\n if (prices.length === 0) return \"—\";\n\n return prices\n .map((price) => {\n if (price.price === 0) return \"Free\";\n return `${formatSettlementPrice(price.price)}${INTERVAL_SHORT[price.billingInterval]}`;\n })\n .join(\" / \");\n}\n\nfunction renderFeatures(plans: Plan[]): string | null {\n const allBooleanCodes = new Set<string>();\n for (const plan of plans) {\n for (const feature of plan.features) {\n if (feature.type === \"boolean\") {\n allBooleanCodes.add(feature.code);\n }\n }\n }\n\n if (allBooleanCodes.size === 0) return null;\n\n const enabledOnAll = new Set<string>();\n for (const code of allBooleanCodes) {\n const enabledOnEveryPlan = plans.every((plan) => {\n const feature = plan.features.find((f) => f.code === code);\n return feature?.enabled;\n });\n if (enabledOnEveryPlan) {\n enabledOnAll.add(code);\n }\n }\n\n const perPlanLines: string[] = [];\n for (const plan of plans) {\n const uniqueFeatures = plan.features\n .filter(\n (feature) =>\n feature.type === \"boolean\" &&\n feature.enabled &&\n !enabledOnAll.has(feature.code),\n )\n .map((feature) => feature.name);\n\n if (uniqueFeatures.length > 0) {\n perPlanLines.push(`- **${plan.name}**: ${uniqueFeatures.join(\", \")}`);\n }\n }\n\n const commonFeatures = plans[0]?.features\n .filter(\n (feature) =>\n feature.type === \"boolean\" && enabledOnAll.has(feature.code),\n )\n .map((feature) => feature.name);\n\n const parts: string[] = [];\n\n if (perPlanLines.length > 0) {\n parts.push(perPlanLines.join(\"\\n\"));\n }\n\n if (commonFeatures && commonFeatures.length > 0) {\n parts.push(`All plans include: ${commonFeatures.join(\", \")}.`);\n }\n\n return parts.length > 0 ? `## Features\\n\\n${parts.join(\"\\n\\n\")}` : null;\n}\n\nfunction renderCreditPacks(packs: CreditPack[]): string {\n const lines = [\n \"| Pack | Credits | Price |\",\n \"| --- | --- | --- |\",\n ...packs.map(\n (pack) =>\n `| ${pack.name} | ${formatNumber(pack.credits)} credits | ${formatSettlementPrice(pack.price)} |`,\n ),\n ];\n\n return `## Credit Packs\\n\\n${lines.join(\"\\n\")}`;\n}\n\ninterface UsageFeatureColumn {\n code: string;\n name: string;\n unitName: string | null;\n}\n\nfunction collectUsageFeatures(plans: Plan[]): UsageFeatureColumn[] {\n const seen = new Map<string, UsageFeatureColumn>();\n for (const plan of plans) {\n for (const feature of plan.features) {\n if (\n (feature.type === \"metered\" || feature.type === \"seats\") &&\n !seen.has(feature.code)\n ) {\n seen.set(feature.code, {\n code: feature.code,\n name: feature.name,\n unitName: feature.unitName,\n });\n }\n }\n }\n return Array.from(seen.values());\n}\n\nfunction formatSettlementPrice(cents: number): string {\n if (cents === 0) return \"Free\";\n const dollars = cents / 100;\n const [whole, decimal] = dollars.toFixed(2).split(\".\");\n return `$${Number(whole).toLocaleString(\"en-US\")}.${decimal}`;\n}\n\nfunction formatRatePrice(rate: number): string {\n const dollars = rate / 10000;\n\n if (dollars === Math.floor(dollars)) {\n return `$${dollars.toFixed(2)}`;\n }\n\n const formatted = dollars.toFixed(4).replace(/0+$/, \"\");\n const decimalPlaces = formatted.split(\".\")[1]?.length ?? 0;\n if (decimalPlaces < 2) {\n return `$${dollars.toFixed(2)}`;\n }\n\n return `$${formatted}`;\n}\n\nfunction formatNumber(n: number): string {\n return n.toLocaleString(\"en-US\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAA2C;AAE3C,oBAA+C;AA2BxC,IAAM,WAAW,CAAC,WAA2B;AAClD,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAGJ,QAAM,WAAW,IAAI,YAAAA,SAAe;AAEpC,SAAO,OAAO,YAAyB;AACrC,QAAI;AAEF,YAAM,UAAU,MAAM,QAAQ,KAAK;AAGnC,YAAM,YAAY,QAAQ,QAAQ,IAAI,oBAAoB;AAG1D,YAAM,UAAU,SAAS,OAAO;AAAA,QAC9B,SAAS;AAAA,QACT;AAAA,QACA,QAAQ;AAAA,MACV,CAAC;AAED,UAAI,CAAC,SAAS;AACZ,gBAAQ,MAAM,oCAAoC;AAClD,eAAO,2BAAa;AAAA,UAClB,EAAE,UAAU,OAAO,OAAO,oBAAoB;AAAA,UAC9C,EAAE,QAAQ,I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,OAAO,IAAI,QAAQ,QAAQ,CAAC,EAAE,MAAM,GAAG;AACrD,SAAO,IAAI,OAAO,KAAK,EAAE,eAAe,OAAO,CAAC,IAAI,OAAO;AAC7D;AAEA,SAAS,gBAAgB,MAAsB;AAC7C,QAAM,UAAU,OAAO;AAEvB,MAAI,YAAY,KAAK,MAAM,OAAO,GAAG;AACnC,WAAO,IAAI,QAAQ,QAAQ,CAAC,CAAC;AAAA,EAC/B;AAEA,QAAM,YAAY,QAAQ,QAAQ,CAAC,EAAE,QAAQ,OAAO,EAAE;AACtD,QAAM,gBAAgB,UAAU,MAAM,GAAG,EAAE,CAAC,GAAG,UAAU;AACzD,MAAI,gBAAgB,GAAG;AACrB,WAAO,IAAI,QAAQ,QAAQ,CAAC,CAAC;AAAA,EAC/B;AAEA,SAAO,IAAI,SAAS;AACtB;AAEA,SAAS,aAAa,GAAmB;AACvC,SAAO,EAAE,eAAe,OAAO;AACjC;","names":["CommetWebhooks","import_node","import_server","import_node","import_server"]}
|
package/dist/index.mjs
CHANGED
|
@@ -140,7 +140,7 @@ var CustomerPortal = ({
|
|
|
140
140
|
externalId: customerId
|
|
141
141
|
});
|
|
142
142
|
if (!result.success || !result.data) {
|
|
143
|
-
throw new Error(result.
|
|
143
|
+
throw new Error(result.message || "Failed to create portal session");
|
|
144
144
|
}
|
|
145
145
|
return NextResponse2.redirect(result.data.portalUrl);
|
|
146
146
|
} catch (error) {
|
|
@@ -154,8 +154,239 @@ var CustomerPortal = ({
|
|
|
154
154
|
}
|
|
155
155
|
};
|
|
156
156
|
};
|
|
157
|
+
|
|
158
|
+
// src/pricing-markdown.ts
|
|
159
|
+
import { Commet as Commet2 } from "@commet/node";
|
|
160
|
+
import { NextResponse as NextResponse3 } from "next/server";
|
|
161
|
+
var INTERVAL_SHORT = {
|
|
162
|
+
monthly: "/mo",
|
|
163
|
+
quarterly: "/qtr",
|
|
164
|
+
yearly: "/yr"
|
|
165
|
+
};
|
|
166
|
+
var PricingMarkdown = ({
|
|
167
|
+
apiKey,
|
|
168
|
+
title,
|
|
169
|
+
description,
|
|
170
|
+
includeCreditPacks = false,
|
|
171
|
+
billingIntervals,
|
|
172
|
+
cacheMaxAge = 3600,
|
|
173
|
+
onError
|
|
174
|
+
}) => {
|
|
175
|
+
const commet = new Commet2({ apiKey });
|
|
176
|
+
return async (_req) => {
|
|
177
|
+
try {
|
|
178
|
+
const plansResult = await commet.plans.list();
|
|
179
|
+
if (!plansResult.success || !plansResult.data) {
|
|
180
|
+
throw new Error(plansResult.message ?? "Failed to fetch plans");
|
|
181
|
+
}
|
|
182
|
+
const publicPlans = plansResult.data.filter((plan) => plan.isPublic);
|
|
183
|
+
const creditPacks = includeCreditPacks ? await commet.creditPacks.list().then(
|
|
184
|
+
(result) => result.success && result.data ? result.data : []
|
|
185
|
+
) : [];
|
|
186
|
+
const markdown = generateMarkdown(
|
|
187
|
+
title,
|
|
188
|
+
description,
|
|
189
|
+
publicPlans,
|
|
190
|
+
creditPacks,
|
|
191
|
+
billingIntervals
|
|
192
|
+
);
|
|
193
|
+
return new NextResponse3(markdown, {
|
|
194
|
+
status: 200,
|
|
195
|
+
headers: {
|
|
196
|
+
"Content-Type": "text/markdown; charset=utf-8",
|
|
197
|
+
"Cache-Control": `public, s-maxage=${cacheMaxAge}, stale-while-revalidate=${cacheMaxAge * 2}`
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
} catch (error) {
|
|
201
|
+
const errorObj = error instanceof Error ? error : new Error(String(error));
|
|
202
|
+
onError?.(errorObj);
|
|
203
|
+
console.error("[Commet PricingMarkdown]", errorObj);
|
|
204
|
+
return NextResponse3.json(
|
|
205
|
+
{ error: "Failed to generate pricing markdown" },
|
|
206
|
+
{ status: 500 }
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
};
|
|
211
|
+
function generateMarkdown(title, description, plans, creditPacks, billingIntervals) {
|
|
212
|
+
const sections = [`# ${title}`];
|
|
213
|
+
if (description) {
|
|
214
|
+
sections.push(description);
|
|
215
|
+
}
|
|
216
|
+
if (plans.length > 0) {
|
|
217
|
+
sections.push(renderPlansTable(plans, billingIntervals));
|
|
218
|
+
const featuresSection = renderFeatures(plans);
|
|
219
|
+
if (featuresSection) {
|
|
220
|
+
sections.push(featuresSection);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
if (creditPacks.length > 0) {
|
|
224
|
+
sections.push(renderCreditPacks(creditPacks));
|
|
225
|
+
}
|
|
226
|
+
return sections.join("\n\n");
|
|
227
|
+
}
|
|
228
|
+
function renderPlansTable(plans, filterIntervals) {
|
|
229
|
+
const usageFeatures = collectUsageFeatures(plans);
|
|
230
|
+
const headerCols = ["Plan", "Price"];
|
|
231
|
+
for (const { name, unitName } of usageFeatures) {
|
|
232
|
+
headerCols.push(`${name}/${unitName ?? "unit"}`);
|
|
233
|
+
headerCols.push("Overage");
|
|
234
|
+
}
|
|
235
|
+
const rows = plans.map((plan) => {
|
|
236
|
+
const priceCell = renderPriceCell(plan, filterIntervals);
|
|
237
|
+
const cols = [plan.name, priceCell];
|
|
238
|
+
const featuresByCode = new Map(
|
|
239
|
+
plan.features.map((feature) => [feature.code, feature])
|
|
240
|
+
);
|
|
241
|
+
for (const { code } of usageFeatures) {
|
|
242
|
+
const feature = featuresByCode.get(code);
|
|
243
|
+
if (!feature) {
|
|
244
|
+
cols.push("\u2014", "\u2014");
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
if (feature.unlimited) {
|
|
248
|
+
cols.push("Unlimited", "\u2014");
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
const included = feature.includedAmount;
|
|
252
|
+
cols.push(included ? formatNumber(included) : "\u2014");
|
|
253
|
+
const overagePrice = feature.overageEnabled && feature.overageUnitPrice !== void 0 ? formatRatePrice(feature.overageUnitPrice) : "\u2014";
|
|
254
|
+
cols.push(overagePrice);
|
|
255
|
+
}
|
|
256
|
+
return cols;
|
|
257
|
+
});
|
|
258
|
+
const separator = headerCols.map(() => "---");
|
|
259
|
+
const lines = [
|
|
260
|
+
`| ${headerCols.join(" | ")} |`,
|
|
261
|
+
`| ${separator.join(" | ")} |`,
|
|
262
|
+
...rows.map((cols) => `| ${cols.join(" | ")} |`)
|
|
263
|
+
];
|
|
264
|
+
const footnotes = [];
|
|
265
|
+
const trialPlans = plans.filter(
|
|
266
|
+
(plan) => plan.prices.some((price) => price.trialDays > 0)
|
|
267
|
+
);
|
|
268
|
+
for (const plan of trialPlans) {
|
|
269
|
+
const trialPrice = plan.prices.find((price) => price.trialDays > 0);
|
|
270
|
+
footnotes.push(
|
|
271
|
+
`*${plan.name} plan includes a ${trialPrice.trialDays}-day free trial.*`
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
if (usageFeatures.length > 0) {
|
|
275
|
+
footnotes.push(
|
|
276
|
+
"The overage rate applies only to usage beyond the included volume."
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
return footnotes.length > 0 ? `## Plans
|
|
280
|
+
|
|
281
|
+
${lines.join("\n")}
|
|
282
|
+
|
|
283
|
+
${footnotes.join("\n\n")}` : `## Plans
|
|
284
|
+
|
|
285
|
+
${lines.join("\n")}`;
|
|
286
|
+
}
|
|
287
|
+
function renderPriceCell(plan, filterIntervals) {
|
|
288
|
+
if (plan.isFree) return "Free";
|
|
289
|
+
const prices = filterIntervals ? plan.prices.filter((price) => filterIntervals.includes(price.billingInterval)) : plan.prices;
|
|
290
|
+
if (prices.length === 0) return "\u2014";
|
|
291
|
+
return prices.map((price) => {
|
|
292
|
+
if (price.price === 0) return "Free";
|
|
293
|
+
return `${formatSettlementPrice(price.price)}${INTERVAL_SHORT[price.billingInterval]}`;
|
|
294
|
+
}).join(" / ");
|
|
295
|
+
}
|
|
296
|
+
function renderFeatures(plans) {
|
|
297
|
+
const allBooleanCodes = /* @__PURE__ */ new Set();
|
|
298
|
+
for (const plan of plans) {
|
|
299
|
+
for (const feature of plan.features) {
|
|
300
|
+
if (feature.type === "boolean") {
|
|
301
|
+
allBooleanCodes.add(feature.code);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
if (allBooleanCodes.size === 0) return null;
|
|
306
|
+
const enabledOnAll = /* @__PURE__ */ new Set();
|
|
307
|
+
for (const code of allBooleanCodes) {
|
|
308
|
+
const enabledOnEveryPlan = plans.every((plan) => {
|
|
309
|
+
const feature = plan.features.find((f) => f.code === code);
|
|
310
|
+
return feature?.enabled;
|
|
311
|
+
});
|
|
312
|
+
if (enabledOnEveryPlan) {
|
|
313
|
+
enabledOnAll.add(code);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
const perPlanLines = [];
|
|
317
|
+
for (const plan of plans) {
|
|
318
|
+
const uniqueFeatures = plan.features.filter(
|
|
319
|
+
(feature) => feature.type === "boolean" && feature.enabled && !enabledOnAll.has(feature.code)
|
|
320
|
+
).map((feature) => feature.name);
|
|
321
|
+
if (uniqueFeatures.length > 0) {
|
|
322
|
+
perPlanLines.push(`- **${plan.name}**: ${uniqueFeatures.join(", ")}`);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
const commonFeatures = plans[0]?.features.filter(
|
|
326
|
+
(feature) => feature.type === "boolean" && enabledOnAll.has(feature.code)
|
|
327
|
+
).map((feature) => feature.name);
|
|
328
|
+
const parts = [];
|
|
329
|
+
if (perPlanLines.length > 0) {
|
|
330
|
+
parts.push(perPlanLines.join("\n"));
|
|
331
|
+
}
|
|
332
|
+
if (commonFeatures && commonFeatures.length > 0) {
|
|
333
|
+
parts.push(`All plans include: ${commonFeatures.join(", ")}.`);
|
|
334
|
+
}
|
|
335
|
+
return parts.length > 0 ? `## Features
|
|
336
|
+
|
|
337
|
+
${parts.join("\n\n")}` : null;
|
|
338
|
+
}
|
|
339
|
+
function renderCreditPacks(packs) {
|
|
340
|
+
const lines = [
|
|
341
|
+
"| Pack | Credits | Price |",
|
|
342
|
+
"| --- | --- | --- |",
|
|
343
|
+
...packs.map(
|
|
344
|
+
(pack) => `| ${pack.name} | ${formatNumber(pack.credits)} credits | ${formatSettlementPrice(pack.price)} |`
|
|
345
|
+
)
|
|
346
|
+
];
|
|
347
|
+
return `## Credit Packs
|
|
348
|
+
|
|
349
|
+
${lines.join("\n")}`;
|
|
350
|
+
}
|
|
351
|
+
function collectUsageFeatures(plans) {
|
|
352
|
+
const seen = /* @__PURE__ */ new Map();
|
|
353
|
+
for (const plan of plans) {
|
|
354
|
+
for (const feature of plan.features) {
|
|
355
|
+
if ((feature.type === "metered" || feature.type === "seats") && !seen.has(feature.code)) {
|
|
356
|
+
seen.set(feature.code, {
|
|
357
|
+
code: feature.code,
|
|
358
|
+
name: feature.name,
|
|
359
|
+
unitName: feature.unitName
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
return Array.from(seen.values());
|
|
365
|
+
}
|
|
366
|
+
function formatSettlementPrice(cents) {
|
|
367
|
+
if (cents === 0) return "Free";
|
|
368
|
+
const dollars = cents / 100;
|
|
369
|
+
const [whole, decimal] = dollars.toFixed(2).split(".");
|
|
370
|
+
return `$${Number(whole).toLocaleString("en-US")}.${decimal}`;
|
|
371
|
+
}
|
|
372
|
+
function formatRatePrice(rate) {
|
|
373
|
+
const dollars = rate / 1e4;
|
|
374
|
+
if (dollars === Math.floor(dollars)) {
|
|
375
|
+
return `$${dollars.toFixed(2)}`;
|
|
376
|
+
}
|
|
377
|
+
const formatted = dollars.toFixed(4).replace(/0+$/, "");
|
|
378
|
+
const decimalPlaces = formatted.split(".")[1]?.length ?? 0;
|
|
379
|
+
if (decimalPlaces < 2) {
|
|
380
|
+
return `$${dollars.toFixed(2)}`;
|
|
381
|
+
}
|
|
382
|
+
return `$${formatted}`;
|
|
383
|
+
}
|
|
384
|
+
function formatNumber(n) {
|
|
385
|
+
return n.toLocaleString("en-US");
|
|
386
|
+
}
|
|
157
387
|
export {
|
|
158
388
|
CustomerPortal,
|
|
389
|
+
PricingMarkdown,
|
|
159
390
|
Webhooks
|
|
160
391
|
};
|
|
161
392
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/webhooks.ts","../src/portal.ts"],"sourcesContent":["import { Webhooks as CommetWebhooks } from \"@commet/node\";\nimport type { WebhookPayload } from \"@commet/node\";\nimport { type NextRequest, NextResponse } from \"next/server\";\nimport type { WebhooksConfig } from \"./types\";\n\n/**\n * Create a Next.js webhook handler for Commet events\n *\n * Automatically verifies signatures, routes events to handlers, and returns proper responses.\n *\n * @param config - Webhook configuration with secret and event handlers\n * @returns Next.js route handler function\n *\n * @example\n * ```typescript\n * // app/api/webhooks/commet/route.ts\n * import { Webhooks } from \"@commet/next\";\n *\n * export const POST = Webhooks({\n * webhookSecret: process.env.COMMET_WEBHOOK_SECRET!,\n * onSubscriptionActivated: async (payload) => {\n * // Grant access to user\n * },\n * onSubscriptionCanceled: async (payload) => {\n * // Revoke access from user\n * },\n * });\n * ```\n */\nexport const Webhooks = (config: WebhooksConfig) => {\n const {\n webhookSecret,\n onSubscriptionActivated,\n onSubscriptionCanceled,\n onSubscriptionCreated,\n onSubscriptionUpdated,\n onPayload,\n onError,\n } = config;\n\n // Create webhook verifier instance\n const webhooks = new CommetWebhooks();\n\n return async (request: NextRequest) => {\n try {\n // 1. Read raw request body\n const rawBody = await request.text();\n\n // 2. Extract signature from headers\n const signature = request.headers.get(\"x-commet-signature\");\n\n // 3. Verify signature\n const isValid = webhooks.verify({\n payload: rawBody,\n signature,\n secret: webhookSecret,\n });\n\n if (!isValid) {\n console.error(\"[Commet Webhook] Invalid signature\");\n return NextResponse.json(\n { received: false, error: \"Invalid signature\" },\n { status: 403 },\n );\n }\n\n // 4. Parse payload\n let payload: WebhookPayload;\n try {\n payload = JSON.parse(rawBody) as WebhookPayload;\n } catch (parseError) {\n console.error(\"[Commet Webhook] Failed to parse payload:\", parseError);\n if (onError) {\n await onError(\n parseError instanceof Error\n ? parseError\n : new Error(\"Failed to parse webhook payload\"),\n rawBody,\n );\n }\n return NextResponse.json(\n { received: false, error: \"Invalid payload\" },\n { status: 400 },\n );\n }\n\n // 5. Collect promises for parallel execution\n const promises: Promise<void>[] = [];\n\n // Call catch-all handler if provided\n if (onPayload) {\n promises.push(onPayload(payload));\n }\n\n // 6. Route to specific event handler\n switch (payload.event) {\n case \"subscription.activated\":\n if (onSubscriptionActivated) {\n promises.push(onSubscriptionActivated(payload));\n }\n break;\n\n case \"subscription.canceled\":\n if (onSubscriptionCanceled) {\n promises.push(onSubscriptionCanceled(payload));\n }\n break;\n\n case \"subscription.created\":\n if (onSubscriptionCreated) {\n promises.push(onSubscriptionCreated(payload));\n }\n break;\n\n case \"subscription.updated\":\n if (onSubscriptionUpdated) {\n promises.push(onSubscriptionUpdated(payload));\n }\n break;\n\n default:\n console.log(`[Commet Webhook] Unhandled event: ${payload.event}`);\n }\n\n // 7. Execute all handlers in parallel\n try {\n await Promise.all(promises);\n } catch (handlerError) {\n console.error(\n \"[Commet Webhook] Handler error:\",\n handlerError instanceof Error ? handlerError.message : handlerError,\n );\n if (onError) {\n await onError(\n handlerError instanceof Error\n ? handlerError\n : new Error(\"Handler execution failed\"),\n payload,\n );\n }\n // Still return 200 to prevent retries for handler errors\n return NextResponse.json(\n { received: true, warning: \"Handler failed\" },\n { status: 200 },\n );\n }\n\n // 8. Success response\n return NextResponse.json({ received: true }, { status: 200 });\n } catch (error) {\n console.error(\"[Commet Webhook] Unexpected error:\", error);\n if (onError) {\n try {\n await onError(\n error instanceof Error ? error : new Error(\"Unexpected error\"),\n undefined,\n );\n } catch (errorHandlerError) {\n console.error(\n \"[Commet Webhook] Error handler failed:\",\n errorHandlerError,\n );\n }\n }\n return NextResponse.json(\n { received: false, error: \"Internal error\" },\n { status: 500 },\n );\n }\n };\n};\n","import { Commet } from \"@commet/node\";\nimport { type NextRequest, NextResponse } from \"next/server\";\n\nexport interface CustomerPortalConfig {\n apiKey: string;\n getCustomerId: (req: NextRequest) => Promise<string | null>;\n environment?: \"sandbox\" | \"production\";\n onError?: (error: Error) => void;\n}\n\n/**\n * Creates Next.js route handler for Customer Portal access\n *\n * @example\n * ```typescript\n * // app/api/commet/portal/route.ts\n * import { CustomerPortal } from \"@commet/next\";\n * import { auth } from \"@/lib/auth\";\n *\n * export const GET = CustomerPortal({\n * apiKey: process.env.COMMET_API_KEY!,\n * getCustomerId: async (req) => {\n * const session = await auth.api.getSession({ headers: req.headers });\n * return session?.user.id ?? null;\n * },\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Use in component\n * export function BillingButton() {\n * return (\n * <Button asChild>\n * <Link href=\"/api/commet/portal\">Manage Billing</Link>\n * </Button>\n * );\n * }\n * ```\n */\nexport const CustomerPortal = ({\n apiKey,\n environment = \"production\",\n getCustomerId,\n onError,\n}: CustomerPortalConfig) => {\n const commet = new Commet({\n apiKey,\n environment,\n });\n\n return async (req: NextRequest) => {\n try {\n // Get customer identifier from request\n const customerId = await getCustomerId(req);\n\n if (!customerId) {\n return NextResponse.json(\n { error: \"Customer not authenticated\" },\n { status: 401 },\n );\n }\n\n // Get portal URL from Commet\n const result = await commet.portal.getUrl({\n externalId: customerId,\n });\n\n if (!result.success || !result.data) {\n throw new Error(result.error || \"Failed to create portal session\");\n }\n\n // Redirect to customer portal\n return NextResponse.redirect(result.data.portalUrl);\n } catch (error) {\n const errorObj =\n error instanceof Error ? error : new Error(String(error));\n\n // Call custom error handler if provided\n onError?.(errorObj);\n\n // Log error\n console.error(\"[Commet Portal]\", errorObj);\n\n // Return error response\n return NextResponse.json(\n { error: \"Failed to access customer portal\" },\n { status: 500 },\n );\n }\n };\n};\n"],"mappings":";AAAA,SAAS,YAAY,sBAAsB;AAE3C,SAA2B,oBAAoB;AA2BxC,IAAM,WAAW,CAAC,WAA2B;AAClD,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF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M,aAAa,MAAM,cAAc,GAAG;AAE1C,UAAI,CAAC,YAAY;AACf,eAAOA,cAAa;AAAA,UAClB,EAAE,OAAO,6BAA6B;AAAA,UACtC,EAAE,QAAQ,IAAI;AAAA,QAChB;AAAA,MACF;AAGA,YAAM,SAAS,MAAM,OAAO,OAAO,OAAO;AAAA,QACxC,YAAY;AAAA,MACd,CAAC;AAED,UAAI,CAAC,OAAO,WAAW,CAAC,OAAO,MAAM;AACnC,cAAM,IAAI,MAAM,OAAO,SAAS,iCAAiC;AAAA,MACnE;AAGA,aAAOA,cAAa,SAAS,OAAO,KAAK,SAAS;AAAA,IACpD,SAAS,OAAO;AACd,YAAM,WACJ,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AAG1D,gBAAU,QAAQ;AAGlB,cAAQ,MAAM,mBAAmB,QAAQ;AAGzC,aAAOA,cAAa;AAAA,QAClB,EAAE,OAAO,mCAAmC;AAAA,QAC5C,EAAE,QAAQ,IAAI;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AACF;","names":["NextResponse"]}
|
|
1
|
+
{"version":3,"sources":["../src/webhooks.ts","../src/portal.ts","../src/pricing-markdown.ts"],"sourcesContent":["import { Webhooks as CommetWebhooks } from \"@commet/node\";\nimport type { WebhookPayload } from \"@commet/node\";\nimport { type NextRequest, NextResponse } from \"next/server\";\nimport type { WebhooksConfig } from \"./types\";\n\n/**\n * Create a Next.js webhook handler for Commet events\n *\n * Automatically verifies signatures, routes events to handlers, and returns proper responses.\n *\n * @param config - Webhook configuration with secret and event handlers\n * @returns Next.js route handler function\n *\n * @example\n * ```typescript\n * // app/api/webhooks/commet/route.ts\n * import { Webhooks } from \"@commet/next\";\n *\n * export const POST = Webhooks({\n * webhookSecret: process.env.COMMET_WEBHOOK_SECRET!,\n * onSubscriptionActivated: async (payload) => {\n * // Grant access to user\n * },\n * onSubscriptionCanceled: async (payload) => {\n * // Revoke access from user\n * },\n * });\n * ```\n */\nexport const Webhooks = (config: WebhooksConfig) => {\n const {\n webhookSecret,\n onSubscriptionActivated,\n onSubscriptionCanceled,\n onSubscriptionCreated,\n onSubscriptionUpdated,\n onPayload,\n onError,\n } = config;\n\n // Create webhook verifier instance\n const webhooks = new CommetWebhooks();\n\n return async (request: NextRequest) => {\n try {\n // 1. Read raw request body\n const rawBody = await request.text();\n\n // 2. Extract signature from headers\n const signature = request.headers.get(\"x-commet-signature\");\n\n // 3. Verify signature\n const isValid = webhooks.verify({\n payload: rawBody,\n signature,\n secret: webhookSecret,\n });\n\n if (!isValid) {\n console.error(\"[Commet Webhook] Invalid signature\");\n return NextResponse.json(\n { received: false, error: \"Invalid signature\" },\n { status: 403 },\n );\n }\n\n // 4. Parse payload\n let payload: WebhookPayload;\n try {\n payload = JSON.parse(rawBody) as WebhookPayload;\n } catch (parseError) {\n console.error(\"[Commet Webhook] Failed to parse payload:\", parseError);\n if (onError) {\n await onError(\n parseError instanceof Error\n ? parseError\n : new Error(\"Failed to parse webhook payload\"),\n rawBody,\n );\n }\n return NextResponse.json(\n { received: false, error: \"Invalid payload\" },\n { status: 400 },\n );\n }\n\n // 5. Collect promises for parallel execution\n const promises: Promise<void>[] = [];\n\n // Call catch-all handler if provided\n if (onPayload) {\n promises.push(onPayload(payload));\n }\n\n // 6. Route to specific event handler\n switch (payload.event) {\n case \"subscription.activated\":\n if (onSubscriptionActivated) {\n promises.push(onSubscriptionActivated(payload));\n }\n break;\n\n case \"subscription.canceled\":\n if (onSubscriptionCanceled) {\n promises.push(onSubscriptionCanceled(payload));\n }\n break;\n\n case \"subscription.created\":\n if (onSubscriptionCreated) {\n promises.push(onSubscriptionCreated(payload));\n }\n break;\n\n case \"subscription.updated\":\n if (onSubscriptionUpdated) {\n promises.push(onSubscriptionUpdated(payload));\n }\n break;\n\n default:\n console.log(`[Commet Webhook] Unhandled event: ${payload.event}`);\n }\n\n // 7. Execute all handlers in parallel\n try {\n await Promise.all(promises);\n } catch (handlerError) {\n console.error(\n \"[Commet Webhook] Handler error:\",\n handlerError instanceof Error ? handlerError.message : handlerError,\n );\n if (onError) {\n await onError(\n handlerError instanceof Error\n ? handlerError\n : new Error(\"Handler execution failed\"),\n payload,\n );\n }\n // Still return 200 to prevent retries for handler errors\n return NextResponse.json(\n { received: true, warning: \"Handler failed\" },\n { status: 200 },\n );\n }\n\n // 8. Success response\n return NextResponse.json({ received: true }, { status: 200 });\n } catch (error) {\n console.error(\"[Commet Webhook] Unexpected error:\", error);\n if (onError) {\n try {\n await onError(\n error instanceof Error ? error : new Error(\"Unexpected error\"),\n undefined,\n );\n } catch (errorHandlerError) {\n console.error(\n \"[Commet Webhook] Error handler failed:\",\n errorHandlerError,\n );\n }\n }\n return NextResponse.json(\n { received: false, error: \"Internal error\" },\n { status: 500 },\n );\n }\n };\n};\n","import { Commet } from \"@commet/node\";\nimport { type NextRequest, NextResponse } from \"next/server\";\n\nexport interface CustomerPortalConfig {\n apiKey: string;\n getCustomerId: (req: NextRequest) => Promise<string | null>;\n environment?: \"sandbox\" | \"production\";\n onError?: (error: Error) => void;\n}\n\n/**\n * Creates Next.js route handler for Customer Portal access\n *\n * @example\n * ```typescript\n * // app/api/commet/portal/route.ts\n * import { CustomerPortal } from \"@commet/next\";\n * import { auth } from \"@/lib/auth\";\n *\n * export const GET = CustomerPortal({\n * apiKey: process.env.COMMET_API_KEY!,\n * getCustomerId: async (req) => {\n * const session = await auth.api.getSession({ headers: req.headers });\n * return session?.user.id ?? null;\n * },\n * });\n * ```\n *\n * @example\n * ```tsx\n * // Use in component\n * export function BillingButton() {\n * return (\n * <Button asChild>\n * <Link href=\"/api/commet/portal\">Manage Billing</Link>\n * </Button>\n * );\n * }\n * ```\n */\nexport const CustomerPortal = ({\n apiKey,\n environment = \"production\",\n getCustomerId,\n onError,\n}: CustomerPortalConfig) => {\n const commet = new Commet({\n apiKey,\n environment,\n });\n\n return async (req: NextRequest) => {\n try {\n // Get customer identifier from request\n const customerId = await getCustomerId(req);\n\n if (!customerId) {\n return NextResponse.json(\n { error: \"Customer not authenticated\" },\n { status: 401 },\n );\n }\n\n // Get portal URL from Commet\n const result = await commet.portal.getUrl({\n externalId: customerId,\n });\n\n if (!result.success || !result.data) {\n throw new Error(result.message || \"Failed to create portal session\");\n }\n\n // Redirect to customer portal\n return NextResponse.redirect(result.data.portalUrl);\n } catch (error) {\n const errorObj =\n error instanceof Error ? error : new Error(String(error));\n\n // Call custom error handler if provided\n onError?.(errorObj);\n\n // Log error\n console.error(\"[Commet Portal]\", errorObj);\n\n // Return error response\n return NextResponse.json(\n { error: \"Failed to access customer portal\" },\n { status: 500 },\n );\n }\n };\n};\n","import { Commet } from \"@commet/node\";\nimport type { BillingInterval, CreditPack, Plan, PlanFeature } from \"@commet/node\";\nimport { type NextRequest, NextResponse } from \"next/server\";\n\nexport interface PricingMarkdownConfig {\n apiKey: string;\n title: string;\n description?: string;\n includeCreditPacks?: boolean;\n billingIntervals?: BillingInterval[];\n cacheMaxAge?: number;\n onError?: (error: Error) => void;\n}\n\nconst INTERVAL_SHORT: Record<BillingInterval, string> = {\n monthly: \"/mo\",\n quarterly: \"/qtr\",\n yearly: \"/yr\",\n};\n\nexport const PricingMarkdown = ({\n apiKey,\n title,\n description,\n includeCreditPacks = false,\n billingIntervals,\n cacheMaxAge = 3600,\n onError,\n}: PricingMarkdownConfig) => {\n const commet = new Commet({ apiKey });\n\n return async (_req: NextRequest) => {\n try {\n const plansResult = await commet.plans.list();\n\n if (!plansResult.success || !plansResult.data) {\n throw new Error(plansResult.message ?? \"Failed to fetch plans\");\n }\n\n const publicPlans = plansResult.data.filter((plan) => plan.isPublic);\n\n const creditPacks = includeCreditPacks\n ? await commet.creditPacks\n .list()\n .then((result) =>\n result.success && result.data ? result.data : [],\n )\n : [];\n\n const markdown = generateMarkdown(\n title,\n description,\n publicPlans,\n creditPacks,\n billingIntervals,\n );\n\n return new NextResponse(markdown, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/markdown; charset=utf-8\",\n \"Cache-Control\": `public, s-maxage=${cacheMaxAge}, stale-while-revalidate=${cacheMaxAge * 2}`,\n },\n });\n } catch (error) {\n const errorObj =\n error instanceof Error ? error : new Error(String(error));\n\n onError?.(errorObj);\n console.error(\"[Commet PricingMarkdown]\", errorObj);\n\n return NextResponse.json(\n { error: \"Failed to generate pricing markdown\" },\n { status: 500 },\n );\n }\n };\n};\n\nfunction generateMarkdown(\n title: string,\n description: string | undefined,\n plans: Plan[],\n creditPacks: CreditPack[],\n billingIntervals?: BillingInterval[],\n): string {\n const sections: string[] = [`# ${title}`];\n\n if (description) {\n sections.push(description);\n }\n\n if (plans.length > 0) {\n sections.push(renderPlansTable(plans, billingIntervals));\n\n const featuresSection = renderFeatures(plans);\n if (featuresSection) {\n sections.push(featuresSection);\n }\n }\n\n if (creditPacks.length > 0) {\n sections.push(renderCreditPacks(creditPacks));\n }\n\n return sections.join(\"\\n\\n\");\n}\n\nfunction renderPlansTable(plans: Plan[], filterIntervals?: BillingInterval[]): string {\n const usageFeatures = collectUsageFeatures(plans);\n\n const headerCols = [\"Plan\", \"Price\"];\n for (const { name, unitName } of usageFeatures) {\n headerCols.push(`${name}/${unitName ?? \"unit\"}`);\n headerCols.push(\"Overage\");\n }\n\n const rows = plans.map((plan) => {\n const priceCell = renderPriceCell(plan, filterIntervals);\n const cols = [plan.name, priceCell];\n\n const featuresByCode = new Map(\n plan.features.map((feature) => [feature.code, feature]),\n );\n\n for (const { code } of usageFeatures) {\n const feature = featuresByCode.get(code);\n\n if (!feature) {\n cols.push(\"—\", \"—\");\n continue;\n }\n\n if (feature.unlimited) {\n cols.push(\"Unlimited\", \"—\");\n continue;\n }\n\n const included = feature.includedAmount;\n cols.push(included ? formatNumber(included) : \"—\");\n\n const overagePrice =\n feature.overageEnabled && feature.overageUnitPrice !== undefined\n ? formatRatePrice(feature.overageUnitPrice)\n : \"—\";\n cols.push(overagePrice);\n }\n\n return cols;\n });\n\n const separator = headerCols.map(() => \"---\");\n const lines = [\n `| ${headerCols.join(\" | \")} |`,\n `| ${separator.join(\" | \")} |`,\n ...rows.map((cols) => `| ${cols.join(\" | \")} |`),\n ];\n\n const footnotes: string[] = [];\n\n const trialPlans = plans.filter((plan) =>\n plan.prices.some((price) => price.trialDays > 0),\n );\n for (const plan of trialPlans) {\n const trialPrice = plan.prices.find((price) => price.trialDays > 0)!;\n footnotes.push(\n `*${plan.name} plan includes a ${trialPrice.trialDays}-day free trial.*`,\n );\n }\n\n if (usageFeatures.length > 0) {\n footnotes.push(\n \"The overage rate applies only to usage beyond the included volume.\",\n );\n }\n\n return footnotes.length > 0\n ? `## Plans\\n\\n${lines.join(\"\\n\")}\\n\\n${footnotes.join(\"\\n\\n\")}`\n : `## Plans\\n\\n${lines.join(\"\\n\")}`;\n}\n\nfunction renderPriceCell(plan: Plan, filterIntervals?: BillingInterval[]): string {\n if (plan.isFree) return \"Free\";\n\n const prices = filterIntervals\n ? plan.prices.filter((price) => filterIntervals.includes(price.billingInterval))\n : plan.prices;\n\n if (prices.length === 0) return \"—\";\n\n return prices\n .map((price) => {\n if (price.price === 0) return \"Free\";\n return `${formatSettlementPrice(price.price)}${INTERVAL_SHORT[price.billingInterval]}`;\n })\n .join(\" / \");\n}\n\nfunction renderFeatures(plans: Plan[]): string | null {\n const allBooleanCodes = new Set<string>();\n for (const plan of plans) {\n for (const feature of plan.features) {\n if (feature.type === \"boolean\") {\n allBooleanCodes.add(feature.code);\n }\n }\n }\n\n if (allBooleanCodes.size === 0) return null;\n\n const enabledOnAll = new Set<string>();\n for (const code of allBooleanCodes) {\n const enabledOnEveryPlan = plans.every((plan) => {\n const feature = plan.features.find((f) => f.code === code);\n return feature?.enabled;\n });\n if (enabledOnEveryPlan) {\n enabledOnAll.add(code);\n }\n }\n\n const perPlanLines: string[] = [];\n for (const plan of plans) {\n const uniqueFeatures = plan.features\n .filter(\n (feature) =>\n feature.type === \"boolean\" &&\n feature.enabled &&\n !enabledOnAll.has(feature.code),\n )\n .map((feature) => feature.name);\n\n if (uniqueFeatures.length > 0) {\n perPlanLines.push(`- **${plan.name}**: ${uniqueFeatures.join(\", \")}`);\n }\n }\n\n const commonFeatures = plans[0]?.features\n .filter(\n (feature) =>\n feature.type === \"boolean\" && enabledOnAll.has(feature.code),\n )\n .map((feature) => feature.name);\n\n const parts: string[] = [];\n\n if (perPlanLines.length > 0) {\n parts.push(perPlanLines.join(\"\\n\"));\n }\n\n if (commonFeatures && commonFeatures.length > 0) {\n parts.push(`All plans include: ${commonFeatures.join(\", \")}.`);\n }\n\n return parts.length > 0 ? `## Features\\n\\n${parts.join(\"\\n\\n\")}` : null;\n}\n\nfunction renderCreditPacks(packs: CreditPack[]): string {\n const lines = [\n \"| Pack | Credits | Price |\",\n \"| --- | --- | --- |\",\n ...packs.map(\n (pack) =>\n `| ${pack.name} | ${formatNumber(pack.credits)} credits | ${formatSettlementPrice(pack.price)} |`,\n ),\n ];\n\n return `## Credit Packs\\n\\n${lines.join(\"\\n\")}`;\n}\n\ninterface UsageFeatureColumn {\n code: string;\n name: string;\n unitName: string | null;\n}\n\nfunction collectUsageFeatures(plans: Plan[]): UsageFeatureColumn[] {\n const seen = new Map<string, UsageFeatureColumn>();\n for (const plan of plans) {\n for (const feature of plan.features) {\n if (\n (feature.type === \"metered\" || feature.type === \"seats\") &&\n !seen.has(feature.code)\n ) {\n seen.set(feature.code, {\n code: feature.code,\n name: feature.name,\n unitName: feature.unitName,\n });\n }\n }\n }\n return Array.from(seen.values());\n}\n\nfunction formatSettlementPrice(cents: number): string {\n if (cents === 0) return \"Free\";\n const dollars = cents / 100;\n const [whole, decimal] = dollars.toFixed(2).split(\".\");\n return `$${Number(whole).toLocaleString(\"en-US\")}.${decimal}`;\n}\n\nfunction formatRatePrice(rate: number): string {\n const dollars = rate / 10000;\n\n if (dollars === Math.floor(dollars)) {\n return `$${dollars.toFixed(2)}`;\n }\n\n const formatted = dollars.toFixed(4).replace(/0+$/, \"\");\n const decimalPlaces = formatted.split(\".\")[1]?.length ?? 0;\n if (decimalPlaces < 2) {\n return `$${dollars.toFixed(2)}`;\n }\n\n return `$${formatted}`;\n}\n\nfunction formatNumber(n: number): string {\n return n.toLocaleString(\"en-US\");\n}\n"],"mappings":";AAAA,SAAS,YAAY,sBAAsB;AAE3C,SAA2B,oBAAoB;AA2BxC,IAAM,WAAW,CAAC,WAA2B;AAClD,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAGJ,QAAM,WAAW,IAAI,eAAe;AAEpC,SAAO,OAAO,YAAyB;AACrC,QAAI;AAEF,YAAM,UAAU,MAAM,QAAQ,KAAK;AAGnC,YAAM,YAAY,QAAQ,QAAQ,IAAI,oBAAoB;AAG1D,YAAM,UAAU,SAAS,OAAO;AAAA,QAC9B,SAAS;AAAA,QACT;AAAA,QACA,QAAQ;AAAA,MACV,CAAC;AAED,UAAI,CAAC,SAAS;AACZ,gBAAQ,MAAM,oCAAoC;AAClD,eAAO,aAAa;AAAA,UAClB,EAAE,UAAU,OAAO,OAAO,oBAAoB;AAAA,UAC9C,EAAE,QAAQ,IAAI;AAAA,QAChB;AAAA,MACF;AAGA,UAAI;AACJ,UAAI;AACF,kBAAU,KAAK,MAAM,OAAO;AAAA,MAC9B,SAAS,YAAY;AACnB,gBAAQ,MAAM,6CAA6C,UAAU;AACrE,YAAI,SAAS;AACX,gBAAM;AAAA,YACJ,sBAAsB,QAClB,aACA,IAAI,MAAM,iCAAiC;AAAA,YAC/C;AAAA,UACF;AAAA,QACF;AACA,eAAO,aAAa;AAAA,UAClB,EAAE,UAAU,OAAO,OAAO,kBAAkB;AAAA,UAC5C,EAAE,QAAQ,IAAI;AAAA,QAChB;AAAA,MACF;AAGA,YAAM,WAA4B,CAAC;AAGnC,UAAI,WAAW;AACb,iBAAS,KAAK,UAAU,OAAO,CAAC;AAAA,MAClC;AAGA,cAAQ,QAAQ,OAAO;AAAA,QACrB,KAAK;AACH,cAAI,yBAAyB;AAC3B,qBA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,aAAa,GAAmB;AACvC,SAAO,EAAE,eAAe,OAAO;AACjC;","names":["NextResponse","Commet","NextResponse"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@commet/next",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Next.js integration for Commet billing platform",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"author": "Commet Team",
|
|
27
27
|
"license": "MIT",
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@commet/node": "1.6.
|
|
29
|
+
"@commet/node": "1.6.2"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
32
|
"@types/node": "24.10.1",
|