@velastack/patterns 0.5.0 → 0.7.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 (152) hide show
  1. package/README.md +11 -0
  2. package/dist/chunks/{_layout-D-FzWqn0.js → _layout-Bsx3eNrC.js} +3 -3
  3. package/dist/chunks/{_layout-D-FzWqn0.js.map → _layout-Bsx3eNrC.js.map} +1 -1
  4. package/dist/chunks/{auth-pages-B52ei-4z.js → auth-pages-jsyDV1GR.js} +7 -10
  5. package/dist/chunks/{auth-pages-B52ei-4z.js.map → auth-pages-jsyDV1GR.js.map} +1 -1
  6. package/dist/chunks/collections-BrEA7a62.js +309 -0
  7. package/dist/chunks/collections-BrEA7a62.js.map +1 -0
  8. package/dist/chunks/{collections-Cpjo2OiQ.js → collections-DrUG8ngq.js} +39 -35
  9. package/dist/chunks/collections-DrUG8ngq.js.map +1 -0
  10. package/dist/chunks/{compose-handle-BDlZ7Pif.js → compose-handle-BBlamPfx.js} +18 -22
  11. package/dist/chunks/{compose-handle-BDlZ7Pif.js.map → compose-handle-BBlamPfx.js.map} +1 -1
  12. package/dist/chunks/{config-target-rHgjaA8u.js → config-target-BgyFkbFL.js} +2 -2
  13. package/dist/chunks/{config-target-rHgjaA8u.js.map → config-target-BgyFkbFL.js.map} +1 -1
  14. package/dist/chunks/{constants-Rq8SCXwH.js → constants-iej3WkEa.js} +3 -3
  15. package/dist/chunks/constants-iej3WkEa.js.map +1 -0
  16. package/dist/chunks/dedent-Gq6Krl4n.js.map +1 -1
  17. package/dist/chunks/{env-BPfk1VAw.js → env-BugddEjd.js} +5 -9
  18. package/dist/chunks/{env-BPfk1VAw.js.map → env-BugddEjd.js.map} +1 -1
  19. package/dist/chunks/{env-vars-Bj41Nccm.js → env-vars-CdarYsrc.js} +6 -11
  20. package/dist/chunks/{env-vars-Bj41Nccm.js.map → env-vars-CdarYsrc.js.map} +1 -1
  21. package/dist/chunks/{generate-dNlBII84.js → generate-27CjLiGW.js} +2 -2
  22. package/dist/chunks/{generate-dNlBII84.js.map → generate-27CjLiGW.js.map} +1 -1
  23. package/dist/chunks/{generate-yi8AP3xH.js → generate-BFcy2wrS.js} +3 -3
  24. package/dist/chunks/{generate-yi8AP3xH.js.map → generate-BFcy2wrS.js.map} +1 -1
  25. package/dist/chunks/generate-BxOzEdc_.js +171 -0
  26. package/dist/chunks/generate-BxOzEdc_.js.map +1 -0
  27. package/dist/chunks/{generate-B6Odfk5f.js → generate-Cqwa8kD9.js} +2 -2
  28. package/dist/chunks/{generate-B6Odfk5f.js.map → generate-Cqwa8kD9.js.map} +1 -1
  29. package/dist/chunks/{generate-DjBMRzsB.js → generate-D3mSFPdT.js} +2 -2
  30. package/dist/chunks/{generate-DjBMRzsB.js.map → generate-D3mSFPdT.js.map} +1 -1
  31. package/dist/chunks/{generate-ZIOVLH6Q.js → generate-DdLwP0E7.js} +51 -47
  32. package/dist/chunks/generate-DdLwP0E7.js.map +1 -0
  33. package/dist/chunks/generate-DyV5R8NP.js.map +1 -1
  34. package/dist/chunks/{generate.runtime-MjWwR2Bd.js → generate.runtime-9KuMcI5r.js} +10 -13
  35. package/dist/chunks/{generate.runtime-MjWwR2Bd.js.map → generate.runtime-9KuMcI5r.js.map} +1 -1
  36. package/dist/chunks/{generate.runtime-BKINIJ2c.js → generate.runtime-B10-KA87.js} +69 -69
  37. package/dist/chunks/{generate.runtime-BKINIJ2c.js.map → generate.runtime-B10-KA87.js.map} +1 -1
  38. package/dist/chunks/{generate.runtime-DaRVyiSg.js → generate.runtime-B8-GLMkk.js} +131 -197
  39. package/dist/chunks/generate.runtime-B8-GLMkk.js.map +1 -0
  40. package/dist/chunks/{generate.runtime-Bdpu4rX0.js → generate.runtime-BGuXHl5o.js} +3 -3
  41. package/dist/chunks/{generate.runtime-Bdpu4rX0.js.map → generate.runtime-BGuXHl5o.js.map} +1 -1
  42. package/dist/chunks/{generate.runtime-DjCzW3zU.js → generate.runtime-BJxM7FNA.js} +7 -7
  43. package/dist/chunks/{generate.runtime-DjCzW3zU.js.map → generate.runtime-BJxM7FNA.js.map} +1 -1
  44. package/dist/chunks/{generate.runtime-BdmoAVJK.js → generate.runtime-BWRtyQeD.js} +5 -5
  45. package/dist/chunks/{generate.runtime-BdmoAVJK.js.map → generate.runtime-BWRtyQeD.js.map} +1 -1
  46. package/dist/chunks/{generate.runtime-CV4soy2n.js → generate.runtime-B_tWu-Bw.js} +47 -47
  47. package/dist/chunks/{generate.runtime-CV4soy2n.js.map → generate.runtime-B_tWu-Bw.js.map} +1 -1
  48. package/dist/chunks/{generate.runtime-NaSIZlP5.js → generate.runtime-BdghkfNp.js} +3 -3
  49. package/dist/chunks/{generate.runtime-NaSIZlP5.js.map → generate.runtime-BdghkfNp.js.map} +1 -1
  50. package/dist/chunks/{generate.runtime-B4QoBn5v.js → generate.runtime-Blb6QPZn.js} +8 -8
  51. package/dist/chunks/{generate.runtime-B4QoBn5v.js.map → generate.runtime-Blb6QPZn.js.map} +1 -1
  52. package/dist/chunks/{generate.runtime-DRRyPa-e.js → generate.runtime-CEexT8cJ.js} +66 -66
  53. package/dist/chunks/{generate.runtime-DRRyPa-e.js.map → generate.runtime-CEexT8cJ.js.map} +1 -1
  54. package/dist/chunks/{generate.runtime-BKTkVCEm.js → generate.runtime-CIZO2XO9.js} +4 -4
  55. package/dist/chunks/{generate.runtime-BKTkVCEm.js.map → generate.runtime-CIZO2XO9.js.map} +1 -1
  56. package/dist/chunks/{generate.runtime-DmsOEsJV.js → generate.runtime-CK0MTeqc.js} +4 -4
  57. package/dist/chunks/{generate.runtime-DmsOEsJV.js.map → generate.runtime-CK0MTeqc.js.map} +1 -1
  58. package/dist/chunks/{generate.runtime-BavEh01F.js → generate.runtime-CMO-Skpk.js} +5 -5
  59. package/dist/chunks/{generate.runtime-BavEh01F.js.map → generate.runtime-CMO-Skpk.js.map} +1 -1
  60. package/dist/chunks/{generate.runtime-BXZDKLbA.js → generate.runtime-CVDb-yLt.js} +12 -20
  61. package/dist/chunks/{generate.runtime-BXZDKLbA.js.map → generate.runtime-CVDb-yLt.js.map} +1 -1
  62. package/dist/chunks/generate.runtime-C_5Ghjri.js +17 -0
  63. package/dist/chunks/generate.runtime-C_5Ghjri.js.map +1 -0
  64. package/dist/chunks/{generate.runtime-CWgZhxQt.js → generate.runtime-CbOMXQSo.js} +3 -3
  65. package/dist/chunks/{generate.runtime-CWgZhxQt.js.map → generate.runtime-CbOMXQSo.js.map} +1 -1
  66. package/dist/chunks/{generate.runtime-DBBtYTAa.js → generate.runtime-CbT-EbQT.js} +5 -5
  67. package/dist/chunks/{generate.runtime-DBBtYTAa.js.map → generate.runtime-CbT-EbQT.js.map} +1 -1
  68. package/dist/chunks/{generate.runtime-CSUnP0l-.js → generate.runtime-Cxr15Y5H.js} +27 -27
  69. package/dist/chunks/{generate.runtime-CSUnP0l-.js.map → generate.runtime-Cxr15Y5H.js.map} +1 -1
  70. package/dist/chunks/{generate.runtime-pMpn0Pbf.js → generate.runtime-CyTxBcX3.js} +10 -10
  71. package/dist/chunks/{generate.runtime-pMpn0Pbf.js.map → generate.runtime-CyTxBcX3.js.map} +1 -1
  72. package/dist/chunks/{generate.runtime-azOvp6tl.js → generate.runtime-D5HxAups.js} +39 -36
  73. package/dist/chunks/generate.runtime-D5HxAups.js.map +1 -0
  74. package/dist/chunks/{generate.runtime-b2RtuPy4.js → generate.runtime-D6vhkGs8.js} +5 -5
  75. package/dist/chunks/{generate.runtime-b2RtuPy4.js.map → generate.runtime-D6vhkGs8.js.map} +1 -1
  76. package/dist/chunks/{generate.runtime-DlbG-8Xm.js → generate.runtime-DIeAeOJg.js} +6 -6
  77. package/dist/chunks/{generate.runtime-DlbG-8Xm.js.map → generate.runtime-DIeAeOJg.js.map} +1 -1
  78. package/dist/chunks/{generate.runtime-QbmCPT42.js → generate.runtime-DMTAocSE.js} +17 -17
  79. package/dist/chunks/{generate.runtime-QbmCPT42.js.map → generate.runtime-DMTAocSE.js.map} +1 -1
  80. package/dist/chunks/{generate.runtime-utFLS6Jz.js → generate.runtime-DlLwmjGF.js} +133 -121
  81. package/dist/chunks/generate.runtime-DlLwmjGF.js.map +1 -0
  82. package/dist/chunks/{generate.runtime-BYfyZHhs.js → generate.runtime-DtCaz98N.js} +6 -6
  83. package/dist/chunks/{generate.runtime-BYfyZHhs.js.map → generate.runtime-DtCaz98N.js.map} +1 -1
  84. package/dist/chunks/{generate.runtime-BcgjZJug.js → generate.runtime-HSZD935T.js} +4 -4
  85. package/dist/chunks/{generate.runtime-BcgjZJug.js.map → generate.runtime-HSZD935T.js.map} +1 -1
  86. package/dist/chunks/{generate.runtime-OEgsdWRP.js → generate.runtime-Nnk5E8Pi.js} +3 -3
  87. package/dist/chunks/{generate.runtime-OEgsdWRP.js.map → generate.runtime-Nnk5E8Pi.js.map} +1 -1
  88. package/dist/chunks/{generate.runtime-D-qtaVdq.js → generate.runtime-NxuWvkKt.js} +13 -13
  89. package/dist/chunks/{generate.runtime-D-qtaVdq.js.map → generate.runtime-NxuWvkKt.js.map} +1 -1
  90. package/dist/chunks/{generate.runtime-CCV4O6_I.js → generate.runtime-dFTOU_KE.js} +71 -71
  91. package/dist/chunks/{generate.runtime-CCV4O6_I.js.map → generate.runtime-dFTOU_KE.js.map} +1 -1
  92. package/dist/chunks/{generate.runtime-C7s1Mx5L.js → generate.runtime-m0m43lkL.js} +7 -7
  93. package/dist/chunks/{generate.runtime-C7s1Mx5L.js.map → generate.runtime-m0m43lkL.js.map} +1 -1
  94. package/dist/chunks/{generate.runtime-BdHv7Jp1.js → generate.runtime-si5Za61F.js} +3 -3
  95. package/dist/chunks/{generate.runtime-BdHv7Jp1.js.map → generate.runtime-si5Za61F.js.map} +1 -1
  96. package/dist/chunks/{generate.runtime-DetYynf4.js → generate.runtime-tGKorg85.js} +10 -14
  97. package/dist/chunks/{generate.runtime-DetYynf4.js.map → generate.runtime-tGKorg85.js.map} +1 -1
  98. package/dist/chunks/{generate.runtime-CcPCAEV0.js → generate.runtime-ww3-1FWf.js} +6 -6
  99. package/dist/chunks/{generate.runtime-CcPCAEV0.js.map → generate.runtime-ww3-1FWf.js.map} +1 -1
  100. package/dist/chunks/{modify-file-Bbhyfiy_.js → modify-file-COBp4eCh.js} +4 -4
  101. package/dist/chunks/{modify-file-Bbhyfiy_.js.map → modify-file-COBp4eCh.js.map} +1 -1
  102. package/dist/chunks/{modify-nav-user-B8h8WTrM.js → modify-nav-user-CJ1LevSU.js} +2 -2
  103. package/dist/chunks/{modify-nav-user-B8h8WTrM.js.map → modify-nav-user-CJ1LevSU.js.map} +1 -1
  104. package/dist/chunks/{modify-svelte-config-remote-DhuRX4FI.js → modify-svelte-config-remote-CEyYydL7.js} +2 -2
  105. package/dist/chunks/{modify-svelte-config-remote-DhuRX4FI.js.map → modify-svelte-config-remote-CEyYydL7.js.map} +1 -1
  106. package/dist/chunks/{modify-user-signup-BbqTiUuA.js → modify-user-signup-DLtopazD.js} +2 -2
  107. package/dist/chunks/{modify-user-signup-BbqTiUuA.js.map → modify-user-signup-DLtopazD.js.map} +1 -1
  108. package/dist/chunks/{package-imports-Bbw3iMPg.js → package-imports-Dx05A-4S.js} +2 -2
  109. package/dist/chunks/{package-imports-Bbw3iMPg.js.map → package-imports-Dx05A-4S.js.map} +1 -1
  110. package/dist/chunks/{pocketbase-CgwbH1gI.js → pocketbase-DL02rq73.js} +5 -13
  111. package/dist/chunks/{pocketbase-CgwbH1gI.js.map → pocketbase-DL02rq73.js.map} +1 -1
  112. package/dist/chunks/{providers-DwbwccSW.js → providers-CAehyySB.js} +2 -2
  113. package/dist/chunks/{providers-DwbwccSW.js.map → providers-CAehyySB.js.map} +1 -1
  114. package/dist/chunks/{rolldown-runtime-DArdT4gl.js → rolldown-runtime-5HNE8Q1r.js} +1 -1
  115. package/dist/chunks/{shared-D5GOS97l.js → shared-C_Fr8wph.js} +2 -2
  116. package/dist/chunks/{shared-D5GOS97l.js.map → shared-C_Fr8wph.js.map} +1 -1
  117. package/dist/chunks/site-BoujshKo.js +108 -0
  118. package/dist/chunks/site-BoujshKo.js.map +1 -0
  119. package/dist/chunks/{table-core-DhDqT03G.js → table-core-BPv_RYgD.js} +3 -3
  120. package/dist/chunks/{table-core-DhDqT03G.js.map → table-core-BPv_RYgD.js.map} +1 -1
  121. package/dist/chunks/{taggedTemplateLiteral-CswN2AAa.js → taggedTemplateLiteral-KSUnuvOk.js} +1 -1
  122. package/dist/chunks/{test-setup-DZoyF8Ak.js → test-setup-pYUIfWb2.js} +5 -5
  123. package/dist/chunks/{test-setup-DZoyF8Ak.js.map → test-setup-pYUIfWb2.js.map} +1 -1
  124. package/dist/chunks/{ts-morph-helpers-Bepc-Es2.js → ts-morph-helpers-CHI9wAil.js} +7 -11
  125. package/dist/chunks/{ts-morph-helpers-Bepc-Es2.js.map → ts-morph-helpers-CHI9wAil.js.map} +1 -1
  126. package/dist/chunks/{ui-BuocThuh.js → ui-B2yn8c_-.js} +3 -3
  127. package/dist/chunks/{ui-BuocThuh.js.map → ui-B2yn8c_-.js.map} +1 -1
  128. package/dist/chunks/{unmodify-load-Bl5vXQiL.js → unmodify-load-Buak-r1f.js} +2 -2
  129. package/dist/chunks/{unmodify-load-Bl5vXQiL.js.map → unmodify-load-Buak-r1f.js.map} +1 -1
  130. package/dist/chunks/{whatsapp-CguKGTtw.js → whatsapp-5qJ_xCV1.js} +2 -2
  131. package/dist/chunks/{whatsapp-CguKGTtw.js.map → whatsapp-5qJ_xCV1.js.map} +1 -1
  132. package/dist/chunks/{write-result-Cq-9A7Zy.js → write-result-Bn4bnrBI.js} +20 -50
  133. package/dist/chunks/write-result-Bn4bnrBI.js.map +1 -0
  134. package/dist/chunks/wuchale-config-c3Q4JVSF.js +50 -0
  135. package/dist/chunks/wuchale-config-c3Q4JVSF.js.map +1 -0
  136. package/dist/index.d.ts +162 -1
  137. package/dist/index.js +2193 -2330
  138. package/dist/index.js.map +1 -1
  139. package/package.json +2 -2
  140. package/dist/chunks/collections-Cpjo2OiQ.js.map +0 -1
  141. package/dist/chunks/constants-Rq8SCXwH.js.map +0 -1
  142. package/dist/chunks/generate-BClgUH4J.js +0 -137
  143. package/dist/chunks/generate-BClgUH4J.js.map +0 -1
  144. package/dist/chunks/generate-ZIOVLH6Q.js.map +0 -1
  145. package/dist/chunks/generate.runtime-DaRVyiSg.js.map +0 -1
  146. package/dist/chunks/generate.runtime-azOvp6tl.js.map +0 -1
  147. package/dist/chunks/generate.runtime-utFLS6Jz.js.map +0 -1
  148. package/dist/chunks/shopify-page-D-VFwGxI.js +0 -11
  149. package/dist/chunks/shopify-page-D-VFwGxI.js.map +0 -1
  150. package/dist/chunks/site-lj0CDdQ1.js +0 -55
  151. package/dist/chunks/site-lj0CDdQ1.js.map +0 -1
  152. package/dist/chunks/write-result-Cq-9A7Zy.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@velastack/patterns",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Registry of VelaStack patterns: generators and modifications applied to SvelteKit projects by the VelaStack CLI.",
5
5
  "type": "module",
6
6
  "private": false,
@@ -108,7 +108,7 @@
108
108
  "pluralize": "^8.0.0",
109
109
  "pocketbase": "^0.28.0",
110
110
  "shadcn-svelte": "^1.6.0",
111
- "stripe": "^22.6.1",
111
+ "stripe": "^23.0.0",
112
112
  "svelte": "^5.56.10",
113
113
  "ts-morph": "^28.0.0",
114
114
  "typescript": "^6.0.0",
@@ -1 +0,0 @@
1
- {"version":3,"file":"collections-Cpjo2OiQ.js","names":["__exportAll","languageFromPath","getLogger","NOOP_LOGGER","withPocketbase","migrationDelay","getMigrationFile","collections_exports","applyCollectionFieldsPatches","applyCollectionRulePatches","createCollectionIdempotent","createCollections","dropCollectionIdempotent","dropCollections","getCollectionStats","planCollectionDrops","isCollectionAlreadyExistsError","error","message","resolveRelationTargets","fields","spec","relations","field","existing","pb","ids","c","byName","id","name","logger","rulePayloadFromPatch","payload","patch","migrations","patches","escaped","col","options","migrationFile","readFileSync","applyFieldChanges","change","f","InvalidArgumentError","index","collection","newFields","plans","names","stats","specs","dropped","collections","created"],"sources":["../../src/runtime/collections.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type PocketBase from \"pocketbase\";\nimport type { CollectionModel } from \"pocketbase\";\nimport type {\n CollectionDropSpec,\n CollectionFieldSpec,\n CollectionFieldsPatch,\n CollectionRulesPatch,\n CollectionSpec,\n File,\n Options,\n} from \"../core/types\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { getMigrationFile, migrationDelay, withPocketbase } from \"./pocketbase\";\n\ninterface PocketBaseCollectionCreateError {\n response?: {\n data?: {\n name?: {\n code?: string;\n };\n };\n };\n message?: string;\n}\n\nfunction isCollectionAlreadyExistsError(\n error: PocketBaseCollectionCreateError,\n): boolean {\n if (\n error.response?.data?.name?.code === \"validation_collection_name_exists\"\n ) {\n return true;\n }\n\n const message = error.message?.toLowerCase() ?? \"\";\n return (\n message.includes(\"already exists\") || message.includes(\"must be unique\")\n );\n}\n\ntype CollectionCreateInput = Parameters<PocketBase[\"collections\"][\"create\"]>[0];\n\ninterface RelationFieldLike {\n type?: string;\n collectionId?: string;\n}\n\n/**\n * A spec may name the collection a relation points at (`stripe_customers`)\n * where PocketBase wants its id; specs read better by name, and the id is\n * only known once the target exists. Names are swapped for ids here, and a\n * value that already is an id (`_pb_users_auth_`) is left alone.\n */\nasync function resolveRelationTargets(\n pb: PocketBase,\n spec: CollectionCreateInput,\n): Promise<CollectionCreateInput> {\n const fields = (spec as { fields?: RelationFieldLike[] }).fields;\n const relations = (fields ?? []).filter(\n (field) => field.type === \"relation\" && field.collectionId,\n );\n if (relations.length === 0) return spec;\n\n const existing = await pb.collections.getFullList();\n const ids = new Set(existing.map((c) => c.id));\n const byName = new Map(existing.map((c) => [c.name, c.id]));\n if (relations.every((field) => ids.has(field.collectionId!))) return spec;\n\n return {\n ...spec,\n fields: fields!.map((field) => {\n if (field.type !== \"relation\" || !field.collectionId) return field;\n const id = byName.get(field.collectionId);\n return id && !ids.has(field.collectionId)\n ? { ...field, collectionId: id }\n : field;\n }),\n } as CollectionCreateInput;\n}\n\nexport interface CreateCollectionResult {\n collection: CollectionModel;\n created: boolean;\n}\n\n/**\n * Idempotent wrapper around `pb.collections.create`. If the collection already\n * exists, logs and returns the existing model with `created: false` so callers\n * can skip work tied to a fresh create (e.g. appending a newly-generated\n * migration file to the result).\n */\nexport async function createCollectionIdempotent(\n pb: PocketBase,\n spec: CollectionCreateInput,\n logger: Logger = NOOP_LOGGER,\n): Promise<CreateCollectionResult> {\n const name = (spec as { name: string }).name;\n try {\n const collection = await pb.collections.create(\n await resolveRelationTargets(pb, spec),\n );\n return { collection, created: true };\n } catch (error) {\n if (\n !isCollectionAlreadyExistsError(error as PocketBaseCollectionCreateError)\n ) {\n throw error;\n }\n logger.info(`Collection \"${name}\" already exists, skipping`);\n const collection = await pb.collections.getOne(name);\n return { collection, created: false };\n }\n}\n\nfunction rulePayloadFromPatch(\n patch: CollectionRulesPatch,\n): Record<string, unknown> {\n const payload: Record<string, unknown> = {};\n if (patch.listRule !== undefined) payload.listRule = patch.listRule;\n if (patch.viewRule !== undefined) payload.viewRule = patch.viewRule;\n if (patch.createRule !== undefined) payload.createRule = patch.createRule;\n if (patch.updateRule !== undefined) payload.updateRule = patch.updateRule;\n if (patch.deleteRule !== undefined) payload.deleteRule = patch.deleteRule;\n return payload;\n}\n\n/**\n * Applies API rule updates in array order. Call after all referenced collections exist.\n * Collects migration files produced by each update when `options` is provided.\n */\nexport async function applyCollectionRulePatches(\n pb: {\n collections: {\n getFirstListItem: (filter: string) => Promise<{ id: string }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionRulesPatch[],\n options?: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const escaped = patch.collectionName.replace(/'/g, \"''\");\n const col = await pb.collections.getFirstListItem(`name='${escaped}'`);\n logger.info(`Updating rules on collection \"${patch.collectionName}\"`);\n await pb.collections.update(col.id, rulePayloadFromPatch(patch));\n await migrationDelay();\n\n if (options) {\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (migrationFile) {\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n }\n }\n\n return migrations;\n}\n\nfunction applyFieldChanges(\n existing: CollectionFieldSpec[],\n patch: CollectionFieldsPatch,\n): CollectionFieldSpec[] {\n const fields = existing.map((field) => ({ ...field }));\n\n for (const change of patch.changes) {\n if (change.op === \"add\") {\n if (fields.some((f) => f.name === change.field.name)) {\n throw new InvalidArgumentError(\n `Field \"${change.field.name}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n fields.push(change.field);\n continue;\n }\n if (change.op === \"remove\") {\n const index = fields.findIndex((f) => f.name === change.fieldName);\n if (index === -1) {\n throw new InvalidArgumentError(\n `Field \"${change.fieldName}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n fields.splice(index, 1);\n continue;\n }\n if (change.op === \"rename\") {\n const field = fields.find((f) => f.name === change.from);\n if (!field) {\n throw new InvalidArgumentError(\n `Field \"${change.from}\" does not exist on collection \"${patch.collectionName}\"`,\n );\n }\n if (fields.some((f) => f.name === change.to)) {\n throw new InvalidArgumentError(\n `Field \"${change.to}\" already exists on collection \"${patch.collectionName}\"`,\n );\n }\n field.name = change.to;\n continue;\n }\n }\n\n return fields;\n}\n\nexport async function applyCollectionFieldsPatches(\n pb: {\n collections: {\n getOne: (\n name: string,\n ) => Promise<{ id: string; fields: CollectionFieldSpec[] }>;\n update: (id: string, body: Record<string, unknown>) => Promise<unknown>;\n };\n },\n patches: CollectionFieldsPatch[],\n options: Options,\n logger: Logger = NOOP_LOGGER,\n): Promise<File[]> {\n const migrations: File[] = [];\n\n for (const patch of patches) {\n const collection = await pb.collections.getOne(patch.collectionName);\n const newFields = applyFieldChanges(collection.fields, patch);\n logger.info(`Updating fields on collection \"${patch.collectionName}\"`);\n await pb.collections.update(collection.id, { fields: newFields });\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n patch.collectionName,\n \"updated\",\n options,\n );\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n\n return migrations;\n}\n\nexport interface DropCollectionResult {\n dropped: boolean;\n existed: boolean;\n}\n\n/**\n * Idempotent collection drop. Returns `{ existed: false, dropped: false }` if\n * the collection is already gone, matching the idempotency contract of\n * `createCollectionIdempotent`.\n */\nexport async function dropCollectionIdempotent(\n pb: PocketBase,\n name: string,\n logger: Logger = NOOP_LOGGER,\n): Promise<DropCollectionResult> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n logger.info(`Collection \"${name}\" does not exist, skipping drop`);\n return { dropped: false, existed: false };\n }\n throw error;\n }\n await pb.collections.delete(name);\n return { dropped: true, existed: true };\n}\n\nexport interface CollectionStats {\n exists: boolean;\n rowCount: number;\n}\n\nexport async function getCollectionStats(\n pb: PocketBase,\n name: string,\n): Promise<CollectionStats> {\n try {\n await pb.collections.getOne(name);\n } catch (error) {\n const status = (error as { status?: number }).status;\n if (status === 404) {\n return { exists: false, rowCount: 0 };\n }\n throw error;\n }\n\n try {\n const result = await pb\n .collection(name)\n .getList(1, 1, { skipTotal: false });\n return { exists: true, rowCount: result.totalItems };\n } catch {\n return { exists: true, rowCount: 0 };\n }\n}\n\n/**\n * Resolve the set of collections to drop, with current row counts. Missing\n * collections are included with `exists: false, rowCount: 0` so callers can\n * display the full reversal plan even when some collections were already gone.\n */\nexport async function planCollectionDrops(\n pb: PocketBase,\n names: string[],\n): Promise<CollectionDropSpec[]> {\n const plans: CollectionDropSpec[] = [];\n for (const name of names) {\n const stats = await getCollectionStats(pb, name);\n plans.push({ name, exists: stats.exists, rowCount: stats.rowCount });\n }\n return plans;\n}\n\n/**\n * Drop each of the given collections (skipping those that are already gone)\n * and collect the `_deleted_<name>.js` migration file PocketBase emits for\n * each successful drop. Symmetric to `createCollections`.\n */\nexport async function dropCollections(\n specs: CollectionDropSpec[],\n options: Options,\n): Promise<File[]> {\n if (specs.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const spec of specs) {\n logger.info(`Dropping collection \"${spec.name}\"`);\n const { dropped } = await dropCollectionIdempotent(pb, spec.name, logger);\n if (!dropped) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(spec.name, \"deleted\", options);\n if (!migrationFile) continue;\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n\nexport async function createCollections(\n collections: CollectionSpec[],\n options: Options,\n): Promise<File[]> {\n if (collections.length === 0) {\n return [];\n }\n\n const migrations: File[] = [];\n const logger = getLogger(options);\n\n await withPocketbase(options.root, async (pb) => {\n for (const collection of collections) {\n logger.info(`Creating collection \"${collection.name}\"`);\n const { created } = await createCollectionIdempotent(\n pb,\n collection,\n logger,\n );\n if (!created) continue;\n await migrationDelay();\n\n const migrationFile = getMigrationFile(\n collection.name,\n \"created\",\n options,\n );\n if (!migrationFile) {\n continue;\n }\n\n migrations.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n }\n });\n\n return migrations;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,SAASgB,EACP,GACS;CACT,IACEC,EAAM,UAAU,MAAM,MAAM,SAAS,qCAErC,OAAO;CAGT,IAAMC,IAAUD,EAAM,SAAS,YAAY,KAAK;CAChD,OACEC,EAAQ,SAAS,gBAAgB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,GAAS;GACd,MAAMhD,EAAe;GAErB,IAAMmC,IAAgBlC,EAAiBe,EAAK,MAAM,WAAWkB,CAAO;GACpE,AAAKC,KAELL,EAAW,KAAK;IACd,MAAMK;IACN,UAAUvC,EAAiBuC,CAAa;IACxC,SAASC,EAAaD,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEML;AACT;AAEA,eAAsBxB,EACpB,GACA,GACiB;CACjB,IAAI2C,EAAY,WAAW,GACzB,OAAO,CAAC;CAGV,IAAMnB,IAAqB,CAAC,GACtBJ,IAAS7B,EAAUqC,CAAO;CA+BhC,OA7BA,MAAMnC,EAAemC,EAAQ,MAAM,OAAO,MAAO;EAC/C,KAAK,IAAMQ,KAAcO,GAAa;GACpC,EAAO,KAAK,wBAAwBP,EAAW,KAAK,EAAE;GACtD,IAAM,EAAE,eAAY,MAAMrC,EACxBe,GACAsB,GACAhB,CACF;GACA,IAAI,CAACwB,GAAS;GACd,MAAMlD,EAAe;GAErB,IAAMmC,IAAgBlC,EACpByC,EAAW,MACX,WACAR,CACF;GACA,AAAKC,KAILL,EAAW,KAAK;IACd,MAAMK;IACN,UAAUvC,EAAiBuC,CAAa;IACxC,SAASC,EAAaD,GAAe,MAAM;IAC3C,QAAQ;GACV,CAAC;EACH;CACF,CAAC,GAEML;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants-Rq8SCXwH.js","names":["DATA_DIR","MIGRATIONS_DIR","PUBLIC_DIR","APP_DIR","TANSTACK_TABLE_CORE","FORMSNAP","SUPERFORMS_VERSION","SUPERFORMS","FORMSNAP_OVERRIDES","FLASH","ADAPTER_NODE","ADAPTER_STATIC","VELASTACK_KIT","VELASTACK_POCKETBASE","VELASTACK_CMS","NEGOTIATE","ZOD","WUCHALE","WUCHALE_SVELTE"],"sources":["../../src/core/constants.ts"],"sourcesContent":["export const DATA_DIR = \"data\";\nexport const MIGRATIONS_DIR = \"migrations\";\nexport const FIXTURE_PREFIX = \"vela\";\nexport const PUBLIC_DIR = \"(public)\";\nexport const APP_DIR = \"(app)\";\nexport const AUTHED_REDIRECT_PATH = \"/dashboard\";\nexport const API_URL = \"http://localhost:5173\";\n\n/**\n * The table helpers this repo ships (`data-table`, `column-header`,\n * `faceted-filter`, `pagination`) and the pages the scaffold generators emit\n * target TanStack Table v9, whose API and types are incompatible with v8; see\n * `assertTableCoreV9` for projects that still have the v8 helpers.\n */\nexport const TANSTACK_TABLE_CORE = \"@tanstack/table-core@^9.2.4\";\n\n/** The major `TANSTACK_TABLE_CORE` pins. */\nexport const TANSTACK_TABLE_CORE_MAJOR = 9;\n\n/** `file-form` and `multiselect` build on formsnap's field context. */\nexport const FORMSNAP = \"formsnap@^2.0.1\";\n\n/**\n * The superforms release that supports SvelteKit 3 (its `latest` accepts\n * only Kit 1 and 2). Installed exactly, not with a caret: a caret on a\n * prerelease would follow later `next` builds.\n */\nexport const SUPERFORMS_VERSION = \"3.0.0-next.1\";\n\n/**\n * What a generated superforms page needs. Vela's templates already carry\n * both; a project vela did not create may have neither.\n */\nexport const SUPERFORMS = `sveltekit-superforms@${SUPERFORMS_VERSION}`;\n\n/**\n * formsnap 2 peers `sveltekit-superforms ^2`, so every project that installs\n * it needs this npm override, or `npm install` fails with ERESOLVE. The value\n * is the literal version: `$sveltekit-superforms` breaks on npm 10.\n * `writeResult` adds it before any install that brings formsnap in.\n */\nexport const FORMSNAP_OVERRIDES = {\n formsnap: { \"sveltekit-superforms\": SUPERFORMS_VERSION },\n};\n\n/** The flash-message release that supports SvelteKit 3; installed exactly, like superforms. */\nexport const FLASH = \"sveltekit-flash-message@3.0.0-next.0\";\n\n/** The adapter `vela enable backend` moves a project to. */\nexport const ADAPTER_NODE = \"@sveltejs/adapter-node@^6.0.0\";\n\n/** The adapter a static project builds with (`vela disable backend`). */\nexport const ADAPTER_STATIC = \"@sveltejs/adapter-static@^4.0.0\";\n\n/** The VelaStack libraries' SvelteKit 3 releases. */\nexport const VELASTACK_KIT = \"@velastack/kit@^0.4.0\";\n/** 0.4.2 proxies plugin webhooks (pocketbase-whatsapp) to PocketBase. */\nexport const VELASTACK_POCKETBASE = \"@velastack/pocketbase@^0.4.2\";\nexport const VELASTACK_CMS = \"@velastack/cms@^0.6.0\";\nexport const NEGOTIATE = \"sveltekit-negotiate@^0.3.0\";\nexport const ZOD = \"zod@^4.1.11\";\n\n/** What `vela enable i18n` installs: wuchale and its Svelte adapter. */\nexport const WUCHALE = \"wuchale@^0.26.3\";\nexport const WUCHALE_SVELTE = \"@wuchale/svelte@^0.21.1\";\n"],"mappings":";AAAA,IAAaA,IAAW,QACXC,IAAiB,cAEjBC,IAAa,YACbC,IAAU,SAUVC,IAAsB,+BAMtBC,IAAW,mBAOXC,IAAqB,gBAMrBC,IAAa,wBAAwBD,KAQrCE,IAAqB,EAChC,UAAU,EAAE,wBAAwBF,EAAmB,EACzD,GAGaG,IAAQ,wCAGRC,IAAe,iCAGfC,IAAiB,mCAGjBC,IAAgB,yBAEhBC,IAAuB,gCACvBC,IAAgB,yBAChBC,IAAY,8BACZC,IAAM,eAGNC,IAAU,mBACVC,IAAiB"}
@@ -1,137 +0,0 @@
1
- import { t as e } from "./errors-DR3gF_7a.js";
2
- import { c as t, i as n, r } from "./providers-CL9kQ4hp.js";
3
- import { t as i } from "./stripe-customer-B3tP8gtD.js";
4
- import { n as a, t as o } from "./_page-DoPdZgZv.js";
5
- //#region src/patterns/enable/payments/providers/shopify/src/lib/components/payments/buy-button.svelte?raw
6
- var s = "<script lang=\"ts\">\n import { toast } from 'svelte-sonner';\n import { Button } from '#lib/components/ui/button/index.js';\n import type { ButtonProps } from '#lib/components/ui/button/index.js';\n import { storefront } from '#lib/shopify.js';\n\n interface Props {\n /** The product variant to buy: `gid://shopify/ProductVariant/...`. */\n variantId: string;\n quantity?: number;\n label?: string;\n processingLabel?: string;\n }\n\n let {\n variantId,\n quantity = 1,\n label = 'Buy now',\n processingLabel = 'Redirecting...',\n disabled,\n ...rest\n }: Props & ButtonProps = $props();\n\n const CART_CREATE = `#graphql\n mutation BuyNow($lines: [CartLineInput!]!) {\n cartCreate(input: { lines: $lines }) {\n cart {\n checkoutUrl\n }\n userErrors {\n message\n }\n }\n }\n `;\n\n let isProcessing = $state(false);\n\n // A one-line cart, then Shopify's checkout for it.\n async function buy() {\n isProcessing = true;\n try {\n const { data, errors } = await storefront().request(CART_CREATE, {\n variables: { lines: [{ merchandiseId: variantId, quantity }] }\n });\n const checkoutUrl = data?.cartCreate?.cart?.checkoutUrl;\n if (errors || !checkoutUrl) {\n throw new Error(\n data?.cartCreate?.userErrors?.[0]?.message ?? errors?.message ?? 'No checkout URL'\n );\n }\n window.location.assign(checkoutUrl);\n } catch (error) {\n console.error('Shopify checkout failed:', error);\n toast.error('Could not start checkout');\n isProcessing = false;\n }\n }\n<\/script>\n\n<Button disabled={disabled || isProcessing} onclick={buy} {...rest}>\n {#if isProcessing}\n {processingLabel}\n {:else}\n {label}\n {/if}\n</Button>\n", c = "import { PUBLIC_SHOPIFY_STORE_DOMAIN, PUBLIC_SHOPIFY_STOREFRONT_TOKEN } from '$app/env/public';\nimport {\n createStorefrontApiClient,\n type StorefrontApiClient\n} from '@shopify/storefront-api-client';\n\n/** Shopify supports each Storefront API version for a year; move this forward when it nears its end. */\nexport const SHOPIFY_API_VERSION = '2026-10';\n\nlet client: StorefrontApiClient | undefined;\n\n/**\n * The Storefront API client. Built on first use, not on import: it refuses to\n * be created without a token, and a build or prerender with an empty `.env`\n * should still pass, failing only the requests that need Shopify.\n */\nexport function storefront(): StorefrontApiClient {\n if (!client) {\n if (!PUBLIC_SHOPIFY_STORE_DOMAIN || !PUBLIC_SHOPIFY_STOREFRONT_TOKEN) {\n throw new Error(\n 'PUBLIC_SHOPIFY_STORE_DOMAIN and PUBLIC_SHOPIFY_STOREFRONT_TOKEN are not set, so Shopify cannot be called.'\n );\n }\n client = createStorefrontApiClient({\n storeDomain: PUBLIC_SHOPIFY_STORE_DOMAIN,\n apiVersion: SHOPIFY_API_VERSION,\n publicAccessToken: PUBLIC_SHOPIFY_STOREFRONT_TOKEN\n });\n }\n return client;\n}\n", l = "<script lang=\"ts\">\n import type { Stripe } from '@stripe/stripe-js';\n import { Button } from '#lib/components/ui/button/index.js';\n import * as Dialog from '#lib/components/ui/dialog/index.js';\n import { toast } from 'svelte-sonner';\n import { page } from '$app/state';\n import { invalidate } from '$app/navigation';\n\n interface Props {\n stripe: Stripe | null;\n open: boolean;\n amount: number;\n currency: string;\n brand?: string;\n last4?: string;\n clientSecret?: string;\n onopenchange: (open: boolean) => void;\n onsuccess: () => void;\n }\n\n let {\n stripe,\n open = $bindable(),\n amount,\n currency,\n brand,\n last4,\n clientSecret,\n onopenchange,\n onsuccess\n }: Props = $props();\n\n const brandNames = {\n amex: 'American Express',\n cartes_bancaires: 'Cartes Bancaires',\n diners: 'Diners',\n discover: 'Discover',\n eftpos_au: 'Eftpos Au',\n jcb: 'Jcb',\n link: 'Link',\n mastercard: 'Mastercard',\n unionpay: 'Unionpay',\n visa: 'Visa',\n unknown: 'Unknown'\n };\n\n let isProcessing = $state(false);\n\n let amountFormatted = $derived.by(() => {\n let formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: currency });\n return formatter.format(amount / 100);\n });\n\n const handleOpenChangeComplete = (isOpen: boolean) => {\n if (!isOpen) {\n resetDialog();\n }\n onopenchange(isOpen);\n };\n\n function resetDialog() {\n open = false;\n isProcessing = false;\n }\n\n async function handlePaymentMethod() {\n if (!stripe || !clientSecret) return;\n\n isProcessing = true;\n\n try {\n const { error: confirmError } = await stripe.confirmPayment({\n clientSecret,\n confirmParams: {\n return_url: page.url.toString()\n },\n redirect: 'if_required'\n });\n\n if (confirmError) {\n toast.error(confirmError.message || 'Failed to pay for your purchase');\n return;\n }\n\n await invalidate('app:billing');\n toast.success('Payment successful');\n onsuccess();\n resetDialog();\n } catch (err) {\n console.error('Error paying for your purchase:', err);\n toast.error('Failed to pay for your purchase');\n } finally {\n isProcessing = false;\n }\n }\n<\/script>\n\n<Dialog.Root bind:open onOpenChangeComplete={handleOpenChangeComplete}>\n <!-- Stripe's card form is tall: scroll within the screen so the buttons stay reachable -->\n <Dialog.Content class=\"max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-[500px]\">\n <Dialog.Header>\n <Dialog.Title>Confirm payment</Dialog.Title>\n <Dialog.Description>\n Are you sure you want to pay {amountFormatted} with your\n {brandNames[brand as keyof typeof brandNames]}\n credit card ending in **** {last4}?\n </Dialog.Description>\n </Dialog.Header>\n <Dialog.Footer>\n <Button variant=\"outline\" onclick={resetDialog} disabled={isProcessing}>Cancel</Button>\n <Button onclick={handlePaymentMethod} disabled={isProcessing}>\n {isProcessing ? 'Processing...' : 'Pay Now'}\n </Button>\n </Dialog.Footer>\n </Dialog.Content>\n</Dialog.Root>\n", u = "<script lang=\"ts\">\n import { Button } from '#lib/components/ui/button/index.js';\n import PaymentDialog from '#lib/components/payments/payment-dialog.svelte';\n import ConfirmDialog from '#lib/components/payments/confirm-dialog.svelte';\n import { useStripe } from '#lib/components/payments/use-stripe.svelte.js';\n import { usePaymentIntent } from '#lib/components/payments/use-payment-intent.svelte.js';\n import type { ButtonProps } from '#lib/components/ui/button/index.js';\n\n interface Props {\n priceId: string;\n user?: { email?: string; name?: string } | null;\n disabled?: boolean;\n isProcessing?: boolean;\n label?: string;\n processingLabel?: string;\n onsuccess?: () => void;\n }\n\n let {\n priceId,\n user,\n disabled = false,\n isProcessing = false,\n label = 'Purchase',\n processingLabel = 'Processing...',\n onsuccess,\n ...rest\n }: Props & ButtonProps = $props();\n\n const stripeManager = useStripe();\n const paymentIntentManager = usePaymentIntent();\n\n let mode = $state<'payment' | 'confirm'>('payment');\n let showDialog = $state(false);\n let amount = $state<number>(0);\n let currency = $state<string>('usd');\n let clientSecret = $state<string>();\n let brand = $state<string>();\n let last4 = $state<string>();\n let setupFutureUsage = $state<'off_session' | null>(null);\n\n async function handleBuyClick() {\n const result = await paymentIntentManager.fetchPaymentIntent({\n priceId\n });\n\n if (!result) return;\n\n if (result.type === 'confirm') {\n mode = 'confirm';\n brand = result.brand;\n last4 = result.last4;\n } else if (result.type === 'payment') {\n mode = 'payment';\n }\n\n amount = result.amount || 0;\n currency = result.currency || 'usd';\n clientSecret = result.clientSecret;\n setupFutureUsage = result.setupFutureUsage ?? null;\n showDialog = true;\n }\n\n function handleDialogOpenChange(open: boolean) {\n showDialog = open;\n }\n\n function handlePaymentSuccess() {\n onsuccess?.();\n }\n<\/script>\n\n<Button disabled={disabled || isProcessing} onclick={handleBuyClick} {...rest}>\n {#if isProcessing}\n {processingLabel}\n {:else}\n {label}\n {/if}\n</Button>\n\n{#if mode === 'confirm'}\n <ConfirmDialog\n bind:open={showDialog}\n stripe={stripeManager.stripe}\n {amount}\n {currency}\n {brand}\n {last4}\n {clientSecret}\n onopenchange={handleDialogOpenChange}\n onsuccess={handlePaymentSuccess}\n />\n{:else if mode === 'payment'}\n <PaymentDialog\n bind:open={showDialog}\n stripe={stripeManager.stripe}\n {amount}\n {currency}\n {clientSecret}\n {setupFutureUsage}\n {user}\n onopenchange={handleDialogOpenChange}\n onsuccess={handlePaymentSuccess}\n />\n{/if}\n", d = "<script lang=\"ts\">\n import type { Stripe, StripeElements } from '@stripe/stripe-js';\n import { Button } from '#lib/components/ui/button/index.js';\n import * as Dialog from '#lib/components/ui/dialog/index.js';\n import { Input } from '#lib/components/ui/input/index.js';\n import { Label } from '#lib/components/ui/label/index.js';\n import { toast } from 'svelte-sonner';\n import { page } from '$app/state';\n import { invalidate } from '$app/navigation';\n import StripePaymentForm from './stripe-payment-form.svelte';\n\n interface Props {\n stripe: Stripe | null;\n open: boolean;\n amount: number;\n currency: string;\n clientSecret?: string;\n /** From the intent: `off_session` when the card is kept for the customer. */\n setupFutureUsage?: 'off_session' | null;\n user?: { email?: string; name?: string } | null;\n onopenchange: (open: boolean) => void;\n onsuccess: () => void;\n }\n\n let {\n stripe,\n open = $bindable(),\n amount,\n currency,\n clientSecret,\n setupFutureUsage = null,\n user = null,\n onopenchange,\n onsuccess\n }: Props = $props();\n\n let isProcessing = $state(false);\n let cardComplete = $state(false);\n let savePaymentMethod = $state(false);\n let email = $state<string>();\n let formRef = $state<{\n getElements: () => StripeElements | null;\n }>();\n\n let amountFormatted = $derived.by(() => {\n let formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: currency });\n return formatter.format(amount / 100);\n });\n\n const handleOpenChangeComplete = (isOpen: boolean) => {\n if (!isOpen) {\n resetDialog();\n }\n onopenchange(isOpen);\n };\n\n function resetDialog() {\n open = false;\n isProcessing = false;\n cardComplete = false;\n }\n\n function handleCardChange(complete: boolean) {\n cardComplete = complete;\n }\n\n async function handlePaymentMethod() {\n if (!stripe || !formRef || !cardComplete || !clientSecret) return;\n\n const elements = formRef.getElements();\n if (!elements) return;\n\n isProcessing = true;\n\n try {\n const { error: submitError } = await elements.submit();\n if (submitError) {\n toast.error(submitError.message || 'Failed to pay for your purchase');\n return;\n }\n\n const { error: confirmError } = await stripe.confirmPayment({\n elements,\n clientSecret,\n confirmParams: {\n return_url: page.url.toString(),\n payment_method_data: {\n billing_details: {\n // Stripe rejects an empty string.\n email: email || user?.email || undefined\n },\n allow_redisplay: savePaymentMethod ? 'always' : 'unspecified'\n }\n },\n redirect: 'if_required'\n });\n\n if (confirmError) {\n toast.error(confirmError.message || 'Failed to pay for your purchase');\n return;\n }\n\n await invalidate('app:billing');\n toast.success('Payment successful');\n onsuccess();\n resetDialog();\n } catch (err) {\n console.error('Error paying for your purchase:', err);\n toast.error('Failed to pay for your purchase');\n } finally {\n isProcessing = false;\n }\n }\n<\/script>\n\n<Dialog.Root bind:open onOpenChangeComplete={handleOpenChangeComplete}>\n <!-- Stripe's card form is tall: scroll within the screen so the buttons stay reachable -->\n <Dialog.Content class=\"max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-[500px]\">\n <Dialog.Header>\n <Dialog.Title>{amountFormatted}</Dialog.Title>\n <Dialog.Description>Enter your card details to pay for your purchase.</Dialog.Description>\n </Dialog.Header>\n <!-- For the receipt: guests, and accounts made with a phone number -->\n {#if !user?.email}\n <div class=\"space-y-2\">\n <Label for=\"email\">Email</Label>\n <Input type=\"email\" bind:value={email} />\n </div>\n {/if}\n <div>\n {#if stripe && open}\n <StripePaymentForm\n bind:this={formRef}\n mode=\"payment\"\n {stripe}\n {amount}\n {currency}\n {savePaymentMethod}\n {setupFutureUsage}\n {user}\n onchange={handleCardChange}\n />\n {/if}\n </div>\n <!-- Only a signed-in customer's card is kept, and so can be shown again -->\n {#if setupFutureUsage}\n <div class=\"flex items-center gap-2\">\n <input type=\"checkbox\" id=\"savePaymentMethod\" bind:checked={savePaymentMethod} />\n <label for=\"savePaymentMethod\" class=\"text-sm text-muted-foreground\">\n Save payment method for future purchases\n </label>\n </div>\n {/if}\n <Dialog.Footer>\n <Button variant=\"outline\" onclick={resetDialog} disabled={isProcessing}>Cancel</Button>\n <Button onclick={handlePaymentMethod} disabled={!cardComplete || isProcessing}>\n {isProcessing ? 'Processing...' : 'Pay Now'}\n </Button>\n </Dialog.Footer>\n </Dialog.Content>\n</Dialog.Root>\n", f = "export const TERMS_AUTO = {\n applePay: \"auto\" as const,\n auBecsDebit: \"auto\" as const,\n bancontact: \"auto\" as const,\n card: \"auto\" as const,\n cashapp: \"auto\" as const,\n googlePay: \"auto\" as const,\n ideal: \"auto\" as const,\n paypal: \"auto\" as const,\n sepaDebit: \"auto\" as const,\n sofort: \"auto\" as const,\n usBankAccount: \"auto\" as const,\n};\n\nexport const TERMS_NEVER = {\n applePay: \"never\" as const,\n auBecsDebit: \"never\" as const,\n bancontact: \"never\" as const,\n card: \"never\" as const,\n cashapp: \"never\" as const,\n googlePay: \"never\" as const,\n ideal: \"never\" as const,\n paypal: \"never\" as const,\n sepaDebit: \"never\" as const,\n sofort: \"never\" as const,\n usBankAccount: \"never\" as const,\n};\n", p = "<script lang=\"ts\">\n import type {\n Stripe,\n StripeElements,\n StripePaymentElement,\n StripeElementsOptionsMode\n } from '@stripe/stripe-js';\n import { mode as modeWatcher } from 'mode-watcher';\n import { TERMS_AUTO, TERMS_NEVER } from './stripe-constants';\n import { onMount } from 'svelte';\n\n interface Props {\n stripe: Stripe;\n mode: 'payment' | 'setup';\n amount?: number;\n currency?: string;\n savePaymentMethod?: boolean;\n /**\n * The intent's `setup_future_usage`, which Elements must match. A setup\n * (adding a card) always keeps the card.\n */\n setupFutureUsage?: 'off_session' | null;\n user?: { email?: string; name?: string } | null;\n onchange: (complete: boolean) => void;\n }\n\n let {\n stripe,\n mode,\n amount = 0,\n currency = 'usd',\n savePaymentMethod = false,\n setupFutureUsage = null,\n user,\n onchange\n }: Props = $props();\n\n let cardContainer = $state<HTMLDivElement | null>(null);\n let elements = $state<StripeElements | null>(null);\n let paymentElement = $state<StripePaymentElement | null>(null);\n\n function initializeElements() {\n if (!stripe) return;\n\n // Clean up previous elements\n if (paymentElement) {\n paymentElement.destroy();\n paymentElement = null;\n }\n\n const appearance = {\n theme: modeWatcher.current === 'dark' ? ('night' as const) : ('stripe' as const),\n inputs: 'condensed' as const,\n labels: 'floating' as const\n };\n\n elements = stripe.elements({\n mode,\n appearance,\n currency,\n ...(mode === 'payment' && {\n amount: amount\n }),\n ...(mode === 'setup' || setupFutureUsage\n ? {\n setupFutureUsage: 'off_session' as const\n }\n : {})\n } as StripeElementsOptionsMode);\n\n paymentElement = elements.create('payment', {\n layout: 'tabs',\n defaultValues: {\n billingDetails: {\n email: user?.email || undefined,\n name: user?.name || undefined\n }\n },\n terms: savePaymentMethod ? TERMS_AUTO : TERMS_NEVER\n });\n\n if (cardContainer && paymentElement) {\n paymentElement.mount(cardContainer);\n paymentElement.on('change', (event: any) => {\n onchange(event.complete);\n });\n }\n }\n\n // Initialize elements when component mounts\n onMount(() => {\n initializeElements();\n\n return () => {\n if (paymentElement) {\n paymentElement.destroy();\n }\n };\n });\n\n // Update terms when savePaymentMethod changes\n $effect(() => {\n if (paymentElement) {\n paymentElement.update({\n terms: savePaymentMethod ? TERMS_AUTO : TERMS_NEVER\n });\n }\n });\n\n export function getElements() {\n return elements;\n }\n<\/script>\n\n<div bind:this={cardContainer}></div>\n", m = "import { toast } from \"svelte-sonner\";\n\nexport interface PaymentIntentResult {\n type: \"payment\" | \"confirm\";\n amount?: number;\n currency?: string;\n clientSecret?: string;\n brand?: string;\n last4?: string;\n /**\n * What the intent was created with: `off_session` when the card is kept\n * for the signed-in customer. The card form has to match it.\n */\n setupFutureUsage?: \"off_session\" | null;\n}\n\nexport function usePaymentIntent() {\n let isLoading = $state(false);\n\n async function fetchPaymentIntent({\n priceId,\n }: {\n priceId: string;\n }): Promise<PaymentIntentResult | null> {\n isLoading = true;\n\n const res = await fetch(\"/api/stripe/payment-intent\", {\n method: \"POST\",\n body: JSON.stringify({\n priceId: priceId,\n }),\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n\n if (!res.ok) {\n toast.error(\"Failed to initialize payment\");\n return null;\n }\n\n return res.json();\n }\n\n async function fetchSetupIntent(): Promise<PaymentIntentResult | null> {\n isLoading = true;\n\n const res = await fetch(\"/api/stripe/setup-intent\", {\n method: \"POST\",\n });\n\n if (!res.ok) {\n toast.error(\"Failed to initialize setup\");\n return null;\n }\n\n return res.json();\n }\n\n return {\n get isLoading() {\n return isLoading;\n },\n fetchPaymentIntent,\n fetchSetupIntent,\n };\n}\n", h = "import { loadStripe, type Stripe } from \"@stripe/stripe-js\";\nimport { toast } from \"svelte-sonner\";\nimport { PUBLIC_STRIPE_PUBLISHABLE_KEY } from \"$app/env/public\";\n\nexport function useStripe() {\n let stripe = $state<Stripe | null>(null);\n let isLoading = $state(true);\n let error = $state<string | null>(null);\n\n async function initialize() {\n try {\n stripe = await loadStripe(PUBLIC_STRIPE_PUBLISHABLE_KEY);\n isLoading = false;\n } catch (err) {\n console.error(\"Failed to load Stripe:\", err);\n error = \"Failed to initialize payment system\";\n toast.error(\"Failed to initialize payment system\");\n isLoading = false;\n }\n }\n\n // Auto-initialize\n initialize();\n\n return {\n get stripe() {\n return stripe;\n },\n get isLoading() {\n return isLoading;\n },\n get error() {\n return error;\n },\n };\n}\n", g = "import { STRIPE_SECRET_KEY } from \"$app/env/private\";\nimport Stripe from \"stripe\";\n\nlet client: Stripe | undefined;\n\nfunction getClient(): Stripe {\n if (!client) {\n if (!STRIPE_SECRET_KEY) {\n throw new Error(\n \"STRIPE_SECRET_KEY is not set, so Stripe cannot be called.\",\n );\n }\n // No apiVersion: the SDK pins the version it was built for, and naming one\n // here fell behind it in every fresh project.\n client = new Stripe(STRIPE_SECRET_KEY);\n }\n return client;\n}\n\n// Built on first use, not on import. The workflow worker imports every workflow\n// at startup, and some import this module, so a client built at module scope\n// takes the whole server down wherever the key is unset - a pull request\n// preview, say - instead of failing only the requests that need Stripe.\nconst stripe = new Proxy({} as Stripe, {\n get(_target, property) {\n const value = Reflect.get(getClient(), property);\n return typeof value === \"function\" ? value.bind(getClient()) : value;\n },\n});\n\nexport default stripe;\n", _ = "import type Stripe from 'stripe';\nimport { getAdmin, ow } from '#lib/server/workflows.js';\nimport { dispatchStripeEvent } from '../../routes/webhooks/stripe/handlers/dispatch';\n\n/**\n * One run per Stripe event, keyed on the event id by the webhook route, so\n * Stripe's retries and a replay from its dashboard land on the run that\n * already exists. A handler that throws is retried with backoff; the run and\n * its error are listed under Workflows in the PocketBase dashboard.\n */\nexport const handleStripeEvent = ow.defineWorkflow<Stripe.Event, void>(\n { name: 'stripe-event', retryPolicy: { maximumAttempts: 5 } },\n async ({ input: event, step }) => {\n await step.run({ name: event.type }, async () => {\n const admin = await getAdmin();\n await dispatchStripeEvent(event, { admin } as App.Locals);\n });\n }\n);\n", v = "import stripe from '#lib/stripe.js';\nimport { getAdmin, ow } from '#lib/server/workflows.js';\n\n/** Copies every Stripe product into stripe_products, adding new ones and updating the rest. */\nexport const syncStripeProducts = ow.defineWorkflow(\n { name: 'sync-stripe-products', retryPolicy: { maximumAttempts: 3 } },\n async ({ step }) => {\n const products = await step.run({ name: 'list' }, async () => {\n const rows = [];\n for await (const product of stripe.products.list({ limit: 100 })) {\n rows.push({\n id: product.id,\n name: product.name,\n active: product.active,\n default_price:\n typeof product.default_price === 'string'\n ? product.default_price\n : (product.default_price?.id ?? null)\n });\n }\n return rows;\n });\n\n await step.run({ name: 'upsert' }, async () => {\n const admin = await getAdmin();\n for (const product of products) {\n try {\n await admin.collection('stripe_products').update(product.id, product);\n } catch {\n await admin.collection('stripe_products').create(product);\n }\n }\n });\n\n return { synced: products.length };\n }\n);\n\n/** The same for prices. */\nexport const syncStripePrices = ow.defineWorkflow(\n { name: 'sync-stripe-prices', retryPolicy: { maximumAttempts: 3 } },\n async ({ step }) => {\n const prices = await step.run({ name: 'list' }, async () => {\n const rows = [];\n for await (const price of stripe.prices.list({ limit: 100 })) {\n rows.push({\n id: price.id,\n billing_scheme: price.billing_scheme,\n currency: price.currency,\n product: typeof price.product === 'string' ? price.product : price.product.id,\n recurring: price.recurring,\n type: price.type,\n unit_amount: price.unit_amount,\n active: price.active\n });\n }\n return rows;\n });\n\n await step.run({ name: 'upsert' }, async () => {\n const admin = await getAdmin();\n for (const price of prices) {\n try {\n await admin.collection('stripe_prices').update(price.id, price);\n } catch {\n await admin.collection('stripe_prices').create(price);\n }\n }\n });\n\n return { synced: prices.length };\n }\n);\n\n/** Both run on this schedule; a product or price changed in Stripe shows up within ten minutes. */\nexport const cron = '*/10 * * * *';\n", y = "import stripe from \"#lib/stripe.js\";\nimport type { Stripe } from \"stripe\";\n\nconst createPaymentIntent = async (price: Stripe.Price) => {\n if (price.unit_amount === null || price.unit_amount === undefined) {\n console.error(\"Price does not have a per unit amount\");\n throw new Error(\"Price does not have a per unit amount\");\n }\n\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n if (!intent.client_secret) {\n console.error(\"Payment intent created without client secret\");\n throw new Error(\"Failed to create payment intent\");\n }\n\n return {\n type: \"payment\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n // A guest's card is not kept, so the card form must not ask to keep it.\n setupFutureUsage: null,\n };\n};\n\nexport const POST = async ({ request, locals }) => {\n let body;\n try {\n body = await request.json();\n } catch (error) {\n console.error(\"Invalid JSON in request body\");\n return Response.json({ error: \"Invalid request body\" }, { status: 400 });\n }\n\n const { priceId } = body as { priceId?: string };\n\n // Validate required fields\n if (!priceId || typeof priceId !== \"string\" || priceId === \"\") {\n console.error(\"Missing or invalid priceId\");\n return Response.json({ error: \"Price ID is required\" }, { status: 400 });\n }\n\n // Retrieve price from Stripe\n let price;\n try {\n price = await stripe.prices.retrieve(priceId);\n } catch (error) {\n console.error(\"Failed to retrieve price from Stripe:\", priceId);\n return Response.json(\n { error: \"Invalid price ID or price not found\" },\n { status: 404 },\n );\n }\n\n // Validate price is active\n if (!price.active) {\n console.error(\"Price is not active:\", priceId);\n return Response.json(\n { error: \"This price is no longer available\" },\n { status: 400 },\n );\n }\n\n try {\n const res = await createPaymentIntent(price);\n return Response.json(res, { status: 200 });\n } catch (error) {\n console.error(\"Error creating payment intent for price:\", priceId);\n const errorMessage =\n error instanceof Error\n ? error.message\n : \"Failed to create payment intent\";\n return Response.json({ error: errorMessage }, { status: 500 });\n }\n};\n", b = "import { describe, it, expect, beforeAll } from \"vitest\";\nimport type { Match } from \"@velastack/kit\";\nimport type { RouteId } from \"./$types\";\nimport stripe from \"#lib/stripe.js\";\nimport type Stripe from \"stripe\";\n\ndescribe(\"POST /api/stripe/payment-intent\", () => {\n let product: Stripe.Product;\n let activePrice: Stripe.Price;\n let inactivePrice: Stripe.Price;\n\n beforeAll(async () => {\n const productName = \"Test Product - Payment Intent\";\n const products = await stripe.products.search({\n query: `name:\"${productName}\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n product = products.data[0];\n\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n\n if (prices.data.length > 0) {\n activePrice = prices.data[0];\n }\n\n const inactivePrices = await stripe.prices.list({\n product: product.id,\n active: false,\n limit: 1,\n });\n\n if (inactivePrices.data.length > 0) {\n inactivePrice = inactivePrices.data[0];\n }\n }\n\n // Create if not found or no active price\n if (!product) {\n product = await stripe.products.create({\n name: productName,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!activePrice) {\n activePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!inactivePrice) {\n inactivePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 2000,\n currency: \"usd\",\n active: false,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent-inactive\",\n },\n });\n }\n });\n\n describe(\"Request validation\", () => {\n it(\"should return 400 if request body is not valid JSON\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .set(\"Content-Type\", \"application/json\")\n .send(\"invalid json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Invalid request body\");\n });\n\n it(\"should return 400 if priceId is missing\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({});\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is not a string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: 12345 });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is an empty string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"\" });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 404 if price does not exist\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"price_nonexistent123\" });\n\n expect(response.status).toBe(404);\n expect(response.body.error).toBe(\"Invalid price ID or price not found\");\n });\n\n it(\"should return 400 if price is not active\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: inactivePrice.id });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"This price is no longer available\");\n });\n });\n\n describe(\"Guest user (unauthenticated)\", () => {\n it(\"should create payment intent for guest user\", async (context) => {\n const response = await context.request\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBeUndefined();\n expect(response.body.last4).toBeUndefined();\n expect(response.body.setupFutureUsage).toBeNull();\n\n // Verify the payment intent was created in Stripe\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.amount).toBe(1000);\n expect(intent.currency).toBe(\"usd\");\n expect(intent.customer).toBeNull();\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n});\n", x = "import Stripe from 'stripe';\nimport { STRIPE_WEBHOOK_SECRET } from '$app/env/private';\nimport stripe from '#lib/stripe.js';\nimport { handleStripeEvent } from '#lib/workflows/stripe-event.js';\n\nasync function verifyWebhookSignature(request: Request, webhookSecret: string): Promise<Stripe.Event> {\n const body = await request.text();\n const signature = request.headers.get('stripe-signature');\n\n if (!signature) {\n throw new Error('Missing stripe-signature header');\n }\n\n if (!webhookSecret) {\n throw new Error('Missing webhook secret');\n }\n\n try {\n return stripe.webhooks.constructEvent(body, signature, webhookSecret);\n } catch (err) {\n console.error('Webhook signature verification failed:', err);\n throw new Error('Invalid signature');\n }\n}\n\nexport const POST = async ({ request }) => {\n try {\n const event = await verifyWebhookSignature(request, STRIPE_WEBHOOK_SECRET);\n\n // Queued, not handled here: the workflow runs the handler with retries,\n // and its idempotency key means a redelivery of the same event returns\n // the existing run instead of handling it twice.\n const handle = await handleStripeEvent.run(event, { idempotencyKey: event.id });\n console.log(`Queued webhook event ${event.type} (${event.id}) as run ${handle.workflowRun.id}`);\n\n return Response.json({\n received: true,\n eventId: event.id,\n eventType: event.type,\n runId: handle.workflowRun.id\n });\n } catch (error) {\n console.error('Webhook processing error:', error);\n\n return Response.json(\n {\n error: 'Webhook processing failed',\n message: error instanceof Error ? error.message : 'Unknown error'\n },\n { status: 400 }\n );\n }\n};\n", S = "import type Stripe from 'stripe';\nimport { handlePaymentIntentSucceeded } from './payment-intent/succeeded';\n\n/**\n * Routes a verified Stripe event to its handler. Runs inside the stripe-event\n * workflow, so a handler that throws is retried with backoff rather than lost.\n */\nexport async function dispatchStripeEvent(event: Stripe.Event, locals: App.Locals) {\n switch (event.type) {\n case 'payment_intent.succeeded':\n await handlePaymentIntentSucceeded(event.data.object, locals);\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n}\n", C = "import { describe, it, expect } from \"vitest\";\nimport stripe from \"#lib/stripe.js\";\nimport { handlePaymentIntentSucceeded } from \"./succeeded\";\n\ndescribe(\"payment_intent.succeeded\", () => {\n it(\"handles a payment intent successfully\", async (context) => {\n const paymentIntent = await stripe.paymentIntents.create({\n amount: 2000,\n currency: \"usd\",\n });\n const locals = { admin: context.admin } as App.Locals;\n const result = await handlePaymentIntentSucceeded(paymentIntent, locals);\n\n expect(result).toEqual({});\n });\n});\n", w = "import Stripe from \"stripe\";\n\n/**\n * Handles payment_intent.succeeded event\n */\nexport async function handlePaymentIntentSucceeded(\n paymentIntent: Stripe.PaymentIntent,\n locals: App.Locals,\n) {\n return {};\n}\n", T = "import { describe, it, expect } from \"vitest\";\nimport type { RouteId } from \"./$types\";\nimport type { Match } from \"@velastack/kit\";\nimport type Stripe from \"stripe\";\nimport stripe from \"#lib/stripe.js\";\n\ndescribe(\"POST /webhooks/stripe\", () => {\n it(\"accepts valid webhook signature\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2026-08-26.dahlia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;\n\n const signature = stripe.webhooks.generateTestHeaderString({\n payload,\n secret: webhookSecret,\n });\n\n const response = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", signature)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response.status).toBe(200);\n expect(response.body.received).toBe(true);\n expect(response.body.eventId).toBe(event.id);\n expect(response.body.eventType).toBe(\"test.event\");\n });\n\n it(\"rejects invalid webhook signature\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2026-08-26.dahlia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n\n const response = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", \"invalid_signature\")\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Webhook processing failed\");\n });\n\n it(\"rejects request without signature header\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2026-08-26.dahlia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n\n const response = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Webhook processing failed\");\n expect(response.body.message).toBe(\"Missing stripe-signature header\");\n });\n\n it(\"handles duplicate webhook events\", async (context) => {\n const event = {\n id: `evt_test_${Date.now()}`,\n object: \"event\",\n api_version: \"2026-08-26.dahlia\",\n created: Math.floor(Date.now() / 1000),\n type: \"test.event\",\n data: {\n object: {},\n },\n livemode: false,\n pending_webhooks: 0,\n request: {\n id: null,\n idempotency_key: null,\n },\n } as unknown as Stripe.Event;\n\n const payload = JSON.stringify(event);\n const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;\n const signature = stripe.webhooks.generateTestHeaderString({\n payload,\n secret: webhookSecret,\n });\n\n // Send first webhook\n const response1 = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", signature)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n expect(response1.status).toBe(200);\n expect(response1.body.received).toBe(true);\n\n // Send duplicate webhook\n const response2 = await context.request\n .post(\"/webhooks/stripe\" satisfies Match<RouteId>)\n .set(\"stripe-signature\", signature)\n .send(payload)\n .set(\"Content-Type\", \"application/json\");\n\n // The same event id lands on the same workflow run.\n expect(response2.status).toBe(200);\n expect(response2.body.received).toBe(true);\n expect(response2.body.runId).toBe(response1.body.runId);\n });\n});\n", E = "<script lang=\"ts\">\n import { Button } from '#lib/components/ui/button/index.js';\n import SetupDialog from '#lib/components/payments/setup-dialog.svelte';\n import { useStripe } from '#lib/components/payments/use-stripe.svelte.js';\n import { usePaymentIntent } from '#lib/components/payments/use-payment-intent.svelte.js';\n\n interface Props {\n disabled?: boolean;\n isProcessing?: boolean;\n label?: string;\n processingLabel?: string;\n onsuccess?: () => void;\n }\n\n let {\n disabled = false,\n isProcessing = false,\n label,\n processingLabel,\n onsuccess\n }: Props = $props();\n\n const stripeManager = useStripe();\n const paymentIntentManager = usePaymentIntent();\n\n let showDialog = $state(false);\n let clientSecret = $state<string>();\n\n async function handleSetupClick() {\n const result = await paymentIntentManager.fetchSetupIntent();\n\n if (!result) return;\n\n clientSecret = result.clientSecret;\n showDialog = true;\n }\n\n function handleDialogOpenChange(open: boolean) {\n showDialog = open;\n }\n\n function handlePaymentSuccess() {\n onsuccess?.();\n }\n<\/script>\n\n<Button disabled={disabled || isProcessing} onclick={handleSetupClick}>\n {#if isProcessing}\n {processingLabel}\n {:else}\n {label}\n {/if}\n</Button>\n\n<SetupDialog\n bind:open={showDialog}\n stripe={stripeManager.stripe}\n {clientSecret}\n onopenchange={handleDialogOpenChange}\n onsuccess={handlePaymentSuccess}\n/>\n", D = "<script lang=\"ts\">\n import type { Stripe, StripeElements } from '@stripe/stripe-js';\n import { Button } from '#lib/components/ui/button/index.js';\n import * as Dialog from '#lib/components/ui/dialog/index.js';\n import { toast } from 'svelte-sonner';\n import { page } from '$app/state';\n import { invalidate } from '$app/navigation';\n import StripePaymentForm from './stripe-payment-form.svelte';\n\n interface Props {\n stripe: Stripe | null;\n open: boolean;\n clientSecret?: string;\n onopenchange: (open: boolean) => void;\n onsuccess: () => void;\n }\n\n let { stripe, open = $bindable(), clientSecret, onopenchange, onsuccess }: Props = $props();\n\n let isProcessing = $state(false);\n let cardComplete = $state(false);\n let formRef = $state<{\n getElements: () => StripeElements | null;\n }>();\n\n const handleOpenChangeComplete = (isOpen: boolean) => {\n if (!isOpen) {\n resetDialog();\n }\n onopenchange(isOpen);\n };\n\n function resetDialog() {\n open = false;\n isProcessing = false;\n cardComplete = false;\n }\n\n function handleCardChange(complete: boolean) {\n cardComplete = complete;\n }\n\n async function handleSetupPaymentMethod() {\n if (!stripe || !formRef || !cardComplete || !clientSecret) return;\n\n const elements = formRef.getElements();\n if (!elements) return;\n\n isProcessing = true;\n\n try {\n const { error: submitError } = await elements.submit();\n if (submitError) {\n toast.error(submitError.message || 'Failed to add payment method');\n return;\n }\n\n const { error: confirmError } = await stripe.confirmSetup({\n elements,\n clientSecret,\n confirmParams: {\n return_url: page.url.toString(),\n payment_method_data: {\n allow_redisplay: 'always'\n }\n },\n redirect: 'if_required'\n });\n\n if (confirmError) {\n toast.error(confirmError.message || 'Failed to add payment method');\n return;\n }\n\n await invalidate('app:billing');\n toast.success('Payment method added successfully');\n onsuccess();\n resetDialog();\n } catch (err) {\n console.error('Error adding payment method:', err);\n toast.error('Failed to add payment method');\n } finally {\n isProcessing = false;\n }\n }\n<\/script>\n\n<Dialog.Root bind:open onOpenChangeComplete={handleOpenChangeComplete}>\n <!-- Stripe's card form is tall: scroll within the screen so the buttons stay reachable -->\n <Dialog.Content class=\"max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-[500px]\">\n <Dialog.Header>\n <Dialog.Title>Add payment method</Dialog.Title>\n <Dialog.Description>Enter your card details to add a new payment method.</Dialog.Description>\n </Dialog.Header>\n <div>\n {#if stripe && open}\n <StripePaymentForm\n bind:this={formRef}\n mode=\"setup\"\n {stripe}\n onchange={handleCardChange}\n savePaymentMethod={true}\n />\n {/if}\n </div>\n <Dialog.Footer>\n <Button variant=\"outline\" onclick={resetDialog} disabled={isProcessing}>Cancel</Button>\n <Button onclick={handleSetupPaymentMethod} disabled={!cardComplete || isProcessing}>\n {isProcessing ? 'Processing...' : 'Add Card'}\n </Button>\n </Dialog.Footer>\n </Dialog.Content>\n</Dialog.Root>\n", O = "import { z } from 'zod';\nimport stripe from '#lib/stripe.js';\nimport { getAdmin, ow } from '#lib/server/workflows.js';\n\n/**\n * Gives a user a Stripe customer, reusing one that already carries the email\n * and copying over its saved cards. A user without an email (one made with a\n * phone number) gets a new customer under their name and number. Signup starts\n * it with the user's id as the idempotency key, so however many times it is\n * started or retried there is one run and one customer per user.\n */\nexport const linkStripeCustomer = ow.defineWorkflow(\n {\n name: 'link-stripe-customer',\n schema: z.object({ userId: z.string(), email: z.string().optional() }),\n retryPolicy: { maximumAttempts: 5 }\n },\n async ({ input, step }) => {\n const customer = await step.run({ name: 'find-or-create-customer' }, async () => {\n if (!input.email) {\n const admin = await getAdmin();\n // `phone` is there once enable-whatsapp has added it.\n const user: { name?: string; phone?: string } = await admin\n .collection('users')\n .getOne(input.userId);\n const created = await stripe.customers.create({\n name: user.name || undefined,\n phone: user.phone || undefined\n });\n return { id: created.id, existing: false, defaultPaymentMethod: null };\n }\n\n const matching = await stripe.customers.list({\n email: input.email,\n limit: 1,\n expand: ['data.invoice_settings']\n });\n const existing = matching.data[0];\n if (existing) {\n const method = existing.invoice_settings?.default_payment_method;\n return {\n id: existing.id,\n existing: true,\n defaultPaymentMethod: typeof method === 'string' ? method : (method?.id ?? null)\n };\n }\n const created = await stripe.customers.create({ email: input.email });\n return { id: created.id, existing: false, defaultPaymentMethod: null };\n });\n\n await step.run({ name: 'record-customer' }, async () => {\n const admin = await getAdmin();\n try {\n await admin.collection('stripe_customers').getOne(customer.id);\n } catch {\n await admin.collection('stripe_customers').create({ id: customer.id, user: input.userId });\n }\n });\n\n if (!customer.existing) return { customerId: customer.id, cards: 0 };\n\n const cards = await step.run({ name: 'list-cards' }, async () => {\n const methods = await stripe.customers.listPaymentMethods(customer.id, {\n type: 'card',\n allow_redisplay: 'always'\n });\n return methods.data\n .filter((method) => method.allow_redisplay !== 'unspecified')\n .map((method) => ({\n id: method.id,\n brand: method.card?.brand,\n last4: method.card?.last4,\n exp_month: method.card?.exp_month,\n exp_year: method.card?.exp_year\n }));\n });\n\n await step.run({ name: 'record-cards' }, async () => {\n const admin = await getAdmin();\n for (const card of cards) {\n try {\n await admin.collection('stripe_payment_methods').create({ ...card, customer: customer.id });\n } catch {\n // Already recorded by an earlier attempt.\n }\n }\n if (customer.defaultPaymentMethod) {\n try {\n await admin.collection('stripe_customers').update(customer.id, {\n default_payment_method: customer.defaultPaymentMethod\n });\n } catch {\n // The default card was not one that can be shown again.\n }\n }\n });\n\n return { customerId: customer.id, cards: cards.length };\n }\n);\n", k = "import { getAdmin, ow } from '#lib/server/workflows.js';\nimport { linkStripeCustomer } from './link-stripe-customer';\n\n/**\n * The safety net for users that did not come through signup (the dashboard,\n * an import): starts link-stripe-customer for each one without a customer.\n * The idempotency key means a user whose run already exists, finished or\n * still retrying, is left alone.\n */\nexport const syncStripeCustomers = ow.defineWorkflow(\n { name: 'sync-stripe-customers', retryPolicy: { maximumAttempts: 3 } },\n async ({ step }) => {\n const users = await step.run({ name: 'find-unlinked' }, async () => {\n const admin = await getAdmin();\n const rows = await admin\n .collection('users')\n .getFullList({ filter: 'stripe_customers_via_user.id = null' });\n return rows.map((user) => ({ id: user.id, email: user.email || undefined }));\n });\n\n await step.run({ name: 'start-links' }, async () => {\n for (const user of users) {\n await linkStripeCustomer.run(\n { userId: user.id, email: user.email },\n { idempotencyKey: user.id }\n );\n }\n });\n\n return { queued: users.length };\n }\n);\n\nexport const cron = '*/10 * * * *';\n", A = "export const load = async ({ parent }) => {\n const { breadcrumbs } = await parent();\n\n return {\n breadcrumbs: [...breadcrumbs, { title: \"Billing\", url: \"/billing\" }],\n };\n};\n", j = "# Billing Page - Stripe Payment Methods\n\nThis billing page provides a modern UI for managing payment methods with Stripe.\n\n## Features\n\n✅ **Display Payment Methods** - Shows all saved cards with brand, last 4 digits, and expiration\n✅ **Add Payment Methods** - Secure card input using Stripe Elements\n✅ **Remove Payment Methods** - Delete cards with confirmation dialog\n✅ **Default Payment Method** - Set and display the default payment method\n✅ **Responsive Design** - Mobile-friendly layout\n✅ **Error Handling** - Toast notifications for user feedback\n\n## Current Status\n\nThe frontend is **fully functional** with mock data. To connect to your backend, follow the integration steps below.\n\n## Backend Integration\n\n### 1. Update Stripe Publishable Key\n\nIn `+page.svelte`, replace the placeholder with your actual Stripe publishable key:\n\n```typescript\nconst STRIPE_PUBLISHABLE_KEY = \"pk_test_YOUR_KEY_HERE\";\n```\n\nOr better yet, load it from environment variables:\n\n```typescript\nimport { PUBLIC_STRIPE_PUBLISHABLE_KEY } from \"$app/env/public\";\nconst STRIPE_PUBLISHABLE_KEY = PUBLIC_STRIPE_PUBLISHABLE_KEY;\n```\n\n### 2. Fetch Payment Methods on Load\n\nUpdate `+page.server.ts` to fetch payment methods:\n\n```typescript\nexport const load: PageServerLoad = async ({ locals }) => {\n const user = locals.user;\n\n if (!user?.stripeCustomerId) {\n return { paymentMethods: [] };\n }\n\n // Fetch payment methods from Stripe\n const stripe = await import(\"#lib/stripe.js\").then((m) => m.default);\n const paymentMethods = await stripe.paymentMethods.list({\n customer: user.stripeCustomerId,\n type: \"card\",\n });\n\n return {\n paymentMethods: paymentMethods.data.map((pm) => ({\n id: pm.id,\n brand: pm.card?.brand || \"unknown\",\n last4: pm.card?.last4 || \"0000\",\n expMonth: pm.card?.exp_month || 1,\n expYear: pm.card?.exp_year || 2025,\n isDefault: false, // You'll need to track this separately\n })),\n };\n};\n```\n\n### 3. Create API Endpoints\n\nCreate the following server endpoints:\n\n#### Add Payment Method: `+page.server.ts`\n\n```typescript\nexport const actions = {\n addPaymentMethod: async ({ request, locals }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\");\n\n // Attach payment method to customer\n const stripe = await import(\"#lib/stripe.js\").then((m) => m.default);\n await stripe.paymentMethods.attach(paymentMethodId, {\n customer: locals.user.stripeCustomerId,\n });\n\n return { success: true };\n },\n\n removePaymentMethod: async ({ request, locals }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\");\n\n // Detach payment method from customer\n const stripe = await import(\"#lib/stripe.js\").then((m) => m.default);\n await stripe.paymentMethods.detach(paymentMethodId);\n\n return { success: true };\n },\n\n setDefaultPaymentMethod: async ({ request, locals }) => {\n const formData = await request.formData();\n const paymentMethodId = formData.get(\"paymentMethodId\");\n\n // Update customer's default payment method\n const stripe = await import(\"#lib/stripe.js\").then((m) => m.default);\n await stripe.customers.update(locals.user.stripeCustomerId, {\n invoice_settings: {\n default_payment_method: paymentMethodId,\n },\n });\n\n return { success: true };\n },\n};\n```\n\n### 4. Update Frontend to Use Actions\n\nReplace the mock functions in `+page.svelte`:\n\n```typescript\nasync function handleAddPaymentMethod() {\n if (!stripe || !cardElement || !cardComplete) return;\n\n isProcessing = true;\n\n try {\n const { error, paymentMethod } = await stripe.createPaymentMethod({\n type: \"card\",\n card: cardElement,\n });\n\n if (error) {\n toast.error(error.message);\n return;\n }\n\n // Submit to your backend\n const formData = new FormData();\n formData.append(\"paymentMethodId\", paymentMethod.id);\n\n const response = await fetch(\"?/addPaymentMethod\", {\n method: \"POST\",\n body: formData,\n });\n\n if (response.ok) {\n toast.success(\"Payment method added\");\n // Reload page to fetch updated payment methods\n window.location.reload();\n }\n } finally {\n isProcessing = false;\n }\n}\n```\n\n## Security Considerations\n\n⚠️ **Important**: Never expose your Stripe secret key on the frontend\n✅ All sensitive operations should happen on your backend\n✅ Use Stripe's publishable key for frontend operations\n✅ Validate user permissions before modifying payment methods\n✅ Use HTTPS in production\n\n## Testing\n\nUse [Stripe's test cards](https://stripe.com/docs/testing) for testing:\n\n- **Success**: 4242 4242 4242 4242\n- **Decline**: 4000 0000 0000 0002\n- **Requires authentication**: 4000 0025 0000 3155\n\nUse any future expiration date and any 3-digit CVC.\n\n## Styling\n\nThe page uses Tailwind CSS and shadcn/ui components. All components are styled to match your existing design system with support for light/dark modes.\n\n### Stripe Elements Styling\n\nSince Stripe Elements render in an iframe, they cannot access CSS variables directly. Additionally, Stripe only accepts HEX, RGB, or HSL colors (not modern formats like OKLCH).\n\nThe implementation:\n\n1. **Creates temporary DOM elements** with CSS variables applied\n2. **Lets the browser compute colors** - converts OKLCH/HSL/any format to RGB\n3. **Extracts RGB values** that Stripe Elements can understand\n4. **Passes computed colors** to Stripe Elements on initialization\n5. **Matches the current theme** automatically (light/dark mode)\n\nThis approach works with any CSS color format (oklch, hsl, rgb, hex) and ensures Stripe Elements always match your theme when the \"Add Payment Method\" dialog opens.\n\n## Dependencies\n\n- `@stripe/stripe-js` - Stripe.js for frontend\n- `stripe` - Stripe Node.js SDK for backend\n- `svelte-sonner` - Toast notifications\n- `@lucide/svelte` - Icons\n- shadcn/ui components\n", M = "import stripe from \"#lib/stripe.js\";\nimport type { Stripe } from \"stripe\";\nimport { getStripeCustomerId } from \"#lib/server/stripe-customer.js\";\n\nconst createPaymentIntent = async (\n price: Stripe.Price,\n customer?: { id: string; default_payment_method?: string },\n) => {\n if (price.unit_amount === null || price.unit_amount === undefined) {\n console.error(\"Price does not have a per unit amount\");\n throw new Error(\"Price does not have a per unit amount\");\n }\n\n // Guest\n if (!customer) {\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n if (!intent.client_secret) {\n console.error(\"Payment intent created without client secret\");\n throw new Error(\"Failed to create payment intent\");\n }\n\n return {\n type: \"payment\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n setupFutureUsage: null,\n };\n }\n\n // Customer with saved payment method\n if (customer.default_payment_method) {\n const paymentMethod = await stripe.customers.retrievePaymentMethod(\n customer.id,\n customer.default_payment_method,\n );\n\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n customer: customer.id,\n payment_method: customer.default_payment_method,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n return {\n type: \"confirm\",\n clientSecret: intent.client_secret,\n setupFutureUsage: null,\n amount: price.unit_amount,\n currency: price.currency,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n };\n }\n\n // Customer without saved payment method\n const intent = await stripe.paymentIntents.create({\n amount: price.unit_amount,\n currency: price.currency,\n customer: customer.id,\n setup_future_usage: \"off_session\",\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n if (!intent.client_secret) {\n console.error(\"Payment intent created without client secret\");\n throw new Error(\"Failed to create payment intent\");\n }\n\n return {\n type: \"payment\",\n clientSecret: intent.client_secret,\n amount: price.unit_amount,\n currency: price.currency,\n // The card form must set the same `setupFutureUsage` as the intent, or\n // Stripe refuses to confirm it.\n setupFutureUsage: \"off_session\",\n };\n};\n\nexport const POST = async ({ request, locals }) => {\n const user = locals.pb.authStore.record;\n\n let body;\n try {\n body = await request.json();\n } catch (error) {\n console.error(\"Invalid JSON in request body\");\n return Response.json({ error: \"Invalid request body\" }, { status: 400 });\n }\n\n const { priceId } = body as { priceId?: string };\n\n // Validate required fields\n if (!priceId || typeof priceId !== \"string\" || priceId === \"\") {\n console.error(\"Missing or invalid priceId\");\n return Response.json({ error: \"Price ID is required\" }, { status: 400 });\n }\n\n // Retrieve price from Stripe\n let price;\n try {\n price = await stripe.prices.retrieve(priceId);\n } catch (error) {\n console.error(\"Failed to retrieve price from Stripe:\", priceId);\n return Response.json(\n { error: \"Invalid price ID or price not found\" },\n { status: 404 },\n );\n }\n\n // Validate price is active\n if (!price.active) {\n console.error(\"Price is not active:\", priceId);\n return Response.json(\n { error: \"This price is no longer available\" },\n { status: 400 },\n );\n }\n\n let customer;\n\n if (user) {\n try {\n // Links the user to a Stripe customer first if they have none yet (a\n // signup whose link run has not finished, a one-time-code signup).\n const customerId = await getStripeCustomerId(locals.admin, user);\n customer = await locals.admin\n .collection(\"stripe_customers\")\n .getOne(customerId);\n } catch (error) {\n // Not linked in time: pay as a guest rather than not at all.\n console.log(\"No Stripe customer for user, paying as a guest:\", user.id);\n }\n }\n\n try {\n const res = await createPaymentIntent(price, customer);\n return Response.json(res, { status: 200 });\n } catch (error) {\n console.error(\"Error creating payment intent for price:\", priceId);\n const errorMessage =\n error instanceof Error\n ? error.message\n : \"Failed to create payment intent\";\n return Response.json({ error: errorMessage }, { status: 500 });\n }\n};\n", N = "import { describe, it, expect, beforeAll, beforeEach, afterEach } from \"vitest\";\nimport type { Match } from \"@velastack/kit\";\nimport type { RouteId } from \"./$types\";\nimport stripe from \"#lib/stripe.js\";\nimport type Stripe from \"stripe\";\n\ndescribe(\"POST /api/stripe/payment-intent\", () => {\n let product: Stripe.Product;\n let activePrice: Stripe.Price;\n let inactivePrice: Stripe.Price;\n let stripeCustomer: Stripe.Customer;\n let paymentMethod: Stripe.PaymentMethod;\n\n beforeAll(async () => {\n const productName = \"Test Product - Payment Intent\";\n const products = await stripe.products.search({\n query: `name:\"${productName}\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n product = products.data[0];\n\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n\n if (prices.data.length > 0) {\n activePrice = prices.data[0];\n }\n\n const inactivePrices = await stripe.prices.list({\n product: product.id,\n active: false,\n limit: 1,\n });\n\n if (inactivePrices.data.length > 0) {\n inactivePrice = inactivePrices.data[0];\n }\n }\n\n // Create if not found or no active price\n if (!product) {\n product = await stripe.products.create({\n name: productName,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!activePrice) {\n activePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n metadata: {\n test: \"true\",\n test_type: \"payment-intent\",\n },\n });\n }\n\n if (!inactivePrice) {\n inactivePrice = await stripe.prices.create({\n product: product.id,\n unit_amount: 2000,\n currency: \"usd\",\n active: false,\n metadata: {\n test: \"true\",\n test_type: \"payment-intent-inactive\",\n },\n });\n }\n });\n\n beforeEach(async (context) => {\n // Create a Stripe customer for authenticated user tests\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n // Create a payment method for the customer\n paymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_visa\",\n },\n });\n\n await stripe.paymentMethods.attach(paymentMethod.id, {\n customer: stripeCustomer.id,\n });\n });\n\n afterEach(async () => {\n if (paymentMethod?.id) {\n await stripe.paymentMethods.detach(paymentMethod.id);\n }\n\n if (stripeCustomer?.id) {\n await stripe.customers.del(stripeCustomer.id);\n }\n });\n\n describe(\"Request validation\", () => {\n it(\"should return 400 if request body is not valid JSON\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .set(\"Content-Type\", \"application/json\")\n .send(\"invalid json\");\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Invalid request body\");\n });\n\n it(\"should return 400 if priceId is missing\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({});\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is not a string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: 12345 });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 400 if priceId is an empty string\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"\" });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"Price ID is required\");\n });\n\n it(\"should return 404 if price does not exist\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: \"price_nonexistent123\" });\n\n expect(response.status).toBe(404);\n expect(response.body.error).toBe(\"Invalid price ID or price not found\");\n });\n\n it(\"should return 400 if price is not active\", async (context) => {\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: inactivePrice.id });\n\n expect(response.status).toBe(400);\n expect(response.body.error).toBe(\"This price is no longer available\");\n });\n });\n\n describe(\"Guest user (unauthenticated)\", () => {\n it(\"should create payment intent for guest user\", async (context) => {\n const response = await context.request\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBeUndefined();\n expect(response.body.last4).toBeUndefined();\n expect(response.body.setupFutureUsage).toBeNull();\n\n // Verify the payment intent was created in Stripe\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.amount).toBe(1000);\n expect(intent.currency).toBe(\"usd\");\n expect(intent.customer).toBeNull();\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n\n describe(\"Authenticated user without Stripe customer\", () => {\n it(\"should link a Stripe customer and keep the card for them\", async (context) => {\n await context.agent.authenticateUser();\n\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.setupFutureUsage).toBe(\"off_session\");\n\n // The link-stripe-customer run linked one on the spot, reusing the\n // Stripe customer that already has the user's email.\n const linked = await context.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(\n context.admin.filter(\"user = {:user}\", { user: context.user.id }),\n );\n expect(linked.id).toBe(stripeCustomer.id);\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.amount).toBe(1000);\n expect(intent.customer).toBe(linked.id);\n expect(intent.setup_future_usage).toBe(\"off_session\");\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n await context.admin.collection(\"stripe_customers\").delete(linked.id);\n });\n });\n\n describe(\"Authenticated user with Stripe customer\", () => {\n let customerRecord: { id: string };\n\n beforeEach(async (context) => {\n // Link the Stripe customer to the PocketBase user\n customerRecord = await context.admin\n .collection(\"stripe_customers\")\n .create({\n user: context.user.id,\n id: stripeCustomer.id,\n email: stripeCustomer.email,\n });\n });\n\n afterEach(async (context) => {\n // Clean up the PocketBase customer record\n await context.admin\n .collection(\"stripe_customers\")\n .delete(customerRecord.id);\n });\n\n it(\"should create payment intent with setup_future_usage for user without default payment method\", async (context) => {\n await context.agent.authenticateUser();\n\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"payment\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBeUndefined();\n expect(response.body.last4).toBeUndefined();\n expect(response.body.setupFutureUsage).toBe(\"off_session\");\n\n // Verify the payment intent has setup_future_usage\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.customer).toBe(stripeCustomer.id);\n expect(intent.setup_future_usage).toBe(\"off_session\");\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n\n it(\"should create payment intent with default payment method for customer with saved payment method\", async (context) => {\n // Set default payment method\n await stripe.customers.update(stripeCustomer.id, {\n invoice_settings: {\n default_payment_method: paymentMethod.id,\n },\n });\n\n const customerRecord = await context.admin\n .collection(\"stripe_customers\")\n .getFirstListItem(\n context.admin.filter(\"user = {:user}\", { user: context.user.id }),\n );\n\n await context.admin.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customerRecord.id,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n exp_month: paymentMethod.card?.exp_month,\n exp_year: paymentMethod.card?.exp_year,\n });\n\n await context.admin\n .collection(\"stripe_customers\")\n .update(customerRecord.id, {\n default_payment_method: paymentMethod.id,\n });\n\n await context.agent.authenticateUser();\n\n const response = await context.agent\n .post(\"/api/stripe/payment-intent\" satisfies Match<RouteId>)\n .send({ priceId: activePrice.id });\n\n expect(response.status).toBe(200);\n expect(response.body.type).toBe(\"confirm\");\n expect(response.body.clientSecret).toBeDefined();\n expect(response.body.amount).toBe(1000);\n expect(response.body.currency).toBe(\"usd\");\n expect(response.body.brand).toBe(\"visa\");\n expect(response.body.last4).toBeDefined();\n expect(response.body.last4).toMatch(/^\\d{4}$/);\n expect(response.body.setupFutureUsage).toBeNull();\n\n // Verify the payment intent has the payment method attached\n const intentId = response.body.clientSecret.split(\"_secret_\")[0];\n const intent = await stripe.paymentIntents.retrieve(intentId);\n expect(intent.customer).toBe(stripeCustomer.id);\n expect(intent.payment_method).toBe(paymentMethod.id);\n\n // Clean up\n await stripe.paymentIntents.cancel(intent.id);\n });\n });\n});\n", P = "import stripe from \"#lib/stripe.js\";\nimport { getStripeCustomerId } from \"#lib/server/stripe-customer.js\";\n\nexport const POST = async ({ locals }) => {\n const user = locals.pb.authStore.record;\n\n if (!user) {\n return Response.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n let customer: string;\n try {\n customer = await getStripeCustomerId(locals.admin, user);\n } catch {\n return Response.json(\n { error: \"Billing is still being set up. Try again shortly.\" },\n { status: 503 },\n );\n }\n\n const setupIntent = await stripe.setupIntents.create({\n customer,\n automatic_payment_methods: {\n enabled: true,\n allow_redirects: \"never\",\n },\n });\n\n return Response.json({ clientSecret: setupIntent.client_secret });\n};\n", F = "import { describe, it, expect, beforeEach, afterEach } from \"vitest\";\nimport type { Match } from \"@velastack/kit\";\nimport type Stripe from \"stripe\";\nimport stripe from \"#lib/stripe.js\";\nimport type { RouteId } from \"./$types\";\n\ndescribe(\"POST /api/stripe/setup-intent\", () => {\n let stripeCustomer: Stripe.Customer;\n\n beforeEach(async (context) => {\n await context.agent.authenticateUser();\n\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n await context.admin.collection(\"stripe_customers\").create({\n id: stripeCustomer.id,\n user: context.user.id,\n });\n });\n\n afterEach(async (context) => {\n await context.admin\n .collection(\"stripe_customers\")\n .delete(stripeCustomer.id);\n });\n\n it(\"creates a setup intent\", async (context) => {\n const response = await context.agent.post(\n \"/api/stripe/setup-intent\" satisfies Match<RouteId>,\n );\n expect(response.status).toBe(200);\n expect(response.body.clientSecret).toBeDefined();\n });\n});\n", I = "import type Stripe from 'stripe';\nimport { handlePaymentIntentSucceeded } from './payment-intent/succeeded';\nimport { handlePaymentMethodAttached } from './payment-method/attached';\n\n/**\n * Routes a verified Stripe event to its handler. Runs inside the stripe-event\n * workflow, so a handler that throws is retried with backoff rather than lost.\n */\nexport async function dispatchStripeEvent(event: Stripe.Event, locals: App.Locals) {\n switch (event.type) {\n case 'payment_intent.succeeded':\n await handlePaymentIntentSucceeded(event.data.object, locals);\n break;\n\n case 'payment_method.attached':\n await handlePaymentMethodAttached(event.data.object, locals);\n break;\n\n default:\n console.log(`Unhandled event type: ${event.type}`);\n }\n}\n", L = "import { describe, it, expect, beforeEach, afterEach } from \"vitest\";\nimport type Stripe from \"stripe\";\nimport stripe from \"#lib/stripe.js\";\nimport { handlePaymentIntentSucceeded } from \"./succeeded\";\n\ndescribe(\"payment_intent.succeeded\", () => {\n let stripeCustomer: Stripe.Customer;\n let paymentIntent: Stripe.PaymentIntent;\n let paymentMethod: Stripe.PaymentMethod;\n\n beforeEach(async (context) => {\n // Create a Stripe customer\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n // Link the Stripe customer to the test user\n await context.admin.collection(\"stripe_customers\").create({\n id: stripeCustomer.id,\n user: context.user.id,\n });\n\n // Create a payment method for testing\n paymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_visa\",\n },\n });\n\n // Attach payment method to customer\n await stripe.paymentMethods.attach(paymentMethod.id, {\n customer: stripeCustomer.id,\n });\n\n // Create a payment intent\n paymentIntent = await stripe.paymentIntents.create({\n amount: 2000, // $20.00\n currency: \"usd\",\n customer: stripeCustomer.id,\n payment_method: paymentMethod.id,\n confirm: true,\n return_url: \"https://example.com/return\",\n });\n });\n\n afterEach(async (context) => {\n // Clean up transactions\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\"stripe_customer = {:stripeCustomer}\", {\n stripeCustomer: stripeCustomer.id,\n }),\n });\n for (const transaction of transactions) {\n await context.admin.collection(\"transactions\").delete(transaction.id);\n }\n\n // Clean up Stripe resources\n if (paymentMethod?.id) {\n try {\n await stripe.paymentMethods.detach(paymentMethod.id);\n } catch (e) {\n // Payment method may already be detached\n }\n }\n\n // Delete customer (this will also delete associated payment methods)\n if (stripeCustomer?.id) {\n await context.admin\n .collection(\"stripe_customers\")\n .delete(stripeCustomer.id);\n await stripe.customers.del(stripeCustomer.id);\n }\n });\n\n it(\"creates a transaction record when payment intent succeeds\", async (context) => {\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(paymentIntent, locals);\n\n // Verify transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(1);\n const transaction = transactions[0];\n\n expect(transaction.stripe_payment_intent).toBe(paymentIntent.id);\n expect(transaction.stripe_customer).toBe(stripeCustomer.id);\n expect(transaction.amount).toBe(2000);\n expect(transaction.currency).toBe(\"usd\");\n expect(transaction.user).toBe(context.user.id);\n expect(transaction.stripe_charge).toBeDefined();\n expect(transaction.last4).toBeDefined();\n expect(transaction.brand).toBeDefined();\n expect(transaction.created).toBeDefined();\n expect(transaction.receipt_url).toBeDefined();\n });\n\n it(\"handles payment intent with charge object instead of string\", async (context) => {\n // Retrieve the payment intent with expanded charge\n const expandedPaymentIntent = await stripe.paymentIntents.retrieve(\n paymentIntent.id,\n {\n expand: [\"latest_charge\"],\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(expandedPaymentIntent, locals);\n\n // Verify transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(1);\n const transaction = transactions[0];\n\n expect(transaction.stripe_payment_intent).toBe(paymentIntent.id);\n expect(transaction.stripe_charge).toBeDefined();\n });\n\n it(\"handles payment intent with customer object instead of string\", async (context) => {\n // Retrieve the payment intent with expanded customer\n const expandedPaymentIntent = await stripe.paymentIntents.retrieve(\n paymentIntent.id,\n {\n expand: [\"customer\"],\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(expandedPaymentIntent, locals);\n\n // Verify transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(1);\n expect(transactions[0].stripe_customer).toBe(stripeCustomer.id);\n });\n\n it(\"handles missing charge ID gracefully\", async (context) => {\n const paymentIntentWithoutCharge = {\n ...paymentIntent,\n latest_charge: null,\n } as Stripe.PaymentIntent;\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(paymentIntentWithoutCharge, locals);\n\n // Verify no transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(0);\n });\n\n it(\"handles missing customer ID gracefully\", async (context) => {\n const paymentIntentWithoutCustomer = {\n ...paymentIntent,\n customer: null,\n } as Stripe.PaymentIntent;\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentIntentSucceeded(paymentIntentWithoutCustomer, locals);\n\n // Verify no transaction was created\n const transactions = await context.admin\n .collection(\"transactions\")\n .getFullList({\n filter: context.admin.filter(\n \"stripe_payment_intent = {:paymentIntent}\",\n {\n paymentIntent: paymentIntent.id,\n },\n ),\n });\n\n expect(transactions).toHaveLength(0);\n });\n});\n", R = "import Stripe from \"stripe\";\nimport stripe from \"#lib/stripe.js\";\n/**\n * Handles payment_intent.succeeded event\n */\nexport async function handlePaymentIntentSucceeded(\n paymentIntent: Stripe.PaymentIntent,\n locals: App.Locals,\n) {\n const chargeId =\n typeof paymentIntent.latest_charge === \"string\"\n ? paymentIntent.latest_charge\n : paymentIntent.latest_charge?.id;\n\n if (!chargeId) {\n console.error(\"No charge ID found for payment intent\");\n return;\n }\n\n const charge = await stripe.charges.retrieve(chargeId);\n\n const customerId =\n typeof paymentIntent.customer === \"string\"\n ? paymentIntent.customer\n : paymentIntent.customer?.id;\n\n if (!customerId) {\n console.error(\"No customer ID found for payment intent\");\n return;\n }\n\n const customer = await locals.admin\n .collection(\"stripe_customers\")\n .getOne(customerId);\n const created = new Date(charge.created * 1000);\n\n await locals.admin.collection(\"transactions\").create({\n stripe_payment_intent: paymentIntent.id,\n stripe_charge: chargeId,\n stripe_customer: customerId,\n amount: paymentIntent.amount,\n currency: paymentIntent.currency,\n created: created.toISOString(),\n last4: charge.payment_method_details?.card?.last4,\n brand: charge.payment_method_details?.card?.brand,\n receipt_url: charge.receipt_url,\n user: customer.user,\n });\n}\n", z = "import Stripe from \"stripe\";\nimport stripe from \"#lib/stripe.js\";\n\n/**\n * Handles payment_method.attached event\n */\nexport async function handlePaymentMethodAttached(\n paymentMethod: Stripe.PaymentMethod,\n locals: App.Locals,\n) {\n if (\n paymentMethod.allow_redisplay === \"unspecified\" ||\n !paymentMethod.customer\n ) {\n return;\n }\n\n const customer =\n typeof paymentMethod.customer === \"string\"\n ? paymentMethod.customer\n : paymentMethod.customer?.id;\n\n await locals.admin.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customer,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n exp_month: paymentMethod.card?.exp_month,\n exp_year: paymentMethod.card?.exp_year,\n });\n\n const paymentMethodRecords = await locals.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: locals.admin.filter(\"customer = {:customer}\", {\n customer: customer,\n }),\n });\n\n if (paymentMethodRecords.length === 1) {\n const paymentMethod = paymentMethodRecords[0];\n\n await stripe.customers.update(customer, {\n invoice_settings: {\n default_payment_method: paymentMethod.id,\n },\n });\n\n await locals.admin.collection(\"stripe_customers\").update(customer, {\n default_payment_method: paymentMethod.id,\n });\n }\n}\n", B = "import { describe, it, expect, beforeEach, afterEach } from \"vitest\";\nimport type Stripe from \"stripe\";\nimport stripe from \"#lib/stripe.js\";\nimport { handlePaymentMethodAttached } from \"./attached\";\n\ndescribe(\"payment_method.attached\", () => {\n let stripeCustomer: Stripe.Customer;\n let paymentMethod: Stripe.PaymentMethod;\n\n beforeEach(async (context) => {\n stripeCustomer = await stripe.customers.create({\n email: context.user.email,\n metadata: {\n test: \"true\",\n },\n });\n\n await context.admin.collection(\"stripe_customers\").create({\n id: stripeCustomer.id,\n user: context.user.id,\n });\n\n paymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_visa\",\n },\n });\n\n await stripe.paymentMethods.attach(paymentMethod.id, {\n customer: stripeCustomer.id,\n });\n\n paymentMethod = await stripe.paymentMethods.update(paymentMethod.id, {\n allow_redisplay: \"always\",\n });\n });\n\n afterEach(async (context) => {\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"customer = {:stripeCustomer}\", {\n stripeCustomer: stripeCustomer.id,\n }),\n });\n\n for (const pm of paymentMethods) {\n await context.admin.collection(\"stripe_payment_methods\").delete(pm.id);\n }\n\n if (paymentMethod?.id) {\n try {\n await stripe.paymentMethods.detach(paymentMethod.id);\n } catch {}\n }\n\n if (stripeCustomer?.id) {\n await context.admin\n .collection(\"stripe_customers\")\n .delete(stripeCustomer.id);\n await stripe.customers.del(stripeCustomer.id);\n }\n });\n\n it(\"creates a payment method record when payment method is attached\", async (context) => {\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(paymentMethod, locals);\n\n // Verify payment method was created\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"id = {:paymentMethod}\", {\n paymentMethod: paymentMethod.id,\n }),\n });\n\n expect(paymentMethods).toHaveLength(1);\n const pm = paymentMethods[0];\n\n expect(pm.id).toBe(paymentMethod.id);\n expect(pm.customer).toBe(stripeCustomer.id);\n expect(pm.brand).toBe(paymentMethod.card?.brand);\n expect(pm.last4).toBe(paymentMethod.card?.last4);\n expect(pm.exp_month).toBe(paymentMethod.card?.exp_month);\n expect(pm.exp_year).toBe(paymentMethod.card?.exp_year);\n });\n\n it(\"sets payment method as default when it is the first one\", async (context) => {\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(paymentMethod, locals);\n\n // Verify it was set as default in database\n const customer = await context.admin\n .collection(\"stripe_customers\")\n .getOne(stripeCustomer.id);\n expect(customer.default_payment_method).toBe(paymentMethod.id);\n\n // Verify it was set as default in Stripe\n const stripeCustomerUpdated = await stripe.customers.retrieve(\n stripeCustomer.id,\n );\n if (\"deleted\" in stripeCustomerUpdated) {\n throw new Error(\"Customer should not be deleted\");\n }\n expect(stripeCustomerUpdated.invoice_settings.default_payment_method).toBe(\n paymentMethod.id,\n );\n });\n\n it(\"does not set as default when there are already payment methods\", async (context) => {\n // Handle the first payment method\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(paymentMethod, locals);\n\n // Verify it was set as default\n let customer = await context.admin\n .collection(\"stripe_customers\")\n .getOne(stripeCustomer.id);\n expect(customer.default_payment_method).toBe(paymentMethod.id);\n\n // Create and attach a first payment method\n let secondPaymentMethod = await stripe.paymentMethods.create({\n type: \"card\",\n card: {\n token: \"tok_mastercard\",\n },\n });\n\n await stripe.paymentMethods.attach(secondPaymentMethod.id, {\n customer: stripeCustomer.id,\n });\n\n secondPaymentMethod = await stripe.paymentMethods.update(\n secondPaymentMethod.id,\n {\n allow_redisplay: \"always\",\n },\n );\n\n // Now handle the second payment method\n await handlePaymentMethodAttached(secondPaymentMethod, locals);\n\n // Verify the default did NOT change\n customer = await context.admin\n .collection(\"stripe_customers\")\n .getOne(stripeCustomer.id);\n expect(customer.default_payment_method).toBe(paymentMethod.id);\n\n // Clean up the second payment method\n await context.admin\n .collection(\"stripe_payment_methods\")\n .delete(secondPaymentMethod.id);\n await stripe.paymentMethods.detach(secondPaymentMethod.id);\n });\n\n it(\"handles payment method with customer object instead of string\", async (context) => {\n // Retrieve the payment method with expanded customer\n const expandedPaymentMethod = await stripe.paymentMethods.retrieve(\n paymentMethod.id,\n {\n expand: [\"customer\"],\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(expandedPaymentMethod, locals);\n\n // Verify payment method was created\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"id = {:paymentMethod}\", {\n paymentMethod: paymentMethod.id,\n }),\n });\n\n expect(paymentMethods).toHaveLength(1);\n expect(paymentMethods[0].customer).toBe(stripeCustomer.id);\n });\n\n it(\"does not create record when allow_redisplay is unspecified\", async (context) => {\n // Update payment method to have unspecified allow_redisplay\n const unspecifiedPaymentMethod = await stripe.paymentMethods.update(\n paymentMethod.id,\n {\n allow_redisplay: \"unspecified\",\n },\n );\n\n const locals = { admin: context.admin } as App.Locals;\n await handlePaymentMethodAttached(unspecifiedPaymentMethod, locals);\n\n // Verify no payment method was created\n const paymentMethods = await context.admin\n .collection(\"stripe_payment_methods\")\n .getFullList({\n filter: context.admin.filter(\"id = {:paymentMethod}\", {\n paymentMethod: paymentMethod.id,\n }),\n });\n\n expect(paymentMethods).toHaveLength(0);\n });\n});\n", V = [{
7
- id: "stripe",
8
- label: "Stripe",
9
- env: [
10
- {
11
- key: "STRIPE_SECRET_KEY",
12
- label: "Stripe secret key",
13
- placeholder: "sk_...",
14
- secret: !0,
15
- required: !0,
16
- description: "Stripe secret key (`sk_...`) the server calls the Stripe API with."
17
- },
18
- {
19
- key: "PUBLIC_STRIPE_PUBLISHABLE_KEY",
20
- label: "Stripe publishable key",
21
- placeholder: "pk_...",
22
- public: !0,
23
- required: !0,
24
- description: "Stripe publishable key (`pk_...`) that Stripe.js loads in the browser."
25
- },
26
- {
27
- key: "STRIPE_WEBHOOK_SECRET",
28
- label: "Stripe webhook signing secret",
29
- placeholder: "whsec_...",
30
- secret: !0,
31
- required: !0,
32
- description: "Signing secret (`whsec_...`) that `/webhooks/stripe` verifies events with."
33
- }
34
- ],
35
- markers: [{ env: "STRIPE_SECRET_KEY" }, { path: "src/routes/webhooks/stripe" }],
36
- requires: {
37
- backend: !0,
38
- workflows: !0
39
- }
40
- }, {
41
- id: "shopify",
42
- label: "Shopify",
43
- env: [{
44
- key: "PUBLIC_SHOPIFY_STORE_DOMAIN",
45
- label: "Shopify store domain",
46
- placeholder: "your-store.myshopify.com",
47
- public: !0,
48
- required: !0,
49
- description: "The store's `*.myshopify.com` domain the Storefront API is called on."
50
- }, {
51
- key: "PUBLIC_SHOPIFY_STOREFRONT_TOKEN",
52
- label: "Shopify Storefront API public access token",
53
- public: !0,
54
- required: !0,
55
- description: "Public Storefront API access token, from the store's Headless channel."
56
- }]
57
- }], H = {
58
- slug: "enable-payments",
59
- providers: V
60
- };
61
- function U(e, t = {}) {
62
- return n(e, `${e.label} credentials`, t);
63
- }
64
- var W = {
65
- stripe: [
66
- "dialog",
67
- "input",
68
- "label"
69
- ],
70
- shopify: ["button"]
71
- }, G = {
72
- stripe: ["stripe", "@stripe/stripe-js"],
73
- shopify: ["@shopify/storefront-api-client"]
74
- }, K = /* #__PURE__ */ Object.assign({
75
- "./providers/shopify/src/lib/components/payments/buy-button.svelte": s,
76
- "./providers/shopify/src/lib/shopify.ts": c,
77
- "./providers/stripe/src/lib/components/payments/confirm-dialog.svelte": l,
78
- "./providers/stripe/src/lib/components/payments/payment-button.svelte": u,
79
- "./providers/stripe/src/lib/components/payments/payment-dialog.svelte": d,
80
- "./providers/stripe/src/lib/components/payments/stripe-constants.ts": f,
81
- "./providers/stripe/src/lib/components/payments/stripe-payment-form.svelte": p,
82
- "./providers/stripe/src/lib/components/payments/use-payment-intent.svelte.ts": m,
83
- "./providers/stripe/src/lib/components/payments/use-stripe.svelte.ts": h,
84
- "./providers/stripe/src/lib/stripe.ts": g,
85
- "./providers/stripe/src/lib/workflows/stripe-event.ts": _,
86
- "./providers/stripe/src/lib/workflows/sync-stripe-catalog.ts": v,
87
- "./providers/stripe/src/routes/api/stripe/payment-intent/+server.ts": y,
88
- "./providers/stripe/src/routes/api/stripe/payment-intent/server.test.ts": b,
89
- "./providers/stripe/src/routes/webhooks/stripe/+server.ts": x,
90
- "./providers/stripe/src/routes/webhooks/stripe/handlers/dispatch.ts": S,
91
- "./providers/stripe/src/routes/webhooks/stripe/handlers/payment-intent/server.test.ts": C,
92
- "./providers/stripe/src/routes/webhooks/stripe/handlers/payment-intent/succeeded.ts": w,
93
- "./providers/stripe/src/routes/webhooks/stripe/server.test.ts": T
94
- }), q = /* #__PURE__ */ Object.assign({
95
- "./providers-app-mode/stripe/src/lib/components/payments/setup-button.svelte": E,
96
- "./providers-app-mode/stripe/src/lib/components/payments/setup-dialog.svelte": D,
97
- "./providers-app-mode/stripe/src/lib/server/stripe-customer.ts": i,
98
- "./providers-app-mode/stripe/src/lib/workflows/link-stripe-customer.ts": O,
99
- "./providers-app-mode/stripe/src/lib/workflows/sync-stripe-customers.ts": k,
100
- "./providers-app-mode/stripe/src/routes/(app)/billing/+layout.server.ts": A,
101
- "./providers-app-mode/stripe/src/routes/(app)/billing/+page.server.ts": a,
102
- "./providers-app-mode/stripe/src/routes/(app)/billing/+page.svelte": o,
103
- "./providers-app-mode/stripe/src/routes/(app)/billing/README.md": j,
104
- "./providers-app-mode/stripe/src/routes/api/stripe/payment-intent/+server.ts": M,
105
- "./providers-app-mode/stripe/src/routes/api/stripe/payment-intent/server.test.ts": N,
106
- "./providers-app-mode/stripe/src/routes/api/stripe/setup-intent/+server.ts": P,
107
- "./providers-app-mode/stripe/src/routes/api/stripe/setup-intent/server.test.ts": F,
108
- "./providers-app-mode/stripe/src/routes/webhooks/stripe/handlers/dispatch.ts": I,
109
- "./providers-app-mode/stripe/src/routes/webhooks/stripe/handlers/payment-intent/server.test.ts": L,
110
- "./providers-app-mode/stripe/src/routes/webhooks/stripe/handlers/payment-intent/succeeded.ts": R,
111
- "./providers-app-mode/stripe/src/routes/webhooks/stripe/handlers/payment-method/attached.ts": z,
112
- "./providers-app-mode/stripe/src/routes/webhooks/stripe/handlers/payment-method/server.test.ts": B
113
- });
114
- async function J(n) {
115
- let i = t(H, n), a = n.providers?.payments;
116
- if (a !== void 0 && a !== i.id) {
117
- let t = V.find((e) => e.id === a)?.label ?? a;
118
- throw new e(`This project already uses ${t} payments. To switch to ${i.label}, run \`vela disable payments\` first, then enable payments again.`);
119
- }
120
- let o = n.features.auth, s = new Map(r(K, i.id).map((e) => [e.path, e]));
121
- if (o) for (let e of r(q, i.id, "./providers-app-mode/")) s.set(e.path, e);
122
- let c = [...W[i.id] ?? []];
123
- return o && i.id === "stripe" && c.push("alert-dialog"), {
124
- creates: [...s.values()].sort((e, t) => e.path.localeCompare(t.path)),
125
- modifies: [],
126
- deletes: [],
127
- components: c,
128
- packages: G[i.id] ?? [],
129
- collections: [],
130
- collectionPatches: [],
131
- collectionDrops: []
132
- };
133
- }
134
- //#endregion
135
- export { h as A, S as C, v as D, y as E, u as F, l as I, c as L, p as M, f as N, _ as O, d as P, s as R, C as S, b as T, O as _, B as a, T as b, L as c, P as d, N as f, k as g, A as h, J as i, m as j, g as k, I as l, j as m, V as n, z as o, M as p, U as r, R as s, H as t, F as u, D as v, x as w, w as x, E as y };
136
-
137
- //# sourceMappingURL=generate-BClgUH4J.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate-BClgUH4J.js","names":["__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__0_3_","__import_glob__0_4_","__import_glob__0_5_","__import_glob__0_6_","__import_glob__0_7_","__import_glob__0_8_","__import_glob__0_9_","__import_glob__0_10_","__import_glob__0_11_","__import_glob__0_12_","__import_glob__0_13_","__import_glob__0_14_","__import_glob__0_15_","__import_glob__0_16_","__import_glob__0_17_","__import_glob__0_18_","__import_glob__1_0_","__import_glob__1_1_","__import_glob__1_2_","__import_glob__1_3_","__import_glob__1_4_","__import_glob__1_5_","__import_glob__1_6_","__import_glob__1_7_","__import_glob__1_8_","__import_glob__1_9_","__import_glob__1_10_","__import_glob__1_11_","__import_glob__1_12_","__import_glob__1_13_","__import_glob__1_14_","__import_glob__1_15_","__import_glob__1_16_","__import_glob__1_17_","InvalidArgumentError","resolveProvider","providerEnvEdits","stripe_customer_default","_page_server_default","_page_default","buy_button_default","shopify_default","confirm_dialog_default","payment_button_default","payment_dialog_default","stripe_constants_default","stripe_payment_form_default","use_payment_intent_svelte_default","use_stripe_svelte_default","stripe_default","stripe_event_default","sync_stripe_catalog_default","_server_default$3","server_test_default$6","_server_default$2","dispatch_default$1","server_test_default$5","succeeded_default$1","server_test_default$4","setup_button_default","setup_dialog_default","link_stripe_customer_default","sync_stripe_customers_default","_layout_server_default","README_default","_server_default$1","server_test_default$3","_server_default","server_test_default$2","dispatch_default","server_test_default$1","succeeded_default","attached_default","server_test_default","PROVIDERS","META","envEditsFor","provider","supplied","COMPONENTS","PACKAGES","providersRaw","providersAppModeRaw","generate","options","current","label","candidate","isAppMode","creates","providerCreates","file","components","a","b"],"sources":["../../src/patterns/enable/payments/generate.ts"],"sourcesContent":["import type {\n Component,\n Options,\n Package,\n Provider,\n Result,\n} from \"../../../core/types\";\nimport type { EnvEdit } from \"../../../runtime/env\";\nimport {\n providerCreates,\n providerEnvEdits,\n resolveProvider,\n} from \"../../../core/providers\";\nimport { InvalidArgumentError } from \"../../../core/errors\";\n\n/**\n * The providers in prompt order. Each one's `env` keys are what the CLI asks\n * for, what `generate.runtime.ts` writes to `.env` (in this order, under a\n * `# <Label> credentials` heading) and declares in `src/env.ts`.\n */\nexport const PROVIDERS: Provider[] = [\n {\n id: \"stripe\",\n label: \"Stripe\",\n env: [\n {\n key: \"STRIPE_SECRET_KEY\",\n label: \"Stripe secret key\",\n placeholder: \"sk_...\",\n secret: true,\n required: true,\n description:\n \"Stripe secret key (`sk_...`) the server calls the Stripe API with.\",\n },\n {\n key: \"PUBLIC_STRIPE_PUBLISHABLE_KEY\",\n label: \"Stripe publishable key\",\n placeholder: \"pk_...\",\n public: true,\n required: true,\n description:\n \"Stripe publishable key (`pk_...`) that Stripe.js loads in the browser.\",\n },\n {\n key: \"STRIPE_WEBHOOK_SECRET\",\n label: \"Stripe webhook signing secret\",\n placeholder: \"whsec_...\",\n secret: true,\n required: true,\n description:\n \"Signing secret (`whsec_...`) that `/webhooks/stripe` verifies events with.\",\n },\n ],\n // The webhook route predates the `src/env.ts` declarations, so a project\n // that enabled payments before them is still recognised.\n markers: [\n { env: \"STRIPE_SECRET_KEY\" },\n { path: \"src/routes/webhooks/stripe\" },\n ],\n // Products, prices and customers are synced into PocketBase by workflows.\n requires: { backend: true, workflows: true },\n },\n {\n id: \"shopify\",\n label: \"Shopify\",\n env: [\n {\n key: \"PUBLIC_SHOPIFY_STORE_DOMAIN\",\n label: \"Shopify store domain\",\n placeholder: \"your-store.myshopify.com\",\n public: true,\n required: true,\n description:\n \"The store's `*.myshopify.com` domain the Storefront API is called on.\",\n },\n {\n key: \"PUBLIC_SHOPIFY_STOREFRONT_TOKEN\",\n label: \"Shopify Storefront API public access token\",\n public: true,\n required: true,\n description:\n \"Public Storefront API access token, from the store's Headless channel.\",\n },\n ],\n },\n];\n\n/** What `resolveProvider` needs; `index.ts` spreads the rest of the metadata. */\nexport const META = { slug: \"enable-payments\", providers: PROVIDERS };\n\n/** The `.env` lines for a provider, under a `# <Label> credentials` heading. */\nexport function envEditsFor(\n provider: Provider,\n supplied: Record<string, string> = {},\n): EnvEdit[] {\n return providerEnvEdits(provider, `${provider.label} credentials`, supplied);\n}\n\nconst COMPONENTS: Record<string, Component[]> = {\n stripe: [\"dialog\", \"input\", \"label\"],\n shopify: [\"button\"],\n};\n\nconst PACKAGES: Record<string, Package[]> = {\n stripe: [\"stripe\", \"@stripe/stripe-js\"],\n shopify: [\"@shopify/storefront-api-client\"],\n};\n\nconst providersRaw = import.meta.glob<string>(\"./providers/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nconst providersAppModeRaw = import.meta.glob<string>(\n \"./providers-app-mode/**\",\n { query: \"?raw\", import: \"default\", eager: true },\n);\n\nexport async function generate(options: Options) {\n const provider = resolveProvider(META, options);\n\n // A second provider would leave the project with both, and the patterns\n // built on payments could no longer tell which one it uses.\n const current = options.providers?.payments;\n if (current !== undefined && current !== provider.id) {\n const label =\n PROVIDERS.find((candidate) => candidate.id === current)?.label ?? current;\n throw new InvalidArgumentError(\n `This project already uses ${label} payments. To switch to ${provider.label}, ` +\n \"run `vela disable payments` first, then enable payments again.\",\n );\n }\n // Stripe keeps cards and customers for signed-in users; Shopify's checkout\n // owns its customers, so it has no app-mode files.\n const isAppMode = options.features.auth;\n\n const creates = new Map(\n providerCreates(providersRaw, provider.id).map((file) => [file.path, file]),\n );\n if (isAppMode) {\n for (const file of providerCreates(\n providersAppModeRaw,\n provider.id,\n \"./providers-app-mode/\",\n )) {\n creates.set(file.path, file);\n }\n }\n\n const components = [...(COMPONENTS[provider.id] ?? [])];\n if (isAppMode && provider.id === \"stripe\") components.push(\"alert-dialog\");\n\n return {\n creates: [...creates.values()].sort((a, b) => a.path.localeCompare(b.path)),\n modifies: [],\n deletes: [],\n components,\n packages: PACKAGES[provider.id] ?? [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;q2yFAoBa6E,IAAwB,CACnC;CACE,IAAI;CACJ,OAAO;CACP,KAAK;EACH;GACE,KAAK;GACL,OAAO;GACP,aAAa;GACb,QAAQ;GACR,UAAU;GACV,aACE;EACJ;EACA;GACE,KAAK;GACL,OAAO;GACP,aAAa;GAC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AAC;CAAA,+EAAAC;CAAA,mFAAAC;CAAA,6EAAAC;CAAA,iFAAAC;CAAA,+EAAAC;CAAA,iGAAAC;CAAA,+FAAAC;CAAA,8FAAAC;CAAA,iGAAAC;AAG5B,CAAA;AAEA,eAAsBkD,EAAS,GAAkB;CAC/C,IAAMN,IAAW1C,EAAgBwC,GAAMS,CAAO,GAIxCC,IAAUD,EAAQ,WAAW;CACnC,IAAIC,MAAY,KAAA,KAAaA,MAAYR,EAAS,IAAI;EACpD,IAAMS,IACJZ,EAAU,MAAM,MAAca,EAAU,OAAOF,CAAO,CAAC,EAAE,SAASA;EACpE,MAAM,IAAInD,EACR,6BAA6BoD,EAAM,0BAA0BT,EAAS,MAAM,mEAE9E;CACF;CAGA,IAAMW,IAAYJ,EAAQ,SAAS,MAE7BK,IAAU,IAAI,IAClBC,EAAgBT,GAAcJ,EAAS,EAAE,CAAC,CAAC,KAAK,MAAS,CAACc,EAAK,MAAMA,CAAI,CAAC,CAC5E;CACA,IAAIH,GACF,KAAK,IAAMG,KAAQD,EACjBR,GACAL,EAAS,IACT,uBACF,GACE,EAAQ,IAAIc,EAAK,MAAMA,CAAI;CAI/B,IAAMC,IAAa,CAAC,GAAIb,EAAWF,EAAS,OAAO,CAAC,CAAE;CAGtD,OAFIW,KAAaX,EAAS,OAAO,YAAUe,EAAW,KAAK,cAAc,GAElE;EACL,SAAS,CAAC,GAAGH,EAAQ,OAAO,CAAC,CAAC,CAAC,MAAM,GAAG,MAAMI,EAAE,KAAK,cAAcC,EAAE,IAAI,CAAC;EAC1E,UAAU,CAAC;EACX,SAAS,CAAC;EACV;EACA,UAAUd,EAASH,EAAS,OAAO,CAAC;EACpC,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate-ZIOVLH6Q.js","names":["__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__0_3_","__import_glob__0_4_","__import_glob__0_5_","__import_glob__0_6_","__import_glob__0_7_","__import_glob__0_8_","__import_glob__0_9_","__import_glob__0_10_","__import_glob__0_11_","__import_glob__0_12_","__import_glob__0_13_","__import_glob__0_14_","__import_glob__0_15_","__import_glob__0_16_","__import_glob__0_17_","__import_glob__0_18_","__import_glob__0_19_","__import_glob__0_20_","__import_glob__0_21_","__import_glob__0_22_","__import_glob__0_23_","__import_glob__0_24_","__import_glob__0_25_","__import_glob__0_26_","__import_glob__0_27_","__import_glob__0_28_","__import_glob__0_29_","__import_glob__0_30_","__import_glob__0_31_","__import_glob__0_32_","__import_glob__0_33_","__import_glob__0_34_","__import_glob__0_35_","__import_glob__0_36_","languageFromPath","use_stripe_svelte_default","dispatch_default","sync_stripe_catalog_default","_server_default","payment_button_default","confirm_dialog_default","shopify_default","stripe_payment_form_default","stripe_constants_default","stripe_event_default","payment_dialog_default","buy_button_default","server_test_default$1","server_test_default","link_stripe_customer_default","server_test_default$6","server_test_default$2","server_test_default$5","_server_default$3","server_test_default$3","sync_stripe_customers_default","_layout_server_default","use_payment_intent_svelte_default","stripe_default","dispatch_default$1","README_default","PROVIDERS","attached_default","_server_default$2","succeeded_default$1","server_test_default$4","setup_dialog_default","_server_default$1","succeeded_default","setup_button_default","stripe_customer_default","_page_server_default","_page_default","providersRaw","DEMO_PAGE","providersToRemove","detected","options","match","provider","generate","paths","path","allProviderPaths"],"sources":["../../src/patterns/disable/payments/generate.ts"],"sourcesContent":["import type { File, Options, Provider, Result } from \"../../../core/types\";\nimport { allProviderPaths } from \"../../../core/providers\";\nimport { languageFromPath } from \"../../../core/util\";\nimport { PROVIDERS } from \"../../enable/payments/generate\";\n\nconst providersRaw = import.meta.glob<string>(\n [\n \"../../enable/payments/providers/**\",\n \"../../enable/payments/providers-app-mode/**\",\n ],\n { query: \"?raw\", import: \"default\", eager: true },\n);\n\n// The demo page enable-payments writes at runtime (it carries the price or\n// variant id), so it is in no template tree: without the payment components it\n// would no longer build.\nconst DEMO_PAGE = \"src/routes/(public)/payment/+page.svelte\";\n\n/**\n * The provider whose files to remove: the one detected, else every one.\n * Removing every provider's files is safe, since a missing path is skipped.\n */\nexport function providersToRemove(\n options: Pick<Options, \"providers\">,\n): Provider[] {\n const detected = options.providers?.payments;\n const match = PROVIDERS.filter((provider) => provider.id === detected);\n return match.length > 0 ? match : PROVIDERS;\n}\n\nexport async function generate(options: Options) {\n // Both the plain and the app-mode files go, whatever auth is now: auth may\n // have been turned on or off since payments was enabled.\n const paths = new Set([DEMO_PAGE]);\n for (const provider of providersToRemove(options)) {\n for (const path of allProviderPaths(providersRaw, provider.id)) {\n paths.add(path);\n }\n }\n\n const deletes: File[] = [...paths].sort().map((path) => ({\n path,\n language: languageFromPath(path),\n content: \"\",\n status: \"success\",\n }));\n\n return {\n creates: [],\n modifies: [],\n deletes,\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;;AAKA,IAAM4E,IAAe,uBAAA,OAAA;CAAA,yFAAA5E;CAAA,8DAAAC;CAAA,4FAAAC;CAAA,4FAAAC;CAAA,4FAAAC;CAAA,0FAAAC;CAAA,iGAAAC;CAAA,mGAAAC;CAAA,2FAAAC;CAAA,4DAAAC;CAAA,4EAAAC;CAAA,mFAAAC;CAAA,0FAAAC;CAAA,8FAAAC;CAAA,gFAAAC;CAAA,0FAAAC;CAAA,4GAAAC;CAAA,0GAAAC;CAAA,oFAAAC;CAAA,mGAAAC;CAAA,mGAAAC;CAAA,qFAAAC;CAAA,6FAAAC;CAAA,8FAAAC;CAAA,8FAAAC;CAAA,4FAAAC;CAAA,yFAAAC;CAAA,sFAAAC;CAAA,mGAAAC;CAAA,uGAAAC;CAAA,iGAAAC;CAAA,qGAAAC;CAAA,mGAAAC;CAAA,qHAAAC;CAAA,mHAAAC;CAAA,kHAAAC;CAAA,qHAAAC;AAMrB,CAAA,GAKMyC,IAAY;AAMlB,SAAgBC,EACd,GACY;CACZ,IAAMC,IAAWC,EAAQ,WAAW,UAC9BC,IAAQjB,EAAU,QAAQ,MAAakB,EAAS,OAAOH,CAAQ;CACrE,OAAOE,EAAM,SAAS,IAAIA,IAAQjB;AACpC;AAEA,eAAsBmB,EAAS,GAAkB;CAG/C,IAAMC,oBAAQ,IAAI,IAAI,CAACP,CAAS,CAAC;CACjC,KAAK,IAAMK,KAAYJ,EAAkBE,CAAO,GAC9C,KAAK,IAAMK,KAAQC,EAAiBV,GAAcM,EAAS,EAAE,GAC3D,EAAM,IAAIG,CAAI;CAWlB,OAAO;EACL,SAAS,CAAC;EACV,UAAU,CAAC;EACX,SAVsB,CAAC,GAAGD,CAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,OAAU;GACvD;GACA,UAAU/C,EAAiBgD,CAAI;GAC/B,SAAS;GACT,QAAQ;EACV,EAKE;EACA,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate.runtime-DaRVyiSg.js","names":["languageFromPath","mergeResults","providerEnvVars","resolveProvider","suppliedProviderEnv","dedent","_taggedTemplateLiteral","getLogger","envEditsFor","META","buyPageSnippet","modifyEnv","addNavItemToScript","modifyOutcomeToFile","SvelteFile","withPocketbase","migrationDelay","getMigrationFile","modifyUserSignup","createCollectionIdempotent","fs","path","Stripe","setupShopify","logger","options","variantId","creates","BILLING_NAV_SNIPPET","FAILURE_HINT","NOT_FOUND_HINT","addItemToNavUser","file","navUserSnippet","wasAdded","tryAdd","run","result","source","title","url","icon","iconImportPath","fn","modifyNavUser","navUserPath","newNavUserSnippet","syncUsersToStripeCustomers","stripe","stripeSecretKey","users","pb","existing","linkedUserIds","c","user","matching","label","customer","isExistingCustomer","error","paymentMethods","paymentMethod","defaultPaymentMethod","createTestProductAndPrice","products","product","prices","getProductAndPriceById","price","priceId","_templateObject","pushMigrationCreates","created","migrationFile","collectionName","action","paymentPageSnippet","setupStripe","stripePriceId","isAppMode","modifies","pushResult","create","spec","productsResult","pricesResult","customersResult","stripeCustomersCollection","paymentMethodsResult","stripePaymentMethodsCollection","transactionsResult","syncResult","userSignupPath","generate","provider","envPath","envVars","modifyEnvVarsFiles","env","setup"],"sources":["../../src/patterns/enable/payments/runtime/setup-shopify.ts","../../src/patterns/enable/payments/modifies/modify-nav-user.ts","../../src/patterns/enable/payments/runtime/stripe.ts","../../src/patterns/enable/payments/runtime/setup-stripe.ts","../../src/patterns/enable/payments/generate.runtime.ts"],"sourcesContent":["import type { Options, Result } from \"../../../../core/types\";\nimport { getLogger } from \"../../../../core/logger\";\nimport { buyPageSnippet } from \"../shopify-page\";\n\n/**\n * Shopify keeps products, customers and checkout on its side, so past the env\n * there is only the demo page, and only when a variant to sell was given.\n */\nexport async function setupShopify(options: Options) {\n const logger = getLogger(options);\n const variantId =\n typeof options.input.demoId === \"string\" ? options.input.demoId.trim() : \"\";\n\n const creates = [];\n if (variantId) {\n logger.info(\"Creating payment +page.svelte\");\n creates.push({\n path: \"src/routes/(public)/payment/+page.svelte\",\n language: \"svelte\",\n content: buyPageSnippet(variantId),\n status: \"success\" as const,\n });\n }\n\n return {\n creates,\n modifies: [],\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n","import fs from \"node:fs\";\nimport { SvelteFile } from \"../../../../runtime/svelte-file\";\nimport { addNavItemToScript } from \"../../../../runtime/ts-morph-helpers\";\nimport type { ModifyOutcome } from \"../../../../core/types\";\n\nconst BILLING_NAV_SNIPPET = [\n \"import CreditCardIcon from '@lucide/svelte/icons/credit-card';\",\n \"\",\n \"// Add to your navUser array:\",\n \"{ title: 'Billing', url: '/billing', icon: CreditCardIcon }\",\n].join(\"\\n\");\n\nconst FAILURE_HINT = [\n \"Add a Billing nav item to nav-user.svelte:\",\n \"\",\n BILLING_NAV_SNIPPET,\n].join(\"\\n\");\n\nconst NOT_FOUND_HINT = [\n \"Create nav-user.svelte with a Billing entry:\",\n \"\",\n BILLING_NAV_SNIPPET,\n].join(\"\\n\");\n\nexport function addItemToNavUser(\n navUserSnippet: string,\n title: string,\n url: string,\n icon: string,\n iconImportPath: string,\n): { newNavUserSnippet: string; wasAdded: boolean } {\n const file = new SvelteFile(navUserSnippet);\n let wasAdded = false;\n\n const tryAdd = (run: (fn: (s: string) => string) => boolean) => {\n if (wasAdded) return;\n run((source) => {\n const result = addNavItemToScript(\n source,\n title,\n url,\n icon,\n iconImportPath,\n );\n if (result.wasAdded) wasAdded = true;\n return result.source;\n });\n };\n\n tryAdd((fn) => file.modifyModuleScript(fn));\n if (!wasAdded) tryAdd((fn) => file.modifyScript(fn));\n\n return { newNavUserSnippet: file.toString(), wasAdded };\n}\n\nexport function modifyNavUser(navUserPath: string): ModifyOutcome {\n if (!fs.existsSync(navUserPath)) {\n return { status: \"not-found\", message: NOT_FOUND_HINT };\n }\n\n const navUserSnippet = fs.readFileSync(navUserPath, \"utf8\");\n if (navUserSnippet.includes(\"/billing\")) {\n return { status: \"success\", changed: false };\n }\n\n const { newNavUserSnippet, wasAdded } = addItemToNavUser(\n navUserSnippet,\n \"Billing\",\n \"/billing\",\n \"CreditCardIcon\",\n \"@lucide/svelte/icons/credit-card\",\n );\n\n if (!wasAdded) {\n return { status: \"failed\", message: FAILURE_HINT };\n }\n\n fs.writeFileSync(navUserPath, newNavUserSnippet, \"utf8\");\n return { status: \"success\", changed: true };\n}\n","import Stripe from \"stripe\";\nimport type PocketBase from \"pocketbase\";\nimport type { Logger } from \"../../../../core/logger\";\n\nexport interface StripeTestFixture {\n product: Stripe.Product;\n price: Stripe.Price;\n existing: boolean;\n}\n\nexport interface SyncUsersResult {\n total: number;\n linked: number;\n created: number;\n reused: number;\n skipped: number;\n}\n\nexport async function syncUsersToStripeCustomers(\n pb: PocketBase,\n stripeSecretKey: string,\n logger: Logger,\n): Promise<SyncUsersResult> {\n const stripe = new Stripe(stripeSecretKey);\n const users = await pb.collection(\"users\").getFullList<{\n id: string;\n email?: string;\n name?: string;\n phone?: string;\n }>();\n\n const existing = await pb\n .collection(\"stripe_customers\")\n .getFullList<{ id: string; user: string }>();\n const linkedUserIds = new Set(existing.map((c) => c.user));\n\n const result: SyncUsersResult = {\n total: users.length,\n linked: linkedUserIds.size,\n created: 0,\n reused: 0,\n skipped: 0,\n };\n\n for (const user of users) {\n if (linkedUserIds.has(user.id)) {\n result.skipped += 1;\n continue;\n }\n\n // A user made with a phone number may have no email to match on.\n const matching = user.email\n ? await stripe.customers.list({\n email: user.email,\n limit: 1,\n expand: [\"data.invoice_settings\"],\n })\n : { data: [] };\n const label = user.email || user.id;\n\n let customer: Stripe.Customer;\n let isExistingCustomer = false;\n\n if (matching.data.length > 0) {\n customer = matching.data[0];\n isExistingCustomer = true;\n result.reused += 1;\n logger.info(`Reusing Stripe customer ${customer.id} for ${label}`);\n } else {\n customer = await stripe.customers.create(\n user.email\n ? { email: user.email }\n : { name: user.name || undefined, phone: user.phone || undefined },\n );\n result.created += 1;\n logger.info(`Created Stripe customer ${customer.id} for ${label}`);\n }\n\n try {\n await pb.collection(\"stripe_customers\").create({\n id: customer.id,\n user: user.id,\n });\n } catch (error) {\n logger.info(\n `Failed to create stripe_customers row for ${label}: ${(error as Error).message}`,\n );\n continue;\n }\n\n if (!isExistingCustomer) {\n continue;\n }\n\n const paymentMethods = await stripe.customers.listPaymentMethods(\n customer.id,\n { type: \"card\", allow_redisplay: \"always\" },\n );\n\n for (const paymentMethod of paymentMethods.data) {\n if (paymentMethod.allow_redisplay === \"unspecified\") continue;\n try {\n await pb.collection(\"stripe_payment_methods\").create({\n id: paymentMethod.id,\n customer: customer.id,\n brand: paymentMethod.card?.brand,\n last4: paymentMethod.card?.last4,\n exp_month: paymentMethod.card?.exp_month,\n exp_year: paymentMethod.card?.exp_year,\n });\n } catch {}\n }\n\n const defaultPaymentMethod =\n customer.invoice_settings?.default_payment_method;\n if (defaultPaymentMethod) {\n try {\n await pb.collection(\"stripe_customers\").update(customer.id, {\n default_payment_method:\n typeof defaultPaymentMethod === \"string\"\n ? defaultPaymentMethod\n : defaultPaymentMethod.id,\n });\n } catch {}\n }\n }\n\n return result;\n}\n\nexport async function createTestProductAndPrice(\n stripeSecretKey: string,\n): Promise<StripeTestFixture> {\n const stripe = new Stripe(stripeSecretKey);\n\n const products = await stripe.products.search({\n query: `name:\"Test Product\" AND metadata[\"test\"]:\"true\"`,\n limit: 1,\n });\n\n if (products.data.length > 0) {\n const product = products.data[0];\n const prices = await stripe.prices.list({\n product: product.id,\n active: true,\n limit: 1,\n });\n if (prices.data.length > 0) {\n return { product, price: prices.data[0], existing: true };\n }\n }\n\n const product = await stripe.products.create({\n name: \"Test Product\",\n metadata: { test: \"true\" },\n });\n\n const price = await stripe.prices.create({\n product: product.id,\n unit_amount: 1000,\n currency: \"usd\",\n });\n\n return { product, price, existing: false };\n}\n\nexport async function getProductAndPriceById(\n stripeSecretKey: string,\n priceId: string,\n): Promise<StripeTestFixture> {\n const stripe = new Stripe(stripeSecretKey);\n const price = await stripe.prices.retrieve(priceId, { expand: [\"product\"] });\n const product =\n typeof price.product === \"string\"\n ? await stripe.products.retrieve(price.product)\n : (price.product as Stripe.Product);\n price.product = product.id;\n return { product, price, existing: true };\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport dedent from \"dedent\";\nimport type { File, Options, Result } from \"../../../../core/types\";\nimport { getLogger } from \"../../../../core/logger\";\nimport { suppliedProviderEnv } from \"../../../../core/providers\";\nimport { languageFromPath } from \"../../../../core/util\";\nimport {\n getMigrationFile,\n migrationDelay,\n withPocketbase,\n} from \"../../../../runtime/pocketbase\";\nimport { createCollectionIdempotent } from \"../../../../runtime/collections\";\nimport { modifyOutcomeToFile } from \"../../../../runtime/modify-file\";\nimport { modifyNavUser } from \"../modifies/modify-nav-user\";\nimport { modifyUserSignup } from \"../modifies/modify-user-signup\";\nimport {\n createTestProductAndPrice,\n getProductAndPriceById,\n syncUsersToStripeCustomers,\n} from \"./stripe\";\n\nasync function pushMigrationCreates(\n creates: File[],\n collectionName: string,\n action: \"created\" | \"updated\",\n options: Options,\n created = true,\n) {\n if (!created) return;\n await migrationDelay();\n const migrationFile = getMigrationFile(collectionName, action, options);\n if (!migrationFile) return;\n creates.push({\n path: migrationFile,\n language: languageFromPath(migrationFile),\n content: fs.readFileSync(migrationFile, \"utf8\"),\n status: \"success\",\n });\n}\n\nfunction paymentPageSnippet(priceId: string): string {\n return dedent`\n <script lang=\"ts\">\n import PaymentButton from '#lib/components/payments/payment-button.svelte';\n </script>\n\n <section data-role=\"content\">\n <PaymentButton priceId=\"${priceId}\" />\n </section>\n `;\n}\n\n/**\n * Everything Stripe needs past its env: the catalog and customer collections,\n * the existing users as Stripe customers, a product/price for the demo page,\n * and, with auth, the billing nav item and the signup link to Stripe.\n */\nexport async function setupStripe(options: Options) {\n const stripeSecretKey = suppliedProviderEnv(options).STRIPE_SECRET_KEY ?? \"\";\n const stripePriceId =\n typeof options.input.demoId === \"string\" && options.input.demoId !== \"\"\n ? options.input.demoId\n : undefined;\n\n const isAppMode = options.features.auth;\n const logger = getLogger(options);\n const creates: File[] = [];\n const modifies: File[] = [];\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n await withPocketbase(options.root, async (pb) => {\n const create = (spec: Parameters<typeof createCollectionIdempotent>[1]) =>\n createCollectionIdempotent(pb, spec, logger);\n\n logger.info(\"Creating stripe_products collection\");\n const productsResult = await create({\n name: \"stripe_products\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"name\", required: false, type: \"text\" },\n { name: \"active\", required: false, type: \"text\" },\n { name: \"default_price\", required: false, type: \"text\" },\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_products\",\n \"created\",\n options,\n productsResult.created,\n );\n\n logger.info(\"Creating stripe_prices collection\");\n const pricesResult = await create({\n name: \"stripe_prices\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"billing_scheme\", required: false, type: \"text\" },\n { name: \"currency\", required: false, type: \"text\" },\n { name: \"product\", required: false, type: \"text\" },\n { name: \"recurring\", required: false, type: \"json\" },\n { name: \"type\", required: false, type: \"text\" },\n { name: \"unit_amount\", required: false, type: \"number\" },\n { name: \"active\", required: false, type: \"bool\" },\n { name: \"created\", onCreate: true, onUpdate: false, type: \"autodate\" },\n { name: \"updated\", onCreate: true, onUpdate: true, type: \"autodate\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_prices\",\n \"created\",\n options,\n pricesResult.created,\n );\n\n if (isAppMode) {\n logger.info(\"Creating stripe_customers collection\");\n const customersResult = await create({\n name: \"stripe_customers\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const stripeCustomersCollection = customersResult.collection;\n await pushMigrationCreates(\n creates,\n \"stripe_customers\",\n \"created\",\n options,\n customersResult.created,\n );\n\n logger.info(\"Creating stripe_payment_methods collection\");\n const paymentMethodsResult = await create({\n name: \"stripe_payment_methods\",\n type: \"base\",\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"brand\", required: true, type: \"text\" },\n { name: \"last4\", required: true, type: \"text\" },\n { name: \"exp_month\", required: true, type: \"number\" },\n { name: \"exp_year\", required: true, type: \"number\" },\n {\n collectionId: stripeCustomersCollection.id,\n maxSelect: 1,\n minSelect: 0,\n name: \"customer\",\n required: true,\n type: \"relation\",\n cascadeDelete: true,\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n const stripePaymentMethodsCollection = paymentMethodsResult.collection;\n await pushMigrationCreates(\n creates,\n \"stripe_payment_methods\",\n \"created\",\n options,\n paymentMethodsResult.created,\n );\n\n logger.info(\"Linking default_payment_method on stripe_customers\");\n await pb.collections.update(\"stripe_customers\", {\n fields: [\n {\n name: \"id\",\n pattern: \"^[a-zA-Z0-9_]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n {\n collectionId: stripePaymentMethodsCollection.id,\n maxSelect: 1,\n minSelect: 0,\n name: \"default_payment_method\",\n required: false,\n type: \"relation\",\n },\n {\n name: \"created\",\n onCreate: true,\n onUpdate: false,\n type: \"autodate\",\n },\n {\n name: \"updated\",\n onCreate: true,\n onUpdate: true,\n type: \"autodate\",\n },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"stripe_customers\",\n \"updated\",\n options,\n );\n\n logger.info(\"Creating transactions collection\");\n const transactionsResult = await create({\n name: \"transactions\",\n type: \"base\",\n fields: [\n {\n autogeneratePattern: \"[a-z0-9]{15}\",\n max: 15,\n min: 15,\n name: \"id\",\n pattern: \"^[a-z0-9]+$\",\n primaryKey: true,\n required: true,\n system: true,\n type: \"text\",\n },\n { name: \"stripe_payment_intent\", required: true, type: \"text\" },\n { name: \"amount\", required: true, type: \"number\" },\n { name: \"currency\", required: true, type: \"text\" },\n { name: \"last4\", required: true, type: \"text\" },\n { name: \"brand\", required: true, type: \"text\" },\n { name: \"created\", required: true, type: \"date\" },\n { name: \"stripe_charge\", required: true, type: \"text\" },\n { name: \"stripe_customer\", required: true, type: \"text\" },\n {\n collectionId: \"_pb_users_auth_\",\n maxSelect: 1,\n minSelect: 0,\n name: \"user\",\n required: true,\n type: \"relation\",\n },\n { name: \"receipt_url\", required: true, type: \"url\" },\n ],\n });\n await pushMigrationCreates(\n creates,\n \"transactions\",\n \"created\",\n options,\n transactionsResult.created,\n );\n\n logger.info(\"Syncing existing PocketBase users to Stripe customers\");\n const syncResult = await syncUsersToStripeCustomers(\n pb,\n stripeSecretKey,\n logger,\n );\n logger.info(\n `Synced ${syncResult.total} users (created ${syncResult.created}, reused ${syncResult.reused}, skipped ${syncResult.skipped})`,\n );\n }\n });\n\n if (stripePriceId) {\n logger.info(`Fetching Stripe product/price ${stripePriceId}`);\n } else {\n logger.info(\"Creating test Stripe product and price\");\n }\n const { product, price, existing } = stripePriceId\n ? await getProductAndPriceById(stripeSecretKey, stripePriceId)\n : await createTestProductAndPrice(stripeSecretKey);\n\n if (existing) {\n logger.info(\"Stripe product/price already exists, skipping creation\");\n }\n\n logger.info(\"Seeding Stripe product/price records\");\n await withPocketbase(options.root, async (pb) => {\n try {\n await pb.collection(\"stripe_products\").getOne(product.id);\n } catch (error) {\n await pb.collection(\"stripe_products\").create({\n id: product.id,\n name: product.name,\n active: product.active,\n default_price: product.default_price,\n });\n }\n\n try {\n await pb.collection(\"stripe_prices\").getOne(price.id);\n } catch (error) {\n await pb.collection(\"stripe_prices\").create({\n id: price.id,\n billing_scheme: price.billing_scheme,\n currency: price.currency,\n product: price.product,\n recurring: price.recurring,\n type: price.type,\n unit_amount: price.unit_amount,\n active: price.active,\n });\n }\n });\n\n logger.info(\"Creating payment +page.svelte\");\n creates.push({\n path: \"src/routes/(public)/payment/+page.svelte\",\n language: \"svelte\",\n content: paymentPageSnippet(price.id),\n status: \"success\",\n });\n\n if (isAppMode) {\n logger.info(\"Modifying nav-user.svelte\");\n const navUserPath = path.join(\n options.root,\n \"src\",\n \"lib\",\n \"components\",\n \"nav-user.svelte\",\n );\n pushResult(modifyOutcomeToFile(navUserPath, modifyNavUser(navUserPath)));\n\n logger.info(\"Modifying signup +page.server.ts\");\n const userSignupPath = path.join(\n options.root,\n \"src\",\n \"routes\",\n \"(public)\",\n \"(auth)\",\n \"signup\",\n \"+page.server.ts\",\n );\n pushResult(\n modifyOutcomeToFile(userSignupPath, modifyUserSignup(userSignupPath)),\n );\n }\n\n return {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n","import path from \"node:path\";\nimport type { File, Options, Result } from \"../../../core/types\";\nimport { getLogger } from \"../../../core/logger\";\nimport {\n providerEnvVars,\n resolveProvider,\n suppliedProviderEnv,\n} from \"../../../core/providers\";\nimport { mergeResults } from \"../../../core/util\";\nimport { modifyEnvVarsFiles } from \"../../../runtime/env-vars\";\nimport { modifyOutcomeToFile } from \"../../../runtime/modify-file\";\nimport { modifyEnv } from \"../../../runtime/env\";\nimport { envEditsFor, META } from \"./generate\";\nimport { setupShopify } from \"./runtime/setup-shopify\";\nimport { setupStripe } from \"./runtime/setup-stripe\";\n\nexport async function generate(options: Options) {\n const logger = getLogger(options);\n const provider = resolveProvider(META, options);\n const creates: File[] = [];\n const modifies: File[] = [];\n\n const pushResult = (file: File | null) => {\n if (file) modifies.push(file);\n };\n\n logger.info(`Writing ${provider.label} credentials to .env`);\n const envPath = path.join(options.root, \".env\");\n pushResult(\n modifyOutcomeToFile(\n envPath,\n modifyEnv(envPath, envEditsFor(provider, suppliedProviderEnv(options))),\n ),\n );\n\n // SvelteKit 3 exposes only declared variables, and only `public: true`\n // ones through `$app/env/public`.\n logger.info(`Declaring ${provider.label} variables in src/env.ts`);\n const envVars = modifyEnvVarsFiles(options.root, providerEnvVars(provider));\n if (envVars.create) creates.push(envVars.create);\n pushResult(envVars.modify);\n\n const env: Result = {\n creates,\n modifies,\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n };\n\n const setup =\n provider.id === \"stripe\"\n ? await setupStripe(options)\n : await setupShopify(options);\n\n return mergeResults([env, setup]) satisfies Result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAQA,eAAsBuB,EAAa,GAAkB;CACnD,IAAMC,IAASjB,EAAUkB,CAAO,GAC1BC,IACJ,OAAOD,EAAQ,MAAM,UAAW,WAAWA,EAAQ,MAAM,OAAO,KAAK,IAAI,IAErEE,IAAU,CAAC;CAWjB,OAVID,MACFF,EAAO,KAAK,+BAA+B,GAC3CG,EAAQ,KAAK;EACX,MAAM;EACN,UAAU;EACV,SAASjB,EAAegB,CAAS;EACjC,QAAQ;CACV,CAAC,IAGI;EACL;EACA,UAAU,CAAC;EACX,SAAS,CAAC;EACV,YAAY,CAAC;EACb,UAAU,CAAC;EACX,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF;;;AC7BA,IAAME,IAAsB;CAC1B;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI,GAELC,IAAe;CACnB;CACA;CACAD;AACF,CAAC,CAAC,KAAK,IAAI,GAELE,IAAiB;CACrB;CACA;CACAF;AACF,CAAC,CAAC,KAAK,IAAI;AAEX,SAAgBG,EACd,GACA,GACA,GACA,GACA,GACkD;CAClD,IAAMC,IAAO,IAAIlB,EAAWmB,CAAc,GACtCC,IAAW,IAETC,KAAU,MAAgD;EAC9D,AAAID,KACJE,GAAK,MAAW;GACd,IAAMC,IAASzB,EACb0B,GACAC,GACAC,GACAC,GACAC,CACF;GAEA,OADIL,EAAO,aAAU,IAAW,KACzBA,EAAO;EAChB,CAAC;CACH;CAKA,OAHAF,GAAQ,MAAOH,EAAK,mBAAmBW,CAAE,CAAC,GACrCT,KAAUC,GAAQ,MAAOH,EAAK,aAAaW,CAAE,CAAC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