@shophost/rest-api 2.0.34 → 2.0.36

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 (220) hide show
  1. package/LICENSE +17 -13
  2. package/README.md +76 -66
  3. package/package.json +2 -2
  4. package/scripts/minify-dist.mjs +45 -0
  5. package/src/app.js +1 -53
  6. package/src/app.js.map +1 -1
  7. package/src/core/auth/auth.schema.js +1 -41
  8. package/src/core/auth/auth.util.js +1 -44
  9. package/src/core/auth/better-auth.lib.js +1 -100
  10. package/src/core/auth/generate-password-hash.util.js +1 -30
  11. package/src/core/auth/headers.schema.js +1 -22
  12. package/src/core/auth/user.schema.js +1 -30
  13. package/src/core/db/__generated__/client/browser.js +1 -18
  14. package/src/core/db/__generated__/client/client.js +1 -35
  15. package/src/core/db/__generated__/client/commonInputTypes.js +1 -11
  16. package/src/core/db/__generated__/client/enums.js +1 -200
  17. package/src/core/db/__generated__/client/internal/class.js +769 -55
  18. package/src/core/db/__generated__/client/internal/prismaNamespace.d.ts +2 -2
  19. package/src/core/db/__generated__/client/internal/prismaNamespace.js +1 -541
  20. package/src/core/db/__generated__/client/internal/prismaNamespaceBrowser.js +1 -512
  21. package/src/core/db/__generated__/client/models/Account.d.ts +0 -5
  22. package/src/core/db/__generated__/client/models/Account.js +1 -2
  23. package/src/core/db/__generated__/client/models/Address.d.ts +0 -5
  24. package/src/core/db/__generated__/client/models/Address.js +1 -2
  25. package/src/core/db/__generated__/client/models/Campaign.d.ts +0 -5
  26. package/src/core/db/__generated__/client/models/Campaign.js +1 -2
  27. package/src/core/db/__generated__/client/models/ClosingTimes.d.ts +0 -5
  28. package/src/core/db/__generated__/client/models/ClosingTimes.js +1 -2
  29. package/src/core/db/__generated__/client/models/File.d.ts +0 -5
  30. package/src/core/db/__generated__/client/models/File.js +1 -2
  31. package/src/core/db/__generated__/client/models/Invitation.d.ts +0 -5
  32. package/src/core/db/__generated__/client/models/Invitation.js +1 -2
  33. package/src/core/db/__generated__/client/models/LegalEntity.d.ts +0 -5
  34. package/src/core/db/__generated__/client/models/LegalEntity.js +1 -2
  35. package/src/core/db/__generated__/client/models/Manufacturer.d.ts +0 -5
  36. package/src/core/db/__generated__/client/models/Manufacturer.js +1 -2
  37. package/src/core/db/__generated__/client/models/ManufacturerTranslation.d.ts +0 -5
  38. package/src/core/db/__generated__/client/models/ManufacturerTranslation.js +1 -2
  39. package/src/core/db/__generated__/client/models/Member.d.ts +0 -5
  40. package/src/core/db/__generated__/client/models/Member.js +1 -2
  41. package/src/core/db/__generated__/client/models/Modifier.d.ts +0 -5
  42. package/src/core/db/__generated__/client/models/Modifier.js +1 -2
  43. package/src/core/db/__generated__/client/models/ModifierGroup.d.ts +0 -5
  44. package/src/core/db/__generated__/client/models/ModifierGroup.js +1 -2
  45. package/src/core/db/__generated__/client/models/ModifierGroupTranslation.d.ts +0 -5
  46. package/src/core/db/__generated__/client/models/ModifierGroupTranslation.js +1 -2
  47. package/src/core/db/__generated__/client/models/OpeningTimes.d.ts +0 -5
  48. package/src/core/db/__generated__/client/models/OpeningTimes.js +1 -2
  49. package/src/core/db/__generated__/client/models/Order.d.ts +0 -5
  50. package/src/core/db/__generated__/client/models/Order.js +1 -2
  51. package/src/core/db/__generated__/client/models/OrderItem.d.ts +0 -5
  52. package/src/core/db/__generated__/client/models/OrderItem.js +1 -2
  53. package/src/core/db/__generated__/client/models/OrderItemTranslation.d.ts +0 -5
  54. package/src/core/db/__generated__/client/models/OrderItemTranslation.js +1 -2
  55. package/src/core/db/__generated__/client/models/Organization.d.ts +0 -5
  56. package/src/core/db/__generated__/client/models/Organization.js +1 -2
  57. package/src/core/db/__generated__/client/models/OrganizationConfiguration.d.ts +0 -5
  58. package/src/core/db/__generated__/client/models/OrganizationConfiguration.js +1 -2
  59. package/src/core/db/__generated__/client/models/Payment.d.ts +0 -5
  60. package/src/core/db/__generated__/client/models/Payment.js +1 -2
  61. package/src/core/db/__generated__/client/models/PaymentSession.d.ts +0 -5
  62. package/src/core/db/__generated__/client/models/PaymentSession.js +1 -2
  63. package/src/core/db/__generated__/client/models/Product.d.ts +0 -5
  64. package/src/core/db/__generated__/client/models/Product.js +1 -2
  65. package/src/core/db/__generated__/client/models/ProductCategory.d.ts +0 -5
  66. package/src/core/db/__generated__/client/models/ProductCategory.js +1 -2
  67. package/src/core/db/__generated__/client/models/ProductCategoryTranslation.d.ts +0 -5
  68. package/src/core/db/__generated__/client/models/ProductCategoryTranslation.js +1 -2
  69. package/src/core/db/__generated__/client/models/ProductSnapshot.d.ts +0 -5
  70. package/src/core/db/__generated__/client/models/ProductSnapshot.js +1 -2
  71. package/src/core/db/__generated__/client/models/ProductTranslation.d.ts +0 -5
  72. package/src/core/db/__generated__/client/models/ProductTranslation.js +1 -2
  73. package/src/core/db/__generated__/client/models/Reservation.d.ts +0 -5
  74. package/src/core/db/__generated__/client/models/Reservation.js +1 -2
  75. package/src/core/db/__generated__/client/models/Session.d.ts +0 -5
  76. package/src/core/db/__generated__/client/models/Session.js +1 -2
  77. package/src/core/db/__generated__/client/models/ShippingMethod.d.ts +0 -5
  78. package/src/core/db/__generated__/client/models/ShippingMethod.js +1 -2
  79. package/src/core/db/__generated__/client/models/ShippingZone.d.ts +0 -5
  80. package/src/core/db/__generated__/client/models/ShippingZone.js +1 -2
  81. package/src/core/db/__generated__/client/models/User.d.ts +0 -5
  82. package/src/core/db/__generated__/client/models/User.js +1 -2
  83. package/src/core/db/__generated__/client/models/Verification.d.ts +0 -5
  84. package/src/core/db/__generated__/client/models/Verification.js +1 -2
  85. package/src/core/db/__generated__/client/models.js +1 -2
  86. package/src/core/db/index.js +1 -2
  87. package/src/core/email/components.d.ts +16 -0
  88. package/src/core/email/components.js +1 -0
  89. package/src/core/email/components.js.map +1 -0
  90. package/src/core/exceptions/http-exception.js +1 -9
  91. package/src/core/hono/hono.js +1 -123
  92. package/src/core/lib/prisma.d.ts +8 -8
  93. package/src/core/lib/prisma.js +1 -11
  94. package/src/core/logging/pino.js +1 -5
  95. package/src/core/notifications/email.service.js +1 -116
  96. package/src/core/openapi/openapi.lib.js +1 -26
  97. package/src/core/types/google-maps.types.js +1 -2
  98. package/src/core/utils/currency.util.js +1 -11
  99. package/src/core/utils/env.util.js +1 -8
  100. package/src/core/utils/object.util.js +1 -39
  101. package/src/core/utils/translations.util.js +0 -1
  102. package/src/core/utils/zod.util.js +1 -85
  103. package/src/db.js +1 -3
  104. package/src/features/access/access.handler.js +1 -91
  105. package/src/features/access/access.route.js +1 -220
  106. package/src/features/access/access.schema.js +1 -108
  107. package/src/features/access/access.service.js +1 -294
  108. package/src/features/analytics/analytics.handler.d.ts +2 -0
  109. package/src/features/analytics/analytics.handler.js +1 -0
  110. package/src/features/analytics/analytics.handler.js.map +1 -0
  111. package/src/features/analytics/analytics.route.d.ts +3 -0
  112. package/src/features/analytics/analytics.route.js +1 -0
  113. package/src/features/analytics/analytics.route.js.map +1 -0
  114. package/src/features/analytics/analytics.schema.d.ts +86 -0
  115. package/src/features/analytics/analytics.schema.js +1 -0
  116. package/src/features/analytics/analytics.schema.js.map +1 -0
  117. package/src/features/analytics/analytics.service.d.ts +45 -0
  118. package/src/features/analytics/analytics.service.js +1 -0
  119. package/src/features/analytics/analytics.service.js.map +1 -0
  120. package/src/features/cart/cart.handler.js +1 -17
  121. package/src/features/cart/cart.route.js +1 -32
  122. package/src/features/cart/cart.schema.d.ts +1 -1
  123. package/src/features/cart/cart.schema.js +1 -39
  124. package/src/features/cart/cart.service.d.ts +1 -1
  125. package/src/features/cart/cart.service.js +1 -97
  126. package/src/features/cart/cart.util.js +1 -76
  127. package/src/features/file/file.handler.js +1 -23
  128. package/src/features/file/file.route.js +1 -34
  129. package/src/features/file/file.schema.js +1 -77
  130. package/src/features/file/file.service.js +1 -66
  131. package/src/features/health/health.handler.js +1 -10
  132. package/src/features/health/health.route.js +1 -25
  133. package/src/features/index.d.ts +1 -0
  134. package/src/features/index.js +1 -16
  135. package/src/features/index.js.map +1 -1
  136. package/src/features/location/location.handler.js +1 -25
  137. package/src/features/location/location.route.js +1 -56
  138. package/src/features/location/location.schema.js +1 -50
  139. package/src/features/location/location.service.js +1 -141
  140. package/src/features/manufacturer/manufacturer.handler.js +1 -53
  141. package/src/features/manufacturer/manufacturer.route.js +1 -97
  142. package/src/features/manufacturer/manufacturer.schema.js +1 -125
  143. package/src/features/manufacturer/manufacturer.service.js +1 -190
  144. package/src/features/order/emails/order-confirmation.email.js +1 -229
  145. package/src/features/order/emails/order-confirmation.email.js.map +1 -1
  146. package/src/features/order/emails/order-notification.email.js +1 -229
  147. package/src/features/order/emails/order-notification.email.js.map +1 -1
  148. package/src/features/order/fulfilment.schema.js +1 -3
  149. package/src/features/order/order.handler.js +1 -54
  150. package/src/features/order/order.route.js +1 -111
  151. package/src/features/order/order.schema.d.ts +4 -4
  152. package/src/features/order/order.schema.js +1 -158
  153. package/src/features/order/order.service.d.ts +4 -4
  154. package/src/features/order/order.service.js +1 -306
  155. package/src/features/order/recipient.schema.js +1 -38
  156. package/src/features/organization/legal-entity.schema.js +1 -83
  157. package/src/features/organization/organization-configuration.schema.js +1 -115
  158. package/src/features/organization/organization.handler.js +1 -48
  159. package/src/features/organization/organization.route.js +1 -84
  160. package/src/features/organization/organization.schema.js +1 -64
  161. package/src/features/organization/organization.service.js +1 -334
  162. package/src/features/payment/payment.handler.js +1 -16
  163. package/src/features/payment/payment.route.js +1 -22
  164. package/src/features/payment/payment.schema.d.ts +3 -3
  165. package/src/features/payment/payment.schema.js +1 -46
  166. package/src/features/payment/payment.service.d.ts +1 -1
  167. package/src/features/payment/payment.service.js +1 -100
  168. package/src/features/payment/stripe.service.js +1 -164
  169. package/src/features/product/product-modifier.schema.js +1 -84
  170. package/src/features/product/product.handler.js +1 -87
  171. package/src/features/product/product.route.js +1 -179
  172. package/src/features/product/product.schema.d.ts +3 -3
  173. package/src/features/product/product.schema.js +1 -143
  174. package/src/features/product/product.service.d.ts +2 -2
  175. package/src/features/product/product.service.js +1 -440
  176. package/src/features/product-category/product-category.handler.js +1 -59
  177. package/src/features/product-category/product-category.route.js +1 -139
  178. package/src/features/product-category/product-category.schema.js +1 -86
  179. package/src/features/product-category/product-category.service.js +1 -220
  180. package/src/features/reservation/emails/reservation-cancellation.email.js +1 -82
  181. package/src/features/reservation/emails/reservation-cancellation.email.js.map +1 -1
  182. package/src/features/reservation/emails/reservation-confirmation.email.js +1 -82
  183. package/src/features/reservation/emails/reservation-confirmation.email.js.map +1 -1
  184. package/src/features/reservation/emails/reservation-notification.email.js +1 -93
  185. package/src/features/reservation/emails/reservation-notification.email.js.map +1 -1
  186. package/src/features/reservation/reservation.handler.js +1 -65
  187. package/src/features/reservation/reservation.route.js +1 -167
  188. package/src/features/reservation/reservation.schema.d.ts +1 -1
  189. package/src/features/reservation/reservation.schema.js +1 -51
  190. package/src/features/reservation/reservation.service.js +1 -231
  191. package/src/features/shipping/shipping.handler.js +1 -32
  192. package/src/features/shipping/shipping.route.js +1 -51
  193. package/src/features/shipping/shipping.service.js +1 -96
  194. package/src/features/shipping-method/shipping-method.handler.js +1 -60
  195. package/src/features/shipping-method/shipping-method.route.js +1 -144
  196. package/src/features/shipping-method/shipping-method.schema.js +1 -48
  197. package/src/features/shipping-method/shipping-method.service.js +1 -229
  198. package/src/features/shipping-method/shipping-zone.schema.js +1 -31
  199. package/src/features/webhook/webhook.handler.js +1 -50
  200. package/src/features/webhook/webhook.route.js +1 -33
  201. package/src/index.js +1 -6
  202. package/src/integrations/next.js +1 -82
  203. package/src/schemas/address.schema.js +1 -112
  204. package/src/schemas/currency.schema.js +1 -118
  205. package/src/schemas/error.schema.js +1 -12
  206. package/src/schemas/index.d.ts +1 -0
  207. package/src/schemas/index.js +1 -29
  208. package/src/schemas/index.js.map +1 -1
  209. package/src/schemas/locales.schema.js +1 -238
  210. package/src/schemas/number.schema.js +1 -29
  211. package/src/schemas/pagination.schema.js +1 -54
  212. package/src/schemas/params.schema.js +1 -20
  213. package/src/schemas/queries.schema.js +1 -6
  214. package/src/test/global-setup.js +1 -37
  215. package/src/test/integration/api-fixtures.js +1 -160
  216. package/src/test/integration/seed.js +1 -368
  217. package/src/test/integration/test-helpers.d.ts +2 -0
  218. package/src/test/integration/test-helpers.js +1 -154
  219. package/src/test/integration/test-helpers.js.map +1 -1
  220. package/src/test/setup-test-env.js +1 -7
package/LICENSE CHANGED
@@ -1,17 +1,21 @@
1
- Copyright (c) 2024 Shophost. All rights reserved.
1
+ MIT License
2
2
 
3
- PROPRIETARY SOFTWARE LICENSE
3
+ Copyright (c) 2026 Abhishek Shaji
4
4
 
5
- This software and associated documentation files (the "Software") are the proprietary and confidential information of Shophost ("Company"). The Software is licensed, not sold.
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:
6
11
 
7
- RESTRICTIONS:
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
8
14
 
9
- - You may NOT use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software without explicit written permission from Shophost.
10
- - You may NOT reverse engineer, decompile, or disassemble the Software.
11
- - This Software is provided for evaluation purposes only.
12
-
13
- UNAUTHORIZED USE IS STRICTLY PROHIBITED.
14
-
15
- For licensing inquiries, please contact: [kontakt@abhishek.pl]
16
-
17
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
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,114 +1,124 @@
1
1
  # @shophost/rest-api
2
2
 
3
- A comprehensive REST API package for Shophost with TypeScript support.
3
+ `@shophost/rest-api` is the backend package for ShopHost. It provides:
4
+
5
+ - the core API app builder
6
+ - a Next.js route handler integration
7
+ - exported Zod/OpenAPI schemas
8
+ - a packaged Prisma schema and CLI for database sync
4
9
 
5
10
  ## Installation
6
11
 
7
12
  ```bash
8
- npm install @shophost/rest-api
9
- # or
10
- pnpm add @shophost/rest-api
11
- # or
12
- yarn add @shophost/rest-api
13
+ pnpm add @shophost/rest-api prisma @prisma/client @prisma/client-runtime-utils
13
14
  ```
14
15
 
15
- **⚠️ IMPORTANT LEGAL NOTICE:** This package is publicly available for download but is **proprietary software**. Installation and use requires explicit permission from Shophost. See the [License](#license) section below for details.
16
-
17
- ## Exports
16
+ Peer dependencies:
18
17
 
19
- This package provides 4 main entry points:
18
+ - `next >= 14`
19
+ - `react >= 18`
20
+ - `react-dom >= 18`
20
21
 
21
- ### 1. Main API (`@shophost/rest-api`)
22
+ ## Entry Points
22
23
 
23
- ```typescript
24
- import "@shophost/rest-api";
25
- ```
24
+ - `@shophost/rest-api`
25
+ Exposes `buildApiApp`, `generateOpenApiSpec`, and schema exports.
26
+ - `@shophost/rest-api/next`
27
+ Exposes `createNextHandler` for Next.js App Router route handlers.
28
+ - `@shophost/rest-api/db`
29
+ Exposes packaged Prisma client helpers.
30
+ - `@shophost/rest-api/schemas`
31
+ Exposes reusable request/response schemas.
26
32
 
27
- ### 2. Generated client (`@shophost/client`)
28
-
29
- ```typescript
30
- import { initClient } from "@shophost/client";
31
- ```
33
+ ## Next.js Usage
32
34
 
33
- ### 3. Next.js integration (`@shophost/rest-api/next`)
35
+ Create an App Router API route:
34
36
 
35
- ```typescript
37
+ ```ts
36
38
  import { createNextHandler } from "@shophost/rest-api/next";
37
- ```
38
-
39
- ### 4. Schemas (`@shophost/rest-api/schemas`)
40
39
 
41
- ```typescript
42
- import { ManufacturerSchema } from "@shophost/rest-api/schemas";
40
+ const handler = createNextHandler({
41
+ database: {
42
+ connectionString: process.env.DATABASE_URL!,
43
+ log: ["info", "warn", "error"],
44
+ },
45
+ maps: {
46
+ google: {
47
+ key: process.env.GOOGLE_PLACES_API_KEY!,
48
+ },
49
+ },
50
+ auth: {
51
+ baseURL: process.env.NEXT_PUBLIC_API_BASE_URL!,
52
+ domain: new URL(process.env.NEXT_PUBLIC_API_BASE_URL!).hostname.split(".").slice(-2).join("."),
53
+ trustedOrigins: [process.env.NEXT_PUBLIC_APP_DOMAIN!],
54
+ socialProviders: {
55
+ google: {
56
+ clientId: process.env.AUTH_GOOGLE_ID!,
57
+ clientSecret: process.env.AUTH_GOOGLE_SECRET!,
58
+ },
59
+ },
60
+ },
61
+ payment: {
62
+ stripe: {
63
+ secretKey: process.env.STRIPE_SECRET_KEY!,
64
+ webhookSecret: process.env.STRIPE_WEBHOOK_SECRET!,
65
+ resendApiKey: process.env.RESEND_API_KEY!,
66
+ paymentMethods: ["card", "blik"],
67
+ },
68
+ },
69
+ });
70
+
71
+ export { handler as GET, handler as POST, handler as PUT, handler as PATCH, handler as DELETE, handler as OPTIONS };
43
72
  ```
44
73
 
45
74
  ## Database Schema Sync
46
75
 
47
- The published package includes a CLI so a fresh project can push the packaged Prisma schema to its own database without copying `schema.prisma` into the app.
76
+ The published package ships the Prisma schema and a CLI so a consuming app can
77
+ push the schema without copying Prisma files into the host project.
48
78
 
49
- 1. Add your database URL to one of these places in the consuming app:
50
- - `.env.local`
51
- - `.env`
52
- - the shell environment
53
- 2. Use one of these variables:
54
- - `DATABASE_URL`
55
- - `DATABASE_URL`
56
- 3. Run:
79
+ 1. Set `DATABASE_URL` in `.env.local`, `.env`, or your shell.
80
+ 2. Run:
57
81
 
58
82
  ```bash
59
83
  pnpm exec shophost-rest-api db push
60
- # or
61
- npx shophost-rest-api db push
62
84
  ```
63
85
 
64
- Example:
65
-
66
- ```env
67
- # .env.local
68
- DATABASE_URL=postgresql://user:password@host:5432/dbname?sslmode=require
69
- ```
70
-
71
- You can pass regular Prisma `db push` flags through as well:
86
+ You can also pass standard Prisma flags through:
72
87
 
73
88
  ```bash
74
89
  pnpm exec shophost-rest-api db push --accept-data-loss
75
90
  pnpm exec shophost-rest-api db push --url "postgresql://user:password@host:5432/dbname?sslmode=require"
76
91
  ```
77
92
 
78
- Notes:
79
-
80
- - `.env.local` overrides `.env`
81
- - `DATABASE_URL` takes precedence over `DATABASE_URL`
82
- - the CLI uses the `schema.prisma` and `prisma.config.ts` shipped inside `@shophost/rest-api`
93
+ ## Schemas and Utilities
83
94
 
84
- ## Development
95
+ Import shared schemas:
85
96
 
86
- To build this package:
87
-
88
- ```bash
89
- nx build rest-api
97
+ ```ts
98
+ import { CreateProductSchema, ProductSchema } from "@shophost/rest-api/schemas";
90
99
  ```
91
100
 
92
- To regenerate the OpenAPI document and frontend client:
101
+ Import Prisma helpers owned by this package:
93
102
 
94
- ```bash
95
- pnpm run client:generate
103
+ ```ts
104
+ import { createPrismaClient, PrismaClient } from "@shophost/rest-api/db";
96
105
  ```
97
106
 
98
- To publish (dry-run):
107
+ Generate the OpenAPI document:
99
108
 
100
- ```bash
101
- nx npm:publish:dry-run rest-api
109
+ ```ts
110
+ import { generateOpenApiSpec } from "@shophost/rest-api";
111
+
112
+ const spec = generateOpenApiSpec();
102
113
  ```
103
114
 
104
- To publish:
115
+ ## Local Development
105
116
 
106
117
  ```bash
107
- nx npm:publish rest-api
118
+ pnpm exec nx run rest-api:prisma:generate
119
+ pnpm exec nx run rest-api:test
108
120
  ```
109
121
 
110
122
  ## License
111
123
 
112
- Proprietary - All Rights Reserved
113
-
114
- This software is proprietary and confidential. Unauthorized copying, distribution, or use is strictly prohibited. For licensing inquiries, please contact Shophost.
124
+ MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shophost/rest-api",
3
- "version": "2.0.34",
3
+ "version": "2.0.36",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "shophost-rest-api": "./scripts/shophost-rest-api.mjs"
@@ -56,7 +56,7 @@
56
56
  "typescript"
57
57
  ],
58
58
  "author": "Abhishek Shaji (kontakt@abhishek.pl)",
59
- "license": "UNLICENSED",
59
+ "license": "MIT",
60
60
  "repository": {
61
61
  "type": "git",
62
62
  "url": "https://github.com/abhishek-shaji/shophost",
@@ -0,0 +1,45 @@
1
+ import { transform } from "esbuild";
2
+ import { readdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ const distRoot = path.resolve("dist/packages/rest-api/src");
6
+ let count = 0;
7
+ let savedBytes = 0;
8
+
9
+ async function walk(dir) {
10
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
11
+ const full = path.join(dir, entry.name);
12
+ if (entry.isDirectory()) {
13
+ await walk(full);
14
+ continue;
15
+ }
16
+ if (!entry.name.endsWith(".js")) continue;
17
+
18
+ const source = readFileSync(full, "utf8");
19
+
20
+ // Preserve "use client" / "use server" directives
21
+ const directiveMatch = source.match(
22
+ /^(?:["']use (?:client|server)["'];?\s*\n?)+/
23
+ );
24
+ const directive = directiveMatch ? directiveMatch[0].trim() + "\n" : "";
25
+ const code = directive
26
+ ? source.slice(directiveMatch[0].length)
27
+ : source;
28
+
29
+ const result = await transform(code, {
30
+ minify: true,
31
+ loader: "js",
32
+ target: "es2020",
33
+ });
34
+
35
+ const output = directive + result.code;
36
+ savedBytes += source.length - output.length;
37
+ writeFileSync(full, output);
38
+ count++;
39
+ }
40
+ }
41
+
42
+ await walk(distRoot);
43
+ console.log(
44
+ `✓ Minified ${count} files (saved ${(savedBytes / 1024).toFixed(0)} KB)`
45
+ );
package/src/app.js CHANGED
@@ -1,53 +1 @@
1
- import { __awaiter } from "tslib";
2
- import { cors } from "hono/cors";
3
- import { createApiRouter, createUnavailableAuth, handleAppError, } from "./core/hono/hono";
4
- import { buildAccessHandler, buildCartHandler, buildFileHandler, buildHealthHandler, buildLocationHandler, buildManufacturerHandler, buildOrderHandler, buildOrganizationHandler, buildPaymentHandler, buildProductCategoryHandler, buildProductHandler, buildReservationHandler, buildShippingHandler, buildShippingMethodHandler, buildWebhookHandler, } from "./features";
5
- const defaultCorsOptions = {
6
- allowHeaders: [
7
- "Content-Type",
8
- "Authorization",
9
- "X-Requested-With",
10
- "Accept",
11
- "Origin",
12
- "X-CSRF-Token",
13
- ],
14
- allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"],
15
- credentials: true,
16
- exposeHeaders: ["Content-Length", "X-Kuma-Revision"],
17
- origin: ["http://localhost:3000"],
18
- };
19
- export const buildApiApp = ({ corsOptions, maps, payment, prisma, resolveAuth = () => createUnavailableAuth(), } = {}) => {
20
- var _a, _b, _c, _d, _e;
21
- const app = createApiRouter();
22
- // cors
23
- app.use("*", cors(Object.assign(Object.assign({}, defaultCorsOptions), corsOptions)));
24
- // auth
25
- app.use("*", (c, next) => __awaiter(void 0, void 0, void 0, function* () {
26
- const auth = resolveAuth(c.req.raw, c.req.path);
27
- c.set("auth", auth);
28
- Object.assign(c.req.raw, { auth });
29
- yield next();
30
- }));
31
- // error handler
32
- app.onError((error) => handleAppError(error));
33
- // routes
34
- app.route("/", buildHealthHandler());
35
- app.route("/", buildManufacturerHandler(prisma));
36
- app.route("/", buildOrganizationHandler(prisma, (_b = (_a = maps === null || maps === void 0 ? void 0 : maps.google) === null || _a === void 0 ? void 0 : _a.key) !== null && _b !== void 0 ? _b : ""));
37
- app.route("/", buildFileHandler(prisma));
38
- app.route("/", buildProductCategoryHandler(prisma));
39
- app.route("/", buildProductHandler(prisma));
40
- app.route("/", buildAccessHandler(prisma));
41
- app.route("/", buildShippingMethodHandler(prisma));
42
- app.route("/", buildOrderHandler(prisma, payment !== null && payment !== void 0 ? payment : {}));
43
- app.route("/", buildCartHandler(prisma));
44
- app.route("/", buildShippingHandler(prisma, (_d = (_c = maps === null || maps === void 0 ? void 0 : maps.google) === null || _c === void 0 ? void 0 : _c.key) !== null && _d !== void 0 ? _d : ""));
45
- app.route("/", buildLocationHandler(maps !== null && maps !== void 0 ? maps : {}));
46
- app.route("/", buildPaymentHandler(prisma, payment !== null && payment !== void 0 ? payment : {}));
47
- app.route("/", buildWebhookHandler(prisma, payment !== null && payment !== void 0 ? payment : {}));
48
- if ((_e = payment === null || payment === void 0 ? void 0 : payment.stripe) === null || _e === void 0 ? void 0 : _e.resendApiKey) {
49
- app.route("/", buildReservationHandler(prisma, payment.stripe.resendApiKey));
50
- }
51
- return app;
52
- };
53
- //# sourceMappingURL=app.js.map
1
+ import{__awaiter as h}from"tslib";import{cors as g}from"hono/cors";import{createApiRouter as A,createUnavailableAuth as s,handleAppError as O}from"./core/hono/hono";import{buildAccessHandler as f,buildAnalyticsHandler as T,buildCartHandler as C,buildFileHandler as P,buildHealthHandler as _,buildLocationHandler as E,buildManufacturerHandler as w,buildOrderHandler as R,buildOrganizationHandler as S,buildPaymentHandler as k,buildProductCategoryHandler as q,buildProductHandler as j,buildReservationHandler as K,buildShippingHandler as L,buildShippingMethodHandler as M,buildWebhookHandler as X}from"./features";const x={allowHeaders:["Content-Type","Authorization","X-Requested-With","Accept","Origin","X-CSRF-Token"],allowMethods:["GET","POST","PUT","DELETE","OPTIONS","PATCH"],credentials:!0,exposeHeaders:["Content-Length","X-Kuma-Revision"],origin:["http://localhost:3000"]};export const buildApiApp=({corsOptions:a,maps:d,payment:l,prisma:o,resolveAuth:c=()=>s()}={})=>{var i,u,t,n,v;const e=A();return e.use("*",g(Object.assign(Object.assign({},x),a))),e.use("*",(r,H)=>h(void 0,void 0,void 0,function*(){const b=c(r.req.raw,r.req.path);r.set("auth",b),Object.assign(r.req.raw,{auth:b}),yield H()})),e.onError(r=>O(r)),e.route("/",_()),e.route("/",T(o)),e.route("/",w(o)),e.route("/",S(o,(u=(i=d?.google)===null||i===void 0?void 0:i.key)!==null&&u!==void 0?u:"")),e.route("/",P(o)),e.route("/",q(o)),e.route("/",j(o)),e.route("/",f(o)),e.route("/",M(o)),e.route("/",R(o,l??{})),e.route("/",C(o)),e.route("/",L(o,(n=(t=d?.google)===null||t===void 0?void 0:t.key)!==null&&n!==void 0?n:"")),e.route("/",E(d??{})),e.route("/",k(o,l??{})),e.route("/",X(o,l??{})),!((v=l?.stripe)===null||v===void 0)&&v.resendApiKey&&e.route("/",K(o,l.stripe.resendApiKey)),e};
package/src/app.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"app.js","sourceRoot":"","sources":["../../../../packages/rest-api/src/app.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAEL,eAAe,EACf,qBAAqB,EACrB,cAAc,GACf,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,EAClB,oBAAoB,EACpB,wBAAwB,EACxB,iBAAiB,EACjB,wBAAwB,EACxB,mBAAmB,EACnB,2BAA2B,EAC3B,mBAAmB,EACnB,uBAAuB,EACvB,oBAAoB,EACpB,0BAA0B,EAC1B,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAGpB,MAAM,kBAAkB,GAAG;IACzB,YAAY,EAAE;QACZ,cAAc;QACd,eAAe;QACf,kBAAkB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AE,MAAM,0CAAE,YAAY,EAAE,CAAC;QAClC,GAAG,CAAC,KAAK,CACP,GAAG,EACH,uBAAuB,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,YAAY,CAAC,CAC7D,CAAC;IACJ,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC,CAAC"}
@@ -1,41 +1 @@
1
- import { z } from "@hono/zod-openapi";
2
- export const SignUpSchema = z.object({
3
- email: z
4
- .string()
5
- .min(1, "Email is required")
6
- .email("Invalid email")
7
- .openapi({
8
- example: "user@example.com",
9
- description: "User's email address",
10
- }),
11
- password: z
12
- .string()
13
- .min(1, "Password is required")
14
- .min(8, "Password must be more than 8 characters")
15
- .max(32, "Password must be less than 32 characters")
16
- .openapi({
17
- example: "password123",
18
- description: "User's password",
19
- }),
20
- firstname: z
21
- .string()
22
- .min(1, "First name is required")
23
- .max(32, "First name must be less than 32 characters")
24
- .openapi({
25
- example: "John",
26
- description: "User's first name",
27
- }),
28
- lastname: z
29
- .string()
30
- .min(1, "Last name is required")
31
- .max(32, "Last name must be less than 32 characters")
32
- .openapi({
33
- example: "Doe",
34
- description: "User's last name",
35
- }),
36
- }).openapi("SignUp");
37
- export const SignInSchema = SignUpSchema.pick({
38
- email: true,
39
- password: true,
40
- }).openapi("SignIn");
41
- //# sourceMappingURL=auth.schema.js.map
1
+ import{z as e}from"@hono/zod-openapi";export const SignUpSchema=e.object({email:e.string().min(1,"Email is required").email("Invalid email").openapi({example:"user@example.com",description:"User's email address"}),password:e.string().min(1,"Password is required").min(8,"Password must be more than 8 characters").max(32,"Password must be less than 32 characters").openapi({example:"password123",description:"User's password"}),firstname:e.string().min(1,"First name is required").max(32,"First name must be less than 32 characters").openapi({example:"John",description:"User's first name"}),lastname:e.string().min(1,"Last name is required").max(32,"Last name must be less than 32 characters").openapi({example:"Doe",description:"User's last name"})}).openapi("SignUp"),SignInSchema=SignUpSchema.pick({email:!0,password:!0}).openapi("SignIn");
@@ -1,44 +1 @@
1
- import { __awaiter } from "tslib";
2
- import { HttpException } from "../exceptions/http-exception";
3
- import { logger } from "../logging/pino";
4
- export const getCurrentUser = (auth) => (headers) => __awaiter(void 0, void 0, void 0, function* () {
5
- const session = yield auth.api.getSession({
6
- headers: headers,
7
- });
8
- if (!(session === null || session === void 0 ? void 0 : session.user)) {
9
- throw new HttpException(401, "Unauthorized");
10
- }
11
- return session.user;
12
- });
13
- export const isGranted = (auth) => (headers, organizationId, accessLevel) => __awaiter(void 0, void 0, void 0, function* () {
14
- if (!accessLevel) {
15
- throw new Error("Resource and access level are required");
16
- }
17
- const session = yield auth.api.getSession({
18
- headers: headers,
19
- });
20
- if (!(session === null || session === void 0 ? void 0 : session.user)) {
21
- throw new HttpException(401, "Unauthorized");
22
- }
23
- const hasPermission = yield auth.api.hasPermission({
24
- headers,
25
- body: {
26
- organizationId,
27
- permissions: {
28
- project: [accessLevel],
29
- },
30
- },
31
- });
32
- if (!hasPermission.success) {
33
- logger.error({
34
- organizationId,
35
- accessLevel,
36
- message: "User does not have permission",
37
- userId: session.user.id,
38
- hasPermission,
39
- });
40
- throw new HttpException(403, "Forbidden");
41
- }
42
- return session.user;
43
- });
44
- //# sourceMappingURL=auth.util.js.map
1
+ import{__awaiter as d}from"tslib";import{HttpException as n}from"../exceptions/http-exception";import{logger as u}from"../logging/pino";export const getCurrentUser=r=>i=>d(void 0,void 0,void 0,function*(){const e=yield r.api.getSession({headers:i});if(!e?.user)throw new n(401,"Unauthorized");return e.user}),isGranted=r=>(i,e,s)=>d(void 0,void 0,void 0,function*(){if(!s)throw new Error("Resource and access level are required");const o=yield r.api.getSession({headers:i});if(!o?.user)throw new n(401,"Unauthorized");const t=yield r.api.hasPermission({headers:i,body:{organizationId:e,permissions:{project:[s]}}});if(!t.success)throw u.error({organizationId:e,accessLevel:s,message:"User does not have permission",userId:o.user.id,hasPermission:t}),new n(403,"Forbidden");return o.user});
@@ -1,100 +1 @@
1
- import { betterAuth } from "better-auth";
2
- import { prismaAdapter } from "better-auth/adapters/prisma";
3
- import { nextCookies } from "better-auth/next-js";
4
- import { openAPI, organization } from "better-auth/plugins";
5
- import { createAccessControl } from "better-auth/plugins/access";
6
- import { getCurrentUser, isGranted } from "./auth.util";
7
- const statement = {
8
- project: ["create", "read", "update", "delete"],
9
- organization: ["create", "read", "update", "delete"],
10
- };
11
- const ac = createAccessControl(statement);
12
- const readOnly = ac.newRole({
13
- project: ["read"],
14
- });
15
- const member = ac.newRole({
16
- project: ["read"],
17
- });
18
- const manager = ac.newRole({
19
- project: ["create", "read", "update", "delete"],
20
- });
21
- const admin = ac.newRole({
22
- project: ["create", "read", "update", "delete"],
23
- organization: ["update"],
24
- });
25
- const owner = ac.newRole({
26
- project: ["create", "read", "update", "delete"],
27
- organization: ["update", "delete"],
28
- });
29
- export const createAuthClient = ({ prisma, baseURL, domain, trustedOrigins, socialProviders, }) => {
30
- const auth = betterAuth({
31
- baseURL,
32
- database: prismaAdapter(prisma, {
33
- provider: "postgresql",
34
- }),
35
- trustedOrigins,
36
- user: {
37
- additionalFields: {
38
- firstname: {
39
- type: "string",
40
- required: true,
41
- },
42
- lastname: {
43
- type: "string",
44
- required: true,
45
- },
46
- },
47
- },
48
- advanced: {
49
- crossSubDomainCookies: {
50
- enabled: true,
51
- domain: domain,
52
- },
53
- useSecureCookies: domain !== "localhost",
54
- defaultCookieAttributes: {
55
- path: "/",
56
- sameSite: "lax", // Use "none" if you need cross-site requests, but requires secure: true
57
- httpOnly: true, // Prevents JavaScript access to cookies
58
- secure: domain !== "localhost",
59
- },
60
- },
61
- emailAndPassword: {
62
- enabled: true,
63
- },
64
- socialProviders: Object.assign({}, ((socialProviders === null || socialProviders === void 0 ? void 0 : socialProviders.google)
65
- ? {
66
- google: {
67
- prompt: "select_account",
68
- clientId: socialProviders.google.clientId,
69
- clientSecret: socialProviders.google.clientSecret,
70
- mapProfileToUser: (profile) => {
71
- return {
72
- firstname: profile.given_name,
73
- lastname: profile.family_name,
74
- };
75
- },
76
- },
77
- }
78
- : {})),
79
- plugins: [
80
- openAPI(),
81
- nextCookies(),
82
- organization({
83
- ac,
84
- roles: {
85
- member,
86
- readOnly,
87
- manager,
88
- admin,
89
- owner,
90
- },
91
- }),
92
- ],
93
- });
94
- return {
95
- auth,
96
- getCurrentUser: getCurrentUser(auth),
97
- isGranted: isGranted(auth),
98
- };
99
- };
100
- //# sourceMappingURL=better-auth.lib.js.map
1
+ import{betterAuth as l}from"better-auth";import{prismaAdapter as d}from"better-auth/adapters/prisma";import{nextCookies as c}from"better-auth/next-js";import{openAPI as p,organization as u}from"better-auth/plugins";import{createAccessControl as m}from"better-auth/plugins/access";import{getCurrentUser as g,isGranted as f}from"./auth.util";const b={project:["create","read","update","delete"],organization:["create","read","update","delete"]},e=m(b),C=e.newRole({project:["read"]}),h=e.newRole({project:["read"]}),j=e.newRole({project:["create","read","update","delete"]}),w=e.newRole({project:["create","read","update","delete"],organization:["update"]}),A=e.newRole({project:["create","read","update","delete"],organization:["update","delete"]});export const createAuthClient=({prisma:n,baseURL:s,domain:r,trustedOrigins:i,socialProviders:t})=>{const o=l({baseURL:s,database:d(n,{provider:"postgresql"}),trustedOrigins:i,user:{additionalFields:{firstname:{type:"string",required:!0},lastname:{type:"string",required:!0}}},advanced:{crossSubDomainCookies:{enabled:!0,domain:r},useSecureCookies:r!=="localhost",defaultCookieAttributes:{path:"/",sameSite:"lax",httpOnly:!0,secure:r!=="localhost"}},emailAndPassword:{enabled:!0},socialProviders:Object.assign({},t?.google?{google:{prompt:"select_account",clientId:t.google.clientId,clientSecret:t.google.clientSecret,mapProfileToUser:a=>({firstname:a.given_name,lastname:a.family_name})}}:{}),plugins:[p(),c(),u({ac:e,roles:{member:h,readOnly:C,manager:j,admin:w,owner:A}})]});return{auth:o,getCurrentUser:g(o),isGranted:f(o)}};
@@ -1,30 +1 @@
1
- import { __awaiter } from "tslib";
2
- import crypto from "crypto";
3
- /**
4
- * Generate a random salt using crypto.
5
- */
6
- function randomBytes() {
7
- return new Promise((resolve, reject) => crypto.randomBytes(32, (err, saltBuffer) => err ? reject(err) : resolve(saltBuffer)));
8
- }
9
- /**
10
- * Generate a hash using PBKDF2.
11
- */
12
- function pbkdf2Promisified(password, salt) {
13
- return new Promise((resolve, reject) => crypto.pbkdf2(password, salt, 25000, // Number of iterations
14
- 512, // Key length
15
- "sha256", // Digest algorithm
16
- (err, hashRaw) => (err ? reject(err) : resolve(hashRaw))));
17
- }
18
- /**
19
- * Generate a salt and hash for the password.
20
- */
21
- export function generatePasswordSaltHash(password) {
22
- return __awaiter(this, void 0, void 0, function* () {
23
- const saltBuffer = yield randomBytes();
24
- const salt = saltBuffer.toString("hex");
25
- const hashRaw = yield pbkdf2Promisified(password, salt);
26
- const hash = hashRaw.toString("hex");
27
- return { hash, salt };
28
- });
29
- }
30
- //# sourceMappingURL=generate-password-hash.util.js.map
1
+ import{__awaiter as a}from"tslib";import e from"crypto";function f(){return new Promise((o,n)=>e.randomBytes(32,(t,r)=>t?n(t):o(r)))}function h(o,n){return new Promise((t,r)=>e.pbkdf2(o,n,25e3,512,"sha256",(s,i)=>s?r(s):t(i)))}export function generatePasswordSaltHash(o){return a(this,void 0,void 0,function*(){const t=(yield f()).toString("hex");return{hash:(yield h(o,t)).toString("hex"),salt:t}})}
@@ -1,22 +1 @@
1
- import { z } from "@hono/zod-openapi";
2
- export const HeaderSchema = z
3
- .object({
4
- "accept-language": z.string().optional().openapi({
5
- example: "en-US",
6
- description: "Accept-Language header",
7
- param: {
8
- in: "header",
9
- name: "accept-language",
10
- },
11
- }),
12
- cookie: z.string().optional().openapi({
13
- example: "session=1234567890",
14
- description: "Cookie header",
15
- param: {
16
- in: "header",
17
- name: "cookie",
18
- },
19
- }),
20
- })
21
- .openapi("Headers");
22
- //# sourceMappingURL=headers.schema.js.map
1
+ import{z as e}from"@hono/zod-openapi";export const HeaderSchema=e.object({"accept-language":e.string().optional().openapi({example:"en-US",description:"Accept-Language header",param:{in:"header",name:"accept-language"}}),cookie:e.string().optional().openapi({example:"session=1234567890",description:"Cookie header",param:{in:"header",name:"cookie"}})}).openapi("Headers");
@@ -1,30 +1 @@
1
- import { z } from "@hono/zod-openapi";
2
- export const UserSchema = z
3
- .object({
4
- id: z.string().openapi({
5
- example: "clm1234567890abcdef",
6
- description: "User's ID",
7
- }),
8
- email: z.string().openapi({
9
- example: "user@example.com",
10
- description: "User's email address",
11
- format: "email",
12
- }),
13
- firstname: z.string().openapi({
14
- example: "John",
15
- description: "User's first name",
16
- }),
17
- lastname: z.string().openapi({
18
- example: "Doe",
19
- description: "User's last name",
20
- }),
21
- image: z.string().nullable().optional().openapi({
22
- example: "https://example.com/image.jpg",
23
- description: "User's profile image",
24
- }),
25
- name: z.string().nullable().optional().openapi({
26
- description: "User's full name (optional)",
27
- }),
28
- })
29
- .openapi("User");
30
- //# sourceMappingURL=user.schema.js.map
1
+ import{z as e}from"@hono/zod-openapi";export const UserSchema=e.object({id:e.string().openapi({example:"clm1234567890abcdef",description:"User's ID"}),email:e.string().openapi({example:"user@example.com",description:"User's email address",format:"email"}),firstname:e.string().openapi({example:"John",description:"User's first name"}),lastname:e.string().openapi({example:"Doe",description:"User's last name"}),image:e.string().nullable().optional().openapi({example:"https://example.com/image.jpg",description:"User's profile image"}),name:e.string().nullable().optional().openapi({description:"User's full name (optional)"})}).openapi("User");