@amboras-dev/aliexpress-dropshipping 1.1.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts","../src/settings-form.tsx"],"sourcesContent":["/**\n * Public types for @amboras-dev/aliexpress-dropshipping.\n *\n * These are the single source of truth for the wire shape between the\n * Amboras admin settings form and the medusa-backend-orchestrator\n * Store API routes under `/store/aliexpress-dropshipping/*`. The DTO\n * files on the medusa side must stay byte-compatible with these.\n */\n\n/**\n * Sentinel returned in place of a stored secret when the settings form\n * reads back current config. Matches the pattern used by meta-ads and\n * pinterest so the admin never sees the plaintext secret after write.\n */\nexport const SECRET_SET_SENTINEL = '__SECRET_SET__' as const\nexport type SecretSetSentinel = typeof SECRET_SET_SENTINEL\n\n/**\n * Per-store AliExpress plugin configuration.\n *\n * - `appKey` / `appSecret` are per-store developer app credentials\n * supplied by the merchant. The admin form receives\n * `SECRET_SET_SENTINEL` for `appSecret` on read, and only sends a\n * real value on user edit.\n * - `connectedSellerId` is populated after the merchant completes the\n * OAuth flow to `/rest/auth/token/create`.\n * - `needsReauth` is flipped by the backend runtime detector when it\n * sees `MissingParameter access_token` or `IllegalAccessToken`\n * sub-codes on any envelope.\n * - `lastSuccessfulCallAt` is an ISO-8601 timestamp for the status card.\n */\nexport interface AliExpressPluginConfig {\n enabled: boolean\n appKey: string | null\n appSecret: string | SecretSetSentinel | null\n connectedSellerId: string | null\n needsReauth: boolean\n lastSuccessfulCallAt: string | null\n}\n\n/**\n * Reasons the backend surfaces when a merchant token becomes invalid.\n * Kept narrow so the admin banner can render a specific message.\n */\nexport enum AliExpressReauthReason {\n MissingAccessToken = 'missing_access_token',\n IllegalAccessToken = 'illegal_access_token',\n RefreshFailed = 'refresh_failed',\n Disconnected = 'disconnected',\n}\n\n/**\n * Category node returned by `aliexpress.ds.category.get`. The API\n * returns a flat list; the admin renders it as a tree by walking\n * `parentCategoryId`.\n */\nexport interface AliExpressCategoryDto {\n categoryId: string\n categoryName: string\n parentCategoryId: string | null\n}\n\n/**\n * Product summary shape returned by `aliexpress.ds.recommend.feed.get`.\n * Used by the \"browse products\" admin surface.\n */\nexport interface AliExpressProductSummaryDto {\n productId: string\n title: string\n imageUrl: string | null\n minPrice: number | null\n maxPrice: number | null\n currency: string | null\n productDetailUrl: string | null\n}\n\n/**\n * Full product shape returned by `aliexpress.ds.product.get`. Consumed\n * by the medusa-side mapper `aliexpressProductToMedusaDraft`.\n */\nexport interface AliExpressProductDto {\n productId: string\n title: string\n description: string | null\n images: string[]\n variants: AliExpressProductVariantDto[]\n weightGrams: number | null\n sourceUrl: string | null\n}\n\nexport interface AliExpressProductVariantDto {\n skuId: string\n title: string | null\n price: number\n currency: string\n stock: number | null\n attributes: Record<string, string>\n}\n\n/**\n * Return shape from `POST /store/aliexpress-dropshipping/products/:id/import`.\n */\nexport interface AliExpressImportResultDto {\n medusaProductId: string\n sourceProductId: string\n importedVariants: number\n}\n\n/**\n * Return shape from `GET /store/aliexpress-dropshipping/status` - drives\n * the admin status card.\n */\nexport interface AliExpressConnectionStatusDto {\n connected: boolean\n sellerId: string | null\n needsReauth: boolean\n reauthReason: AliExpressReauthReason | null\n lastSuccessfulCallAt: string | null\n}\n\n/**\n * Return shape from `POST /store/aliexpress-dropshipping/test-connection`.\n */\nexport type AliExpressTestConnectionResult =\n | { ok: true; categoryCount: number }\n | { ok: false; code: string; msg: string }\n\nexport interface PreflightMerchantError {\n code: string\n message: string\n}\n\nexport interface PreflightAddressError {\n code: string\n message: string\n field: string\n}\n\nexport interface PreflightItemError {\n variantId: string\n productTitle: string\n code: 'CORRUPT_METADATA' | 'PRODUCT_OFFLINE' | 'OUT_OF_STOCK' | 'CANNOT_SHIP' | 'PRICE_DRIFT'\n message: string\n removable: boolean\n}\n\nexport interface PreflightResult {\n ok: boolean\n merchantErrors: PreflightMerchantError[]\n addressErrors: PreflightAddressError[]\n itemErrors: PreflightItemError[]\n warnings: Array<{ code: string; message: string }>\n degraded?: boolean\n warning?: string\n}\n","'use client'\n\n/**\n * Admin settings form for the AliExpress Dropshipping integration.\n *\n * Class B: this component owns the UI and talks to the Medusa Store API\n * under `/store/aliexpress-dropshipping/*`. It does NOT embed any\n * AliExpress SDK, does not sign requests, and does not touch OAuth\n * tokens directly - the backend does all of that.\n *\n * The component is intentionally dependency-light (no external UI kit,\n * no @tanstack/react-query peer) so the admin bundle can drop it in\n * without extra peer dep resolution.\n */\n\nimport * as React from 'react'\nimport type {\n AliExpressPluginConfig,\n AliExpressConnectionStatusDto,\n AliExpressTestConnectionResult,\n} from './types'\nimport { SECRET_SET_SENTINEL } from './types'\n\nexport interface AliExpressDropshippingSettingsFormProps {\n /** Current config for this store (fetched by the parent server component). */\n initialConfig: AliExpressPluginConfig\n /** Current connection status (from `GET /status`). */\n initialStatus: AliExpressConnectionStatusDto\n /**\n * Persist non-secret + optionally new secret values. The parent maps\n * this onto `PATCH /store/aliexpress-dropshipping/config` (or\n * equivalent) and then re-fetches config on success.\n *\n * `appSecret` is only sent when the merchant actually typed a new\n * value; if they leave the field untouched, this method receives\n * `undefined` for that key so the backend keeps the existing secret.\n */\n onSaveConfig: (patch: {\n appKey?: string\n appSecret?: string\n enabled?: boolean\n }) => Promise<void>\n /** Kick off `POST /oauth/start` and redirect to the returned URL. */\n onConnect: () => Promise<void>\n /** Kick off `POST /oauth/disconnect` and clear merchant credentials. */\n onDisconnect: () => Promise<void>\n /** Call `POST /test-connection` and return the result. */\n onTestConnection: () => Promise<AliExpressTestConnectionResult>\n}\n\ntype SaveState = 'idle' | 'saving' | 'saved' | 'error'\ntype TestState =\n | { kind: 'idle' }\n | { kind: 'running' }\n | { kind: 'ok'; categoryCount: number }\n | { kind: 'err'; code: string; msg: string }\n\n/**\n * Amboras admin settings surface for AliExpress Dropshipping.\n * Renders AppKey + AppSecret inputs, Test / Connect / Disconnect\n * buttons, status card, and a \"Coming soon\" order-forwarding block.\n */\nexport function AliExpressDropshippingSettingsForm(\n props: AliExpressDropshippingSettingsFormProps,\n): React.ReactElement {\n const {\n initialConfig,\n initialStatus,\n onSaveConfig,\n onConnect,\n onDisconnect,\n onTestConnection,\n } = props\n\n const [appKey, setAppKey] = React.useState<string>(\n initialConfig.appKey ?? '',\n )\n const secretPreset =\n initialConfig.appSecret === SECRET_SET_SENTINEL ||\n (typeof initialConfig.appSecret === 'string' &&\n initialConfig.appSecret.length > 0)\n const [appSecret, setAppSecret] = React.useState<string>('')\n const [secretDirty, setSecretDirty] = React.useState<boolean>(false)\n\n const [saveState, setSaveState] = React.useState<SaveState>('idle')\n const [saveError, setSaveError] = React.useState<string | null>(null)\n\n const [testState, setTestState] = React.useState<TestState>({ kind: 'idle' })\n const [testEverSucceeded, setTestEverSucceeded] = React.useState<boolean>(\n initialStatus.connected,\n )\n\n const [busyOAuth, setBusyOAuth] = React.useState<boolean>(false)\n\n const hasStoredSecret = secretPreset || secretDirty\n const canTest = appKey.trim().length > 0 && hasStoredSecret\n const canConnect = testEverSucceeded && !initialStatus.connected\n const canDisconnect = initialStatus.connected\n\n const handleSave = React.useCallback(async () => {\n setSaveState('saving')\n setSaveError(null)\n try {\n const patch: {\n appKey?: string\n appSecret?: string\n enabled?: boolean\n } = {}\n if (appKey.trim() !== (initialConfig.appKey ?? '')) {\n patch.appKey = appKey.trim()\n }\n if (secretDirty && appSecret.length > 0) {\n patch.appSecret = appSecret\n }\n await onSaveConfig(patch)\n setSaveState('saved')\n setSecretDirty(false)\n setAppSecret('')\n } catch (err) {\n setSaveState('error')\n setSaveError(err instanceof Error ? err.message : 'Save failed')\n }\n }, [appKey, appSecret, secretDirty, initialConfig.appKey, onSaveConfig])\n\n const handleTest = React.useCallback(async () => {\n setTestState({ kind: 'running' })\n try {\n const result = await onTestConnection()\n if (result.ok) {\n setTestState({ kind: 'ok', categoryCount: result.categoryCount })\n setTestEverSucceeded(true)\n } else {\n setTestState({ kind: 'err', code: result.code, msg: result.msg })\n }\n } catch (err) {\n setTestState({\n kind: 'err',\n code: 'UNKNOWN',\n msg: err instanceof Error ? err.message : 'Test failed',\n })\n }\n }, [onTestConnection])\n\n const handleConnect = React.useCallback(async () => {\n setBusyOAuth(true)\n try {\n await onConnect()\n } finally {\n setBusyOAuth(false)\n }\n }, [onConnect])\n\n const handleDisconnect = React.useCallback(async () => {\n setBusyOAuth(true)\n try {\n await onDisconnect()\n } finally {\n setBusyOAuth(false)\n }\n }, [onDisconnect])\n\n return (\n <div className=\"aliexpress-dropshipping-settings\">\n <section aria-labelledby=\"ae-credentials-heading\">\n <h2 id=\"ae-credentials-heading\">Developer app credentials</h2>\n <p>\n Enter your AliExpress Open Platform app credentials. These are\n stored encrypted at rest and used to sign every AliExpress API\n call for this store.\n </p>\n\n <label>\n <span>App Key</span>\n <input\n type=\"text\"\n value={appKey}\n onChange={(e) => setAppKey(e.target.value)}\n autoComplete=\"off\"\n spellCheck={false}\n />\n </label>\n\n <label>\n <span>App Secret</span>\n <input\n type=\"password\"\n value={appSecret}\n placeholder={secretPreset ? '(secret set - leave blank to keep)' : ''}\n onChange={(e) => {\n setAppSecret(e.target.value)\n setSecretDirty(true)\n }}\n autoComplete=\"off\"\n spellCheck={false}\n />\n </label>\n\n <div className=\"actions\">\n <button\n type=\"button\"\n onClick={handleSave}\n disabled={saveState === 'saving' || appKey.trim().length === 0}\n >\n {saveState === 'saving' ? 'Saving...' : 'Save credentials'}\n </button>\n <button\n type=\"button\"\n onClick={handleTest}\n disabled={!canTest || testState.kind === 'running'}\n >\n {testState.kind === 'running' ? 'Testing...' : 'Test connection'}\n </button>\n </div>\n\n {saveState === 'saved' ? <p role=\"status\">Saved.</p> : null}\n {saveState === 'error' && saveError ? (\n <p role=\"alert\">Save failed: {saveError}</p>\n ) : null}\n\n {testState.kind === 'ok' ? (\n <p role=\"status\">\n Connected to AliExpress. Found {testState.categoryCount} categories.\n </p>\n ) : null}\n {testState.kind === 'err' ? (\n <p role=\"alert\">\n Test failed ({testState.code}): {testState.msg}\n </p>\n ) : null}\n </section>\n\n <section aria-labelledby=\"ae-oauth-heading\">\n <h2 id=\"ae-oauth-heading\">Merchant account connection</h2>\n <p>\n Connect a specific AliExpress seller account to enable product\n import into this store. This is separate from the developer app\n credentials above.\n </p>\n\n {initialStatus.needsReauth ? (\n <p role=\"alert\" className=\"reauth-banner\">\n Re-authentication required. Please reconnect your AliExpress account.\n </p>\n ) : null}\n\n <div className=\"status-card\">\n <div>\n <strong>Status:</strong>{' '}\n {initialStatus.connected ? 'Connected' : 'Not connected'}\n </div>\n {initialStatus.sellerId ? (\n <div>\n <strong>Seller ID:</strong> {initialStatus.sellerId}\n </div>\n ) : null}\n {initialStatus.lastSuccessfulCallAt ? (\n <div>\n <strong>Last successful call:</strong>{' '}\n {initialStatus.lastSuccessfulCallAt}\n </div>\n ) : null}\n </div>\n\n <div className=\"actions\">\n <button\n type=\"button\"\n onClick={handleConnect}\n disabled={!canConnect || busyOAuth}\n >\n {busyOAuth ? 'Working...' : 'Connect merchant AliExpress account'}\n </button>\n <button\n type=\"button\"\n onClick={handleDisconnect}\n disabled={!canDisconnect || busyOAuth}\n >\n Disconnect\n </button>\n </div>\n\n {!testEverSucceeded ? (\n <p>\n Run <em>Test connection</em> once with your AppKey/AppSecret before\n connecting a merchant account.\n </p>\n ) : null}\n </section>\n\n <section aria-labelledby=\"ae-coming-soon-heading\">\n <h2 id=\"ae-coming-soon-heading\">Order forwarding</h2>\n <p>\n Coming soon. Automatic order forwarding to AliExpress requires\n our app to be approved out of Test status by AliExpress. Product\n import and browsing work today.\n </p>\n </section>\n </div>\n )\n}\n\nexport default AliExpressDropshippingSettingsForm\n"],"mappings":";AAcO,IAAM,sBAAsB;AA8B5B,IAAK,yBAAL,kBAAKA,4BAAL;AACL,EAAAA,wBAAA,wBAAqB;AACrB,EAAAA,wBAAA,wBAAqB;AACrB,EAAAA,wBAAA,mBAAgB;AAChB,EAAAA,wBAAA,kBAAe;AAJL,SAAAA;AAAA,GAAA;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G,IAAG,oBAAmB,yCAA2B;AAAA,MACrD,oBAAC,OAAE,+JAIH;AAAA,MAEC,cAAc,cACb,oBAAC,OAAE,MAAK,SAAQ,WAAU,iBAAgB,mFAE1C,IACE;AAAA,MAEJ,qBAAC,SAAI,WAAU,eACb;AAAA,6BAAC,SACC;AAAA,8BAAC,YAAO,qBAAO;AAAA,UAAU;AAAA,UACxB,cAAc,YAAY,cAAc;AAAA,WAC3C;AAAA,QACC,cAAc,WACb,qBAAC,SACC;AAAA,8BAAC,YAAO,wBAAU;AAAA,UAAS;AAAA,UAAE,cAAc;AAAA,WAC7C,IACE;AAAA,QACH,cAAc,uBACb,qBAAC,SACC;AAAA,8BAAC,YAAO,mCAAqB;AAAA,UAAU;AAAA,UACtC,cAAc;AAAA,WACjB,IACE;AAAA,SACN;AAAA,MAEA,qBAAC,SAAI,WAAU,WACb;AAAA;AAAA,UAAC;AAAA;AAAA,YACC,MAAK;AAAA,YACL,SAAS;AAAA,YACT,UAAU,CAAC,cAAc;AAAA,YAExB,sBAAY,eAAe;AAAA;AAAA,QAC9B;AAAA,QACA;AAAA,UAAC;AAAA;AAAA,YACC,MAAK;AAAA,YACL,SAAS;AAAA,YACT,UAAU,CAAC,iBAAiB;AAAA,YAC7B;AAAA;AAAA,QAED;AAAA,SACF;AAAA,MAEC,CAAC,oBACA,qBAAC,OAAE;AAAA;AAAA,QACG,oBAAC,QAAG,6BAAe;AAAA,QAAK;AAAA,SAE9B,IACE;AAAA,OACN;AAAA,IAEA,qBAAC,aAAQ,mBAAgB,0BACvB;AAAA,0BAAC,QAAG,IAAG,0BAAyB,8BAAgB;AAAA,MAChD,oBAAC,OAAE,6KAIH;AAAA,OACF;AAAA,KACF;AAEJ;","names":["AliExpressReauthReason"]}
@@ -0,0 +1,89 @@
1
+ // src/client/use-preflight.ts
2
+ import { useCallback, useState } from "react";
3
+ function useAliexpressPreflight(options = {}) {
4
+ const [isPending, setIsPending] = useState(false);
5
+ const mutateAsync = useCallback(async ({ cartId }) => {
6
+ setIsPending(true);
7
+ try {
8
+ const baseUrl = options.baseUrl ?? process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL ?? "";
9
+ const publishableKey = options.publishableKey ?? process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY ?? "";
10
+ const response = await fetch(`${baseUrl.replace(/\/$/, "")}/store/aliexpress-dropshipping/preflight-cart`, {
11
+ method: "POST",
12
+ headers: {
13
+ "Content-Type": "application/json",
14
+ ...publishableKey ? { "x-publishable-api-key": publishableKey } : {}
15
+ },
16
+ body: JSON.stringify({ cart_id: cartId })
17
+ });
18
+ if (!response.ok) throw new Error(`Preflight check failed: ${response.status}`);
19
+ return await response.json();
20
+ } finally {
21
+ setIsPending(false);
22
+ }
23
+ }, [options.baseUrl, options.publishableKey]);
24
+ return { mutateAsync, isPending };
25
+ }
26
+
27
+ // src/client/preflight-guard.tsx
28
+ import { useEffect, useState as useState2 } from "react";
29
+ import { jsx, jsxs } from "react/jsx-runtime";
30
+ function AliexpressCheckoutGuard({ cartId, options, onBlock }) {
31
+ const preflight = useAliexpressPreflight(options);
32
+ const [blockedResult, setBlockedResult] = useState2(null);
33
+ useEffect(() => {
34
+ if (!cartId) return;
35
+ let cancelled = false;
36
+ void preflight.mutateAsync({ cartId }).then((result) => {
37
+ if (cancelled) return;
38
+ if (!result.ok) {
39
+ setBlockedResult(result);
40
+ onBlock?.(result);
41
+ } else {
42
+ setBlockedResult(null);
43
+ }
44
+ }).catch(() => {
45
+ if (!cancelled) setBlockedResult(null);
46
+ });
47
+ return () => {
48
+ cancelled = true;
49
+ };
50
+ }, [cartId]);
51
+ if (!blockedResult) return null;
52
+ const itemErrors = blockedResult.itemErrors ?? [];
53
+ const addressErrors = blockedResult.addressErrors ?? [];
54
+ const merchantErrors = blockedResult.merchantErrors ?? [];
55
+ return /* @__PURE__ */ jsxs(
56
+ "div",
57
+ {
58
+ role: "alert",
59
+ style: {
60
+ border: "1px solid #f5c2c7",
61
+ background: "#f8d7da",
62
+ color: "#842029",
63
+ padding: "12px 16px",
64
+ borderRadius: 8,
65
+ marginBottom: 16,
66
+ fontSize: 14,
67
+ lineHeight: 1.4
68
+ },
69
+ children: [
70
+ /* @__PURE__ */ jsx("strong", { style: { display: "block", marginBottom: 6 }, children: "Some items in your cart can't be shipped" }),
71
+ /* @__PURE__ */ jsxs("ul", { style: { margin: 0, paddingLeft: 20 }, children: [
72
+ itemErrors.map((err) => /* @__PURE__ */ jsxs("li", { children: [
73
+ /* @__PURE__ */ jsx("strong", { children: err.productTitle }),
74
+ ": ",
75
+ err.message
76
+ ] }, err.variantId)),
77
+ addressErrors.map((err, idx) => /* @__PURE__ */ jsx("li", { children: err.message }, `addr-${idx}`)),
78
+ merchantErrors.map((err, idx) => /* @__PURE__ */ jsx("li", { children: err.message }, `merchant-${idx}`))
79
+ ] })
80
+ ]
81
+ }
82
+ );
83
+ }
84
+
85
+ export {
86
+ useAliexpressPreflight,
87
+ AliexpressCheckoutGuard
88
+ };
89
+ //# sourceMappingURL=chunk-FPBGH4MH.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client/use-preflight.ts","../src/client/preflight-guard.tsx"],"sourcesContent":["'use client'\n\nimport { useCallback, useState } from 'react'\nimport type { PreflightResult } from '../types'\n\nexport interface UseAliexpressPreflightOptions {\n baseUrl?: string\n publishableKey?: string\n}\n\nexport function useAliexpressPreflight(options: UseAliexpressPreflightOptions = {}) {\n const [isPending, setIsPending] = useState(false)\n const mutateAsync = useCallback(async ({ cartId }: { cartId: string }): Promise<PreflightResult> => {\n setIsPending(true)\n try {\n const baseUrl = options.baseUrl ?? process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL ?? ''\n const publishableKey = options.publishableKey ?? process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY ?? ''\n const response = await fetch(`${baseUrl.replace(/\\/$/, '')}/store/aliexpress-dropshipping/preflight-cart`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(publishableKey ? { 'x-publishable-api-key': publishableKey } : {}),\n },\n body: JSON.stringify({ cart_id: cartId }),\n })\n if (!response.ok) throw new Error(`Preflight check failed: ${response.status}`)\n return await response.json() as PreflightResult\n } finally {\n setIsPending(false)\n }\n }, [options.baseUrl, options.publishableKey])\n\n return { mutateAsync, isPending }\n}\n","'use client'\n\nimport { useEffect, useState } from 'react'\nimport { useAliexpressPreflight, type UseAliexpressPreflightOptions } from './use-preflight'\nimport type { PreflightResult } from '../types'\n\nexport interface AliexpressCheckoutGuardProps {\n /**\n * Cart id to preflight. Passed by the storefront checkout page or the plugin slot's\n * `context.cartId`. If undefined (cart not yet loaded), the guard renders nothing.\n */\n cartId?: string\n /** Optional TanStack Query hook options (e.g. custom baseUrl for tests). */\n options?: UseAliexpressPreflightOptions\n /** Optional callback merchant storefronts can wire to react to the block state. */\n onBlock?: (result: PreflightResult) => void\n}\n\n/**\n * Standalone slot-compatible AliExpress preflight component.\n *\n * Rendered by the plugin registry at the `checkoutStart` slot. On mount + whenever\n * `cartId` changes, runs the pre-payment shipping/address/OAuth check. If any AE line\n * item is unfulfillable, renders an inline warning block above the checkout form.\n *\n * NOTE: this is a SOFT warning (not a hard block on the pay button). For hard blocking,\n * the merchant's checkout page should call `useAliexpressPreflight` directly and gate\n * its own `cart.complete()` on the result. See package README for both integration\n * patterns.\n *\n * Fail-open: if the preflight endpoint is unreachable, the guard renders nothing rather\n * than block checkout. Better to occasionally let through an unfulfillable order (which\n * downstream retry + refund handles) than to lock the merchant out of checkouts on a\n * transient outage.\n */\nexport function AliexpressCheckoutGuard({ cartId, options, onBlock }: AliexpressCheckoutGuardProps) {\n const preflight = useAliexpressPreflight(options)\n const [blockedResult, setBlockedResult] = useState<PreflightResult | null>(null)\n\n useEffect(() => {\n if (!cartId) return\n let cancelled = false\n void preflight\n .mutateAsync({ cartId })\n .then((result) => {\n if (cancelled) return\n if (!result.ok) {\n setBlockedResult(result)\n onBlock?.(result)\n } else {\n setBlockedResult(null)\n }\n })\n .catch(() => {\n // Fail-open: don't block checkout if the preflight endpoint itself is unreachable.\n if (!cancelled) setBlockedResult(null)\n })\n return () => {\n cancelled = true\n }\n // Intentionally re-runs only on cartId change, not on mutation reference change.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [cartId])\n\n if (!blockedResult) return null\n\n const itemErrors = blockedResult.itemErrors ?? []\n const addressErrors = blockedResult.addressErrors ?? []\n const merchantErrors = blockedResult.merchantErrors ?? []\n\n return (\n <div\n role=\"alert\"\n style={{\n border: '1px solid #f5c2c7',\n background: '#f8d7da',\n color: '#842029',\n padding: '12px 16px',\n borderRadius: 8,\n marginBottom: 16,\n fontSize: 14,\n lineHeight: 1.4,\n }}\n >\n <strong style={{ display: 'block', marginBottom: 6 }}>\n Some items in your cart can&apos;t be shipped\n </strong>\n <ul style={{ margin: 0, paddingLeft: 20 }}>\n {itemErrors.map((err) => (\n <li key={err.variantId}>\n <strong>{err.productTitle}</strong>: {err.message}\n </li>\n ))}\n {addressErrors.map((err, idx) => (\n <li key={`addr-${idx}`}>{err.message}</li>\n ))}\n {merchantErrors.map((err, idx) => (\n <li key={`merchant-${idx}`}>{err.message}</li>\n ))}\n </ul>\n </div>\n )\n}\n"],"mappings":";AAEA,SAAS,aAAa,gBAAgB;AAQ/B,SAAS,uBAAuB,UAAyC,CAAC,GAAG;AAClF,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAChD,QAAM,cAAc,YAAY,OAAO,EAAE,OAAO,MAAoD;AAClG,iBAAa,IAAI;AACjB,QAAI;AACF,YAAM,UAAU,QAAQ,WAAW,QAAQ,IAAI,kCAAkC;AACjF,YAAM,iBAAiB,QAAQ,kBAAkB,QAAQ,IAAI,sCAAsC;AACnG,YAAM,WAAW,MAAM,MAAM,GAAG,QAAQ,QAAQ,OAAO,EAAE,CAAC,iDAAiD;AAAA,QACzG,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,gBAAgB;AAAA,UAChB,GAAI,iBAAiB,EA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AAAA,QACZ,OAAO;AAAA,QACP,SAAS;AAAA,QACT,cAAc;AAAA,QACd,cAAc;AAAA,QACd,UAAU;AAAA,QACV,YAAY;AAAA,MACd;AAAA,MAEA;AAAA,4BAAC,YAAO,OAAO,EAAE,SAAS,SAAS,cAAc,EAAE,GAAG,sDAEtD;AAAA,QACA,qBAAC,QAAG,OAAO,EAAE,QAAQ,GAAG,aAAa,GAAG,GACrC;AAAA,qBAAW,IAAI,CAAC,QACf,qBAAC,QACC;AAAA,gCAAC,YAAQ,cAAI,cAAa;AAAA,YAAS;AAAA,YAAG,IAAI;AAAA,eADnC,IAAI,SAEb,CACD;AAAA,UACA,cAAc,IAAI,CAAC,KAAK,QACvB,oBAAC,QAAwB,cAAI,WAApB,QAAQ,GAAG,EAAiB,CACtC;AAAA,UACA,eAAe,IAAI,CAAC,KAAK,QACxB,oBAAC,QAA4B,cAAI,WAAxB,YAAY,GAAG,EAAiB,CAC1C;AAAA,WACH;AAAA;AAAA;AAAA,EACF;AAEJ;","names":["useState","useState"]}
@@ -0,0 +1,46 @@
1
+ import { P as PreflightResult } from '../types-CLTkhq_u.mjs';
2
+ export { j as PreflightAddressError, k as PreflightItemError, l as PreflightMerchantError } from '../types-CLTkhq_u.mjs';
3
+ import * as react_jsx_runtime from 'react/jsx-runtime';
4
+
5
+ interface UseAliexpressPreflightOptions {
6
+ baseUrl?: string;
7
+ publishableKey?: string;
8
+ }
9
+ declare function useAliexpressPreflight(options?: UseAliexpressPreflightOptions): {
10
+ mutateAsync: ({ cartId }: {
11
+ cartId: string;
12
+ }) => Promise<PreflightResult>;
13
+ isPending: boolean;
14
+ };
15
+
16
+ interface AliexpressCheckoutGuardProps {
17
+ /**
18
+ * Cart id to preflight. Passed by the storefront checkout page or the plugin slot's
19
+ * `context.cartId`. If undefined (cart not yet loaded), the guard renders nothing.
20
+ */
21
+ cartId?: string;
22
+ /** Optional TanStack Query hook options (e.g. custom baseUrl for tests). */
23
+ options?: UseAliexpressPreflightOptions;
24
+ /** Optional callback merchant storefronts can wire to react to the block state. */
25
+ onBlock?: (result: PreflightResult) => void;
26
+ }
27
+ /**
28
+ * Standalone slot-compatible AliExpress preflight component.
29
+ *
30
+ * Rendered by the plugin registry at the `checkoutStart` slot. On mount + whenever
31
+ * `cartId` changes, runs the pre-payment shipping/address/OAuth check. If any AE line
32
+ * item is unfulfillable, renders an inline warning block above the checkout form.
33
+ *
34
+ * NOTE: this is a SOFT warning (not a hard block on the pay button). For hard blocking,
35
+ * the merchant's checkout page should call `useAliexpressPreflight` directly and gate
36
+ * its own `cart.complete()` on the result. See package README for both integration
37
+ * patterns.
38
+ *
39
+ * Fail-open: if the preflight endpoint is unreachable, the guard renders nothing rather
40
+ * than block checkout. Better to occasionally let through an unfulfillable order (which
41
+ * downstream retry + refund handles) than to lock the merchant out of checkouts on a
42
+ * transient outage.
43
+ */
44
+ declare function AliexpressCheckoutGuard({ cartId, options, onBlock }: AliexpressCheckoutGuardProps): react_jsx_runtime.JSX.Element | null;
45
+
46
+ export { AliexpressCheckoutGuard, type AliexpressCheckoutGuardProps, PreflightResult, type UseAliexpressPreflightOptions, useAliexpressPreflight };
@@ -0,0 +1,46 @@
1
+ import { P as PreflightResult } from '../types-CLTkhq_u.js';
2
+ export { j as PreflightAddressError, k as PreflightItemError, l as PreflightMerchantError } from '../types-CLTkhq_u.js';
3
+ import * as react_jsx_runtime from 'react/jsx-runtime';
4
+
5
+ interface UseAliexpressPreflightOptions {
6
+ baseUrl?: string;
7
+ publishableKey?: string;
8
+ }
9
+ declare function useAliexpressPreflight(options?: UseAliexpressPreflightOptions): {
10
+ mutateAsync: ({ cartId }: {
11
+ cartId: string;
12
+ }) => Promise<PreflightResult>;
13
+ isPending: boolean;
14
+ };
15
+
16
+ interface AliexpressCheckoutGuardProps {
17
+ /**
18
+ * Cart id to preflight. Passed by the storefront checkout page or the plugin slot's
19
+ * `context.cartId`. If undefined (cart not yet loaded), the guard renders nothing.
20
+ */
21
+ cartId?: string;
22
+ /** Optional TanStack Query hook options (e.g. custom baseUrl for tests). */
23
+ options?: UseAliexpressPreflightOptions;
24
+ /** Optional callback merchant storefronts can wire to react to the block state. */
25
+ onBlock?: (result: PreflightResult) => void;
26
+ }
27
+ /**
28
+ * Standalone slot-compatible AliExpress preflight component.
29
+ *
30
+ * Rendered by the plugin registry at the `checkoutStart` slot. On mount + whenever
31
+ * `cartId` changes, runs the pre-payment shipping/address/OAuth check. If any AE line
32
+ * item is unfulfillable, renders an inline warning block above the checkout form.
33
+ *
34
+ * NOTE: this is a SOFT warning (not a hard block on the pay button). For hard blocking,
35
+ * the merchant's checkout page should call `useAliexpressPreflight` directly and gate
36
+ * its own `cart.complete()` on the result. See package README for both integration
37
+ * patterns.
38
+ *
39
+ * Fail-open: if the preflight endpoint is unreachable, the guard renders nothing rather
40
+ * than block checkout. Better to occasionally let through an unfulfillable order (which
41
+ * downstream retry + refund handles) than to lock the merchant out of checkouts on a
42
+ * transient outage.
43
+ */
44
+ declare function AliexpressCheckoutGuard({ cartId, options, onBlock }: AliexpressCheckoutGuardProps): react_jsx_runtime.JSX.Element | null;
45
+
46
+ export { AliexpressCheckoutGuard, type AliexpressCheckoutGuardProps, PreflightResult, type UseAliexpressPreflightOptions, useAliexpressPreflight };
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/client/index.ts
21
+ var client_exports = {};
22
+ __export(client_exports, {
23
+ AliexpressCheckoutGuard: () => AliexpressCheckoutGuard,
24
+ useAliexpressPreflight: () => useAliexpressPreflight
25
+ });
26
+ module.exports = __toCommonJS(client_exports);
27
+
28
+ // src/client/use-preflight.ts
29
+ var import_react = require("react");
30
+ function useAliexpressPreflight(options = {}) {
31
+ const [isPending, setIsPending] = (0, import_react.useState)(false);
32
+ const mutateAsync = (0, import_react.useCallback)(async ({ cartId }) => {
33
+ setIsPending(true);
34
+ try {
35
+ const baseUrl = options.baseUrl ?? process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL ?? "";
36
+ const publishableKey = options.publishableKey ?? process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY ?? "";
37
+ const response = await fetch(`${baseUrl.replace(/\/$/, "")}/store/aliexpress-dropshipping/preflight-cart`, {
38
+ method: "POST",
39
+ headers: {
40
+ "Content-Type": "application/json",
41
+ ...publishableKey ? { "x-publishable-api-key": publishableKey } : {}
42
+ },
43
+ body: JSON.stringify({ cart_id: cartId })
44
+ });
45
+ if (!response.ok) throw new Error(`Preflight check failed: ${response.status}`);
46
+ return await response.json();
47
+ } finally {
48
+ setIsPending(false);
49
+ }
50
+ }, [options.baseUrl, options.publishableKey]);
51
+ return { mutateAsync, isPending };
52
+ }
53
+
54
+ // src/client/preflight-guard.tsx
55
+ var import_react2 = require("react");
56
+ var import_jsx_runtime = require("react/jsx-runtime");
57
+ function AliexpressCheckoutGuard({ cartId, options, onBlock }) {
58
+ const preflight = useAliexpressPreflight(options);
59
+ const [blockedResult, setBlockedResult] = (0, import_react2.useState)(null);
60
+ (0, import_react2.useEffect)(() => {
61
+ if (!cartId) return;
62
+ let cancelled = false;
63
+ void preflight.mutateAsync({ cartId }).then((result) => {
64
+ if (cancelled) return;
65
+ if (!result.ok) {
66
+ setBlockedResult(result);
67
+ onBlock?.(result);
68
+ } else {
69
+ setBlockedResult(null);
70
+ }
71
+ }).catch(() => {
72
+ if (!cancelled) setBlockedResult(null);
73
+ });
74
+ return () => {
75
+ cancelled = true;
76
+ };
77
+ }, [cartId]);
78
+ if (!blockedResult) return null;
79
+ const itemErrors = blockedResult.itemErrors ?? [];
80
+ const addressErrors = blockedResult.addressErrors ?? [];
81
+ const merchantErrors = blockedResult.merchantErrors ?? [];
82
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
83
+ "div",
84
+ {
85
+ role: "alert",
86
+ style: {
87
+ border: "1px solid #f5c2c7",
88
+ background: "#f8d7da",
89
+ color: "#842029",
90
+ padding: "12px 16px",
91
+ borderRadius: 8,
92
+ marginBottom: 16,
93
+ fontSize: 14,
94
+ lineHeight: 1.4
95
+ },
96
+ children: [
97
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { style: { display: "block", marginBottom: 6 }, children: "Some items in your cart can't be shipped" }),
98
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("ul", { style: { margin: 0, paddingLeft: 20 }, children: [
99
+ itemErrors.map((err) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { children: [
100
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: err.productTitle }),
101
+ ": ",
102
+ err.message
103
+ ] }, err.variantId)),
104
+ addressErrors.map((err, idx) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { children: err.message }, `addr-${idx}`)),
105
+ merchantErrors.map((err, idx) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { children: err.message }, `merchant-${idx}`))
106
+ ] })
107
+ ]
108
+ }
109
+ );
110
+ }
111
+ // Annotate the CommonJS export names for ESM import in node:
112
+ 0 && (module.exports = {
113
+ AliexpressCheckoutGuard,
114
+ useAliexpressPreflight
115
+ });
116
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/client/index.ts","../../src/client/use-preflight.ts","../../src/client/preflight-guard.tsx"],"sourcesContent":["export { useAliexpressPreflight, type UseAliexpressPreflightOptions } from './use-preflight'\nexport { AliexpressCheckoutGuard, type AliexpressCheckoutGuardProps } from './preflight-guard'\nexport type {\n PreflightResult,\n PreflightMerchantError,\n PreflightAddressError,\n PreflightItemError,\n} from '../types'\n","'use client'\n\nimport { useCallback, useState } from 'react'\nimport type { PreflightResult } from '../types'\n\nexport interface UseAliexpressPreflightOptions {\n baseUrl?: string\n publishableKey?: string\n}\n\nexport function useAliexpressPreflight(options: UseAliexpressPreflightOptions = {}) {\n const [isPending, setIsPending] = useState(false)\n const mutateAsync = useCallback(async ({ cartId }: { cartId: string }): Promise<PreflightResult> => {\n setIsPending(true)\n try {\n const baseUrl = options.baseUrl ?? process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL ?? ''\n const publishableKey = options.publishableKey ?? process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY ?? ''\n const response = await fetch(`${baseUrl.replace(/\\/$/, '')}/store/aliexpress-dropshipping/preflight-cart`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(publishableKey ? { 'x-publishable-api-key': publishableKey } : {}),\n },\n body: JSON.stringify({ cart_id: cartId }),\n })\n if (!response.ok) throw new Error(`Preflight check failed: ${response.status}`)\n return await response.json() as PreflightResult\n } finally {\n setIsPending(false)\n }\n }, [options.baseUrl, options.publishableKey])\n\n return { mutateAsync, isPending }\n}\n","'use client'\n\nimport { useEffect, useState } from 'react'\nimport { useAliexpressPreflight, type UseAliexpressPreflightOptions } from './use-preflight'\nimport type { PreflightResult } from '../types'\n\nexport interface AliexpressCheckoutGuardProps {\n /**\n * Cart id to preflight. Passed by the storefront checkout page or the plugin slot's\n * `context.cartId`. If undefined (cart not yet loaded), the guard renders nothing.\n */\n cartId?: string\n /** Optional TanStack Query hook options (e.g. custom baseUrl for tests). */\n options?: UseAliexpressPreflightOptions\n /** Optional callback merchant storefronts can wire to react to the block state. */\n onBlock?: (result: PreflightResult) => void\n}\n\n/**\n * Standalone slot-compatible AliExpress preflight component.\n *\n * Rendered by the plugin registry at the `checkoutStart` slot. On mount + whenever\n * `cartId` changes, runs the pre-payment shipping/address/OAuth check. If any AE line\n * item is unfulfillable, renders an inline warning block above the checkout form.\n *\n * NOTE: this is a SOFT warning (not a hard block on the pay button). For hard blocking,\n * the merchant's checkout page should call `useAliexpressPreflight` directly and gate\n * its own `cart.complete()` on the result. See package README for both integration\n * patterns.\n *\n * Fail-open: if the preflight endpoint is unreachable, the guard renders nothing rather\n * than block checkout. Better to occasionally let through an unfulfillable order (which\n * downstream retry + refund handles) than to lock the merchant out of checkouts on a\n * transient outage.\n */\nexport function AliexpressCheckoutGuard({ cartId, options, onBlock }: AliexpressCheckoutGuardProps) {\n const preflight = useAliexpressPreflight(options)\n const [blockedResult, setBlockedResult] = useState<PreflightResult | null>(null)\n\n useEffect(() => {\n if (!cartId) return\n let cancelled = false\n void preflight\n .mutateAsync({ cartId })\n .then((result) => {\n if (cancelled) return\n if (!result.ok) {\n setBlockedResult(result)\n onBlock?.(result)\n } else {\n setBlockedResult(null)\n }\n })\n .catch(() => {\n // Fail-open: don't block checkout if the preflight endpoint itself is unreachable.\n if (!cancelled) setBlockedResult(null)\n })\n return () => {\n cancelled = true\n }\n // Intentionally re-runs only on cartId change, not on mutation reference change.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [cartId])\n\n if (!blockedResult) return null\n\n const itemErrors = blockedResult.itemErrors ?? []\n const addressErrors = blockedResult.addressErrors ?? []\n const merchantErrors = blockedResult.merchantErrors ?? []\n\n return (\n <div\n role=\"alert\"\n style={{\n border: '1px solid #f5c2c7',\n background: '#f8d7da',\n color: '#842029',\n padding: '12px 16px',\n borderRadius: 8,\n marginBottom: 16,\n fontSize: 14,\n lineHeight: 1.4,\n }}\n >\n <strong style={{ display: 'block', marginBottom: 6 }}>\n Some items in your cart can&apos;t be shipped\n </strong>\n <ul style={{ margin: 0, paddingLeft: 20 }}>\n {itemErrors.map((err) => (\n <li key={err.variantId}>\n <strong>{err.productTitle}</strong>: {err.message}\n </li>\n ))}\n {addressErrors.map((err, idx) => (\n <li key={`addr-${idx}`}>{err.message}</li>\n ))}\n {merchantErrors.map((err, idx) => (\n <li key={`merchant-${idx}`}>{err.message}</li>\n ))}\n </ul>\n </div>\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,mBAAsC;AAQ/B,SAAS,uBAAuB,UAAyC,CAAC,GAAG;AAClF,QAAM,CAAC,WAAW,YAAY,QAAI,uBAAS,KAAK;AAChD,QAAM,kBAAc,0BAAY,OAAO,EAAE,OAAO,MAAoD;AAClG,iBAAa,IAAI;AACjB,QAAI;AACF,YAAM,UAAU,QAAQ,WAAW,QAAQ,IAAI,kCAAkC;AACjF,YAAM,iBAAiB,QAAQ,kBAAkB,QAAQ,IAAI,sCAAsC;AACnG,YAAM,WAAW,MAAM,MAAM,GAAG,QAAQ,QAAQ,OAAO,EAAE,CAAC,iDAAiD;AAAA,QACzG,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,gBAAgB;AAAA,UAChB,GAAI,iBAAiB,EAAE,yBAAyB,eAAe,IAAI,CAAC;AAAA,QACtE;AAAA,QACA,MAAM,KAAK,UAAU,EAAE,SAAS,OAAO,CAAC;AAAA,MAC1C,CAAC;AACD,UAAI,CAAC,SAAS,GAAI,OAAM,IAAI,MAAM,2BAA2B,SAAS,MAAM,EAAE;AAC9E,aAAO,MAAM,SAAS,KAAK;AAAA,IAC7B,UAAE;AACA,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF,GAAG,CAAC,QAAQ,SAAS,QAAQ,cAAc,CAAC;AAE5C,SAAO,EAAE,aAAa,UAAU;AAClC;;;AC/BA,IAAAA,gBAAoC;AAkF9B;AAjDC,SAAS,wBAAwB,EAAE,QAAQ,SAAS,QAAQ,GAAiC;AAClG,QAAM,YAAY,uBAAu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ACA,eAAe,IAAI,CAAC,KAAK,QACxB,4CAAC,QAA4B,cAAI,WAAxB,YAAY,GAAG,EAAiB,CAC1C;AAAA,WACH;AAAA;AAAA;AAAA,EACF;AAEJ;","names":["import_react"]}
@@ -0,0 +1,9 @@
1
+ import {
2
+ AliexpressCheckoutGuard,
3
+ useAliexpressPreflight
4
+ } from "../chunk-FPBGH4MH.mjs";
5
+ export {
6
+ AliexpressCheckoutGuard,
7
+ useAliexpressPreflight
8
+ };
9
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/dist/index.d.mts CHANGED
@@ -1,171 +1,5 @@
1
- import * as React from 'react';
2
-
3
- /**
4
- * Public types for @amboras-dev/aliexpress-dropshipping.
5
- *
6
- * These are the single source of truth for the wire shape between the
7
- * Amboras admin settings form and the medusa-backend-orchestrator
8
- * Store API routes under `/store/aliexpress-dropshipping/*`. The DTO
9
- * files on the medusa side must stay byte-compatible with these.
10
- */
11
- /**
12
- * Sentinel returned in place of a stored secret when the settings form
13
- * reads back current config. Matches the pattern used by meta-ads and
14
- * pinterest so the admin never sees the plaintext secret after write.
15
- */
16
- declare const SECRET_SET_SENTINEL: "__SECRET_SET__";
17
- type SecretSetSentinel = typeof SECRET_SET_SENTINEL;
18
- /**
19
- * Per-store AliExpress plugin configuration.
20
- *
21
- * - `appKey` / `appSecret` are per-store developer app credentials
22
- * supplied by the merchant. The admin form receives
23
- * `SECRET_SET_SENTINEL` for `appSecret` on read, and only sends a
24
- * real value on user edit.
25
- * - `connectedSellerId` is populated after the merchant completes the
26
- * OAuth flow to `/rest/auth/token/create`.
27
- * - `needsReauth` is flipped by the backend runtime detector when it
28
- * sees `MissingParameter access_token` or `IllegalAccessToken`
29
- * sub-codes on any envelope.
30
- * - `lastSuccessfulCallAt` is an ISO-8601 timestamp for the status card.
31
- */
32
- interface AliExpressPluginConfig {
33
- enabled: boolean;
34
- appKey: string | null;
35
- appSecret: string | SecretSetSentinel | null;
36
- connectedSellerId: string | null;
37
- needsReauth: boolean;
38
- lastSuccessfulCallAt: string | null;
39
- }
40
- /**
41
- * Reasons the backend surfaces when a merchant token becomes invalid.
42
- * Kept narrow so the admin banner can render a specific message.
43
- */
44
- declare enum AliExpressReauthReason {
45
- MissingAccessToken = "missing_access_token",
46
- IllegalAccessToken = "illegal_access_token",
47
- RefreshFailed = "refresh_failed",
48
- Disconnected = "disconnected"
49
- }
50
- /**
51
- * Category node returned by `aliexpress.ds.category.get`. The API
52
- * returns a flat list; the admin renders it as a tree by walking
53
- * `parentCategoryId`.
54
- */
55
- interface AliExpressCategoryDto {
56
- categoryId: string;
57
- categoryName: string;
58
- parentCategoryId: string | null;
59
- }
60
- /**
61
- * Product summary shape returned by `aliexpress.ds.recommend.feed.get`.
62
- * Used by the "browse products" admin surface.
63
- */
64
- interface AliExpressProductSummaryDto {
65
- productId: string;
66
- title: string;
67
- imageUrl: string | null;
68
- minPrice: number | null;
69
- maxPrice: number | null;
70
- currency: string | null;
71
- productDetailUrl: string | null;
72
- }
73
- /**
74
- * Full product shape returned by `aliexpress.ds.product.get`. Consumed
75
- * by the medusa-side mapper `aliexpressProductToMedusaDraft`.
76
- */
77
- interface AliExpressProductDto {
78
- productId: string;
79
- title: string;
80
- description: string | null;
81
- images: string[];
82
- variants: AliExpressProductVariantDto[];
83
- weightGrams: number | null;
84
- sourceUrl: string | null;
85
- }
86
- interface AliExpressProductVariantDto {
87
- skuId: string;
88
- title: string | null;
89
- price: number;
90
- currency: string;
91
- stock: number | null;
92
- attributes: Record<string, string>;
93
- }
94
- /**
95
- * Return shape from `POST /store/aliexpress-dropshipping/products/:id/import`.
96
- */
97
- interface AliExpressImportResultDto {
98
- medusaProductId: string;
99
- sourceProductId: string;
100
- importedVariants: number;
101
- }
102
- /**
103
- * Return shape from `GET /store/aliexpress-dropshipping/status` - drives
104
- * the admin status card.
105
- */
106
- interface AliExpressConnectionStatusDto {
107
- connected: boolean;
108
- sellerId: string | null;
109
- needsReauth: boolean;
110
- reauthReason: AliExpressReauthReason | null;
111
- lastSuccessfulCallAt: string | null;
112
- }
113
- /**
114
- * Return shape from `POST /store/aliexpress-dropshipping/test-connection`.
115
- */
116
- type AliExpressTestConnectionResult = {
117
- ok: true;
118
- categoryCount: number;
119
- } | {
120
- ok: false;
121
- code: string;
122
- msg: string;
123
- };
124
-
125
- /**
126
- * Admin settings form for the AliExpress Dropshipping integration.
127
- *
128
- * Class B: this component owns the UI and talks to the Medusa Store API
129
- * under `/store/aliexpress-dropshipping/*`. It does NOT embed any
130
- * AliExpress SDK, does not sign requests, and does not touch OAuth
131
- * tokens directly - the backend does all of that.
132
- *
133
- * The component is intentionally dependency-light (no external UI kit,
134
- * no @tanstack/react-query peer) so the admin bundle can drop it in
135
- * without extra peer dep resolution.
136
- */
137
-
138
- interface AliExpressDropshippingSettingsFormProps {
139
- /** Current config for this store (fetched by the parent server component). */
140
- initialConfig: AliExpressPluginConfig;
141
- /** Current connection status (from `GET /status`). */
142
- initialStatus: AliExpressConnectionStatusDto;
143
- /**
144
- * Persist non-secret + optionally new secret values. The parent maps
145
- * this onto `PATCH /store/aliexpress-dropshipping/config` (or
146
- * equivalent) and then re-fetches config on success.
147
- *
148
- * `appSecret` is only sent when the merchant actually typed a new
149
- * value; if they leave the field untouched, this method receives
150
- * `undefined` for that key so the backend keeps the existing secret.
151
- */
152
- onSaveConfig: (patch: {
153
- appKey?: string;
154
- appSecret?: string;
155
- enabled?: boolean;
156
- }) => Promise<void>;
157
- /** Kick off `POST /oauth/start` and redirect to the returned URL. */
158
- onConnect: () => Promise<void>;
159
- /** Kick off `POST /oauth/disconnect` and clear merchant credentials. */
160
- onDisconnect: () => Promise<void>;
161
- /** Call `POST /test-connection` and return the result. */
162
- onTestConnection: () => Promise<AliExpressTestConnectionResult>;
163
- }
164
- /**
165
- * Amboras admin settings surface for AliExpress Dropshipping.
166
- * Renders AppKey + AppSecret inputs, Test / Connect / Disconnect
167
- * buttons, status card, and a "Coming soon" order-forwarding block.
168
- */
169
- declare function AliExpressDropshippingSettingsForm(props: AliExpressDropshippingSettingsFormProps): React.ReactElement;
170
-
171
- export { type AliExpressCategoryDto, type AliExpressConnectionStatusDto, AliExpressDropshippingSettingsForm, type AliExpressDropshippingSettingsFormProps, type AliExpressImportResultDto, type AliExpressPluginConfig, type AliExpressProductDto, type AliExpressProductSummaryDto, type AliExpressProductVariantDto, AliExpressReauthReason, type AliExpressTestConnectionResult, SECRET_SET_SENTINEL, type SecretSetSentinel };
1
+ export { AliExpressDropshippingSettingsForm, AliExpressDropshippingSettingsFormProps } from './admin/index.mjs';
2
+ export { A as AliExpressCategoryDto, a as AliExpressConnectionStatusDto, b as AliExpressImportResultDto, c as AliExpressPluginConfig, d as AliExpressProductDto, e as AliExpressProductSummaryDto, f as AliExpressProductVariantDto, g as AliExpressReauthReason, h as AliExpressTestConnectionResult, S as SECRET_SET_SENTINEL, i as SecretSetSentinel } from './types-CLTkhq_u.mjs';
3
+ export { AliexpressCheckoutGuard, AliexpressCheckoutGuardProps, UseAliexpressPreflightOptions, useAliexpressPreflight } from './client/index.mjs';
4
+ import 'react';
5
+ import 'react/jsx-runtime';