@mufucloud/shopify-app-kit 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mufucloud
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,164 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @mufucloud/shopify-app-kit
2
+
3
+ [![CI](https://github.com/MUFU-Cloud/shopify-app-kit/actions/workflows/ci.yml/badge.svg)](https://github.com/MUFU-Cloud/shopify-app-kit/actions/workflows/ci.yml)
4
+
5
+ Server helpers shared by mufucloud's Shopify apps (React Router template): plan checks with Shopify
6
+ App Pricing, Admin API helpers, Klaviyo signup, Free plan limits and hydration-safe formatting.
7
+ TypeScript, ESM only, no runtime dependencies.
8
+
9
+ ## Install
10
+
11
+ Install from GitHub, pinned to a tag:
12
+
13
+ ```bash
14
+ npm install github:MUFU-Cloud/shopify-app-kit#v0.2.0
15
+ ```
16
+
17
+ `dist` is not committed; npm builds it on install through the `prepare` script. Node 20.19 or newer.
18
+
19
+ ## Environment
20
+
21
+ | Variable | Value |
22
+ |---|---|
23
+ | `SHOPIFY_PARTNER_ORG_ID` | the number in the Partner Dashboard URL |
24
+ | `SHOPIFY_PARTNER_API_ACCESS_TOKEN` | Partner API client with "Manage apps" |
25
+ | `SHOPIFY_APP_GID` | `gid://shopify/App/<id>` |
26
+ | `DEV_FORCE_PLAN` | `pro` or `free`, local testing only (ignored when `NODE_ENV=production`) |
27
+
28
+ Without the three Partner API variables the Billing API (`billing.check()`) decides.
29
+
30
+ ## Plan check
31
+
32
+ ```ts
33
+ import { checkIsPro, createMemoryPlanCache, getShopId } from "@mufucloud/shopify-app-kit";
34
+
35
+ // module level, shared across requests
36
+ const planCache = createMemoryPlanCache(); // { ttlMs: 300_000, max: 1000 }
37
+
38
+ const { admin, billing } = await authenticate.admin(request);
39
+ const isPro = await checkIsPro({
40
+ billing,
41
+ shopGid: await getShopId(admin),
42
+ lastKnown: saved?.isPro ?? false,
43
+ cache: planCache,
44
+ });
45
+ ```
46
+
47
+ How the plan is decided:
48
+
49
+ - The Partner API (Active Subscription API) is asked first. A subscription item counts as Pro when
50
+ its handle doesn't contain "free". App Pricing also creates a $0 subscription for the Free plan, and
51
+ paid plans are $0 on dev stores, so price is not used.
52
+ - Pass `proPlans: ["pro", "pro-yearly"]` to list the Pro plan handles explicitly instead (case
53
+ insensitive). `isProSubscriptionItem(item, proPlans?)` applies the same rule to a single item.
54
+ - `legacyBilling: true` also checks `billing.check()` when the Partner API finds nothing. Use it
55
+ only if the app sold Billing API subscriptions before switching to App Pricing.
56
+ - A failed lookup never downgrades a shop: it returns `lastKnown` and nothing is cached.
57
+ - With `cache`, results are reused for `ttlMs`. Pass `refresh: true` after a plan change (for example
58
+ in the subscription webhook or on the return from the plan page) to skip the cache and store the
59
+ fresh result.
60
+
61
+ Other options: `partnerApi` (config object, or `null` to skip the Partner API; defaults to the
62
+ environment), `env` (defaults to `process.env`), `logger` (defaults to `console`).
63
+
64
+ ## Metafields
65
+
66
+ ```ts
67
+ import { getShopId, setMetafields, deleteMetafields } from "@mufucloud/shopify-app-kit";
68
+
69
+ const shopId = await getShopId(admin);
70
+ const errors = await setMetafields(admin, "my_app", shopId, [
71
+ { key: "app_enabled", type: "boolean", value: "true" },
72
+ { key: "settings", type: "json", value: JSON.stringify(settings) },
73
+ ]);
74
+ await deleteMetafields(admin, "my_app", shopId, ["old_key"]);
75
+ ```
76
+
77
+ Both return the `userErrors` (empty on success) and log them. `setMetafields` sends 25 metafields
78
+ per request, the `metafieldsSet` limit.
79
+
80
+ ## Web pixel
81
+
82
+ ```ts
83
+ import { ensureWebPixel } from "@mufucloud/shopify-app-kit";
84
+
85
+ const ok = await ensureWebPixel(admin, process.env.SHOPIFY_APP_URL!); // endpoint: <appUrl>/api/conversion
86
+ ```
87
+
88
+ Creates the app's web pixel or updates its `endpoint` setting. Returns `false` when it couldn't,
89
+ usually because `write_pixels` isn't granted yet. The third argument changes the path.
90
+
91
+ ## Discount codes
92
+
93
+ ```ts
94
+ import { checkDiscountCode } from "@mufucloud/shopify-app-kit";
95
+
96
+ const problem = await checkDiscountCode(admin, "SUMMER10"); // "not_found" | "inactive" | null
97
+ ```
98
+
99
+ `null` means the code is fine or couldn't be checked (for example without `read_discounts`).
100
+
101
+ ## Klaviyo
102
+
103
+ ```ts
104
+ import { subscribeToKlaviyo } from "@mufucloud/shopify-app-kit";
105
+
106
+ const ok = await subscribeToKlaviyo({
107
+ publicKey, // the merchant's public (site) key
108
+ listId,
109
+ email,
110
+ source: "My App",
111
+ properties: { lang: "en" },
112
+ });
113
+ ```
114
+
115
+ Uses the client subscriptions endpoint, so only the public key is needed. The profile is subscribed
116
+ with explicit email marketing consent. Returns `false` on HTTP or network errors and on timeout
117
+ (`timeoutMs`); it doesn't throw.
118
+
119
+ ## Free plan limit
120
+
121
+ ```ts
122
+ import { splitByPlanLimit } from "@mufucloud/shopify-app-kit";
123
+
124
+ const { live, offline } = splitByPlanLimit(products, {
125
+ isPro,
126
+ limit: 5,
127
+ createdAt: (p) => p.createdAt,
128
+ });
129
+ ```
130
+
131
+ On Free, the oldest `limit` items stay live and the rest go offline (kept, not deleted). On Pro
132
+ everything is live.
133
+
134
+ ## Formatting
135
+
136
+ Server and browser must render the same text or hydration fails, so these use a fixed locale
137
+ (`en-US` by default) and UTC.
138
+
139
+ ```ts
140
+ import { formatNumber, formatMoney, formatPercent, formatUtcDateTime, formatUtcDate } from "@mufucloud/shopify-app-kit";
141
+
142
+ formatNumber(12345.6); // "12,345.6"
143
+ formatNumber(0.5, { maximumFractionDigits: 0, locale: "de-DE" });
144
+ formatMoney(19.9, "EUR"); // "€19.90"
145
+ formatPercent(0.1234); // "12.3%"
146
+ formatPercent(0.1234, 0); // "12%"
147
+ formatUtcDateTime("2026-11-16T09:05:00Z"); // "2026-11-16 09:05 UTC"
148
+ formatUtcDate(new Date()); // "2026-11-16"
149
+ ```
150
+
151
+ ## Logging
152
+
153
+ Helpers that log take an optional `logger` (anything with `error`/`warn`, defaults to `console`):
154
+ in the options object for `checkIsPro` and `subscribeToKlaviyo`, and as a trailing `{ logger }` for
155
+ the admin helpers, for example `setMetafields(admin, ns, ownerId, fields, { logger })`.
156
+
157
+ ## Versioning
158
+
159
+ Pin a tag in `package.json` and bump it deliberately. While the version is 0.x, breaking changes bump
160
+ the minor version (0.2 to 0.3), so read the [changelog](CHANGELOG.md) before upgrading.
161
+
162
+ ## License
163
+
164
+ [MIT](LICENSE)
@@ -0,0 +1,23 @@
1
+ import type { Logger } from "./logger.js";
2
+ export type AdminGraphql = {
3
+ graphql: (query: string, options?: {
4
+ variables?: Record<string, unknown>;
5
+ }) => Promise<Response>;
6
+ };
7
+ export interface MetafieldValue {
8
+ key: string;
9
+ type: "boolean" | "json" | "single_line_text_field" | (string & {});
10
+ value: string;
11
+ }
12
+ export interface MetafieldUserError {
13
+ field: string[] | null;
14
+ message: string;
15
+ }
16
+ export interface AdminOptions {
17
+ logger?: Logger;
18
+ }
19
+ export declare function getShopId(admin: AdminGraphql, _options?: AdminOptions): Promise<string>;
20
+ export declare function setMetafields(admin: AdminGraphql, namespace: string, ownerId: string, fields: MetafieldValue[], options?: AdminOptions): Promise<MetafieldUserError[]>;
21
+ export declare function deleteMetafields(admin: AdminGraphql, namespace: string, ownerId: string, keys: string[], options?: AdminOptions): Promise<MetafieldUserError[]>;
22
+ export declare function checkDiscountCode(admin: AdminGraphql, code: string, options?: AdminOptions): Promise<"not_found" | "inactive" | null>;
23
+ export declare function ensureWebPixel(admin: AdminGraphql, appUrl: string, path?: string, options?: AdminOptions): Promise<boolean>;
package/dist/admin.js ADDED
@@ -0,0 +1,137 @@
1
+ // metafieldsSet takes at most 25 metafields per call
2
+ const METAFIELDS_SET_LIMIT = 25;
3
+ export async function getShopId(admin, _options = {}) {
4
+ const res = await admin.graphql(`#graphql
5
+ query ShopId { shop { id } }`);
6
+ const json = await res.json();
7
+ if (json?.errors?.length) {
8
+ throw new Error(`Shop id query failed: ${json.errors.map((e) => e?.message ?? e).join("; ")}`);
9
+ }
10
+ const id = json?.data?.shop?.id;
11
+ if (!id)
12
+ throw new Error("Shop id query returned no shop.id");
13
+ return id;
14
+ }
15
+ function topLevelErrors(json) {
16
+ return (json?.errors ?? []).map((e) => ({ field: null, message: String(e?.message ?? e) }));
17
+ }
18
+ export async function setMetafields(admin, namespace, ownerId, fields, options = {}) {
19
+ const { logger = console } = options;
20
+ const errors = [];
21
+ for (let i = 0; i < fields.length; i += METAFIELDS_SET_LIMIT) {
22
+ const chunk = fields.slice(i, i + METAFIELDS_SET_LIMIT);
23
+ const res = await admin.graphql(`#graphql
24
+ mutation MetafieldsSet($metafields: [MetafieldsSetInput!]!) {
25
+ metafieldsSet(metafields: $metafields) {
26
+ userErrors { field message }
27
+ }
28
+ }`, { variables: { metafields: chunk.map((f) => ({ ...f, namespace, ownerId })) } });
29
+ const json = await res.json();
30
+ errors.push(...topLevelErrors(json), ...(json?.data?.metafieldsSet?.userErrors ?? []));
31
+ }
32
+ if (errors.length)
33
+ logger.error("metafieldsSet errors", errors);
34
+ return errors;
35
+ }
36
+ export async function deleteMetafields(admin, namespace, ownerId, keys, options = {}) {
37
+ const { logger = console } = options;
38
+ if (keys.length === 0)
39
+ return [];
40
+ const res = await admin.graphql(`#graphql
41
+ mutation MetafieldsDelete($metafields: [MetafieldIdentifierInput!]!) {
42
+ metafieldsDelete(metafields: $metafields) {
43
+ userErrors { field message }
44
+ }
45
+ }`, { variables: { metafields: keys.map((key) => ({ ownerId, namespace, key })) } });
46
+ const json = await res.json();
47
+ const errors = [...topLevelErrors(json), ...(json?.data?.metafieldsDelete?.userErrors ?? [])];
48
+ if (errors.length)
49
+ logger.error("metafieldsDelete errors", errors);
50
+ return errors;
51
+ }
52
+ // null = fine, or not checkable (e.g. no read_discounts)
53
+ export async function checkDiscountCode(admin, code, options = {}) {
54
+ const { logger = console } = options;
55
+ try {
56
+ const res = await admin.graphql(`#graphql
57
+ query DiscountByCode($code: String!) {
58
+ codeDiscountNodeByCode(code: $code) {
59
+ id
60
+ codeDiscount {
61
+ ... on DiscountCodeBasic { status }
62
+ ... on DiscountCodeBxgy { status }
63
+ ... on DiscountCodeFreeShipping { status }
64
+ ... on DiscountCodeApp { status }
65
+ }
66
+ }
67
+ }`, { variables: { code } });
68
+ const json = await res.json();
69
+ if (json.errors?.length)
70
+ return null;
71
+ const node = json.data?.codeDiscountNodeByCode;
72
+ if (!node)
73
+ return "not_found";
74
+ const status = node.codeDiscount?.status;
75
+ return status && status !== "ACTIVE" ? "inactive" : null;
76
+ }
77
+ catch (e) {
78
+ logger.warn("discount code check skipped", e);
79
+ return null;
80
+ }
81
+ }
82
+ // false when write_pixels isn't granted yet
83
+ export async function ensureWebPixel(admin, appUrl, path = "/api/conversion", options = {}) {
84
+ const { logger = console } = options;
85
+ if (!appUrl)
86
+ return false;
87
+ const settings = JSON.stringify({ endpoint: `${appUrl.replace(/\/$/, "")}${path}` });
88
+ let pixel = null;
89
+ try {
90
+ const existing = await admin.graphql(`#graphql
91
+ query WebPixel { webPixel { id settings } }`);
92
+ const json = await existing.json();
93
+ if (json?.data?.webPixel?.id)
94
+ pixel = json.data.webPixel;
95
+ }
96
+ catch {
97
+ // throws when there is no pixel yet
98
+ }
99
+ if (pixel) {
100
+ if (pixel.settings === settings)
101
+ return true;
102
+ try {
103
+ const res = await admin.graphql(`#graphql
104
+ mutation WebPixelUpdate($id: ID!, $webPixel: WebPixelInput!) {
105
+ webPixelUpdate(id: $id, webPixel: $webPixel) { userErrors { field message code } webPixel { id } }
106
+ }`, { variables: { id: pixel.id, webPixel: { settings } } });
107
+ const json = await res.json();
108
+ const errors = json?.data?.webPixelUpdate?.userErrors;
109
+ if (errors?.length) {
110
+ logger.error("webPixelUpdate errors", errors);
111
+ return false;
112
+ }
113
+ return true;
114
+ }
115
+ catch (e) {
116
+ logger.error("webPixelUpdate failed", e);
117
+ return false;
118
+ }
119
+ }
120
+ try {
121
+ const res = await admin.graphql(`#graphql
122
+ mutation WebPixelCreate($webPixel: WebPixelInput!) {
123
+ webPixelCreate(webPixel: $webPixel) { userErrors { field message code } webPixel { id } }
124
+ }`, { variables: { webPixel: { settings } } });
125
+ const json = await res.json();
126
+ const errors = json?.data?.webPixelCreate?.userErrors;
127
+ if (errors?.length) {
128
+ logger.error("webPixelCreate errors", errors);
129
+ return false;
130
+ }
131
+ return true;
132
+ }
133
+ catch (e) {
134
+ logger.error("webPixelCreate failed (missing write_pixels scope?)", e);
135
+ return false;
136
+ }
137
+ }
@@ -0,0 +1,8 @@
1
+ export declare const DEFAULT_LOCALE = "en-US";
2
+ export declare function formatNumber(n: number, options?: Intl.NumberFormatOptions & {
3
+ locale?: string;
4
+ }): string;
5
+ export declare function formatMoney(amount: number, currency: string | null | undefined, locale?: string): string;
6
+ export declare function formatPercent(ratio: number, digits?: number): string;
7
+ export declare function formatUtcDateTime(value: Date | string | number): string;
8
+ export declare function formatUtcDate(value: Date | string | number): string;
package/dist/format.js ADDED
@@ -0,0 +1,45 @@
1
+ // Fixed locale and UTC: the server and the browser must print the same text, or hydration fails.
2
+ export const DEFAULT_LOCALE = "en-US";
3
+ const cache = new Map();
4
+ function numberFormat(locale, options) {
5
+ const key = locale + JSON.stringify(options);
6
+ let nf = cache.get(key);
7
+ if (!nf) {
8
+ nf = new Intl.NumberFormat(locale, options);
9
+ cache.set(key, nf);
10
+ }
11
+ return nf;
12
+ }
13
+ export function formatNumber(n, options = {}) {
14
+ const { locale = DEFAULT_LOCALE, ...rest } = options;
15
+ return numberFormat(locale, rest).format(n);
16
+ }
17
+ export function formatMoney(amount, currency, locale = DEFAULT_LOCALE) {
18
+ if (!currency)
19
+ return amount.toFixed(2);
20
+ try {
21
+ return numberFormat(locale, { style: "currency", currency }).format(amount);
22
+ }
23
+ catch {
24
+ return `${amount.toFixed(2)} ${currency}`;
25
+ }
26
+ }
27
+ export function formatPercent(ratio, digits = 1) {
28
+ return numberFormat(DEFAULT_LOCALE, {
29
+ style: "percent",
30
+ minimumFractionDigits: digits,
31
+ maximumFractionDigits: digits,
32
+ }).format(ratio);
33
+ }
34
+ // Invalid dates give "" so a bad row doesn't break the page.
35
+ function utcIso(value) {
36
+ const d = value instanceof Date ? value : new Date(value);
37
+ return Number.isNaN(d.getTime()) ? "" : d.toISOString();
38
+ }
39
+ export function formatUtcDateTime(value) {
40
+ const iso = utcIso(value);
41
+ return iso && `${iso.slice(0, 16).replace("T", " ")} UTC`;
42
+ }
43
+ export function formatUtcDate(value) {
44
+ return utcIso(value).slice(0, 10);
45
+ }
@@ -0,0 +1,8 @@
1
+ export * from "./partner-api.js";
2
+ export * from "./plan.js";
3
+ export * from "./plan-cache.js";
4
+ export * from "./logger.js";
5
+ export * from "./admin.js";
6
+ export * from "./klaviyo.js";
7
+ export * from "./limits.js";
8
+ export * from "./format.js";
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ export * from "./partner-api.js";
2
+ export * from "./plan.js";
3
+ export * from "./plan-cache.js";
4
+ export * from "./logger.js";
5
+ export * from "./admin.js";
6
+ export * from "./klaviyo.js";
7
+ export * from "./limits.js";
8
+ export * from "./format.js";
@@ -0,0 +1,12 @@
1
+ import type { Logger } from "./logger.js";
2
+ export declare const KLAVIYO_REVISION = "2026-10-15";
3
+ export declare function subscribeToKlaviyo(opts: {
4
+ publicKey: string;
5
+ listId: string;
6
+ email: string;
7
+ source: string;
8
+ properties?: Record<string, string | null | undefined>;
9
+ logger?: Logger;
10
+ timeoutMs?: number;
11
+ fetch?: typeof fetch;
12
+ }): Promise<boolean>;
@@ -0,0 +1,44 @@
1
+ export const KLAVIYO_REVISION = "2026-10-15";
2
+ // Client subscriptions endpoint, works with the public key only.
3
+ export async function subscribeToKlaviyo(opts) {
4
+ const { publicKey, listId, email, source, properties, logger = console, timeoutMs = 8000 } = opts;
5
+ const doFetch = opts.fetch ?? fetch;
6
+ try {
7
+ const res = await doFetch(`https://a.klaviyo.com/client/subscriptions/?company_id=${encodeURIComponent(publicKey)}`, {
8
+ method: "POST",
9
+ headers: {
10
+ "Content-Type": "application/vnd.api+json",
11
+ accept: "application/vnd.api+json",
12
+ revision: KLAVIYO_REVISION,
13
+ },
14
+ body: JSON.stringify({
15
+ data: {
16
+ type: "subscription",
17
+ attributes: {
18
+ custom_source: source,
19
+ profile: {
20
+ data: {
21
+ type: "profile",
22
+ attributes: {
23
+ email,
24
+ properties: properties ?? {},
25
+ subscriptions: { email: { marketing: { consent: "SUBSCRIBED" } } },
26
+ },
27
+ },
28
+ },
29
+ },
30
+ relationships: { list: { data: { type: "list", id: listId } } },
31
+ },
32
+ }),
33
+ signal: AbortSignal.timeout(timeoutMs),
34
+ });
35
+ if (!res.ok) {
36
+ logger.error("Klaviyo subscribe failed", res.status, await res.text().catch(() => ""));
37
+ }
38
+ return res.ok;
39
+ }
40
+ catch (e) {
41
+ logger.error("Klaviyo subscribe failed", e);
42
+ return false;
43
+ }
44
+ }
@@ -0,0 +1,11 @@
1
+ export declare const FREE_PRODUCT_LIMIT = 5;
2
+ export declare const isLiveOnPlan: (index: number, isPro: boolean, limit?: number) => boolean;
3
+ export interface PlanLimitOptions<T> {
4
+ isPro: boolean;
5
+ limit?: number;
6
+ createdAt: (item: T) => Date | string | number;
7
+ }
8
+ export declare function splitByPlanLimit<T>(items: readonly T[], options: PlanLimitOptions<T>): {
9
+ live: T[];
10
+ offline: T[];
11
+ };
package/dist/limits.js ADDED
@@ -0,0 +1,23 @@
1
+ // Free plan: features on up to this many products. Pro: unlimited.
2
+ export const FREE_PRODUCT_LIMIT = 5;
3
+ // `index` is the item's position when sorted oldest first.
4
+ export const isLiveOnPlan = (index, isPro, limit = FREE_PRODUCT_LIMIT) => isPro || index < limit;
5
+ // Over the Free limit items stay saved but go offline; the oldest ones stay live.
6
+ export function splitByPlanLimit(items, options) {
7
+ const { isPro, limit = FREE_PRODUCT_LIMIT, createdAt } = options;
8
+ if (isPro)
9
+ return { live: [...items], offline: [] };
10
+ // invalid dates count as newest
11
+ const time = items.map((item) => {
12
+ const t = new Date(createdAt(item)).getTime();
13
+ return Number.isNaN(t) ? Infinity : t;
14
+ });
15
+ // sort is stable, so ties keep their input order
16
+ const order = items.map((_, i) => i).sort((a, b) => (time[a] === time[b] ? 0 : time[a] - time[b]));
17
+ const rank = new Array(items.length);
18
+ order.forEach((i, r) => (rank[i] = r));
19
+ const live = [];
20
+ const offline = [];
21
+ items.forEach((item, i) => (isLiveOnPlan(rank[i], false, limit) ? live : offline).push(item));
22
+ return { live, offline };
23
+ }
@@ -0,0 +1 @@
1
+ export type Logger = Pick<Console, "error" | "warn">;
package/dist/logger.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,15 @@
1
+ export declare const PARTNER_API_VERSION = "2026-10";
2
+ export interface PartnerApiConfig {
3
+ orgId: string;
4
+ accessToken: string;
5
+ appGid: string;
6
+ apiVersion?: string;
7
+ timeoutMs?: number;
8
+ fetch?: typeof fetch;
9
+ }
10
+ export interface SubscriptionItem {
11
+ handle: string | null;
12
+ description: string | null;
13
+ }
14
+ export declare function partnerApiConfigFromEnv(env?: Record<string, string | undefined>): PartnerApiConfig | null;
15
+ export declare function fetchActiveSubscription(config: PartnerApiConfig, shopGid: string): Promise<SubscriptionItem[] | null>;
@@ -0,0 +1,32 @@
1
+ export const PARTNER_API_VERSION = "2026-10";
2
+ export function partnerApiConfigFromEnv(env = process.env) {
3
+ const orgId = env.SHOPIFY_PARTNER_ORG_ID;
4
+ const accessToken = env.SHOPIFY_PARTNER_API_ACCESS_TOKEN;
5
+ const appGid = env.SHOPIFY_APP_GID;
6
+ return orgId && accessToken && appGid ? { orgId, accessToken, appGid } : null;
7
+ }
8
+ // null = no subscription. Throws on API errors.
9
+ export async function fetchActiveSubscription(config, shopGid) {
10
+ const version = config.apiVersion ?? PARTNER_API_VERSION;
11
+ const doFetch = config.fetch ?? fetch;
12
+ const res = await doFetch(`https://partners.shopify.com/${config.orgId}/api/${version}/graphql.json`, {
13
+ method: "POST",
14
+ headers: {
15
+ "Content-Type": "application/json",
16
+ "X-Shopify-Access-Token": config.accessToken,
17
+ },
18
+ body: JSON.stringify({
19
+ query: `query ActiveSubscription($appId: ID!, $shopId: ID!) {
20
+ activeSubscription(appId: $appId, shopId: $shopId) { items { handle description } }
21
+ }`,
22
+ variables: { appId: config.appGid, shopId: shopGid },
23
+ }),
24
+ signal: AbortSignal.timeout(config.timeoutMs ?? 8000),
25
+ });
26
+ const json = await res.json().catch(() => null);
27
+ if (!res.ok || !json || json.errors) {
28
+ throw new Error(`activeSubscription failed: ${res.status} ${JSON.stringify(json?.errors ?? null)}`);
29
+ }
30
+ const sub = json.data?.activeSubscription;
31
+ return sub ? (sub.items ?? []) : null;
32
+ }
@@ -0,0 +1,11 @@
1
+ export interface PlanCache {
2
+ get(shopGid: string): boolean | undefined;
3
+ set(shopGid: string, isPro: boolean): void;
4
+ delete(shopGid: string): void;
5
+ }
6
+ export interface MemoryPlanCacheOptions {
7
+ ttlMs?: number;
8
+ max?: number;
9
+ now?: () => number;
10
+ }
11
+ export declare function createMemoryPlanCache({ ttlMs, max, now }?: MemoryPlanCacheOptions): PlanCache;
@@ -0,0 +1,25 @@
1
+ export function createMemoryPlanCache({ ttlMs = 5 * 60_000, max = 1000, now = Date.now } = {}) {
2
+ const entries = new Map();
3
+ return {
4
+ get(shopGid) {
5
+ const entry = entries.get(shopGid);
6
+ if (!entry)
7
+ return undefined;
8
+ if (entry.expires <= now()) {
9
+ entries.delete(shopGid);
10
+ return undefined;
11
+ }
12
+ return entry.isPro;
13
+ },
14
+ set(shopGid, isPro) {
15
+ // re-insert so Map order stays oldest-first
16
+ entries.delete(shopGid);
17
+ entries.set(shopGid, { isPro, expires: now() + ttlMs });
18
+ while (entries.size > max)
19
+ entries.delete(entries.keys().next().value);
20
+ },
21
+ delete(shopGid) {
22
+ entries.delete(shopGid);
23
+ },
24
+ };
25
+ }
package/dist/plan.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ import { type PartnerApiConfig, type SubscriptionItem } from "./partner-api.js";
2
+ import type { PlanCache } from "./plan-cache.js";
3
+ export declare const isProPlanName: (name: string | undefined | null) => boolean;
4
+ export declare function isProSubscriptionItem(item: SubscriptionItem, proPlans?: readonly string[]): boolean;
5
+ export interface BillingCheck {
6
+ check: () => Promise<any>;
7
+ }
8
+ export interface CheckIsProOptions {
9
+ billing: BillingCheck;
10
+ shopGid: string;
11
+ lastKnown: boolean;
12
+ partnerApi?: PartnerApiConfig | null;
13
+ legacyBilling?: boolean;
14
+ proPlans?: readonly string[];
15
+ cache?: PlanCache;
16
+ refresh?: boolean;
17
+ env?: Record<string, string | undefined>;
18
+ logger?: Pick<Console, "error">;
19
+ }
20
+ export declare function checkIsPro(options: CheckIsProOptions): Promise<boolean>;
package/dist/plan.js ADDED
@@ -0,0 +1,55 @@
1
+ import { fetchActiveSubscription, partnerApiConfigFromEnv } from "./partner-api.js";
2
+ // Free plan also has an active $0 subscription, and paid plans are $0 on dev stores.
3
+ export const isProPlanName = (name) => Boolean(name) && !/free/i.test(name);
4
+ const matchesPlan = (name, plans) => Boolean(name) && plans.some((p) => p.toLowerCase() === name.toLowerCase());
5
+ export function isProSubscriptionItem(item, proPlans) {
6
+ const name = item.handle ?? item.description;
7
+ return proPlans ? matchesPlan(name, proPlans) : isProPlanName(name);
8
+ }
9
+ export async function checkIsPro(options) {
10
+ const { shopGid, lastKnown, cache, refresh = false, env = process.env } = options;
11
+ const forced = env.NODE_ENV !== "production" ? env.DEV_FORCE_PLAN : undefined;
12
+ if (forced === "pro" || forced === "free")
13
+ return forced === "pro";
14
+ if (cache && !refresh) {
15
+ const cached = cache.get(shopGid);
16
+ if (cached !== undefined)
17
+ return cached;
18
+ }
19
+ const isPro = await lookupPlan(options, env);
20
+ // undefined = a lookup failed; don't downgrade and don't cache
21
+ if (isPro === undefined)
22
+ return lastKnown;
23
+ cache?.set(shopGid, isPro);
24
+ return isPro;
25
+ }
26
+ async function lookupPlan(options, env) {
27
+ const { billing, shopGid, legacyBilling = false, proPlans, logger = console } = options;
28
+ const partnerApi = options.partnerApi === undefined ? partnerApiConfigFromEnv(env) : options.partnerApi;
29
+ let failed = false;
30
+ if (partnerApi) {
31
+ try {
32
+ const items = await fetchActiveSubscription(partnerApi, shopGid);
33
+ if (items?.some((i) => isProSubscriptionItem(i, proPlans)))
34
+ return true;
35
+ }
36
+ catch (e) {
37
+ logger.error("Partner API plan check failed", e);
38
+ failed = true;
39
+ }
40
+ if (!legacyBilling)
41
+ return failed ? undefined : false;
42
+ }
43
+ try {
44
+ const result = await billing.check();
45
+ const subs = result?.appSubscriptions ?? [];
46
+ const isProName = (name) => (proPlans ? matchesPlan(name, proPlans) : isProPlanName(name));
47
+ if (subs.some((s) => (!s.status || s.status === "ACTIVE") && isProName(s.name)))
48
+ return true;
49
+ }
50
+ catch (e) {
51
+ logger.error("billing.check failed", e);
52
+ failed = true;
53
+ }
54
+ return failed ? undefined : false;
55
+ }
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
- {
2
- "name": "@mufucloud/shopify-app-kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@mufucloud/shopify-app-kit",
3
+ "version": "0.2.0",
4
+ "description": "Shared server helpers for mufucloud Shopify apps: plan checks with Shopify App Pricing (Partner API + Billing API), shop metafields, revenue web pixel, discount lookup and Klaviyo signup.",
5
+ "license": "MIT",
6
+ "author": "mufucloud",
7
+ "type": "module",
8
+ "repository": { "type": "git", "url": "git+https://github.com/MUFU-Cloud/shopify-app-kit.git" },
9
+ "homepage": "https://github.com/MUFU-Cloud/shopify-app-kit#readme",
10
+ "bugs": { "url": "https://github.com/MUFU-Cloud/shopify-app-kit/issues" },
11
+ "keywords": ["shopify", "shopify-app", "app-pricing", "partner-api", "billing", "metafields", "web-pixel", "klaviyo"],
12
+ "exports": {
13
+ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
14
+ "./package.json": "./package.json"
15
+ },
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "files": ["dist", "README.md", "LICENSE"],
19
+ "sideEffects": false,
20
+ "engines": { "node": ">=20.19" },
21
+ "publishConfig": { "access": "public" },
22
+ "scripts": {
23
+ "build": "tsc -p tsconfig.json",
24
+ "prepare": "npm run build",
25
+ "typecheck": "tsc -p tsconfig.json --noEmit",
26
+ "test": "npm run build && node --test"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^22.18.8",
30
+ "typescript": "^5.9.3"
31
+ }
32
+ }