@stripe/extensibility-dev-tools 0.23.5

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 (253) hide show
  1. package/LICENSE.md +19 -0
  2. package/dist/bin/build-custom-object-definitions.cjs +2111 -0
  3. package/dist/bin/build-custom-object-definitions.d.ts +11 -0
  4. package/dist/bin/build-custom-object-definitions.d.ts.map +1 -0
  5. package/dist/bin/build-custom-object-definitions.js +2088 -0
  6. package/dist/bin/create-upload-image.cjs +2136 -0
  7. package/dist/bin/create-upload-image.d.ts +17 -0
  8. package/dist/bin/create-upload-image.d.ts.map +1 -0
  9. package/dist/bin/create-upload-image.js +2113 -0
  10. package/dist/bin/dev-tools-rpc.cjs +3874 -0
  11. package/dist/bin/dev-tools-rpc.d.ts +3 -0
  12. package/dist/bin/dev-tools-rpc.d.ts.map +1 -0
  13. package/dist/bin/dev-tools-rpc.js +3864 -0
  14. package/dist/bin/gen-schemas.cjs +20739 -0
  15. package/dist/bin/gen-schemas.d.ts +8 -0
  16. package/dist/bin/gen-schemas.d.ts.map +1 -0
  17. package/dist/bin/gen-schemas.js +20715 -0
  18. package/dist/bin/gen-workspace.cjs +3847 -0
  19. package/dist/bin/gen-workspace.d.ts +8 -0
  20. package/dist/bin/gen-workspace.d.ts.map +1 -0
  21. package/dist/bin/gen-workspace.js +3841 -0
  22. package/dist/bin/manifest.cjs +686 -0
  23. package/dist/bin/manifest.d.ts +10 -0
  24. package/dist/bin/manifest.d.ts.map +1 -0
  25. package/dist/bin/manifest.js +663 -0
  26. package/dist/bin/rpc/dispatch.d.ts +10 -0
  27. package/dist/bin/rpc/dispatch.d.ts.map +1 -0
  28. package/dist/bin/rpc/handlers.d.ts +4 -0
  29. package/dist/bin/rpc/handlers.d.ts.map +1 -0
  30. package/dist/bin/rpc/types.d.ts +29 -0
  31. package/dist/bin/rpc/types.d.ts.map +1 -0
  32. package/dist/bin/template-info.cjs +1511 -0
  33. package/dist/bin/template-info.d.ts +9 -0
  34. package/dist/bin/template-info.d.ts.map +1 -0
  35. package/dist/bin/template-info.js +1488 -0
  36. package/dist/custom-objects/build-definitions.d.ts +98 -0
  37. package/dist/custom-objects/build-definitions.d.ts.map +1 -0
  38. package/dist/custom-objects/generated/proto/custom_objects/pub/api/app_api/object_definitions_app_service.pb.d.ts +191 -0
  39. package/dist/custom-objects/generated/proto/custom_objects/pub/api/app_api/object_definitions_app_service.pb.d.ts.map +1 -0
  40. package/dist/custom-objects/generated/proto/custom_objects/pub/api/common/schema.pb.d.ts +131 -0
  41. package/dist/custom-objects/generated/proto/custom_objects/pub/api/common/schema.pb.d.ts.map +1 -0
  42. package/dist/custom-objects/generated/proto/google/protobuf/descriptor.pb.d.ts +1482 -0
  43. package/dist/custom-objects/generated/proto/google/protobuf/descriptor.pb.d.ts.map +1 -0
  44. package/dist/custom-objects/generated/proto/google/protobuf/timestamp.pb.d.ts +167 -0
  45. package/dist/custom-objects/generated/proto/google/protobuf/timestamp.pb.d.ts.map +1 -0
  46. package/dist/custom-objects/generated/proto/proto/annotations.pb.d.ts +64 -0
  47. package/dist/custom-objects/generated/proto/proto/annotations.pb.d.ts.map +1 -0
  48. package/dist/custom-objects/generated/proto/proto/extensions.pb.d.ts +657 -0
  49. package/dist/custom-objects/generated/proto/proto/extensions.pb.d.ts.map +1 -0
  50. package/dist/custom-objects/generated/proto/vendor/metadata/pub/api/api_metadata.pb.d.ts +105 -0
  51. package/dist/custom-objects/generated/proto/vendor/metadata/pub/api/api_metadata.pb.d.ts.map +1 -0
  52. package/dist/custom-objects/generated/proto/vendor/net/idempotency/idempotency_model.pb.d.ts +79 -0
  53. package/dist/custom-objects/generated/proto/vendor/net/idempotency/idempotency_model.pb.d.ts.map +1 -0
  54. package/dist/custom-objects/generated/proto/vendor/publicapi/api_group_enum.pb.d.ts +129 -0
  55. package/dist/custom-objects/generated/proto/vendor/publicapi/api_group_enum.pb.d.ts.map +1 -0
  56. package/dist/custom-objects/generated/proto/vendor/publicapi/api_visibility.pb.d.ts +76 -0
  57. package/dist/custom-objects/generated/proto/vendor/publicapi/api_visibility.pb.d.ts.map +1 -0
  58. package/dist/custom-objects/generated/proto/vendor/publicapi/customize_dispatch_middleware_enum.pb.d.ts +78 -0
  59. package/dist/custom-objects/generated/proto/vendor/publicapi/customize_dispatch_middleware_enum.pb.d.ts.map +1 -0
  60. package/dist/custom-objects/generated/proto/vendor/publicapi/docs_namespace_group_enum.pb.d.ts +146 -0
  61. package/dist/custom-objects/generated/proto/vendor/publicapi/docs_namespace_group_enum.pb.d.ts.map +1 -0
  62. package/dist/custom-objects/generated/proto/vendor/publicapi/documented_enum.pb.d.ts +76 -0
  63. package/dist/custom-objects/generated/proto/vendor/publicapi/documented_enum.pb.d.ts.map +1 -0
  64. package/dist/custom-objects/generated/proto/vendor/publicapi/event_scope_enum.pb.d.ts +92 -0
  65. package/dist/custom-objects/generated/proto/vendor/publicapi/event_scope_enum.pb.d.ts.map +1 -0
  66. package/dist/custom-objects/generated/proto/vendor/publicapi/extension_interface.pb.d.ts +124 -0
  67. package/dist/custom-objects/generated/proto/vendor/publicapi/extension_interface.pb.d.ts.map +1 -0
  68. package/dist/custom-objects/generated/proto/vendor/publicapi/feature_enum.pb.d.ts +1070 -0
  69. package/dist/custom-objects/generated/proto/vendor/publicapi/feature_enum.pb.d.ts.map +1 -0
  70. package/dist/custom-objects/generated/proto/vendor/publicapi/field_validation_rules.pb.d.ts +279 -0
  71. package/dist/custom-objects/generated/proto/vendor/publicapi/field_validation_rules.pb.d.ts.map +1 -0
  72. package/dist/custom-objects/generated/proto/vendor/publicapi/flavor_enum.pb.d.ts +78 -0
  73. package/dist/custom-objects/generated/proto/vendor/publicapi/flavor_enum.pb.d.ts.map +1 -0
  74. package/dist/custom-objects/generated/proto/vendor/publicapi/http_error_status.pb.d.ts +102 -0
  75. package/dist/custom-objects/generated/proto/vendor/publicapi/http_error_status.pb.d.ts.map +1 -0
  76. package/dist/custom-objects/generated/proto/vendor/publicapi/method_kind_enum.pb.d.ts +86 -0
  77. package/dist/custom-objects/generated/proto/vendor/publicapi/method_kind_enum.pb.d.ts.map +1 -0
  78. package/dist/custom-objects/generated/proto/vendor/publicapi/method_priority.pb.d.ts +80 -0
  79. package/dist/custom-objects/generated/proto/vendor/publicapi/method_priority.pb.d.ts.map +1 -0
  80. package/dist/custom-objects/generated/proto/vendor/publicapi/permission_check_enum.pb.d.ts +74 -0
  81. package/dist/custom-objects/generated/proto/vendor/publicapi/permission_check_enum.pb.d.ts.map +1 -0
  82. package/dist/custom-objects/generated/proto/vendor/publicapi/redaction_enum.pb.d.ts +76 -0
  83. package/dist/custom-objects/generated/proto/vendor/publicapi/redaction_enum.pb.d.ts.map +1 -0
  84. package/dist/custom-objects/generated/proto/vendor/publicapi/region_routers.pb.d.ts +103 -0
  85. package/dist/custom-objects/generated/proto/vendor/publicapi/region_routers.pb.d.ts.map +1 -0
  86. package/dist/custom-objects/generated/proto/vendor/publicapi/rollout_configs.pb.d.ts +153 -0
  87. package/dist/custom-objects/generated/proto/vendor/publicapi/rollout_configs.pb.d.ts.map +1 -0
  88. package/dist/custom-objects/generated/proto/vendor/publicapi/v2ext.pb.d.ts +1111 -0
  89. package/dist/custom-objects/generated/proto/vendor/publicapi/v2ext.pb.d.ts.map +1 -0
  90. package/dist/custom-objects/generated/proto/vendor/vext/annotations.pb.d.ts +602 -0
  91. package/dist/custom-objects/generated/proto/vendor/vext/annotations.pb.d.ts.map +1 -0
  92. package/dist/custom-objects/generated/proto/vendor/vext/extensions.pb.d.ts +144 -0
  93. package/dist/custom-objects/generated/proto/vendor/vext/extensions.pb.d.ts.map +1 -0
  94. package/dist/custom-objects/generated/proto/vendor/vext/privacy_unified_annotations.pb.d.ts +851 -0
  95. package/dist/custom-objects/generated/proto/vendor/vext/privacy_unified_annotations.pb.d.ts.map +1 -0
  96. package/dist/custom-objects/generated/proto/vendor/vext/xml_annotations.pb.d.ts +125 -0
  97. package/dist/custom-objects/generated/proto/vendor/vext/xml_annotations.pb.d.ts.map +1 -0
  98. package/dist/custom-objects/to-proto-json.d.ts +17 -0
  99. package/dist/custom-objects/to-proto-json.d.ts.map +1 -0
  100. package/dist/dependencies/index.cjs +601 -0
  101. package/dist/dependencies/index.d.ts +320 -0
  102. package/dist/dependencies/index.d.ts.map +1 -0
  103. package/dist/dependencies/index.js +560 -0
  104. package/dist/extensibility-dev-tools-alpha.d.ts +199 -0
  105. package/dist/extensibility-dev-tools-beta.d.ts +199 -0
  106. package/dist/extensibility-dev-tools-dependencies-alpha.d.ts +51 -0
  107. package/dist/extensibility-dev-tools-dependencies-beta.d.ts +51 -0
  108. package/dist/extensibility-dev-tools-dependencies-internal.d.ts +372 -0
  109. package/dist/extensibility-dev-tools-dependencies-public.d.ts +51 -0
  110. package/dist/extensibility-dev-tools-internal.d.ts +1722 -0
  111. package/dist/extensibility-dev-tools-jsonschema-tools-alpha.d.ts +57 -0
  112. package/dist/extensibility-dev-tools-jsonschema-tools-beta.d.ts +57 -0
  113. package/dist/extensibility-dev-tools-jsonschema-tools-internal.d.ts +123 -0
  114. package/dist/extensibility-dev-tools-jsonschema-tools-public.d.ts +57 -0
  115. package/dist/extensibility-dev-tools-manifest-alpha.d.ts +31 -0
  116. package/dist/extensibility-dev-tools-manifest-beta.d.ts +31 -0
  117. package/dist/extensibility-dev-tools-manifest-internal.d.ts +461 -0
  118. package/dist/extensibility-dev-tools-manifest-public.d.ts +31 -0
  119. package/dist/extensibility-dev-tools-public.d.ts +199 -0
  120. package/dist/extensibility-dev-tools-schemas-alpha.d.ts +9 -0
  121. package/dist/extensibility-dev-tools-schemas-beta.d.ts +9 -0
  122. package/dist/extensibility-dev-tools-schemas-internal.d.ts +41 -0
  123. package/dist/extensibility-dev-tools-schemas-public.d.ts +9 -0
  124. package/dist/extensibility-dev-tools-templates-alpha.d.ts +67 -0
  125. package/dist/extensibility-dev-tools-templates-beta.d.ts +67 -0
  126. package/dist/extensibility-dev-tools-templates-internal.d.ts +554 -0
  127. package/dist/extensibility-dev-tools-templates-public.d.ts +67 -0
  128. package/dist/extensibility-dev-tools-workspace-alpha.d.ts +51 -0
  129. package/dist/extensibility-dev-tools-workspace-beta.d.ts +51 -0
  130. package/dist/extensibility-dev-tools-workspace-internal.d.ts +410 -0
  131. package/dist/extensibility-dev-tools-workspace-public.d.ts +51 -0
  132. package/dist/index.cjs +3810 -0
  133. package/dist/index.d.ts +18 -0
  134. package/dist/index.d.ts.map +1 -0
  135. package/dist/index.js +3758 -0
  136. package/dist/jsonschema-tools.cjs +20451 -0
  137. package/dist/jsonschema-tools.d.ts +98 -0
  138. package/dist/jsonschema-tools.d.ts.map +1 -0
  139. package/dist/jsonschema-tools.js +20404 -0
  140. package/dist/manifest/index.cjs +610 -0
  141. package/dist/manifest/index.d.ts +8 -0
  142. package/dist/manifest/index.d.ts.map +1 -0
  143. package/dist/manifest/index.js +571 -0
  144. package/dist/manifest/manifest-v1.d.ts +102 -0
  145. package/dist/manifest/manifest-v1.d.ts.map +1 -0
  146. package/dist/manifest/manifest-v2.d.ts +253 -0
  147. package/dist/manifest/manifest-v2.d.ts.map +1 -0
  148. package/dist/manifest/stripe-app-manifest.d.ts +114 -0
  149. package/dist/manifest/stripe-app-manifest.d.ts.map +1 -0
  150. package/dist/schemas/index.cjs +20692 -0
  151. package/dist/schemas/index.d.ts +37 -0
  152. package/dist/schemas/index.d.ts.map +1 -0
  153. package/dist/schemas/index.js +20656 -0
  154. package/dist/templates/diff-viewer/diff-generator.d.ts +22 -0
  155. package/dist/templates/diff-viewer/diff-generator.d.ts.map +1 -0
  156. package/dist/templates/diff-viewer/diff-prompt.d.ts +13 -0
  157. package/dist/templates/diff-viewer/diff-prompt.d.ts.map +1 -0
  158. package/dist/templates/diff-viewer/index.d.ts +7 -0
  159. package/dist/templates/diff-viewer/index.d.ts.map +1 -0
  160. package/dist/templates/diff-viewer/terminal-renderer.d.ts +29 -0
  161. package/dist/templates/diff-viewer/terminal-renderer.d.ts.map +1 -0
  162. package/dist/templates/diff-viewer/types.d.ts +58 -0
  163. package/dist/templates/diff-viewer/types.d.ts.map +1 -0
  164. package/dist/templates/extensions/base.d.ts +23 -0
  165. package/dist/templates/extensions/base.d.ts.map +1 -0
  166. package/dist/templates/extensions/billing.bill.discount_calculation.d.ts +6 -0
  167. package/dist/templates/extensions/billing.bill.discount_calculation.d.ts.map +1 -0
  168. package/dist/templates/extensions/billing.customer_balance_application.d.ts +6 -0
  169. package/dist/templates/extensions/billing.customer_balance_application.d.ts.map +1 -0
  170. package/dist/templates/extensions/billing.invoice_collection_setting.d.ts +6 -0
  171. package/dist/templates/extensions/billing.invoice_collection_setting.d.ts.map +1 -0
  172. package/dist/templates/extensions/billing.prorations.d.ts +6 -0
  173. package/dist/templates/extensions/billing.prorations.d.ts.map +1 -0
  174. package/dist/templates/extensions/billing.recurring_billing_item_handling.d.ts +6 -0
  175. package/dist/templates/extensions/billing.recurring_billing_item_handling.d.ts.map +1 -0
  176. package/dist/templates/extensions/core.workflows.custom_action.d.ts +6 -0
  177. package/dist/templates/extensions/core.workflows.custom_action.d.ts.map +1 -0
  178. package/dist/templates/extensions/extend.objects.custom_objects.d.ts +6 -0
  179. package/dist/templates/extensions/extend.objects.custom_objects.d.ts.map +1 -0
  180. package/dist/templates/extensions/extend.workflows.custom_action.d.ts +6 -0
  181. package/dist/templates/extensions/extend.workflows.custom_action.d.ts.map +1 -0
  182. package/dist/templates/extensions/index.d.ts +13 -0
  183. package/dist/templates/extensions/index.d.ts.map +1 -0
  184. package/dist/templates/extensions/registry.d.ts +10 -0
  185. package/dist/templates/extensions/registry.d.ts.map +1 -0
  186. package/dist/templates/extensions/types.d.ts +104 -0
  187. package/dist/templates/extensions/types.d.ts.map +1 -0
  188. package/dist/templates/file-writer.d.ts +140 -0
  189. package/dist/templates/file-writer.d.ts.map +1 -0
  190. package/dist/templates/fs/_impl.d.ts +29 -0
  191. package/dist/templates/fs/_impl.d.ts.map +1 -0
  192. package/dist/templates/fs/filesystem.d.ts +8 -0
  193. package/dist/templates/fs/filesystem.d.ts.map +1 -0
  194. package/dist/templates/fs/in-memory.d.ts +9 -0
  195. package/dist/templates/fs/in-memory.d.ts.map +1 -0
  196. package/dist/templates/fs/index.d.ts +25 -0
  197. package/dist/templates/fs/index.d.ts.map +1 -0
  198. package/dist/templates/fs-utils.d.ts +17 -0
  199. package/dist/templates/fs-utils.d.ts.map +1 -0
  200. package/dist/templates/index.cjs +2248 -0
  201. package/dist/templates/index.d.ts +32 -0
  202. package/dist/templates/index.d.ts.map +1 -0
  203. package/dist/templates/index.js +2203 -0
  204. package/dist/templates/root/index.d.ts +60 -0
  205. package/dist/templates/root/index.d.ts.map +1 -0
  206. package/dist/templates/simple-templates.d.ts +8 -0
  207. package/dist/templates/simple-templates.d.ts.map +1 -0
  208. package/dist/templates/template-manager.d.ts +8 -0
  209. package/dist/templates/template-manager.d.ts.map +1 -0
  210. package/dist/templates/types.d.ts +9 -0
  211. package/dist/templates/types.d.ts.map +1 -0
  212. package/dist/tsconfig.build.tsbuildinfo +1 -0
  213. package/dist/workspace/index.cjs +3756 -0
  214. package/dist/workspace/index.d.ts +336 -0
  215. package/dist/workspace/index.d.ts.map +1 -0
  216. package/dist/workspace/index.js +3731 -0
  217. package/package.json +137 -0
  218. package/templates/extensions/billing.bill.discount_calculation/index.test.ts +15 -0
  219. package/templates/extensions/billing.bill.discount_calculation/index.ts +20 -0
  220. package/templates/extensions/billing.customer_balance_application/index.test.ts +15 -0
  221. package/templates/extensions/billing.customer_balance_application/index.ts +18 -0
  222. package/templates/extensions/billing.invoice_collection_setting/index.test.ts +15 -0
  223. package/templates/extensions/billing.invoice_collection_setting/index.ts +16 -0
  224. package/templates/extensions/billing.prorations/index.test.ts +15 -0
  225. package/templates/extensions/billing.prorations/index.ts +18 -0
  226. package/templates/extensions/billing.recurring_billing_item_handling/index.test.ts +15 -0
  227. package/templates/extensions/billing.recurring_billing_item_handling/index.ts +42 -0
  228. package/templates/extensions/common/.prettierignore +3 -0
  229. package/templates/extensions/common/eslint.config.mts.mustache +95 -0
  230. package/templates/extensions/common/package.json.mustache +26 -0
  231. package/templates/extensions/common/tsconfig.build.json.mustache +15 -0
  232. package/templates/extensions/common/tsconfig.json.mustache +16 -0
  233. package/templates/extensions/core.workflows.custom_action/custom_input.schema.json +6 -0
  234. package/templates/extensions/core.workflows.custom_action/index.test.ts +15 -0
  235. package/templates/extensions/core.workflows.custom_action/index.ts +31 -0
  236. package/templates/extensions/extend.workflows.custom_action/custom_input.schema.json +6 -0
  237. package/templates/extensions/extend.workflows.custom_action/index.test.ts +15 -0
  238. package/templates/extensions/extend.workflows.custom_action/index.ts +31 -0
  239. package/templates/root/.husky/pre-commit +1 -0
  240. package/templates/root/.prettierignore +5 -0
  241. package/templates/root/.prettierrc +7 -0
  242. package/templates/root/_gitignore +28 -0
  243. package/templates/root/custom-objects/package.json +20 -0
  244. package/templates/root/custom-objects/tsconfig.json +9 -0
  245. package/templates/root/eslint.config.mts +95 -0
  246. package/templates/root/package.json.mustache +32 -0
  247. package/templates/root/pnpm-workspace.yaml +7 -0
  248. package/templates/root/stripe-app.yaml.mustache +6 -0
  249. package/templates/root/tools/test.mts +38 -0
  250. package/templates/root/tsconfig.base.json +23 -0
  251. package/templates/root/tsconfig.json +15 -0
  252. package/templates/root/ui/package.json +17 -0
  253. package/templates/root/vitest.config.mts +47 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,3810 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ _CliUx: () => import_extensibility_tool_utils12._CliUx,
34
+ _DependencyManager: () => _DependencyManager,
35
+ _ExtensionTemplateManager: () => _ExtensionTemplateManager,
36
+ _ManifestV1: () => _ManifestV1,
37
+ _ManifestV2: () => _ManifestV2,
38
+ _NpmDependencyHandler: () => _NpmDependencyHandler,
39
+ _SingleTemplateManager: () => import_extensibility_tool_utils3._SingleTemplateManager,
40
+ _StripeAppManifest: () => _StripeAppManifest,
41
+ _StripeCliPluginHandler: () => _StripeCliPluginHandler,
42
+ _TemplateManager: () => import_extensibility_tool_utils._TemplateManager,
43
+ _advancedDiffPrompt: () => _advancedDiffPrompt,
44
+ _createCliContext: () => import_extensibility_tool_utils12._createCliContext,
45
+ _createExtensionEslintConfigFile: () => _createExtensionEslintConfigFile,
46
+ _createSimpleSingleFileTemplate: () => import_extensibility_tool_utils3._createSimpleSingleFileTemplate,
47
+ _createSimpleTemplate: () => import_extensibility_tool_utils3._createSimpleTemplate,
48
+ _defaultServices: () => _defaultServices,
49
+ _detectPackageManager: () => _detectPackageManager,
50
+ _devNpmDep: () => _devNpmDep,
51
+ _fs: () => _fs,
52
+ _npmDep: () => _npmDep,
53
+ _promptOverwrite: () => _promptOverwrite,
54
+ _regenAppProjectWorkspace: () => _regenAppProjectWorkspace,
55
+ _regenWorkspaceOptionsSchema: () => _regenWorkspaceOptionsSchema,
56
+ _resolvePackageMetadata: () => _resolvePackageMetadata,
57
+ _rootTemplateManager: () => _rootTemplateManager,
58
+ _rootWorkspaceTemplate: () => _rootWorkspaceTemplate,
59
+ _stripeCliPluginDep: () => _stripeCliPluginDep,
60
+ _templateManager: () => _templateManager,
61
+ _writeGeneratedFiles: () => _writeGeneratedFiles
62
+ });
63
+ module.exports = __toCommonJS(src_exports);
64
+
65
+ // src/templates/template-manager.ts
66
+ var import_extensibility_tool_utils = require("@stripe/extensibility-tool-utils");
67
+
68
+ // src/templates/fs/in-memory.ts
69
+ var import_extensibility_tool_utils2 = require("@stripe/extensibility-tool-utils");
70
+
71
+ // templates-virtual:./_impl.js
72
+ var TEMPLATE_FS_IMAGE = [
73
+ {
74
+ path: "extensions/billing.bill.discount_calculation/index.test.ts",
75
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
76
+
77
+ import MyDiscountCalculation from './index.js';
78
+
79
+ describe('MyDiscountCalculation', () => {
80
+ let instance: MyDiscountCalculation;
81
+
82
+ beforeEach(() => {
83
+ instance = new MyDiscountCalculation();
84
+ });
85
+
86
+ it('should be constructable', () => {
87
+ expect(instance).toBeInstanceOf(MyDiscountCalculation);
88
+ });
89
+ });
90
+ `
91
+ },
92
+ {
93
+ path: "extensions/billing.bill.discount_calculation/index.ts",
94
+ content: `import type { Billing } from '@stripe/extensibility-sdk/extensions';
95
+ import type { Context } from '@stripe/extensibility-sdk/extensions';
96
+
97
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
98
+ interface MyDiscountCalculationConfig extends Record<string, unknown> {}
99
+
100
+ export default class MyDiscountCalculation implements Billing.Bill
101
+ .DiscountCalculation<MyDiscountCalculationConfig> {
102
+ computeDiscounts(
103
+ request: Billing.Bill.DiscountCalculation.DiscountableItem,
104
+ _config: MyDiscountCalculationConfig,
105
+ _context: Context
106
+ ) {
107
+ // TODO: implement your discount logic here
108
+
109
+ return {
110
+ discount: { amount: request.grossAmount },
111
+ };
112
+ }
113
+ }
114
+ `
115
+ },
116
+ {
117
+ path: "extensions/billing.customer_balance_application/index.test.ts",
118
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
119
+
120
+ import MyCustomerBalanceApplication from './index.js';
121
+
122
+ describe('MyCustomerBalanceApplication', () => {
123
+ let instance: MyCustomerBalanceApplication;
124
+
125
+ beforeEach(() => {
126
+ instance = new MyCustomerBalanceApplication();
127
+ });
128
+
129
+ it('should be constructable', () => {
130
+ expect(instance).toBeInstanceOf(MyCustomerBalanceApplication);
131
+ });
132
+ });
133
+ `
134
+ },
135
+ {
136
+ path: "extensions/billing.customer_balance_application/index.ts",
137
+ content: `import type { Billing, Context } from '@stripe/extensibility-sdk/extensions';
138
+
139
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
140
+ interface MyCustomerBalanceApplicationConfig extends Record<string, unknown> {}
141
+
142
+ export default class MyCustomerBalanceApplication implements Billing.CustomerBalanceApplication<MyCustomerBalanceApplicationConfig> {
143
+ computeAppliedCustomerBalance(
144
+ request: Billing.CustomerBalanceApplication.CustomerBalanceApplicationInput,
145
+ _config: MyCustomerBalanceApplicationConfig,
146
+ _context: Context
147
+ ) {
148
+ // TODO: implement your customer balance logic here
149
+
150
+ return {
151
+ appliedCustomerBalance: request.customerBalance,
152
+ };
153
+ }
154
+ }
155
+ `
156
+ },
157
+ {
158
+ path: "extensions/billing.invoice_collection_setting/index.test.ts",
159
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
160
+
161
+ import MyInvoiceCollectionSetting from './index.js';
162
+
163
+ describe('MyInvoiceCollectionSetting', () => {
164
+ let instance: MyInvoiceCollectionSetting;
165
+
166
+ beforeEach(() => {
167
+ instance = new MyInvoiceCollectionSetting();
168
+ });
169
+
170
+ it('should be constructable', () => {
171
+ expect(instance).toBeInstanceOf(MyInvoiceCollectionSetting);
172
+ });
173
+ });
174
+ `
175
+ },
176
+ {
177
+ path: "extensions/billing.invoice_collection_setting/index.ts",
178
+ content: `import type { Billing, Context } from '@stripe/extensibility-sdk/extensions';
179
+
180
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
181
+ interface MyInvoiceCollectionSettingConfig extends Record<string, unknown> {}
182
+
183
+ export default class MyInvoiceCollectionSetting implements Billing.InvoiceCollectionSetting<MyInvoiceCollectionSettingConfig> {
184
+ collectionOverride(
185
+ _request: Billing.InvoiceCollectionSetting.InvoiceCollectionRequest,
186
+ _config: MyInvoiceCollectionSettingConfig,
187
+ _context: Context
188
+ ) {
189
+ // TODO: implement your collection setting logic here
190
+
191
+ return {};
192
+ }
193
+ }
194
+ `
195
+ },
196
+ {
197
+ path: "extensions/billing.prorations/index.test.ts",
198
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
199
+
200
+ import MyProrations from './index.js';
201
+
202
+ describe('MyProrations', () => {
203
+ let instance: MyProrations;
204
+
205
+ beforeEach(() => {
206
+ instance = new MyProrations();
207
+ });
208
+
209
+ it('should be constructable', () => {
210
+ expect(instance).toBeInstanceOf(MyProrations);
211
+ });
212
+ });
213
+ `
214
+ },
215
+ {
216
+ path: "extensions/billing.prorations/index.ts",
217
+ content: `import type { Billing, Context } from '@stripe/extensibility-sdk/extensions';
218
+
219
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
220
+ interface MyProrationsConfig extends Record<string, unknown> {}
221
+
222
+ export default class MyProrations implements Billing.Prorations<MyProrationsConfig> {
223
+ prorateItems(
224
+ _request: Billing.Prorations.ProrateItemsInput,
225
+ _config: MyProrationsConfig,
226
+ _context: Context
227
+ ) {
228
+ // TODO: implement your proration logic here
229
+
230
+ return {
231
+ items: [],
232
+ };
233
+ }
234
+ }
235
+ `
236
+ },
237
+ {
238
+ path: "extensions/billing.recurring_billing_item_handling/index.test.ts",
239
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
240
+
241
+ import MyRecurringBillingItemHandling from './index.js';
242
+
243
+ describe('MyRecurringBillingItemHandling', () => {
244
+ let instance: MyRecurringBillingItemHandling;
245
+
246
+ beforeEach(() => {
247
+ instance = new MyRecurringBillingItemHandling();
248
+ });
249
+
250
+ it('should be constructable', () => {
251
+ expect(instance).toBeInstanceOf(MyRecurringBillingItemHandling);
252
+ });
253
+ });
254
+ `
255
+ },
256
+ {
257
+ path: "extensions/billing.recurring_billing_item_handling/index.ts",
258
+ content: `import type { Billing, Context } from '@stripe/extensibility-sdk/extensions';
259
+
260
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
261
+ interface MyRecurringBillingItemHandlingConfig extends Record<string, unknown> {}
262
+
263
+ export default class MyRecurringBillingItemHandling implements Billing.RecurringBillingItemHandling<MyRecurringBillingItemHandlingConfig> {
264
+ beforeItemCreation(
265
+ _request: Billing.RecurringBillingItemHandling.BeforeItemCreationInput,
266
+ _config: MyRecurringBillingItemHandlingConfig,
267
+ _context: Context
268
+ ) {
269
+ // TODO: implement your before-item-creation logic here
270
+
271
+ return {
272
+ items: [],
273
+ };
274
+ }
275
+
276
+ filterItems(
277
+ _request: Billing.RecurringBillingItemHandling.FilterItemsInput,
278
+ _config: MyRecurringBillingItemHandlingConfig,
279
+ _context: Context
280
+ ) {
281
+ // TODO: implement your filter-items logic here
282
+
283
+ return {
284
+ items: [],
285
+ };
286
+ }
287
+
288
+ groupItems(
289
+ _request: Billing.RecurringBillingItemHandling.GroupItemsInput,
290
+ _config: MyRecurringBillingItemHandlingConfig,
291
+ _context: Context
292
+ ) {
293
+ // TODO: implement your group-items logic here
294
+
295
+ return {
296
+ groups: [],
297
+ };
298
+ }
299
+ }
300
+ `
301
+ },
302
+ {
303
+ path: "extensions/common/.prettierignore",
304
+ content: `dist
305
+ generated
306
+ node_modules
307
+ `
308
+ },
309
+ {
310
+ path: "extensions/common/eslint.config.mts.mustache",
311
+ content: `import eslint from '@eslint/js';
312
+ import { defineConfig } from 'eslint/config';
313
+ import tseslint from 'typescript-eslint';
314
+ import eslintConfigPrettier from 'eslint-config-prettier/flat';
315
+
316
+ import globals from 'globals';
317
+
318
+ import stripeAppsConfig from '@stripe/extensibility-eslint-plugin';
319
+ import extensionTypeConfig from '@stripe/extensibility-eslint-plugin/{{extensionInterfaceId}}';
320
+
321
+ export default defineConfig([
322
+ eslint.configs.recommended,
323
+ ...tseslint.configs.recommended,
324
+ ...stripeAppsConfig,
325
+ ...extensionTypeConfig,
326
+
327
+ // Global ignores
328
+ {
329
+ ignores: ['dist', 'generated', 'node_modules'],
330
+ },
331
+
332
+ // TypeScript source files (with type-checking)
333
+ {
334
+ name: 'sources',
335
+ files: ['src/**/*.ts'],
336
+ ignores: ['**/*.test.ts', '**/__tests__/**'],
337
+ languageOptions: {
338
+ globals: {
339
+ ...globals.node,
340
+ },
341
+ parserOptions: {
342
+ projectService: true,
343
+ tsconfigRootDir: import.meta.dirname,
344
+ },
345
+ },
346
+ },
347
+
348
+ // Test files (type-checking, relaxed rules)
349
+ {
350
+ name: 'tests',
351
+ files: ['src/**/*.test.ts', 'src/**/__tests__/**/*.ts'],
352
+ languageOptions: {
353
+ globals: {
354
+ ...globals.node,
355
+ },
356
+ parserOptions: {
357
+ projectService: true,
358
+ tsconfigRootDir: import.meta.dirname,
359
+ },
360
+ },
361
+ rules: {
362
+ '@typescript-eslint/no-explicit-any': 'off',
363
+ '@typescript-eslint/no-unused-vars': 'off',
364
+ 'no-console': 'off',
365
+ },
366
+ },
367
+
368
+ // Config files
369
+ {
370
+ name: 'ts-configs',
371
+ files: ['*.config.m?ts', 'eslint.config.mts'],
372
+ languageOptions: {
373
+ globals: {
374
+ ...globals.node,
375
+ },
376
+ parserOptions: {
377
+ projectService: false,
378
+ },
379
+ },
380
+ rules: {
381
+ '@typescript-eslint/no-unused-vars': 'off',
382
+ },
383
+ },
384
+
385
+ // JavaScript/MJS files (scripts, configs)
386
+ {
387
+ name: 'js-configs',
388
+ files: ['**/*.js', '**/*.mjs'],
389
+ languageOptions: {
390
+ globals: {
391
+ ...globals.node,
392
+ },
393
+ parserOptions: {
394
+ projectService: false,
395
+ },
396
+ },
397
+ rules: {
398
+ '@typescript-eslint/no-require-imports': 'off',
399
+ '@typescript-eslint/no-unused-vars': 'off',
400
+ 'no-unused-vars': 'off',
401
+ },
402
+ },
403
+
404
+ eslintConfigPrettier,
405
+ ]);
406
+ `
407
+ },
408
+ {
409
+ path: "extensions/common/package.json.mustache",
410
+ content: `{
411
+ "name": "{{id}}",
412
+ "version": "{{version}}",
413
+ "description": "{{name}}",
414
+ "private": true,
415
+ "license": "~~proprietary~~",
416
+ "type": "module",
417
+ "scripts": {
418
+ "build": "tsc -p tsconfig.build.json && pnpm build:schemas",
419
+ "build:schemas": "gen-schemas --root ../.. --extension-id \\"$npm_package_name\\" --out-dir generated --schema-name config",
420
+ "lint": "pnpm lint:types && pnpm lint:eslint && pnpm lint:format",
421
+ "lint:types": "tsc -p tsconfig.build.json --noEmit && tsc -p tsconfig.json --noEmit",
422
+ "lint:eslint": "eslint .",
423
+ "lint:format": "prettier --check .",
424
+ "fix:lint": "eslint --fix .",
425
+ "fix:format": "prettier --write .",
426
+ "test": "vitest --root ../.. run --project \\"$npm_package_name\\"",
427
+ "test:watch": "pnpm test --watch",
428
+ "dev": "concurrently -n build,lint,test -c blue,yellow,green 'tsc -p tsconfig.json -w --noEmit' 'chokidar \\"src/**/*.{ts,json}\\" -c \\"eslint .\\"' 'pnpm test --watch --no-clear-screen'",
429
+ "stripe:regen": "gen-workspace --root ../.. --package-dir . --template-id {{extensionInterfaceId}}"
430
+ },
431
+ "lint-staged": {
432
+ "*.{ts,mts,mjs,js}": ["eslint --fix", "prettier --write"],
433
+ "*.{json,md,yaml}": "prettier --write"
434
+ }
435
+ }
436
+ `
437
+ },
438
+ {
439
+ path: "extensions/common/tsconfig.build.json.mustache",
440
+ content: `{
441
+ "extends": "../../tsconfig.base.json",
442
+ "compilerOptions": {
443
+ "lib": null,
444
+ "noLib": true,
445
+ "outDir": "./dist",
446
+ "rootDir": "./src"
447
+ },
448
+ "include": [
449
+ "src/**/*.ts",
450
+ "node_modules/@stripe/extensibility-sdk/tslibs/5.9.3/lib.es2022.{{executionProfile}}.d.ts",
451
+ "node_modules/@stripe/extensibility-sdk/tslibs/lib.{{executionProfile}}.globals.d.ts"
452
+ ],
453
+ "exclude": ["src/**/*.test.ts", "src/**/__tests__"]
454
+ }
455
+ `
456
+ },
457
+ {
458
+ path: "extensions/common/tsconfig.json.mustache",
459
+ content: `{
460
+ "extends": "../../tsconfig.json",
461
+ "compilerOptions": {
462
+ "rootDir": ".",
463
+ "plugins": [
464
+ {
465
+ "name": "@stripe/extensibility-language-server/plugin"
466
+ }
467
+ ]
468
+ },
469
+ "include": [
470
+ "src/**/*.ts",
471
+ "node_modules/@stripe/extensibility-sdk/tslibs/lib.{{executionProfile}}.globals.d.ts"
472
+ ],
473
+ "exclude": ["dist"]
474
+ }
475
+ `
476
+ },
477
+ {
478
+ path: "extensions/core.workflows.custom_action/custom_input.schema.json",
479
+ content: `{
480
+ "$schema": "http://json-schema.org/draft-07/schema#",
481
+ "type": "object",
482
+ "properties": {},
483
+ "additionalProperties": false
484
+ }
485
+ `
486
+ },
487
+ {
488
+ path: "extensions/core.workflows.custom_action/index.test.ts",
489
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
490
+
491
+ import MyCustomAction from './index.js';
492
+
493
+ describe('MyCustomAction', () => {
494
+ let instance: MyCustomAction;
495
+
496
+ beforeEach(() => {
497
+ instance = new MyCustomAction();
498
+ });
499
+
500
+ it('should be constructable', () => {
501
+ expect(instance).toBeInstanceOf(MyCustomAction);
502
+ });
503
+ });
504
+ `
505
+ },
506
+ {
507
+ path: "extensions/core.workflows.custom_action/index.ts",
508
+ content: `import type { Core } from '@stripe/extensibility-sdk/extensions';
509
+ import type { Context } from '@stripe/extensibility-sdk/extensions';
510
+
511
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
512
+ interface MyCustomActionConfig extends Record<string, unknown> {}
513
+
514
+ export default class MyCustomAction implements Core.Workflows
515
+ .CustomAction<MyCustomActionConfig> {
516
+ execute(
517
+ _request: Core.Workflows.CustomAction.ExecuteCustomActionRequest,
518
+ _config: MyCustomActionConfig,
519
+ _context: Context
520
+ ) {
521
+ // TODO: implement your action logic here
522
+
523
+ return {};
524
+ }
525
+
526
+ getFormState(
527
+ _request: Core.Workflows.CustomAction.GetFormStateRequest,
528
+ _config: MyCustomActionConfig,
529
+ _context: Context
530
+ ) {
531
+ // TODO: implement your logic here
532
+
533
+ return {
534
+ values: {},
535
+ config: {},
536
+ };
537
+ }
538
+ }
539
+ `
540
+ },
541
+ {
542
+ path: "extensions/extend.workflows.custom_action/custom_input.schema.json",
543
+ content: `{
544
+ "$schema": "http://json-schema.org/draft-07/schema#",
545
+ "type": "object",
546
+ "properties": {},
547
+ "additionalProperties": false
548
+ }
549
+ `
550
+ },
551
+ {
552
+ path: "extensions/extend.workflows.custom_action/index.test.ts",
553
+ content: `import { beforeEach, describe, it, expect } from 'vitest';
554
+
555
+ import MyCustomAction from './index.js';
556
+
557
+ describe('MyCustomAction', () => {
558
+ let instance: MyCustomAction;
559
+
560
+ beforeEach(() => {
561
+ instance = new MyCustomAction();
562
+ });
563
+
564
+ it('should be constructable', () => {
565
+ expect(instance).toBeInstanceOf(MyCustomAction);
566
+ });
567
+ });
568
+ `
569
+ },
570
+ {
571
+ path: "extensions/extend.workflows.custom_action/index.ts",
572
+ content: `import type { Extend } from '@stripe/extensibility-sdk/extensions';
573
+ import type { Context } from '@stripe/extensibility-sdk/extensions';
574
+
575
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
576
+ interface MyCustomActionConfig extends Record<string, unknown> {}
577
+
578
+ export default class MyCustomAction implements Extend.Workflows
579
+ .CustomAction<MyCustomActionConfig> {
580
+ execute(
581
+ _request: Extend.Workflows.CustomAction.ExecuteCustomActionRequest,
582
+ _config: MyCustomActionConfig,
583
+ _context: Context
584
+ ) {
585
+ // TODO: implement your action logic here
586
+
587
+ return {};
588
+ }
589
+
590
+ getFormState(
591
+ _request: Extend.Workflows.CustomAction.GetFormStateRequest,
592
+ _config: MyCustomActionConfig,
593
+ _context: Context
594
+ ) {
595
+ // TODO: implement your logic here
596
+
597
+ return {
598
+ values: {},
599
+ config: {},
600
+ };
601
+ }
602
+ }
603
+ `
604
+ },
605
+ {
606
+ path: "root/.husky/pre-commit",
607
+ content: `pnpm lint-staged
608
+ `
609
+ },
610
+ {
611
+ path: "root/.prettierignore",
612
+ content: `dist
613
+ generated
614
+ node_modules
615
+ pnpm-lock.yaml
616
+ .build
617
+ `
618
+ },
619
+ {
620
+ path: "root/.prettierrc",
621
+ content: `{
622
+ "semi": true,
623
+ "singleQuote": true,
624
+ "tabWidth": 2,
625
+ "trailingComma": "es5",
626
+ "printWidth": 90
627
+ }
628
+ `
629
+ },
630
+ {
631
+ path: "root/_gitignore",
632
+ content: `# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
633
+
634
+ *~
635
+
636
+ # dependencies
637
+ node_modules
638
+ dist
639
+
640
+ # testing
641
+ /coverage
642
+
643
+ # production
644
+ /.build
645
+
646
+ # misc
647
+ .DS_Store
648
+ .env.local
649
+ .env.development.local
650
+ .env.test.local
651
+ .env.production.local
652
+
653
+ npm-debug.log*
654
+ yarn-debug.log*
655
+ yarn-error.log*
656
+ install-deps.log
657
+
658
+ # generated schemas
659
+ generated
660
+ `
661
+ },
662
+ {
663
+ path: "root/custom-objects/package.json",
664
+ content: `{
665
+ "name": "custom-objects",
666
+ "type": "module",
667
+ "version": "0.0.1",
668
+ "license": "UNLICENSED",
669
+ "private": true,
670
+ "scripts": {
671
+ "build": "test -d src && custom-objects-build --input src --output dist || true",
672
+ "lint:types": "test ! -d src || tsc --noEmit",
673
+ "test": "vitest run"
674
+ },
675
+ "dependencies": {
676
+ "@stripe/extensibility-custom-objects": "0.7.4",
677
+ "@stripe/extensibility-sdk": "0.22.4"
678
+ },
679
+ "devDependencies": {
680
+ "@stripe/extensibility-custom-objects-tools": "0.40.0",
681
+ "@stripe/extensibility-test-helpers": "0.2.7"
682
+ }
683
+ }
684
+ `
685
+ },
686
+ {
687
+ path: "root/custom-objects/tsconfig.json",
688
+ content: `{
689
+ "extends": "../tsconfig.base.json",
690
+ "compilerOptions": {
691
+ "module": "ESNext",
692
+ "moduleResolution": "bundler",
693
+ "types": ["vitest/globals"]
694
+ },
695
+ "exclude": ["dist"]
696
+ }
697
+ `
698
+ },
699
+ {
700
+ path: "root/eslint.config.mts",
701
+ content: `import { readFileSync } from 'node:fs';
702
+ import { dirname, resolve } from 'node:path';
703
+ import { fileURLToPath } from 'node:url';
704
+ import eslint from '@eslint/js';
705
+ import { defineConfig } from 'eslint/config';
706
+ import tseslint from 'typescript-eslint';
707
+ import workspaces from 'eslint-plugin-workspaces';
708
+ import eslintConfigPrettier from 'eslint-config-prettier/flat';
709
+
710
+ import globals from 'globals';
711
+
712
+ import stripeAppsConfig from '@stripe/extensibility-eslint-plugin';
713
+
714
+ // Read additional ignore globs from package.json (written by the generate plugin
715
+ // to exclude generated SDK directories from linting).
716
+ let stripeGlobsToIgnore: string[] = [];
717
+ try {
718
+ const configDir = dirname(fileURLToPath(import.meta.url));
719
+ const packageJsonPath = resolve(configDir, './package.json');
720
+ const pkg = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
721
+ const globs = pkg?.stripe?.eslintIgnoreGlobs;
722
+ if (Array.isArray(globs)) {
723
+ stripeGlobsToIgnore = globs.filter(
724
+ (g: unknown): g is string => typeof g === 'string'
725
+ );
726
+ }
727
+ } catch {
728
+ // package.json not found or unparseable \u2014 ignore
729
+ }
730
+
731
+ export default defineConfig([
732
+ eslint.configs.recommended,
733
+ ...tseslint.configs.recommended,
734
+ ...stripeAppsConfig,
735
+
736
+ // Global ignores
737
+ {
738
+ ignores: [
739
+ '.build',
740
+ '**/dist',
741
+ '**/generated',
742
+ '**/node_modules',
743
+ 'extensions/**',
744
+ 'custom-objects',
745
+ 'ui',
746
+ ...stripeGlobsToIgnore,
747
+ ],
748
+ },
749
+
750
+ // Common rules for all files
751
+ {
752
+ plugins: { workspaces },
753
+ rules: {
754
+ ...workspaces.configs.recommended.rules,
755
+ },
756
+ },
757
+
758
+ // Config files (vitest.config.ts, eslint.config.ts, etc.)
759
+ {
760
+ name: 'ts-configs',
761
+ files: ['extensions/*/*.config.m?ts', '*.config.m?ts', 'eslint.config.mts'],
762
+ languageOptions: {
763
+ globals: {
764
+ ...globals.node,
765
+ },
766
+ parserOptions: {
767
+ projectService: false,
768
+ },
769
+ },
770
+ rules: {
771
+ '@typescript-eslint/no-unused-vars': 'off',
772
+ },
773
+ },
774
+
775
+ // JavaScript/MJS files (scripts, configs)
776
+ {
777
+ name: 'js-configs',
778
+ files: ['**/*.js', '**/*.mjs'],
779
+ languageOptions: {
780
+ globals: {
781
+ ...globals.node,
782
+ },
783
+ parserOptions: {
784
+ projectService: false,
785
+ },
786
+ },
787
+ rules: {
788
+ '@typescript-eslint/no-require-imports': 'off',
789
+ '@typescript-eslint/no-unused-vars': 'off',
790
+ 'no-unused-vars': 'off',
791
+ },
792
+ },
793
+
794
+ eslintConfigPrettier,
795
+ ]);
796
+ `
797
+ },
798
+ {
799
+ path: "root/package.json.mustache",
800
+ content: `{
801
+ "name": "{{ appId }}",
802
+ "version": "{{ version }}",
803
+ "description": "{{ appName }}",
804
+ "private": true,
805
+ "license": "~~proprietary~~",
806
+ "engines": {
807
+ "node": ">=20.0.0"
808
+ },
809
+ "packageManager": "pnpm@10.30.3",
810
+ "scripts": {
811
+ "build": "pnpm -r --if-present build",
812
+ "lint": "pnpm lint:types && pnpm lint:eslint && pnpm lint:format",
813
+ "lint:types": "pnpm -r --if-present lint:types",
814
+ "lint:eslint": "eslint . --ignore-pattern 'extensions/**' && pnpm -r --filter './extensions/*' --if-present lint:eslint",
815
+ "lint:format": "prettier --check .",
816
+ "fix:lint": "eslint --fix . --ignore-pattern 'extensions/**' && pnpm -r --filter './extensions/*' --if-present fix:lint",
817
+ "fix:format": "prettier --write .",
818
+ "test": "tsx tools/test.mts",
819
+ "test:watch": "vitest watch",
820
+ "check": "pnpm build && pnpm lint && pnpm test",
821
+ "prepare": "husky",
822
+ "preimage": "pnpm install --lockfile-only && pnpm build && pnpm lint:types && pnpm lint:eslint && pnpm test",
823
+ "image": "rm -rf .build && create-upload-image .build",
824
+ "postimage": "cp pnpm-lock.yaml .build/",
825
+ "stripe:regen": "gen-workspace --package-dir ."
826
+ },
827
+ "lint-staged": {
828
+ "*.{ts,mts,mjs,js}": ["eslint --fix", "prettier --write"],
829
+ "*.{json,md,yaml}": "prettier --write"
830
+ }
831
+ }
832
+ `
833
+ },
834
+ {
835
+ path: "root/pnpm-workspace.yaml",
836
+ content: `packages:
837
+ - extensions/*
838
+ - custom-objects
839
+ - ui
840
+
841
+ overrides:
842
+ vite: ^6.0.0
843
+ `
844
+ },
845
+ {
846
+ path: "root/stripe-app.yaml.mustache",
847
+ content: `$schema: https://stripe.com/stripe-app/v2.0.0/schema
848
+ id: '{{ appId }}'
849
+ name: '{{ appName }}'
850
+ version: 0.0.1
851
+ declarations:
852
+ distribution_type: private
853
+ `
854
+ },
855
+ {
856
+ path: "root/tools/test.mts",
857
+ content: `#!/usr/bin/env tsx
858
+ /**
859
+ * Runs tests across the workspace:
860
+ * - vitest for script extensions and custom objects (extensions/*)
861
+ * - jest for UI extensions (ui/)
862
+ */
863
+ import { existsSync, readdirSync } from 'node:fs';
864
+ import { execSync } from 'node:child_process';
865
+
866
+ const hasExtensions =
867
+ existsSync('extensions') &&
868
+ readdirSync('extensions').some((name) => existsSync(\`extensions/\${name}/package.json\`));
869
+
870
+ const hasUI = existsSync('ui/package.json');
871
+
872
+ let exitCode = 0;
873
+
874
+ function run(cmd: string): void {
875
+ try {
876
+ execSync(cmd, { stdio: 'inherit' });
877
+ } catch (e: unknown) {
878
+ exitCode = (e as NodeJS.ErrnoException & { status?: number }).status ?? 1;
879
+ }
880
+ }
881
+
882
+ if (hasExtensions) {
883
+ run('vitest run');
884
+ }
885
+
886
+ if (hasUI) {
887
+ try {
888
+ execSync('pnpm --filter "./ui" test', { stdio: 'inherit' });
889
+ } catch {
890
+ // UI test failures are non-fatal
891
+ }
892
+ }
893
+
894
+ process.exit(exitCode);
895
+ `
896
+ },
897
+ {
898
+ path: "root/tsconfig.base.json",
899
+ content: `{
900
+ "compilerOptions": {
901
+ "target": "ES2022",
902
+ "module": "NodeNext",
903
+ "moduleResolution": "NodeNext",
904
+ "lib": ["ES2022"],
905
+ "declaration": true,
906
+ "declarationMap": true,
907
+ "esModuleInterop": true,
908
+ "exactOptionalPropertyTypes": false,
909
+ "forceConsistentCasingInFileNames": true,
910
+ "isolatedModules": true,
911
+ "noFallthroughCasesInSwitch": true,
912
+ "noImplicitReturns": true,
913
+ "removeComments": false,
914
+ "resolveJsonModule": true,
915
+ "skipLibCheck": true,
916
+ "sourceMap": true,
917
+ "strict": true,
918
+ "types": [],
919
+ "verbatimModuleSyntax": true
920
+ }
921
+ }
922
+ `
923
+ },
924
+ {
925
+ path: "root/tsconfig.json",
926
+ content: `{
927
+ "extends": "./tsconfig.base.json",
928
+ "compilerOptions": {
929
+ "noEmit": true,
930
+ "plugins": [
931
+ {
932
+ "name": "@stripe/extensibility-language-server/plugin"
933
+ }
934
+ ],
935
+ "preserveWatchOutput": true,
936
+ "types": ["vitest/globals", "node"]
937
+ },
938
+ "include": ["**/*.ts"],
939
+ "exclude": ["**/node_modules", "**/dist"]
940
+ }
941
+ `
942
+ },
943
+ {
944
+ path: "root/ui/package.json",
945
+ content: `{
946
+ "name": "ui",
947
+ "version": "0.0.1",
948
+ "license": "UNLICENSED",
949
+ "private": true,
950
+ "scripts": {
951
+ "test": "jest --passWithNoTests"
952
+ },
953
+ "dependencies": {
954
+ "@stripe/ui-extension-sdk": "^9.1.0"
955
+ },
956
+ "devDependencies": {
957
+ "@stripe/ui-extension-tools": "^0.0.1",
958
+ "@types/jest": "^27.5.2",
959
+ "@types/react": "^17.0.2"
960
+ }
961
+ }
962
+ `
963
+ },
964
+ {
965
+ path: "root/vitest.config.mts",
966
+ content: `import { defineConfig } from 'vitest/config';
967
+ import { existsSync, readdirSync } from 'fs';
968
+ import { dirname, resolve } from 'path';
969
+ import { fileURLToPath } from 'url';
970
+
971
+ const rootDir = dirname(fileURLToPath(import.meta.url));
972
+ const extensionsDir = resolve(rootDir, 'extensions');
973
+
974
+ const extensionProjects = existsSync(extensionsDir)
975
+ ? readdirSync(extensionsDir)
976
+ .filter((name) => existsSync(resolve(extensionsDir, name, 'package.json')))
977
+ .map((name) => resolve(extensionsDir, name))
978
+ : [];
979
+
980
+ const coProjects = existsSync(resolve(rootDir, 'custom-objects/package.json'))
981
+ ? [resolve(rootDir, 'custom-objects')]
982
+ : [];
983
+
984
+ const projects = [...extensionProjects, ...coProjects];
985
+
986
+ if (projects.length === 0) {
987
+ console.debug(\`No vitest projects detected. This means either:
988
+ - You have no extension projects defined, in which case this warning is expected.
989
+ - There is an internal error detecting vitest projects relative to the project root
990
+ \${rootDir}.
991
+ \`);
992
+ }
993
+
994
+ export default projects.length > 0
995
+ ? defineConfig({
996
+ test: {
997
+ projects,
998
+ passWithNoTests: true,
999
+
1000
+ // Only run tests from src, not compiled dist
1001
+ exclude: ['**/node_modules', '**/dist'],
1002
+ // Place snapshots alongside test files instead of in __snapshots__
1003
+ snapshotFormat: {
1004
+ escapeString: false,
1005
+ printBasicPrototype: false,
1006
+ },
1007
+ resolveSnapshotPath: (testPath, snapExtension) => {
1008
+ return testPath.replace(/\\.test\\.ts$/, \`.test\${snapExtension}\`);
1009
+ },
1010
+ },
1011
+ })
1012
+ : defineConfig({ test: { passWithNoTests: true, include: [] } });
1013
+ `
1014
+ }
1015
+ ];
1016
+ var _fs = (0, import_extensibility_tool_utils2._createInMemoryTemplateFS)(TEMPLATE_FS_IMAGE);
1017
+
1018
+ // src/templates/simple-templates.ts
1019
+ var import_extensibility_tool_utils3 = require("@stripe/extensibility-tool-utils");
1020
+
1021
+ // src/templates/file-writer.ts
1022
+ var import_path = __toESM(require("path"), 1);
1023
+ var import_promises2 = require("fs/promises");
1024
+ var import_node_readline = require("readline");
1025
+ var import_extensibility_tool_utils4 = require("@stripe/extensibility-tool-utils");
1026
+
1027
+ // src/templates/fs-utils.ts
1028
+ var import_promises = require("fs/promises");
1029
+ async function pathExists(filePath, predicate) {
1030
+ try {
1031
+ const stats = await (0, import_promises.stat)(filePath);
1032
+ return predicate(stats);
1033
+ } catch (error) {
1034
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
1035
+ return false;
1036
+ }
1037
+ throw error;
1038
+ }
1039
+ }
1040
+ async function fileExists(filePath) {
1041
+ return pathExists(filePath, (stats) => stats.isFile());
1042
+ }
1043
+ async function directoryExists(dirPath) {
1044
+ return pathExists(dirPath, (stats) => stats.isDirectory());
1045
+ }
1046
+
1047
+ // src/templates/file-writer.ts
1048
+ var logger = (0, import_extensibility_tool_utils4._createLogger)({ name: "file-writer" });
1049
+ async function _promptOverwrite(filePath) {
1050
+ const prompt = `${filePath} exists. Overwrite [yNaq]? `;
1051
+ if (!process.stdin.isTTY) {
1052
+ const rl = (0, import_node_readline.createInterface)({
1053
+ input: process.stdin,
1054
+ output: process.stdout
1055
+ });
1056
+ return new Promise((resolve) => {
1057
+ rl.question(prompt, (answer) => {
1058
+ rl.close();
1059
+ const normalized = answer.toLowerCase().trim();
1060
+ switch (normalized) {
1061
+ case "y":
1062
+ case "yes":
1063
+ resolve("overwrite");
1064
+ break;
1065
+ case "n":
1066
+ case "no":
1067
+ case "":
1068
+ resolve("skip");
1069
+ break;
1070
+ case "a":
1071
+ case "all":
1072
+ resolve("overwrite-all");
1073
+ break;
1074
+ case "q":
1075
+ case "quit":
1076
+ resolve("abort");
1077
+ break;
1078
+ default:
1079
+ logger.warn("Invalid input '%s', treating as 'no'", answer);
1080
+ resolve("skip");
1081
+ }
1082
+ });
1083
+ });
1084
+ }
1085
+ process.stdout.write(prompt);
1086
+ return new Promise((resolve) => {
1087
+ const stdin = process.stdin;
1088
+ const wasRaw = stdin.isRaw;
1089
+ stdin.setRawMode(true);
1090
+ stdin.resume();
1091
+ const onData = (buffer) => {
1092
+ stdin.setRawMode(wasRaw || false);
1093
+ stdin.pause();
1094
+ stdin.removeListener("data", onData);
1095
+ const key = buffer.toString();
1096
+ const code = buffer[0];
1097
+ if (code === 3) {
1098
+ process.stdout.write("\nCancelled.\n");
1099
+ setTimeout(() => process.exit(0), 100);
1100
+ return;
1101
+ }
1102
+ if (code === 13 || code === 10) {
1103
+ process.stdout.write("n\n");
1104
+ resolve("skip");
1105
+ return;
1106
+ }
1107
+ const normalized = key.toLowerCase();
1108
+ let decision;
1109
+ switch (normalized) {
1110
+ case "y":
1111
+ process.stdout.write("y\n");
1112
+ decision = "overwrite";
1113
+ break;
1114
+ case "n":
1115
+ process.stdout.write("n\n");
1116
+ decision = "skip";
1117
+ break;
1118
+ case "a":
1119
+ process.stdout.write("a\n");
1120
+ decision = "overwrite-all";
1121
+ break;
1122
+ case "q":
1123
+ process.stdout.write("q\n");
1124
+ decision = "abort";
1125
+ break;
1126
+ default:
1127
+ process.stdout.write(`${key}
1128
+ `);
1129
+ logger.warn("Invalid input '%s', treating as 'no'", key);
1130
+ decision = "skip";
1131
+ }
1132
+ resolve(decision);
1133
+ };
1134
+ stdin.on("data", onData);
1135
+ });
1136
+ }
1137
+ async function _writeGeneratedFiles(files, options = {}) {
1138
+ const { cwd = process.cwd(), onFileWritten, onFileSkipped, onFileIdentical } = options;
1139
+ let write = options.write ?? "abort-if-existing";
1140
+ const existing = [];
1141
+ for (const file of files) {
1142
+ const fullPath = import_path.default.join(cwd, file.path);
1143
+ if (await fileExists(fullPath)) {
1144
+ existing.push(file.path);
1145
+ }
1146
+ }
1147
+ if (existing.length > 0 && write === "abort-if-existing") {
1148
+ if (onFileSkipped) {
1149
+ for (const file of files) {
1150
+ if (existing.includes(file.path)) {
1151
+ onFileSkipped(file);
1152
+ }
1153
+ }
1154
+ }
1155
+ return {
1156
+ written: [],
1157
+ existing,
1158
+ skipped: true,
1159
+ aborted: false
1160
+ };
1161
+ }
1162
+ const written = [];
1163
+ for (const file of files) {
1164
+ const fullPath = import_path.default.join(cwd, file.path);
1165
+ const fileDir = import_path.default.dirname(fullPath);
1166
+ const isExisting = existing.includes(file.path);
1167
+ if (isExisting) {
1168
+ const existingContent = await (0, import_promises2.readFile)(fullPath, "utf-8");
1169
+ if (existingContent === file.content) {
1170
+ if (onFileIdentical) {
1171
+ onFileIdentical(file);
1172
+ }
1173
+ continue;
1174
+ }
1175
+ }
1176
+ if (isExisting && (write === "if-missing" || file.precious)) {
1177
+ if (onFileSkipped) {
1178
+ onFileSkipped(file);
1179
+ }
1180
+ continue;
1181
+ }
1182
+ if (isExisting && typeof write === "function") {
1183
+ const decision = await write(file.path, cwd, file.content);
1184
+ switch (decision) {
1185
+ case "skip":
1186
+ if (onFileSkipped) {
1187
+ onFileSkipped(file);
1188
+ }
1189
+ continue;
1190
+ case "overwrite":
1191
+ break;
1192
+ case "overwrite-all":
1193
+ write = "overwrite-all";
1194
+ break;
1195
+ case "abort":
1196
+ return {
1197
+ written,
1198
+ existing,
1199
+ skipped: false,
1200
+ aborted: true
1201
+ };
1202
+ }
1203
+ }
1204
+ if (!await directoryExists(fileDir)) {
1205
+ await (0, import_promises2.mkdir)(fileDir, { recursive: true });
1206
+ }
1207
+ await (0, import_promises2.writeFile)(fullPath, file.content, "utf-8");
1208
+ if (onFileWritten) {
1209
+ onFileWritten(file, isExisting);
1210
+ }
1211
+ written.push(file.path);
1212
+ }
1213
+ return {
1214
+ written,
1215
+ existing,
1216
+ // Always populated; write='abort-if-existing' returns early above
1217
+ skipped: false,
1218
+ aborted: false
1219
+ };
1220
+ }
1221
+
1222
+ // src/templates/diff-viewer/diff-prompt.ts
1223
+ var import_node_path = __toESM(require("path"), 1);
1224
+
1225
+ // src/templates/diff-viewer/diff-generator.ts
1226
+ var import_diff = require("diff");
1227
+ var import_promises3 = require("fs/promises");
1228
+ async function generateDiff(filePath, oldContent, newContent, contextLines = 3) {
1229
+ if (isBinary(oldContent) || isBinary(newContent)) {
1230
+ return {
1231
+ lines: [{ type: "header", text: "Binary file changed" }],
1232
+ oldFileName: filePath,
1233
+ newFileName: filePath,
1234
+ isBinary: true
1235
+ };
1236
+ }
1237
+ const patch = (0, import_diff.createPatch)(filePath, oldContent, newContent, "existing", "new", {
1238
+ context: contextLines
1239
+ });
1240
+ const lines = parsePatch(patch);
1241
+ return {
1242
+ lines,
1243
+ oldFileName: filePath,
1244
+ newFileName: filePath,
1245
+ isBinary: false
1246
+ };
1247
+ }
1248
+ function parsePatch(patch) {
1249
+ const lines = [];
1250
+ const patchLines = patch.split("\n");
1251
+ let oldLine = 0;
1252
+ let newLine = 0;
1253
+ for (const line of patchLines) {
1254
+ if (line.startsWith("@@")) {
1255
+ const match = line.match(/@@ -(\d+),?\d* \+(\d+),?\d* @@/);
1256
+ if (match !== null) {
1257
+ oldLine = parseInt(match[1], 10);
1258
+ newLine = parseInt(match[2], 10);
1259
+ lines.push({ type: "header", text: line });
1260
+ }
1261
+ } else if (line.startsWith("+")) {
1262
+ lines.push({ type: "add", text: line, newLine: newLine++ });
1263
+ } else if (line.startsWith("-")) {
1264
+ lines.push({ type: "remove", text: line, oldLine: oldLine++ });
1265
+ } else if (line.startsWith(" ")) {
1266
+ lines.push({
1267
+ type: "context",
1268
+ text: line,
1269
+ oldLine: oldLine++,
1270
+ newLine: newLine++
1271
+ });
1272
+ } else if (line.startsWith("\\")) {
1273
+ lines.push({ type: "context", text: line });
1274
+ }
1275
+ }
1276
+ return lines;
1277
+ }
1278
+ function isBinary(content) {
1279
+ return content.includes("\0");
1280
+ }
1281
+ async function readExistingFile(resolvedPath) {
1282
+ try {
1283
+ return await (0, import_promises3.readFile)(resolvedPath, "utf-8");
1284
+ } catch (err) {
1285
+ if (err instanceof Error && "code" in err && err.code === "ENOENT") {
1286
+ return "";
1287
+ }
1288
+ throw err;
1289
+ }
1290
+ }
1291
+
1292
+ // src/templates/diff-viewer/terminal-renderer.ts
1293
+ var import_child_process = require("child_process");
1294
+ var import_string_width = __toESM(require("string-width"), 1);
1295
+ var ANSI = {
1296
+ // Colors
1297
+ RED: "\x1B[31m",
1298
+ GREEN: "\x1B[32m",
1299
+ CYAN: "\x1B[36m",
1300
+ GRAY: "\x1B[90m",
1301
+ RESET: "\x1B[0m",
1302
+ // Text styles
1303
+ BOLD: "\x1B[1m",
1304
+ DIM: "\x1B[2m"
1305
+ };
1306
+ var BOX_HORIZONTAL = "\u2500";
1307
+ function render(state, filePath, clearPrevious = false) {
1308
+ const maxTotalHeight = Math.floor(state.terminalHeight * 0.75);
1309
+ const maxContentHeight = maxTotalHeight - 3;
1310
+ const contentHeight = state.diffLines.length;
1311
+ const windowHeight = Math.min(contentHeight, maxContentHeight);
1312
+ const visibleLines = state.diffLines.slice(
1313
+ state.scrollOffset,
1314
+ state.scrollOffset + windowHeight
1315
+ );
1316
+ const totalLines = state.diffLines.length;
1317
+ const startLine = state.scrollOffset + 1;
1318
+ const endLine = state.scrollOffset + visibleLines.length;
1319
+ if (clearPrevious && state.renderedHeight > 0) {
1320
+ clearPreviousRender(state.renderedHeight - 1);
1321
+ }
1322
+ let output = "";
1323
+ output += renderTopBar(filePath, state.terminalWidth) + "\n";
1324
+ for (const line of visibleLines) {
1325
+ output += colorize(line, state.terminalWidth) + "\n";
1326
+ }
1327
+ output += renderBottomBar(startLine, endLine, totalLines, state, state.terminalWidth) + "\n";
1328
+ output += "\n";
1329
+ output += `overwrite ${filePath} [yNaqd]? `;
1330
+ state.renderedHeight = 1 + visibleLines.length + 1 + 1 + 1;
1331
+ process.stdout.write(output);
1332
+ }
1333
+ function clearPreviousRender(lines) {
1334
+ process.stdout.write(`\x1B[${lines}A`);
1335
+ process.stdout.write("\r");
1336
+ process.stdout.write("\x1B[0J");
1337
+ }
1338
+ function renderTopBar(filePath, width) {
1339
+ const prefix = BOX_HORIZONTAL.repeat(3) + " ";
1340
+ const suffix = " " + BOX_HORIZONTAL.repeat(3);
1341
+ const availableWidth = width - (0, import_string_width.default)(prefix) - (0, import_string_width.default)(suffix);
1342
+ let displayName = filePath;
1343
+ if ((0, import_string_width.default)(displayName) + 1 > availableWidth) {
1344
+ while ((0, import_string_width.default)("..." + displayName) + 1 > availableWidth && displayName.length > 0) {
1345
+ displayName = displayName.slice(1);
1346
+ }
1347
+ displayName = "..." + displayName;
1348
+ }
1349
+ const paddingLength = Math.max(0, availableWidth - (0, import_string_width.default)(displayName) - 1);
1350
+ const padding = BOX_HORIZONTAL.repeat(paddingLength);
1351
+ return ANSI.CYAN + prefix + ANSI.BOLD + displayName + ANSI.RESET + " " + ANSI.CYAN + padding + suffix + ANSI.RESET;
1352
+ }
1353
+ function renderBottomBar(startLine, endLine, totalLines, _state, width) {
1354
+ const prefix = BOX_HORIZONTAL.repeat(3) + " ";
1355
+ const positionIndicator = `${startLine}-${endLine}/${totalLines}`;
1356
+ const content = positionIndicator;
1357
+ const suffix = " " + BOX_HORIZONTAL.repeat(3);
1358
+ const availableWidth = width - (0, import_string_width.default)(prefix) - (0, import_string_width.default)(suffix);
1359
+ const paddingLength = Math.max(0, availableWidth - (0, import_string_width.default)(content));
1360
+ const padding = BOX_HORIZONTAL.repeat(paddingLength);
1361
+ return ANSI.CYAN + prefix + ANSI.RESET + ANSI.DIM + content + ANSI.RESET + ANSI.CYAN + padding + suffix + ANSI.RESET;
1362
+ }
1363
+ function clearDiffWindow() {
1364
+ process.stdout.write("\n");
1365
+ }
1366
+ function colorize(line, terminalWidth) {
1367
+ const maxWidth = Math.max(10, terminalWidth - 3);
1368
+ const text = truncateLine(line.text, maxWidth);
1369
+ switch (line.type) {
1370
+ case "add":
1371
+ return ANSI.GREEN + text + ANSI.RESET;
1372
+ case "remove":
1373
+ return ANSI.RED + text + ANSI.RESET;
1374
+ case "header":
1375
+ return ANSI.CYAN + text + ANSI.RESET;
1376
+ case "context":
1377
+ return ANSI.GRAY + text + ANSI.RESET;
1378
+ default:
1379
+ return text;
1380
+ }
1381
+ }
1382
+ function truncateLine(text, maxWidth) {
1383
+ if ((0, import_string_width.default)(text) <= maxWidth) {
1384
+ return text;
1385
+ }
1386
+ let truncated = text;
1387
+ while ((0, import_string_width.default)(truncated + "...") > maxWidth && truncated.length > 0) {
1388
+ truncated = truncated.slice(0, -1);
1389
+ }
1390
+ return truncated + "...";
1391
+ }
1392
+ function getTerminalSize() {
1393
+ let columns = 80;
1394
+ let rows = 24;
1395
+ try {
1396
+ const sttyOutput = (0, import_child_process.execSync)("stty size </dev/tty", {
1397
+ encoding: "utf-8",
1398
+ stdio: ["ignore", "pipe", "ignore"],
1399
+ timeout: 200,
1400
+ shell: "/bin/bash"
1401
+ }).trim();
1402
+ const parts = sttyOutput.split(/\s+/);
1403
+ if (parts.length === 2) {
1404
+ const sttyRows = parseInt(parts[0], 10);
1405
+ const sttyCols = parseInt(parts[1], 10);
1406
+ if (!isNaN(sttyRows) && sttyRows > 0) {
1407
+ rows = sttyRows;
1408
+ }
1409
+ if (!isNaN(sttyCols) && sttyCols > 0) {
1410
+ columns = sttyCols;
1411
+ }
1412
+ }
1413
+ } catch {
1414
+ try {
1415
+ const tputCols = (0, import_child_process.execSync)("tput cols </dev/tty", {
1416
+ encoding: "utf-8",
1417
+ stdio: ["ignore", "pipe", "ignore"],
1418
+ timeout: 100,
1419
+ shell: "/bin/bash"
1420
+ }).trim();
1421
+ const cols = parseInt(tputCols, 10);
1422
+ if (!isNaN(cols) && cols > 0) {
1423
+ columns = cols;
1424
+ }
1425
+ } catch {
1426
+ }
1427
+ try {
1428
+ const tputRows = (0, import_child_process.execSync)("tput lines </dev/tty", {
1429
+ encoding: "utf-8",
1430
+ stdio: ["ignore", "pipe", "ignore"],
1431
+ timeout: 100,
1432
+ shell: "/bin/bash"
1433
+ }).trim();
1434
+ const lns = parseInt(tputRows, 10);
1435
+ if (!isNaN(lns) && lns > 0) {
1436
+ rows = lns;
1437
+ }
1438
+ } catch {
1439
+ }
1440
+ }
1441
+ return { rows, columns };
1442
+ }
1443
+
1444
+ // src/templates/diff-viewer/diff-prompt.ts
1445
+ var import_extensibility_tool_utils5 = require("@stripe/extensibility-tool-utils");
1446
+ var logger2 = (0, import_extensibility_tool_utils5._createLogger)({ name: "diff-prompt" });
1447
+ function isInteractiveTerminal() {
1448
+ if (process.env["CI"] === "true" || process.env["CI"] === "1") {
1449
+ return false;
1450
+ }
1451
+ const term = process.env["TERM"];
1452
+ if (!term || term === "dumb") {
1453
+ return false;
1454
+ }
1455
+ if (typeof process.stdin.setRawMode !== "function") {
1456
+ return false;
1457
+ }
1458
+ const termSize = getTerminalSize();
1459
+ if (termSize.rows === 24 && termSize.columns === 80) {
1460
+ }
1461
+ return true;
1462
+ }
1463
+ async function _advancedDiffPrompt(filePath, cwd, newContent) {
1464
+ const resolvedPath = import_node_path.default.resolve(cwd, filePath);
1465
+ if (!isInteractiveTerminal()) {
1466
+ return await _promptOverwrite(filePath);
1467
+ }
1468
+ try {
1469
+ const existingContent = await readExistingFile(resolvedPath);
1470
+ const diffResult = await generateDiff(filePath, existingContent, newContent);
1471
+ const termSize = getTerminalSize();
1472
+ if (termSize.rows < 20) {
1473
+ return await _promptOverwrite(filePath);
1474
+ }
1475
+ if (diffResult.lines.length > 5e3) {
1476
+ logger2.info("Diff too large to display comfortably");
1477
+ return await _promptOverwrite(filePath);
1478
+ }
1479
+ const wasRaw = process.stdin.isRaw ?? false;
1480
+ try {
1481
+ process.stdin.setRawMode(true);
1482
+ } catch {
1483
+ return await _promptOverwrite(filePath);
1484
+ }
1485
+ process.stdin.resume();
1486
+ const maxTotalHeight = Math.floor(termSize.rows * 0.75);
1487
+ const maxContentHeight = maxTotalHeight - 3;
1488
+ const windowHeight = Math.min(diffResult.lines.length, maxContentHeight);
1489
+ const state = {
1490
+ scrollOffset: 0,
1491
+ maxScroll: Math.max(0, diffResult.lines.length - windowHeight),
1492
+ diffLines: diffResult.lines,
1493
+ terminalHeight: termSize.rows,
1494
+ terminalWidth: termSize.columns,
1495
+ wasRaw,
1496
+ renderedHeight: 0,
1497
+ fullFileMode: false
1498
+ };
1499
+ render(state, filePath, false);
1500
+ return new Promise((resolve) => {
1501
+ const onExit = () => {
1502
+ cleanup(state.wasRaw, onData, onExit);
1503
+ };
1504
+ const onData = (buffer) => {
1505
+ handleKeypress(buffer, state, filePath, newContent, existingContent).then((result) => {
1506
+ if (result !== "continue") {
1507
+ cleanup(state.wasRaw, onData, onExit);
1508
+ resolve(result);
1509
+ }
1510
+ }).catch((err) => {
1511
+ cleanup(state.wasRaw, onData, onExit);
1512
+ logger2.error({ err }, "Error handling keypress");
1513
+ resolve("abort");
1514
+ });
1515
+ };
1516
+ process.stdin.on("data", onData);
1517
+ process.on("exit", onExit);
1518
+ });
1519
+ } catch (err) {
1520
+ logger2.warn({ err }, "Error displaying diff, using basic prompt");
1521
+ return await _promptOverwrite(filePath);
1522
+ }
1523
+ }
1524
+ async function handleKeypress(buffer, state, filePath, newContent, existingContent) {
1525
+ const code = buffer[0];
1526
+ const key = buffer.toString();
1527
+ if (code === 3) {
1528
+ process.stdout.write("\nCancelled.\n");
1529
+ return "abort";
1530
+ }
1531
+ switch (key.toLowerCase()) {
1532
+ case "y":
1533
+ return "overwrite";
1534
+ case "n":
1535
+ case "\r":
1536
+ case "\n":
1537
+ return "skip";
1538
+ case "a":
1539
+ return "overwrite-all";
1540
+ case "q":
1541
+ return "abort";
1542
+ case "d":
1543
+ await toggleDiffContext(state, filePath, newContent, existingContent);
1544
+ return "continue";
1545
+ }
1546
+ if (buffer.length >= 3 && buffer[0] === 27 && buffer[1] === 91) {
1547
+ const maxTotalHeight = Math.floor(state.terminalHeight * 0.75);
1548
+ const maxContentHeight = maxTotalHeight - 3;
1549
+ const windowHeight = Math.min(state.diffLines.length, maxContentHeight);
1550
+ let scrollDelta = 0;
1551
+ if (buffer[2] === 65) {
1552
+ scrollDelta = -1;
1553
+ } else if (buffer[2] === 66) {
1554
+ scrollDelta = 1;
1555
+ } else if (buffer[2] === 53) {
1556
+ scrollDelta = -windowHeight;
1557
+ } else if (buffer[2] === 54) {
1558
+ scrollDelta = windowHeight;
1559
+ }
1560
+ const newScrollOffset = Math.max(
1561
+ 0,
1562
+ Math.min(state.maxScroll, state.scrollOffset + scrollDelta)
1563
+ );
1564
+ if (newScrollOffset !== state.scrollOffset) {
1565
+ state.scrollOffset = newScrollOffset;
1566
+ render(state, filePath, true);
1567
+ }
1568
+ }
1569
+ return "continue";
1570
+ }
1571
+ function cleanup(wasRaw, onData, onExit) {
1572
+ if (process.stdin.setRawMode !== void 0) {
1573
+ process.stdin.setRawMode(wasRaw);
1574
+ }
1575
+ process.stdin.pause();
1576
+ if (onData) {
1577
+ process.stdin.off("data", onData);
1578
+ }
1579
+ if (onExit) {
1580
+ process.off("exit", onExit);
1581
+ }
1582
+ clearDiffWindow();
1583
+ }
1584
+ async function toggleDiffContext(state, filePath, newContent, existingContent) {
1585
+ state.fullFileMode = !state.fullFileMode;
1586
+ const contextLines = state.fullFileMode ? 1e4 : 3;
1587
+ const visibleStartIndex = state.scrollOffset;
1588
+ let referenceLineFinder = null;
1589
+ let skippedLines = 0;
1590
+ for (let i = visibleStartIndex; i < state.diffLines.length; i++) {
1591
+ const line = state.diffLines[i];
1592
+ if (line !== void 0) {
1593
+ if (line.type === "header") {
1594
+ skippedLines++;
1595
+ continue;
1596
+ }
1597
+ if (line.newLine !== void 0) {
1598
+ const targetNewLine = line.newLine;
1599
+ referenceLineFinder = (dl) => dl.newLine !== void 0 && dl.newLine >= targetNewLine - skippedLines;
1600
+ break;
1601
+ } else if (line.oldLine !== void 0) {
1602
+ const targetOldLine = line.oldLine;
1603
+ referenceLineFinder = (dl) => dl.oldLine !== void 0 && dl.oldLine >= targetOldLine - skippedLines;
1604
+ break;
1605
+ }
1606
+ }
1607
+ }
1608
+ const diffResult = await generateDiff(
1609
+ filePath,
1610
+ existingContent,
1611
+ newContent,
1612
+ contextLines
1613
+ );
1614
+ state.diffLines = diffResult.lines;
1615
+ let newScrollOffset = 0;
1616
+ if (referenceLineFinder !== null) {
1617
+ const referenceIndex = diffResult.lines.findIndex(referenceLineFinder);
1618
+ if (referenceIndex !== -1) {
1619
+ newScrollOffset = Math.max(0, referenceIndex);
1620
+ }
1621
+ }
1622
+ const maxTotalHeight = Math.floor(state.terminalHeight * 0.75);
1623
+ const maxContentHeight = maxTotalHeight - 3;
1624
+ const windowHeight = Math.min(diffResult.lines.length, maxContentHeight);
1625
+ state.maxScroll = Math.max(0, diffResult.lines.length - windowHeight);
1626
+ state.scrollOffset = Math.min(newScrollOffset, state.maxScroll);
1627
+ render(state, filePath, true);
1628
+ }
1629
+
1630
+ // src/templates/extensions/types.ts
1631
+ var _ExtensionTemplateManager = class extends import_extensibility_tool_utils._TemplateManager {
1632
+ /**
1633
+ * Get summary info for all registered extension templates
1634
+ */
1635
+ getTemplateInfo() {
1636
+ return this.getTemplateEntries().map(([key, t]) => ({
1637
+ key,
1638
+ description: t.description,
1639
+ deprecated: t.deprecated ?? false,
1640
+ hidden: t.hidden ?? false,
1641
+ methods: t.methods
1642
+ }));
1643
+ }
1644
+ };
1645
+
1646
+ // src/dependencies/index.ts
1647
+ var import_node_path2 = __toESM(require("path"), 1);
1648
+ var import_node_fs = __toESM(require("fs"), 1);
1649
+ var import_node_os = __toESM(require("os"), 1);
1650
+ var import_node_child_process = require("child_process");
1651
+ var import_package_json = __toESM(require("@npmcli/package-json"), 1);
1652
+ var semver = __toESM(require("semver"), 1);
1653
+ var import_js_toml = require("js-toml");
1654
+ var import_extensibility_tool_utils6 = require("@stripe/extensibility-tool-utils");
1655
+ function _npmDep(name, version) {
1656
+ return { type: "npm", name, version };
1657
+ }
1658
+ function _devNpmDep(name, version) {
1659
+ return { type: "dev-npm", name, version };
1660
+ }
1661
+ function _stripeCliPluginDep(name, minVersion) {
1662
+ return minVersion ? { type: "stripe-cli-plugin", name, minVersion } : { type: "stripe-cli-plugin", name };
1663
+ }
1664
+ function _detectPackageManager(cwd) {
1665
+ if (import_node_fs.default.existsSync(import_node_path2.default.join(cwd, "pnpm-lock.yaml"))) {
1666
+ return "pnpm";
1667
+ }
1668
+ if (import_node_fs.default.existsSync(import_node_path2.default.join(cwd, "yarn.lock"))) {
1669
+ return "yarn";
1670
+ }
1671
+ if (import_node_fs.default.existsSync(import_node_path2.default.join(cwd, "package-lock.json"))) {
1672
+ return "npm";
1673
+ }
1674
+ let currentDir = cwd;
1675
+ const root = import_node_path2.default.parse(currentDir).root;
1676
+ while (currentDir !== root) {
1677
+ const parentDir = import_node_path2.default.dirname(currentDir);
1678
+ if (parentDir === currentDir) break;
1679
+ if (import_node_fs.default.existsSync(import_node_path2.default.join(parentDir, "pnpm-lock.yaml"))) {
1680
+ if (import_node_fs.default.existsSync(import_node_path2.default.join(parentDir, "pnpm-workspace.yaml"))) {
1681
+ return "pnpm";
1682
+ }
1683
+ }
1684
+ if (import_node_fs.default.existsSync(import_node_path2.default.join(parentDir, "yarn.lock"))) {
1685
+ return "yarn";
1686
+ }
1687
+ if (import_node_fs.default.existsSync(import_node_path2.default.join(parentDir, "package-lock.json"))) {
1688
+ return "npm";
1689
+ }
1690
+ currentDir = parentDir;
1691
+ }
1692
+ return "npm";
1693
+ }
1694
+ var _NpmDependencyHandler = class {
1695
+ cwd;
1696
+ quiet;
1697
+ devDependencies;
1698
+ context;
1699
+ constructor(options) {
1700
+ this.cwd = options.cwd;
1701
+ this.quiet = options.quiet;
1702
+ this.devDependencies = options.devDependencies ?? false;
1703
+ this.context = options.context ?? (0, import_extensibility_tool_utils6._createCliContext)();
1704
+ }
1705
+ get dependencyKey() {
1706
+ return this.devDependencies ? "devDependencies" : "dependencies";
1707
+ }
1708
+ get dependencyLabel() {
1709
+ return this.devDependencies ? "devDependencies" : "dependencies";
1710
+ }
1711
+ /** Check whether the npm dependency is already present in package.json. */
1712
+ async check(dep) {
1713
+ const packageJsonPath = import_node_path2.default.join(this.cwd, "package.json");
1714
+ if (!import_node_fs.default.existsSync(packageJsonPath)) {
1715
+ return {
1716
+ satisfied: false,
1717
+ message: `package.json not found at ${this.cwd}`
1718
+ };
1719
+ }
1720
+ const pkgJson = await import_package_json.default.load(this.cwd);
1721
+ const rawDeps = pkgJson.content[this.dependencyKey];
1722
+ const deps = rawDeps ?? {};
1723
+ const currentVersion = deps[dep.name];
1724
+ if (currentVersion === void 0) {
1725
+ return {
1726
+ satisfied: false,
1727
+ message: `${dep.name} not found in ${this.dependencyLabel}`
1728
+ };
1729
+ }
1730
+ if (currentVersion === dep.version) {
1731
+ return {
1732
+ satisfied: true,
1733
+ currentVersion,
1734
+ message: `${dep.name}@${dep.version} already in ${this.dependencyLabel}`
1735
+ };
1736
+ }
1737
+ if (this.versionsCompatible(currentVersion, dep.version)) {
1738
+ return {
1739
+ satisfied: true,
1740
+ currentVersion,
1741
+ message: `${dep.name}@${currentVersion} satisfies ${dep.version}`
1742
+ };
1743
+ }
1744
+ return {
1745
+ satisfied: false,
1746
+ currentVersion,
1747
+ message: `${dep.name}@${currentVersion} does not satisfy ${dep.version}`
1748
+ };
1749
+ }
1750
+ /** Check whether the requested version conflicts with the currently installed version. */
1751
+ async checkConflict(dep) {
1752
+ const packageJsonPath = import_node_path2.default.join(this.cwd, "package.json");
1753
+ if (!import_node_fs.default.existsSync(packageJsonPath)) {
1754
+ return { hasConflict: false };
1755
+ }
1756
+ const pkgJson = await import_package_json.default.load(this.cwd);
1757
+ const rawDeps = pkgJson.content[this.dependencyKey];
1758
+ const deps = rawDeps ?? {};
1759
+ const existingVersion = deps[dep.name];
1760
+ if (existingVersion === void 0) {
1761
+ return { hasConflict: false };
1762
+ }
1763
+ if (existingVersion === dep.version) {
1764
+ return { hasConflict: false };
1765
+ }
1766
+ const existingMajor = this.extractMajorVersion(existingVersion);
1767
+ const requestedMajor = this.extractMajorVersion(dep.version);
1768
+ if (existingMajor !== null && requestedMajor !== null && existingMajor !== requestedMajor) {
1769
+ return {
1770
+ hasConflict: true,
1771
+ existingVersion,
1772
+ requestedVersion: dep.version,
1773
+ message: `Major version mismatch: existing ${existingVersion} vs requested ${dep.version}`
1774
+ };
1775
+ }
1776
+ if (!this.versionsCompatible(existingVersion, dep.version)) {
1777
+ return {
1778
+ hasConflict: true,
1779
+ existingVersion,
1780
+ requestedVersion: dep.version,
1781
+ message: `Incompatible version ranges: existing ${existingVersion} vs requested ${dep.version}`
1782
+ };
1783
+ }
1784
+ return { hasConflict: false };
1785
+ }
1786
+ /** Add or update the npm dependency in package.json. */
1787
+ async add(dep) {
1788
+ const packageJsonPath = import_node_path2.default.join(this.cwd, "package.json");
1789
+ if (!import_node_fs.default.existsSync(packageJsonPath)) {
1790
+ throw new Error(`package.json not found at ${this.cwd}`);
1791
+ }
1792
+ const pkgJson = await import_package_json.default.load(this.cwd);
1793
+ const rawDeps = pkgJson.content[this.dependencyKey];
1794
+ const deps = rawDeps ?? {};
1795
+ const existingVersion = deps[dep.name];
1796
+ const isUpdate = existingVersion !== void 0;
1797
+ const update = {
1798
+ [this.dependencyKey]: {
1799
+ ...deps,
1800
+ [dep.name]: dep.version
1801
+ }
1802
+ };
1803
+ pkgJson.update(update);
1804
+ await pkgJson.save();
1805
+ const action = isUpdate ? "update" : "add";
1806
+ const message = isUpdate ? `Updated ${dep.name} from ${existingVersion} to ${dep.version} in ${this.dependencyLabel}` : `Added ${dep.name}@${dep.version} to ${this.dependencyLabel}`;
1807
+ if (!this.quiet) {
1808
+ this.context.ux.log(`\u2713 ${message}`);
1809
+ }
1810
+ return { action, message };
1811
+ }
1812
+ /** Run the package manager install command in the working directory. */
1813
+ install(_deps) {
1814
+ const packageManager = _detectPackageManager(this.cwd);
1815
+ if (!this.quiet) {
1816
+ this.context.ux.log(`Running ${packageManager} install...`);
1817
+ }
1818
+ try {
1819
+ (0, import_node_child_process.execSync)(`${packageManager} install`, {
1820
+ cwd: this.cwd,
1821
+ stdio: this.quiet ? "pipe" : "inherit"
1822
+ });
1823
+ } catch (error) {
1824
+ const baseMessage = `Failed to run ${packageManager} install`;
1825
+ if (error instanceof Error) {
1826
+ return Promise.reject(new Error(`${baseMessage}: ${error.message}`));
1827
+ }
1828
+ return Promise.reject(new Error(`${baseMessage}: ${String(error)}`));
1829
+ }
1830
+ return Promise.resolve();
1831
+ }
1832
+ versionsCompatible(existing, requested) {
1833
+ if (existing.startsWith("file:") || requested.startsWith("file:") || existing.startsWith("workspace:") || requested.startsWith("workspace:")) {
1834
+ return existing === requested;
1835
+ }
1836
+ if (!semver.validRange(existing) || !semver.validRange(requested)) {
1837
+ return existing === requested;
1838
+ }
1839
+ return semver.intersects(existing, requested);
1840
+ }
1841
+ extractMajorVersion(version) {
1842
+ if (version.startsWith("file:") || version.startsWith("workspace:")) {
1843
+ return null;
1844
+ }
1845
+ const coerced = semver.coerce(version);
1846
+ if (coerced) {
1847
+ return coerced.major;
1848
+ }
1849
+ return null;
1850
+ }
1851
+ };
1852
+ var _StripeCliPluginHandler = class {
1853
+ stripeConfigDir;
1854
+ quiet;
1855
+ context;
1856
+ constructor(options) {
1857
+ this.stripeConfigDir = options.stripeConfigDir;
1858
+ this.quiet = options.quiet;
1859
+ this.context = options.context ?? (0, import_extensibility_tool_utils6._createCliContext)();
1860
+ }
1861
+ /** Check whether the Stripe CLI plugin is installed and meets the minimum version. */
1862
+ check(dep) {
1863
+ const pluginsTomlPath = import_node_path2.default.join(this.stripeConfigDir, "plugins.toml");
1864
+ if (!import_node_fs.default.existsSync(pluginsTomlPath)) {
1865
+ return Promise.resolve({
1866
+ satisfied: false,
1867
+ message: `Stripe CLI plugin '${dep.name}' is not installed (plugins.toml not found)`
1868
+ });
1869
+ }
1870
+ const pluginsContent = import_node_fs.default.readFileSync(pluginsTomlPath, "utf-8");
1871
+ const installedPlugin = this.findPluginInToml(pluginsContent, dep.name);
1872
+ if (!installedPlugin) {
1873
+ return Promise.resolve({
1874
+ satisfied: false,
1875
+ message: `Stripe CLI plugin '${dep.name}' is not installed`
1876
+ });
1877
+ }
1878
+ if (dep.minVersion && installedPlugin.version) {
1879
+ if (!this.isVersionSatisfied(installedPlugin.version, dep.minVersion)) {
1880
+ return Promise.resolve({
1881
+ satisfied: false,
1882
+ currentVersion: installedPlugin.version,
1883
+ message: `Stripe CLI plugin '${dep.name}' version ${installedPlugin.version} is below minimum ${dep.minVersion}`
1884
+ });
1885
+ }
1886
+ }
1887
+ const result = {
1888
+ satisfied: true,
1889
+ message: `Stripe CLI plugin '${dep.name}' is installed${installedPlugin.version ? ` (version ${installedPlugin.version})` : ""}`
1890
+ };
1891
+ if (installedPlugin.version) {
1892
+ result.currentVersion = installedPlugin.version;
1893
+ }
1894
+ return Promise.resolve(result);
1895
+ }
1896
+ /** Check whether the installed plugin version conflicts with the requested minimum. */
1897
+ async checkConflict(dep) {
1898
+ const checkResult = await this.check(dep);
1899
+ if (checkResult.satisfied) {
1900
+ return { hasConflict: false };
1901
+ }
1902
+ if (checkResult.currentVersion && dep.minVersion) {
1903
+ return {
1904
+ hasConflict: true,
1905
+ existingVersion: checkResult.currentVersion,
1906
+ requestedVersion: dep.minVersion,
1907
+ message: `Installed version ${checkResult.currentVersion} is below minimum ${dep.minVersion}`
1908
+ };
1909
+ }
1910
+ return { hasConflict: false };
1911
+ }
1912
+ /** Stage a Stripe CLI plugin for installation; the actual install happens in `install`. */
1913
+ async add(dep) {
1914
+ const checkResult = await this.check(dep);
1915
+ const isUpdate = checkResult.currentVersion !== void 0;
1916
+ const action = isUpdate ? "update" : "add";
1917
+ const message = isUpdate ? `Will update Stripe CLI plugin '${dep.name}'` : `Will install Stripe CLI plugin '${dep.name}'`;
1918
+ return { action, message };
1919
+ }
1920
+ /** Install Stripe CLI plugins using `stripe plugin install`. */
1921
+ async install(deps) {
1922
+ for (const dep of deps) {
1923
+ const checkResult = await this.check(dep);
1924
+ const isUpdate = checkResult.currentVersion !== void 0;
1925
+ try {
1926
+ (0, import_node_child_process.execSync)(`stripe plugin install ${dep.name}`, {
1927
+ stdio: this.quiet ? "pipe" : "inherit"
1928
+ });
1929
+ const message = isUpdate ? `Updated Stripe CLI plugin '${dep.name}'` : `Installed Stripe CLI plugin '${dep.name}'`;
1930
+ if (!this.quiet) {
1931
+ this.context.ux.log(`\u2713 ${message}`);
1932
+ }
1933
+ } catch (error) {
1934
+ const baseMessage = `Failed to install Stripe CLI plugin '${dep.name}'`;
1935
+ if (error instanceof Error) {
1936
+ throw new Error(`${baseMessage}: ${error.message}`);
1937
+ }
1938
+ throw new Error(`${baseMessage}: ${String(error)}`);
1939
+ }
1940
+ }
1941
+ }
1942
+ findPluginInToml(content, pluginName) {
1943
+ try {
1944
+ const parsed = (0, import_js_toml.load)(content);
1945
+ const plugins = parsed.Plugin;
1946
+ if (!plugins || !Array.isArray(plugins)) {
1947
+ return null;
1948
+ }
1949
+ const plugin = plugins.find((p) => p.Shortname === pluginName);
1950
+ if (!plugin) {
1951
+ return null;
1952
+ }
1953
+ if (plugin.Release && Array.isArray(plugin.Release) && plugin.Release.length > 0) {
1954
+ const currentArch = import_node_os.default.arch();
1955
+ const currentOS = import_node_os.default.platform();
1956
+ const normalizedArch = currentArch === "x64" ? "amd64" : currentArch;
1957
+ const normalizedOS = currentOS === "win32" ? "windows" : currentOS;
1958
+ const platformReleases = plugin.Release.filter(
1959
+ (r) => r.Arch === normalizedArch && r.OS === normalizedOS
1960
+ );
1961
+ if (platformReleases.length === 0) {
1962
+ return null;
1963
+ }
1964
+ const localBuildRelease = platformReleases.find(
1965
+ (r) => r.Version === "local.build.dev"
1966
+ );
1967
+ if (localBuildRelease) {
1968
+ return { version: "local.build.dev" };
1969
+ }
1970
+ const versions = platformReleases.map((r) => r.Version).filter((v) => v !== void 0);
1971
+ if (versions.length === 0) {
1972
+ return null;
1973
+ }
1974
+ const sortedVersions = versions.map((v) => ({ original: v, parsed: semver.coerce(v) })).filter(
1975
+ (v) => v.parsed !== null
1976
+ ).sort((a, b) => semver.rcompare(a.parsed, b.parsed));
1977
+ if (sortedVersions.length === 0) {
1978
+ return { version: versions[0] };
1979
+ }
1980
+ return { version: sortedVersions[0]?.original };
1981
+ }
1982
+ return { version: plugin.Version };
1983
+ } catch {
1984
+ return null;
1985
+ }
1986
+ }
1987
+ /**
1988
+ * Check if installed version satisfies the required minimum version.
1989
+ *
1990
+ * Permissive policy: Non-semver versions (e.g., "local.build.dev", "dev", "canary-abc123")
1991
+ * always satisfy version requirements. This avoids forcing upgrades during local development
1992
+ * when developers are using locally built plugins.
1993
+ *
1994
+ * For valid semver versions, uses the semver library for proper semantic version comparison.
1995
+ *
1996
+ * @param installed - The installed version string
1997
+ * @param required - The required minimum version string
1998
+ * @returns true if installed version satisfies requirement
1999
+ */
2000
+ isVersionSatisfied(installed, required) {
2001
+ const installedSemver = semver.coerce(installed);
2002
+ const requiredSemver = semver.coerce(required);
2003
+ if (!installedSemver) {
2004
+ return true;
2005
+ }
2006
+ if (!requiredSemver) {
2007
+ return true;
2008
+ }
2009
+ return semver.gte(installedSemver, requiredSemver);
2010
+ }
2011
+ };
2012
+ function dependencyKey(dep) {
2013
+ return `${dep.type}:${dep.name}`;
2014
+ }
2015
+ var _DependencyManager = class {
2016
+ cwd;
2017
+ stripeConfigDir;
2018
+ quiet;
2019
+ context;
2020
+ npmHandler;
2021
+ devNpmHandler;
2022
+ stripeCliPluginHandler;
2023
+ /** Internal state: pending changes indexed by dependency key */
2024
+ pendingChanges = /* @__PURE__ */ new Map();
2025
+ /** Whether commit() has been called */
2026
+ committed = false;
2027
+ constructor(options = {}) {
2028
+ this.cwd = options.cwd ?? process.cwd();
2029
+ this.stripeConfigDir = options.stripeConfigDir ?? import_node_path2.default.join(import_node_os.default.homedir(), ".config", "stripe");
2030
+ this.quiet = options.quiet ?? false;
2031
+ this.context = options.context ?? (0, import_extensibility_tool_utils6._createCliContext)();
2032
+ this.npmHandler = new _NpmDependencyHandler({
2033
+ cwd: this.cwd,
2034
+ quiet: this.quiet,
2035
+ devDependencies: false,
2036
+ context: this.context
2037
+ });
2038
+ this.devNpmHandler = new _NpmDependencyHandler({
2039
+ cwd: this.cwd,
2040
+ quiet: this.quiet,
2041
+ devDependencies: true,
2042
+ context: this.context
2043
+ });
2044
+ this.stripeCliPluginHandler = new _StripeCliPluginHandler({
2045
+ stripeConfigDir: this.stripeConfigDir,
2046
+ quiet: this.quiet,
2047
+ context: this.context
2048
+ });
2049
+ }
2050
+ /**
2051
+ * Analyze dependencies and accumulate changes.
2052
+ * Can be called multiple times before commit().
2053
+ * Returns the changes for this specific call.
2054
+ */
2055
+ async ensureDependencies(input) {
2056
+ if (this.committed) {
2057
+ throw new Error("DependencyManager has already been committed");
2058
+ }
2059
+ const { required, optional = [] } = input;
2060
+ const changes = [];
2061
+ for (const dep of [...required, ...optional]) {
2062
+ const change = await this.analyzeDependency(dep);
2063
+ changes.push(change);
2064
+ this.pendingChanges.set(dependencyKey(dep), change);
2065
+ }
2066
+ return changes;
2067
+ }
2068
+ /**
2069
+ * Resolve a conflict by marking it for force install.
2070
+ * Throws if the dependency is not in conflict state.
2071
+ */
2072
+ resolveConflict(dep) {
2073
+ if (this.committed) {
2074
+ throw new Error("DependencyManager has already been committed");
2075
+ }
2076
+ const key = dependencyKey(dep);
2077
+ const change = this.pendingChanges.get(key);
2078
+ if (!change) {
2079
+ throw new Error(`Dependency '${dep.name}' not found in pending changes`);
2080
+ }
2081
+ if (change.action !== "conflict") {
2082
+ throw new Error(
2083
+ `Dependency '${dep.name}' is not in conflict (action: ${change.action})`
2084
+ );
2085
+ }
2086
+ change.conflictResolved = true;
2087
+ }
2088
+ /**
2089
+ * Get all pending changes (accumulated across all ensureDependencies calls).
2090
+ */
2091
+ getPendingChanges() {
2092
+ return Array.from(this.pendingChanges.values());
2093
+ }
2094
+ /**
2095
+ * Commit all accumulated changes.
2096
+ * - For npm deps: updates package.json, optionally runs package manager install
2097
+ * - For Stripe CLI deps: always installs (no separate add step)
2098
+ *
2099
+ * @param options - Commit options. `options.runInstall`: if true, run package manager install for npm deps (default: true)
2100
+ * @returns Summary of changes made
2101
+ * @throws If called more than once
2102
+ */
2103
+ async commit(options = {}) {
2104
+ if (this.committed) {
2105
+ throw new Error("DependencyManager has already been committed");
2106
+ }
2107
+ this.committed = true;
2108
+ const { runInstall = true } = options;
2109
+ let added = 0;
2110
+ let updated = 0;
2111
+ const npmDeps = [];
2112
+ const stripeCliDeps = [];
2113
+ for (const change of this.pendingChanges.values()) {
2114
+ if (change.action === "already-satisfied") {
2115
+ continue;
2116
+ }
2117
+ if (change.action === "conflict" && !change.conflictResolved) {
2118
+ continue;
2119
+ }
2120
+ const dep = change.dependency;
2121
+ if (dep.type === "npm" || dep.type === "dev-npm") {
2122
+ npmDeps.push(dep);
2123
+ } else {
2124
+ stripeCliDeps.push(dep);
2125
+ }
2126
+ }
2127
+ for (const dep of npmDeps) {
2128
+ const handler = dep.type === "npm" ? this.npmHandler : this.devNpmHandler;
2129
+ const result = await handler.add(dep);
2130
+ if (result.action === "add") {
2131
+ added++;
2132
+ } else {
2133
+ updated++;
2134
+ }
2135
+ }
2136
+ if (runInstall && npmDeps.length > 0) {
2137
+ await this.npmHandler.install(npmDeps);
2138
+ }
2139
+ if (stripeCliDeps.length > 0) {
2140
+ await this.stripeCliPluginHandler.install(stripeCliDeps);
2141
+ for (const dep of stripeCliDeps) {
2142
+ const change = this.pendingChanges.get(dependencyKey(dep));
2143
+ if (change?.action === "add" || change?.action === "conflict" && !change.previousVersion) {
2144
+ added++;
2145
+ } else {
2146
+ updated++;
2147
+ }
2148
+ }
2149
+ }
2150
+ return { added, updated };
2151
+ }
2152
+ async analyzeDependency(dep) {
2153
+ const handler = this.getHandler(dep);
2154
+ const checkResult = await handler.check(dep);
2155
+ if (checkResult.satisfied) {
2156
+ return {
2157
+ dependency: dep,
2158
+ action: "already-satisfied",
2159
+ message: checkResult.message
2160
+ };
2161
+ }
2162
+ const conflictResult = await handler.checkConflict(dep);
2163
+ if (conflictResult.hasConflict) {
2164
+ const result2 = {
2165
+ dependency: dep,
2166
+ action: "conflict",
2167
+ message: conflictResult.message ?? "Dependency conflict detected",
2168
+ conflict: conflictResult
2169
+ };
2170
+ if (conflictResult.existingVersion) {
2171
+ result2.previousVersion = conflictResult.existingVersion;
2172
+ }
2173
+ return result2;
2174
+ }
2175
+ const isUpdate = checkResult.currentVersion !== void 0;
2176
+ const result = {
2177
+ dependency: dep,
2178
+ action: isUpdate ? "update" : "add",
2179
+ message: isUpdate ? `Will update ${dep.name} from ${String(checkResult.currentVersion)}` : `Will add ${dep.name}`
2180
+ };
2181
+ if (checkResult.currentVersion) {
2182
+ result.previousVersion = checkResult.currentVersion;
2183
+ }
2184
+ return result;
2185
+ }
2186
+ getHandler(dep) {
2187
+ switch (dep.type) {
2188
+ case "npm":
2189
+ return this.npmHandler;
2190
+ case "dev-npm":
2191
+ return this.devNpmHandler;
2192
+ case "stripe-cli-plugin":
2193
+ return this.stripeCliPluginHandler;
2194
+ }
2195
+ }
2196
+ };
2197
+
2198
+ // src/templates/extensions/base.ts
2199
+ var import_extensibility_tool_utils7 = require("@stripe/extensibility-tool-utils");
2200
+ var SDK_PACKAGE_NAME = "@stripe/extensibility-sdk";
2201
+ var LANGUAGE_SERVER_PACKAGE_NAME = "@stripe/extensibility-language-server";
2202
+ var LANGUAGE_SERVER_PACKAGE_VERSION = "^0.2.0";
2203
+ function _createExtensionEslintConfigFile(params, context) {
2204
+ const { id, extensionInterfaceId } = params;
2205
+ const { fs: fs2 } = context;
2206
+ return {
2207
+ path: `extensions/${id}/eslint.config.mts`,
2208
+ content: fs2.mustache(
2209
+ { extensionInterfaceId },
2210
+ "common",
2211
+ "eslint.config.mts.mustache"
2212
+ ),
2213
+ precious: true
2214
+ };
2215
+ }
2216
+ function _createBaseOutput(params, context) {
2217
+ const { id } = params;
2218
+ const { fs: fs2 } = context;
2219
+ return {
2220
+ files: [
2221
+ {
2222
+ path: `extensions/${id}/package.json`,
2223
+ content: fs2.mustache(params, "common", "package.json.mustache")
2224
+ },
2225
+ {
2226
+ ..._createExtensionEslintConfigFile(params, context)
2227
+ },
2228
+ {
2229
+ path: `extensions/${id}/tsconfig.build.json`,
2230
+ content: fs2.mustache(params, "common", "tsconfig.build.json.mustache")
2231
+ },
2232
+ {
2233
+ path: `extensions/${id}/tsconfig.json`,
2234
+ content: fs2.mustache(params, "common", "tsconfig.json.mustache")
2235
+ },
2236
+ {
2237
+ path: `extensions/${id}/.prettierignore`,
2238
+ content: fs2.textFile("common", ".prettierignore")
2239
+ }
2240
+ ],
2241
+ methods: {},
2242
+ dependencies: {
2243
+ // Exact pin (no caret) — the SDK is tightly coupled to dev-tools and
2244
+ // must match the version that generated the extension scaffolding.
2245
+ runtime: [_npmDep(SDK_PACKAGE_NAME, (0, import_extensibility_tool_utils7._workspaceVersion)(SDK_PACKAGE_NAME))],
2246
+ dev: [_devNpmDep(LANGUAGE_SERVER_PACKAGE_NAME, LANGUAGE_SERVER_PACKAGE_VERSION)]
2247
+ },
2248
+ postGenerationHooks: [
2249
+ {
2250
+ script: "build",
2251
+ description: "Build extension"
2252
+ },
2253
+ {
2254
+ exec: "prettier --write .",
2255
+ description: "Format generated files"
2256
+ }
2257
+ ]
2258
+ };
2259
+ }
2260
+
2261
+ // src/templates/extensions/core.workflows.custom_action.ts
2262
+ var EXTENSION_INTERFACE_ID = "core.workflows.custom_action";
2263
+ var customActionTemplate = {
2264
+ methods: {
2265
+ execute: { implementation_types: ["script", "remote-function"] },
2266
+ get_form_state: { implementation_types: ["script", "remote-function"] }
2267
+ },
2268
+ description: "Custom actions let your app define actions that users can add to their automated workflows. When a workflow triggers a custom action, Stripe calls your app to execute it.",
2269
+ generate: (params, context) => {
2270
+ const { id } = params;
2271
+ const { fs: fs2 } = context;
2272
+ const base = _createBaseOutput(
2273
+ {
2274
+ ...params,
2275
+ extensionInterfaceId: EXTENSION_INTERFACE_ID,
2276
+ executionProfile: "egress"
2277
+ },
2278
+ context
2279
+ );
2280
+ return {
2281
+ ...base,
2282
+ files: [
2283
+ {
2284
+ path: `extensions/${id}/src/index.ts`,
2285
+ content: fs2.textFile(EXTENSION_INTERFACE_ID, "index.ts"),
2286
+ precious: true
2287
+ },
2288
+ {
2289
+ path: `extensions/${id}/src/custom_input.schema.json`,
2290
+ content: fs2.textFile(EXTENSION_INTERFACE_ID, "custom_input.schema.json"),
2291
+ precious: true
2292
+ },
2293
+ {
2294
+ path: `extensions/${id}/src/index.test.ts`,
2295
+ content: fs2.textFile(EXTENSION_INTERFACE_ID, "index.test.ts"),
2296
+ precious: true
2297
+ },
2298
+ ...base.files
2299
+ ],
2300
+ methods: {
2301
+ execute: {
2302
+ implementation_type: "script",
2303
+ custom_input: {
2304
+ input_schema: {
2305
+ type: "json_schema",
2306
+ content: `extensions/${id}/src/custom_input.schema.json`
2307
+ }
2308
+ }
2309
+ },
2310
+ get_form_state: {
2311
+ implementation_type: "script"
2312
+ }
2313
+ }
2314
+ };
2315
+ }
2316
+ };
2317
+ var core_workflows_custom_action_default = {
2318
+ [EXTENSION_INTERFACE_ID]: customActionTemplate
2319
+ };
2320
+
2321
+ // src/templates/extensions/extend.objects.custom_objects.ts
2322
+ var EXTENSION_INTERFACE_ID2 = "extend.objects.custom_objects";
2323
+ var customObjectsTemplate = {
2324
+ methods: {
2325
+ execute_method: { implementation_types: ["script"] }
2326
+ },
2327
+ description: "Methods extension for custom object actions. Generated at build time \u2014 the transformed custom object class becomes the entry point.",
2328
+ hidden: true,
2329
+ generate: (params, context) => {
2330
+ const base = _createBaseOutput(
2331
+ {
2332
+ ...params,
2333
+ extensionInterfaceId: EXTENSION_INTERFACE_ID2,
2334
+ executionProfile: "egress"
2335
+ },
2336
+ context
2337
+ );
2338
+ return {
2339
+ ...base,
2340
+ methods: {
2341
+ execute_method: {
2342
+ implementation_type: "script"
2343
+ }
2344
+ }
2345
+ };
2346
+ }
2347
+ };
2348
+ var extend_objects_custom_objects_default = {
2349
+ [EXTENSION_INTERFACE_ID2]: customObjectsTemplate
2350
+ };
2351
+
2352
+ // src/templates/extensions/extend.workflows.custom_action.ts
2353
+ var EXTENSION_INTERFACE_ID3 = "extend.workflows.custom_action";
2354
+ var extendCustomActionTemplate = {
2355
+ methods: {
2356
+ execute: { implementation_types: ["script", "remote-function"] },
2357
+ get_form_state: { implementation_types: ["script", "remote-function"] }
2358
+ },
2359
+ description: "Custom actions let your app define actions that users can add to their automated workflows. When a workflow triggers a custom action, Stripe calls your app to execute it.",
2360
+ generate: (params, context) => {
2361
+ const { id } = params;
2362
+ const { fs: fs2 } = context;
2363
+ const base = _createBaseOutput(
2364
+ {
2365
+ ...params,
2366
+ extensionInterfaceId: EXTENSION_INTERFACE_ID3,
2367
+ executionProfile: "egress"
2368
+ },
2369
+ context
2370
+ );
2371
+ return {
2372
+ ...base,
2373
+ files: [
2374
+ {
2375
+ path: `extensions/${id}/src/index.ts`,
2376
+ content: fs2.textFile(EXTENSION_INTERFACE_ID3, "index.ts"),
2377
+ precious: true
2378
+ },
2379
+ {
2380
+ path: `extensions/${id}/src/custom_input.schema.json`,
2381
+ content: fs2.textFile(EXTENSION_INTERFACE_ID3, "custom_input.schema.json"),
2382
+ precious: true
2383
+ },
2384
+ {
2385
+ path: `extensions/${id}/src/index.test.ts`,
2386
+ content: fs2.textFile(EXTENSION_INTERFACE_ID3, "index.test.ts"),
2387
+ precious: true
2388
+ },
2389
+ ...base.files
2390
+ ],
2391
+ methods: {
2392
+ execute: {
2393
+ implementation_type: "script",
2394
+ custom_input: {
2395
+ input_schema: {
2396
+ type: "json_schema",
2397
+ content: `extensions/${id}/src/custom_input.schema.json`
2398
+ }
2399
+ }
2400
+ },
2401
+ get_form_state: {
2402
+ implementation_type: "script"
2403
+ }
2404
+ }
2405
+ };
2406
+ }
2407
+ };
2408
+ var extend_workflows_custom_action_default = {
2409
+ [EXTENSION_INTERFACE_ID3]: extendCustomActionTemplate
2410
+ };
2411
+
2412
+ // src/templates/extensions/billing.customer_balance_application.ts
2413
+ var EXTENSION_INTERFACE_ID4 = "billing.customer_balance_application";
2414
+ var customerBalanceApplicationTemplate = {
2415
+ methods: {
2416
+ compute_applied_customer_balance: { implementation_types: ["script"] }
2417
+ },
2418
+ description: "Implement custom logic to control when and how much customer balance is applied to subscription invoices using scripts.",
2419
+ generate: (params, context) => {
2420
+ const { id } = params;
2421
+ const { fs: fs2 } = context;
2422
+ const base = _createBaseOutput(
2423
+ {
2424
+ ...params,
2425
+ extensionInterfaceId: EXTENSION_INTERFACE_ID4,
2426
+ executionProfile: "restricted"
2427
+ },
2428
+ context
2429
+ );
2430
+ return {
2431
+ ...base,
2432
+ files: [
2433
+ {
2434
+ path: `extensions/${id}/src/index.ts`,
2435
+ content: fs2.textFile(EXTENSION_INTERFACE_ID4, "index.ts"),
2436
+ precious: true
2437
+ },
2438
+ {
2439
+ path: `extensions/${id}/src/index.test.ts`,
2440
+ content: fs2.textFile(EXTENSION_INTERFACE_ID4, "index.test.ts"),
2441
+ precious: true
2442
+ },
2443
+ ...base.files
2444
+ ],
2445
+ methods: {
2446
+ compute_applied_customer_balance: {
2447
+ implementation_type: "script"
2448
+ }
2449
+ }
2450
+ };
2451
+ }
2452
+ };
2453
+ var billing_customer_balance_application_default = {
2454
+ [EXTENSION_INTERFACE_ID4]: customerBalanceApplicationTemplate
2455
+ };
2456
+
2457
+ // src/templates/extensions/billing.bill.discount_calculation.ts
2458
+ var EXTENSION_INTERFACE_ID5 = "billing.bill.discount_calculation";
2459
+ var discountCalculationTemplate = {
2460
+ hidden: true,
2461
+ methods: {
2462
+ compute_discounts: { implementation_types: ["script"] }
2463
+ },
2464
+ description: "Create coupons with custom scripting logic for dynamic discounts based on subscription attributes, customer metadata, and complex business rules.",
2465
+ generate: (params, context) => {
2466
+ const { id } = params;
2467
+ const { fs: fs2 } = context;
2468
+ const base = _createBaseOutput(
2469
+ {
2470
+ ...params,
2471
+ extensionInterfaceId: EXTENSION_INTERFACE_ID5,
2472
+ executionProfile: "restricted"
2473
+ },
2474
+ context
2475
+ );
2476
+ return {
2477
+ ...base,
2478
+ files: [
2479
+ {
2480
+ path: `extensions/${id}/src/index.ts`,
2481
+ content: fs2.textFile(EXTENSION_INTERFACE_ID5, "index.ts"),
2482
+ precious: true
2483
+ },
2484
+ {
2485
+ path: `extensions/${id}/src/index.test.ts`,
2486
+ content: fs2.textFile(EXTENSION_INTERFACE_ID5, "index.test.ts"),
2487
+ precious: true
2488
+ },
2489
+ ...base.files
2490
+ ],
2491
+ methods: {
2492
+ compute_discounts: {
2493
+ implementation_type: "script"
2494
+ }
2495
+ }
2496
+ };
2497
+ }
2498
+ };
2499
+ var billing_bill_discount_calculation_default = {
2500
+ [EXTENSION_INTERFACE_ID5]: discountCalculationTemplate
2501
+ };
2502
+
2503
+ // src/templates/extensions/billing.invoice_collection_setting.ts
2504
+ var EXTENSION_INTERFACE_ID6 = "billing.invoice_collection_setting";
2505
+ var invoiceCollectionSettingTemplate = {
2506
+ hidden: true,
2507
+ methods: {
2508
+ collection_override: { implementation_types: ["script"] }
2509
+ },
2510
+ description: "Use Stripe Scripts to create custom invoice collection logic that controls how your integration handles invoices generated from subscriptions.",
2511
+ generate: (params, context) => {
2512
+ const { id } = params;
2513
+ const { fs: fs2 } = context;
2514
+ const base = _createBaseOutput(
2515
+ {
2516
+ ...params,
2517
+ extensionInterfaceId: EXTENSION_INTERFACE_ID6,
2518
+ executionProfile: "restricted"
2519
+ },
2520
+ context
2521
+ );
2522
+ return {
2523
+ ...base,
2524
+ files: [
2525
+ {
2526
+ path: `extensions/${id}/src/index.ts`,
2527
+ content: fs2.textFile(EXTENSION_INTERFACE_ID6, "index.ts"),
2528
+ precious: true
2529
+ },
2530
+ {
2531
+ path: `extensions/${id}/src/index.test.ts`,
2532
+ content: fs2.textFile(EXTENSION_INTERFACE_ID6, "index.test.ts"),
2533
+ precious: true
2534
+ },
2535
+ ...base.files
2536
+ ],
2537
+ methods: {
2538
+ collection_override: {
2539
+ implementation_type: "script"
2540
+ }
2541
+ }
2542
+ };
2543
+ }
2544
+ };
2545
+ var billing_invoice_collection_setting_default = {
2546
+ [EXTENSION_INTERFACE_ID6]: invoiceCollectionSettingTemplate
2547
+ };
2548
+
2549
+ // src/templates/extensions/billing.prorations.ts
2550
+ var EXTENSION_INTERFACE_ID7 = "billing.prorations";
2551
+ var prorationsTemplate = {
2552
+ methods: {
2553
+ prorate_items: { implementation_types: ["script"] }
2554
+ },
2555
+ description: "Create custom proration logic for subscriptions using scripts to handle upgrades, downgrades, and mid-cycle changes.",
2556
+ generate: (params, context) => {
2557
+ const { id } = params;
2558
+ const { fs: fs2 } = context;
2559
+ const base = _createBaseOutput(
2560
+ {
2561
+ ...params,
2562
+ extensionInterfaceId: EXTENSION_INTERFACE_ID7,
2563
+ executionProfile: "restricted"
2564
+ },
2565
+ context
2566
+ );
2567
+ return {
2568
+ ...base,
2569
+ files: [
2570
+ {
2571
+ path: `extensions/${id}/src/index.ts`,
2572
+ content: fs2.textFile(EXTENSION_INTERFACE_ID7, "index.ts"),
2573
+ precious: true
2574
+ },
2575
+ {
2576
+ path: `extensions/${id}/src/index.test.ts`,
2577
+ content: fs2.textFile(EXTENSION_INTERFACE_ID7, "index.test.ts"),
2578
+ precious: true
2579
+ },
2580
+ ...base.files
2581
+ ],
2582
+ methods: {
2583
+ prorate_items: {
2584
+ implementation_type: "script"
2585
+ }
2586
+ }
2587
+ };
2588
+ }
2589
+ };
2590
+ var billing_prorations_default = {
2591
+ [EXTENSION_INTERFACE_ID7]: prorationsTemplate
2592
+ };
2593
+
2594
+ // src/templates/extensions/billing.recurring_billing_item_handling.ts
2595
+ var EXTENSION_INTERFACE_ID8 = "billing.recurring_billing_item_handling";
2596
+ var template = {
2597
+ methods: {
2598
+ before_item_creation: { implementation_types: ["script"] },
2599
+ filter_items: { implementation_types: ["script"] },
2600
+ group_items: { implementation_types: ["script"] }
2601
+ },
2602
+ description: "Customize how recurring billing items are filtered, grouped, and created during subscription billing runs.",
2603
+ generate: (params, context) => {
2604
+ const { id } = params;
2605
+ const { fs: fs2 } = context;
2606
+ const base = _createBaseOutput(
2607
+ {
2608
+ ...params,
2609
+ extensionInterfaceId: EXTENSION_INTERFACE_ID8,
2610
+ executionProfile: "restricted"
2611
+ },
2612
+ context
2613
+ );
2614
+ return {
2615
+ ...base,
2616
+ files: [
2617
+ {
2618
+ path: `extensions/${id}/src/index.ts`,
2619
+ content: fs2.textFile(EXTENSION_INTERFACE_ID8, "index.ts"),
2620
+ precious: true
2621
+ },
2622
+ {
2623
+ path: `extensions/${id}/src/index.test.ts`,
2624
+ content: fs2.textFile(EXTENSION_INTERFACE_ID8, "index.test.ts"),
2625
+ precious: true
2626
+ },
2627
+ ...base.files
2628
+ ],
2629
+ methods: {
2630
+ before_item_creation: {
2631
+ implementation_type: "script"
2632
+ },
2633
+ filter_items: {
2634
+ implementation_type: "script"
2635
+ },
2636
+ group_items: {
2637
+ implementation_type: "script"
2638
+ }
2639
+ }
2640
+ };
2641
+ }
2642
+ };
2643
+ var billing_recurring_billing_item_handling_default = {
2644
+ [EXTENSION_INTERFACE_ID8]: template
2645
+ };
2646
+
2647
+ // src/templates/extensions/registry.ts
2648
+ var DEFAULT_TEMPLATES = {
2649
+ ...core_workflows_custom_action_default,
2650
+ ...extend_objects_custom_objects_default,
2651
+ ...extend_workflows_custom_action_default,
2652
+ ...billing_customer_balance_application_default,
2653
+ ...billing_bill_discount_calculation_default,
2654
+ ...billing_invoice_collection_setting_default,
2655
+ ...billing_prorations_default,
2656
+ ...billing_recurring_billing_item_handling_default
2657
+ };
2658
+ var registry_default = DEFAULT_TEMPLATES;
2659
+
2660
+ // src/templates/extensions/index.ts
2661
+ var _templateManager = new _ExtensionTemplateManager(
2662
+ registry_default,
2663
+ _fs.scope("extensions")
2664
+ );
2665
+
2666
+ // src/templates/root/index.ts
2667
+ var import_extensibility_tool_utils8 = require("@stripe/extensibility-tool-utils");
2668
+ var EXTENSIBILITY_ESLINT_PLUGIN_PACKAGE_NAME = "@stripe/extensibility-eslint-plugin";
2669
+ var EXTENSIBILITY_ESLINT_PLUGIN_VERSION = `^${(0, import_extensibility_tool_utils8._workspaceVersion)(EXTENSIBILITY_ESLINT_PLUGIN_PACKAGE_NAME)}`;
2670
+ var _rootWorkspaceTemplate = {
2671
+ generate: (params, context) => {
2672
+ const { fs: fs2 } = context;
2673
+ return {
2674
+ files: [
2675
+ {
2676
+ path: "stripe-app.yaml",
2677
+ content: fs2.mustache(params, "stripe-app.yaml.mustache"),
2678
+ precious: true
2679
+ },
2680
+ {
2681
+ path: "package.json",
2682
+ content: fs2.mustache(params, "package.json.mustache")
2683
+ },
2684
+ {
2685
+ path: ".husky/pre-commit",
2686
+ content: fs2.textFile(".husky/pre-commit")
2687
+ },
2688
+ {
2689
+ path: "tsconfig.base.json",
2690
+ content: fs2.textFile("tsconfig.base.json")
2691
+ },
2692
+ {
2693
+ path: "tsconfig.json",
2694
+ content: fs2.textFile("tsconfig.json")
2695
+ },
2696
+ {
2697
+ path: "eslint.config.mts",
2698
+ content: fs2.textFile("eslint.config.mts")
2699
+ },
2700
+ {
2701
+ path: "vitest.config.mts",
2702
+ content: fs2.textFile("vitest.config.mts")
2703
+ },
2704
+ {
2705
+ path: ".gitignore",
2706
+ content: fs2.textFile("_gitignore")
2707
+ },
2708
+ {
2709
+ path: "pnpm-workspace.yaml",
2710
+ content: fs2.textFile("pnpm-workspace.yaml")
2711
+ },
2712
+ {
2713
+ path: ".prettierrc",
2714
+ content: fs2.textFile(".prettierrc")
2715
+ },
2716
+ {
2717
+ path: ".prettierignore",
2718
+ content: fs2.textFile(".prettierignore")
2719
+ },
2720
+ {
2721
+ path: "custom-objects/package.json",
2722
+ content: fs2.textFile("custom-objects/package.json"),
2723
+ precious: true
2724
+ },
2725
+ {
2726
+ path: "custom-objects/tsconfig.json",
2727
+ content: fs2.textFile("custom-objects/tsconfig.json"),
2728
+ precious: true
2729
+ },
2730
+ {
2731
+ path: "ui/package.json",
2732
+ content: fs2.textFile("ui/package.json"),
2733
+ precious: true
2734
+ },
2735
+ {
2736
+ path: "tools/test.mts",
2737
+ content: fs2.textFile("tools/test.mts")
2738
+ },
2739
+ {
2740
+ // temporarily add dummy JSON manifest until stripe apps plugin is fixed
2741
+ path: "stripe-app.json",
2742
+ content: "{}\n"
2743
+ }
2744
+ ],
2745
+ dependencies: {
2746
+ dev: [
2747
+ _devNpmDep("@eslint/js", "^9.0.0"),
2748
+ _devNpmDep(
2749
+ EXTENSIBILITY_ESLINT_PLUGIN_PACKAGE_NAME,
2750
+ EXTENSIBILITY_ESLINT_PLUGIN_VERSION
2751
+ ),
2752
+ _devNpmDep(LANGUAGE_SERVER_PACKAGE_NAME, LANGUAGE_SERVER_PACKAGE_VERSION),
2753
+ _devNpmDep("@types/node", "^20.19.0"),
2754
+ _devNpmDep(
2755
+ "@stripe/extensibility-dev-tools",
2756
+ `^${(0, import_extensibility_tool_utils8._workspaceVersion)("@stripe/extensibility-dev-tools")}`
2757
+ ),
2758
+ _devNpmDep("concurrently", "^9.2.1"),
2759
+ _devNpmDep("eslint", "^9.0.0"),
2760
+ _devNpmDep("eslint-config-prettier", "^10.1.8"),
2761
+ _devNpmDep("eslint-plugin-workspaces", "^0.12.1"),
2762
+ _devNpmDep("globals", "^17.4.0"),
2763
+ _devNpmDep("husky", "^9.1.7"),
2764
+ _devNpmDep("jiti", "^2.6.1"),
2765
+ _devNpmDep("lint-staged", "^16.2.7"),
2766
+ _devNpmDep("chokidar-cli", "^3.0.0"),
2767
+ _devNpmDep("prettier", "^3.8.1"),
2768
+ _devNpmDep("ts-node", "^10.9.2"),
2769
+ _devNpmDep("tsx", "^4.21.0"),
2770
+ _devNpmDep("typescript", "^5.9.3"),
2771
+ _devNpmDep("typescript-eslint", "^8.54.0"),
2772
+ _devNpmDep("vitest", "^3.0.0")
2773
+ ]
2774
+ },
2775
+ postGenerationHooks: [
2776
+ {
2777
+ exec: "prettier --write .",
2778
+ description: "Format generated files"
2779
+ }
2780
+ ]
2781
+ };
2782
+ }
2783
+ };
2784
+ var _rootTemplateManager = new import_extensibility_tool_utils3._SingleTemplateManager(_rootWorkspaceTemplate, _fs.scope("root"));
2785
+
2786
+ // src/manifest/stripe-app-manifest.ts
2787
+ var import_extensibility_tool_utils10 = require("@stripe/extensibility-tool-utils");
2788
+
2789
+ // src/manifest/manifest-v1.ts
2790
+ var import_fs4 = require("fs");
2791
+ function formatCustomObjectEntry(entry) {
2792
+ return `${entry.filePath}#${entry.className}`;
2793
+ }
2794
+ function parseCustomObjectEntry(entryString) {
2795
+ const parts = entryString.split("#");
2796
+ if (parts.length !== 2) {
2797
+ throw new Error(
2798
+ `Invalid object entry format: ${entryString}. Expected format: "path/to/file.d.ts#ClassName"`
2799
+ );
2800
+ }
2801
+ const [filePath, className] = parts;
2802
+ if (!filePath || !className) {
2803
+ throw new Error(
2804
+ `Invalid object entry format: ${entryString}. Expected format: "path/to/file.d.ts#ClassName"`
2805
+ );
2806
+ }
2807
+ return { filePath, className };
2808
+ }
2809
+ var _ManifestV1 = class __ManifestV1 {
2810
+ constructor(filePath, data) {
2811
+ this.filePath = filePath;
2812
+ this.data = data;
2813
+ }
2814
+ /**
2815
+ * Load stripe-app.json from disk
2816
+ * @param filePath - Path to stripe-app.json
2817
+ * @throws Error if file is invalid or cannot be read
2818
+ */
2819
+ static load(filePath) {
2820
+ if (!(0, import_fs4.existsSync)(filePath)) {
2821
+ throw new Error(`Manifest file not found: ${filePath}`);
2822
+ }
2823
+ const content = (0, import_fs4.readFileSync)(filePath, "utf-8");
2824
+ const data = JSON.parse(content);
2825
+ if (!data.id) {
2826
+ throw new Error('Manifest must contain "id" field');
2827
+ }
2828
+ return new __ManifestV1(filePath, data);
2829
+ }
2830
+ /**
2831
+ * Get the app ID from the manifest
2832
+ */
2833
+ getAppId() {
2834
+ return this.data.id;
2835
+ }
2836
+ /**
2837
+ * Get the app name from the manifest
2838
+ */
2839
+ getAppName() {
2840
+ return this.data.name;
2841
+ }
2842
+ /**
2843
+ * Get all custom objects as structured entries
2844
+ */
2845
+ getCustomObjects() {
2846
+ const entries = [];
2847
+ if (this.data.exported_custom_objects) {
2848
+ for (const entry of this.data.exported_custom_objects) {
2849
+ entries.push(parseCustomObjectEntry(entry));
2850
+ }
2851
+ }
2852
+ return entries;
2853
+ }
2854
+ /**
2855
+ * Check if a custom object entry exists in the manifest
2856
+ */
2857
+ hasCustomObject(entry) {
2858
+ const objects = this.getCustomObjects();
2859
+ return objects.some(
2860
+ (existing) => existing.filePath === entry.filePath && existing.className === entry.className
2861
+ );
2862
+ }
2863
+ /**
2864
+ * Add a custom object entry to the manifest
2865
+ * Does nothing if entry already exists
2866
+ * @returns true if entry was added, false if it already existed
2867
+ */
2868
+ addCustomObject(entry) {
2869
+ if (this.hasCustomObject(entry)) {
2870
+ return false;
2871
+ }
2872
+ const entryString = formatCustomObjectEntry(entry);
2873
+ this.data.exported_custom_objects ??= [];
2874
+ this.data.exported_custom_objects.push(entryString);
2875
+ return true;
2876
+ }
2877
+ /**
2878
+ * Remove a custom object entry from the manifest
2879
+ * @returns true if entry was removed, false if it didn't exist
2880
+ */
2881
+ removeCustomObject(entry) {
2882
+ if (!this.data.exported_custom_objects) {
2883
+ return false;
2884
+ }
2885
+ const entryString = formatCustomObjectEntry(entry);
2886
+ const originalLength = this.data.exported_custom_objects.length;
2887
+ this.data.exported_custom_objects = this.data.exported_custom_objects.filter(
2888
+ (e) => e !== entryString
2889
+ );
2890
+ if (this.data.exported_custom_objects.length === 0) {
2891
+ delete this.data.exported_custom_objects;
2892
+ }
2893
+ return this.data.exported_custom_objects?.length !== originalLength;
2894
+ }
2895
+ /**
2896
+ * Get the raw manifest data (for reading other fields)
2897
+ */
2898
+ getRawData() {
2899
+ return this.data;
2900
+ }
2901
+ /**
2902
+ * Save changes back to disk
2903
+ */
2904
+ save() {
2905
+ (0, import_fs4.writeFileSync)(this.filePath, JSON.stringify(this.data, null, 2) + "\n");
2906
+ }
2907
+ };
2908
+
2909
+ // src/manifest/manifest-v2.ts
2910
+ var import_promises4 = require("fs/promises");
2911
+ var yaml = __toESM(require("yaml"), 1);
2912
+ var import_extensibility_tool_utils9 = require("@stripe/extensibility-tool-utils");
2913
+ function isNonEmptyString(value) {
2914
+ return typeof value === "string" && value.trim().length > 0;
2915
+ }
2916
+ function isYamlObject(value) {
2917
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2918
+ }
2919
+ function validateManifestV2Data(data) {
2920
+ if (!isNonEmptyString(data.id)) {
2921
+ throw new Error('Manifest must contain non-empty "id" field');
2922
+ }
2923
+ if (!isNonEmptyString(data.name)) {
2924
+ throw new Error('Manifest must contain non-empty "name" field');
2925
+ }
2926
+ if (!isNonEmptyString(data.version)) {
2927
+ throw new Error('Manifest must contain non-empty "version" field');
2928
+ }
2929
+ if ("extensions" in data && !Array.isArray(data.extensions)) {
2930
+ throw new Error('Manifest field "extensions" must be an array when provided');
2931
+ }
2932
+ if ("custom_object_definitions" in data && !isYamlObject(data.custom_object_definitions)) {
2933
+ throw new Error(
2934
+ 'Manifest field "custom_object_definitions" must be an object with a "definitions" array'
2935
+ );
2936
+ }
2937
+ const coBlock = data.custom_object_definitions;
2938
+ const definitions = isYamlObject(coBlock) ? coBlock.definitions : void 0;
2939
+ if (!definitions) {
2940
+ return;
2941
+ }
2942
+ if (!Array.isArray(definitions)) {
2943
+ throw new Error(
2944
+ 'Manifest field "custom_object_definitions.definitions" must be an array'
2945
+ );
2946
+ }
2947
+ for (let i = 0; i < definitions.length; i++) {
2948
+ const def = definitions[i];
2949
+ const prefix = `custom_object_definitions.definitions[${String(i)}]`;
2950
+ if (!isYamlObject(def) || !isNonEmptyString(def.id)) {
2951
+ throw new Error(
2952
+ `${prefix}: missing or invalid "id" field. Got: ${JSON.stringify(def)}`
2953
+ );
2954
+ }
2955
+ if (!isYamlObject(def.specification)) {
2956
+ throw new Error(
2957
+ `${prefix}: missing or invalid "specification" field. Expected: { type: "typescript", content: "path/to/file.ts" }. Got: ${JSON.stringify(def)}`
2958
+ );
2959
+ }
2960
+ if (!isNonEmptyString(def.specification.type)) {
2961
+ throw new Error(
2962
+ `${prefix}: missing or invalid "specification.type" field. Got: ${JSON.stringify(def)}`
2963
+ );
2964
+ }
2965
+ if (!isNonEmptyString(def.specification.content)) {
2966
+ throw new Error(
2967
+ `${prefix}: missing or invalid "specification.content" field. Got: ${JSON.stringify(def)}`
2968
+ );
2969
+ }
2970
+ }
2971
+ }
2972
+ var _ManifestV2 = class __ManifestV2 {
2973
+ constructor(filePath, data) {
2974
+ this.filePath = filePath;
2975
+ this.data = data;
2976
+ }
2977
+ /**
2978
+ * Load stripe-app.yaml from disk
2979
+ * @param filePath - Path to stripe-app.yaml
2980
+ * @throws Error if file is invalid or cannot be read
2981
+ */
2982
+ static async load(filePath) {
2983
+ try {
2984
+ const content = await (0, import_promises4.readFile)(filePath, "utf-8");
2985
+ const parsed = yaml.parse(content);
2986
+ if (!isYamlObject(parsed)) {
2987
+ throw new Error("Invalid stripe-app.yaml format: root must be an object");
2988
+ }
2989
+ validateManifestV2Data(parsed);
2990
+ const data = parsed;
2991
+ data.extensions ??= [];
2992
+ return new __ManifestV2(filePath, data);
2993
+ } catch (err) {
2994
+ if (err instanceof Error) {
2995
+ throw new Error(`Error reading stripe-app.yaml: ${err.message}`);
2996
+ }
2997
+ throw new Error(`Error reading stripe-app.yaml: ${String(err)}`);
2998
+ }
2999
+ }
3000
+ /**
3001
+ * Get the app ID from the manifest
3002
+ */
3003
+ getAppId() {
3004
+ return this.data.id;
3005
+ }
3006
+ /**
3007
+ * Get the app name from the manifest
3008
+ */
3009
+ getAppName() {
3010
+ return this.data.name;
3011
+ }
3012
+ // ============================================================
3013
+ // Custom Objects
3014
+ // ============================================================
3015
+ /**
3016
+ * Get all custom object definitions, parsed into internal format.
3017
+ * Entries are guaranteed structurally valid by load-time validation.
3018
+ */
3019
+ getCustomObjects() {
3020
+ const definitions = this.data.custom_object_definitions?.definitions;
3021
+ if (!definitions || definitions.length === 0) {
3022
+ return [];
3023
+ }
3024
+ return definitions.map((def) => ({
3025
+ id: def.id,
3026
+ type: def.specification.type,
3027
+ path: def.specification.content,
3028
+ name: (0, import_extensibility_tool_utils9._toPascalCase)(def.id)
3029
+ }));
3030
+ }
3031
+ /**
3032
+ * Check if a custom object exists by id
3033
+ */
3034
+ hasCustomObject(id) {
3035
+ const definitions = this.data.custom_object_definitions?.definitions;
3036
+ if (!definitions) return false;
3037
+ return definitions.some((def) => def.id === id);
3038
+ }
3039
+ /**
3040
+ * Add a custom object definition.
3041
+ *
3042
+ * Identity is keyed on `id` alone. The export name is derived via
3043
+ * `_toPascalCase(id)` at read time, so `id` should be valid snake_case
3044
+ * (e.g., "device", "loyalty_card", "http_request").
3045
+ *
3046
+ * @param id - Object identifier (e.g., "device", "loyalty_card")
3047
+ * @param content - Path to the definition file (e.g., "src/device.object.ts")
3048
+ * @param type - Specification type, defaults to "typescript"
3049
+ * @returns true if added, false if already exists
3050
+ */
3051
+ addCustomObject(id, content, type = "typescript") {
3052
+ if (this.hasCustomObject(id)) {
3053
+ return false;
3054
+ }
3055
+ this.data.custom_object_definitions ??= {};
3056
+ this.data.custom_object_definitions.definitions ??= [];
3057
+ this.data.custom_object_definitions.definitions.push({
3058
+ id,
3059
+ specification: { type, content }
3060
+ });
3061
+ return true;
3062
+ }
3063
+ /**
3064
+ * Remove a custom object definition by id
3065
+ * @param id - Object identifier to remove
3066
+ * @returns true if removed, false if not found
3067
+ */
3068
+ removeCustomObject(id) {
3069
+ const block = this.data.custom_object_definitions;
3070
+ if (!block?.definitions) {
3071
+ return false;
3072
+ }
3073
+ const originalLength = block.definitions.length;
3074
+ block.definitions = block.definitions.filter((def) => def.id !== id);
3075
+ const newLength = block.definitions.length;
3076
+ if (newLength === 0) {
3077
+ delete this.data.custom_object_definitions;
3078
+ }
3079
+ return newLength < originalLength;
3080
+ }
3081
+ // ============================================================
3082
+ // Extensions
3083
+ // ============================================================
3084
+ /**
3085
+ * Add a new extension or update an existing one by ID
3086
+ * If an extension with the provided ID exists, it will be replaced entirely
3087
+ * @param extension - Extension configuration with all required fields including id
3088
+ * @returns The extension ID
3089
+ */
3090
+ addOrUpdateExtension(extension) {
3091
+ const newExtension = {
3092
+ id: extension.id,
3093
+ name: extension.name,
3094
+ interface_id: extension.interface_id,
3095
+ version: extension.version,
3096
+ ...extension.description !== void 0 && {
3097
+ description: extension.description
3098
+ },
3099
+ ...extension.stripe_version !== void 0 && {
3100
+ stripe_version: extension.stripe_version
3101
+ },
3102
+ ...extension.script_entry_point !== void 0 && {
3103
+ script_entry_point: extension.script_entry_point
3104
+ },
3105
+ ...extension.script !== void 0 && { script: extension.script },
3106
+ permissions: extension.permissions,
3107
+ methods: extension.methods,
3108
+ ...extension.configuration !== void 0 && {
3109
+ configuration: extension.configuration
3110
+ },
3111
+ ...extension.endpoints !== void 0 && {
3112
+ endpoints: extension.endpoints
3113
+ }
3114
+ };
3115
+ this.data.extensions ??= [];
3116
+ const existingIndex = this.data.extensions.findIndex(
3117
+ (ext) => ext.id === extension.id
3118
+ );
3119
+ if (existingIndex !== -1) {
3120
+ this.data.extensions[existingIndex] = newExtension;
3121
+ } else {
3122
+ this.data.extensions.push(newExtension);
3123
+ }
3124
+ return extension.id;
3125
+ }
3126
+ /**
3127
+ * Get a read-only view of all extensions
3128
+ */
3129
+ getExtensions() {
3130
+ return this.data.extensions ?? [];
3131
+ }
3132
+ /**
3133
+ * Get the raw manifest data (for reading other fields)
3134
+ */
3135
+ getRawData() {
3136
+ return this.data;
3137
+ }
3138
+ /**
3139
+ * Save changes back to disk
3140
+ * @throws Error if file cannot be written
3141
+ */
3142
+ async save() {
3143
+ try {
3144
+ const updatedContent = yaml.stringify(this.data);
3145
+ await (0, import_promises4.writeFile)(this.filePath, updatedContent, "utf-8");
3146
+ } catch (err) {
3147
+ if (err instanceof Error) {
3148
+ throw new Error(`Error writing stripe-app.yaml: ${err.message}`);
3149
+ }
3150
+ throw new Error(`Error writing stripe-app.yaml: ${String(err)}`);
3151
+ }
3152
+ }
3153
+ };
3154
+
3155
+ // src/manifest/stripe-app-manifest.ts
3156
+ var _StripeAppManifest = class __StripeAppManifest {
3157
+ constructor(manifestPath, version, v1, v2) {
3158
+ this.manifestPath = manifestPath;
3159
+ this.version = version;
3160
+ this.v1 = v1;
3161
+ this.v2 = v2;
3162
+ }
3163
+ /**
3164
+ * Load a manifest file, automatically detecting the version.
3165
+ * @param manifestPath - Path to stripe-app.json or stripe-app.yaml
3166
+ * @returns Loaded manifest instance
3167
+ */
3168
+ static async load(manifestPath) {
3169
+ const version = __StripeAppManifest.detectVersion(manifestPath);
3170
+ if (version === "v1") {
3171
+ const reader = _ManifestV1.load(manifestPath);
3172
+ return new __StripeAppManifest(manifestPath, version, reader, null);
3173
+ } else {
3174
+ const reader = await _ManifestV2.load(manifestPath);
3175
+ return new __StripeAppManifest(manifestPath, version, null, reader);
3176
+ }
3177
+ }
3178
+ /**
3179
+ * Detect manifest version from file path.
3180
+ * TODO: Add content-based detection if needed.
3181
+ */
3182
+ static detectVersion(manifestPath) {
3183
+ const lowerPath = manifestPath.toLowerCase();
3184
+ if (lowerPath.endsWith(".yaml") || lowerPath.endsWith(".yml")) {
3185
+ return "v2";
3186
+ }
3187
+ if (lowerPath.endsWith(".json")) {
3188
+ return "v1";
3189
+ }
3190
+ throw new Error(
3191
+ `Cannot detect manifest version from path: ${manifestPath}. Expected .json (v1) or .yaml/.yml (v2) extension.`
3192
+ );
3193
+ }
3194
+ /**
3195
+ * Get the detected manifest version
3196
+ */
3197
+ getVersion() {
3198
+ return this.version;
3199
+ }
3200
+ /**
3201
+ * Get the manifest file path
3202
+ */
3203
+ getManifestPath() {
3204
+ return this.manifestPath;
3205
+ }
3206
+ // ============================================================
3207
+ // App Metadata (supported by both V1 and V2)
3208
+ // ============================================================
3209
+ /**
3210
+ * Get the app ID from the manifest
3211
+ */
3212
+ getAppId() {
3213
+ if (this.v1) {
3214
+ return this.v1.getAppId();
3215
+ }
3216
+ if (this.v2) {
3217
+ return this.v2.getAppId();
3218
+ }
3219
+ return void 0;
3220
+ }
3221
+ /**
3222
+ * Get the app name from the manifest
3223
+ */
3224
+ getAppName() {
3225
+ if (this.v1) {
3226
+ return this.v1.getAppName();
3227
+ }
3228
+ if (this.v2) {
3229
+ return this.v2.getAppName();
3230
+ }
3231
+ return void 0;
3232
+ }
3233
+ // ============================================================
3234
+ // Custom Objects (supported by both V1 and V2)
3235
+ // ============================================================
3236
+ /**
3237
+ * Get all custom objects from the manifest
3238
+ */
3239
+ getCustomObjects() {
3240
+ if (this.v1) {
3241
+ return this.v1.getCustomObjects();
3242
+ }
3243
+ if (this.v2) {
3244
+ return this.v2.getCustomObjects().map((obj) => ({
3245
+ filePath: obj.path,
3246
+ className: obj.name
3247
+ }));
3248
+ }
3249
+ return [];
3250
+ }
3251
+ /**
3252
+ * Check if a custom object entry exists in the manifest.
3253
+ *
3254
+ * **V2 note:** Identity is keyed on `_toSnakeCase(className)` alone — `filePath`
3255
+ * is not considered. Two entries with the same class name but different file
3256
+ * paths are treated as the same object. The `_toSnakeCase` → `_toPascalCase`
3257
+ * round-trip is lossless for typical class names but lossy for consecutive
3258
+ * uppercase (e.g., `HTTPClient` → `http_client` → `HttpClient`). The manifest
3259
+ * `id` field is the source of truth; see `_CustomObjectDefinitionYaml` docs.
3260
+ */
3261
+ hasCustomObject(entry) {
3262
+ if (this.v1) {
3263
+ return this.v1.hasCustomObject(entry);
3264
+ }
3265
+ if (this.v2) {
3266
+ return this.v2.hasCustomObject((0, import_extensibility_tool_utils10._toSnakeCase)(entry.className));
3267
+ }
3268
+ return false;
3269
+ }
3270
+ /**
3271
+ * Add a custom object entry to the manifest.
3272
+ *
3273
+ * **V2 note:** The manifest `id` is derived as `_toSnakeCase(className)` and
3274
+ * `filePath` is stored as the specification `content` path. Identity/dedup
3275
+ * is based on `id` alone — see `hasCustomObject` for details.
3276
+ *
3277
+ * @param entry - The custom object entry to add
3278
+ * @returns true if entry was added, false if it already existed
3279
+ */
3280
+ addCustomObject(entry) {
3281
+ if (this.v1) {
3282
+ return this.v1.addCustomObject(entry);
3283
+ }
3284
+ if (this.v2) {
3285
+ return this.v2.addCustomObject((0, import_extensibility_tool_utils10._toSnakeCase)(entry.className), entry.filePath);
3286
+ }
3287
+ return false;
3288
+ }
3289
+ /**
3290
+ * Remove a custom object entry from the manifest.
3291
+ *
3292
+ * **V2 note:** Removal is keyed on `_toSnakeCase(className)` — `filePath` is
3293
+ * not considered. See `hasCustomObject` for identity semantics.
3294
+ *
3295
+ * @param entry - The custom object entry to remove
3296
+ * @returns true if entry was removed, false if it didn't exist
3297
+ */
3298
+ removeCustomObject(entry) {
3299
+ if (this.v1) {
3300
+ return this.v1.removeCustomObject(entry);
3301
+ }
3302
+ if (this.v2) {
3303
+ return this.v2.removeCustomObject((0, import_extensibility_tool_utils10._toSnakeCase)(entry.className));
3304
+ }
3305
+ return false;
3306
+ }
3307
+ // ============================================================
3308
+ // Extensions (V2 only)
3309
+ // ============================================================
3310
+ /**
3311
+ * Get all extensions from the manifest
3312
+ * @throws Error if manifest version doesn't support extensions
3313
+ */
3314
+ getExtensions() {
3315
+ if (this.v2) {
3316
+ return this.v2.getExtensions();
3317
+ }
3318
+ throw new Error("Extensions are not supported in V1 manifests (stripe-app.json)");
3319
+ }
3320
+ /**
3321
+ * Add or update an extension in the manifest.
3322
+ * If an extension with the same ID exists, it will be replaced.
3323
+ *
3324
+ * @param config - Full extension configuration
3325
+ * @returns The extension ID
3326
+ * @throws Error if manifest version doesn't support extensions
3327
+ */
3328
+ addOrUpdateExtension(config) {
3329
+ if (this.v2) {
3330
+ return this.v2.addOrUpdateExtension(config);
3331
+ }
3332
+ throw new Error("Extensions are not supported in V1 manifests (stripe-app.json)");
3333
+ }
3334
+ // ============================================================
3335
+ // Persistence
3336
+ // ============================================================
3337
+ /**
3338
+ * Save changes back to disk
3339
+ */
3340
+ async save() {
3341
+ if (this.v1) {
3342
+ this.v1.save();
3343
+ return;
3344
+ }
3345
+ if (this.v2) {
3346
+ await this.v2.save();
3347
+ return;
3348
+ }
3349
+ throw new Error("No reader loaded - this should never happen");
3350
+ }
3351
+ };
3352
+
3353
+ // src/workspace/index.ts
3354
+ var import_zod = require("zod");
3355
+ var import_node_path3 = __toESM(require("path"), 1);
3356
+ var import_node_fs2 = require("fs");
3357
+ var import_promises5 = require("fs/promises");
3358
+ var import_node_child_process2 = require("child_process");
3359
+ var import_internal = require("@stripe/extensibility-custom-objects-tools/internal");
3360
+ var import_extensibility_tool_utils11 = require("@stripe/extensibility-tool-utils");
3361
+ var _regenWorkspaceOptionsSchema = import_zod.z.object({
3362
+ /** Workspace template ID (e.g., 'core.workflows.custom_action', 'custom-objects'). Absence means root workspace mode. */
3363
+ templateId: import_zod.z.string().optional(),
3364
+ /** Path to project root. Resolved relative to cwd. Defaults to cwd. */
3365
+ root: import_zod.z.string().optional(),
3366
+ /** Path to directory containing package.json (resolved relative to cwd). Used for reading existing metadata. If undefined, package.json is not read. */
3367
+ packageDir: import_zod.z.string().optional(),
3368
+ /** Workspace ID. Validated against package.json if both are present. */
3369
+ workspaceId: import_zod.z.string().optional(),
3370
+ /** Workspace name. Overrides package.json description if provided. */
3371
+ workspaceName: import_zod.z.string().optional(),
3372
+ /** Skip dependency installation */
3373
+ skipDependencies: import_zod.z.boolean().optional(),
3374
+ /** Skip post-generation hooks */
3375
+ skipHooks: import_zod.z.boolean().optional(),
3376
+ /** Force overwrite all files without prompting */
3377
+ force: import_zod.z.boolean().optional(),
3378
+ /** Custom object name. Required when templateId is 'custom-object'. */
3379
+ name: import_zod.z.string().optional(),
3380
+ /** Implementation type. When 'remote-function', only .schema.json files are written and dependencies/hooks are skipped. */
3381
+ implementationType: import_zod.z.enum(["script", "remote-function"]).optional()
3382
+ });
3383
+ async function readPackageMetadata(dir) {
3384
+ const pkgPath = import_node_path3.default.join(dir, "package.json");
3385
+ try {
3386
+ const pkgContent = await (0, import_promises5.readFile)(pkgPath, "utf-8");
3387
+ const pkg = JSON.parse(pkgContent);
3388
+ return {
3389
+ ...pkg.name !== void 0 && { id: pkg.name },
3390
+ ...pkg.description !== void 0 && { name: pkg.description },
3391
+ ...pkg.version !== void 0 && { version: pkg.version }
3392
+ };
3393
+ } catch {
3394
+ return null;
3395
+ }
3396
+ }
3397
+ async function _resolvePackageMetadata(providedId, providedName, packageDir) {
3398
+ let id = providedId;
3399
+ let name = providedName;
3400
+ let version = "0.0.1";
3401
+ if (packageDir !== void 0) {
3402
+ const pkgMetadata = await readPackageMetadata(packageDir);
3403
+ if (pkgMetadata) {
3404
+ if (id && pkgMetadata.id && id !== pkgMetadata.id) {
3405
+ throw new Error(
3406
+ `Workspace ID mismatch: --workspace-id "${id}" does not match package.json name "${pkgMetadata.id}"`
3407
+ );
3408
+ }
3409
+ id ??= pkgMetadata.id;
3410
+ name ??= pkgMetadata.name;
3411
+ if (pkgMetadata.version) {
3412
+ version = pkgMetadata.version;
3413
+ }
3414
+ }
3415
+ }
3416
+ if (!id) {
3417
+ throw new Error(
3418
+ "ID required: provide --workspace-id or ensure package.json has a name field"
3419
+ );
3420
+ }
3421
+ name ??= id;
3422
+ return { id, name, version };
3423
+ }
3424
+ function runPostGenerationHooks(hooks, workingDir, disabled = false, context = (0, import_extensibility_tool_utils11._createCliContext)()) {
3425
+ if (!hooks || hooks.length === 0 || disabled) {
3426
+ return Promise.resolve();
3427
+ }
3428
+ context.ux.log("\nRunning post-generation hooks...");
3429
+ for (const hook of hooks) {
3430
+ const description = hook.description ? ` (${hook.description})` : "";
3431
+ let command;
3432
+ let hookName;
3433
+ if ("script" in hook) {
3434
+ command = `pnpm run ${hook.script}`;
3435
+ hookName = hook.script;
3436
+ } else {
3437
+ command = `pnpm exec ${hook.exec}`;
3438
+ hookName = hook.exec;
3439
+ }
3440
+ context.ux.log(`
3441
+ Running: ${command}${description}`);
3442
+ try {
3443
+ (0, import_node_child_process2.execSync)(command, {
3444
+ cwd: workingDir,
3445
+ stdio: "inherit"
3446
+ });
3447
+ context.ux.log(`\u2713 Hook completed: ${hookName}`);
3448
+ } catch (error) {
3449
+ context.ux.error(`! Hook failed: ${hookName}`);
3450
+ if (error instanceof Error) {
3451
+ context.ux.error(` ${error.message}`);
3452
+ }
3453
+ }
3454
+ }
3455
+ return Promise.resolve();
3456
+ }
3457
+ async function installDependencies(services, cwd, dependencies, context) {
3458
+ if (dependencies.length === 0) {
3459
+ return;
3460
+ }
3461
+ const depManager = services.createDepManager({ cwd, context });
3462
+ const pendingChanges = await depManager.ensureDependencies({
3463
+ required: dependencies
3464
+ });
3465
+ for (const pendingChange of pendingChanges) {
3466
+ if (pendingChange.action === "conflict") {
3467
+ depManager.resolveConflict(pendingChange.dependency);
3468
+ }
3469
+ }
3470
+ await depManager.commit();
3471
+ }
3472
+ async function backfillMissingExtensionEslintConfigs(services, projectRoot) {
3473
+ const manifestPath = import_node_path3.default.join(projectRoot, "stripe-app.yaml");
3474
+ if (!(0, import_node_fs2.existsSync)(manifestPath)) {
3475
+ return [];
3476
+ }
3477
+ const manifest = await services.loadManifest(manifestPath);
3478
+ const extensions = manifest.getExtensions();
3479
+ return extensions.flatMap((extension) => {
3480
+ const eslintConfigPath = `extensions/${extension.id}/eslint.config.mts`;
3481
+ if ((0, import_node_fs2.existsSync)(import_node_path3.default.join(projectRoot, eslintConfigPath))) {
3482
+ return [];
3483
+ }
3484
+ return _createExtensionEslintConfigFile(
3485
+ {
3486
+ id: extension.id,
3487
+ extensionInterfaceId: extension.interface_id
3488
+ },
3489
+ { fs: _fs.scope("extensions") }
3490
+ );
3491
+ });
3492
+ }
3493
+ function resolveMode(options, projectRoot, packageDir) {
3494
+ if (!options.templateId) {
3495
+ return {
3496
+ label: "root",
3497
+ workspaceDir: () => packageDir ?? projectRoot,
3498
+ generate: (svc, meta) => svc.generateRoot({
3499
+ appId: meta.id,
3500
+ appName: meta.name,
3501
+ version: meta.version
3502
+ })
3503
+ };
3504
+ }
3505
+ if (options.templateId === "custom-objects") {
3506
+ return {
3507
+ label: "custom-objects",
3508
+ workspaceDir: () => packageDir ?? import_node_path3.default.join(projectRoot, "custom-objects"),
3509
+ generate: async (svc) => {
3510
+ const workspaceResult = await svc.generateCustomObjectsWorkspace({});
3511
+ return {
3512
+ ...workspaceResult,
3513
+ files: workspaceResult.files.map((f) => ({ ...f, precious: true }))
3514
+ };
3515
+ }
3516
+ };
3517
+ }
3518
+ if (options.templateId === "custom-object") {
3519
+ const objectName = options.name;
3520
+ if (!objectName) {
3521
+ throw new Error("--name is required when --template-id is 'custom-object'");
3522
+ }
3523
+ return {
3524
+ label: `custom-object:${objectName}`,
3525
+ workspaceDir: () => packageDir ?? import_node_path3.default.join(projectRoot, "custom-objects"),
3526
+ generate: async (svc) => {
3527
+ const customObjectsWorkspaceDir = packageDir ?? import_node_path3.default.join(projectRoot, "custom-objects");
3528
+ const workspaceExists = (0, import_node_fs2.existsSync)(import_node_path3.default.join(customObjectsWorkspaceDir, "package.json")) && (0, import_node_fs2.existsSync)(import_node_path3.default.join(customObjectsWorkspaceDir, "tsconfig.json"));
3529
+ const objectResult = await svc.generateCustomObject({ name: objectName });
3530
+ if (workspaceExists) {
3531
+ return objectResult;
3532
+ }
3533
+ const workspaceResult = await svc.generateCustomObjectsWorkspace({});
3534
+ return {
3535
+ ...objectResult,
3536
+ files: [
3537
+ ...workspaceResult.files.map((f) => ({ ...f, precious: true })),
3538
+ ...objectResult.files
3539
+ ]
3540
+ };
3541
+ },
3542
+ finalize: async (_svc, _meta, root, _output, context) => {
3543
+ context.ux.log("\nUpdating stripe-app.yaml...");
3544
+ const manifestPath = import_node_path3.default.join(root, "stripe-app.yaml");
3545
+ const manifest = await (0, import_extensibility_tool_utils11._openStripeAppManifest)(manifestPath);
3546
+ const apiName = (0, import_extensibility_tool_utils11._toSnakeCase)(objectName);
3547
+ if (!manifest.hasCustomObject(apiName)) {
3548
+ manifest.addCustomObject(apiName, `custom-objects/src/${apiName}.object.ts`);
3549
+ const tx = (0, import_extensibility_tool_utils11._beginTransaction)();
3550
+ tx.adopt(manifest);
3551
+ const report = await tx.commit();
3552
+ if (report.written.length > 0) {
3553
+ context.ux.log("\u2713 Updated stripe-app.yaml");
3554
+ }
3555
+ } else {
3556
+ context.ux.log("- Custom object already registered in stripe-app.yaml");
3557
+ }
3558
+ }
3559
+ };
3560
+ }
3561
+ const interfaceId = options.templateId;
3562
+ function buildRemoteFunctionMethodsAndEndpoints(extensionId, outputMethods) {
3563
+ const methods = {};
3564
+ const endpoints = Object.entries(outputMethods).map(([methodName, methodConfig]) => {
3565
+ const endpointId = `${extensionId}.${methodName}`;
3566
+ const customInput = typeof methodConfig === "object" && methodConfig !== null && "custom_input" in methodConfig ? Reflect.get(methodConfig, "custom_input") : void 0;
3567
+ methods[methodName] = {
3568
+ implementation_type: "remote_function",
3569
+ ...customInput !== void 0 && { custom_input: customInput },
3570
+ endpoint_id: endpointId
3571
+ };
3572
+ return {
3573
+ id: endpointId,
3574
+ type: "remote_function",
3575
+ live: { url: "https://example.com/" }
3576
+ };
3577
+ });
3578
+ return { methods, endpoints };
3579
+ }
3580
+ return {
3581
+ label: interfaceId,
3582
+ workspaceDir: (meta) => packageDir ?? import_node_path3.default.join(projectRoot, "extensions", meta.id),
3583
+ generate: (svc, meta) => svc.generateExtension(interfaceId, {
3584
+ id: meta.id,
3585
+ name: meta.name,
3586
+ version: meta.version
3587
+ }),
3588
+ finalize: async (svc, meta, root, output, context) => {
3589
+ if (!output.methods) return;
3590
+ context.ux.log("\nUpdating stripe-app.yaml...");
3591
+ const manifest = await svc.loadManifest(import_node_path3.default.join(root, "stripe-app.yaml"));
3592
+ const permissions = [];
3593
+ const baseConfig = {
3594
+ id: meta.id,
3595
+ name: meta.name,
3596
+ interface_id: interfaceId,
3597
+ version: meta.version,
3598
+ permissions
3599
+ };
3600
+ if (options.implementationType === "remote-function") {
3601
+ const { methods, endpoints } = buildRemoteFunctionMethodsAndEndpoints(
3602
+ meta.id,
3603
+ output.methods
3604
+ );
3605
+ manifest.addOrUpdateExtension({ ...baseConfig, methods, endpoints });
3606
+ } else {
3607
+ manifest.addOrUpdateExtension({
3608
+ ...baseConfig,
3609
+ script: {
3610
+ type: "typescript",
3611
+ content: `extensions/${meta.id}/src/index.ts`
3612
+ },
3613
+ methods: output.methods,
3614
+ configuration: {
3615
+ input_schema: {
3616
+ type: "json_schema",
3617
+ content: `extensions/${meta.id}/generated/config.schema.json`
3618
+ },
3619
+ ui_schema: {
3620
+ type: "jsonforms",
3621
+ content: `extensions/${meta.id}/generated/config.ui.json`
3622
+ }
3623
+ }
3624
+ });
3625
+ }
3626
+ await manifest.save();
3627
+ }
3628
+ };
3629
+ }
3630
+ var _defaultServices = {
3631
+ generateRoot: (vars) => _rootTemplateManager.generate(vars),
3632
+ generateExtension: (key, vars) => _templateManager.generate(key, vars),
3633
+ generateCustomObject: async (vars) => {
3634
+ const plan = await import_internal._customObjectGenerators.plan(vars, {
3635
+ scope: "project",
3636
+ projectRoot: process.cwd()
3637
+ });
3638
+ return {
3639
+ files: plan.files.map((f) => ({ path: f.path, content: f.content }))
3640
+ };
3641
+ },
3642
+ generateCustomObjectsWorkspace: async (vars) => {
3643
+ const runner = new import_extensibility_tool_utils11._GeneratorRunner(import_internal._customObjectsWorkspaceGenerator);
3644
+ const plan = await runner.plan(vars, {
3645
+ scope: "project",
3646
+ projectRoot: process.cwd()
3647
+ });
3648
+ return {
3649
+ files: plan.files.map((f) => ({ path: f.path, content: f.content }))
3650
+ };
3651
+ },
3652
+ writeFiles: _writeGeneratedFiles,
3653
+ createDepManager: ({ cwd, context }) => new _DependencyManager({ cwd, ...context !== void 0 && { context } }),
3654
+ loadManifest: (manifestPath) => _StripeAppManifest.load(manifestPath),
3655
+ runHooks: runPostGenerationHooks
3656
+ };
3657
+ async function _regenAppProjectWorkspace(options, services = _defaultServices, context = (0, import_extensibility_tool_utils11._createCliContext)()) {
3658
+ const isCustomObjectMode = options.templateId === "custom-object";
3659
+ if (!isCustomObjectMode && !options.packageDir && !options.workspaceId) {
3660
+ throw new Error("At least one of packageDir or workspaceId is required");
3661
+ }
3662
+ const projectRoot = import_node_path3.default.resolve(options.root ?? ".");
3663
+ const packageDir = options.packageDir ? import_node_path3.default.resolve(options.packageDir) : void 0;
3664
+ const mode = resolveMode(options, projectRoot, packageDir);
3665
+ const metadata = isCustomObjectMode ? { id: "", name: "", version: "" } : await _resolvePackageMetadata(
3666
+ options.workspaceId,
3667
+ options.workspaceName,
3668
+ packageDir
3669
+ );
3670
+ const workspaceDir = mode.workspaceDir(metadata);
3671
+ const isRootRegen = options.templateId === void 0;
3672
+ context.ux.log(`Generating files from template: ${mode.label}...`);
3673
+ const templateOutput = await mode.generate(services, metadata);
3674
+ const allFiles = isRootRegen ? [
3675
+ ...templateOutput.files,
3676
+ ...await backfillMissingExtensionEslintConfigs(services, projectRoot)
3677
+ ] : templateOutput.files;
3678
+ const filesToWrite = options.implementationType === "remote-function" ? allFiles.filter((f) => f.path.endsWith(".schema.json")) : allFiles;
3679
+ if (isRootRegen) {
3680
+ const existingPkgPath = import_node_path3.default.join(projectRoot, "package.json");
3681
+ let existingOverrides;
3682
+ try {
3683
+ const existingPkg = JSON.parse(await (0, import_promises5.readFile)(existingPkgPath, "utf-8"));
3684
+ existingOverrides = existingPkg.pnpm?.overrides;
3685
+ } catch {
3686
+ }
3687
+ if (existingOverrides && Object.keys(existingOverrides).length > 0) {
3688
+ const pkgFile = filesToWrite.find((f) => f.path === "package.json");
3689
+ if (pkgFile) {
3690
+ let newPkg;
3691
+ try {
3692
+ newPkg = JSON.parse(pkgFile.content);
3693
+ } catch (err) {
3694
+ throw new Error(
3695
+ `Failed to parse generated package.json while preserving pnpm.overrides: ${err instanceof Error ? err.message : String(err)}`
3696
+ );
3697
+ }
3698
+ newPkg.pnpm = {
3699
+ ...newPkg.pnpm,
3700
+ overrides: { ...newPkg.pnpm?.overrides, ...existingOverrides }
3701
+ };
3702
+ pkgFile.content = JSON.stringify(newPkg, null, 2) + "\n";
3703
+ }
3704
+ }
3705
+ }
3706
+ if (isRootRegen) {
3707
+ const existingPkgPath = import_node_path3.default.join(projectRoot, "package.json");
3708
+ try {
3709
+ const existingPkg = JSON.parse(await (0, import_promises5.readFile)(existingPkgPath, "utf-8"));
3710
+ const existingOverrides = existingPkg.pnpm?.overrides;
3711
+ if (existingOverrides && Object.keys(existingOverrides).length > 0) {
3712
+ const pkgFile = filesToWrite.find((f) => f.path === "package.json");
3713
+ if (pkgFile) {
3714
+ const newPkg = JSON.parse(pkgFile.content);
3715
+ newPkg.pnpm = {
3716
+ ...newPkg.pnpm,
3717
+ overrides: { ...newPkg.pnpm?.overrides, ...existingOverrides }
3718
+ };
3719
+ pkgFile.content = JSON.stringify(newPkg, null, 2) + "\n";
3720
+ }
3721
+ }
3722
+ } catch {
3723
+ }
3724
+ }
3725
+ context.ux.log("Writing files...");
3726
+ const writeResult = await services.writeFiles(filesToWrite, {
3727
+ cwd: projectRoot,
3728
+ write: options.force ? "overwrite-all" : (path5, cwd, newContent) => _advancedDiffPrompt(path5, cwd, newContent),
3729
+ onFileWritten: (file, wasOverwrite) => {
3730
+ const verb = wasOverwrite ? "Updated" : "Wrote";
3731
+ context.ux.log(`\u2713 ${verb} ${file.path}`);
3732
+ },
3733
+ onFileSkipped: (file) => {
3734
+ context.ux.log(`- Skipped ${file.path}`);
3735
+ },
3736
+ onFileIdentical: (file) => {
3737
+ context.ux.log(`= Identical ${file.path}`);
3738
+ }
3739
+ });
3740
+ if (writeResult.aborted) {
3741
+ context.ux.log("\nAborted by user.");
3742
+ return;
3743
+ }
3744
+ if (options.implementationType !== "remote-function" && !options.skipDependencies && templateOutput.dependencies) {
3745
+ context.ux.log("\nInstalling dependencies...");
3746
+ const allDeps = [
3747
+ ...templateOutput.dependencies.runtime ?? [],
3748
+ ...templateOutput.dependencies.dev ?? []
3749
+ ];
3750
+ await installDependencies(services, workspaceDir, allDeps, context);
3751
+ }
3752
+ if (options.implementationType !== "remote-function" && !options.skipDependencies && !isRootRegen && !isCustomObjectMode) {
3753
+ await installDependencies(
3754
+ services,
3755
+ projectRoot,
3756
+ [
3757
+ _devNpmDep(
3758
+ EXTENSIBILITY_ESLINT_PLUGIN_PACKAGE_NAME,
3759
+ EXTENSIBILITY_ESLINT_PLUGIN_VERSION
3760
+ )
3761
+ ],
3762
+ context
3763
+ );
3764
+ }
3765
+ await mode.finalize?.(services, metadata, projectRoot, templateOutput, context);
3766
+ if (options.implementationType !== "remote-function" && !options.skipHooks) {
3767
+ await services.runHooks(
3768
+ templateOutput.postGenerationHooks,
3769
+ workspaceDir,
3770
+ false,
3771
+ context
3772
+ );
3773
+ }
3774
+ context.ux.log("\n\u2713 Regeneration complete");
3775
+ }
3776
+
3777
+ // src/index.ts
3778
+ var import_extensibility_tool_utils12 = require("@stripe/extensibility-tool-utils");
3779
+ // Annotate the CommonJS export names for ESM import in node:
3780
+ 0 && (module.exports = {
3781
+ _CliUx,
3782
+ _DependencyManager,
3783
+ _ExtensionTemplateManager,
3784
+ _ManifestV1,
3785
+ _ManifestV2,
3786
+ _NpmDependencyHandler,
3787
+ _SingleTemplateManager,
3788
+ _StripeAppManifest,
3789
+ _StripeCliPluginHandler,
3790
+ _TemplateManager,
3791
+ _advancedDiffPrompt,
3792
+ _createCliContext,
3793
+ _createExtensionEslintConfigFile,
3794
+ _createSimpleSingleFileTemplate,
3795
+ _createSimpleTemplate,
3796
+ _defaultServices,
3797
+ _detectPackageManager,
3798
+ _devNpmDep,
3799
+ _fs,
3800
+ _npmDep,
3801
+ _promptOverwrite,
3802
+ _regenAppProjectWorkspace,
3803
+ _regenWorkspaceOptionsSchema,
3804
+ _resolvePackageMetadata,
3805
+ _rootTemplateManager,
3806
+ _rootWorkspaceTemplate,
3807
+ _stripeCliPluginDep,
3808
+ _templateManager,
3809
+ _writeGeneratedFiles
3810
+ });