@velastack/patterns 0.4.3 → 0.6.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 (145) hide show
  1. package/README.md +22 -2
  2. package/dist/chunks/{_page-e_I-fdSR.js → _page-DoPdZgZv.js} +2 -2
  3. package/dist/chunks/_page-DoPdZgZv.js.map +1 -0
  4. package/dist/chunks/collections-B_DisSfA.js +203 -0
  5. package/dist/chunks/collections-B_DisSfA.js.map +1 -0
  6. package/dist/chunks/{constants-Rq8SCXwH.js → constants-iej3WkEa.js} +3 -3
  7. package/dist/chunks/constants-iej3WkEa.js.map +1 -0
  8. package/dist/chunks/dispatch-BIvOwbKN.js +6 -0
  9. package/dist/chunks/dispatch-BIvOwbKN.js.map +1 -0
  10. package/dist/chunks/{env-vars-CcE6ODqC.js → env-vars-cqQU0ECK.js} +32 -20
  11. package/dist/chunks/env-vars-cqQU0ECK.js.map +1 -0
  12. package/dist/chunks/generate-8FS2ROOJ.js +170 -0
  13. package/dist/chunks/generate-8FS2ROOJ.js.map +1 -0
  14. package/dist/chunks/{generate-CFqpRi9D.js → generate-Bm_jOMtF.js} +4 -4
  15. package/dist/chunks/{generate-CFqpRi9D.js.map → generate-Bm_jOMtF.js.map} +1 -1
  16. package/dist/chunks/{generate-Bg0E3eWm.js → generate-CXoQPz7n.js} +4 -4
  17. package/dist/chunks/{generate-Bg0E3eWm.js.map → generate-CXoQPz7n.js.map} +1 -1
  18. package/dist/chunks/{generate-B6Odfk5f.js → generate-Cqwa8kD9.js} +2 -2
  19. package/dist/chunks/{generate-B6Odfk5f.js.map → generate-Cqwa8kD9.js.map} +1 -1
  20. package/dist/chunks/{generate-CZGHByV3.js → generate-D3mSFPdT.js} +7 -7
  21. package/dist/chunks/{generate-CZGHByV3.js.map → generate-D3mSFPdT.js.map} +1 -1
  22. package/dist/chunks/{generate-DetW_gbr.js → generate-DyV5R8NP.js} +7 -7
  23. package/dist/chunks/{generate-DetW_gbr.js.map → generate-DyV5R8NP.js.map} +1 -1
  24. package/dist/chunks/generate-jx5Iuq5w.js +75 -0
  25. package/dist/chunks/generate-jx5Iuq5w.js.map +1 -0
  26. package/dist/chunks/{generate.runtime-Djas9UNy.js → generate.runtime-B2r11K7S.js} +4 -4
  27. package/dist/chunks/{generate.runtime-Djas9UNy.js.map → generate.runtime-B2r11K7S.js.map} +1 -1
  28. package/dist/chunks/{generate.runtime-Bcrht4M9.js → generate.runtime-B4u9C2YH.js} +9 -9
  29. package/dist/chunks/{generate.runtime-Bcrht4M9.js.map → generate.runtime-B4u9C2YH.js.map} +1 -1
  30. package/dist/chunks/{generate.runtime-DVB7uuht.js → generate.runtime-BRCzUO94.js} +3 -3
  31. package/dist/chunks/{generate.runtime-DVB7uuht.js.map → generate.runtime-BRCzUO94.js.map} +1 -1
  32. package/dist/chunks/{generate.runtime-IWEhGhWY.js → generate.runtime-BVavIXtX.js} +6 -6
  33. package/dist/chunks/{generate.runtime-IWEhGhWY.js.map → generate.runtime-BVavIXtX.js.map} +1 -1
  34. package/dist/chunks/generate.runtime-Bh9Z2cRN.js +82 -0
  35. package/dist/chunks/generate.runtime-Bh9Z2cRN.js.map +1 -0
  36. package/dist/chunks/{generate.runtime-DJHUBL4Z.js → generate.runtime-BxDUtkpT.js} +12 -12
  37. package/dist/chunks/{generate.runtime-DJHUBL4Z.js.map → generate.runtime-BxDUtkpT.js.map} +1 -1
  38. package/dist/chunks/{generate.runtime-hTKzxH2M.js → generate.runtime-BxUGDXIK.js} +7 -7
  39. package/dist/chunks/{generate.runtime-hTKzxH2M.js.map → generate.runtime-BxUGDXIK.js.map} +1 -1
  40. package/dist/chunks/{generate.runtime-5rIc-RNL.js → generate.runtime-CHb4znYx.js} +66 -66
  41. package/dist/chunks/{generate.runtime-5rIc-RNL.js.map → generate.runtime-CHb4znYx.js.map} +1 -1
  42. package/dist/chunks/{generate.runtime-E-zoeSKW.js → generate.runtime-CRhD98rs.js} +7 -7
  43. package/dist/chunks/{generate.runtime-E-zoeSKW.js.map → generate.runtime-CRhD98rs.js.map} +1 -1
  44. package/dist/chunks/{generate.runtime-BpMN5Uq-.js → generate.runtime-CWnIiXwV.js} +3 -3
  45. package/dist/chunks/{generate.runtime-BpMN5Uq-.js.map → generate.runtime-CWnIiXwV.js.map} +1 -1
  46. package/dist/chunks/{generate.runtime-kciwaXxh.js → generate.runtime-CYBs0JgY.js} +4 -4
  47. package/dist/chunks/{generate.runtime-kciwaXxh.js.map → generate.runtime-CYBs0JgY.js.map} +1 -1
  48. package/dist/chunks/{generate.runtime-CAn1qIQ_.js → generate.runtime-CkmledBw.js} +3 -3
  49. package/dist/chunks/{generate.runtime-CAn1qIQ_.js.map → generate.runtime-CkmledBw.js.map} +1 -1
  50. package/dist/chunks/generate.runtime-CyGR8VTx.js +48 -0
  51. package/dist/chunks/generate.runtime-CyGR8VTx.js.map +1 -0
  52. package/dist/chunks/{generate.runtime-a3R4hqFy.js → generate.runtime-DCqf7nYM.js} +12 -12
  53. package/dist/chunks/{generate.runtime-a3R4hqFy.js.map → generate.runtime-DCqf7nYM.js.map} +1 -1
  54. package/dist/chunks/{generate.runtime-uLUiPgqx.js → generate.runtime-DUo-pLRr.js} +6 -6
  55. package/dist/chunks/{generate.runtime-uLUiPgqx.js.map → generate.runtime-DUo-pLRr.js.map} +1 -1
  56. package/dist/chunks/{generate.runtime-CpMKXBkn.js → generate.runtime-DY5vQ3aZ.js} +7 -7
  57. package/dist/chunks/{generate.runtime-CpMKXBkn.js.map → generate.runtime-DY5vQ3aZ.js.map} +1 -1
  58. package/dist/chunks/{generate.runtime-CEqLgLT9.js → generate.runtime-DYdkrHJ1.js} +70 -70
  59. package/dist/chunks/{generate.runtime-CEqLgLT9.js.map → generate.runtime-DYdkrHJ1.js.map} +1 -1
  60. package/dist/chunks/{generate.runtime-DHHlYfTD.js → generate.runtime-DdcVnK8J.js} +3 -3
  61. package/dist/chunks/{generate.runtime-DHHlYfTD.js.map → generate.runtime-DdcVnK8J.js.map} +1 -1
  62. package/dist/chunks/{generate.runtime-koQxLywh.js → generate.runtime-DeniHg8L.js} +48 -48
  63. package/dist/chunks/{generate.runtime-koQxLywh.js.map → generate.runtime-DeniHg8L.js.map} +1 -1
  64. package/dist/chunks/{generate.runtime-DoZJHtZh.js → generate.runtime-Dmob2wFf.js} +6 -6
  65. package/dist/chunks/{generate.runtime-DoZJHtZh.js.map → generate.runtime-Dmob2wFf.js.map} +1 -1
  66. package/dist/chunks/{generate.runtime-Db0HZyj3.js → generate.runtime-Du4uf98c.js} +2 -2
  67. package/dist/chunks/{generate.runtime-Db0HZyj3.js.map → generate.runtime-Du4uf98c.js.map} +1 -1
  68. package/dist/chunks/{generate.runtime-axm9wcQv.js → generate.runtime-Dug2UIhV.js} +4 -4
  69. package/dist/chunks/{generate.runtime-axm9wcQv.js.map → generate.runtime-Dug2UIhV.js.map} +1 -1
  70. package/dist/chunks/{generate.runtime-rs1ZOIET.js → generate.runtime-FGYc365Q.js} +15 -15
  71. package/dist/chunks/{generate.runtime-rs1ZOIET.js.map → generate.runtime-FGYc365Q.js.map} +1 -1
  72. package/dist/chunks/{generate.runtime-BK3mR0Rj.js → generate.runtime-N1KtAG8C.js} +169 -129
  73. package/dist/chunks/generate.runtime-N1KtAG8C.js.map +1 -0
  74. package/dist/chunks/{generate.runtime-CbE9RHcf.js → generate.runtime-_c7daMAw.js} +5 -5
  75. package/dist/chunks/generate.runtime-_c7daMAw.js.map +1 -0
  76. package/dist/chunks/generate.runtime-aN5QWygO.js +106 -0
  77. package/dist/chunks/generate.runtime-aN5QWygO.js.map +1 -0
  78. package/dist/chunks/{generate.runtime-CZ46nkSL.js → generate.runtime-bpH3DB0t.js} +2 -2
  79. package/dist/chunks/{generate.runtime-CZ46nkSL.js.map → generate.runtime-bpH3DB0t.js.map} +1 -1
  80. package/dist/chunks/{generate.runtime-CqncBFNg.js → generate.runtime-gFr2Gsjz.js} +4 -4
  81. package/dist/chunks/{generate.runtime-CqncBFNg.js.map → generate.runtime-gFr2Gsjz.js.map} +1 -1
  82. package/dist/chunks/{generate.runtime-CK10Mum5.js → generate.runtime-kpqW3dVO.js} +25 -25
  83. package/dist/chunks/{generate.runtime-CK10Mum5.js.map → generate.runtime-kpqW3dVO.js.map} +1 -1
  84. package/dist/chunks/{generate.runtime-Dl6OQ7pe.js → generate.runtime-wGRE1zwZ.js} +4 -4
  85. package/dist/chunks/{generate.runtime-Dl6OQ7pe.js.map → generate.runtime-wGRE1zwZ.js.map} +1 -1
  86. package/dist/chunks/{generate.runtime-aQnBmH8D.js → generate.runtime-wziCW3ct.js} +69 -69
  87. package/dist/chunks/{generate.runtime-aQnBmH8D.js.map → generate.runtime-wziCW3ct.js.map} +1 -1
  88. package/dist/chunks/{generate.runtime-DJ9MVVPC.js → generate.runtime-x-o4LS8d.js} +123 -110
  89. package/dist/chunks/generate.runtime-x-o4LS8d.js.map +1 -0
  90. package/dist/chunks/modify-file-289rStJ2.js +53 -0
  91. package/dist/chunks/modify-file-289rStJ2.js.map +1 -0
  92. package/dist/chunks/{modify-nav-user-BLyrW2sK.js → modify-nav-user-B8h8WTrM.js} +2 -2
  93. package/dist/chunks/{modify-nav-user-BLyrW2sK.js.map → modify-nav-user-B8h8WTrM.js.map} +1 -1
  94. package/dist/chunks/{pocketbase-CgwbH1gI.js → pocketbase-B017Cqjq.js} +2 -2
  95. package/dist/chunks/{pocketbase-CgwbH1gI.js.map → pocketbase-B017Cqjq.js.map} +1 -1
  96. package/dist/chunks/providers-CL9kQ4hp.js +98 -0
  97. package/dist/chunks/providers-CL9kQ4hp.js.map +1 -0
  98. package/dist/chunks/providers-CN5J5_fY.js +38 -0
  99. package/dist/chunks/providers-CN5J5_fY.js.map +1 -0
  100. package/dist/chunks/{shared-Cc_ns5-y.js → shared-BPlAVf-T.js} +2 -2
  101. package/dist/chunks/{shared-Cc_ns5-y.js.map → shared-BPlAVf-T.js.map} +1 -1
  102. package/dist/chunks/shopify-page-D-VFwGxI.js +11 -0
  103. package/dist/chunks/shopify-page-D-VFwGxI.js.map +1 -0
  104. package/dist/chunks/site-DkU1-VRq.js +108 -0
  105. package/dist/chunks/site-DkU1-VRq.js.map +1 -0
  106. package/dist/chunks/stripe-customer-B3tP8gtD.js +6 -0
  107. package/dist/chunks/stripe-customer-B3tP8gtD.js.map +1 -0
  108. package/dist/chunks/{svelte-file-B3RfgVdt.js → svelte-file-Dv5-bl79.js} +37 -2
  109. package/dist/chunks/svelte-file-Dv5-bl79.js.map +1 -0
  110. package/dist/chunks/{table-core-DhDqT03G.js → table-core-vXEjJDYP.js} +2 -2
  111. package/dist/chunks/{table-core-DhDqT03G.js.map → table-core-vXEjJDYP.js.map} +1 -1
  112. package/dist/chunks/{test-setup-B9fQ5L_-.js → test-setup-CAfgVlwc.js} +3 -3
  113. package/dist/chunks/{test-setup-B9fQ5L_-.js.map → test-setup-CAfgVlwc.js.map} +1 -1
  114. package/dist/chunks/{ui-CuCsupFq.js → ui-CTdsenEv.js} +3 -3
  115. package/dist/chunks/{ui-CuCsupFq.js.map → ui-CTdsenEv.js.map} +1 -1
  116. package/dist/chunks/{whatsapp-CguKGTtw.js → whatsapp-5qJ_xCV1.js} +2 -2
  117. package/dist/chunks/{whatsapp-CguKGTtw.js.map → whatsapp-5qJ_xCV1.js.map} +1 -1
  118. package/dist/chunks/{write-result-DiZsCS_y.js → write-result-0HYIr5a6.js} +4 -4
  119. package/dist/chunks/write-result-0HYIr5a6.js.map +1 -0
  120. package/dist/index.d.ts +283 -22
  121. package/dist/index.js +2233 -2031
  122. package/dist/index.js.map +1 -1
  123. package/package.json +1 -1
  124. package/dist/chunks/_page-e_I-fdSR.js.map +0 -1
  125. package/dist/chunks/collections-zzZ_HQxB.js +0 -192
  126. package/dist/chunks/collections-zzZ_HQxB.js.map +0 -1
  127. package/dist/chunks/constants-Rq8SCXwH.js.map +0 -1
  128. package/dist/chunks/dispatch-D4TN9pdW.js +0 -6
  129. package/dist/chunks/dispatch-D4TN9pdW.js.map +0 -1
  130. package/dist/chunks/env-vars-CcE6ODqC.js.map +0 -1
  131. package/dist/chunks/env-vars-De0Xs0L2.js +0 -20
  132. package/dist/chunks/env-vars-De0Xs0L2.js.map +0 -1
  133. package/dist/chunks/generate.runtime-BK3mR0Rj.js.map +0 -1
  134. package/dist/chunks/generate.runtime-CbE9RHcf.js.map +0 -1
  135. package/dist/chunks/generate.runtime-DJ9MVVPC.js.map +0 -1
  136. package/dist/chunks/generate.runtime-EQnytCFL.js +0 -122
  137. package/dist/chunks/generate.runtime-EQnytCFL.js.map +0 -1
  138. package/dist/chunks/modify-file-DK-tCH9k.js +0 -46
  139. package/dist/chunks/modify-file-DK-tCH9k.js.map +0 -1
  140. package/dist/chunks/providers-BHR6-XZ7.js +0 -76
  141. package/dist/chunks/providers-BHR6-XZ7.js.map +0 -1
  142. package/dist/chunks/site-lj0CDdQ1.js +0 -55
  143. package/dist/chunks/site-lj0CDdQ1.js.map +0 -1
  144. package/dist/chunks/svelte-file-B3RfgVdt.js.map +0 -1
  145. package/dist/chunks/write-result-DiZsCS_y.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env-vars-cqQU0ECK.js","names":["envVarsFile","ENV_MODULE","envVarEntry","ENV_DECL_CANDIDATES","languageFromPath","toDeleteEntry","ensureNamedImport","formatLikeSource","modifyOutcomeToFile","fs","path","VARIABLES","DEFINE","unwrap","current","expr","Node","exportedLocalName","decl","sf","spec","bindsName","name","ni","statement","nameNode","SyntaxKind","id","locateVariables","reExported","local","init","value","arg","object","propertyName","prop","inner","declaredNames","names","quoteOf","addEnvVars","located","quote","unique","dedupe","specs","entries","declared","missing","removeEnvVars","wanted","doomed","seen","newProject","Project","QuoteKind","findEnvDecl","rel","abs","root","readEnvVarNames","filePath","relative","REASONS","addHint","file","reason","removeHint","modifyEnvVars","existing","original","result","changed","modifyEnvVarsFiles","create","modify","unmodifyEnvVars","holdsNothing","unmodifyEnvVarsFiles","deleted","outcome"],"sources":["../../src/runtime/env-vars.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n Node,\n Project,\n QuoteKind,\n SyntaxKind,\n type Expression,\n type ObjectLiteralElementLike,\n type ObjectLiteralExpression,\n type SourceFile,\n type Statement,\n} from \"ts-morph\";\nimport type { File, ModifyOutcome } from \"../core/types\";\nimport { languageFromPath } from \"../core/util\";\nimport { toDeleteEntry } from \"../patterns/destroy/shared\";\nimport { modifyOutcomeToFile } from \"./modify-file\";\nimport {\n ENV_DECL_CANDIDATES,\n envVarEntry,\n envVarsFile,\n ENV_MODULE,\n type EnvVarSpec,\n} from \"./env-vars-file\";\nimport { ensureNamedImport, formatLikeSource } from \"./ts-morph-helpers\";\n\nexport { ENV_DECL_CANDIDATES, envVarEntry, envVarsFile, type EnvVarSpec };\n\n/**\n * Declares environment variables in `src/env.ts`, where SvelteKit 3 reads\n * them: a variable it finds no declaration for is not exposed through\n * `$app/env/private` or `$app/env/public` at all.\n *\n * Three shapes of `variables` are edited:\n *\n * - `export const variables = defineEnvVars({ ... })`\n * - `const variables = defineEnvVars({ ... }); export { variables }`\n * - either of the above with a plain object literal in place of the call\n *\n * Entries are matched by property name, quoted or not, and an entry that is\n * already there is never touched: a project that declared `STRIPE_SECRET_KEY`\n * as required keeps it required.\n */\n\nconst VARIABLES = \"variables\";\nconst DEFINE = \"defineEnvVars\";\n\nexport type EnvVarsUnsupported =\n /** `variables` is exported some other way: a function, `export let variables;`, a re-export. */\n | \"not-variable\"\n /** `variables` is not an object literal or `defineEnvVars({ ... })`. */\n | \"not-object\"\n /** The object spreads another one in, which may already declare the names. */\n | \"spread\"\n /** A computed key (`[name]: ...`) whose name can't be read. */\n | \"computed-key\";\n\nexport type EnvVarsEditResult =\n | { status: \"changed\" | \"unchanged\" }\n | { status: \"unsupported\"; reason: EnvVarsUnsupported };\n\ntype Located =\n | { kind: \"object\"; object: ObjectLiteralExpression }\n | { kind: \"missing\" }\n | { kind: \"unsupported\"; reason: EnvVarsUnsupported };\n\nfunction unwrap(expr: Expression): Expression {\n let current = expr;\n for (;;) {\n if (\n Node.isParenthesizedExpression(current) ||\n Node.isAsExpression(current) ||\n Node.isSatisfiesExpression(current)\n ) {\n current = current.getExpression();\n continue;\n }\n return current;\n }\n}\n\n/** The local name exported as `variables`: itself, or `x` in `export { x as variables }`. */\nfunction exportedLocalName(sf: SourceFile): string | null | \"re-export\" {\n for (const decl of sf.getExportDeclarations()) {\n for (const spec of decl.getNamedExports()) {\n const exported = spec.getAliasNode()?.getText() ?? spec.getName();\n if (exported !== VARIABLES) continue;\n if (decl.getModuleSpecifier()) return \"re-export\";\n return spec.getName();\n }\n }\n return null;\n}\n\n/** A top-level import or destructuring pattern that binds `name`. */\nfunction bindsName(sf: SourceFile, name: string): boolean {\n const imported = sf\n .getImportDeclarations()\n .some(\n (decl) =>\n decl.getDefaultImport()?.getText() === name ||\n decl.getNamespaceImport()?.getText() === name ||\n decl\n .getNamedImports()\n .some(\n (ni) => (ni.getAliasNode()?.getText() ?? ni.getName()) === name,\n ),\n );\n if (imported) return true;\n return sf.getVariableStatements().some((statement) =>\n statement.getDeclarations().some((decl) => {\n const nameNode = decl.getNameNode();\n return (\n !Node.isIdentifier(nameNode) &&\n nameNode\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .some(\n (id) =>\n id.getText() === name &&\n (Node.isBindingElement(id.getParent()) ||\n Node.isShorthandPropertyAssignment(id.getParent())),\n )\n );\n }),\n );\n}\n\nfunction locateVariables(sf: SourceFile): Located {\n const reExported = exportedLocalName(sf);\n if (reExported === \"re-export\") {\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n const local = reExported ?? VARIABLES;\n\n const decl = sf.getVariableDeclaration(local);\n if (!decl) {\n // A function, class, import or destructured binding of that name,\n // exported or not, is not ours to replace.\n const taken =\n sf.getFunction(local) ?? sf.getClass(local) ?? sf.getEnum(local);\n if (taken || reExported || bindsName(sf, local)) {\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n return { kind: \"missing\" };\n }\n if (!reExported && !decl.isExported()) {\n // `const variables = ...` that SvelteKit can't see; exporting it is the\n // developer's call, not ours.\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n if (!Node.isIdentifier(decl.getNameNode())) {\n return { kind: \"unsupported\", reason: \"not-variable\" };\n }\n const init = decl.getInitializer();\n if (!init) return { kind: \"unsupported\", reason: \"not-variable\" };\n\n const value = unwrap(init);\n if (Node.isObjectLiteralExpression(value)) {\n return { kind: \"object\", object: value };\n }\n if (\n Node.isCallExpression(value) &&\n value.getExpression().getText() === DEFINE\n ) {\n const arg = value.getArguments()[0];\n const object = arg && unwrap(arg as Expression);\n if (object && Node.isObjectLiteralExpression(object)) {\n return { kind: \"object\", object };\n }\n }\n return { kind: \"unsupported\", reason: \"not-object\" };\n}\n\n/** A property's name as SvelteKit sees it, `null` for a spread or computed key. */\nfunction propertyName(prop: ObjectLiteralElementLike): string | null {\n if (Node.isSpreadAssignment(prop)) return null;\n const nameNode = prop.getNameNode();\n if (Node.isComputedPropertyName(nameNode)) {\n const inner = nameNode.getExpression();\n return Node.isStringLiteral(inner) ||\n Node.isNoSubstitutionTemplateLiteral(inner)\n ? inner.getLiteralText()\n : null;\n }\n if (\n Node.isStringLiteral(nameNode) ||\n Node.isNoSubstitutionTemplateLiteral(nameNode)\n ) {\n return nameNode.getLiteralText();\n }\n return nameNode.getText();\n}\n\nfunction declaredNames(\n object: ObjectLiteralExpression,\n): Set<string> | EnvVarsUnsupported {\n const names = new Set<string>();\n for (const prop of object.getProperties()) {\n if (Node.isSpreadAssignment(prop)) return \"spread\";\n const name = propertyName(prop);\n if (name === null) return \"computed-key\";\n names.add(name);\n }\n return names;\n}\n\n/** The quote the file already writes its strings with. */\nfunction quoteOf(sf: SourceFile): \"'\" | '\"' {\n const first = sf.getFirstDescendantByKind(SyntaxKind.StringLiteral);\n return first?.getText().startsWith('\"') ? '\"' : \"'\";\n}\n\n/**\n * Add a declaration for every spec `sf` doesn't declare yet. Creates\n * `export const variables = defineEnvVars({ ... })`, and its import, when the\n * file has no `variables` at all. Neither formats nor saves.\n */\nexport function addEnvVars(\n sf: SourceFile,\n specs: EnvVarSpec[],\n): EnvVarsEditResult {\n const located = locateVariables(sf);\n if (located.kind === \"unsupported\") {\n return { status: \"unsupported\", reason: located.reason };\n }\n const quote = quoteOf(sf);\n\n if (located.kind === \"missing\") {\n const unique = dedupe(specs);\n if (unique.length === 0) return { status: \"unchanged\" };\n ensureNamedImport(sf, ENV_MODULE, DEFINE);\n const entries = unique\n .map((spec) => `\\t${envVarEntry(spec, { quote })}`)\n .join(\",\\n\");\n sf.addStatements(\n `\\nexport const ${VARIABLES} = ${DEFINE}({\\n${entries}\\n});`,\n );\n return { status: \"changed\" };\n }\n\n const declared = declaredNames(located.object);\n if (typeof declared === \"string\") {\n return { status: \"unsupported\", reason: declared };\n }\n const missing = dedupe(specs).filter((spec) => !declared.has(spec.name));\n if (missing.length === 0) return { status: \"unchanged\" };\n for (const spec of missing) {\n located.object.addProperty(envVarEntry(spec, { quote }));\n }\n return { status: \"changed\" };\n}\n\n/**\n * Remove the declarations of `names` from `sf`. A file with no `variables`,\n * or none of the names, is unchanged. Neither formats nor saves.\n */\nexport function removeEnvVars(\n sf: SourceFile,\n names: string[],\n): EnvVarsEditResult {\n const located = locateVariables(sf);\n if (located.kind === \"missing\") return { status: \"unchanged\" };\n if (located.kind === \"unsupported\") {\n return { status: \"unsupported\", reason: located.reason };\n }\n const wanted = new Set(names);\n const doomed = located.object.getProperties().filter((prop) => {\n const name = propertyName(prop);\n return name !== null && wanted.has(name);\n });\n if (doomed.length === 0) return { status: \"unchanged\" };\n for (const prop of doomed.reverse()) prop.remove();\n if (located.object.getProperties().length === 0) {\n located.object.replaceWithText(\"{}\");\n }\n return { status: \"changed\" };\n}\n\nfunction dedupe(specs: EnvVarSpec[]): EnvVarSpec[] {\n const seen = new Set<string>();\n return specs.filter((spec) => {\n if (seen.has(spec.name)) return false;\n seen.add(spec.name);\n return true;\n });\n}\n\nfunction newProject(): Project {\n return new Project({\n compilerOptions: { allowJs: true },\n skipFileDependencyResolution: true,\n manipulationSettings: { quoteKind: QuoteKind.Single },\n });\n}\n\n/** The project's declaration file: `src/env.ts` or `src/env.js`, if either exists. */\nexport function findEnvDecl(root: string): string | null {\n for (const rel of ENV_DECL_CANDIDATES) {\n const abs = path.join(root, rel);\n if (fs.existsSync(abs)) return abs;\n }\n return null;\n}\n\n/**\n * The names `src/env.ts` (or `src/env.js`) declares. Spreads and computed\n * keys it can't read are skipped rather than failing the whole read, so a\n * declaration file this module couldn't edit still reports what it can. No\n * file, or no `variables` this can read, is an empty set.\n */\nexport function readEnvVarNames(root: string): Set<string> {\n const filePath = findEnvDecl(root);\n if (!filePath) return new Set();\n\n const sf = newProject().addSourceFileAtPath(filePath);\n const located = locateVariables(sf);\n if (located.kind !== \"object\") return new Set();\n\n const names = new Set<string>();\n for (const prop of located.object.getProperties()) {\n const name = propertyName(prop);\n if (name !== null) names.add(name);\n }\n return names;\n}\n\nfunction relative(root: string, filePath: string): string {\n return path.relative(root, filePath).split(path.sep).join(\"/\");\n}\n\nconst REASONS: Record<EnvVarsUnsupported, string> = {\n \"not-variable\": \"its `variables` export is not a variable this can edit\",\n \"not-object\":\n \"`variables` is not an object literal or a `defineEnvVars({ ... })` call\",\n spread: \"`variables` spreads in another object\",\n \"computed-key\": \"`variables` has a computed key\",\n};\n\nfunction addHint(\n file: string,\n reason: EnvVarsUnsupported,\n specs: EnvVarSpec[],\n): string {\n return [\n `Could not edit ${file}: ${REASONS[reason]}.`,\n \"Declare these in the object passed to defineEnvVars() (or exported as `variables`), skipping any already there:\",\n \"\",\n ...dedupe(specs).map((spec) => `${envVarEntry(spec)},`),\n ].join(\"\\n\");\n}\n\nfunction removeHint(\n file: string,\n reason: EnvVarsUnsupported,\n names: string[],\n): string {\n return [\n `Could not edit ${file}: ${REASONS[reason]}.`,\n `Remove these declarations from \\`variables\\` by hand: ${names.join(\", \")}`,\n ].join(\"\\n\");\n}\n\nexport interface ModifyEnvVarsResult {\n /** `src/env.ts` to create, when the project has no declaration file. */\n create?: File;\n /** The existing declaration file, already saved when `outcome` changed it. */\n modify?: { filePath: string; outcome: ModifyOutcome };\n}\n\n/**\n * Declare `specs` in the project's `src/env.ts` (or `src/env.js`). Existing\n * entries are never touched.\n *\n * - No declaration file: `create` holds a new `src/env.ts` (always `.ts`,\n * written like the CLI templates' one); nothing is written yet.\n * - An existing file is edited and saved in place, and `modify` reports it\n * like every other runtime modifier: turn it into a File with\n * `modifyOutcomeToFile` (or use {@link modifyEnvVarsFiles}).\n * - A file whose `variables` can't be edited safely is left alone, and the\n * `failed` outcome's message lists the exact entries to paste.\n */\nexport function modifyEnvVars(\n root: string,\n specs: EnvVarSpec[],\n): ModifyEnvVarsResult {\n const existing = findEnvDecl(root);\n if (!existing) {\n if (dedupe(specs).length === 0) return {};\n const filePath = path.join(root, ENV_DECL_CANDIDATES[0]);\n return {\n create: {\n path: filePath,\n language: languageFromPath(filePath),\n content: envVarsFile(specs),\n status: \"success\",\n },\n };\n }\n\n const sf = newProject().addSourceFileAtPath(existing);\n const original = sf.getFullText();\n const result = addEnvVars(sf, specs);\n if (result.status === \"unsupported\") {\n return {\n modify: {\n filePath: existing,\n outcome: {\n status: \"failed\",\n message: addHint(relative(root, existing), result.reason, specs),\n },\n },\n };\n }\n if (result.status === \"unchanged\") {\n return {\n modify: {\n filePath: existing,\n outcome: { status: \"success\", changed: false },\n },\n };\n }\n formatLikeSource(sf);\n const changed = sf.getFullText() !== original;\n if (changed) sf.saveSync();\n return {\n modify: { filePath: existing, outcome: { status: \"success\", changed } },\n };\n}\n\n/** {@link modifyEnvVars} as the File entries a pattern's Result carries. */\nexport function modifyEnvVarsFiles(\n root: string,\n specs: EnvVarSpec[],\n): { create: File | null; modify: File | null } {\n const { create, modify } = modifyEnvVars(root, specs);\n return {\n create: create ?? null,\n modify: modify\n ? modifyOutcomeToFile(modify.filePath, modify.outcome)\n : null,\n };\n}\n\nexport interface UnmodifyEnvVarsResult {\n filePath: string;\n outcome: ModifyOutcome;\n /**\n * The revert left nothing but the `defineEnvVars` import and an empty\n * `variables`. The emptied file has been saved; the caller reports it as a\n * delete (`toDeleteEntry(filePath)`) instead of a modify, as\n * {@link unmodifyEnvVarsFiles} does.\n */\n deleted: boolean;\n}\n\n/**\n * Remove the declarations of `names` from `src/env.ts` (or `.js`). A project\n * without the file, or without the names, is a no-op success.\n */\nexport function unmodifyEnvVars(\n root: string,\n names: string[],\n): UnmodifyEnvVarsResult {\n const existing = findEnvDecl(root);\n if (!existing) {\n return {\n filePath: path.join(root, ENV_DECL_CANDIDATES[0]),\n outcome: { status: \"success\", changed: false },\n deleted: false,\n };\n }\n\n const sf = newProject().addSourceFileAtPath(existing);\n const original = sf.getFullText();\n const result = removeEnvVars(sf, names);\n if (result.status === \"unsupported\") {\n return {\n filePath: existing,\n outcome: {\n status: \"failed\",\n message: removeHint(relative(root, existing), result.reason, names),\n },\n deleted: false,\n };\n }\n if (result.status === \"unchanged\") {\n return {\n filePath: existing,\n outcome: { status: \"success\", changed: false },\n deleted: false,\n };\n }\n formatLikeSource(sf);\n const changed = sf.getFullText() !== original;\n if (changed) sf.saveSync();\n return {\n filePath: existing,\n outcome: { status: \"success\", changed },\n deleted: changed && holdsNothing(sf),\n };\n}\n\n/** {@link unmodifyEnvVars} as the File entries a pattern's Result carries. */\nexport function unmodifyEnvVarsFiles(\n root: string,\n names: string[],\n): { modify: File | null; delete: File | null } {\n const { filePath, outcome, deleted } = unmodifyEnvVars(root, names);\n if (deleted) return { modify: null, delete: toDeleteEntry(filePath) };\n return { modify: modifyOutcomeToFile(filePath, outcome), delete: null };\n}\n\n/**\n * Only the `defineEnvVars` import, an empty `variables` and its\n * `export { variables }` are left. Comments don't count.\n */\nfunction holdsNothing(sf: SourceFile): boolean {\n const located = locateVariables(sf);\n if (located.kind !== \"object\") return false;\n if (located.object.getProperties().length > 0) return false;\n const decl = located.object.getFirstAncestorByKind(\n SyntaxKind.VariableStatement,\n );\n return sf.getStatements().every((statement: Statement) => {\n if (statement === decl) return true;\n if (Node.isEmptyStatement(statement)) return true;\n if (Node.isImportDeclaration(statement)) {\n return (\n statement.getModuleSpecifierValue() === ENV_MODULE &&\n !statement.getDefaultImport() &&\n !statement.getNamespaceImport() &&\n statement.getNamedImports().every((ni) => ni.getName() === DEFINE)\n );\n }\n if (Node.isExportDeclaration(statement)) {\n return (\n !statement.getModuleSpecifier() &&\n statement\n .getNamedExports()\n .every(\n (spec) =>\n (spec.getAliasNode()?.getText() ?? spec.getName()) === VARIABLES,\n )\n );\n }\n return false;\n });\n}\n"],"mappings":";;;;;;;;;AA4CA,IAAMW,IAAY,aACZC,IAAS;AAqBf,SAASC,EAAO,GAA8B;CAC5C,IAAIC,IAAUC;CACd,SAAS;EACP,IACEC,EAAK,0BAA0BF,CAAO,KACtCE,EAAK,eAAeF,CAAO,KAC3BE,EAAK,sBAAsBF,CAAO,GAClC;GACA,IAAUA,EAAQ,cAAc;GAChC;EACF;EACA,OAAOA;CACT;AACF;AAGA,SAASG,EAAkB,GAA6C;CACtE,KAAK,IAAMC,KAAQC,EAAG,sBAAsB,GAC1C,KAAK,IAAMC,KAAQF,EAAK,gBAAgB,GAEtC,KADiBE,EAAK,aAAa,CAAC,EAAE,QAAQ,KAAKA,EAAK,QAAQ,OAC/CT,GAEjB,OADIO,EAAK,mBAAmB,IAAU,cAC/BE,EAAK,QAAQ;CAGxB,OAAO;AACT;AAGA,SAASC,EAAU,GAAgB,GAAuB;CAcxD,OAbiBF,EACd,sBAAsB,CAAC,CACvB,MACE,MACCD,EAAK,iBAAiB,CAAC,EAAE,QAAQ,MAAMI,KACvCJ,EAAK,mBAAmB,CAAC,EAAE,QAAQ,MAAMI,KACzCJ,EACG,gBAAgB,CAAC,CACjB,MACE,OAAQK,EAAG,aAAa,CAAC,EAAE,QAAQ,KAAKA,EAAG,QAAQ,OAAOD,CAC7D,CAEJ,IAAiB,KACdH,EAAG,sBAAsB,CAAC,CAAC,MAAM,MACtC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oBsD,GAAUmB,CAAO;EAAG,QAAQ;CAAK;AACxE;AAMA,SAASH,EAAa,GAAyB;CAC7C,IAAMpC,IAAUd,EAAgBT,CAAE;CAElC,IADIuB,EAAQ,SAAS,YACjBA,EAAQ,OAAO,cAAc,CAAC,CAAC,SAAS,GAAG,OAAO;CACtD,IAAMxB,IAAOwB,EAAQ,OAAO,uBAC1BhB,EAAW,iBACb;CACA,OAAOP,EAAG,cAAc,CAAC,CAAC,OAAO,MAC3BK,MAAcN,KACdF,EAAK,iBAAiBQ,CAAS,IAAU,KACzCR,EAAK,oBAAoBQ,CAAS,IAElCA,EAAU,wBAAwB,MAAA,uBAClC,CAACA,EAAU,iBAAiB,KAC5B,CAACA,EAAU,mBAAmB,KAC9BA,EAAU,gBAAgB,CAAC,CAAC,OAAO,MAAOD,EAAG,QAAQ,MAAMX,CAAM,IAGjEI,EAAK,oBAAoBQ,CAAS,IAElC,CAACA,EAAU,mBAAmB,KAC9BA,EACG,gBAAgB,CAAC,CACjB,OACE,OACEJ,EAAK,aAAa,CAAC,EAAE,QAAQ,KAAKA,EAAK,QAAQ,OAAOT,CAC3D,IAGC,EACR;AACH"}
@@ -0,0 +1,170 @@
1
+ import { t as e } from "./errors-DR3gF_7a.js";
2
+ import { _ as t } from "./constants-iej3WkEa.js";
3
+ import { c as n, i as r, r as i } from "./providers-CL9kQ4hp.js";
4
+ import { t as a } from "./stripe-customer-B3tP8gtD.js";
5
+ import { n as o, t as s } from "./_page-DoPdZgZv.js";
6
+ //#region src/patterns/enable/payments/providers/shopify/src/lib/components/payments/buy-button.svelte?raw
7
+ var c = "<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", l = "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", u = "<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", d = "<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", f = "<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", p = "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", m = "<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", h = "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", g = "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", _ = "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", v = "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", y = "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", b = "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", x = "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", S = "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", C = "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", w = "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", T = "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", E = "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", D = "<script lang=\"ts\">\n import { Input } from '#lib/components/ui/input/index.js';\n import { Label } from '#lib/components/ui/label/index.js';\n import { Textarea } from '#lib/components/ui/textarea/index.js';\n\n /** Who is ordering: what the business needs to follow up an order whose chat was never sent. */\n let { disabled = false }: { disabled?: boolean } = $props();\n<\/script>\n\n<div class=\"grid gap-2\">\n <Label for=\"order-name\">Name</Label>\n <Input id=\"order-name\" name=\"name\" autocomplete=\"name\" required {disabled} />\n</div>\n<div class=\"grid gap-2\">\n <Label for=\"order-phone\">Phone</Label>\n <Input id=\"order-phone\" name=\"phone\" type=\"tel\" autocomplete=\"tel\" required {disabled} />\n</div>\n<div class=\"grid gap-2\">\n <Label for=\"order-note\">Note (optional)</Label>\n <Textarea id=\"order-note\" name=\"note\" rows={2} {disabled} />\n</div>\n<!-- A person never sees this; a bot that fills it is dropped by the hosted form. -->\n<input type=\"text\" name=\"_gotcha\" tabindex=\"-1\" autocomplete=\"off\" aria-hidden=\"true\" class=\"hidden\" />\n", O = "<script lang=\"ts\">\n import { toast } from 'svelte-sonner';\n import { formToken, orderRef, orderSubtotal, type OrderLine } from '@velastack/whatsapp';\n import { Button, buttonVariants } from '#lib/components/ui/button/index.js';\n import type { ButtonProps } from '#lib/components/ui/button/index.js';\n import * as Dialog from '#lib/components/ui/dialog/index.js';\n import CustomerFields from './customer-fields.svelte';\n import { ORDER_FORM, placeOrder } from '#lib/order.js';\n import { site } from '#lib/site.js';\n\n interface Props {\n /** What is being ordered, as the business will read it. */\n name: string;\n /** The unit price in `site.currency`, written as you would (`4.5`). Leave it out to quote in the chat. */\n price?: number;\n quantity?: number;\n label?: string;\n }\n\n let {\n name,\n price,\n quantity = 1,\n label = 'Order on WhatsApp',\n ...rest\n }: Props & ButtonProps = $props();\n\n let open = $state(false);\n let placed = $state<{ ref: string; href: string } | null>(null);\n // Fetched once, the first time the dialog opens: the hosted form refuses\n // a token younger than two seconds, and filling the form in takes longer.\n let token: string | null = null;\n\n $effect(() => {\n if (!open || !ORDER_FORM || token) return;\n formToken(ORDER_FORM).then((value) => (token = value));\n });\n\n function submit(event: SubmitEvent) {\n event.preventDefault();\n const data = new FormData(event.currentTarget as HTMLFormElement);\n const lines: OrderLine[] = [{ name, quantity, price }];\n const order = {\n ref: orderRef(),\n name: String(data.get('name') ?? ''),\n phone: String(data.get('phone') ?? ''),\n note: String(data.get('note') ?? '') || undefined,\n currency: site.currency,\n lines,\n subtotal: orderSubtotal(lines, site.currency)\n };\n const href = placeOrder(order, { token, gotcha: String(data.get('_gotcha') ?? '') });\n if (!href) {\n toast.error('WhatsApp ordering is not set up yet');\n return;\n }\n placed = { ref: order.ref, href };\n }\n\n function close() {\n open = false;\n placed = null;\n }\n<\/script>\n\n<Button onclick={() => (open = true)} {...rest}>{label}</Button>\n\n<Dialog.Root bind:open onOpenChange={(value) => !value && close()}>\n <Dialog.Content class=\"sm:max-w-md\">\n {#if placed}\n <Dialog.Header>\n <Dialog.Title>Order {placed.ref} opened in WhatsApp</Dialog.Title>\n <Dialog.Description>\n Send the message in WhatsApp to place your order. We'll reply there.\n </Dialog.Description>\n </Dialog.Header>\n <Dialog.Footer>\n <a\n href={placed.href}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n class={buttonVariants({ variant: 'outline' })}\n >\n Open WhatsApp again\n </a>\n <Button onclick={close}>Done</Button>\n </Dialog.Footer>\n {:else}\n <form class=\"grid gap-4\" onsubmit={submit}>\n <Dialog.Header>\n <Dialog.Title>Order {name}</Dialog.Title>\n <Dialog.Description>\n Your order opens in WhatsApp, ready to send.\n </Dialog.Description>\n </Dialog.Header>\n <CustomerFields />\n <Dialog.Footer>\n <Button type=\"submit\">Continue in WhatsApp</Button>\n </Dialog.Footer>\n </form>\n {/if}\n </Dialog.Content>\n</Dialog.Root>\n", k = "import { browser } from '$app/env';\nimport { PUBLIC_WHATSAPP_NUMBER, PUBLIC_WHATSAPP_ORDER_FORM } from '$app/env/public';\nimport {\n formatLines,\n formatMoney,\n openChat,\n recordOrder,\n whatsappHref,\n type Order\n} from '@velastack/whatsapp';\nimport { site } from '#lib/site.js';\n\n/** The hosted VelaStack form each order is recorded to. Empty records nothing. */\nexport const ORDER_FORM = PUBLIC_WHATSAPP_ORDER_FORM;\n\n/**\n * The page's language, so a price reads the way the page does (an English\n * page shows MXN as `MX$5.50`, a Spanish one as `$5.50`) rather than the way\n * the visitor's browser is set.\n */\nfunction pageLocale(): string | undefined {\n return (browser && document.documentElement.lang) || undefined;\n}\n\n/** A price in the business's currency (`site.currency`), formatted for the page. */\nexport function formatPrice(amount: number): string {\n return formatMoney(amount, site.currency, pageLocale());\n}\n\n/**\n * The message the customer sends the business. It is yours to change: this\n * is what lands in the business's WhatsApp.\n */\nexport function orderMessage(order: Order): string {\n const lines = [\n `Hi! I'd like to place an order (${order.ref}):`,\n '',\n formatLines(order.lines, order.currency, pageLocale())\n ];\n if (order.subtotal !== undefined) lines.push('', `Total: ${formatPrice(order.subtotal)}`);\n lines.push('', `Name: ${order.name}`, `Phone: ${order.phone}`);\n if (order.note) lines.push(`Note: ${order.note}`);\n return lines.join('\\n');\n}\n\n/**\n * Records the order and opens the chat with the business. Call it straight\n * from the submit handler: the chat has to open before anything is awaited,\n * or the browser blocks it. Returns the chat link, or `null` when\n * `PUBLIC_WHATSAPP_NUMBER` is not set.\n */\nexport function placeOrder(\n order: Order,\n form: { token: string | null; gotcha: string }\n): string | null {\n const message = orderMessage(order);\n const href = whatsappHref(PUBLIC_WHATSAPP_NUMBER, message);\n if (!href) return null;\n if (ORDER_FORM) {\n recordOrder(ORDER_FORM, order, { message, ...form }).catch((error) => {\n console.error('Recording the order failed:', error);\n });\n }\n openChat(href);\n return href;\n}\n", A = "<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", j = "<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", M = "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", N = "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", P = "export const load = async ({ parent }) => {\n const { breadcrumbs } = await parent();\n\n return {\n breadcrumbs: [...breadcrumbs, { title: \"Billing\", url: \"/billing\" }],\n };\n};\n", F = "# 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", I = "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", L = "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", R = "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", z = "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", B = "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", V = "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", H = "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", U = "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", W = "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", G = [
8
+ {
9
+ id: "stripe",
10
+ label: "Stripe",
11
+ env: [
12
+ {
13
+ key: "STRIPE_SECRET_KEY",
14
+ label: "Stripe secret key",
15
+ placeholder: "sk_...",
16
+ secret: !0,
17
+ required: !0,
18
+ description: "Stripe secret key (`sk_...`) the server calls the Stripe API with."
19
+ },
20
+ {
21
+ key: "PUBLIC_STRIPE_PUBLISHABLE_KEY",
22
+ label: "Stripe publishable key",
23
+ placeholder: "pk_...",
24
+ public: !0,
25
+ required: !0,
26
+ description: "Stripe publishable key (`pk_...`) that Stripe.js loads in the browser."
27
+ },
28
+ {
29
+ key: "STRIPE_WEBHOOK_SECRET",
30
+ label: "Stripe webhook signing secret",
31
+ placeholder: "whsec_...",
32
+ secret: !0,
33
+ required: !0,
34
+ description: "Signing secret (`whsec_...`) that `/webhooks/stripe` verifies events with."
35
+ }
36
+ ],
37
+ markers: [{ env: "STRIPE_SECRET_KEY" }, { path: "src/routes/webhooks/stripe" }],
38
+ requires: {
39
+ backend: !0,
40
+ workflows: !0
41
+ }
42
+ },
43
+ {
44
+ id: "shopify",
45
+ label: "Shopify",
46
+ env: [{
47
+ key: "PUBLIC_SHOPIFY_STORE_DOMAIN",
48
+ label: "Shopify store domain",
49
+ placeholder: "your-store.myshopify.com",
50
+ public: !0,
51
+ required: !0,
52
+ description: "The store's `*.myshopify.com` domain the Storefront API is called on."
53
+ }, {
54
+ key: "PUBLIC_SHOPIFY_STOREFRONT_TOKEN",
55
+ label: "Shopify Storefront API public access token",
56
+ public: !0,
57
+ required: !0,
58
+ description: "Public Storefront API access token, from the store's Headless channel."
59
+ }]
60
+ },
61
+ {
62
+ id: "whatsapp",
63
+ label: "WhatsApp",
64
+ env: [{
65
+ key: "PUBLIC_WHATSAPP_NUMBER",
66
+ label: "WhatsApp number orders are sent to",
67
+ placeholder: "+353 1 555 0100",
68
+ public: !0,
69
+ required: !0,
70
+ description: "The business's WhatsApp number, with country code, that orders open a chat with."
71
+ }, {
72
+ key: "PUBLIC_WHATSAPP_ORDER_FORM",
73
+ label: "Hosted VelaStack form orders are recorded to",
74
+ placeholder: "https://velastack.dev/v1/projects/<project>/forms/order",
75
+ public: !0,
76
+ description: "The hosted VelaStack form each order is recorded to, so it is kept even if the chat is never sent. Empty records nothing."
77
+ }]
78
+ }
79
+ ], K = {
80
+ slug: "enable-payments",
81
+ providers: G
82
+ };
83
+ function q(e, t = {}) {
84
+ return r(e, `${e.label} credentials`, t);
85
+ }
86
+ var J = {
87
+ stripe: [
88
+ "dialog",
89
+ "input",
90
+ "label"
91
+ ],
92
+ shopify: ["button"],
93
+ whatsapp: [
94
+ "button",
95
+ "dialog",
96
+ "input",
97
+ "label",
98
+ "textarea"
99
+ ]
100
+ }, Y = {
101
+ stripe: ["stripe", "@stripe/stripe-js"],
102
+ shopify: ["@shopify/storefront-api-client"],
103
+ whatsapp: [t]
104
+ }, X = /* #__PURE__ */ Object.assign({
105
+ "./providers/shopify/src/lib/components/payments/buy-button.svelte": c,
106
+ "./providers/shopify/src/lib/shopify.ts": l,
107
+ "./providers/stripe/src/lib/components/payments/confirm-dialog.svelte": u,
108
+ "./providers/stripe/src/lib/components/payments/payment-button.svelte": d,
109
+ "./providers/stripe/src/lib/components/payments/payment-dialog.svelte": f,
110
+ "./providers/stripe/src/lib/components/payments/stripe-constants.ts": p,
111
+ "./providers/stripe/src/lib/components/payments/stripe-payment-form.svelte": m,
112
+ "./providers/stripe/src/lib/components/payments/use-payment-intent.svelte.ts": h,
113
+ "./providers/stripe/src/lib/components/payments/use-stripe.svelte.ts": g,
114
+ "./providers/stripe/src/lib/stripe.ts": _,
115
+ "./providers/stripe/src/lib/workflows/stripe-event.ts": v,
116
+ "./providers/stripe/src/lib/workflows/sync-stripe-catalog.ts": y,
117
+ "./providers/stripe/src/routes/api/stripe/payment-intent/+server.ts": b,
118
+ "./providers/stripe/src/routes/api/stripe/payment-intent/server.test.ts": x,
119
+ "./providers/stripe/src/routes/webhooks/stripe/+server.ts": S,
120
+ "./providers/stripe/src/routes/webhooks/stripe/handlers/dispatch.ts": C,
121
+ "./providers/stripe/src/routes/webhooks/stripe/handlers/payment-intent/server.test.ts": w,
122
+ "./providers/stripe/src/routes/webhooks/stripe/handlers/payment-intent/succeeded.ts": T,
123
+ "./providers/stripe/src/routes/webhooks/stripe/server.test.ts": E,
124
+ "./providers/whatsapp/src/lib/components/payments/customer-fields.svelte": D,
125
+ "./providers/whatsapp/src/lib/components/payments/order-button.svelte": O,
126
+ "./providers/whatsapp/src/lib/order.ts": k
127
+ }), Z = /* #__PURE__ */ Object.assign({
128
+ "./providers-app-mode/stripe/src/lib/components/payments/setup-button.svelte": A,
129
+ "./providers-app-mode/stripe/src/lib/components/payments/setup-dialog.svelte": j,
130
+ "./providers-app-mode/stripe/src/lib/server/stripe-customer.ts": a,
131
+ "./providers-app-mode/stripe/src/lib/workflows/link-stripe-customer.ts": M,
132
+ "./providers-app-mode/stripe/src/lib/workflows/sync-stripe-customers.ts": N,
133
+ "./providers-app-mode/stripe/src/routes/(app)/billing/+layout.server.ts": P,
134
+ "./providers-app-mode/stripe/src/routes/(app)/billing/+page.server.ts": o,
135
+ "./providers-app-mode/stripe/src/routes/(app)/billing/+page.svelte": s,
136
+ "./providers-app-mode/stripe/src/routes/(app)/billing/README.md": F,
137
+ "./providers-app-mode/stripe/src/routes/api/stripe/payment-intent/+server.ts": I,
138
+ "./providers-app-mode/stripe/src/routes/api/stripe/payment-intent/server.test.ts": L,
139
+ "./providers-app-mode/stripe/src/routes/api/stripe/setup-intent/+server.ts": R,
140
+ "./providers-app-mode/stripe/src/routes/api/stripe/setup-intent/server.test.ts": z,
141
+ "./providers-app-mode/stripe/src/routes/webhooks/stripe/handlers/dispatch.ts": B,
142
+ "./providers-app-mode/stripe/src/routes/webhooks/stripe/handlers/payment-intent/server.test.ts": V,
143
+ "./providers-app-mode/stripe/src/routes/webhooks/stripe/handlers/payment-intent/succeeded.ts": H,
144
+ "./providers-app-mode/stripe/src/routes/webhooks/stripe/handlers/payment-method/attached.ts": U,
145
+ "./providers-app-mode/stripe/src/routes/webhooks/stripe/handlers/payment-method/server.test.ts": W
146
+ });
147
+ async function Q(t) {
148
+ let r = n(K, t), a = t.providers?.payments;
149
+ if (a !== void 0 && a !== r.id) {
150
+ let t = G.find((e) => e.id === a)?.label ?? a;
151
+ throw new e(`This project already uses ${t} payments. To switch to ${r.label}, run \`vela disable payments\` first, then enable payments again.`);
152
+ }
153
+ let o = t.features.auth, s = new Map(i(X, r.id).map((e) => [e.path, e]));
154
+ if (o) for (let e of i(Z, r.id, "./providers-app-mode/")) s.set(e.path, e);
155
+ let c = [...J[r.id] ?? []];
156
+ return o && r.id === "stripe" && c.push("alert-dialog"), {
157
+ creates: [...s.values()].sort((e, t) => e.path.localeCompare(t.path)),
158
+ modifies: [],
159
+ deletes: [],
160
+ components: c,
161
+ packages: Y[r.id] ?? [],
162
+ collections: [],
163
+ collectionPatches: [],
164
+ collectionDrops: []
165
+ };
166
+ }
167
+ //#endregion
168
+ export { y as A, l as B, E as C, S as D, C as E, m as F, p as I, f as L, _ as M, g as N, x as O, h as P, d as R, D as S, w as T, c as V, M as _, W as a, k as b, V as c, R as d, L as f, N as g, P as h, Q as i, v as j, b as k, B as l, F as m, G as n, U as o, I as p, q as r, H as s, K as t, z as u, j as v, T as w, O as x, A as y, u as z };
169
+
170
+ //# sourceMappingURL=generate-8FS2ROOJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate-8FS2ROOJ.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__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","VELASTACK_WHATSAPP","resolveProvider","providerEnvEdits","providerCreates","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","customer_fields_default","order_button_default","order_default","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","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\";\nimport { VELASTACK_WHATSAPP } from \"../../../core/constants\";\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 id: \"whatsapp\",\n label: \"WhatsApp\",\n env: [\n {\n key: \"PUBLIC_WHATSAPP_NUMBER\",\n label: \"WhatsApp number orders are sent to\",\n placeholder: \"+353 1 555 0100\",\n public: true,\n required: true,\n description:\n \"The business's WhatsApp number, with country code, that orders open a chat with.\",\n },\n {\n key: \"PUBLIC_WHATSAPP_ORDER_FORM\",\n label: \"Hosted VelaStack form orders are recorded to\",\n placeholder: \"https://velastack.dev/v1/projects/<project>/forms/order\",\n public: true,\n description:\n \"The hosted VelaStack form each order is recorded to, so it is kept even if the chat is never sent. Empty records nothing.\",\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 whatsapp: [\"button\", \"dialog\", \"input\", \"label\", \"textarea\"],\n};\n\nconst PACKAGES: Record<string, Package[]> = {\n stripe: [\"stripe\", \"@stripe/stripe-js\"],\n shopify: [\"@shopify/storefront-api-client\"],\n whatsapp: [VELASTACK_WHATSAPP],\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 and WhatsApp has none, so neither has 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":";;;;;;6z/FAqBaqF,IAAwB;CACnC;EACE,IAAI;EACJ,OAAO;EACP,KAAK;GACH;IACE,KAAK;IACL,OAAO;IACP,aAAa;IACb,QAAQ;IACR,UAAU;IAC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,GAAGF,EAAQ,OAAO,CAAC,CAAC,CAAC,MAAM,GAAG,MAAMG,EAAE,KAAK,cAAcC,EAAE,IAAI,CAAC;EAC1E,UAAU,CAAC;EACX,SAAS,CAAC;EACV;EACA,UAAUb,EAASH,EAAS,OAAO,CAAC;EACpC,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,7 +1,7 @@
1
1
  import { t as e } from "./util-BLYliuUK.js";
2
- import { t } from "./providers-BHR6-XZ7.js";
3
- import { a as n, d as r, f as i, g as a, h as o, i as s, l as c, m as l, o as u, p as d, r as f, s as p, t as m, u as h } from "./generate-CZGHByV3.js";
4
- import { n as g } from "./shared-Cc_ns5-y.js";
2
+ import { t } from "./providers-CL9kQ4hp.js";
3
+ import { a as n, d as r, f as i, g as a, h as o, i as s, l as c, m as l, o as u, p as d, r as f, s as p, t as m, u as h } from "./generate-D3mSFPdT.js";
4
+ import { n as g } from "./shared-BPlAVf-T.js";
5
5
  //#region src/patterns/disable/ai/generate.ts
6
6
  var _ = /* #__PURE__ */ Object.assign({
7
7
  "../../enable/ai/creates/src/routes/(public)/ai/+page.svelte": a,
@@ -55,4 +55,4 @@ async function T(e) {
55
55
  //#endregion
56
56
  export { T as i, w as n, b as r, C as t };
57
57
 
58
- //# sourceMappingURL=generate-CFqpRi9D.js.map
58
+ //# sourceMappingURL=generate-Bm_jOMtF.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate-CFqpRi9D.js","names":["__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__1_0_","__import_glob__1_1_","__import_glob__2_0_","__import_glob__2_1_","__import_glob__2_2_","appRelativePath","PROVIDER_PACKAGES","ai_default","server_test_default$1","_page_default","_server_default","PROVIDERS","ai_default$2","server_test_default","demoDir","_server_default$1","PACKAGES","envEditsFor","DEMO_DIR","ai_default$1","toDeleteEntry","createsRaw","createsAppModeRaw","providersRaw","demoDirs","dirs","options","atDemoDir","path","dir","aiPaths","paths","allProviderPaths","raw","prefix","key","allEnvEdits","provider","allEnvNames","variable","generate"],"sources":["../../src/patterns/disable/ai/generate.ts"],"sourcesContent":["import type { Options, Result } from \"../../../core/types\";\nimport type { EnvEdit } from \"../../../runtime/env\";\nimport { allProviderPaths } from \"../../../core/providers\";\nimport { appRelativePath } from \"../../../core/util\";\nimport { toDeleteEntry } from \"../../destroy/shared\";\nimport {\n DEMO_DIR,\n demoDir,\n envEditsFor,\n PACKAGES,\n PROVIDER_PACKAGES,\n PROVIDERS,\n} from \"../../enable/ai/generate\";\n\nconst createsRaw = import.meta.glob<string>(\"../../enable/ai/creates/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nconst createsAppModeRaw = import.meta.glob<string>(\n \"../../enable/ai/creates-app-mode/**\",\n { query: \"?raw\", import: \"default\", eager: true },\n);\n\nconst providersRaw = import.meta.glob<string>(\"../../enable/ai/providers/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\ntype DemoOptions = Pick<Options, \"features\" | \"routeGroups\">;\n\n/**\n * Where enable-ai may have put the demo page in this project: the group it\n * picks with auth on and with it off. Auth enabled after AI leaves the page\n * in the public group, so both are candidates.\n */\nexport function demoDirs(options: DemoOptions): string[] {\n const dirs = [false, true].map((auth) =>\n demoDir({ ...options, features: { ...options.features, auth } }),\n );\n return [...new Set(dirs)];\n}\n\n/** A path enable-ai writes, with the stored demo directory moved to `dir`. */\nfunction atDemoDir(path: string, dir: string): string {\n return path.startsWith(DEMO_DIR)\n ? `${dir}/${path.slice(DEMO_DIR.length)}`\n : path;\n}\n\n/**\n * Every path enable-ai writes for this project: the model module, the\n * endpoint and its test, and the demo page in its current default group.\n * `generate.runtime.ts` adds the page in the other group when it exists.\n */\nexport function aiPaths(options: DemoOptions): string[] {\n const dir = demoDir(options);\n const paths = new Set<string>(allProviderPaths(providersRaw));\n for (const [raw, prefix] of [\n [createsRaw, \"../../enable/ai/creates/\"],\n [createsAppModeRaw, \"../../enable/ai/creates-app-mode/\"],\n ] as const) {\n for (const key of Object.keys(raw)) {\n paths.add(atDemoDir(appRelativePath(key, prefix), dir));\n }\n }\n return [...paths].sort();\n}\n\n/**\n * The `.env` lines every provider writes. Which provider was chosen is not\n * recorded, so all are removed; keys that are not there are skipped.\n */\nexport function allEnvEdits(): EnvEdit[] {\n return PROVIDERS.flatMap((provider) => envEditsFor(provider));\n}\n\n/** Every provider's env var names, as `src/env.ts` declares them. */\nexport function allEnvNames(): string[] {\n return PROVIDERS.flatMap((provider) =>\n (provider.env ?? []).map((variable) => variable.key),\n );\n}\n\nexport async function generate(options: Options) {\n return {\n creates: [],\n modifies: [],\n // Missing ones are skipped, and emptied directories (api/chat, ai) go too.\n deletes: aiPaths(options).map(toDeleteEntry),\n components: [],\n packages: [],\n // zod and the shadcn button/textarea stay: other code uses them.\n uninstalls: [...PACKAGES, ...Object.values(PROVIDER_PACKAGES).flat()],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;AAcA,IAAMwB,IAAa,uBAAA,OAAA;CAAA,+DAAAxB;CAAA,0DAAAC;CAAA,8DAAAC;AAIlB,CAAA,GAEKuB,IAAoB,uBAAA,OAAA;CAAA,mEAAAtB;CAAA,uEAAAC;AAG1B,CAAA,GAEMsB,IAAe,uBAAA,OAAA;CAAA,4DAAArB;CAAA,0DAAAC;CAAA,yDAAAC;AAIpB,CAAA;AASD,SAAgBoB,EAAS,GAAgC;CACvD,IAAMC,IAAO,CAAC,IAAO,EAAI,CAAC,CAAC,KAAK,MAC9BX,EAAQ;EAAE,GAAGY;EAAS,UAAU;GAAE,GAAGA,EAAQ;GAAU;EAAK;CAAE,CAAC,CACjE;CACA,OAAO,CAAC,GAAG,IAAI,IAAID,CAAI,CAAC;AAC1B;AAGA,SAASE,EAAU,GAAc,GAAqB;CACpD,OAAOC,EAAK,WAAA,yBAAmB,IAC3B,GAAGC,EAAI,GAAGD,EAAK,MAAMV,EAAS,MAAM,MACpCU;AACN;AAOA,SAAgBE,EAAQ,GAAgC;CACtD,IAAMD,IAAMf,EAAQY,CAAO,GACrBK,IAAQ,IAAI,IAAYC,EAAiBT,CAAY,CAAC;CAC5D,KAAK,IAAM,CAACU,GAAKC,MAAW,CAC1B,CAACb,GAAY,0BAA0B,GACvC,CAACC,GAAmB,mCAAmC,CACzD,GACE,KAAK,IAAMa,KAAO,OAAO,KAAKF,CAAG,GAC/B,EAAM,IAAIN,EAAUtB,EAAgB8B,GAAKD,CAAM,GAAGL,CAAG,CAAC;CAG1D,OAAO,CAAC,GAAGE,CAAK,CAAC,CAAC,KAAK;AACzB;AAMA,SAAgBK,IAAyB;CACvC,OAAOzB,EAAU,SAAS,MAAaM,EAAYoB,CAAQ,CAAC;AAC9D;AAGA,SAAgBC,IAAwB;CACtC,OAAO3B,EAAU,SAAS,OACvB0B,EAAS,OAAO,CAAC,EAAA,CAAG,KAAK,MAAaE,EAAS,GAAG,CACrD;AACF;AAEA,eAAsBC,EAAS,GAAkB;CAC/C,OAAO;EACL,SAAS,CAAC;EACV,UAAU,CAAC;EAEX,SAASV,EAAQJ,CAAO,CAAC,CAAC,IAAIN,CAAa;EAC3C,YAAY,CAAC;EACb,UAAU,CAAC;EAEX,YAAY,CAAC,GAAGJ,GAAU,GAAG,OAAO,OAAOV,CAAiB,CAAC,CAAC,KAAK,CAAC;EACpE,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate-Bm_jOMtF.js","names":["__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__1_0_","__import_glob__1_1_","__import_glob__2_0_","__import_glob__2_1_","__import_glob__2_2_","appRelativePath","PROVIDER_PACKAGES","ai_default","server_test_default$1","_page_default","_server_default","PROVIDERS","ai_default$2","server_test_default","demoDir","_server_default$1","PACKAGES","envEditsFor","DEMO_DIR","ai_default$1","toDeleteEntry","createsRaw","createsAppModeRaw","providersRaw","demoDirs","dirs","options","atDemoDir","path","dir","aiPaths","paths","allProviderPaths","raw","prefix","key","allEnvEdits","provider","allEnvNames","variable","generate"],"sources":["../../src/patterns/disable/ai/generate.ts"],"sourcesContent":["import type { Options, Result } from \"../../../core/types\";\nimport type { EnvEdit } from \"../../../runtime/env\";\nimport { allProviderPaths } from \"../../../core/providers\";\nimport { appRelativePath } from \"../../../core/util\";\nimport { toDeleteEntry } from \"../../destroy/shared\";\nimport {\n DEMO_DIR,\n demoDir,\n envEditsFor,\n PACKAGES,\n PROVIDER_PACKAGES,\n PROVIDERS,\n} from \"../../enable/ai/generate\";\n\nconst createsRaw = import.meta.glob<string>(\"../../enable/ai/creates/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\nconst createsAppModeRaw = import.meta.glob<string>(\n \"../../enable/ai/creates-app-mode/**\",\n { query: \"?raw\", import: \"default\", eager: true },\n);\n\nconst providersRaw = import.meta.glob<string>(\"../../enable/ai/providers/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\ntype DemoOptions = Pick<Options, \"features\" | \"routeGroups\">;\n\n/**\n * Where enable-ai may have put the demo page in this project: the group it\n * picks with auth on and with it off. Auth enabled after AI leaves the page\n * in the public group, so both are candidates.\n */\nexport function demoDirs(options: DemoOptions): string[] {\n const dirs = [false, true].map((auth) =>\n demoDir({ ...options, features: { ...options.features, auth } }),\n );\n return [...new Set(dirs)];\n}\n\n/** A path enable-ai writes, with the stored demo directory moved to `dir`. */\nfunction atDemoDir(path: string, dir: string): string {\n return path.startsWith(DEMO_DIR)\n ? `${dir}/${path.slice(DEMO_DIR.length)}`\n : path;\n}\n\n/**\n * Every path enable-ai writes for this project: the model module, the\n * endpoint and its test, and the demo page in its current default group.\n * `generate.runtime.ts` adds the page in the other group when it exists.\n */\nexport function aiPaths(options: DemoOptions): string[] {\n const dir = demoDir(options);\n const paths = new Set<string>(allProviderPaths(providersRaw));\n for (const [raw, prefix] of [\n [createsRaw, \"../../enable/ai/creates/\"],\n [createsAppModeRaw, \"../../enable/ai/creates-app-mode/\"],\n ] as const) {\n for (const key of Object.keys(raw)) {\n paths.add(atDemoDir(appRelativePath(key, prefix), dir));\n }\n }\n return [...paths].sort();\n}\n\n/**\n * The `.env` lines every provider writes. Which provider was chosen is not\n * recorded, so all are removed; keys that are not there are skipped.\n */\nexport function allEnvEdits(): EnvEdit[] {\n return PROVIDERS.flatMap((provider) => envEditsFor(provider));\n}\n\n/** Every provider's env var names, as `src/env.ts` declares them. */\nexport function allEnvNames(): string[] {\n return PROVIDERS.flatMap((provider) =>\n (provider.env ?? []).map((variable) => variable.key),\n );\n}\n\nexport async function generate(options: Options) {\n return {\n creates: [],\n modifies: [],\n // Missing ones are skipped, and emptied directories (api/chat, ai) go too.\n deletes: aiPaths(options).map(toDeleteEntry),\n components: [],\n packages: [],\n // zod and the shadcn button/textarea stay: other code uses them.\n uninstalls: [...PACKAGES, ...Object.values(PROVIDER_PACKAGES).flat()],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;;AAcA,IAAMwB,IAAa,uBAAA,OAAA;CAAA,+DAAAxB;CAAA,0DAAAC;CAAA,8DAAAC;AAIlB,CAAA,GAEKuB,IAAoB,uBAAA,OAAA;CAAA,mEAAAtB;CAAA,uEAAAC;AAG1B,CAAA,GAEMsB,IAAe,uBAAA,OAAA;CAAA,4DAAArB;CAAA,0DAAAC;CAAA,yDAAAC;AAIpB,CAAA;AASD,SAAgBoB,EAAS,GAAgC;CACvD,IAAMC,IAAO,CAAC,IAAO,EAAI,CAAC,CAAC,KAAK,MAC9BX,EAAQ;EAAE,GAAGY;EAAS,UAAU;GAAE,GAAGA,EAAQ;GAAU;EAAK;CAAE,CAAC,CACjE;CACA,OAAO,CAAC,GAAG,IAAI,IAAID,CAAI,CAAC;AAC1B;AAGA,SAASE,EAAU,GAAc,GAAqB;CACpD,OAAOC,EAAK,WAAA,yBAAmB,IAC3B,GAAGC,EAAI,GAAGD,EAAK,MAAMV,EAAS,MAAM,MACpCU;AACN;AAOA,SAAgBE,EAAQ,GAAgC;CACtD,IAAMD,IAAMf,EAAQY,CAAO,GACrBK,IAAQ,IAAI,IAAYC,EAAiBT,CAAY,CAAC;CAC5D,KAAK,IAAM,CAACU,GAAKC,MAAW,CAC1B,CAACb,GAAY,0BAA0B,GACvC,CAACC,GAAmB,mCAAmC,CACzD,GACE,KAAK,IAAMa,KAAO,OAAO,KAAKF,CAAG,GAC/B,EAAM,IAAIN,EAAUtB,EAAgB8B,GAAKD,CAAM,GAAGL,CAAG,CAAC;CAG1D,OAAO,CAAC,GAAGE,CAAK,CAAC,CAAC,KAAK;AACzB;AAMA,SAAgBK,IAAyB;CACvC,OAAOzB,EAAU,SAAS,MAAaM,EAAYoB,CAAQ,CAAC;AAC9D;AAGA,SAAgBC,IAAwB;CACtC,OAAO3B,EAAU,SAAS,OACvB0B,EAAS,OAAO,CAAC,EAAA,CAAG,KAAK,MAAaE,EAAS,GAAG,CACrD;AACF;AAEA,eAAsBC,EAAS,GAAkB;CAC/C,OAAO;EACL,SAAS,CAAC;EACV,UAAU,CAAC;EAEX,SAASV,EAAQJ,CAAO,CAAC,CAAC,IAAIN,CAAa;EAC3C,YAAY,CAAC;EACb,UAAU,CAAC;EAEX,YAAY,CAAC,GAAGJ,GAAU,GAAG,OAAO,OAAOV,CAAiB,CAAC,CAAC,KAAK,CAAC;EACpE,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
@@ -1,6 +1,6 @@
1
- import { t as e } from "./providers-BHR6-XZ7.js";
2
- import { a as t, c as n, n as r, o as i, r as a, s as o } from "./generate-DetW_gbr.js";
3
- import { n as s } from "./shared-Cc_ns5-y.js";
1
+ import { t as e } from "./providers-CL9kQ4hp.js";
2
+ import { a as t, c as n, n as r, o as i, r as a, s as o } from "./generate-DyV5R8NP.js";
3
+ import { n as s } from "./shared-BPlAVf-T.js";
4
4
  //#region src/patterns/disable/analytics/generate.ts
5
5
  var c = /* #__PURE__ */ Object.assign({
6
6
  "../../enable/analytics/providers/google/src/lib/components/analytics/analytics.svelte": n,
@@ -30,4 +30,4 @@ async function d(t) {
30
30
  //#endregion
31
31
  export { u as n, d as r, l as t };
32
32
 
33
- //# sourceMappingURL=generate-Bg0E3eWm.js.map
33
+ //# sourceMappingURL=generate-CXoQPz7n.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"generate-Bg0E3eWm.js","names":["__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__0_3_","allProviderPaths","analytics_default$2","analytics_default","PROVIDERS","analytics_default$1","envEditsFor","gtag_default","toDeleteEntry","providersRaw","allEnvEdits","provider","allEnvNames","variable","generate"],"sources":["../../src/patterns/disable/analytics/generate.ts"],"sourcesContent":["import type { Options, Result } from \"../../../core/types\";\nimport type { EnvEdit } from \"../../../runtime/env\";\nimport { allProviderPaths } from \"../../../core/providers\";\nimport { toDeleteEntry } from \"../../destroy/shared\";\nimport { envEditsFor, PROVIDERS } from \"../../enable/analytics/generate\";\n\nconst providersRaw = import.meta.glob<string>(\n \"../../enable/analytics/providers/**\",\n { query: \"?raw\", import: \"default\", eager: true },\n);\n\n/**\n * The `.env` lines every provider writes. The project only has one set, but\n * which one is not recorded anywhere, so all are removed; keys that are not\n * there are skipped.\n */\nexport function allEnvEdits(): EnvEdit[] {\n return PROVIDERS.flatMap((provider) => envEditsFor(provider));\n}\n\n/** Every provider's env var names, as `src/env.ts` declares them. */\nexport function allEnvNames(): string[] {\n return PROVIDERS.flatMap((provider) =>\n (provider.env ?? []).map((variable) => variable.key),\n );\n}\n\nexport async function generate(_options: Options) {\n return {\n creates: [],\n modifies: [],\n // Every provider's files: missing ones are skipped, and the emptied\n // components/analytics directory goes with them.\n deletes: allProviderPaths(providersRaw).map(toDeleteEntry),\n components: [],\n packages: [],\n // PostHog's SDK; the other providers load a script and install nothing.\n uninstalls: [\"posthog-js\"],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;AAMA,IAAMY,IAAe,uBAAA,OAAA;CAAA,yFAAAZ;CAAA,gFAAAC;CAAA,4FAAAC;CAAA,0FAAAC;AAGrB,CAAA;AAOA,SAAgBU,IAAyB;CACvC,OAAON,EAAU,SAAS,MAAaE,EAAYK,CAAQ,CAAC;AAC9D;AAGA,SAAgBC,IAAwB;CACtC,OAAOR,EAAU,SAAS,OACvBO,EAAS,OAAO,CAAC,EAAA,CAAG,KAAK,MAAaE,EAAS,GAAG,CACrD;AACF;AAEA,eAAsBC,EAAS,GAAmB;CAChD,OAAO;EACL,SAAS,CAAC;EACV,UAAU,CAAC;EAGX,SAASb,EAAiBQ,CAAY,CAAC,CAAC,IAAID,CAAa;EACzD,YAAY,CAAC;EACb,UAAU,CAAC;EAEX,YAAY,CAAC,YAAY;EACzB,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"generate-CXoQPz7n.js","names":["__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__0_3_","allProviderPaths","analytics_default$2","analytics_default","PROVIDERS","analytics_default$1","envEditsFor","gtag_default","toDeleteEntry","providersRaw","allEnvEdits","provider","allEnvNames","variable","generate"],"sources":["../../src/patterns/disable/analytics/generate.ts"],"sourcesContent":["import type { Options, Result } from \"../../../core/types\";\nimport type { EnvEdit } from \"../../../runtime/env\";\nimport { allProviderPaths } from \"../../../core/providers\";\nimport { toDeleteEntry } from \"../../destroy/shared\";\nimport { envEditsFor, PROVIDERS } from \"../../enable/analytics/generate\";\n\nconst providersRaw = import.meta.glob<string>(\n \"../../enable/analytics/providers/**\",\n { query: \"?raw\", import: \"default\", eager: true },\n);\n\n/**\n * The `.env` lines every provider writes. The project only has one set, but\n * which one is not recorded anywhere, so all are removed; keys that are not\n * there are skipped.\n */\nexport function allEnvEdits(): EnvEdit[] {\n return PROVIDERS.flatMap((provider) => envEditsFor(provider));\n}\n\n/** Every provider's env var names, as `src/env.ts` declares them. */\nexport function allEnvNames(): string[] {\n return PROVIDERS.flatMap((provider) =>\n (provider.env ?? []).map((variable) => variable.key),\n );\n}\n\nexport async function generate(_options: Options) {\n return {\n creates: [],\n modifies: [],\n // Every provider's files: missing ones are skipped, and the emptied\n // components/analytics directory goes with them.\n deletes: allProviderPaths(providersRaw).map(toDeleteEntry),\n components: [],\n packages: [],\n // PostHog's SDK; the other providers load a script and install nothing.\n uninstalls: [\"posthog-js\"],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n } satisfies Result;\n}\n"],"mappings":";;;;AAMA,IAAMY,IAAe,uBAAA,OAAA;CAAA,yFAAAZ;CAAA,gFAAAC;CAAA,4FAAAC;CAAA,0FAAAC;AAGrB,CAAA;AAOA,SAAgBU,IAAyB;CACvC,OAAON,EAAU,SAAS,MAAaE,EAAYK,CAAQ,CAAC;AAC9D;AAGA,SAAgBC,IAAwB;CACtC,OAAOR,EAAU,SAAS,OACvBO,EAAS,OAAO,CAAC,EAAA,CAAG,KAAK,MAAaE,EAAS,GAAG,CACrD;AACF;AAEA,eAAsBC,EAAS,GAAmB;CAChD,OAAO;EACL,SAAS,CAAC;EACV,UAAU,CAAC;EAGX,SAASb,EAAiBQ,CAAY,CAAC,CAAC,IAAID,CAAa;EACzD,YAAY,CAAC;EACb,UAAU,CAAC;EAEX,YAAY,CAAC,YAAY;EACzB,aAAa,CAAC;EACd,mBAAmB,CAAC;EACpB,iBAAiB,CAAC;CACpB;AACF"}