packages/ at markup-kit dd1e6eb5270e
A snapshot of packages/ in the Weft repository; the official packages are published from these commits. Markup-Kit-Commit: dd1e6eb5270e62e0c8b6c202b3d01f0da6e00ddc
This commit is contained in:
commit
306b143104
72 changed files with 10915 additions and 0 deletions
1
integration/.gitignore
vendored
Normal file
1
integration/.gitignore
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
weft.lock
|
||||
232
integration/email/main.weft
Normal file
232
integration/email/main.weft
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
// `node packages/email/scripts/integration.mjs` runs this: both providers' APIs against a scripted server, and a full message
|
||||
// printed for Python's `email` parser to read back.
|
||||
import { header, json as jsonResponse, serve, status } from "std/http"
|
||||
import type { Request } from "std/http"
|
||||
import { parse } from "std/json"
|
||||
import { log } from "std/log"
|
||||
import { exit, stdout } from "std/process"
|
||||
import { send } from "@weft/email"
|
||||
import type { EmailError, Message } from "@weft/email"
|
||||
import { toMime } from "@weft/email/mime"
|
||||
import { postmark } from "@weft/email/postmark"
|
||||
import { resend } from "@weft/email/resend"
|
||||
|
||||
let mut passed = 0
|
||||
let mut failed = 0
|
||||
|
||||
fn check(name: string, ok: boolean, detail: string = "") {
|
||||
if ok {
|
||||
passed += 1
|
||||
} else {
|
||||
failed += 1
|
||||
log(`FAIL ${name} ${detail}`)
|
||||
}
|
||||
}
|
||||
|
||||
let mut seen: Request[] = []
|
||||
let mut script: string[] = []
|
||||
|
||||
fn okResend(): json {
|
||||
return { id: "re_123" }
|
||||
}
|
||||
|
||||
fn okPostmark(): json {
|
||||
return {
|
||||
To: "ana@example.com",
|
||||
SubmittedAt: "2026-11-17T10:00:00Z",
|
||||
MessageID: "pm-123",
|
||||
ErrorCode: 0,
|
||||
Message: "OK",
|
||||
}
|
||||
}
|
||||
|
||||
fn refused(): json {
|
||||
return { statusCode: 422, name: "validation_error", message: "The domain is not verified." }
|
||||
}
|
||||
|
||||
fn postmarkRefused(): json {
|
||||
return { ErrorCode: 406, Message: "The address is inactive." }
|
||||
}
|
||||
|
||||
async fn handle(req: Request) {
|
||||
seen.push(req)
|
||||
let step = script.shift() ?? "ok"
|
||||
return match step {
|
||||
"resend-ok" => jsonResponse(okResend()),
|
||||
"postmark-ok" => jsonResponse(okPostmark()),
|
||||
"resend-422" => jsonResponse(refused(), { status: 422 }),
|
||||
"postmark-422" => jsonResponse(postmarkRefused(), { status: 422 }),
|
||||
"postmark-200-error" => jsonResponse(postmarkRefused()),
|
||||
"429" => header(jsonResponse(refused(), { status: 429 }), "retry-after", "12"),
|
||||
"500" => status(500, "broken"),
|
||||
"no-id" => jsonResponse(refused()),
|
||||
_ => status(404),
|
||||
}
|
||||
}
|
||||
|
||||
fn kindOf(e: EmailError?): string {
|
||||
return e == null ? "none" : e.kind
|
||||
}
|
||||
|
||||
fn message(): Message {
|
||||
return {
|
||||
from: { email: "info@example.com", name: "Vidni" },
|
||||
to: ["ana@example.com"],
|
||||
subject: "Vaša vstopnica",
|
||||
html: "<p>Živjo</p>",
|
||||
text: "Živjo",
|
||||
attachments: [
|
||||
{ filename: "vstopnica.pdf", content: Bytes.of([37, 80, 68, 70]), type: "application/pdf" },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
fn edit(change: (mut m: Message) => void): Message {
|
||||
let mut m = message()
|
||||
change(&m)
|
||||
return m
|
||||
}
|
||||
|
||||
fn parsed(req: Request): json {
|
||||
return try parse(req.text()) else null
|
||||
}
|
||||
|
||||
async fn main() {
|
||||
let server = try await serve({ port: 0, host: "127.0.0.1" }, handle)
|
||||
let base = `http://127.0.0.1:${server.port}`
|
||||
|
||||
// ---- Resend ----
|
||||
let viaResend = resend(
|
||||
{ apiKey: "re_key", baseUrl: base, idempotencyKey: m => `order-${m.subject.length}` },
|
||||
)
|
||||
script = ["resend-ok"]
|
||||
seen = []
|
||||
let sent1, e0 = try await send(viaResend, message())
|
||||
check("Resend: sent", sent1?.id == "re_123" && sent1?.provider == "resend", kindOf(e0))
|
||||
check("Resend: the endpoint", seen[0].path == "/emails" && seen[0].method == "POST", seen[0].path)
|
||||
check("Resend: the key", seen[0].headers.get("authorization") == "Bearer re_key")
|
||||
check("Resend: the idempotency key", seen[0].headers.get("idempotency-key") == "order-14")
|
||||
check("Resend: JSON", (seen[0].headers.get("content-type") ?? "").startsWith("application/json"))
|
||||
check(
|
||||
"Resend: the fields",
|
||||
parsed(seen[0]).subject == "Vaša vstopnica" &&
|
||||
parsed(seen[0]).attachments[0].content == "JVBERg==",
|
||||
)
|
||||
|
||||
script = ["resend-422"]
|
||||
let _, e1 = try await send(viaResend, message())
|
||||
match e1 {
|
||||
Rejected { status: s, code, message: m } => check(
|
||||
"Resend: a refusal",
|
||||
s == 422 && code == "validation_error" && m == "The domain is not verified.",
|
||||
),
|
||||
_ => check("Resend: a refusal", false, kindOf(e1)),
|
||||
}
|
||||
script = ["429"]
|
||||
let _, e2 = try await send(viaResend, message())
|
||||
match e2 {
|
||||
RateLimited { retryAfter } => check("Resend: rate limited", retryAfter == 12),
|
||||
_ => check("Resend: rate limited", false, kindOf(e2)),
|
||||
}
|
||||
script = ["500"]
|
||||
let _, e3 = try await send(viaResend, message())
|
||||
check("Resend: a server error", kindOf(e3) == "ProviderFailure", kindOf(e3))
|
||||
script = ["no-id"]
|
||||
let _, e4 = try await send(viaResend, message())
|
||||
check("Resend: an answer without an id", kindOf(e4) == "BadResponse", kindOf(e4))
|
||||
|
||||
// An invalid message never reaches the provider.
|
||||
seen = []
|
||||
let _, e5 = try await send(
|
||||
viaResend,
|
||||
edit((mut m) => {
|
||||
m.subject = "a\r\nBcc: v@x.y"
|
||||
}),
|
||||
)
|
||||
check(
|
||||
"an invalid message isn't sent",
|
||||
kindOf(e5) == "InvalidMessage" && seen.length == 0,
|
||||
kindOf(e5),
|
||||
)
|
||||
|
||||
// ---- Postmark ----
|
||||
let viaPostmark = postmark({ serverToken: "pm_token", baseUrl: base })
|
||||
script = ["postmark-ok"]
|
||||
seen = []
|
||||
let sent2, e10 = try await send(viaPostmark, message())
|
||||
check("Postmark: sent", sent2?.id == "pm-123" && sent2?.provider == "postmark", kindOf(e10))
|
||||
check(
|
||||
"Postmark: the endpoint",
|
||||
seen[0].path == "/email" && seen[0].method == "POST",
|
||||
seen[0].path,
|
||||
)
|
||||
check("Postmark: the token", seen[0].headers.get("x-postmark-server-token") == "pm_token")
|
||||
check(
|
||||
"Postmark: the fields",
|
||||
parsed(seen[0]).Subject == "Vaša vstopnica" &&
|
||||
parsed(seen[0]).MessageStream == "outbound" &&
|
||||
parsed(seen[0]).Attachments[0].Name == "vstopnica.pdf",
|
||||
)
|
||||
|
||||
script = ["postmark-422"]
|
||||
let _, e6 = try await send(viaPostmark, message())
|
||||
match e6 {
|
||||
Rejected { code, message: m } => check(
|
||||
"Postmark: a refusal",
|
||||
code == "406" && m == "The address is inactive.",
|
||||
),
|
||||
_ => check("Postmark: a refusal", false, kindOf(e6)),
|
||||
}
|
||||
script = ["postmark-200-error"]
|
||||
let _, e7 = try await send(viaPostmark, message())
|
||||
check("Postmark: an error code in a 200", kindOf(e7) == "Rejected", kindOf(e7))
|
||||
script = ["500"]
|
||||
let _, e8 = try await send(viaPostmark, message())
|
||||
check("Postmark: a server error", kindOf(e8) == "ProviderFailure", kindOf(e8))
|
||||
|
||||
// ---- nothing listening ----
|
||||
let dead = resend({ apiKey: "k", baseUrl: "http://127.0.0.1:9", timeout: 2000 })
|
||||
let _, e9 = try await send(dead, message())
|
||||
check("no connection", kindOf(e9) == "ConnectionFailed", kindOf(e9))
|
||||
|
||||
await server.close()
|
||||
|
||||
// ---- a full message for Python's parser ----
|
||||
let long = "Pozdravljeni, to je dolgo sporočilo s črkami č, š in ž, ki sega čez mejo šestinsedemdesetih znakov v vrstici. = in pika.\n.vrstica s piko\nKonec "
|
||||
let full: Message = {
|
||||
from: { email: "info@example.com", name: "Žiga \"Vidni\" Novak" },
|
||||
to: ["ana@example.com", { email: "bor@example.com", name: "Bor Šuštar" }],
|
||||
cc: ["cene@example.com"],
|
||||
bcc: ["skrito@example.com"],
|
||||
replyTo: { email: "lastnik@example.com", name: "Lastnik" },
|
||||
subject: "Vaša vstopnica za dogodek: čudovit večer na gradu, ki se ga boste še dolgo spominjali",
|
||||
text: long,
|
||||
html: `<p>${long}</p><img src="cid:logo">`,
|
||||
headers: [["List-Unsubscribe", "<https://example.com/odjava?id=1>"], ["X-Oznaka", "račun"]],
|
||||
attachments: [
|
||||
{
|
||||
filename: "račun št. 5.pdf",
|
||||
content: Bytes.of((0..=255).toList()),
|
||||
type: "application/pdf",
|
||||
},
|
||||
{
|
||||
filename: "dogodek.ics",
|
||||
content: Bytes.fromUtf8("BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n"),
|
||||
type: "text/calendar",
|
||||
},
|
||||
{
|
||||
filename: "logo.png",
|
||||
content: Bytes.of([137, 80, 78, 71]),
|
||||
type: "image/png",
|
||||
contentId: "logo",
|
||||
},
|
||||
],
|
||||
}
|
||||
stdout("=====MIME=====\n" + toMime(full) + "=====END=====\n")
|
||||
log(`${passed} passed, ${failed} failed`)
|
||||
if failed > 0 {
|
||||
exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
try await main()
|
||||
5
integration/email/weft.toml
Normal file
5
integration/email/weft.toml
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
# The integration tests of `weft/email`, an app that depends on the package: `node packages/email/scripts/integration.mjs`.
|
||||
main = "main.weft"
|
||||
|
||||
[dependencies]
|
||||
"weft/email" = { path = "../../email", allow = ["http.fetch@api.resend.com", "http.fetch@api.postmarkapp.com", "http.fetch@127.0.0.1", "http.media"] }
|
||||
499
integration/stripe/main.weft
Normal file
499
integration/stripe/main.weft
Normal file
|
|
@ -0,0 +1,499 @@
|
|||
// `node packages/stripe/scripts/integration.mjs` runs this: every call against stripe-mock (Stripe's OpenAPI spec checks each request, and
|
||||
// its fixtures check each response type), then retries, headers and paging against a small server in this program.
|
||||
import { header, json as jsonResponse, serve, status, text } from "std/http"
|
||||
import type { Request } from "std/http"
|
||||
import { log } from "std/log"
|
||||
import { env, exit } from "std/process"
|
||||
import { client, errorMessage, idOf, request } from "@weft/stripe"
|
||||
import type { Client, StripeError } from "@weft/stripe"
|
||||
import * as billing from "@weft/stripe/billing"
|
||||
import * as checkout from "@weft/stripe/checkout"
|
||||
import * as customers from "@weft/stripe/customers"
|
||||
import * as paymentIntents from "@weft/stripe/payment_intents"
|
||||
import * as prices from "@weft/stripe/prices"
|
||||
import * as products from "@weft/stripe/products"
|
||||
import * as refunds from "@weft/stripe/refunds"
|
||||
import * as subscriptions from "@weft/stripe/subscriptions"
|
||||
|
||||
let mut passed = 0
|
||||
let mut failed = 0
|
||||
|
||||
fn check(name: string, ok: boolean, detail: string = "") {
|
||||
if ok {
|
||||
passed += 1
|
||||
} else {
|
||||
failed += 1
|
||||
log(`FAIL ${name} ${detail}`)
|
||||
}
|
||||
}
|
||||
|
||||
fn failure(name: string, e: StripeError) {
|
||||
failed += 1
|
||||
log(`FAIL ${name}: ${errorMessage(e)}`)
|
||||
}
|
||||
|
||||
let mock = client(
|
||||
"sk_test_123",
|
||||
{ baseUrl: env("STRIPE_MOCK_URL") ?? "http://127.0.0.1:12111", maxRetries: 0 },
|
||||
)
|
||||
|
||||
// ---- every call, against Stripe's OpenAPI spec ----
|
||||
async fn runMock() {
|
||||
let customer, e1 = try await customers.create(
|
||||
mock,
|
||||
{
|
||||
email: "ana@example.com",
|
||||
name: "Ana",
|
||||
address: { city: "Ljubljana", country: "SI" },
|
||||
metadata: Map<string, string>([["site", "a1"]]),
|
||||
preferred_locales: ["sl"],
|
||||
},
|
||||
)
|
||||
if e1 != null {
|
||||
return failure("customers.create", e1)
|
||||
}
|
||||
check("customers.create", customer.id != "")
|
||||
let got, e2 = try await customers.retrieve(mock, customer.id)
|
||||
if e2 != null {
|
||||
return failure("customers.retrieve", e2)
|
||||
}
|
||||
check("customers.retrieve", got.id != "")
|
||||
let up, e3 = try await customers.update(
|
||||
mock,
|
||||
customer.id,
|
||||
{ name: "Ana N." },
|
||||
{ idempotencyKey: "k1" },
|
||||
)
|
||||
check("customers.update", e3 == null)
|
||||
let page, e4 = try await customers.list(mock, { limit: 3, email: "ana@example.com" })
|
||||
check("customers.list", e4 == null)
|
||||
let all, e5 = try await customers.listAll(mock, { limit: 3 })
|
||||
check("customers.listAll", e5 == null)
|
||||
let found, e6 = try await customers.search(mock, "email:\"ana@example.com\"")
|
||||
check("customers.search", e6 == null)
|
||||
let gone, e7 = try await customers.remove(mock, customer.id)
|
||||
check("customers.remove", e7 == null && gone.deleted)
|
||||
|
||||
let product, e8 = try await products.create(
|
||||
mock,
|
||||
{ name: "Ticket", active: true, metadata: Map<string, string>([["a", "b"]]) },
|
||||
)
|
||||
if e8 != null {
|
||||
return failure("products.create", e8)
|
||||
}
|
||||
check("products.create", product.id != "")
|
||||
check("products.retrieve", (try await products.retrieve(mock, product.id) else null) != null)
|
||||
check(
|
||||
"products.update",
|
||||
(try await products.update(mock, product.id, { description: "x" }) else null) != null,
|
||||
)
|
||||
check(
|
||||
"products.list",
|
||||
(try await products.list(mock, { active: true, limit: 2 }) else null) != null,
|
||||
)
|
||||
check("products.listAll", (try await products.listAll(mock) else null) != null)
|
||||
check("products.remove", (try await products.remove(mock, product.id) else null) != null)
|
||||
|
||||
let price, e9 = try await prices.create(
|
||||
mock,
|
||||
{
|
||||
currency: "eur",
|
||||
unit_amount: 1999,
|
||||
product: product.id,
|
||||
recurring: { interval: "month", interval_count: 1 },
|
||||
lookup_key: "base-monthly",
|
||||
},
|
||||
)
|
||||
if e9 != null {
|
||||
return failure("prices.create", e9)
|
||||
}
|
||||
check("prices.create", price.id != "")
|
||||
check("prices.retrieve", (try await prices.retrieve(mock, price.id) else null) != null)
|
||||
check(
|
||||
"prices.update",
|
||||
(try await prices.update(mock, price.id, { nickname: "Base", active: true }) else null) != null,
|
||||
)
|
||||
let keyed, e10 = try await prices.list(
|
||||
mock,
|
||||
{ lookup_keys: ["base-monthly"], active: true, limit: 1 },
|
||||
)
|
||||
check("prices.list by lookup key", e10 == null)
|
||||
check(
|
||||
"prices.listAll",
|
||||
(try await prices.listAll(mock, { product: product.id }) else null) != null,
|
||||
)
|
||||
|
||||
let intent, e11 = try await paymentIntents.create(
|
||||
mock,
|
||||
{
|
||||
amount: 1999,
|
||||
currency: "eur",
|
||||
automatic_payment_methods: { enabled: true },
|
||||
metadata: Map<string, string>([["sale", "s1"]]),
|
||||
application_fee_amount: 100,
|
||||
transfer_data: { destination: "acct_1" },
|
||||
},
|
||||
{ idempotencyKey: "sale-s1", stripeAccount: "acct_1" },
|
||||
)
|
||||
if e11 != null {
|
||||
return failure("paymentIntents.create", e11)
|
||||
}
|
||||
check("paymentIntents.create", intent.id != "" && intent.amount > 0)
|
||||
check(
|
||||
"paymentIntents.retrieve",
|
||||
(try await paymentIntents.retrieve(mock, intent.id) else null) != null,
|
||||
)
|
||||
check(
|
||||
"paymentIntents.update",
|
||||
(try await paymentIntents.update(mock, intent.id, { description: "x" }) else null) != null,
|
||||
)
|
||||
check(
|
||||
"paymentIntents.confirm",
|
||||
(try await paymentIntents.confirm(mock, intent.id) else null) != null,
|
||||
)
|
||||
check(
|
||||
"paymentIntents.capture",
|
||||
(try await paymentIntents.capture(mock, intent.id) else null) != null,
|
||||
)
|
||||
check(
|
||||
"paymentIntents.cancel",
|
||||
(try await paymentIntents.cancel(mock, intent.id) else null) != null,
|
||||
)
|
||||
check(
|
||||
"paymentIntents.list",
|
||||
(try await paymentIntents.list(mock, { limit: 2 }) else null) != null,
|
||||
)
|
||||
check("paymentIntents.listAll", (try await paymentIntents.listAll(mock) else null) != null)
|
||||
check(
|
||||
"paymentIntents.search",
|
||||
(try await paymentIntents.search(mock, "status:\"succeeded\"") else null) != null,
|
||||
)
|
||||
|
||||
let sub, e12 = try await subscriptions.create(
|
||||
mock,
|
||||
{
|
||||
customer: "cus_1",
|
||||
items: [{ price: price.id, quantity: 2 }],
|
||||
metadata: Map<string, string>([["siteId", "a1"]]),
|
||||
trial_period_days: 14,
|
||||
},
|
||||
)
|
||||
if e12 != null {
|
||||
return failure("subscriptions.create", e12)
|
||||
}
|
||||
check("subscriptions.create", sub.id != "" && idOf(sub.customer) != null)
|
||||
let item = sub.items.data.at(0)
|
||||
check("a subscription's items carry their price", item != null && item.price != null)
|
||||
check(
|
||||
"subscriptions.retrieve",
|
||||
(try await subscriptions.retrieve(mock, sub.id, { expand: ["customer"] }) else null) != null,
|
||||
)
|
||||
check(
|
||||
"subscriptions.update",
|
||||
(try await subscriptions.update(
|
||||
mock,
|
||||
sub.id,
|
||||
{
|
||||
cancel_at_period_end: true,
|
||||
items: [{ id: "si_1", deleted: true }, { price: price.id, quantity: 1 }],
|
||||
proration_behavior: "none",
|
||||
},
|
||||
) else null) !=
|
||||
null,
|
||||
)
|
||||
check("subscriptions.cancel", (try await subscriptions.cancel(mock, sub.id) else null) != null)
|
||||
check(
|
||||
"subscriptions.list",
|
||||
(try await subscriptions.list(mock, { status: "all", limit: 2 }) else null) != null,
|
||||
)
|
||||
check(
|
||||
"subscriptions.listAll",
|
||||
(try await subscriptions.listAll(mock, { customer: "cus_1" }) else null) != null,
|
||||
)
|
||||
check(
|
||||
"subscriptions.search",
|
||||
(try await subscriptions.search(mock, "status:\"active\"") else null) != null,
|
||||
)
|
||||
|
||||
let session, e13 = try await checkout.create(
|
||||
mock,
|
||||
{
|
||||
mode: "payment",
|
||||
success_url: "https://example.com/thanks?s={CHECKOUT_SESSION_ID}",
|
||||
cancel_url: "https://example.com/cart",
|
||||
customer_email: "ana@example.com",
|
||||
client_reference_id: "sale-1",
|
||||
locale: "sl",
|
||||
metadata: Map<string, string>([["saleId", "s1"]]),
|
||||
line_items: [
|
||||
{
|
||||
quantity: 1,
|
||||
price_data: { currency: "eur", unit_amount: 1999, product_data: { name: "Vstopnica" } },
|
||||
},
|
||||
],
|
||||
payment_intent_data: {
|
||||
application_fee_amount: 100,
|
||||
description: "Ticket",
|
||||
metadata: Map<string, string>([["saleId", "s1"]]),
|
||||
},
|
||||
},
|
||||
{ idempotencyKey: "vidni-sale-s1", stripeAccount: "acct_1" },
|
||||
)
|
||||
if e13 != null {
|
||||
return failure("checkout.create", e13)
|
||||
}
|
||||
check("checkout.create", session.id != "")
|
||||
let sub2, e14 = try await checkout.create(
|
||||
mock,
|
||||
{
|
||||
mode: "subscription",
|
||||
success_url: "https://example.com/ok",
|
||||
line_items: [{ price: price.id, quantity: 1 }],
|
||||
allow_promotion_codes: true,
|
||||
subscription_data: {
|
||||
metadata: Map<string, string>([["siteId", "a1"]]),
|
||||
trial_period_days: 7,
|
||||
},
|
||||
},
|
||||
)
|
||||
check("checkout.create for a subscription", e14 == null)
|
||||
check(
|
||||
"checkout.retrieve",
|
||||
(try await checkout.retrieve(
|
||||
mock,
|
||||
session.id,
|
||||
{ expand: ["subscription", "payment_intent"] },
|
||||
) else null) !=
|
||||
null,
|
||||
)
|
||||
check("checkout.expire", (try await checkout.expire(mock, session.id) else null) != null)
|
||||
check("checkout.list", (try await checkout.list(mock, { limit: 2 }) else null) != null)
|
||||
check("checkout.listAll", (try await checkout.listAll(mock) else null) != null)
|
||||
check("checkout.lineItems", (try await checkout.lineItems(mock, session.id) else null) != null)
|
||||
|
||||
let refund, e15 = try await refunds.create(
|
||||
mock,
|
||||
{ payment_intent: intent.id, amount: 100, reason: "requested_by_customer" },
|
||||
)
|
||||
if e15 != null {
|
||||
return failure("refunds.create", e15)
|
||||
}
|
||||
check("refunds.create", refund.id != "")
|
||||
check("refunds.retrieve", (try await refunds.retrieve(mock, refund.id) else null) != null)
|
||||
check(
|
||||
"refunds.list",
|
||||
(try await refunds.list(mock, { payment_intent: intent.id }) else null) != null,
|
||||
)
|
||||
check("refunds.listAll", (try await refunds.listAll(mock) else null) != null)
|
||||
|
||||
// That stripe-mock really checks requests: a field Stripe doesn't have is refused.
|
||||
let unknown: json = { not_a_field: "x" }
|
||||
let _, e18 = try await customers.create(mock, { extra: unknown })
|
||||
check(
|
||||
"stripe-mock refuses a field Stripe doesn't have",
|
||||
kindOf(e18) == "InvalidRequest",
|
||||
kindOf(e18),
|
||||
)
|
||||
|
||||
let portal, e16 = try await billing.createPortalSession(
|
||||
mock,
|
||||
{ customer: "cus_1", return_url: "https://example.com" },
|
||||
)
|
||||
check("billing.createPortalSession", e16 == null)
|
||||
check(
|
||||
"billing.retrieveCoupon",
|
||||
(try await billing.retrieveCoupon(mock, "co_1") else null) != null,
|
||||
)
|
||||
check(
|
||||
"billing.retrievePromotionCode",
|
||||
(try await billing.retrievePromotionCode(mock, "promo_1") else null) != null,
|
||||
)
|
||||
let components: json = { payments: { enabled: true } }
|
||||
let account, e17 = try await billing.createAccountSession(mock, { account: "acct_1", components })
|
||||
check("billing.createAccountSession", e17 == null)
|
||||
}
|
||||
|
||||
// ---- what stripe-mock can't show: a server that misbehaves on request ----
|
||||
let mut seen: Request[] = []
|
||||
let mut script: string[] = []
|
||||
|
||||
async fn handle(req: Request) {
|
||||
seen.push(req)
|
||||
let step = script.shift() ?? "ok"
|
||||
return match step {
|
||||
"500" => status(500, "{\"error\":{\"type\":\"api_error\",\"message\":\"boom\"}}"),
|
||||
"500-no-retry" => header(
|
||||
status(500, "{\"error\":{\"type\":\"api_error\",\"message\":\"no retry\"}}"),
|
||||
"stripe-should-retry",
|
||||
"false",
|
||||
),
|
||||
"429" => jsonResponse(rateLimit(), { status: 429 }),
|
||||
"402" => header(jsonResponse(declined(), { status: 402 }), "request-id", "req_declined"),
|
||||
"garbage" => text("this is not json"),
|
||||
"wrong-shape" => jsonResponse(wrongShape()),
|
||||
"page1" => jsonResponse(pageOf(["cus_1", "cus_2"], true)),
|
||||
"page2" => jsonResponse(pageOf(["cus_3"], false)),
|
||||
_ => jsonResponse(okCustomer()),
|
||||
}
|
||||
}
|
||||
|
||||
fn rateLimit(): json {
|
||||
return { error: { type: "invalid_request_error", message: "slow down" } }
|
||||
}
|
||||
|
||||
fn declined(): json {
|
||||
return {
|
||||
error: {
|
||||
type: "card_error",
|
||||
code: "card_declined",
|
||||
decline_code: "insufficient_funds",
|
||||
message: "Your card was declined.",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn wrongShape(): json {
|
||||
return { id: 42 }
|
||||
}
|
||||
|
||||
fn okCustomer(): json {
|
||||
return { id: "cus_ok", object: "customer" }
|
||||
}
|
||||
|
||||
fn pageOf(ids: string[], more: boolean): json {
|
||||
let data: json[] = ids.map(id => {
|
||||
let item: json = { id }
|
||||
return item
|
||||
})
|
||||
return { object: "list", data, has_more: more }
|
||||
}
|
||||
|
||||
fn kindOf(e: StripeError?): string {
|
||||
return e == null ? "none" : e.kind
|
||||
}
|
||||
|
||||
async fn runScripted(c: Client) {
|
||||
// A server error is repeated, with the same idempotency key, and then succeeds.
|
||||
script = ["500", "ok"]
|
||||
seen = []
|
||||
let first, e1 = try await customers.create(c, { email: "a@b.c" })
|
||||
check("a 500 is retried", e1 == null && seen.length == 2, kindOf(e1))
|
||||
let keys = seen.map(r => r.headers.get("idempotency-key") ?? "")
|
||||
check("every attempt carries one idempotency key", keys[0] != "" && keys[0] == keys[1])
|
||||
|
||||
// An explicit key is what is sent.
|
||||
script = ["ok"]
|
||||
seen = []
|
||||
let _, e2 = try await customers.create(
|
||||
c,
|
||||
{ email: "a@b.c" },
|
||||
{ idempotencyKey: "my-key", stripeAccount: "acct_9" },
|
||||
)
|
||||
check(
|
||||
"idempotency key and connected account",
|
||||
e2 == null &&
|
||||
seen[0].headers.get("idempotency-key") == "my-key" &&
|
||||
seen[0].headers.get("stripe-account") == "acct_9",
|
||||
)
|
||||
check(
|
||||
"the API key and version are sent",
|
||||
seen[0].headers.get("authorization") == "Bearer sk_test_scripted" &&
|
||||
(seen[0].headers.get("stripe-version") ?? "") != "",
|
||||
)
|
||||
check(
|
||||
"a POST is form encoded",
|
||||
seen[0].headers.get("content-type") == "application/x-www-form-urlencoded" &&
|
||||
seen[0].text() == "email=a%40b.c",
|
||||
)
|
||||
|
||||
// Reads have no key, and carry their parameters in the query.
|
||||
script = ["ok"]
|
||||
seen = []
|
||||
let _, e3 = try await customers.retrieve(c, "cus/1", { expand: ["default_source"] })
|
||||
check(
|
||||
"a GET has no idempotency key",
|
||||
e3 == null && seen[0].headers.get("idempotency-key") == null,
|
||||
)
|
||||
check(
|
||||
"expand goes in the query, the id is escaped",
|
||||
seen[0].url.includes("/v1/customers/cus%2F1?expand[0]=default_source"),
|
||||
seen[0].url,
|
||||
)
|
||||
|
||||
// Stripe saying not to retry is obeyed.
|
||||
script = ["500-no-retry", "ok"]
|
||||
seen = []
|
||||
let _, e4 = try await customers.create(c, { email: "a@b.c" })
|
||||
check("stripe-should-retry: false", kindOf(e4) == "ApiFailure" && seen.length == 1, kindOf(e4))
|
||||
|
||||
// Retries run out.
|
||||
script = ["500", "500", "500", "ok"]
|
||||
seen = []
|
||||
let _, e5 = try await customers.create(c, { email: "a@b.c" })
|
||||
check("retries are limited", kindOf(e5) == "ApiFailure" && seen.length == 3, `${seen.length}`)
|
||||
|
||||
// A 429 is an error the caller decides about, unless Stripe asks for a retry.
|
||||
script = ["429", "ok"]
|
||||
seen = []
|
||||
let _, e6 = try await customers.create(c, { email: "a@b.c" })
|
||||
check("a 429 is a typed error", kindOf(e6) == "RateLimited" && seen.length == 1, kindOf(e6))
|
||||
|
||||
// A declined card.
|
||||
script = ["402"]
|
||||
seen = []
|
||||
let _, e7 = try await customers.create(c, { email: "a@b.c" })
|
||||
match e7 {
|
||||
CardError { failure: f } => check(
|
||||
"a declined card",
|
||||
f.decline_code == "insufficient_funds" && f.request_id == "req_declined",
|
||||
),
|
||||
_ => check("a declined card", false, kindOf(e7)),
|
||||
}
|
||||
|
||||
// What can't be read is an error, not a crash.
|
||||
script = ["wrong-shape"]
|
||||
let _, e8 = try await customers.retrieve(c, "cus_1")
|
||||
check("an unexpected shape", kindOf(e8) == "BadResponse", kindOf(e8))
|
||||
script = ["garbage"]
|
||||
let _, e9 = try await customers.retrieve(c, "cus_1")
|
||||
check("an answer that isn't JSON", kindOf(e9) == "BadResponse", kindOf(e9))
|
||||
|
||||
// Every page is followed.
|
||||
script = ["page1", "page2"]
|
||||
seen = []
|
||||
let all, e10 = try await customers.listAll(c, { limit: 2 })
|
||||
check(
|
||||
"listAll follows the pages",
|
||||
e10 == null && all.map(x => x.id).join(",") == "cus_1,cus_2,cus_3",
|
||||
kindOf(e10),
|
||||
)
|
||||
check(
|
||||
"listAll asks for the page after the last item",
|
||||
seen.length == 2 && seen[1].url.includes("starting_after=cus_2"),
|
||||
)
|
||||
|
||||
// And stops at the limit it was given.
|
||||
script = ["page1", "page2"]
|
||||
seen = []
|
||||
let some, e11 = try await customers.listAll(c, {}, {}, 2)
|
||||
check("listAll stops at max", e11 == null && some.length == 2 && seen.length == 1)
|
||||
|
||||
// Nothing listening.
|
||||
let dead = client(
|
||||
"sk_test_scripted",
|
||||
{ baseUrl: "http://127.0.0.1:9", maxRetries: 1, timeout: 2000 },
|
||||
)
|
||||
let _, e12 = try await customers.retrieve(dead, "cus_1")
|
||||
check("no connection", kindOf(e12) == "ConnectionFailed", kindOf(e12))
|
||||
}
|
||||
|
||||
await runMock()
|
||||
let server = try await serve({ port: 0, host: "127.0.0.1" }, handle)
|
||||
await runScripted(
|
||||
client("sk_test_scripted", { baseUrl: `http://127.0.0.1:${server.port}`, maxRetries: 2 }),
|
||||
)
|
||||
await server.close()
|
||||
log(`${passed} passed, ${failed} failed`)
|
||||
if failed > 0 {
|
||||
exit(1)
|
||||
}
|
||||
5
integration/stripe/weft.toml
Normal file
5
integration/stripe/weft.toml
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
# The integration tests of `weft/stripe`, an app that depends on the package: `node packages/stripe/scripts/integration.mjs`.
|
||||
main = "main.weft"
|
||||
|
||||
[dependencies]
|
||||
"weft/stripe" = { path = "../../stripe", allow = ["http.fetch@api.stripe.com", "http.fetch@127.0.0.1"] }
|
||||
Loading…
Reference in a new issue