@aglyn/plugins-commerce 1.34.1 → 1.35.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.
Files changed (40) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/woo-connections-card.component.d.ts +52 -0
  3. package/src/lib/components/console/woo-connections-card.component.js +189 -0
  4. package/src/lib/components/console/woo-connections-card.component.js.map +1 -0
  5. package/src/lib/plugin.js +13 -1
  6. package/src/lib/plugin.js.map +1 -1
  7. package/src/lib/server/order-event-triggers.js +9 -0
  8. package/src/lib/server/order-event-triggers.js.map +1 -1
  9. package/src/lib/server/woo/woo-connections.d.ts +23 -0
  10. package/src/lib/server/woo/woo-connections.js +109 -0
  11. package/src/lib/server/woo/woo-connections.js.map +1 -0
  12. package/src/lib/server/woo/woo-context.d.ts +45 -0
  13. package/src/lib/server/woo/woo-context.js +36 -0
  14. package/src/lib/server/woo/woo-context.js.map +1 -0
  15. package/src/lib/server/woo/woo-ids.d.ts +45 -0
  16. package/src/lib/server/woo/woo-ids.js +141 -0
  17. package/src/lib/server/woo/woo-ids.js.map +1 -0
  18. package/src/lib/server/woo/woo-meta.d.ts +68 -0
  19. package/src/lib/server/woo/woo-meta.js +127 -0
  20. package/src/lib/server/woo/woo-meta.js.map +1 -0
  21. package/src/lib/server/woo/woo-orders.d.ts +136 -0
  22. package/src/lib/server/woo/woo-orders.js +378 -0
  23. package/src/lib/server/woo/woo-orders.js.map +1 -0
  24. package/src/lib/server/woo/woo-products.d.ts +19 -0
  25. package/src/lib/server/woo/woo-products.js +662 -0
  26. package/src/lib/server/woo/woo-products.js.map +1 -0
  27. package/src/lib/server/woo/woo-route.d.ts +49 -0
  28. package/src/lib/server/woo/woo-route.js +333 -0
  29. package/src/lib/server/woo/woo-route.js.map +1 -0
  30. package/src/lib/server/woo/woo-shapes.d.ts +421 -0
  31. package/src/lib/server/woo/woo-shapes.js +835 -0
  32. package/src/lib/server/woo/woo-shapes.js.map +1 -0
  33. package/src/lib/server/woo/woo-system.d.ts +35 -0
  34. package/src/lib/server/woo/woo-system.js +339 -0
  35. package/src/lib/server/woo/woo-system.js.map +1 -0
  36. package/src/lib/server/woo/woo-webhooks.d.ts +53 -0
  37. package/src/lib/server/woo/woo-webhooks.js +204 -0
  38. package/src/lib/server/woo/woo-webhooks.js.map +1 -0
  39. package/src/lib/server.js +15 -0
  40. package/src/lib/server.js.map +1 -1
@@ -0,0 +1,109 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { disconnectWooConnection, firebaseAdmin, getOrgForHost, listWooConnections, logHostActivity } from "@aglyn/tenant-data-admin";
17
+ import { commerceSitePermissionRefusal } from "../../model/plugin-permissions.js";
18
+ import { holdsCommerceSiteKey } from "../commerce-site-keys.js";
19
+ import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
20
+ export const wooConnectionsHandler = async (req, res)=>{
21
+ var _req_headers_authorization, _ref;
22
+ if (req.method !== 'GET' && req.method !== 'POST') return res.status(405).json({
23
+ error: 'Method not allowed'
24
+ });
25
+ const authorization = String((_req_headers_authorization = req.headers.authorization) != null ? _req_headers_authorization : '');
26
+ const idToken = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : '';
27
+ if (!idToken) return res.status(401).json({
28
+ error: 'Unauthenticated'
29
+ });
30
+ let body = {};
31
+ if (req.method === 'POST') {
32
+ try {
33
+ var _req_body;
34
+ body = typeof req.body === 'string' ? JSON.parse(req.body) : (_req_body = req.body) != null ? _req_body : {};
35
+ } catch (unused) {
36
+ return res.status(400).json({
37
+ error: 'The request could not be read'
38
+ });
39
+ }
40
+ }
41
+ const hostId = String((_ref = req.method === 'GET' ? req.query['hostId'] : body['hostId']) != null ? _ref : '');
42
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(hostId)) return res.status(400).json({
43
+ error: 'Missing hostId'
44
+ });
45
+ try {
46
+ var _body_grantId, _decoded_email;
47
+ let decoded;
48
+ try {
49
+ decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
50
+ } catch (error) {
51
+ // A refused credential is the caller's 401; a failure to check one is
52
+ // ours and keeps a 5xx (AGL-2852).
53
+ if (isRefusedIdToken(error)) return res.status(401).json({
54
+ error: 'Unauthenticated'
55
+ });
56
+ console.error('[commerce] woo connections: the sign-in could not be checked', error);
57
+ return res.status(500).json({
58
+ error: 'The sign-in could not be checked. Try again.'
59
+ });
60
+ }
61
+ const hostSnapshot = await firebaseAdmin.app().firestore().collection('hosts').doc(hostId).get();
62
+ if (!hostSnapshot.exists) return res.status(404).json({
63
+ error: 'Unknown site'
64
+ });
65
+ const canManage = holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.shippingConnections');
66
+ const changes = req.method === 'POST';
67
+ if (changes ? !canManage : !canManage && !holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders')) {
68
+ return res.status(403).json({
69
+ error: commerceSitePermissionRefusal(changes ? 'commerce.shippingConnections' : 'commerce.orders')
70
+ });
71
+ }
72
+ const owner = await getOrgForHost(hostId);
73
+ if (!owner) return res.status(404).json({
74
+ error: 'Unknown site'
75
+ });
76
+ if (!changes) {
77
+ const answer = {
78
+ canManage,
79
+ connections: await listWooConnections(owner.orgId, hostId)
80
+ };
81
+ return res.status(200).json(answer);
82
+ }
83
+ const grantId = String((_body_grantId = body['grantId']) != null ? _body_grantId : '');
84
+ const current = (await listWooConnections(owner.orgId, hostId)).find((entry)=>entry.grantId === grantId);
85
+ if (!current || !await disconnectWooConnection(owner.orgId, hostId, grantId)) {
86
+ return res.status(404).json({
87
+ error: 'That app is no longer connected'
88
+ });
89
+ }
90
+ await logHostActivity(hostId, {
91
+ uid: decoded.uid,
92
+ email: (_decoded_email = decoded.email) != null ? _decoded_email : null
93
+ }, 'Disconnected an app', {
94
+ type: 'commerce:wooConnection',
95
+ id: grantId,
96
+ name: current.appName
97
+ }).catch(()=>undefined);
98
+ return res.status(200).json({
99
+ ok: true
100
+ });
101
+ } catch (error) {
102
+ console.error('[commerce/woo-connections]', error instanceof Error ? error.message : 'unknown');
103
+ return res.status(500).json({
104
+ error: 'That did not go through. Try again.'
105
+ });
106
+ }
107
+ };
108
+
109
+ //# sourceMappingURL=woo-connections.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/woo/woo-connections.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport {\n disconnectWooConnection,\n firebaseAdmin,\n getOrgForHost,\n listWooConnections,\n logHostActivity,\n type PublicWooConnection,\n} from '@aglyn/tenant-data-admin'\nimport { commerceSitePermissionRefusal } from '../../model/plugin-permissions'\nimport { holdsCommerceSiteKey } from '../commerce-site-keys'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\n\n/*\n * THE STORE'S CONNECTED APPS CARD: `commerce/woo-connections`. The apps that\n * linked this store through their WooCommerce connector (`woo-route.ts`),\n * and the way to end one.\n *\n * - GET `?hostId=` → `{ canManage, connections }`, for anyone who reads the\n * order book (\"Manage orders\"), because each link reads it too.\n * - POST `{ hostId, grantId }` → ends that link at once; the app's next call\n * is refused. \"Connect shipping apps\", the key that already decides who\n * may hand an outside app this store's orders.\n */\n\nexport interface WooConnectionsAnswer {\n canManage: boolean\n connections: PublicWooConnection[]\n}\n\nexport const wooConnectionsHandler: Aglyn.PluginApiHandler = async (req, res) => {\n if (req.method !== 'GET' && req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : ''\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n let body: Record<string, unknown> = {}\n if (req.method === 'POST') {\n try {\n body = typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n } catch {\n return res.status(400).json({ error: 'The request could not be read' })\n }\n }\n const hostId = String((req.method === 'GET' ? req.query['hostId'] : body['hostId']) ?? '')\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(hostId)) return res.status(400).json({ error: 'Missing hostId' })\n\n try {\n let decoded: { uid: string; email?: string }\n try {\n decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n } catch (error) {\n // A refused credential is the caller's 401; a failure to check one is\n // ours and keeps a 5xx (AGL-2852).\n if (isRefusedIdToken(error)) return res.status(401).json({ error: 'Unauthenticated' })\n console.error('[commerce] woo connections: the sign-in could not be checked', error)\n return res.status(500).json({ error: 'The sign-in could not be checked. Try again.' })\n }\n const hostSnapshot = await firebaseAdmin.app().firestore().collection('hosts').doc(hostId).get()\n if (!hostSnapshot.exists) return res.status(404).json({ error: 'Unknown site' })\n const canManage = holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.shippingConnections')\n const changes = req.method === 'POST'\n if (changes ? !canManage : !canManage && !holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders')) {\n return res.status(403).json({\n error: commerceSitePermissionRefusal(changes ? 'commerce.shippingConnections' : 'commerce.orders'),\n })\n }\n const owner = await getOrgForHost(hostId)\n if (!owner) return res.status(404).json({ error: 'Unknown site' })\n\n if (!changes) {\n const answer: WooConnectionsAnswer = { canManage, connections: await listWooConnections(owner.orgId, hostId) }\n return res.status(200).json(answer)\n }\n const grantId = String(body['grantId'] ?? '')\n const current = (await listWooConnections(owner.orgId, hostId)).find((entry) => entry.grantId === grantId)\n if (!current || !(await disconnectWooConnection(owner.orgId, hostId, grantId))) {\n return res.status(404).json({ error: 'That app is no longer connected' })\n }\n await logHostActivity(hostId, { uid: decoded.uid, email: decoded.email ?? null }, 'Disconnected an app', {\n type: 'commerce:wooConnection',\n id: grantId,\n name: current.appName,\n }).catch(() => undefined)\n return res.status(200).json({ ok: true })\n } catch (error) {\n console.error('[commerce/woo-connections]', error instanceof Error ? error.message : 'unknown')\n return res.status(500).json({ error: 'That did not go through. Try again.' })\n }\n}\n"],"names":["disconnectWooConnection","firebaseAdmin","getOrgForHost","listWooConnections","logHostActivity","commerceSitePermissionRefusal","holdsCommerceSiteKey","isRefusedIdToken","wooConnectionsHandler","req","res","method","status","json","error","authorization","String","headers","idToken","startsWith","slice","length","body","JSON","parse","hostId","query","test","decoded","app","auth","verifyIdToken","console","hostSnapshot","firestore","collection","doc","get","exists","canManage","uid","changes","owner","answer","connections","orgId","grantId","current","find","entry","email","type","id","name","appName","catch","undefined","ok","Error","message"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SACEA,uBAAuB,EACvBC,aAAa,EACbC,aAAa,EACbC,kBAAkB,EAClBC,eAAe,QAEV,2BAA0B;AACjC,SAASC,6BAA6B,QAAQ,oCAAgC;AAC9E,SAASC,oBAAoB,QAAQ,2BAAuB;AAC5D,SAASC,gBAAgB,QAAQ,mDAAkD;AAmBnF,OAAO,MAAMC,wBAAgD,OAAOC,KAAKC;QAE1CD,4BAWNA;IAZvB,IAAIA,IAAIE,MAAM,KAAK,SAASF,IAAIE,MAAM,KAAK,QAAQ,OAAOD,IAAIE,MAA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QACzE;QACA,MAAMV,gBAAgBqB,QAAQ;YAAEe,KAAKZ,QAAQY,GAAG;YAAEU,KAAK,GAAEtB,iBAAAA,QAAQsB,KAAK,YAAbtB,iBAAiB;QAAK,GAAG,uBAAuB;YACvGuB,MAAM;YACNC,IAAIN;YACJO,MAAMN,QAAQO,OAAO;QACvB,GAAGC,KAAK,CAAC,IAAMC;QACf,OAAO9C,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAE4C,IAAI;QAAK;IACzC,EAAE,OAAO3C,OAAO;QACdkB,QAAQlB,KAAK,CAAC,8BAA8BA,iBAAiB4C,QAAQ5C,MAAM6C,OAAO,GAAG;QACrF,OAAOjD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAsC;IAC7E;AACF,EAAC"}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import type { ApiV1Context } from '@aglyn/tenant-data-admin/server/api-v1-kit';
18
+ /** One proven request to a site's WooCommerce surface. */
19
+ export interface WooRequestContext {
20
+ hostId: string;
21
+ /** The store's own address, `https://shop.example.com`. */
22
+ origin: string;
23
+ /** The context the store's own product and order writers take. */
24
+ api: ApiV1Context;
25
+ /** The link the key belongs to. */
26
+ grantId: string;
27
+ appName: string;
28
+ request: Request;
29
+ url: URL;
30
+ /** The route below `/wc/v3`, split: `['products', '1042', 'variations']`. */
31
+ segments: string[];
32
+ /** The namespace the route was called under: `wc/v3`, `wc/v2`, `wc-shipment-tracking/v3`. */
33
+ namespace: string;
34
+ /** The request's JSON body, read once. */
35
+ body: Record<string, unknown>;
36
+ /** What the request log keeps besides the method, path and status. */
37
+ note: (entry: Record<string, unknown>) => void;
38
+ }
39
+ /** A synthetic request carrying a JSON body to one of the store's own writers. */
40
+ export declare function jsonRequest(method: string, body: unknown, idempotencyKey?: string): Request;
41
+ /** A writer's answer, read: its status and JSON body. */
42
+ export declare function readAnswer(response: Response): Promise<{
43
+ status: number;
44
+ body: unknown;
45
+ }>;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { _ as _extends } from "@swc/helpers/_/_extends";
17
+ /** A synthetic request carrying a JSON body to one of the store's own writers. */ export function jsonRequest(method, body, idempotencyKey) {
18
+ return new Request('https://woocommerce.invalid/', {
19
+ method,
20
+ headers: _extends({
21
+ 'content-type': 'application/json'
22
+ }, idempotencyKey ? {
23
+ 'idempotency-key': idempotencyKey
24
+ } : {}),
25
+ body: JSON.stringify(body != null ? body : {})
26
+ });
27
+ }
28
+ /** A writer's answer, read: its status and JSON body. */ export async function readAnswer(response) {
29
+ const body = await response.json().catch(()=>null);
30
+ return {
31
+ status: response.status,
32
+ body
33
+ };
34
+ }
35
+
36
+ //# sourceMappingURL=woo-context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/woo/woo-context.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ApiV1Context } from '@aglyn/tenant-data-admin/server/api-v1-kit'\n\n/** One proven request to a site's WooCommerce surface. */\nexport interface WooRequestContext {\n hostId: string\n /** The store's own address, `https://shop.example.com`. */\n origin: string\n /** The context the store's own product and order writers take. */\n api: ApiV1Context\n /** The link the key belongs to. */\n grantId: string\n appName: string\n request: Request\n url: URL\n /** The route below `/wc/v3`, split: `['products', '1042', 'variations']`. */\n segments: string[]\n /** The namespace the route was called under: `wc/v3`, `wc/v2`, `wc-shipment-tracking/v3`. */\n namespace: string\n /** The request's JSON body, read once. */\n body: Record<string, unknown>\n /** What the request log keeps besides the method, path and status. */\n note: (entry: Record<string, unknown>) => void\n}\n\n/** A synthetic request carrying a JSON body to one of the store's own writers. */\nexport function jsonRequest(method: string, body: unknown, idempotencyKey?: string): Request {\n return new Request('https://woocommerce.invalid/', {\n method,\n headers: {\n 'content-type': 'application/json',\n ...(idempotencyKey ? { 'idempotency-key': idempotencyKey } : {}),\n },\n body: JSON.stringify(body ?? {}),\n })\n}\n\n/** A writer's answer, read: its status and JSON body. */\nexport async function readAnswer(response: Response): Promise<{ status: number; body: unknown }> {\n const body: unknown = await response.json().catch(() => null)\n return { status: response.status, body }\n}\n"],"names":["jsonRequest","method","body","idempotencyKey","Request","headers","JSON","stringify","readAnswer","response","json","catch","status"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AA0BD,gFAAgF,GAChF,OAAO,SAASA,YAAYC,MAAc,EAAEC,IAAa,EAAEC,cAAuB;IAChF,OAAO,IAAIC,QAAQ,gCAAgC;QACjDH;QACAI,SAAS;YACP,gBAAgB;WACZF,iBAAiB;YAAE,mBAAmBA;QAAe,IAAI,CAAC;QAEhED,MAAMI,KAAKC,SAAS,CAACL,eAAAA,OAAQ,CAAC;IAChC;AACF;AAEA,uDAAuD,GACvD,OAAO,eAAeM,WAAWC,QAAkB;IACjD,MAAMP,OAAgB,MAAMO,SAASC,IAAI,GAAGC,KAAK,CAAC,IAAM;IACxD,OAAO;QAAEC,QAAQH,SAASG,MAAM;QAAEV;IAAK;AACzC"}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ type Firestore = FirebaseFirestore.Firestore;
18
+ export type WooIdTarget = {
19
+ kind: 'product';
20
+ productId: string;
21
+ } | {
22
+ kind: 'variant';
23
+ productId: string;
24
+ variantId: string;
25
+ };
26
+ export declare function wooIdKey(target: WooIdTarget): string;
27
+ /** The document that maps a WooCommerce number back to its Aglyn key. */
28
+ export declare const wooNumberKey: (n: number) => string;
29
+ /**
30
+ * The integer for each target, allocating the ones never shown before.
31
+ * Answers in the targets' order. Two calls racing for the same target agree:
32
+ * the forward document is created inside the allocating transaction, which
33
+ * re-reads it first.
34
+ */
35
+ export declare function wooIdsFor(firestore: Firestore, hostId: string, targets: readonly WooIdTarget[]): Promise<number[]>;
36
+ /** What an integer names, or `null` when this site never showed it. */
37
+ export declare function wooIdTarget(firestore: Firestore, hostId: string, n: number): Promise<WooIdTarget | null>;
38
+ /** The order an integer names: its number. */
39
+ export declare function orderIdForWooId(firestore: Firestore, hostId: string, n: number): Promise<string | null>;
40
+ /**
41
+ * An order's integer: its number. An order with none (a record older than
42
+ * numbering) is not shown to a WooCommerce client at all; `null` says so.
43
+ */
44
+ export declare function wooOrderId(data: Record<string, unknown>): number | null;
45
+ export {};
@@ -0,0 +1,141 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ /*==========================================
18
+ * WOOCOMMERCE IDS: STABLE INTEGERS FOR THE STORE'S RECORDS.
19
+ *
20
+ * WooCommerce clients store a product, a variation and an order by an
21
+ * integer and match on it for good (Tapstitch links a store's variants by
22
+ * "SKU codes and variant IDs"). The store's ids are strings, so each one a
23
+ * client is shown gets an integer the first time, kept for ever under
24
+ * `hosts/{hostId}/wooIds`:
25
+ *
26
+ * - `p.{productId}` and `v.{productId}.{variantId}` → `{ n }`
27
+ * - `n.{n}` → `{ kind, productId, variantId? }`, the way back
28
+ * - `counter` → `{ next }`, the site's next integer, from 1001
29
+ *
30
+ * An order is its own number (`#1042` is id 1042), which is already a
31
+ * per-site integer and what a person reading the app sees; the way back is
32
+ * a query on `number`.
33
+ *
34
+ * The documents sit under the site, so the site's deletion takes them, and no
35
+ * rule names them, so no client reads them.
36
+ *=========================================*/ const FIRST_ID = 1001;
37
+ export function wooIdKey(target) {
38
+ return target.kind === 'product' ? `p.${target.productId}` : `v.${target.productId}.${target.variantId}`;
39
+ }
40
+ /** The document that maps a WooCommerce number back to its Aglyn key. */ export const wooNumberKey = (n)=>`n.${n}`;
41
+ const idsOf = (firestore, hostId)=>firestore.collection('hosts').doc(hostId).collection('wooIds');
42
+ /**
43
+ * The integer for each target, allocating the ones never shown before.
44
+ * Answers in the targets' order. Two calls racing for the same target agree:
45
+ * the forward document is created inside the allocating transaction, which
46
+ * re-reads it first.
47
+ */ export async function wooIdsFor(firestore, hostId, targets) {
48
+ if (!targets.length) return [];
49
+ const collection = idsOf(firestore, hostId);
50
+ const keys = targets.map(wooIdKey);
51
+ const unique = [
52
+ ...new Set(keys)
53
+ ];
54
+ const known = new Map();
55
+ const snaps = await firestore.getAll(...unique.map((key)=>collection.doc(key)));
56
+ snaps.forEach((snap, index)=>{
57
+ const n = Number(snap.get('n'));
58
+ if (snap.exists && Number.isInteger(n)) known.set(unique[index], n);
59
+ });
60
+ const missing = unique.filter((key)=>!known.has(key));
61
+ if (missing.length) {
62
+ const targetByKey = new Map(targets.map((target)=>[
63
+ wooIdKey(target),
64
+ target
65
+ ]));
66
+ const allocated = await firestore.runTransaction(async (tx)=>{
67
+ var _counter_get;
68
+ const counterRef = collection.doc('counter');
69
+ const refs = missing.map((key)=>collection.doc(key));
70
+ const [counter, ...current] = await tx.getAll(counterRef, ...refs);
71
+ let next = Math.max(FIRST_ID, Number((_counter_get = counter.get('next')) != null ? _counter_get : FIRST_ID) || FIRST_ID);
72
+ const out = new Map();
73
+ current.forEach((snap, index)=>{
74
+ const key = missing[index];
75
+ const existing = Number(snap.get('n'));
76
+ if (snap.exists && Number.isInteger(existing)) {
77
+ out.set(key, existing);
78
+ return;
79
+ }
80
+ const n = next;
81
+ next += 1;
82
+ const target = targetByKey.get(key);
83
+ tx.set(collection.doc(key), {
84
+ n
85
+ });
86
+ tx.set(collection.doc(wooNumberKey(n)), _extends({
87
+ kind: target.kind,
88
+ productId: target.productId
89
+ }, target.kind === 'variant' ? {
90
+ variantId: target.variantId
91
+ } : {}));
92
+ out.set(key, n);
93
+ });
94
+ tx.set(counterRef, {
95
+ next
96
+ }, {
97
+ merge: true
98
+ });
99
+ return out;
100
+ });
101
+ for (const [key, n] of allocated)known.set(key, n);
102
+ }
103
+ return keys.map((key)=>known.get(key));
104
+ }
105
+ /** What an integer names, or `null` when this site never showed it. */ export async function wooIdTarget(firestore, hostId, n) {
106
+ var _snap_get;
107
+ if (!Number.isInteger(n) || n <= 0) return null;
108
+ const snap = await idsOf(firestore, hostId).doc(wooNumberKey(n)).get();
109
+ if (!snap.exists) return null;
110
+ const productId = String((_snap_get = snap.get('productId')) != null ? _snap_get : '');
111
+ if (!productId) return null;
112
+ if (snap.get('kind') === 'variant') {
113
+ var _snap_get1;
114
+ const variantId = String((_snap_get1 = snap.get('variantId')) != null ? _snap_get1 : '');
115
+ return variantId ? {
116
+ kind: 'variant',
117
+ productId,
118
+ variantId
119
+ } : null;
120
+ }
121
+ return {
122
+ kind: 'product',
123
+ productId
124
+ };
125
+ }
126
+ /** The order an integer names: its number. */ export async function orderIdForWooId(firestore, hostId, n) {
127
+ var _ref;
128
+ var _snap_docs_;
129
+ if (!Number.isInteger(n) || n <= 0) return null;
130
+ const snap = await firestore.collection('hosts').doc(hostId).collection('orders').where('number', '==', n).limit(1).get();
131
+ return (_ref = (_snap_docs_ = snap.docs[0]) == null ? void 0 : _snap_docs_.id) != null ? _ref : null;
132
+ }
133
+ /**
134
+ * An order's integer: its number. An order with none (a record older than
135
+ * numbering) is not shown to a WooCommerce client at all; `null` says so.
136
+ */ export function wooOrderId(data) {
137
+ const n = data['number'];
138
+ return typeof n === 'number' && Number.isInteger(n) && n > 0 ? n : null;
139
+ }
140
+
141
+ //# sourceMappingURL=woo-ids.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/woo/woo-ids.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * WOOCOMMERCE IDS: STABLE INTEGERS FOR THE STORE'S RECORDS.\n *\n * WooCommerce clients store a product, a variation and an order by an\n * integer and match on it for good (Tapstitch links a store's variants by\n * \"SKU codes and variant IDs\"). The store's ids are strings, so each one a\n * client is shown gets an integer the first time, kept for ever under\n * `hosts/{hostId}/wooIds`:\n *\n * - `p.{productId}` and `v.{productId}.{variantId}` → `{ n }`\n * - `n.{n}` → `{ kind, productId, variantId? }`, the way back\n * - `counter` → `{ next }`, the site's next integer, from 1001\n *\n * An order is its own number (`#1042` is id 1042), which is already a\n * per-site integer and what a person reading the app sees; the way back is\n * a query on `number`.\n *\n * The documents sit under the site, so the site's deletion takes them, and no\n * rule names them, so no client reads them.\n *=========================================*/\n\nconst FIRST_ID = 1001\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport type WooIdTarget = { kind: 'product'; productId: string } | { kind: 'variant'; productId: string; variantId: string }\n\nexport function wooIdKey(target: WooIdTarget): string {\n return target.kind === 'product' ? `p.${target.productId}` : `v.${target.productId}.${target.variantId}`\n}\n\n/** The document that maps a WooCommerce number back to its Aglyn key. */\nexport const wooNumberKey = (n: number): string => `n.${n}`\n\nconst idsOf = (firestore: Firestore, hostId: string) => firestore.collection('hosts').doc(hostId).collection('wooIds')\n\n/**\n * The integer for each target, allocating the ones never shown before.\n * Answers in the targets' order. Two calls racing for the same target agree:\n * the forward document is created inside the allocating transaction, which\n * re-reads it first.\n */\nexport async function wooIdsFor(firestore: Firestore, hostId: string, targets: readonly WooIdTarget[]): Promise<number[]> {\n if (!targets.length) return []\n const collection = idsOf(firestore, hostId)\n const keys = targets.map(wooIdKey)\n const unique = [...new Set(keys)]\n const known = new Map<string, number>()\n const snaps = await firestore.getAll(...unique.map((key) => collection.doc(key)))\n snaps.forEach((snap, index) => {\n const n = Number(snap.get('n'))\n if (snap.exists && Number.isInteger(n)) known.set(unique[index], n)\n })\n const missing = unique.filter((key) => !known.has(key))\n if (missing.length) {\n const targetByKey = new Map(targets.map((target) => [wooIdKey(target), target]))\n const allocated = await firestore.runTransaction(async (tx) => {\n const counterRef = collection.doc('counter')\n const refs = missing.map((key) => collection.doc(key))\n const [counter, ...current] = await tx.getAll(counterRef, ...refs)\n let next = Math.max(FIRST_ID, Number(counter.get('next') ?? FIRST_ID) || FIRST_ID)\n const out = new Map<string, number>()\n current.forEach((snap, index) => {\n const key = missing[index]\n const existing = Number(snap.get('n'))\n if (snap.exists && Number.isInteger(existing)) {\n out.set(key, existing)\n return\n }\n const n = next\n next += 1\n const target = targetByKey.get(key) as WooIdTarget\n tx.set(collection.doc(key), { n })\n tx.set(collection.doc(wooNumberKey(n)), {\n kind: target.kind,\n productId: target.productId,\n ...(target.kind === 'variant' ? { variantId: target.variantId } : {}),\n })\n out.set(key, n)\n })\n tx.set(counterRef, { next }, { merge: true })\n return out\n })\n for (const [key, n] of allocated) known.set(key, n)\n }\n return keys.map((key) => known.get(key) as number)\n}\n\n/** What an integer names, or `null` when this site never showed it. */\nexport async function wooIdTarget(firestore: Firestore, hostId: string, n: number): Promise<WooIdTarget | null> {\n if (!Number.isInteger(n) || n <= 0) return null\n const snap = await idsOf(firestore, hostId).doc(wooNumberKey(n)).get()\n if (!snap.exists) return null\n const productId = String(snap.get('productId') ?? '')\n if (!productId) return null\n if (snap.get('kind') === 'variant') {\n const variantId = String(snap.get('variantId') ?? '')\n return variantId ? { kind: 'variant', productId, variantId } : null\n }\n return { kind: 'product', productId }\n}\n\n/** The order an integer names: its number. */\nexport async function orderIdForWooId(firestore: Firestore, hostId: string, n: number): Promise<string | null> {\n if (!Number.isInteger(n) || n <= 0) return null\n const snap = await firestore.collection('hosts').doc(hostId).collection('orders').where('number', '==', n).limit(1).get()\n return snap.docs[0]?.id ?? null\n}\n\n/**\n * An order's integer: its number. An order with none (a record older than\n * numbering) is not shown to a WooCommerce client at all; `null` says so.\n */\nexport function wooOrderId(data: Record<string, unknown>): number | null {\n const n = data['number']\n return typeof n === 'number' && Number.isInteger(n) && n > 0 ? n : null\n}\n"],"names":["FIRST_ID","wooIdKey","target","kind","productId","variantId","wooNumberKey","n","idsOf","firestore","hostId","collection","doc","wooIdsFor","targets","length","keys","map","unique","Set","known","Map","snaps","getAll","key","forEach","snap","index","Number","get","exists","isInteger","set","missing","filter","has","targetByKey","allocated","runTransaction","tx","counter","counterRef","refs","current","next","Math","max","out","existing","merge","wooIdTarget","String","orderIdForWooId","where","limit","docs","id","wooOrderId","data"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;2CAmB2C,GAE3C,MAAMA,WAAW;AAMjB,OAAO,SAASC,SAASC,MAAmB;IAC1C,OAAOA,OAAOC,IAAI,KAAK,YAAY,CAAC,EAAE,EAAED,OAAOE,SAAS,EAAE,GAAG,CAAC,EAAE,EAAEF,OAAOE,SAAS,CAAC,CAAC,EAAEF,OAAOG,SAAS,EAAE;AAC1G;AAEA,uEAAuE,GACvE,OAAO,MAAMC,eAAe,CAACC,IAAsB,CAAC,EAAE,EAAEA,GAAG,CAAA;AAE3D,MAAMC,QAAQ,CAACC,WAAsBC,SAAmBD,UAAUE,UAAU,CAAC,SAASC,GAAG,CAACF,QAAQC,UAAU,CAAC;AAE7G;;;;;CAKC,GACD,OAAO,eAAeE,UAAUJ,SAAoB,EAAEC,MAAc,EAAEI,OAA+B;IACnG,IAAI,CAACA,QAAQC,MAAM,EAAE,OAAO,EAAE;IAC9B,MAAMJ,aAAaH,MAAMC,WAAWC;IACpC,MAAMM,OAAOF,QAAQG,GAAG,CAAChB;IACzB,MAAMiB,SAAS;WAAI,IAAIC,IAAIH;KAAM;IACjC,MAAMI,QAAQ,IAAIC;IAClB,MAAMC,QAAQ,MAAMb,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c,EAAEH,CAAS;;QAG5EmB;IAFP,IAAI,CAACE,OAAOG,SAAS,CAACxB,MAAMA,KAAK,GAAG,OAAO;IAC3C,MAAMmB,OAAO,MAAMjB,UAAUE,UAAU,CAAC,SAASC,GAAG,CAACF,QAAQC,UAAU,CAAC,UAAU0C,KAAK,CAAC,UAAU,MAAM9C,GAAG+C,KAAK,CAAC,GAAGzB,GAAG;IACvH,gBAAOH,cAAAA,KAAK6B,IAAI,CAAC,EAAE,qBAAZ7B,YAAc8B,EAAE,mBAAI;AAC7B;AAEA;;;CAGC,GACD,OAAO,SAASC,WAAWC,IAA6B;IACtD,MAAMnD,IAAImD,IAAI,CAAC,SAAS;IACxB,OAAO,OAAOnD,MAAM,YAAYqB,OAAOG,SAAS,CAACxB,MAAMA,IAAI,IAAIA,IAAI;AACrE"}
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ export declare const MAX_META = 50;
18
+ export declare const MAX_META_VALUE = 4000;
19
+ export declare const MAX_NOTES = 100;
20
+ type Firestore = FirebaseFirestore.Firestore;
21
+ export type WooMetaMap = Record<string, string>;
22
+ export interface WooNote {
23
+ id: number;
24
+ note: string;
25
+ customer_note: boolean;
26
+ atMs: number;
27
+ }
28
+ /** `meta_data` entries merged onto a stored map, bounded. A `null` value removes a key. */
29
+ export declare function mergeMeta(stored: WooMetaMap, entries: unknown): WooMetaMap;
30
+ /** A stored map as WooCommerce lists `meta_data`. */
31
+ export declare const metaList: (meta: WooMetaMap) => {
32
+ id: number;
33
+ key: string;
34
+ value: string;
35
+ }[];
36
+ export interface ProductMeta {
37
+ sku: string;
38
+ meta: WooMetaMap;
39
+ variants: Record<string, {
40
+ meta?: WooMetaMap;
41
+ image?: string;
42
+ }>;
43
+ }
44
+ export declare function readProductMeta(firestore: Firestore, hostId: string, productId: string): Promise<ProductMeta>;
45
+ export declare function readProductMetas(firestore: Firestore, hostId: string, productIds: readonly string[]): Promise<Map<string, ProductMeta>>;
46
+ export declare function writeProductMeta(firestore: Firestore, hostId: string, productId: string, next: ProductMeta): Promise<void>;
47
+ export interface OrderMeta {
48
+ meta: WooMetaMap;
49
+ notes: WooNote[];
50
+ }
51
+ export declare function readOrderMeta(firestore: Firestore, hostId: string, orderId: string): Promise<OrderMeta>;
52
+ export declare function readOrderMetas(firestore: Firestore, hostId: string, orderIds: readonly string[]): Promise<Map<string, OrderMeta>>;
53
+ export declare function writeOrderMeta(firestore: Firestore, hostId: string, orderId: string, next: OrderMeta): Promise<void>;
54
+ export interface StoredWebhook {
55
+ id: number;
56
+ name: string;
57
+ status: string;
58
+ topic: string;
59
+ delivery_url: string;
60
+ secret: string;
61
+ atMs: number;
62
+ grantId: string;
63
+ /** The store's address the app linked, sent as `X-WC-Webhook-Source`. */
64
+ source?: string;
65
+ }
66
+ export declare function readWebhooks(firestore: Firestore, hostId: string): Promise<StoredWebhook[]>;
67
+ export declare function writeWebhooks(firestore: Firestore, hostId: string, list: readonly StoredWebhook[]): Promise<void>;
68
+ export {};
@@ -0,0 +1,127 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ /*==========================================
18
+ * WHAT A WOOCOMMERCE APP WRITES THAT THE STORE HAS NO FIELD FOR.
19
+ *
20
+ * Apps keep their own references on a WooCommerce record (`meta_data`: a
21
+ * supplier's product id on the product, a production id on the order), a
22
+ * variable product's own SKU, a variation's picture, and notes on an order;
23
+ * and they read them back to match their records. The store's products and
24
+ * orders have no such fields, and adding them to the records every other
25
+ * part of the store reads would be the wrong place, so they are kept beside
26
+ * the record under `hosts/{hostId}/wooMeta`:
27
+ *
28
+ * - `p.{productId}` → `{ sku, meta, variants: { [variantId]: { meta, image } } }`
29
+ * - `o.{orderId}` → `{ meta, notes: [{ id, note, customer_note, atMs }] }`
30
+ * - `webhooks` → `{ list: [...] }`, the webhooks an app registered
31
+ *
32
+ * Bounded: a record keeps at most {@link MAX_META} entries of at most
33
+ * {@link MAX_META_VALUE} characters each, and an order its last
34
+ * {@link MAX_NOTES} notes.
35
+ *=========================================*/ export const MAX_META = 50;
36
+ export const MAX_META_VALUE = 4000;
37
+ export const MAX_NOTES = 100;
38
+ const metaDoc = (firestore, hostId, key)=>firestore.collection('hosts').doc(hostId).collection('wooMeta').doc(key);
39
+ /** `meta_data` entries merged onto a stored map, bounded. A `null` value removes a key. */ export function mergeMeta(stored, entries) {
40
+ const next = _extends({}, stored);
41
+ if (!Array.isArray(entries)) return next;
42
+ for (const entry of entries){
43
+ if (!entry || typeof entry !== 'object') continue;
44
+ const key = entry['key'];
45
+ const value = entry['value'];
46
+ if (typeof key !== 'string' || !key || key.length > 255) continue;
47
+ if (value === null || value === undefined) {
48
+ delete next[key];
49
+ continue;
50
+ }
51
+ if (!(key in next) && Object.keys(next).length >= MAX_META) continue;
52
+ next[key] = (typeof value === 'string' ? value : JSON.stringify(value)).slice(0, MAX_META_VALUE);
53
+ }
54
+ return next;
55
+ }
56
+ /** A stored map as WooCommerce lists `meta_data`. */ export const metaList = (meta)=>Object.entries(meta).map(([key, value], index)=>({
57
+ id: index + 1,
58
+ key,
59
+ value
60
+ }));
61
+ export async function readProductMeta(firestore, hostId, productId) {
62
+ var _data, _data_meta, _data_variants;
63
+ const data = (_data = (await metaDoc(firestore, hostId, `p.${productId}`).get()).data()) != null ? _data : {};
64
+ return {
65
+ sku: typeof data['sku'] === 'string' ? data['sku'] : '',
66
+ meta: (_data_meta = data['meta']) != null ? _data_meta : {},
67
+ variants: (_data_variants = data['variants']) != null ? _data_variants : {}
68
+ };
69
+ }
70
+ export async function readProductMetas(firestore, hostId, productIds) {
71
+ const out = new Map();
72
+ if (!productIds.length) return out;
73
+ const snaps = await firestore.getAll(...productIds.map((id)=>metaDoc(firestore, hostId, `p.${id}`)));
74
+ snaps.forEach((snap, index)=>{
75
+ var _snap_data, _data_meta, _data_variants;
76
+ const data = (_snap_data = snap.data()) != null ? _snap_data : {};
77
+ out.set(productIds[index], {
78
+ sku: typeof data['sku'] === 'string' ? data['sku'] : '',
79
+ meta: (_data_meta = data['meta']) != null ? _data_meta : {},
80
+ variants: (_data_variants = data['variants']) != null ? _data_variants : {}
81
+ });
82
+ });
83
+ return out;
84
+ }
85
+ export async function writeProductMeta(firestore, hostId, productId, next) {
86
+ await metaDoc(firestore, hostId, `p.${productId}`).set(next);
87
+ }
88
+ export async function readOrderMeta(firestore, hostId, orderId) {
89
+ var _data, _data_meta;
90
+ const data = (_data = (await metaDoc(firestore, hostId, `o.${orderId}`).get()).data()) != null ? _data : {};
91
+ return {
92
+ meta: (_data_meta = data['meta']) != null ? _data_meta : {},
93
+ notes: Array.isArray(data['notes']) ? data['notes'] : []
94
+ };
95
+ }
96
+ export async function readOrderMetas(firestore, hostId, orderIds) {
97
+ const out = new Map();
98
+ if (!orderIds.length) return out;
99
+ const snaps = await firestore.getAll(...orderIds.map((id)=>metaDoc(firestore, hostId, `o.${id}`)));
100
+ snaps.forEach((snap, index)=>{
101
+ var _snap_data, _data_meta;
102
+ const data = (_snap_data = snap.data()) != null ? _snap_data : {};
103
+ out.set(orderIds[index], {
104
+ meta: (_data_meta = data['meta']) != null ? _data_meta : {},
105
+ notes: Array.isArray(data['notes']) ? data['notes'] : []
106
+ });
107
+ });
108
+ return out;
109
+ }
110
+ export async function writeOrderMeta(firestore, hostId, orderId, next) {
111
+ await metaDoc(firestore, hostId, `o.${orderId}`).set({
112
+ meta: next.meta,
113
+ notes: next.notes.slice(-MAX_NOTES)
114
+ });
115
+ }
116
+ export async function readWebhooks(firestore, hostId) {
117
+ var _data;
118
+ const data = (_data = (await metaDoc(firestore, hostId, 'webhooks').get()).data()) != null ? _data : {};
119
+ return Array.isArray(data['list']) ? data['list'] : [];
120
+ }
121
+ export async function writeWebhooks(firestore, hostId, list) {
122
+ await metaDoc(firestore, hostId, 'webhooks').set({
123
+ list: list.slice(-50)
124
+ });
125
+ }
126
+
127
+ //# sourceMappingURL=woo-meta.js.map