@occluze/tether 0.6.7 → 0.6.8
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/README.md +3 -3
- package/dist/esm/astro.js +2 -2
- package/dist/esm/chunks/account-C3NP6HFB.js +1 -0
- package/dist/esm/chunks/account-pages-WLK374FO.js +1 -0
- package/dist/esm/chunks/analytics-G3SAWMNL.js +1 -0
- package/dist/esm/chunks/chunk-27PJJZGC.js +1 -0
- package/dist/esm/chunks/chunk-2FSXS55U.js +1 -0
- package/dist/esm/chunks/chunk-FCSWQDVV.js +1 -0
- package/dist/esm/chunks/chunk-FOMSMIAM.js +1 -0
- package/dist/esm/chunks/chunk-GZJTCLLW.js +1 -0
- package/dist/esm/chunks/chunk-HEQILZVR.js +1 -0
- package/dist/esm/chunks/chunk-JOOEXYF3.js +4 -0
- package/dist/esm/chunks/chunk-MPTQYLSM.js +1 -0
- package/dist/esm/chunks/chunk-NEHZ37TU.js +3 -0
- package/dist/esm/chunks/chunk-V74KGEJF.js +1 -0
- package/dist/esm/chunks/chunk-VT4CDUJJ.js +1 -0
- package/dist/esm/chunks/chunk-YJLWX2HK.js +1 -0
- package/dist/esm/chunks/diagnose-6VVGZNTY.js +14 -0
- package/dist/esm/chunks/extras-GJVRDFM3.js +1 -0
- package/dist/esm/chunks/markets-ui-UNB4PTA7.js +1 -0
- package/dist/esm/chunks/search-OU75RNQL.js +1 -0
- package/dist/esm/index.js +1 -1
- package/dist/esm/server.js +2 -1
- package/dist/presets/barba.esm.js +56 -36
- package/dist/tether.account-pages.js +773 -442
- package/dist/tether.account-pages.min.js +1 -1
- package/dist/tether.account.js +648 -318
- package/dist/tether.account.min.js +1 -1
- package/dist/tether.analytics.js +318 -191
- package/dist/tether.analytics.min.js +1 -1
- package/dist/tether.diagnose.js +331 -242
- package/dist/tether.diagnose.min.js +2 -2
- package/dist/tether.extras.js +78 -33
- package/dist/tether.extras.min.js +1 -1
- package/dist/tether.js +3176 -2015
- package/dist/tether.markets.js +231 -126
- package/dist/tether.markets.min.js +1 -1
- package/dist/tether.min.js +0 -0
- package/dist/tether.min.js.map +4 -4
- package/dist/tether.search.js +221 -126
- package/dist/tether.search.min.js +1 -1
- package/package.json +23 -4
- package/src/account/addresses-view.js +92 -0
- package/src/account/browser-session.js +359 -0
- package/src/account/markup.js +48 -0
- package/src/account/operations.js +180 -0
- package/src/account/order-lines.js +96 -0
- package/src/account/order-list.js +91 -0
- package/src/account/order-page.js +192 -0
- package/src/account/page-events.js +288 -0
- package/src/account/server-client.js +172 -0
- package/src/account/shared.js +111 -0
- package/src/account/shopify-auth.js +150 -0
- package/src/account/subscriptions-view.js +158 -0
- package/src/account-api.js +118 -0
- package/src/account-links.js +35 -0
- package/src/account-pages.js +69 -298
- package/src/account.js +280 -323
- package/src/amounts.js +36 -0
- package/src/analytics-shopify.js +241 -0
- package/src/analytics.js +304 -184
- package/src/api-version.js +75 -25
- package/src/astro.js +233 -68
- package/src/cart/checkout.js +97 -0
- package/src/cart/drawer.js +138 -0
- package/src/cart/mutations.js +234 -0
- package/src/cart/render.js +294 -0
- package/src/cart/store.js +326 -0
- package/src/cart.js +320 -488
- package/src/client.js +214 -78
- package/src/collection.js +126 -57
- package/src/config.js +323 -59
- package/src/controls/cart-controls.js +155 -0
- package/src/controls/discount.js +96 -0
- package/src/controls/extras.js +63 -0
- package/src/controls/navigation.js +83 -0
- package/src/diagnose-markup.js +333 -0
- package/src/diagnose.js +251 -202
- package/src/dom.js +219 -220
- package/src/extras.js +119 -37
- package/src/fragments.js +115 -22
- package/src/images.js +104 -0
- package/src/index.js +245 -287
- package/src/initial.js +78 -66
- package/src/lazy-iife.js +92 -22
- package/src/lazy.js +25 -4
- package/src/loader.js +263 -124
- package/src/market-codes.js +35 -0
- package/src/markets-ui.js +169 -55
- package/src/markets.js +286 -85
- package/src/markup.js +64 -0
- package/src/mounting.js +214 -91
- package/src/page-market.js +116 -0
- package/src/parts/account-pages.js +4 -1
- package/src/parts/account.js +4 -1
- package/src/parts/analytics.js +4 -1
- package/src/parts/diagnose.js +4 -1
- package/src/parts/extras.js +4 -1
- package/src/parts/markets.js +4 -1
- package/src/parts/search.js +4 -1
- package/src/presets/barba.js +120 -30
- package/src/product-events.js +130 -0
- package/src/product-render.js +257 -0
- package/src/product-state.js +318 -0
- package/src/product.js +233 -459
- package/src/repeaters.js +173 -0
- package/src/search.js +277 -107
- package/src/selling-plans.js +107 -47
- package/src/server.js +168 -205
- package/src/shopify-values.js +89 -0
- package/src/status.js +99 -39
- package/src/store-html.js +0 -0
- package/src/storefront/catalog.js +199 -0
- package/src/storefront/json-ld.js +167 -0
- package/src/variant-render.js +165 -0
- package/types/astro.d.ts +13 -2
- package/types/index.d.ts +178 -27
- package/types/server.d.ts +89 -17
- package/dist/esm/chunks/account-Q6E2TFEV.js +0 -1
- package/dist/esm/chunks/account-pages-UZXR4R5F.js +0 -1
- package/dist/esm/chunks/analytics-IJBKATUP.js +0 -1
- package/dist/esm/chunks/chunk-4QJKLPYR.js +0 -1
- package/dist/esm/chunks/chunk-64TUD3QR.js +0 -1
- package/dist/esm/chunks/chunk-AJLPU2JC.js +0 -4
- package/dist/esm/chunks/chunk-FIOZPPC5.js +0 -1
- package/dist/esm/chunks/chunk-K2YEQAIH.js +0 -1
- package/dist/esm/chunks/chunk-KIDH76B7.js +0 -1
- package/dist/esm/chunks/chunk-PAYT5ZD7.js +0 -1
- package/dist/esm/chunks/chunk-RREHGH4A.js +0 -1
- package/dist/esm/chunks/chunk-SSJT43CJ.js +0 -1
- package/dist/esm/chunks/chunk-VC46IEJQ.js +0 -1
- package/dist/esm/chunks/diagnose-3WVAWNTX.js +0 -14
- package/dist/esm/chunks/extras-7I7WJX35.js +0 -1
- package/dist/esm/chunks/markets-ui-545XLFTE.js +0 -1
- package/dist/esm/chunks/search-NILMGYXG.js +0 -1
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server mode (`account.server`): the site's Worker holds the Shopify tokens, and this browser only a session cookie
|
|
3
|
+
* its scripts can't read. This module is the browser's side of the Worker's account routes.
|
|
4
|
+
*/
|
|
5
|
+
import { cfg } from '../config.js';
|
|
6
|
+
import { TetherError } from '../client.js';
|
|
7
|
+
import { Cart } from '../cart.js';
|
|
8
|
+
import { emit } from '../dom.js';
|
|
9
|
+
import {
|
|
10
|
+
isRecord,
|
|
11
|
+
loginCountry,
|
|
12
|
+
loginLanguage,
|
|
13
|
+
navigate,
|
|
14
|
+
readJsonObjectOrEmpty,
|
|
15
|
+
setLoginHint,
|
|
16
|
+
textOrNull,
|
|
17
|
+
} from './shared.js';
|
|
18
|
+
/** @import { UserError } from '../client.js' */
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @typedef {{ kind: 'answer', data: Record<string, unknown> } | { kind: 'logged-out' }} ServerAnswer The Worker's
|
|
22
|
+
* answer, or a 401: the session cookie is missing, has expired, or Shopify ended the login.
|
|
23
|
+
*/
|
|
24
|
+
/**
|
|
25
|
+
* @typedef {object} ServerCustomer The profile the Worker's `/me` sends.
|
|
26
|
+
* @property {string | null} firstName
|
|
27
|
+
* @property {string | null} lastName
|
|
28
|
+
* @property {string | null} displayName
|
|
29
|
+
* @property {string | null} email
|
|
30
|
+
* @property {string[] | null} address The default address, one line per entry.
|
|
31
|
+
*/
|
|
32
|
+
/** @typedef {{ loggedIn: true, customer: ServerCustomer } | { loggedIn: false }} ServerLogin */
|
|
33
|
+
/** @typedef {{ method?: 'GET' | 'POST', body?: Record<string, unknown> }} ServerRequest */
|
|
34
|
+
|
|
35
|
+
/** @type {ServerLogin | null} The Worker's `/me` answer, until a change of the customer's data. */
|
|
36
|
+
let known = null;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @returns {string} The Worker's account routes, without a trailing slash; `''` in browser mode. `account.server` is a
|
|
40
|
+
* full URL or a path on this site.
|
|
41
|
+
*/
|
|
42
|
+
export function serverBase() {
|
|
43
|
+
const server = cfg.account?.server;
|
|
44
|
+
if (!server) return '';
|
|
45
|
+
return new URL(server, window.location.href).href.replace(/\/$/, '');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* One request to the Worker, with the session cookie. A POST carries the header the Worker requires against
|
|
50
|
+
* cross-site forms.
|
|
51
|
+
*
|
|
52
|
+
* @param {string} path
|
|
53
|
+
* @param {ServerRequest} [request]
|
|
54
|
+
* @returns {Promise<ServerAnswer>}
|
|
55
|
+
* @throws {TetherError} `HTTP_<status>` for any failure but a 401, with the Worker's `userErrors`.
|
|
56
|
+
*/
|
|
57
|
+
export async function serverFetch(path, { method = 'GET', body } = {}) {
|
|
58
|
+
/** @type {RequestInit} */
|
|
59
|
+
const init = { method, credentials: 'include' };
|
|
60
|
+
if (method === 'POST') init.headers = { 'Content-Type': 'application/json', 'X-Tether-Account': '1' };
|
|
61
|
+
if (body) init.body = JSON.stringify(body);
|
|
62
|
+
const response = await fetch(`${serverBase()}${path}`, init);
|
|
63
|
+
if (response.status === 401) return { kind: 'logged-out' };
|
|
64
|
+
const data = await readJsonObjectOrEmpty(response);
|
|
65
|
+
if (!response.ok) {
|
|
66
|
+
const reason = textOrNull(data['error']) ?? String(response.status);
|
|
67
|
+
/** @type {TetherError['userErrors']} */
|
|
68
|
+
const userErrors = Array.isArray(data['userErrors'])
|
|
69
|
+
? // The Worker sends Shopify's own `userErrors` list unchanged.
|
|
70
|
+
/** @type {UserError[]} */ (data['userErrors'])
|
|
71
|
+
: undefined;
|
|
72
|
+
throw new TetherError(`Customer accounts: ${reason}`, {
|
|
73
|
+
status: response.status,
|
|
74
|
+
...(userErrors && { userErrors }),
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
return { kind: 'answer', data };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* @param {unknown} value
|
|
82
|
+
* @returns {ServerCustomer}
|
|
83
|
+
*/
|
|
84
|
+
function toServerCustomer(value) {
|
|
85
|
+
const customer = isRecord(value) ? value : {};
|
|
86
|
+
const address = customer['address'];
|
|
87
|
+
return {
|
|
88
|
+
firstName: textOrNull(customer['firstName']),
|
|
89
|
+
lastName: textOrNull(customer['lastName']),
|
|
90
|
+
displayName: textOrNull(customer['displayName']),
|
|
91
|
+
email: textOrNull(customer['email']),
|
|
92
|
+
address: Array.isArray(address) ? address.filter((line) => typeof line === 'string') : null,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Who is logged in, asked once and then kept; the "may be logged in" hint follows the answer.
|
|
98
|
+
*
|
|
99
|
+
* @returns {Promise<ServerLogin>}
|
|
100
|
+
* @throws {TetherError} When the Worker can't be reached or fails: that says nothing about the login.
|
|
101
|
+
*/
|
|
102
|
+
export async function serverLogin() {
|
|
103
|
+
if (!known) {
|
|
104
|
+
const answer = await serverFetch('/me');
|
|
105
|
+
known =
|
|
106
|
+
answer.kind === 'answer' && answer.data['loggedIn'] === true
|
|
107
|
+
? { loggedIn: true, customer: toServerCustomer(answer.data['customer']) }
|
|
108
|
+
: { loggedIn: false };
|
|
109
|
+
}
|
|
110
|
+
setLoginHint(known.loggedIn);
|
|
111
|
+
return known;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** @returns {boolean} True when the Worker last said a customer is logged in. */
|
|
115
|
+
export const isServerLoggedIn = () => known?.loggedIn === true;
|
|
116
|
+
|
|
117
|
+
/** Asks the Worker again on the next `serverLogin()`, after a change of the customer's data. */
|
|
118
|
+
export function forgetServerLogin() {
|
|
119
|
+
known = null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* To the Worker's login, which comes back to `returnTo`. The cart is linked later, at checkout, through the Worker's
|
|
124
|
+
* protected `POST /cart`.
|
|
125
|
+
*
|
|
126
|
+
* @param {{ returnTo: string, locale?: string | undefined }} options
|
|
127
|
+
*/
|
|
128
|
+
export function serverLoginRedirect({ returnTo, locale }) {
|
|
129
|
+
const url = new URL(`${serverBase()}/login`);
|
|
130
|
+
url.searchParams.set('returnTo', returnTo);
|
|
131
|
+
const language = loginLanguage(locale);
|
|
132
|
+
if (language) url.searchParams.set('locale', language);
|
|
133
|
+
const country = loginCountry();
|
|
134
|
+
if (country) url.searchParams.set('country', country);
|
|
135
|
+
navigate(url.toString());
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* The logged-in customer's checkout, for `Cart.beforeCheckout`: the Worker links the cart to the customer and answers
|
|
140
|
+
* with its checkout URL.
|
|
141
|
+
*
|
|
142
|
+
* @returns {Promise<string | null>} `null` when nobody is logged in or the Worker linked no cart, so the cart's own
|
|
143
|
+
* checkout URL is used.
|
|
144
|
+
* @throws {TetherError} When the Worker fails; the cart reports it and checks out without the login.
|
|
145
|
+
*/
|
|
146
|
+
export async function serverCheckoutUrl() {
|
|
147
|
+
const cartId = Cart.id();
|
|
148
|
+
if (!(await serverLogin()).loggedIn || !cartId) return null;
|
|
149
|
+
const answer = await serverFetch('/cart', { method: 'POST', body: { cartId } });
|
|
150
|
+
if (answer.kind === 'logged-out') return null;
|
|
151
|
+
const url = textOrNull(answer.data['checkoutUrl']);
|
|
152
|
+
if (!url) return null;
|
|
153
|
+
return `${url}${url.includes('?') ? '&' : '?'}logged_in=true`;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Ends the session at the Worker, which also unlinks the cart, then goes on to Shopify's logout when the Worker says
|
|
158
|
+
* where. Sends `tether:account-logout`.
|
|
159
|
+
*
|
|
160
|
+
* @param {string} returnTo
|
|
161
|
+
* @returns {Promise<'redirected' | 'stayed'>}
|
|
162
|
+
*/
|
|
163
|
+
export async function serverLogout(returnTo) {
|
|
164
|
+
const answer = await serverFetch('/logout', { method: 'POST', body: { returnTo, cartId: Cart.id() } });
|
|
165
|
+
known = null;
|
|
166
|
+
setLoginHint(false);
|
|
167
|
+
emit('account-logout', {});
|
|
168
|
+
const logoutUrl = answer.kind === 'answer' ? textOrNull(answer.data['logoutUrl']) : null;
|
|
169
|
+
if (!logoutUrl) return 'stayed';
|
|
170
|
+
navigate(logoutUrl);
|
|
171
|
+
return 'redirected';
|
|
172
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What both account modes share: the storage keys, the redirect to Shopify's pages, the login language, and reading
|
|
3
|
+
* the JSON that Shopify and the Worker answer with. Storage throws in private mode and where the visitor blocks site
|
|
4
|
+
* data; a login then lasts as long as the page.
|
|
5
|
+
*/
|
|
6
|
+
import { cfg } from '../config.js';
|
|
7
|
+
|
|
8
|
+
/** @typedef {'session' | 'local'} StorageArea */
|
|
9
|
+
|
|
10
|
+
/** @returns {string} The browser-mode session's key. */
|
|
11
|
+
export const sessionKey = () => `${cfg.prefix}:account:${cfg.domain}`;
|
|
12
|
+
|
|
13
|
+
/** @returns {string} The key of the login in progress (browser mode), between leaving for Shopify and coming back. */
|
|
14
|
+
export const pendingLoginKey = () => `${cfg.prefix}:account-login:${cfg.domain}`;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Server mode's "may be logged in" mark: it makes the core load this part on the next page, and holds no secret.
|
|
18
|
+
*
|
|
19
|
+
* @returns {string}
|
|
20
|
+
*/
|
|
21
|
+
const hintKey = () => `${cfg.prefix}:account-hint:${cfg.domain}`;
|
|
22
|
+
|
|
23
|
+
/** @returns {StorageArea} Where the browser-mode session lives: `localStorage` with `account.remember`. */
|
|
24
|
+
export const sessionArea = () => (cfg.account?.remember ? 'local' : 'session');
|
|
25
|
+
|
|
26
|
+
/** @param {StorageArea} area */
|
|
27
|
+
const storageOf = (area) => (area === 'local' ? window.localStorage : window.sessionStorage);
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @param {StorageArea} area
|
|
31
|
+
* @param {string} key
|
|
32
|
+
* @returns {unknown} The stored JSON value; `null` without one, for text that isn't JSON, or with storage blocked.
|
|
33
|
+
*/
|
|
34
|
+
export function readJsonIfAllowed(area, key) {
|
|
35
|
+
try {
|
|
36
|
+
return JSON.parse(storageOf(area).getItem(key) ?? 'null');
|
|
37
|
+
} catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Keeps `value` as JSON; without storage nothing is kept (see the file's comment).
|
|
44
|
+
*
|
|
45
|
+
* @param {StorageArea} area
|
|
46
|
+
* @param {string} key
|
|
47
|
+
* @param {unknown} value `null` removes the key.
|
|
48
|
+
*/
|
|
49
|
+
export function writeJsonIfAllowed(area, key, value) {
|
|
50
|
+
try {
|
|
51
|
+
if (value === null) storageOf(area).removeItem(key);
|
|
52
|
+
else storageOf(area).setItem(key, JSON.stringify(value));
|
|
53
|
+
} catch {
|
|
54
|
+
// Private mode or blocked storage: see the file's comment.
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** @param {boolean} loggedIn */
|
|
59
|
+
export function setLoginHint(loggedIn) {
|
|
60
|
+
writeJsonIfAllowed('local', hintKey(), loggedIn ? 1 : null);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* @param {unknown} value
|
|
65
|
+
* @returns {value is Record<string, unknown>}
|
|
66
|
+
*/
|
|
67
|
+
export const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* @param {unknown} value
|
|
71
|
+
* @returns {string | null}
|
|
72
|
+
*/
|
|
73
|
+
export const textOrNull = (value) => (typeof value === 'string' ? value : null);
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* An error page that isn't JSON reads as an empty answer: the response's status then says what went wrong.
|
|
77
|
+
*
|
|
78
|
+
* @param {Response} response
|
|
79
|
+
* @returns {Promise<Record<string, unknown>>}
|
|
80
|
+
*/
|
|
81
|
+
export async function readJsonObjectOrEmpty(response) {
|
|
82
|
+
/** @type {unknown} */
|
|
83
|
+
let json;
|
|
84
|
+
try {
|
|
85
|
+
json = await response.json();
|
|
86
|
+
} catch {
|
|
87
|
+
return {};
|
|
88
|
+
}
|
|
89
|
+
return isRecord(json) ? json : {};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Goes to one of Shopify's (or the Worker's) pages, through `account.navigate` when the site replaces the redirect.
|
|
94
|
+
*
|
|
95
|
+
* @param {string} url
|
|
96
|
+
*/
|
|
97
|
+
export function navigate(url) {
|
|
98
|
+
const replacement = cfg.account?.navigate;
|
|
99
|
+
if (replacement) replacement(url);
|
|
100
|
+
else window.location.assign(url);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* @param {string | undefined} locale The caller's choice.
|
|
105
|
+
* @returns {string} The language of Shopify's login page: the caller's, `account.locale`, else the site's; `''` for
|
|
106
|
+
* Shopify's default.
|
|
107
|
+
*/
|
|
108
|
+
export const loginLanguage = (locale) => locale || cfg.account?.locale || (cfg.locale || '').split('-')[0] || '';
|
|
109
|
+
|
|
110
|
+
/** @returns {string} The market's country for Shopify's login page, `''` without one. */
|
|
111
|
+
export const loginCountry = () => (cfg.country ? cfg.country.toUpperCase() : '');
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shopify's side of the browser-mode login: the OAuth and Customer Account API endpoints, found through the shop's
|
|
3
|
+
* `.well-known` documents (a shop with its own accounts domain has other ones), the token endpoint, and the check of
|
|
4
|
+
* the id token it answers with.
|
|
5
|
+
*/
|
|
6
|
+
import { cfg } from '../config.js';
|
|
7
|
+
import { TetherError } from '../client.js';
|
|
8
|
+
import { fromBase64Url } from '../../server/src/shared/base64url.js';
|
|
9
|
+
import { isRecord, readJsonObjectOrEmpty, textOrNull } from './shared.js';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @typedef {object} Endpoints
|
|
13
|
+
* @property {string} issuer The id token's `iss`.
|
|
14
|
+
* @property {string} authorizationEndpoint
|
|
15
|
+
* @property {string} tokenEndpoint
|
|
16
|
+
* @property {string} endSessionEndpoint
|
|
17
|
+
* @property {string} graphql The Customer Account API.
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* @typedef {object} TokenAnswer
|
|
21
|
+
* @property {string} access
|
|
22
|
+
* @property {string | null} refresh Left out of some refresh answers.
|
|
23
|
+
* @property {string | null} idToken Left out of refresh answers.
|
|
24
|
+
* @property {number} expiresInSeconds
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
/** Shopify's access tokens last an hour; an answer without `expires_in` is taken to say so. */
|
|
28
|
+
const DEFAULT_TOKEN_SECONDS = 3600;
|
|
29
|
+
|
|
30
|
+
/** @type {Endpoints | null} */
|
|
31
|
+
let endpoints = null;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @param {string} document `openid-configuration` or `customer-account-api`.
|
|
35
|
+
* @returns {Promise<Record<string, unknown>>}
|
|
36
|
+
*/
|
|
37
|
+
async function wellKnown(document) {
|
|
38
|
+
const shop = cfg.account?.shopDomain || cfg.domain;
|
|
39
|
+
const response = await fetch(`https://${shop}/.well-known/${document}`);
|
|
40
|
+
if (!response.ok) {
|
|
41
|
+
throw new TetherError(`Customer accounts: ${document} answered ${response.status}`, { status: response.status });
|
|
42
|
+
}
|
|
43
|
+
const json = /** @type {unknown} */ (await response.json());
|
|
44
|
+
return isRecord(json) ? json : {};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* @param {Record<string, unknown>} json
|
|
49
|
+
* @param {string} name
|
|
50
|
+
* @returns {string}
|
|
51
|
+
* @throws {TetherError} When Shopify's document lacks the endpoint.
|
|
52
|
+
*/
|
|
53
|
+
function endpointIn(json, name) {
|
|
54
|
+
const url = textOrNull(json[name]);
|
|
55
|
+
if (!url) throw new TetherError(`Customer accounts: Shopify named no ${name}`);
|
|
56
|
+
return url;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @returns {Promise<Endpoints>} The shop's endpoints, asked once per page.
|
|
61
|
+
* @throws {TetherError} When Shopify's documents can't be read.
|
|
62
|
+
*/
|
|
63
|
+
export async function discover() {
|
|
64
|
+
if (endpoints) return endpoints;
|
|
65
|
+
const [openid, api] = await Promise.all([wellKnown('openid-configuration'), wellKnown('customer-account-api')]);
|
|
66
|
+
endpoints = {
|
|
67
|
+
issuer: endpointIn(openid, 'issuer'),
|
|
68
|
+
authorizationEndpoint: endpointIn(openid, 'authorization_endpoint'),
|
|
69
|
+
tokenEndpoint: endpointIn(openid, 'token_endpoint'),
|
|
70
|
+
endSessionEndpoint: endpointIn(openid, 'end_session_endpoint'),
|
|
71
|
+
graphql: endpointIn(api, 'graphql_api'),
|
|
72
|
+
};
|
|
73
|
+
return endpoints;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* A token request, as a "simple" request (a form body, no custom header) so the browser sends it without a CORS
|
|
78
|
+
* preflight. `account.tokenUrl` replaces Shopify's endpoint for a browser that can't reach it; it must be the shop's
|
|
79
|
+
* own first-party endpoint passing the form on to Shopify, because the id token in the answer is trusted unsigned
|
|
80
|
+
* (`idTokenClaims`).
|
|
81
|
+
*
|
|
82
|
+
* @param {Record<string, string>} params
|
|
83
|
+
* @returns {Promise<TokenAnswer>}
|
|
84
|
+
* @throws {TetherError} `SESSION_ENDED` when Shopify refuses the code or refresh token (400, 401), else `TOKEN_FAILED`.
|
|
85
|
+
*/
|
|
86
|
+
export async function requestToken(params) {
|
|
87
|
+
const { tokenEndpoint } = await discover();
|
|
88
|
+
const response = await fetch(cfg.account?.tokenUrl || tokenEndpoint, {
|
|
89
|
+
method: 'POST',
|
|
90
|
+
body: new URLSearchParams(params),
|
|
91
|
+
});
|
|
92
|
+
const data = await readJsonObjectOrEmpty(response);
|
|
93
|
+
const access = textOrNull(data['access_token']);
|
|
94
|
+
if (!response.ok || !access) {
|
|
95
|
+
const ended = response.status === 400 || response.status === 401;
|
|
96
|
+
throw new TetherError(`Customer accounts: token ${response.status} ${textOrNull(data['error']) ?? ''}`.trim(), {
|
|
97
|
+
status: response.status,
|
|
98
|
+
code: ended ? 'SESSION_ENDED' : 'TOKEN_FAILED',
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
access,
|
|
103
|
+
refresh: textOrNull(data['refresh_token']) || null,
|
|
104
|
+
idToken: textOrNull(data['id_token']) || null,
|
|
105
|
+
expiresInSeconds: Number(data['expires_in']) || DEFAULT_TOKEN_SECONDS,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* The id token's claims. Its signature isn't checked: the token comes straight from Shopify's token endpoint over
|
|
111
|
+
* TLS, in answer to this browser's own code and verifier, so nobody else could have written it. That holds only while
|
|
112
|
+
* `account.tokenUrl` (when set) is the shop's own first-party endpoint passing the request on to Shopify (see
|
|
113
|
+
* `requestToken`).
|
|
114
|
+
*
|
|
115
|
+
* @param {string} idToken
|
|
116
|
+
* @returns {Record<string, unknown> | null}
|
|
117
|
+
*/
|
|
118
|
+
function idTokenClaims(idToken) {
|
|
119
|
+
const payload = idToken.split('.')[1];
|
|
120
|
+
if (!payload) return null;
|
|
121
|
+
/** @type {unknown} */
|
|
122
|
+
let claims;
|
|
123
|
+
try {
|
|
124
|
+
claims = JSON.parse(new TextDecoder().decode(fromBase64Url(payload)));
|
|
125
|
+
} catch {
|
|
126
|
+
// Not base64url JSON: not an id token, which the caller refuses.
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
return isRecord(claims) ? claims : null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* @param {string | null} idToken
|
|
134
|
+
* @param {{ nonce: string, issuer: string, client: string }} expected The login's nonce, Shopify's issuer, our client.
|
|
135
|
+
* @returns {boolean} True when the id token answers this login: the expected claims, and not expired.
|
|
136
|
+
*/
|
|
137
|
+
export function answersLogin(idToken, { nonce, issuer, client }) {
|
|
138
|
+
const claims = idToken ? idTokenClaims(idToken) : null;
|
|
139
|
+
if (!claims) return false;
|
|
140
|
+
const audience = claims['aud'];
|
|
141
|
+
const audiences = Array.isArray(audience) ? audience : [audience];
|
|
142
|
+
const expiresAt = claims['exp'];
|
|
143
|
+
return (
|
|
144
|
+
claims['nonce'] === nonce &&
|
|
145
|
+
claims['iss'] === issuer &&
|
|
146
|
+
audiences.includes(client) &&
|
|
147
|
+
typeof expiresAt === 'number' &&
|
|
148
|
+
expiresAt * 1000 >= Date.now()
|
|
149
|
+
);
|
|
150
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The customer's subscriptions (`tether-subscriptions`), with `tether-show="subscriptions-loading"`,
|
|
3
|
+
* `subscriptions-empty` and `subscriptions-error`. Each row's `tether-subscription-show` conditions and action buttons
|
|
4
|
+
* follow the contract's status and its next billing cycle.
|
|
5
|
+
*/
|
|
6
|
+
import { reportError } from '../config.js';
|
|
7
|
+
import { attr, formatMoney, get, qsa, repeat, sel, setImage, setText } from '../dom.js';
|
|
8
|
+
import { bindsIn, enumText, ownValue, showIn } from './markup.js';
|
|
9
|
+
import { subscriptions } from './operations.js';
|
|
10
|
+
import { localDate } from '../account-links.js';
|
|
11
|
+
/** @import { Money } from '../shopify-values.js' */
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @typedef {object} SubscriptionLine
|
|
15
|
+
* @property {string} title
|
|
16
|
+
* @property {string | null} variantTitle
|
|
17
|
+
* @property {number} quantity
|
|
18
|
+
* @property {Money} currentPrice
|
|
19
|
+
* @property {Money | null} lineDiscountedPrice
|
|
20
|
+
* @property {{ url: string, altText: string | null } | null} image
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* @typedef {object} SubscriptionContract The subscriptions document in account-ops.js.
|
|
24
|
+
* @property {string} id
|
|
25
|
+
* @property {'ACTIVE' | 'PAUSED' | 'CANCELLED' | 'EXPIRED' | 'FAILED'} status
|
|
26
|
+
* @property {string | null} nextBillingDate
|
|
27
|
+
* @property {string} currencyCode
|
|
28
|
+
* @property {Money | null} deliveryPrice
|
|
29
|
+
* @property {{ interval: string | null, intervalCount: { count: number } | null } | null} deliveryPolicy
|
|
30
|
+
* @property {{ nodes: SubscriptionLine[] }} lines
|
|
31
|
+
* @property {{ nodes: { cycleIndex: number, skipped: boolean }[] }} upcomingBillingCycles
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @param {SubscriptionContract} contract
|
|
36
|
+
* @returns {Record<string, boolean>} The row's `tether-subscription-show` conditions, `can-<action>` among them.
|
|
37
|
+
*/
|
|
38
|
+
function conditionsOf(contract) {
|
|
39
|
+
const next = contract.upcomingBillingCycles.nodes[0];
|
|
40
|
+
const status = contract.status;
|
|
41
|
+
const active = status === 'ACTIVE';
|
|
42
|
+
return {
|
|
43
|
+
active,
|
|
44
|
+
paused: status === 'PAUSED',
|
|
45
|
+
cancelled: status === 'CANCELLED',
|
|
46
|
+
expired: status === 'EXPIRED',
|
|
47
|
+
failed: status === 'FAILED',
|
|
48
|
+
skipped: Boolean(next?.skipped),
|
|
49
|
+
'can-pause': active,
|
|
50
|
+
'can-resume': status === 'PAUSED' || status === 'FAILED',
|
|
51
|
+
'can-skip': active && next !== undefined && !next.skipped,
|
|
52
|
+
'can-unskip': active && Boolean(next?.skipped),
|
|
53
|
+
'can-cancel': active || status === 'PAUSED' || status === 'FAILED',
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* @param {SubscriptionContract} contract
|
|
59
|
+
* @returns {string} `month`, `3 months`; `''` without a delivery policy.
|
|
60
|
+
*/
|
|
61
|
+
function intervalText(contract) {
|
|
62
|
+
const unit = enumText(contract.deliveryPolicy?.interval);
|
|
63
|
+
if (!unit) return '';
|
|
64
|
+
const count = contract.deliveryPolicy?.intervalCount?.count ?? 1;
|
|
65
|
+
return count <= 1 ? unit : `${count} ${unit}s`;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* @param {SubscriptionContract} contract
|
|
70
|
+
* @returns {Record<string, string>} The text of each `tether-subscription-bind` value.
|
|
71
|
+
*/
|
|
72
|
+
function contractTexts(contract) {
|
|
73
|
+
const lines = contract.lines.nodes;
|
|
74
|
+
const total = lines.reduce((sum, line) => sum + Number.parseFloat(line.lineDiscountedPrice?.amount ?? '0'), 0);
|
|
75
|
+
return {
|
|
76
|
+
status: enumText(contract.status),
|
|
77
|
+
next: contract.nextBillingDate ? localDate(contract.nextBillingDate) : '',
|
|
78
|
+
interval: intervalText(contract),
|
|
79
|
+
products: lines.map((line) => `${line.quantity}× ${line.title}`).join(', '),
|
|
80
|
+
total: lines.length ? formatMoney({ amount: String(total), currencyCode: contract.currencyCode }) : '',
|
|
81
|
+
delivery: formatMoney(contract.deliveryPrice),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* @param {HTMLElement} row
|
|
87
|
+
* @param {SubscriptionLine} line
|
|
88
|
+
*/
|
|
89
|
+
function fillLine(row, line) {
|
|
90
|
+
/** @type {Record<string, string>} */
|
|
91
|
+
const texts = {
|
|
92
|
+
title: line.title,
|
|
93
|
+
'variant-title': line.variantTitle || '',
|
|
94
|
+
quantity: String(line.quantity),
|
|
95
|
+
price: formatMoney(line.currentPrice),
|
|
96
|
+
};
|
|
97
|
+
bindsIn(row, 'subscription-line').forEach((el) => {
|
|
98
|
+
const key = get(el, 'subscription-line') ?? '';
|
|
99
|
+
if (key === 'image') {
|
|
100
|
+
if (line.image) setImage(el, line.image.url, line.image.altText || line.title);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
const text = ownValue(texts, key);
|
|
104
|
+
if (text !== undefined) setText(el, text);
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* @param {HTMLElement} row
|
|
110
|
+
* @param {SubscriptionContract} contract
|
|
111
|
+
*/
|
|
112
|
+
function fillContract(row, contract) {
|
|
113
|
+
row.dataset['tetherSubscription'] = contract.id;
|
|
114
|
+
row.setAttribute(attr('subscription-status'), enumText(contract.status));
|
|
115
|
+
const texts = contractTexts(contract);
|
|
116
|
+
qsa(row, sel('subscription-bind')).forEach((el) => {
|
|
117
|
+
const text = ownValue(texts, get(el, 'subscription-bind') ?? '');
|
|
118
|
+
if (text !== undefined) setText(el, text);
|
|
119
|
+
});
|
|
120
|
+
qsa(row, sel('subscription-lines')).forEach((box) => {
|
|
121
|
+
repeat(box, contract.lines.nodes, fillLine);
|
|
122
|
+
});
|
|
123
|
+
const conditions = conditionsOf(contract);
|
|
124
|
+
showIn(row, 'subscription-show', conditions);
|
|
125
|
+
qsa(row, sel('subscription-action')).forEach((button) => {
|
|
126
|
+
const allowed = ownValue(conditions, `can-${get(button, 'subscription-action') ?? ''}`) === true;
|
|
127
|
+
if ('disabled' in button) button.disabled = !allowed;
|
|
128
|
+
button.classList.toggle('is-disabled', !allowed);
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Loads and renders the subscriptions. A failure is reported and shows `subscriptions-error`.
|
|
134
|
+
*
|
|
135
|
+
* @param {ParentNode} root
|
|
136
|
+
*/
|
|
137
|
+
export async function renderSubscriptions(root) {
|
|
138
|
+
const boxes = qsa(root, sel('subscriptions'));
|
|
139
|
+
if (!boxes.length) return;
|
|
140
|
+
showIn(root, 'show', { 'subscriptions-loading': true, 'subscriptions-empty': false });
|
|
141
|
+
/** @type {SubscriptionContract[]} */
|
|
142
|
+
let list;
|
|
143
|
+
try {
|
|
144
|
+
list = await subscriptions();
|
|
145
|
+
} catch (error) {
|
|
146
|
+
reportError(error, 'subscriptions');
|
|
147
|
+
showIn(root, 'show', { 'subscriptions-loading': false, 'subscriptions-error': true });
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
showIn(root, 'show', {
|
|
151
|
+
'subscriptions-loading': false,
|
|
152
|
+
'subscriptions-empty': list.length === 0,
|
|
153
|
+
'subscriptions-error': false,
|
|
154
|
+
});
|
|
155
|
+
boxes.forEach((box) => {
|
|
156
|
+
repeat(box, list, fillContract);
|
|
157
|
+
});
|
|
158
|
+
}
|