@saplings/sdk 0.0.0-stage → 0.17.1

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 (151) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +21 -0
  3. package/dist/access.d.ts +3 -0
  4. package/dist/access.js +3 -0
  5. package/dist/access.js.map +1 -0
  6. package/dist/accounts.d.ts +3 -0
  7. package/dist/accounts.js +3 -0
  8. package/dist/accounts.js.map +1 -0
  9. package/dist/analytics.d.ts +45 -0
  10. package/dist/analytics.js +129 -0
  11. package/dist/analytics.js.map +1 -0
  12. package/dist/audit.d.ts +21 -0
  13. package/dist/audit.js +36 -0
  14. package/dist/audit.js.map +1 -0
  15. package/dist/automation.d.ts +49 -0
  16. package/dist/automation.js +202 -0
  17. package/dist/automation.js.map +1 -0
  18. package/dist/billing-policy.d.ts +15 -0
  19. package/dist/billing-policy.js +17 -0
  20. package/dist/billing-policy.js.map +1 -0
  21. package/dist/billing.d.ts +53 -0
  22. package/dist/billing.js +118 -0
  23. package/dist/billing.js.map +1 -0
  24. package/dist/business-workflows.d.ts +39 -0
  25. package/dist/business-workflows.js +137 -0
  26. package/dist/business-workflows.js.map +1 -0
  27. package/dist/capabilities.d.ts +49 -0
  28. package/dist/capabilities.js +78 -0
  29. package/dist/capabilities.js.map +1 -0
  30. package/dist/cashfree.d.ts +71 -0
  31. package/dist/cashfree.js +241 -0
  32. package/dist/cashfree.js.map +1 -0
  33. package/dist/commerce.d.ts +21 -0
  34. package/dist/commerce.js +198 -0
  35. package/dist/commerce.js.map +1 -0
  36. package/dist/config.d.ts +4 -0
  37. package/dist/config.js +177 -0
  38. package/dist/config.js.map +1 -0
  39. package/dist/control-plane.d.ts +129 -0
  40. package/dist/control-plane.js +314 -0
  41. package/dist/control-plane.js.map +1 -0
  42. package/dist/data.d.ts +58 -0
  43. package/dist/data.js +214 -0
  44. package/dist/data.js.map +1 -0
  45. package/dist/domain-policy.d.ts +36 -0
  46. package/dist/domain-policy.js +114 -0
  47. package/dist/domain-policy.js.map +1 -0
  48. package/dist/feature-types.d.ts +187 -0
  49. package/dist/feature-types.js +2 -0
  50. package/dist/feature-types.js.map +1 -0
  51. package/dist/federation.d.ts +66 -0
  52. package/dist/federation.js +162 -0
  53. package/dist/federation.js.map +1 -0
  54. package/dist/flags.d.ts +27 -0
  55. package/dist/flags.js +52 -0
  56. package/dist/flags.js.map +1 -0
  57. package/dist/governance.d.ts +45 -0
  58. package/dist/governance.js +128 -0
  59. package/dist/governance.js.map +1 -0
  60. package/dist/http-idempotency.d.ts +22 -0
  61. package/dist/http-idempotency.js +42 -0
  62. package/dist/http-idempotency.js.map +1 -0
  63. package/dist/http.d.ts +2 -0
  64. package/dist/http.js +28 -0
  65. package/dist/http.js.map +1 -0
  66. package/dist/identity.d.ts +3 -0
  67. package/dist/identity.js +3 -0
  68. package/dist/identity.js.map +1 -0
  69. package/dist/impersonation.d.ts +2 -0
  70. package/dist/impersonation.js +3 -0
  71. package/dist/impersonation.js.map +1 -0
  72. package/dist/index.d.ts +210 -0
  73. package/dist/index.js +519 -0
  74. package/dist/index.js.map +1 -0
  75. package/dist/integrations.d.ts +114 -0
  76. package/dist/integrations.js +358 -0
  77. package/dist/integrations.js.map +1 -0
  78. package/dist/jobs.d.ts +29 -0
  79. package/dist/jobs.js +77 -0
  80. package/dist/jobs.js.map +1 -0
  81. package/dist/media.d.ts +18 -0
  82. package/dist/media.js +48 -0
  83. package/dist/media.js.map +1 -0
  84. package/dist/offboarding.d.ts +43 -0
  85. package/dist/offboarding.js +140 -0
  86. package/dist/offboarding.js.map +1 -0
  87. package/dist/operations.d.ts +105 -0
  88. package/dist/operations.js +286 -0
  89. package/dist/operations.js.map +1 -0
  90. package/dist/primitives.d.ts +24 -0
  91. package/dist/primitives.js +111 -0
  92. package/dist/primitives.js.map +1 -0
  93. package/dist/provider-operations.d.ts +43 -0
  94. package/dist/provider-operations.js +143 -0
  95. package/dist/provider-operations.js.map +1 -0
  96. package/dist/provider-workflow.d.ts +33 -0
  97. package/dist/provider-workflow.js +111 -0
  98. package/dist/provider-workflow.js.map +1 -0
  99. package/dist/providers.d.ts +42 -0
  100. package/dist/providers.js +168 -0
  101. package/dist/providers.js.map +1 -0
  102. package/dist/quality-config.d.ts +50 -0
  103. package/dist/quality-config.js +2 -0
  104. package/dist/quality-config.js.map +1 -0
  105. package/dist/razorpay-webhook.d.ts +38 -0
  106. package/dist/razorpay-webhook.js +106 -0
  107. package/dist/razorpay-webhook.js.map +1 -0
  108. package/dist/recurring.d.ts +53 -0
  109. package/dist/recurring.js +241 -0
  110. package/dist/recurring.js.map +1 -0
  111. package/dist/registry.d.ts +58 -0
  112. package/dist/registry.js +839 -0
  113. package/dist/registry.js.map +1 -0
  114. package/dist/reliability.d.ts +45 -0
  115. package/dist/reliability.js +147 -0
  116. package/dist/reliability.js.map +1 -0
  117. package/dist/resources.d.ts +19 -0
  118. package/dist/resources.js +87 -0
  119. package/dist/resources.js.map +1 -0
  120. package/dist/security-state.d.ts +14 -0
  121. package/dist/security-state.js +39 -0
  122. package/dist/security-state.js.map +1 -0
  123. package/dist/storage.d.ts +54 -0
  124. package/dist/storage.js +100 -0
  125. package/dist/storage.js.map +1 -0
  126. package/dist/store.d.ts +21 -0
  127. package/dist/store.js +110 -0
  128. package/dist/store.js.map +1 -0
  129. package/dist/stripe-payment.d.ts +21 -0
  130. package/dist/stripe-payment.js +132 -0
  131. package/dist/stripe-payment.js.map +1 -0
  132. package/dist/stripe-recurring.d.ts +58 -0
  133. package/dist/stripe-recurring.js +226 -0
  134. package/dist/stripe-recurring.js.map +1 -0
  135. package/dist/totp.d.ts +2 -0
  136. package/dist/totp.js +3 -0
  137. package/dist/totp.js.map +1 -0
  138. package/dist/transactional-processing.d.ts +27 -0
  139. package/dist/transactional-processing.js +129 -0
  140. package/dist/transactional-processing.js.map +1 -0
  141. package/dist/types.d.ts +367 -0
  142. package/dist/types.js +2 -0
  143. package/dist/types.js.map +1 -0
  144. package/dist/valkey.d.ts +18 -0
  145. package/dist/valkey.js +22 -0
  146. package/dist/valkey.js.map +1 -0
  147. package/dist/worker.d.ts +28 -0
  148. package/dist/worker.js +200 -0
  149. package/dist/worker.js.map +1 -0
  150. package/package.json +34 -3
  151. package/README.md +0 -3
package/dist/config.js ADDED
@@ -0,0 +1,177 @@
1
+ import { LocalBroker, MemoryEventJournal, MemoryConnectionAdmission, MemoryHierarchicalAdmission, } from '@saplings/realtime';
2
+ import { InMemoryStore } from './store.js';
3
+ import { InMemoryStorage } from './storage.js';
4
+ import { SaplingError } from './types.js';
5
+ import { saasFeatures, securityScanners } from '@saplings/catalog';
6
+ /** Single strongly typed configuration entry point. No unknown keys are silently activated. */
7
+ export function defineSaplingConfig(config) {
8
+ return config;
9
+ }
10
+ export function resolveSaplingConfig(config) {
11
+ if (!config || !config.app?.id?.trim())
12
+ throw new SaplingError('CONFIG_INVALID', 'app.id is required');
13
+ if (!['development', 'test', 'production'].includes(config.app.environment))
14
+ throw new SaplingError('CONFIG_INVALID', 'Valid app.environment is required');
15
+ const known = new Set(saasFeatures.map((f) => f.id));
16
+ for (const [id, settings] of Object.entries(config.features ?? {})) {
17
+ if (!known.has(id))
18
+ throw new SaplingError('UNKNOWN_FEATURE', `Unrecognized feature id ${id}`);
19
+ for (const [action, policy] of Object.entries(settings?.actions ?? {})) {
20
+ const operations = saasFeatures
21
+ .find((f) => f.id === id)
22
+ ?.operations?.split(';')
23
+ .map((a) => a.trim()) ?? [];
24
+ if (!operations.includes(action))
25
+ throw new SaplingError('CONFIG_INVALID', `Unknown configured action for ${id}:${action}`);
26
+ if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(action) ||
27
+ !policy ||
28
+ typeof policy !== 'object' ||
29
+ (policy.authorize !== undefined && typeof policy.authorize !== 'function') ||
30
+ (policy.inputSchema !== undefined &&
31
+ typeof policy.inputSchema.safeParseAsync !== 'function') ||
32
+ (policy.outputSchema !== undefined &&
33
+ typeof policy.outputSchema.safeParseAsync !== 'function'))
34
+ throw new SaplingError('CONFIG_INVALID', `Invalid action policy for ${id}:${action}`);
35
+ }
36
+ if (settings?.enabled !== undefined && typeof settings.enabled !== 'boolean')
37
+ throw new SaplingError('CONFIG_INVALID', `Invalid feature toggle: ${id}`);
38
+ }
39
+ const scannerIds = new Set(securityScanners.map((s) => s.id));
40
+ for (const id of config.security?.scanner?.enabledScannerIds ?? [])
41
+ if (!scannerIds.has(id))
42
+ throw new SaplingError('UNKNOWN_SCANNER', `Unrecognized scanner id ${id}`);
43
+ if ((config.platforms?.harbor && config.platforms?.gateway) ||
44
+ (config.platforms?.kingsman && config.platforms?.identity))
45
+ throw new SaplingError('CONFIG_INVALID', 'Use harbor/kingsman or deprecated gateway/identity aliases, not both');
46
+ if (config.services && config.expanded)
47
+ throw new SaplingError('CONFIG_INVALID', 'Use services or legacy expanded, not both');
48
+ const { expanded: legacyServices, ...rest } = config;
49
+ const resolved = {
50
+ ...rest,
51
+ services: config.services ?? legacyServices,
52
+ runtime: {
53
+ allowInMemoryInProduction: false,
54
+ maxUploadBytes: 10 * 1024 * 1024,
55
+ ...config.runtime,
56
+ },
57
+ tenancy: { enabled: true, enforceContext: true, ...config.tenancy },
58
+ auth: {
59
+ enabled: true,
60
+ apiKeys: { enabled: true, defaultTtlDays: 90, ...config.auth?.apiKeys },
61
+ },
62
+ access: { enabled: true, enforceOnServices: true, defaultDecision: 'deny', ...config.access },
63
+ security: {
64
+ scanner: { enabled: true, ...config.security?.scanner },
65
+ defender: {
66
+ enabled: true,
67
+ mode: 'block',
68
+ blockThreshold: 80,
69
+ alertThreshold: 45,
70
+ rateLimit: { enabled: true, maxRequests: 120, windowMs: 60000 },
71
+ ...config.security?.defender,
72
+ },
73
+ },
74
+ billing: { enabled: true, currency: 'INR', ...config.billing },
75
+ storage: {
76
+ enabled: true,
77
+ provider: 'memory',
78
+ maxUploadBytes: 10 * 1024 * 1024,
79
+ ...config.storage,
80
+ },
81
+ notifications: { enabled: true, provider: 'custom', ...config.notifications },
82
+ payments: {
83
+ enabled: true,
84
+ ...config.payments,
85
+ provider: config.payments?.provider ??
86
+ (config.providers?.payments
87
+ ? (config.providers.payments.name ?? 'custom')
88
+ : 'cashfree'),
89
+ },
90
+ audit: { enabled: true, ...config.audit },
91
+ analytics: { enabled: true, ...config.analytics },
92
+ featureFlags: { enabled: true, ...config.featureFlags },
93
+ workflows: { enabled: true, maxAttempts: 3, ...config.workflows },
94
+ observability: { enabled: true, ...config.observability },
95
+ };
96
+ if (!['cashfree', 'razorpay', 'stripe', 'custom'].includes(resolved.payments.provider))
97
+ throw new SaplingError('CONFIG_INVALID', 'Unknown payment provider');
98
+ if (config.providers?.payments &&
99
+ (config.providers.payments.name ?? 'custom') !== resolved.payments.provider)
100
+ throw new SaplingError('CONFIG_INVALID', 'Injected payment adapter must match selected provider');
101
+ if (resolved.app.environment === 'production' &&
102
+ resolved.payments.enabled &&
103
+ resolved.payments.cashfree &&
104
+ resolved.payments.provider === 'cashfree' &&
105
+ resolved.payments.cashfree.environment !== 'production')
106
+ throw new SaplingError('INSECURE_CONFIG', 'Production Cashfree requires explicit production environment');
107
+ const defender = resolved.security.defender;
108
+ for (const n of [defender.blockThreshold, defender.alertThreshold])
109
+ if (typeof n !== 'number' || !Number.isFinite(n) || n < 1 || n > 100)
110
+ throw new SaplingError('CONFIG_INVALID', 'Defender thresholds must be between 1 and 100');
111
+ const rt = defender.rateLimit;
112
+ if (rt?.maxRequests !== undefined && (!Number.isInteger(rt.maxRequests) || rt.maxRequests < 1))
113
+ throw new SaplingError('CONFIG_INVALID', 'Invalid rate limit maxRequests');
114
+ if (rt?.windowMs !== undefined && rt.windowMs < 1000)
115
+ throw new SaplingError('CONFIG_INVALID', 'Invalid rate limit windowMs');
116
+ if (resolved.runtime.maxUploadBytes < 1 || resolved.storage.maxUploadBytes < 1)
117
+ throw new SaplingError('CONFIG_INVALID', 'maxUploadBytes must be positive');
118
+ if (resolved.services?.encryptionKey && resolved.services.encryptionKey.byteLength !== 32)
119
+ throw new SaplingError('CONFIG_INVALID', 'Encryption key must be 32 bytes');
120
+ if (resolved.middleware?.timeoutMs !== undefined &&
121
+ (!Number.isSafeInteger(resolved.middleware.timeoutMs) ||
122
+ resolved.middleware.timeoutMs < 1 ||
123
+ resolved.middleware.timeoutMs > 3600000))
124
+ throw new SaplingError('CONFIG_INVALID', 'Invalid HTTP deadline');
125
+ if (resolved.middleware?.requestLogging && !resolved.middleware.log)
126
+ throw new SaplingError('CONFIG_INVALID', 'Request logging requires a callback');
127
+ if (resolved.realtime?.enabled === true &&
128
+ (!resolved.realtime.authenticate || !resolved.realtime.authorize))
129
+ throw new SaplingError('CONFIG_INVALID', 'Realtime authentication and authorization required');
130
+ if (resolved.app.environment === 'production') {
131
+ if (resolved.services?.offboarding && !resolved.services.offboarding.legalHold)
132
+ throw new SaplingError('INSECURE_CONFIG', 'Production offboarding requires a legal-hold policy');
133
+ if (resolved.realtime?.enabled === true &&
134
+ (resolved.realtime.admission instanceof MemoryConnectionAdmission ||
135
+ resolved.realtime.admission instanceof MemoryHierarchicalAdmission))
136
+ throw new SaplingError('INSECURE_CONFIG', 'Production admission requires shared storage');
137
+ if (resolved.realtime?.enabled === true &&
138
+ (resolved.realtime.journal
139
+ ? resolved.realtime.journal instanceof MemoryEventJournal
140
+ : !resolved.realtime.broker || resolved.realtime.broker instanceof LocalBroker))
141
+ throw new SaplingError('INSECURE_CONFIG', 'Production realtime requires a shared broker or persistent journal');
142
+ if (resolved.runtime.allowInMemoryInProduction ||
143
+ resolved.providers?.store instanceof InMemoryStore ||
144
+ resolved.providers?.storage instanceof InMemoryStorage)
145
+ throw new SaplingError('INSECURE_CONFIG', 'Volatile production state is prohibited');
146
+ if (!resolved.providers?.store)
147
+ throw new SaplingError('PRODUCTION_STORE_REQUIRED', 'Provide a persistent store adapter in production');
148
+ if (resolved.storage.enabled && !resolved.providers?.storage)
149
+ throw new SaplingError('PRODUCTION_STORAGE_REQUIRED', 'Provide a persistent storage adapter in production');
150
+ if (resolved.tenancy.enforceContext &&
151
+ !resolved.hooks?.resolveRequestContext &&
152
+ !resolved.providers?.authentication)
153
+ throw new SaplingError('PRODUCTION_CONTEXT_REQUIRED', 'Provide verified resolveRequestContext in production');
154
+ if (!resolved.providers?.store?.transaction)
155
+ throw new SaplingError('TRANSACTION_REQUIRED', 'Production store must implement transactions');
156
+ if (!resolved.audit.enabled ||
157
+ !resolved.tenancy.enabled ||
158
+ !resolved.auth.enabled ||
159
+ resolved.security.defender.rateLimit?.enabled === false ||
160
+ !resolved.access.enabled ||
161
+ !resolved.access.enforceOnServices ||
162
+ resolved.access.defaultDecision !== 'deny' ||
163
+ !resolved.tenancy.enforceContext ||
164
+ !resolved.security.defender.enabled ||
165
+ resolved.security.defender.mode !== 'block')
166
+ throw new SaplingError('INSECURE_CONFIG', 'Production requires fail-closed access, tenant context and blocking defender');
167
+ if (resolved.security.defender.policy?.csrf?.enabled &&
168
+ !resolved.security.defender.policy.csrf.verifyToken)
169
+ throw new SaplingError('INSECURE_CONFIG', 'Cookie CSRF requires a session-bound token verifier in production');
170
+ if (resolved.security.defender.excludedPaths?.length)
171
+ throw new SaplingError('INSECURE_CONFIG', 'Production defender path exclusions prohibited; use scoped policies instead');
172
+ if (resolved.security.defender.policy?.failureMode === 'monitor')
173
+ throw new SaplingError('INSECURE_CONFIG', 'Production distributed rate limiter must fail closed');
174
+ }
175
+ return resolved;
176
+ }
177
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,kBAAkB,EAClB,yBAAyB,EACzB,2BAA2B,GAC5B,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAA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ChD,CAAC,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW;YAEnD,MAAM,IAAI,YAAY,CACpB,iBAAiB,EACjB,mEAAmE,CACpE,CAAC;QACJ,IAAI,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,aAAa,EAAE,MAAM;YAClD,MAAM,IAAI,YAAY,CACpB,iBAAiB,EACjB,6EAA6E,CAC9E,CAAC;QACJ,IAAI,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,MAAM,EAAE,WAAW,KAAK,SAAS;YAC9D,MAAM,IAAI,YAAY,CACpB,iBAAiB,EACjB,sDAAsD,CACvD,CAAC;IACN,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC"}
@@ -0,0 +1,129 @@
1
+ import type { ActorContext, FeatureAdapter, JsonRecord } from './types.js';
2
+ export type ProviderToken = () => Promise<string>;
3
+ export interface WorkflowTarget {
4
+ workflow: string;
5
+ ref: string;
6
+ inputNames?: string[];
7
+ tenantIds: string[];
8
+ }
9
+ /** Fixed workflow IDs, refs and tenants. The workflows themselves must use protected environments and safe input handling. */
10
+ export declare class GitHubWorkflowAdapter implements FeatureAdapter {
11
+ private targets;
12
+ private client;
13
+ constructor(owner: string, repository: string, token: ProviderToken, targets: Record<string, WorkflowTarget>);
14
+ execute({ ctx, featureId, action, input }: Parameters<FeatureAdapter['execute']>[0]): Promise<{
15
+ state: string;
16
+ matches: number;
17
+ reference?: undefined;
18
+ conclusion?: undefined;
19
+ } | {
20
+ state: string;
21
+ reference: string;
22
+ conclusion: unknown;
23
+ matches?: undefined;
24
+ } | {
25
+ accepted: boolean;
26
+ workflow: string;
27
+ provider: JsonRecord;
28
+ completion: string;
29
+ }>;
30
+ operationStatus(ctx: ActorContext, featureId: string, action: string, operationId: string): Promise<{
31
+ state: string;
32
+ matches: number;
33
+ reference?: undefined;
34
+ conclusion?: undefined;
35
+ } | {
36
+ state: string;
37
+ reference: string;
38
+ conclusion: unknown;
39
+ matches?: undefined;
40
+ }>;
41
+ assertCorrelation(featureId: string, action: string): void;
42
+ }
43
+ export declare class KubernetesScaleAdapter implements FeatureAdapter {
44
+ private targets;
45
+ private client;
46
+ constructor(apiBase: string, token: ProviderToken, targets: Record<string, {
47
+ namespace: string;
48
+ deployment: string;
49
+ tenantIds: string[];
50
+ min: number;
51
+ max: number;
52
+ }>);
53
+ execute({ ctx, featureId, action, input }: Parameters<FeatureAdapter['execute']>[0]): Promise<JsonRecord>;
54
+ }
55
+ export declare class CloudflareCacheAdapter implements FeatureAdapter {
56
+ private targets;
57
+ private client;
58
+ constructor(token: ProviderToken, targets: Record<string, {
59
+ zoneId: string;
60
+ origin: string;
61
+ tenantIds: string[];
62
+ prefix: string;
63
+ }>);
64
+ execute({ ctx, featureId, action, input }: Parameters<FeatureAdapter['execute']>[0]): Promise<{
65
+ accepted: boolean;
66
+ }>;
67
+ }
68
+ /** Sends an already formed OTLP/HTTP JSON trace payload. Use official OTel SDK to instrument application spans. */
69
+ export declare class OtlpTraceAdapter implements FeatureAdapter {
70
+ private client;
71
+ private sent;
72
+ private failed;
73
+ constructor(base: string, token: ProviderToken);
74
+ execute({ featureId, action, input }: Parameters<FeatureAdapter['execute']>[0]): Promise<{
75
+ sent: number;
76
+ failed: number;
77
+ accepted?: undefined;
78
+ partialSuccess?: undefined;
79
+ } | {
80
+ accepted: boolean;
81
+ partialSuccess: {};
82
+ sent?: undefined;
83
+ failed?: undefined;
84
+ } | {
85
+ accepted: boolean;
86
+ sent?: undefined;
87
+ failed?: undefined;
88
+ partialSuccess?: undefined;
89
+ }>;
90
+ }
91
+ /** Only setup intents and tokenized provider references. The mapping is supplied by trusted backend code, not user IDs from a request. */
92
+ export declare class StripePaymentMethodsAdapter implements FeatureAdapter {
93
+ private token;
94
+ private customer;
95
+ private bulk;
96
+ constructor(token: ProviderToken, customer: (ctx: ActorContext) => Promise<string>);
97
+ private request;
98
+ execute({ ctx, featureId, action, input }: Parameters<FeatureAdapter['execute']>[0]): Promise<{
99
+ id: unknown;
100
+ clientSecret: unknown;
101
+ status: unknown;
102
+ items?: undefined;
103
+ hasMore?: undefined;
104
+ detached?: undefined;
105
+ } | {
106
+ items: {
107
+ id: unknown;
108
+ type: unknown;
109
+ brand: unknown;
110
+ last4: unknown;
111
+ expMonth: unknown;
112
+ expYear: unknown;
113
+ }[];
114
+ hasMore: unknown;
115
+ id?: undefined;
116
+ clientSecret?: undefined;
117
+ status?: undefined;
118
+ detached?: undefined;
119
+ } | {
120
+ id: unknown;
121
+ detached: boolean;
122
+ clientSecret?: undefined;
123
+ status?: undefined;
124
+ items?: undefined;
125
+ hasMore?: undefined;
126
+ }>;
127
+ }
128
+ /** Wrap a fixed GitHub workflow dispatch/status pair for ProviderOperations. Configure run-name: sapling:${{ inputs.operation_id }}. */
129
+ export declare function githubOperationDriver(adapter: GitHubWorkflowAdapter, featureId: string, action: string): import('./provider-operations.js').OperationDriver;
@@ -0,0 +1,314 @@
1
+ import { boundedResponseText } from './http.js';
2
+ import { fail, hash, integer, object, strings, text } from './primitives.js';
3
+ import { Bulkhead, CircuitBreaker, timeout } from './reliability.js';
4
+ const segment = (s) => encodeURIComponent(s);
5
+ class JsonClient {
6
+ token;
7
+ extra;
8
+ limiter = new Bulkhead(16);
9
+ breaker = new CircuitBreaker();
10
+ base;
11
+ constructor(base, token, extra = {}) {
12
+ this.token = token;
13
+ this.extra = extra;
14
+ this.base = new URL(base);
15
+ if (this.base.protocol !== 'https:' ||
16
+ this.base.username ||
17
+ this.base.password ||
18
+ this.base.search ||
19
+ this.base.hash)
20
+ throw Error('Fixed HTTPS provider base required');
21
+ }
22
+ async request(path, method = 'GET', payload, headers = {}) {
23
+ return this.limiter.run(() => this.breaker.run(() => timeout(async (signal) => {
24
+ const url = new URL(this.base.href.replace(/\/$/, '') + path);
25
+ if (url.origin !== this.base.origin)
26
+ throw Error('Provider origin mismatch');
27
+ const token = await this.token();
28
+ if (signal.aborted)
29
+ throw Error('Provider deadline');
30
+ const res = await fetch(url, {
31
+ method,
32
+ redirect: 'error',
33
+ signal,
34
+ headers: {
35
+ authorization: `Bearer ${token}`,
36
+ accept: 'application/json',
37
+ ...this.extra,
38
+ ...(payload ? { 'content-type': 'application/json' } : {}),
39
+ ...headers,
40
+ },
41
+ body: payload ? JSON.stringify(payload) : undefined,
42
+ });
43
+ if (!res.ok) {
44
+ await res.body?.cancel();
45
+ return fail(`Provider returned ${res.status}`, 'PROVIDER_FAILED', 502);
46
+ }
47
+ const raw = await boundedResponseText(res, 2_000_000);
48
+ return raw ? object(JSON.parse(raw)) : {};
49
+ }, 10000)));
50
+ }
51
+ }
52
+ /** Fixed workflow IDs, refs and tenants. The workflows themselves must use protected environments and safe input handling. */
53
+ export class GitHubWorkflowAdapter {
54
+ targets;
55
+ client;
56
+ constructor(owner, repository, token, targets) {
57
+ this.targets = targets;
58
+ this.client = new JsonClient(`https://api.github.com/repos/${segment(owner)}/${segment(repository)}`, token, { 'x-github-api-version': '2022-11-28', accept: 'application/vnd.github+json' });
59
+ }
60
+ async execute({ ctx, featureId, action, input }) {
61
+ const key = `${featureId}:${action}`, target = this.targets[key];
62
+ if (!Object.hasOwn(this.targets, key) || !target.tenantIds.includes(ctx.tenantId))
63
+ return fail('Workflow not authorized', 'FORBIDDEN', 403);
64
+ const path = `/actions/workflows/${segment(target.workflow)}`;
65
+ if (action === 'status')
66
+ return this.operationStatus(ctx, featureId, 'status', text(input.operationId, 'operationId', 100));
67
+ if (['destroy', 'restore', 'rollback', 'apply', 'activate', 'remove', 'configure'].includes(action) &&
68
+ input.confirm !== true)
69
+ return fail('Explicit confirmation required');
70
+ const allowed = target.inputNames ?? [];
71
+ const inputs = {};
72
+ for (const name of allowed) {
73
+ if (name === 'tenant_id')
74
+ inputs[name] = ctx.tenantId;
75
+ else if (name === 'operation_id')
76
+ inputs[name] = text(input.operationId, 'operationId', 100);
77
+ else if (input[name] !== undefined)
78
+ inputs[name] = text(input[name], name, 500);
79
+ }
80
+ const result = await this.client.request(path + '/dispatches', 'POST', {
81
+ ref: target.ref,
82
+ inputs,
83
+ });
84
+ return {
85
+ accepted: true,
86
+ workflow: target.workflow,
87
+ provider: result,
88
+ completion: 'check workflow status',
89
+ };
90
+ }
91
+ async operationStatus(ctx, featureId, action, operationId) {
92
+ const key = `${featureId}:${action}`, target = this.targets[key];
93
+ if (!Object.hasOwn(this.targets, key) || !target.tenantIds.includes(ctx.tenantId))
94
+ return fail('Workflow not authorized', 'FORBIDDEN', 403);
95
+ if (!(target.inputNames ?? []).includes('operation_id'))
96
+ return fail('Operation correlation not configured', 'CONFIG_REQUIRED', 503);
97
+ const r = await this.client.request(`/actions/workflows/${segment(target.workflow)}/runs?event=workflow_dispatch&per_page=100`);
98
+ const rows = (Array.isArray(r.workflow_runs) ? r.workflow_runs : [])
99
+ .map(object)
100
+ .filter((run) => run.display_title === `sapling:${operationId}` &&
101
+ run.event === 'workflow_dispatch' &&
102
+ run.head_branch === target.ref);
103
+ if (rows.length !== 1)
104
+ return { state: 'unknown', matches: rows.length };
105
+ const run = rows[0];
106
+ if (typeof run.id !== 'number' || !Number.isSafeInteger(run.id))
107
+ return fail('Malformed workflow run', 'PROVIDER_FAILED', 502);
108
+ return {
109
+ state: run.status === 'completed'
110
+ ? run.conclusion === 'success'
111
+ ? 'succeeded'
112
+ : 'failed'
113
+ : 'running',
114
+ reference: String(run.id),
115
+ conclusion: run.conclusion,
116
+ };
117
+ }
118
+ assertCorrelation(featureId, action) {
119
+ const target = this.targets[`${featureId}:${action}`];
120
+ if (!target || !(target.inputNames ?? []).includes('operation_id'))
121
+ throw Error('Workflow operation_id input required');
122
+ }
123
+ }
124
+ export class KubernetesScaleAdapter {
125
+ targets;
126
+ client;
127
+ constructor(apiBase, token, targets) {
128
+ this.targets = targets;
129
+ this.client = new JsonClient(apiBase, token);
130
+ }
131
+ async execute({ ctx, featureId, action, input }) {
132
+ if (featureId !== 'SAAS-167' || !['scale', 'status'].includes(action))
133
+ return fail('Unsupported operation');
134
+ const name = text(input.target), target = this.targets[name];
135
+ if (!Object.hasOwn(this.targets, name) || !target.tenantIds.includes(ctx.tenantId))
136
+ return fail('Scale target not authorized', 'FORBIDDEN', 403);
137
+ const path = `/apis/apps/v1/namespaces/${segment(target.namespace)}/deployments/${segment(target.deployment)}/scale`;
138
+ if (action === 'status')
139
+ return this.client.request(path);
140
+ if (input.confirm !== true)
141
+ return fail('Explicit scale confirmation required');
142
+ const replicas = integer(input.replicas, 'replicas', target.min, target.max);
143
+ return this.client.request(path, 'PATCH', { spec: { replicas } }, { 'content-type': 'application/merge-patch+json' });
144
+ }
145
+ }
146
+ export class CloudflareCacheAdapter {
147
+ targets;
148
+ client;
149
+ constructor(token, targets) {
150
+ this.targets = targets;
151
+ this.client = new JsonClient('https://api.cloudflare.com/client/v4', token);
152
+ }
153
+ async execute({ ctx, featureId, action, input }) {
154
+ if (featureId !== 'SAAS-094' || !['purge', 'configure'].includes(action))
155
+ return fail('Unsupported operation');
156
+ const target = text(input.target), config = this.targets[target];
157
+ if (!Object.hasOwn(this.targets, target) || !config.tenantIds.includes(ctx.tenantId))
158
+ return fail('CDN target not authorized', 'FORBIDDEN', 403);
159
+ if (action === 'configure')
160
+ return fail('Cache configuration requires reviewed control-plane workflow', 'PROVIDER_REQUIRED', 503);
161
+ const files = strings(input.urls);
162
+ if (!files.length || files.length > 30)
163
+ return fail('Specify 1–30 URLs');
164
+ for (const raw of files) {
165
+ const url = new URL(raw);
166
+ if (url.origin !== config.origin ||
167
+ url.username ||
168
+ url.password ||
169
+ url.hash ||
170
+ !(url.pathname === config.prefix ||
171
+ url.pathname.startsWith(config.prefix.endsWith('/') ? config.prefix : config.prefix + '/')))
172
+ return fail('URL outside tenant cache scope', 'FORBIDDEN', 403);
173
+ }
174
+ const result = await this.client.request(`/zones/${segment(config.zoneId)}/purge_cache`, 'POST', { files });
175
+ if (result.success !== true)
176
+ return fail('Cache purge rejected', 'PROVIDER_FAILED', 502);
177
+ return { accepted: true };
178
+ }
179
+ }
180
+ /** Sends an already formed OTLP/HTTP JSON trace payload. Use official OTel SDK to instrument application spans. */
181
+ export class OtlpTraceAdapter {
182
+ client;
183
+ sent = 0;
184
+ failed = 0;
185
+ constructor(base, token) {
186
+ this.client = new JsonClient(base, token);
187
+ }
188
+ async execute({ featureId, action, input }) {
189
+ if (featureId !== 'SAAS-155')
190
+ return fail('Unsupported operation');
191
+ if (action === 'status')
192
+ return { sent: this.sent, failed: this.failed };
193
+ if (action !== 'export')
194
+ return fail('Unsupported action');
195
+ const spans = input.resourceSpans;
196
+ if (!Array.isArray(spans) || Buffer.byteLength(JSON.stringify(spans)) > 1000000)
197
+ return fail('Bounded OTLP resourceSpans required');
198
+ try {
199
+ const r = await this.client.request('/v1/traces', 'POST', { resourceSpans: spans });
200
+ if (r.partialSuccess && Number(object(r.partialSuccess).rejectedSpans ?? 0) > 0) {
201
+ this.failed++;
202
+ return { accepted: false, partialSuccess: r.partialSuccess };
203
+ }
204
+ this.sent++;
205
+ return { accepted: true };
206
+ }
207
+ catch (e) {
208
+ this.failed++;
209
+ throw e;
210
+ }
211
+ }
212
+ }
213
+ /** Only setup intents and tokenized provider references. The mapping is supplied by trusted backend code, not user IDs from a request. */
214
+ export class StripePaymentMethodsAdapter {
215
+ token;
216
+ customer;
217
+ bulk = new Bulkhead(16);
218
+ constructor(token, customer) {
219
+ this.token = token;
220
+ this.customer = customer;
221
+ }
222
+ async request(path, method = 'GET', params, idempotency) {
223
+ return this.bulk.run(async () => {
224
+ const r = await fetch('https://api.stripe.com/v1' + path, {
225
+ method,
226
+ redirect: 'error',
227
+ signal: AbortSignal.timeout(10000),
228
+ headers: {
229
+ authorization: `Bearer ${await this.token()}`,
230
+ ...(params ? { 'content-type': 'application/x-www-form-urlencoded' } : {}),
231
+ ...(idempotency ? { 'idempotency-key': idempotency } : {}),
232
+ },
233
+ body: params ? new URLSearchParams(params) : undefined,
234
+ });
235
+ if (!r.ok) {
236
+ await r.body?.cancel();
237
+ return fail(`Stripe status ${r.status}`, 'PROVIDER_FAILED', 502);
238
+ }
239
+ const raw = await boundedResponseText(r, 1000000);
240
+ return object(JSON.parse(raw));
241
+ });
242
+ }
243
+ async execute({ ctx, featureId, action, input }) {
244
+ if (featureId !== 'SAAS-043')
245
+ return fail('Unsupported feature');
246
+ const customer = await this.customer(ctx);
247
+ if (!/^cus_[A-Za-z0-9]+$/.test(customer))
248
+ return fail('Verified customer mapping required', 'FORBIDDEN', 403);
249
+ if (action === 'attach') {
250
+ const key = hash(`${ctx.tenantId}:${customer}:${text(input.idempotencyKey)}`);
251
+ const r = await this.request('/setup_intents', 'POST', { customer, usage: 'off_session', 'payment_method_types[0]': 'card' }, key);
252
+ return { id: r.id, clientSecret: r.client_secret, status: r.status };
253
+ }
254
+ if (action === 'list') {
255
+ const r = await this.request(`/customers/${segment(customer)}/payment_methods?type=card&limit=100`);
256
+ return {
257
+ items: (Array.isArray(r.data) ? r.data : []).map((v) => {
258
+ const x = object(v), card = object(x.card ?? {});
259
+ return {
260
+ id: x.id,
261
+ type: x.type,
262
+ brand: card.brand,
263
+ last4: card.last4,
264
+ expMonth: card.exp_month,
265
+ expYear: card.exp_year,
266
+ };
267
+ }),
268
+ hasMore: r.has_more,
269
+ };
270
+ }
271
+ if (action === 'detach') {
272
+ const id = text(input.paymentMethodId);
273
+ if (!/^pm_[A-Za-z0-9]+$/.test(id))
274
+ return fail('Invalid payment method');
275
+ const r = await this.request(`/payment_methods/${segment(id)}`);
276
+ if (r.customer !== customer)
277
+ return fail('Payment method not owned by customer', 'FORBIDDEN', 403);
278
+ const result = await this.request(`/payment_methods/${segment(id)}/detach`, 'POST', {}, hash(`${ctx.tenantId}:${customer}:${id}:detach`));
279
+ return { id: result.id, detached: result.customer === null };
280
+ }
281
+ return fail('Unknown payment action');
282
+ }
283
+ }
284
+ /** Wrap a fixed GitHub workflow dispatch/status pair for ProviderOperations. Configure run-name: sapling:${{ inputs.operation_id }}. */
285
+ export function githubOperationDriver(adapter, featureId, action) {
286
+ adapter.assertCorrelation(featureId, action);
287
+ return {
288
+ submit: async (ctx, id, input) => {
289
+ await adapter.execute({
290
+ ctx,
291
+ featureId,
292
+ action,
293
+ input: { ...input, operationId: id },
294
+ options: {},
295
+ });
296
+ return { state: 'accepted' };
297
+ },
298
+ inspect: async (ctx, id) => {
299
+ const r = await adapter.operationStatus(ctx, featureId, action, id);
300
+ const result = object(r);
301
+ return {
302
+ state: result.state === 'succeeded'
303
+ ? 'succeeded'
304
+ : result.state === 'failed'
305
+ ? 'failed'
306
+ : result.state === 'running'
307
+ ? 'running'
308
+ : 'unknown',
309
+ reference: typeof result.reference === 'string' ? result.reference : undefined,
310
+ };
311
+ },
312
+ };
313
+ }
314
+ //# sourceMappingURL=control-plane.js.map