anhedral 0.15.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -38
- package/assets/stack/ai-schema.ts.txt +5 -0
- package/assets/stack/ai.ts.txt +30 -0
- package/assets/stack/api-index.ts.txt +15 -0
- package/assets/stack/auth-features.ts.txt +4 -0
- package/assets/stack/auth-journal.json.txt +13 -0
- package/assets/stack/auth-migration.sql.txt +53 -0
- package/assets/stack/auth-routes.ts.txt +11 -0
- package/assets/stack/auth-schema.ts.txt +64 -0
- package/assets/stack/auth-snapshot.json.txt +346 -0
- package/assets/stack/auth.ts.txt +32 -0
- package/assets/stack/billing-mode.ts.txt +8 -0
- package/assets/stack/billing-schema.ts.txt +11 -0
- package/assets/stack/desktop.rs.txt +21 -0
- package/assets/stack/entitlement-guard.ts.txt +32 -0
- package/assets/stack/entitlements.ts.txt +8 -0
- package/assets/stack/events-schema.ts.txt +12 -0
- package/assets/stack/events.ts.txt +59 -0
- package/assets/stack/mobile-auth.ts.txt +25 -0
- package/assets/stack/mobile-billing.tsx.txt +63 -0
- package/assets/stack/mobile-session.tsx.txt +83 -0
- package/assets/stack/native-button.tsx.txt +108 -0
- package/assets/stack/native-global.css.txt +4 -0
- package/assets/stack/native-lib-utils.ts.txt +5 -0
- package/assets/stack/native-metro.config.js.txt +6 -0
- package/assets/stack/native-nativewind-env.d.ts.txt +1 -0
- package/assets/stack/native-tailwind.config.js.txt +73 -0
- package/assets/stack/native-text.tsx.txt +89 -0
- package/assets/stack/purchases.ts.txt +65 -0
- package/assets/stack/revenuecat.ts.txt +88 -0
- package/assets/stack/rtc-schema.ts.txt +10 -0
- package/assets/stack/rtc.ts.txt +122 -0
- package/assets/stack/security.ts.txt +31 -0
- package/assets/stack/storage.ts.txt +36 -0
- package/assets/stack/stripe.ts.txt +126 -0
- package/assets/stack/web-sign-in.tsx.txt +51 -0
- package/assets/ui/LICENSE.react-native-reusables +21 -0
- package/assets/ui/UPSTREAM.json +7 -1
- package/assets/ui/catalog.json +891 -0
- package/assets/ui/extensions/registry.json +6 -0
- package/assets/ui/native/_controls.tsx +521 -0
- package/assets/ui/native/_core.tsx +118 -0
- package/assets/ui/native/_data.tsx +200 -0
- package/assets/ui/native/_display.tsx +453 -0
- package/assets/ui/native/_feedback.tsx +242 -0
- package/assets/ui/native/_legacy-dialog.tsx +38 -0
- package/assets/ui/native/_motion.tsx +520 -0
- package/assets/ui/native/_overlay.tsx +402 -0
- package/assets/ui/native/_selection.tsx +366 -0
- package/assets/ui/native/accordion.tsx +1 -0
- package/assets/ui/native/alert-dialog.tsx +11 -0
- package/assets/ui/native/alert.tsx +1 -0
- package/assets/ui/native/aspect-ratio.tsx +1 -0
- package/assets/ui/native/attachment.tsx +8 -0
- package/assets/ui/native/avatar.tsx +8 -0
- package/assets/ui/native/badge.tsx +1 -0
- package/assets/ui/native/breadcrumb.tsx +9 -0
- package/assets/ui/native/bubble.tsx +1 -0
- package/assets/ui/native/button-group.tsx +1 -0
- package/assets/ui/native/button.tsx +2 -1
- package/assets/ui/native/calendar.tsx +170 -0
- package/assets/ui/native/card.tsx +16 -5
- package/assets/ui/native/carousel.tsx +1 -0
- package/assets/ui/native/chart.tsx +193 -0
- package/assets/ui/native/checkbox.tsx +1 -0
- package/assets/ui/native/code-block.tsx +137 -0
- package/assets/ui/native/collapsible.tsx +1 -0
- package/assets/ui/native/combobox.tsx +1 -0
- package/assets/ui/native/command.tsx +11 -0
- package/assets/ui/native/context-menu.tsx +16 -0
- package/assets/ui/native/data-table.tsx +1 -0
- package/assets/ui/native/date-picker.tsx +43 -0
- package/assets/ui/native/dialog.tsx +14 -74
- package/assets/ui/native/direction.tsx +1 -0
- package/assets/ui/native/drawer.tsx +10 -0
- package/assets/ui/native/dropdown-menu.tsx +16 -0
- package/assets/ui/native/empty.tsx +8 -0
- package/assets/ui/native/field.tsx +13 -0
- package/assets/ui/native/hover-card.tsx +1 -0
- package/assets/ui/native/input-group.tsx +8 -0
- package/assets/ui/native/input-otp.tsx +1 -0
- package/assets/ui/native/input.tsx +2 -1
- package/assets/ui/native/item.tsx +12 -0
- package/assets/ui/native/kbd.tsx +1 -0
- package/assets/ui/native/marker.tsx +1 -0
- package/assets/ui/native/menubar.tsx +17 -0
- package/assets/ui/native/message-scroller.tsx +6 -0
- package/assets/ui/native/message.tsx +10 -0
- package/assets/ui/native/native-select.tsx +1 -0
- package/assets/ui/native/navigation-menu.tsx +10 -0
- package/assets/ui/native/pagination.tsx +9 -0
- package/assets/ui/native/popover.tsx +1 -0
- package/assets/ui/native/progress.tsx +1 -0
- package/assets/ui/native/questionnaire.tsx +130 -0
- package/assets/ui/native/radio-group.tsx +1 -0
- package/assets/ui/native/registry.json +1103 -0
- package/assets/ui/native/resizable.tsx +1 -0
- package/assets/ui/native/scroll-area.tsx +1 -0
- package/assets/ui/native/select.tsx +11 -0
- package/assets/ui/native/separator.tsx +1 -0
- package/assets/ui/native/sheet.tsx +10 -0
- package/assets/ui/native/sidebar.tsx +22 -0
- package/assets/ui/native/skeleton.tsx +1 -0
- package/assets/ui/native/slider.tsx +1 -0
- package/assets/ui/native/spinner.tsx +1 -0
- package/assets/ui/native/switch.tsx +1 -0
- package/assets/ui/native/table.tsx +10 -0
- package/assets/ui/native/tabs.tsx +1 -0
- package/assets/ui/native/textarea.tsx +1 -0
- package/assets/ui/native/toast.tsx +11 -0
- package/assets/ui/native/toggle-group.tsx +1 -0
- package/assets/ui/native/toggle.tsx +1 -0
- package/assets/ui/native/tooltip.tsx +1 -0
- package/assets/ui/native/trace.tsx +20 -0
- package/assets/ui/native/typography.tsx +15 -0
- package/dist/bin.js +7 -12
- package/dist/capabilities.d.ts +4 -33
- package/dist/capabilities.js +2 -66
- package/dist/capability-catalog.d.ts +83 -0
- package/dist/capability-catalog.js +121 -0
- package/dist/capability-command.d.ts +3 -0
- package/dist/capability-command.js +188 -0
- package/dist/capability-editor.d.ts +17 -0
- package/dist/capability-editor.js +97 -0
- package/dist/capability-recipes.d.ts +4 -0
- package/dist/capability-recipes.js +520 -0
- package/dist/capability-references.d.ts +4 -0
- package/dist/capability-references.js +7 -0
- package/dist/cli-commands.d.ts +1 -2
- package/dist/cli-commands.js +10 -104
- package/dist/cli-output.d.ts +1 -2
- package/dist/cli-output.js +6 -251
- package/dist/command-schema.js +39 -322
- package/dist/dependencies.d.ts +29 -6
- package/dist/dependencies.js +61 -14
- package/dist/index.d.ts +1 -42
- package/dist/index.js +1 -27
- package/dist/platforms/mobile.js +1 -20
- package/dist/platforms/web.d.ts +1 -1
- package/dist/platforms/web.js +27 -75
- package/dist/project-config.d.ts +2 -13
- package/dist/project-config.js +10 -82
- package/dist/registry/options.js +1 -5
- package/dist/registry/resolve.d.ts +1 -1
- package/dist/registry/resolve.js +2 -10
- package/dist/registry/usage.js +3 -9
- package/dist/scaffold/backend.js +0 -3
- package/dist/scaffold/database.js +2 -1
- package/dist/scaffold/documentation.js +82 -20
- package/dist/scaffold/expo-runtime.js +3 -4
- package/dist/scaffold/native-ui.js +12 -7
- package/dist/scaffold/stack-documentation.js +1 -1
- package/dist/scaffold/storage.d.ts +2 -0
- package/dist/scaffold/storage.js +21 -0
- package/dist/scaffold/workspace.js +26 -21
- package/dist/stack-registry.d.ts +2 -8
- package/dist/stack-registry.js +11 -87
- package/dist/standard.js +1 -11
- package/dist/ui-catalog.d.ts +26 -0
- package/dist/ui-catalog.js +31 -0
- package/dist/ui-command.d.ts +3 -0
- package/dist/ui-command.js +219 -0
- package/dist/ui-project.d.ts +22 -0
- package/dist/ui-project.js +110 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/docs/anhedral-stack.md +4 -20
- package/docs/capabilities.md +110 -0
- package/docs/native-ui.md +102 -0
- package/docs/software-factory.md +16 -44
- package/docs/stack-standard.md +11 -60
- package/docs/ui.md +33 -0
- package/docs/verification.md +191 -0
- package/package.json +19 -18
- package/dist/access.d.ts +0 -10
- package/dist/access.js +0 -93
- package/dist/auth-schema-snapshot.d.ts +0 -346
- package/dist/auth-schema-snapshot.js +0 -347
- package/dist/auth-schema.d.ts +0 -1
- package/dist/auth-schema.js +0 -57
- package/dist/capability-contract.d.ts +0 -47
- package/dist/capability-contract.js +0 -129
- package/dist/catalog-model.d.ts +0 -24
- package/dist/catalog-model.js +0 -1
- package/dist/catalog-registration.d.ts +0 -16
- package/dist/catalog-registration.js +0 -22
- package/dist/catalog-snapshot.d.ts +0 -5
- package/dist/catalog-snapshot.js +0 -97
- package/dist/cli-delivery.d.ts +0 -3
- package/dist/cli-delivery.js +0 -112
- package/dist/cloudflare.d.ts +0 -25
- package/dist/cloudflare.js +0 -226
- package/dist/delivery-evidence.d.ts +0 -62
- package/dist/delivery-evidence.js +0 -157
- package/dist/delivery.d.ts +0 -82
- package/dist/delivery.js +0 -489
- package/dist/inspector-model.d.ts +0 -123
- package/dist/inspector-model.js +0 -1
- package/dist/integration-service-readers.d.ts +0 -12
- package/dist/integration-service-readers.js +0 -92
- package/dist/lifecycle-model.d.ts +0 -15
- package/dist/lifecycle-model.js +0 -20
- package/dist/lifecycle.d.ts +0 -11
- package/dist/lifecycle.js +0 -91
- package/dist/management.d.ts +0 -3
- package/dist/management.js +0 -47
- package/dist/mobile-delivery.d.ts +0 -77
- package/dist/mobile-delivery.js +0 -370
- package/dist/project-catalog.d.ts +0 -41
- package/dist/project-catalog.js +0 -288
- package/dist/project-inspector.d.ts +0 -4
- package/dist/project-inspector.js +0 -671
- package/dist/project-lifecycle.d.ts +0 -25
- package/dist/project-lifecycle.js +0 -57
- package/dist/project-state.d.ts +0 -47
- package/dist/project-state.js +0 -480
- package/dist/provider-auth.d.ts +0 -41
- package/dist/provider-auth.js +0 -180
- package/dist/provider-readiness.d.ts +0 -30
- package/dist/provider-readiness.js +0 -85
- package/dist/providers/adapters.d.ts +0 -17
- package/dist/providers/adapters.js +0 -103
- package/dist/providers/api.d.ts +0 -29
- package/dist/providers/api.js +0 -253
- package/dist/providers/config.d.ts +0 -15
- package/dist/providers/config.js +0 -136
- package/dist/providers/definitions.d.ts +0 -115
- package/dist/providers/definitions.js +0 -42
- package/dist/providers/provision.d.ts +0 -24
- package/dist/providers/provision.js +0 -76
- package/dist/providers/receipts.d.ts +0 -20
- package/dist/providers/receipts.js +0 -56
- package/dist/providers/recovery-verification.d.ts +0 -7
- package/dist/providers/recovery-verification.js +0 -52
- package/dist/providers/recovery.d.ts +0 -30
- package/dist/providers/recovery.js +0 -34
- package/dist/providers/runtime.d.ts +0 -10
- package/dist/providers/runtime.js +0 -234
- package/dist/providers/schema.d.ts +0 -28
- package/dist/providers/schema.js +0 -49
- package/dist/providers/state.d.ts +0 -55
- package/dist/providers/state.js +0 -283
- package/dist/provision.d.ts +0 -47
- package/dist/provision.js +0 -208
- package/dist/r2-service-data.d.ts +0 -2
- package/dist/r2-service-data.js +0 -136
- package/dist/readiness.d.ts +0 -23
- package/dist/readiness.js +0 -117
- package/dist/registry/add.d.ts +0 -24
- package/dist/registry/add.js +0 -210
- package/dist/registry/bootstrap.d.ts +0 -3
- package/dist/registry/bootstrap.js +0 -5
- package/dist/registry/commands.d.ts +0 -3
- package/dist/registry/commands.js +0 -83
- package/dist/registry/preview.d.ts +0 -11
- package/dist/registry/preview.js +0 -91
- package/dist/registry/receipt.d.ts +0 -3
- package/dist/registry/receipt.js +0 -68
- package/dist/repository.d.ts +0 -24
- package/dist/repository.js +0 -96
- package/dist/scaffold/auth.d.ts +0 -2
- package/dist/scaffold/auth.js +0 -76
- package/dist/scaffold/billing-config.d.ts +0 -1
- package/dist/scaffold/billing-config.js +0 -73
- package/dist/scaffold/billing-contracts.d.ts +0 -2
- package/dist/scaffold/billing-contracts.js +0 -48
- package/dist/scaffold/billing-providers.d.ts +0 -1
- package/dist/scaffold/billing-providers.js +0 -249
- package/dist/scaffold/billing-schema.d.ts +0 -1
- package/dist/scaffold/billing-schema.js +0 -34
- package/dist/scaffold/billing-security.d.ts +0 -1
- package/dist/scaffold/billing-security.js +0 -46
- package/dist/scaffold/billing-server.d.ts +0 -1
- package/dist/scaffold/billing-server.js +0 -139
- package/dist/scaffold/billing-store.d.ts +0 -1
- package/dist/scaffold/billing-store.js +0 -72
- package/dist/scaffold/billing.d.ts +0 -2
- package/dist/scaffold/billing.js +0 -208
- package/dist/scaffold/expo-auth.d.ts +0 -3
- package/dist/scaffold/expo-auth.js +0 -203
- package/dist/scaffold/expo-billing.d.ts +0 -3
- package/dist/scaffold/expo-billing.js +0 -257
- package/dist/scaffold/integrations.d.ts +0 -2
- package/dist/scaffold/integrations.js +0 -11
- package/dist/scaffold/managed-email.d.ts +0 -3
- package/dist/scaffold/managed-email.js +0 -47
- package/dist/scaffold/password-reset.d.ts +0 -1
- package/dist/scaffold/password-reset.js +0 -99
- package/dist/scaffold/private-files.d.ts +0 -2
- package/dist/scaffold/private-files.js +0 -78
- package/dist/scaffold/web-billing.d.ts +0 -2
- package/dist/scaffold/web-billing.js +0 -48
- package/dist/service-deletion.d.ts +0 -29
- package/dist/service-deletion.js +0 -195
- package/dist/service-descriptor.d.ts +0 -10
- package/dist/service-descriptor.js +0 -71
- package/dist/service-model.d.ts +0 -49
- package/dist/service-model.js +0 -8
- package/dist/service-operations.d.ts +0 -29
- package/dist/service-operations.js +0 -48
- package/dist/service-readers.d.ts +0 -8
- package/dist/service-readers.js +0 -216
- package/dist/services-command.d.ts +0 -39
- package/dist/services-command.js +0 -96
- package/dist/ship.d.ts +0 -35
- package/dist/ship.js +0 -107
- package/docs/assets/anhedral-stack-light.png +0 -0
- package/docs/assets/anhedral-stack.png +0 -0
package/dist/registry/preview.js
DELETED
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
import path from 'node:path';
|
|
2
|
-
import { existsSync } from 'node:fs';
|
|
3
|
-
import { readBoundedFile } from '../bounded-file.js';
|
|
4
|
-
const MAX_PREVIEW_FILE_BYTES = 256 * 1024;
|
|
5
|
-
export const MAX_PREVIEW_TOTAL_BYTES = 1024 * 1024;
|
|
6
|
-
export function validatePreviewPath(file) {
|
|
7
|
-
if (!file ||
|
|
8
|
-
path.posix.isAbsolute(file) ||
|
|
9
|
-
file.includes('\\') ||
|
|
10
|
-
/[\x00-\x1f\x7f]/.test(file) ||
|
|
11
|
-
file
|
|
12
|
-
.split('/')
|
|
13
|
-
.some((part) => !part ||
|
|
14
|
-
['.', '..', '.anhedral'].includes(part) ||
|
|
15
|
-
(/^(?:\.env|\.dev\.vars)(?:\.|$)/.test(part) && !part.endsWith('.example'))))
|
|
16
|
-
throw new Error('Select a relative generated source path; private environment and state files cannot be previewed.');
|
|
17
|
-
}
|
|
18
|
-
/** A single contextual hunk is linear in file size and remains an applicable unified patch. */
|
|
19
|
-
export function sourceDiff(file, before, after) {
|
|
20
|
-
const lines = (content) => content === '' ? [] : content.split('\n').slice(0, content.endsWith('\n') ? -1 : undefined);
|
|
21
|
-
const oldLines = lines(before ?? '');
|
|
22
|
-
const newLines = lines(after);
|
|
23
|
-
if (before === after)
|
|
24
|
-
return '';
|
|
25
|
-
let prefix = 0;
|
|
26
|
-
while (prefix < oldLines.length &&
|
|
27
|
-
prefix < newLines.length &&
|
|
28
|
-
oldLines[prefix] === newLines[prefix])
|
|
29
|
-
prefix++;
|
|
30
|
-
// Newline-only changes must still include the final line in the patch.
|
|
31
|
-
if (prefix && oldLines.length === newLines.length && prefix === oldLines.length)
|
|
32
|
-
prefix--;
|
|
33
|
-
let suffix = 0;
|
|
34
|
-
while ((before ?? '').endsWith('\n') === after.endsWith('\n') &&
|
|
35
|
-
suffix < oldLines.length - prefix &&
|
|
36
|
-
suffix < newLines.length - prefix &&
|
|
37
|
-
oldLines.at(-suffix - 1) === newLines.at(-suffix - 1))
|
|
38
|
-
suffix++;
|
|
39
|
-
const start = Math.max(0, prefix - 3);
|
|
40
|
-
const oldEnd = Math.min(oldLines.length, oldLines.length - suffix + 3);
|
|
41
|
-
const newEnd = Math.min(newLines.length, newLines.length - suffix + 3);
|
|
42
|
-
const output = [
|
|
43
|
-
`diff --git a/${file} b/${file}`,
|
|
44
|
-
...(before === undefined ? ['new file mode 100644'] : []),
|
|
45
|
-
`--- ${before === undefined ? '/dev/null' : `a/${file}`}`,
|
|
46
|
-
`+++ b/${file}`,
|
|
47
|
-
`@@ -${oldEnd - start ? start + 1 : start},${oldEnd - start} +${newEnd - start ? start + 1 : start},${newEnd - start} @@`,
|
|
48
|
-
];
|
|
49
|
-
if (before === undefined && !after)
|
|
50
|
-
return output.slice(0, 2).join('\n') + '\n';
|
|
51
|
-
const append = (prefix, line, last, content) => {
|
|
52
|
-
output.push(`${prefix}${line}`);
|
|
53
|
-
if (last && !content.endsWith('\n'))
|
|
54
|
-
output.push('\');
|
|
55
|
-
};
|
|
56
|
-
for (let index = start; index < prefix; index++)
|
|
57
|
-
output.push(` ${oldLines[index]}`);
|
|
58
|
-
for (let index = prefix; index < oldLines.length - suffix; index++)
|
|
59
|
-
append('-', oldLines[index], index === oldLines.length - 1, before ?? '');
|
|
60
|
-
for (let index = prefix; index < newLines.length - suffix; index++)
|
|
61
|
-
append('+', newLines[index], index === newLines.length - 1, after);
|
|
62
|
-
for (let index = oldLines.length - suffix; index < oldEnd; index++)
|
|
63
|
-
append(' ', oldLines[index], index === oldLines.length - 1, after);
|
|
64
|
-
return output.join('\n') + '\n';
|
|
65
|
-
}
|
|
66
|
-
export function sourcePreview(root, stage, file, mode) {
|
|
67
|
-
validatePreviewPath(file);
|
|
68
|
-
const decode = (directory) => new TextDecoder('utf-8', { fatal: true }).decode(readBoundedFile(path.join(directory, file), MAX_PREVIEW_FILE_BYTES));
|
|
69
|
-
let after;
|
|
70
|
-
let before;
|
|
71
|
-
try {
|
|
72
|
-
after = decode(stage);
|
|
73
|
-
if (after.includes('\x00'))
|
|
74
|
-
throw new Error('Binary file');
|
|
75
|
-
if (mode === 'diff' && existsSync(path.join(root, file))) {
|
|
76
|
-
before = decode(root);
|
|
77
|
-
if (before.includes('\x00'))
|
|
78
|
-
throw new Error('Binary file');
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
catch {
|
|
82
|
-
return {
|
|
83
|
-
path: file,
|
|
84
|
-
unavailable: 'Binary, nonregular or oversized file; source preview is unavailable (256 KiB limit).',
|
|
85
|
-
};
|
|
86
|
-
}
|
|
87
|
-
return {
|
|
88
|
-
path: file,
|
|
89
|
-
...(mode === 'view' ? { content: after } : { diff: sourceDiff(file, before, after) }),
|
|
90
|
-
};
|
|
91
|
-
}
|
package/dist/registry/receipt.js
DELETED
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto';
|
|
2
|
-
import { readFileSync, readdirSync } from 'node:fs';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import { PROJECT_CONFIG_FILE, readProjectConfig, readProjectSection, writeProjectSection, } from '../project-config.js';
|
|
5
|
-
const excluded = new Set([
|
|
6
|
-
'.pnpm-store',
|
|
7
|
-
'.artifacts',
|
|
8
|
-
'.git',
|
|
9
|
-
'node_modules',
|
|
10
|
-
'.next',
|
|
11
|
-
'.open-next',
|
|
12
|
-
'.wrangler',
|
|
13
|
-
'.void',
|
|
14
|
-
'.vinext',
|
|
15
|
-
'.void-wrangler.jsonc',
|
|
16
|
-
'.turbo',
|
|
17
|
-
'dist',
|
|
18
|
-
'.output',
|
|
19
|
-
'.expo',
|
|
20
|
-
'.fallow',
|
|
21
|
-
'.anhedral',
|
|
22
|
-
'.anhedral-audit-report.json',
|
|
23
|
-
'.anhedral.lock',
|
|
24
|
-
'.anhedral-txn',
|
|
25
|
-
PROJECT_CONFIG_FILE,
|
|
26
|
-
]);
|
|
27
|
-
export function sourceFiles(root) {
|
|
28
|
-
const files = new Map();
|
|
29
|
-
const visit = (directory) => {
|
|
30
|
-
for (const entry of readdirSync(path.join(root, directory), { withFileTypes: true })) {
|
|
31
|
-
if (excluded.has(entry.name))
|
|
32
|
-
continue;
|
|
33
|
-
const relative = directory ? `${directory}/${entry.name}` : entry.name;
|
|
34
|
-
// Deployment mirrors are disposable; reviewed SQL lives in packages/db/drizzle.
|
|
35
|
-
if (/^apps\/[^/]+\/db\/migrations$/.test(relative))
|
|
36
|
-
continue;
|
|
37
|
-
// Local credentials are never seeded into an addition transaction or fingerprint receipt.
|
|
38
|
-
if (/^(?:\.env|\.dev\.vars)(?:\.|$)/.test(entry.name) && !entry.name.endsWith('.example'))
|
|
39
|
-
continue;
|
|
40
|
-
if (entry.isSymbolicLink())
|
|
41
|
-
throw new Error(`Source symlinks are unsupported: ${relative}.`);
|
|
42
|
-
if (entry.isDirectory())
|
|
43
|
-
visit(relative);
|
|
44
|
-
else if (entry.isFile())
|
|
45
|
-
files.set(relative, createHash('sha256')
|
|
46
|
-
.update(readFileSync(path.join(root, relative)))
|
|
47
|
-
.digest('hex'));
|
|
48
|
-
}
|
|
49
|
-
};
|
|
50
|
-
visit('');
|
|
51
|
-
return files;
|
|
52
|
-
}
|
|
53
|
-
export function configurationFingerprints(root) {
|
|
54
|
-
return Object.fromEntries(Object.entries(readProjectConfig(root))
|
|
55
|
-
.filter(([section]) => !['schemaVersion', 'registry'].includes(section))
|
|
56
|
-
.map(([section, value]) => [
|
|
57
|
-
section,
|
|
58
|
-
createHash('sha256').update(JSON.stringify(value)).digest('hex'),
|
|
59
|
-
]));
|
|
60
|
-
}
|
|
61
|
-
export function recordScaffoldFiles(root) {
|
|
62
|
-
const receipt = readProjectSection(root, 'registry');
|
|
63
|
-
writeProjectSection(root, 'registry', {
|
|
64
|
-
...receipt,
|
|
65
|
-
files: Object.fromEntries(sourceFiles(root)),
|
|
66
|
-
configuration: configurationFingerprints(root),
|
|
67
|
-
});
|
|
68
|
-
}
|
package/dist/repository.d.ts
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { type DeliveryRunner } from './project-state.js';
|
|
2
|
-
interface Repository {
|
|
3
|
-
repoId: number;
|
|
4
|
-
nameWithOwner: string;
|
|
5
|
-
url: string;
|
|
6
|
-
isPrivate: boolean;
|
|
7
|
-
viewerPermission: string;
|
|
8
|
-
owner: {
|
|
9
|
-
login: string;
|
|
10
|
-
};
|
|
11
|
-
}
|
|
12
|
-
export declare function githubRepository(root: string, run?: DeliveryRunner): Promise<Repository>;
|
|
13
|
-
export declare function setupRepository(root: string, options: {
|
|
14
|
-
owner?: string;
|
|
15
|
-
name?: string;
|
|
16
|
-
create?: boolean;
|
|
17
|
-
visibility: 'private' | 'public';
|
|
18
|
-
}, run?: DeliveryRunner): Promise<{
|
|
19
|
-
repository: Repository;
|
|
20
|
-
branch: string;
|
|
21
|
-
commit: string;
|
|
22
|
-
ownership: string;
|
|
23
|
-
}>;
|
|
24
|
-
export {};
|
package/dist/repository.js
DELETED
|
@@ -1,96 +0,0 @@
|
|
|
1
|
-
import { realpathSync } from 'node:fs';
|
|
2
|
-
import { defaultRunner, withApplicationLock } from './project-state.js';
|
|
3
|
-
function environment() {
|
|
4
|
-
if (process.env.GH_HOST && process.env.GH_HOST !== 'github.com')
|
|
5
|
-
throw new Error('Repository automation supports github.com; reconcile the selected GitHub host explicitly.');
|
|
6
|
-
return {
|
|
7
|
-
...process.env,
|
|
8
|
-
GH_HOST: 'github.com',
|
|
9
|
-
GH_PROMPT_DISABLED: '1',
|
|
10
|
-
GIT_TERMINAL_PROMPT: '0',
|
|
11
|
-
};
|
|
12
|
-
}
|
|
13
|
-
function identity(remote) {
|
|
14
|
-
const match = /^(?:https:\/\/github\.com\/|git@github\.com:)([a-zA-Z0-9-]+\/[a-zA-Z0-9_.-]+?)(?:\.git)?$/.exec(remote);
|
|
15
|
-
if (!match || match[1].endsWith('/.') || match[1].endsWith('/..'))
|
|
16
|
-
throw new Error('Origin must identify one GitHub repository without embedded credentials.');
|
|
17
|
-
return match[1];
|
|
18
|
-
}
|
|
19
|
-
async function ownCheckout(root, run) {
|
|
20
|
-
if (realpathSync((await run('git', ['rev-parse', '--show-toplevel'], root, environment())).trim()) !== root)
|
|
21
|
-
throw new Error('Initialize the app in its own Git repository; do not use a parent repository.');
|
|
22
|
-
}
|
|
23
|
-
export async function githubRepository(root, run = defaultRunner) {
|
|
24
|
-
root = realpathSync(root);
|
|
25
|
-
await ownCheckout(root, run);
|
|
26
|
-
const remotes = (await run('git', ['remote', 'get-url', '--all', 'origin'], root, environment()))
|
|
27
|
-
.trim()
|
|
28
|
-
.split(/\r?\n/);
|
|
29
|
-
const pushes = (await run('git', ['remote', 'get-url', '--push', '--all', 'origin'], root, environment()))
|
|
30
|
-
.trim()
|
|
31
|
-
.split(/\r?\n/);
|
|
32
|
-
if (remotes.length !== 1 || pushes.length !== 1 || identity(remotes[0]) !== identity(pushes[0]))
|
|
33
|
-
throw new Error('Reconcile ambiguous or mismatched GitHub fetch/push origins.');
|
|
34
|
-
const name = identity(remotes[0]);
|
|
35
|
-
const repository = JSON.parse(await run('gh', ['repo', 'view', name, '--json', 'nameWithOwner,url,isPrivate,viewerPermission,owner'], root, environment()));
|
|
36
|
-
if (repository.nameWithOwner?.toLowerCase() !== name.toLowerCase() ||
|
|
37
|
-
repository.url?.toLowerCase() !== `https://github.com/${name}`.toLowerCase() ||
|
|
38
|
-
repository.owner?.login?.toLowerCase() !== name.split('/')[0].toLowerCase() ||
|
|
39
|
-
!['ADMIN', 'MAINTAIN', 'WRITE'].includes(repository.viewerPermission) ||
|
|
40
|
-
typeof repository.isPrivate !== 'boolean')
|
|
41
|
-
throw new Error('GitHub did not verify the selected repository identity and write access.');
|
|
42
|
-
repository.repoId = JSON.parse(await run('gh', ['api', `repos/${name}`, '--jq', '.id'], root, environment()));
|
|
43
|
-
if (!Number.isSafeInteger(repository.repoId) || repository.repoId <= 0)
|
|
44
|
-
throw new Error('GitHub did not return a stable repository ID.');
|
|
45
|
-
return repository;
|
|
46
|
-
}
|
|
47
|
-
export async function setupRepository(root, options, run = defaultRunner) {
|
|
48
|
-
root = realpathSync(root);
|
|
49
|
-
return withApplicationLock(root, async () => {
|
|
50
|
-
await ownCheckout(root, run);
|
|
51
|
-
if ((await run('git', ['status', '--porcelain'], root, environment())).trim())
|
|
52
|
-
throw new Error('Review files and commit the application before repository setup; secrets must remain ignored.');
|
|
53
|
-
const commit = (await run('git', ['rev-parse', 'HEAD'], root, environment())).trim();
|
|
54
|
-
if (!/^[a-f0-9]{40,64}$/.test(commit))
|
|
55
|
-
throw new Error('Create a reviewed initial source commit first.');
|
|
56
|
-
const user = JSON.parse(await run('gh', ['api', 'user'], root, environment()));
|
|
57
|
-
const owner = options.owner ?? user.login;
|
|
58
|
-
const name = options.name ?? root.split('/').at(-1);
|
|
59
|
-
if (!/^[a-zA-Z0-9-]+$/.test(owner ?? '') ||
|
|
60
|
-
!/^[a-zA-Z0-9_.-]+$/.test(name) ||
|
|
61
|
-
['.', '..'].includes(name))
|
|
62
|
-
throw new Error('Select a valid GitHub account and repository name.');
|
|
63
|
-
const remotes = (await run('git', ['remote'], root, environment())).trim().split(/\r?\n/);
|
|
64
|
-
if (!remotes.includes('origin')) {
|
|
65
|
-
if (!options.create)
|
|
66
|
-
throw new Error('No origin: use --create for an authorized new GitHub repository.');
|
|
67
|
-
await run('gh', [
|
|
68
|
-
'repo',
|
|
69
|
-
'create',
|
|
70
|
-
`${owner}/${name}`,
|
|
71
|
-
`--${options.visibility}`,
|
|
72
|
-
'--source',
|
|
73
|
-
'.',
|
|
74
|
-
'--remote',
|
|
75
|
-
'origin',
|
|
76
|
-
], root, environment());
|
|
77
|
-
}
|
|
78
|
-
const repository = await githubRepository(root, run);
|
|
79
|
-
if (repository.nameWithOwner.toLowerCase() !== `${owner}/${name}`.toLowerCase() ||
|
|
80
|
-
repository.isPrivate !== (options.visibility === 'private'))
|
|
81
|
-
throw new Error('Existing repository ownership/name/visibility differs; origin and visibility were not replaced.');
|
|
82
|
-
if ((await run('git', ['status', '--porcelain'], root, environment())).trim() ||
|
|
83
|
-
(await run('git', ['rev-parse', 'HEAD'], root, environment())).trim() !== commit)
|
|
84
|
-
throw new Error('Source changed during repository setup; nothing was pushed.');
|
|
85
|
-
const branch = (await run('git', ['symbolic-ref', '--short', 'HEAD'], root, environment())).trim();
|
|
86
|
-
if (!branch || branch.startsWith('-'))
|
|
87
|
-
throw new Error('Select the intended source branch before pushing.');
|
|
88
|
-
await run('git', ['push', '--set-upstream', 'origin', `HEAD:refs/heads/${branch}`], root, environment());
|
|
89
|
-
const remote = (await run('git', ['ls-remote', '--heads', 'origin', `refs/heads/${branch}`], root, environment()))
|
|
90
|
-
.trim()
|
|
91
|
-
.split(/\s+/);
|
|
92
|
-
if (remote[0] !== commit || remote[1] !== `refs/heads/${branch}`)
|
|
93
|
-
throw new Error('GitHub did not confirm the pushed source commit.');
|
|
94
|
-
return { repository, branch, commit, ownership: 'customer' };
|
|
95
|
-
});
|
|
96
|
-
}
|
package/dist/scaffold/auth.d.ts
DELETED
package/dist/scaffold/auth.js
DELETED
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
import { scaffoldPasswordReset } from './password-reset.js';
|
|
2
|
-
import { scaffoldManagedEmail } from './managed-email.js';
|
|
3
|
-
import { expoAuthScheme, scaffoldExpoAuth } from './expo-auth.js';
|
|
4
|
-
import { jsString } from '../render.js';
|
|
5
|
-
import { writeEnvironmentFile } from './environment.js';
|
|
6
|
-
import { STACK_DEPENDENCIES } from '../dependencies.js';
|
|
7
|
-
import { readFileSync } from 'node:fs';
|
|
8
|
-
import path from 'node:path';
|
|
9
|
-
import { writeBetterAuthSchema } from '../auth-schema.js';
|
|
10
|
-
import { put, patchPackage, sharedPackage } from './files.js';
|
|
11
|
-
export function scaffoldBetterAuth({ root, updating }) {
|
|
12
|
-
const scheme = expoAuthScheme(root);
|
|
13
|
-
scaffoldManagedEmail(root);
|
|
14
|
-
writeBetterAuthSchema(root, false);
|
|
15
|
-
sharedPackage(root, 'auth', `import { createManagedEmail, type EmailEnvironment } from '@workspace/managed-email';
|
|
16
|
-
import { expo } from '@better-auth/expo';
|
|
17
|
-
import { betterAuth } from 'better-auth';
|
|
18
|
-
import { drizzleAdapter } from '@better-auth/drizzle-adapter';
|
|
19
|
-
import type { createDatabase } from '@workspace/db';
|
|
20
|
-
export function createAuth(db: ReturnType<typeof createDatabase>, secret: string, baseURL: string, email: EmailEnvironment = {}) {
|
|
21
|
-
const sendEmail = createManagedEmail(email);
|
|
22
|
-
return betterAuth({
|
|
23
|
-
database: drizzleAdapter(db, { provider: 'sqlite', transaction: false }),
|
|
24
|
-
secret, baseURL,
|
|
25
|
-
trustedOrigins: [new URL(baseURL).origin, ${jsString(scheme + '://')}],
|
|
26
|
-
plugins: [expo()],
|
|
27
|
-
emailAndPassword: {
|
|
28
|
-
enabled: true,
|
|
29
|
-
requireEmailVerification: Boolean(sendEmail),
|
|
30
|
-
revokeSessionsOnPasswordReset: true,
|
|
31
|
-
sendResetPassword: sendEmail ? async ({ user, url }) => { await sendEmail('reset-password', user.email, url); } : undefined,
|
|
32
|
-
},
|
|
33
|
-
emailVerification: sendEmail ? {
|
|
34
|
-
sendOnSignUp: true,
|
|
35
|
-
sendVerificationEmail: async ({ user, url }) => { await sendEmail('verify-email', user.email, url); },
|
|
36
|
-
} : undefined,
|
|
37
|
-
});
|
|
38
|
-
}
|
|
39
|
-
`, {
|
|
40
|
-
'better-auth': STACK_DEPENDENCIES['better-auth'],
|
|
41
|
-
'@better-auth/expo': STACK_DEPENDENCIES['@better-auth/expo'],
|
|
42
|
-
'@better-auth/drizzle-adapter': STACK_DEPENDENCIES['@better-auth/drizzle-adapter'],
|
|
43
|
-
'@workspace/db': 'workspace:*',
|
|
44
|
-
'@workspace/managed-email': 'workspace:*',
|
|
45
|
-
});
|
|
46
|
-
patchPackage(root, 'apps/api/package.json', {
|
|
47
|
-
dependencies: {
|
|
48
|
-
'@workspace/auth': 'workspace:*',
|
|
49
|
-
'@workspace/managed-email': 'workspace:*',
|
|
50
|
-
'@workspace/db': 'workspace:*',
|
|
51
|
-
'@workspace/contracts': 'workspace:*',
|
|
52
|
-
},
|
|
53
|
-
});
|
|
54
|
-
let source = readFileSync(path.join(root, 'apps/api/src/index.ts'), 'utf8');
|
|
55
|
-
source =
|
|
56
|
-
"import { createAuth } from '@workspace/auth';\nimport { sessionSchema } from '@workspace/contracts';\n" +
|
|
57
|
-
source;
|
|
58
|
-
source = source.replace('export default app;', `app.get('/api/session', async (c) => {
|
|
59
|
-
c.header('cache-control', 'private, no-store');
|
|
60
|
-
const session = await createAuth(createDatabase(c.env.DB), c.env.BETTER_AUTH_SECRET, c.env.BETTER_AUTH_URL, c.env).api.getSession({ headers: c.req.raw.headers });
|
|
61
|
-
if (!session) return c.json({ error: 'Unauthorized' }, 401);
|
|
62
|
-
return c.json(sessionSchema.parse({ user: session.user }));
|
|
63
|
-
});
|
|
64
|
-
app.on(['GET', 'POST'], '/api/auth/*', (c) => createAuth(createDatabase(c.env.DB), c.env.BETTER_AUTH_SECRET, c.env.BETTER_AUTH_URL, c.env).handler(c.req.raw));
|
|
65
|
-
export default app;`);
|
|
66
|
-
put(root, 'apps/api/src/index.ts', source);
|
|
67
|
-
writeEnvironmentFile(root, 'apps/api/.dev.vars.example', {
|
|
68
|
-
BETTER_AUTH_SECRET: '',
|
|
69
|
-
BETTER_AUTH_URL: 'http://localhost:3000',
|
|
70
|
-
ANHEDRAL_EMAIL_SCOPE: '',
|
|
71
|
-
ANHEDRAL_EMAIL_CAPABILITY: '',
|
|
72
|
-
});
|
|
73
|
-
scaffoldExpoAuth(root, scheme, !updating);
|
|
74
|
-
scaffoldPasswordReset(root);
|
|
75
|
-
put(root, 'apps/api/src/secrets.d.ts', 'import type { EmailEnvironment } from "@workspace/managed-email";\ndeclare global { interface Env extends EmailEnvironment { BETTER_AUTH_SECRET: string; BETTER_AUTH_URL: string } }\n');
|
|
76
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const BILLING_CONFIG = "import { z } from 'zod';\n\nexport interface BillingEnv {\n BILLING_ORIGIN: string;\n BILLING_ENVIRONMENT: string;\n BILLING_PLANS_JSON?: string;\n BILLING_ENTITLEMENTS_JSON: string;\n BILLING_PREMIUM_ENTITLEMENT?: string;\n STRIPE_SECRET_KEY?: string;\n STRIPE_WEBHOOK_SECRET?: string;\n REVENUECAT_SECRET_KEY?: string;\n REVENUECAT_WEBHOOK_AUTHORIZATION?: string;\n REVENUECAT_WEBHOOK_SIGNING_SECRET?: string;\n REVENUECAT_APP_IDS_JSON?: string;\n REVENUECAT_PROJECT_ID?: string;\n}\nconst key = z.string().regex(/^[a-zA-Z0-9_.-]{1,100}$/);\nconst planSchema = z.object({ label: z.string().min(1).max(100), stripePriceId: z.string().regex(/^price_[a-zA-Z0-9]+$/), entitlement: key }).strict();\nconst plansSchema = z.record(key, planSchema);\nexport type Plan = z.infer<typeof planSchema>;\nexport interface Config {\n origin: string;\n environment: 'sandbox' | 'production';\n plans: Record<string, Plan>;\n entitlements: string[];\n appIds: string[];\n projectId: string;\n demoEntitlement: string;\n}\nfunction json(value: string | undefined, fallback: string): unknown {\n return JSON.parse(value ?? fallback);\n}\nfunction protocolAllowed(url: URL, environment: 'sandbox' | 'production'): boolean {\n if (url.protocol === 'https:') return true;\n if (environment !== 'sandbox') return false;\n return url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);\n}\nfunction origin(value: string, environment: 'sandbox' | 'production'): string {\n const url = new URL(value);\n if (!protocolAllowed(url, environment)) throw new Error('Billing requires HTTPS; sandbox HTTP is loopback-only.');\n if ([url.username, url.password, url.pathname !== '/', url.search, url.hash].some(Boolean)) throw new Error('Billing requires an origin without credentials or a path.');\n return url.origin;\n}\nexport function billingConfig(env: BillingEnv): Config {\n const environment = z.enum(['sandbox', 'production']).parse(env.BILLING_ENVIRONMENT);\n const plans = plansSchema.parse(json(env.BILLING_PLANS_JSON, '{}'));\n const entitlements = z.array(key).min(1).max(100).parse(json(env.BILLING_ENTITLEMENTS_JSON, '[]'));\n if (Object.values(plans).some((plan) => !entitlements.includes(plan.entitlement))) throw new Error('Every billing plan needs an allowed entitlement.');\n return {\n origin: origin(env.BILLING_ORIGIN, environment),\n environment,\n plans, entitlements,\n appIds: z.array(z.string().regex(/^app[a-zA-Z0-9_]+$/)).max(50).parse(json(env.REVENUECAT_APP_IDS_JSON, '[]')),\n projectId: env.REVENUECAT_PROJECT_ID ?? '',\n demoEntitlement: key.parse(env.BILLING_PREMIUM_ENTITLEMENT ?? 'premium'),\n };\n}\nexport function requireValue(value: string | undefined): string {\n if (!value?.trim()) throw new Error('Billing provider configuration is incomplete.');\n return value;\n}\nexport async function digest(value: string): Promise<string> {\n const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));\n return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\nexport async function equalSecret(actual: string, expected: string): Promise<boolean> {\n // Fixed-length digests make comparison independent of secret length.\n const values = await Promise.all([digest(actual), digest(expected)]);\n let difference = 0;\n for (let index = 0; index < values[0].length; index++) difference |= values[0].charCodeAt(index) ^ values[1].charCodeAt(index);\n return difference === 0;\n}\n";
|
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
export const BILLING_CONFIG = `import { z } from 'zod';
|
|
2
|
-
|
|
3
|
-
export interface BillingEnv {
|
|
4
|
-
BILLING_ORIGIN: string;
|
|
5
|
-
BILLING_ENVIRONMENT: string;
|
|
6
|
-
BILLING_PLANS_JSON?: string;
|
|
7
|
-
BILLING_ENTITLEMENTS_JSON: string;
|
|
8
|
-
BILLING_PREMIUM_ENTITLEMENT?: string;
|
|
9
|
-
STRIPE_SECRET_KEY?: string;
|
|
10
|
-
STRIPE_WEBHOOK_SECRET?: string;
|
|
11
|
-
REVENUECAT_SECRET_KEY?: string;
|
|
12
|
-
REVENUECAT_WEBHOOK_AUTHORIZATION?: string;
|
|
13
|
-
REVENUECAT_WEBHOOK_SIGNING_SECRET?: string;
|
|
14
|
-
REVENUECAT_APP_IDS_JSON?: string;
|
|
15
|
-
REVENUECAT_PROJECT_ID?: string;
|
|
16
|
-
}
|
|
17
|
-
const key = z.string().regex(/^[a-zA-Z0-9_.-]{1,100}$/);
|
|
18
|
-
const planSchema = z.object({ label: z.string().min(1).max(100), stripePriceId: z.string().regex(/^price_[a-zA-Z0-9]+$/), entitlement: key }).strict();
|
|
19
|
-
const plansSchema = z.record(key, planSchema);
|
|
20
|
-
export type Plan = z.infer<typeof planSchema>;
|
|
21
|
-
export interface Config {
|
|
22
|
-
origin: string;
|
|
23
|
-
environment: 'sandbox' | 'production';
|
|
24
|
-
plans: Record<string, Plan>;
|
|
25
|
-
entitlements: string[];
|
|
26
|
-
appIds: string[];
|
|
27
|
-
projectId: string;
|
|
28
|
-
demoEntitlement: string;
|
|
29
|
-
}
|
|
30
|
-
function json(value: string | undefined, fallback: string): unknown {
|
|
31
|
-
return JSON.parse(value ?? fallback);
|
|
32
|
-
}
|
|
33
|
-
function protocolAllowed(url: URL, environment: 'sandbox' | 'production'): boolean {
|
|
34
|
-
if (url.protocol === 'https:') return true;
|
|
35
|
-
if (environment !== 'sandbox') return false;
|
|
36
|
-
return url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
|
37
|
-
}
|
|
38
|
-
function origin(value: string, environment: 'sandbox' | 'production'): string {
|
|
39
|
-
const url = new URL(value);
|
|
40
|
-
if (!protocolAllowed(url, environment)) throw new Error('Billing requires HTTPS; sandbox HTTP is loopback-only.');
|
|
41
|
-
if ([url.username, url.password, url.pathname !== '/', url.search, url.hash].some(Boolean)) throw new Error('Billing requires an origin without credentials or a path.');
|
|
42
|
-
return url.origin;
|
|
43
|
-
}
|
|
44
|
-
export function billingConfig(env: BillingEnv): Config {
|
|
45
|
-
const environment = z.enum(['sandbox', 'production']).parse(env.BILLING_ENVIRONMENT);
|
|
46
|
-
const plans = plansSchema.parse(json(env.BILLING_PLANS_JSON, '{}'));
|
|
47
|
-
const entitlements = z.array(key).min(1).max(100).parse(json(env.BILLING_ENTITLEMENTS_JSON, '[]'));
|
|
48
|
-
if (Object.values(plans).some((plan) => !entitlements.includes(plan.entitlement))) throw new Error('Every billing plan needs an allowed entitlement.');
|
|
49
|
-
return {
|
|
50
|
-
origin: origin(env.BILLING_ORIGIN, environment),
|
|
51
|
-
environment,
|
|
52
|
-
plans, entitlements,
|
|
53
|
-
appIds: z.array(z.string().regex(/^app[a-zA-Z0-9_]+$/)).max(50).parse(json(env.REVENUECAT_APP_IDS_JSON, '[]')),
|
|
54
|
-
projectId: env.REVENUECAT_PROJECT_ID ?? '',
|
|
55
|
-
demoEntitlement: key.parse(env.BILLING_PREMIUM_ENTITLEMENT ?? 'premium'),
|
|
56
|
-
};
|
|
57
|
-
}
|
|
58
|
-
export function requireValue(value: string | undefined): string {
|
|
59
|
-
if (!value?.trim()) throw new Error('Billing provider configuration is incomplete.');
|
|
60
|
-
return value;
|
|
61
|
-
}
|
|
62
|
-
export async function digest(value: string): Promise<string> {
|
|
63
|
-
const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));
|
|
64
|
-
return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
65
|
-
}
|
|
66
|
-
export async function equalSecret(actual: string, expected: string): Promise<boolean> {
|
|
67
|
-
// Fixed-length digests make comparison independent of secret length.
|
|
68
|
-
const values = await Promise.all([digest(actual), digest(expected)]);
|
|
69
|
-
let difference = 0;
|
|
70
|
-
for (let index = 0; index < values[0].length; index++) difference |= values[0].charCodeAt(index) ^ values[1].charCodeAt(index);
|
|
71
|
-
return difference === 0;
|
|
72
|
-
}
|
|
73
|
-
`;
|
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
-
import { scaffoldContracts } from './backend.js';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import { put } from './files.js';
|
|
5
|
-
/** Public billing transport exposes verified identity and entitlements, never provider secrets. */
|
|
6
|
-
export function scaffoldBillingContracts(root) {
|
|
7
|
-
if (!existsSync(path.join(root, 'packages/contracts/src/http.ts')))
|
|
8
|
-
scaffoldContracts(root);
|
|
9
|
-
put(root, 'packages/contracts/src/billing.ts', `import { z } from 'zod';
|
|
10
|
-
import { createHttpClient, type HttpOptions } from './http';
|
|
11
|
-
|
|
12
|
-
export const billingIdentitySchema = z.object({
|
|
13
|
-
appUserId: z.string(),
|
|
14
|
-
providers: z.object({ stripe: z.boolean(), revenuecat: z.boolean() }),
|
|
15
|
-
plans: z.array(z.object({ id: z.string(), label: z.string() })),
|
|
16
|
-
});
|
|
17
|
-
export const billingEntitlementsSchema = z.object({
|
|
18
|
-
entitlements: z.array(z.object({ key: z.string(), active: z.boolean(), expiresAt: z.string().nullable(), sources: z.array(z.enum(['stripe', 'revenuecat'])) })),
|
|
19
|
-
checkedAt: z.string(),
|
|
20
|
-
});
|
|
21
|
-
export const billingUrlSchema = z.object({ url: z.url().refine((value) => new URL(value).protocol === 'https:', 'Billing navigation requires HTTPS.') });
|
|
22
|
-
export type BillingIdentity = z.infer<typeof billingIdentitySchema>;
|
|
23
|
-
export type BillingEntitlements = z.infer<typeof billingEntitlementsSchema>;
|
|
24
|
-
export function createBillingClient(baseURL = '/api/billing', options: HttpOptions = {}) {
|
|
25
|
-
const request = createHttpClient(baseURL, options);
|
|
26
|
-
function post<T>(route: string, schema: z.ZodType<T>, body: unknown, headers: HeadersInit = {}) {
|
|
27
|
-
const combined = new Headers(headers);
|
|
28
|
-
combined.set('content-type', 'application/json');
|
|
29
|
-
return request(route, schema, { method: 'POST', body: JSON.stringify(body), headers: combined });
|
|
30
|
-
}
|
|
31
|
-
return {
|
|
32
|
-
identity: () => request('/identity', billingIdentitySchema),
|
|
33
|
-
entitlements: () => request('/entitlements', billingEntitlementsSchema),
|
|
34
|
-
refresh: () => post('/refresh', billingEntitlementsSchema, {}),
|
|
35
|
-
checkout: (plan: string, idempotencyKey: string) => {
|
|
36
|
-
const body = z.strictObject({ plan: z.string().min(1) }).parse({ plan });
|
|
37
|
-
const key = z.uuid().parse(idempotencyKey);
|
|
38
|
-
return post('/checkout', billingUrlSchema, body, { 'idempotency-key': key });
|
|
39
|
-
},
|
|
40
|
-
portal: () => post('/portal', billingUrlSchema, {}),
|
|
41
|
-
};
|
|
42
|
-
}
|
|
43
|
-
`);
|
|
44
|
-
const file = 'packages/contracts/src/index.ts';
|
|
45
|
-
const source = readFileSync(path.join(root, file), 'utf8');
|
|
46
|
-
if (!source.includes("export * from './billing'"))
|
|
47
|
-
put(root, file, source + "\nexport * from './billing';\n");
|
|
48
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const BILLING_PROVIDERS = "import Stripe from 'stripe';\nimport { z } from 'zod';\nimport { digest, requireValue, type BillingEnv, type Config, type Plan } from './config';\nimport type { Account, Store } from './store';\n\nexport interface Grant { key: string; expiresAt: number | null; source: 'stripe' | 'revenuecat' }\nexport class BillingConflict extends Error {}\nconst timeout = 15_000;\nexport function stripeClient(env: BillingEnv) {\n return new Stripe(requireValue(env.STRIPE_SECRET_KEY), { httpClient: Stripe.createFetchHttpClient(), maxNetworkRetries: 1, timeout });\n}\nexport function verifyMode(livemode: boolean, config: Config): void {\n if (livemode !== (config.environment === 'production')) throw new Error('Unexpected billing environment.');\n}\nfunction objectId(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n return z.object({ id: z.string() }).safeParse(value).data?.id;\n}\nasync function verifyCustomer(stripe: Stripe, customerId: string, userId: string, config: Config) {\n const customer = await stripe.customers.retrieve(customerId);\n if (customer.deleted) throw new Error('Billing customer no longer exists.');\n verifyMode(customer.livemode, config);\n if (customer.metadata.app_user_id !== userId) throw new Error('Billing customer ownership mismatch.');\n return customer;\n}\nasync function stripeCustomer(stripe: Stripe, account: Account, store: Store, config: Config): Promise<string> {\n if (account.stripeCustomerId) {\n await verifyCustomer(stripe, account.stripeCustomerId, account.userId, config);\n return account.stripeCustomerId;\n }\n const idempotencyKey = 'anhedral-customer-' + await digest(account.userId);\n const customer = await stripe.customers.create({ metadata: { app_user_id: account.userId } }, { idempotencyKey });\n verifyMode(customer.livemode, config);\n await store.customer(account, customer.id);\n return customer.id;\n}\nfunction activeSubscription(subscription: Stripe.Subscription): boolean {\n return ['active', 'trialing'].includes(subscription.status);\n}\nfunction planForPrice(price: string, config: Config): Plan | undefined {\n return Object.values(config.plans).find((plan) => plan.stripePriceId === price);\n}\nasync function soundCharge(stripe: Stripe, payment: Stripe.InvoicePayment, customerId: string, config: Config): Promise<boolean> {\n const intentId = objectId(payment.payment.payment_intent);\n if (!intentId) return false;\n const intent = await stripe.paymentIntents.retrieve(intentId, { expand: ['latest_charge'] });\n verifyMode(intent.livemode, config);\n if (objectId(intent.customer) !== customerId) throw new Error('Payment ownership mismatch.');\n const charge = intent.latest_charge;\n if (!expandedCharge(charge)) return false;\n return validCharge(charge, customerId, config);\n}\nfunction expandedCharge(value: Stripe.Charge | string | null): value is Stripe.Charge {\n return value !== null && typeof value !== 'string';\n}\nfunction validCharge(charge: Stripe.Charge, customerId: string, config: Config): boolean {\n verifyMode(charge.livemode, config);\n if (objectId(charge.customer) !== customerId) throw new Error('Charge ownership mismatch.');\n return [charge.paid, !charge.disputed, charge.amount_refunded === 0].every(Boolean);\n}\nasync function paidInvoice(stripe: Stripe, subscription: Stripe.Subscription, customerId: string, config: Config): Promise<boolean> {\n if (subscription.status === 'trialing') return true;\n const invoiceId = objectId(subscription.latest_invoice);\n if (!invoiceId) return false;\n const invoice = await stripe.invoices.retrieve(invoiceId);\n verifyMode(invoice.livemode, config);\n if (objectId(invoice.customer) !== customerId) throw new Error('Invoice ownership mismatch.');\n return invoicePayment(stripe, invoice, customerId, config);\n}\nasync function invoicePayment(stripe: Stripe, invoice: Stripe.Invoice, customerId: string, config: Config): Promise<boolean> {\n if (invoice.status !== 'paid') return false;\n if (invoice.amount_paid === 0) return true;\n const payments = await stripe.invoicePayments.list({ invoice: invoice.id, status: 'paid', limit: 100 });\n requireCompletePayments(payments);\n if (!payments.data.length) return false;\n const sound = await Promise.all(payments.data.map((payment) => soundCharge(stripe, payment, customerId, config)));\n return sound.every(Boolean);\n}\nfunction requireCompletePayments(payments: Stripe.ApiList<Stripe.InvoicePayment>): void {\n if (payments.has_more) throw new Error('Billing payment pagination requires reconciliation.');\n}\nfunction subscriptionGrants(subscription: Stripe.Subscription, config: Config): Grant[] {\n return subscription.items.data.flatMap((item): Grant[] => {\n const plan = planForPrice(item.price.id, config);\n if (!plan || item.current_period_end * 1000 <= Date.now()) return [];\n return [{ key: plan.entitlement, expiresAt: item.current_period_end * 1000, source: 'stripe' }];\n });\n}\nasync function grantsForSubscription(stripe: Stripe, subscription: Stripe.Subscription, account: Account, config: Config): Promise<Grant[]> {\n verifyMode(subscription.livemode, config);\n if (objectId(subscription.customer) !== account.stripeCustomerId) throw new Error('Subscription ownership mismatch.');\n if (!ownedActiveSubscription(subscription, account.userId)) return [];\n if (!await paidInvoice(stripe, subscription, account.stripeCustomerId!, config)) return [];\n return subscriptionGrants(subscription, config);\n}\nfunction ownedActiveSubscription(subscription: Stripe.Subscription, userId: string): boolean {\n return subscription.metadata.app_user_id === userId && activeSubscription(subscription);\n}\nasync function customerSubscriptions(stripe: Stripe, account: Account, config: Config): Promise<Stripe.Subscription[]> {\n if (!account.stripeCustomerId) return [];\n await verifyCustomer(stripe, account.stripeCustomerId, account.userId, config);\n const subscriptions = await stripe.subscriptions.list({ customer: account.stripeCustomerId, status: 'all', limit: 100 });\n if (subscriptions.has_more) throw new Error('Billing subscription pagination requires reconciliation.');\n return subscriptions.data;\n}\nexport async function stripeGrants(stripe: Stripe, account: Account, config: Config): Promise<Grant[]> {\n const subscriptions = await customerSubscriptions(stripe, account, config);\n const values = await Promise.all(subscriptions.map((subscription) => grantsForSubscription(stripe, subscription, account, config)));\n return values.flat();\n}\nfunction configuredSubscription(subscription: Stripe.Subscription, account: Account, config: Config): boolean {\n verifyMode(subscription.livemode, config);\n if (objectId(subscription.customer) !== account.stripeCustomerId) throw new Error('Subscription ownership mismatch.');\n if (['canceled', 'incomplete_expired'].includes(subscription.status)) return false;\n // A nonterminal configured subscription still needs management when its payment\n // failed or was refunded. Absence of an access grant never authorizes another sale.\n return subscription.items.data.some((item) => Boolean(planForPrice(item.price.id, config)));\n}\nasync function requireNewSubscription(stripe: Stripe, account: Account, config: Config): Promise<void> {\n const subscriptions = await customerSubscriptions(stripe, account, config);\n if (subscriptions.some((subscription) => configuredSubscription(subscription, account, config))) throw new BillingConflict('Manage the existing subscription in its billing portal.');\n}\nfunction verifyOpenSession(session: Stripe.Checkout.Session, account: Account, config: Config): string {\n verifyMode(session.livemode, config);\n if (objectId(session.customer) !== account.stripeCustomerId) throw new Error('Checkout ownership mismatch.');\n if (session.metadata?.app_user_id !== account.userId) throw new Error('Checkout identity mismatch.');\n return configuredSessionPlan(session, config);\n}\nfunction configuredSessionPlan(session: Stripe.Checkout.Session, config: Config): string {\n verifySessionKind(session);\n const plan = sessionPlanId(session);\n if (!plan) throw new Error('Checkout plan is missing.');\n if (!Object.hasOwn(config.plans, plan)) throw new Error('Unexpected checkout plan.');\n return plan;\n}\nfunction verifySessionKind(session: Stripe.Checkout.Session): void {\n if (session.mode !== 'subscription') throw new Error('Unexpected checkout mode.');\n if (session.status !== 'open') throw new Error('Unexpected checkout state.');\n}\nfunction sessionPlanId(session: Stripe.Checkout.Session): string | undefined { return session.metadata?.plan_id; }\nasync function pendingCheckout(stripe: Stripe, account: Account, planId: string, config: Config): Promise<string | undefined> {\n const sessions = await stripe.checkout.sessions.list({ customer: account.stripeCustomerId!, status: 'open', limit: 100 });\n if (sessions.has_more) throw new Error('Checkout pagination requires reconciliation.');\n const plans = sessions.data.map((session) => verifyOpenSession(session, account, config));\n if (plans.some((plan) => plan !== planId)) throw new BillingConflict('Finish the existing checkout before choosing another plan.');\n return openSessionURL(sessions.data);\n}\nfunction openSessionURL(sessions: Stripe.Checkout.Session[]): string | undefined {\n if (!sessions.length) return undefined;\n const session = sessions[0];\n verifySessionExpiration(session);\n return providerURL(requireValue(session.url ?? undefined), 'checkout.stripe.com');\n}\nfunction verifySessionExpiration(session: Stripe.Checkout.Session): void {\n if (!Number.isSafeInteger(session.expires_at)) throw new Error('Invalid checkout expiration.');\n if (session.expires_at * 1000 <= Date.now()) throw new BillingConflict('The existing checkout is expiring. Try again shortly.');\n}\nexport async function createCheckout(stripe: Stripe, account: Account, planId: string, idempotencyKey: string, store: Store, config: Config): Promise<string> {\n const plan = config.plans[planId];\n if (!plan) throw new Error('Unknown billing plan.');\n const customer = await stripeCustomer(stripe, account, store, config);\n const owner = { ...account, stripeCustomerId: customer };\n await requireNewSubscription(stripe, owner, config);\n const pending = await pendingCheckout(stripe, owner, planId, config);\n if (pending) return pending;\n const operation = await digest(account.userId + ':' + idempotencyKey);\n const result = await stripe.checkout.sessions.create({\n mode: 'subscription', customer,\n line_items: [{ price: plan.stripePriceId, quantity: 1 }],\n client_reference_id: account.userId,\n metadata: { app_user_id: account.userId, plan_id: planId },\n subscription_data: { metadata: { app_user_id: account.userId, plan_id: planId } },\n success_url: config.origin + '/billing?result=success',\n cancel_url: config.origin + '/billing?result=cancelled',\n integration_identifier: 'anhedral_' + operation.slice(0, 8).split('').map((character) => String.fromCharCode(97 + Number.parseInt(character, 16))).join(''),\n }, { idempotencyKey: 'anhedral-checkout-' + operation });\n return providerURL(requireValue(result.url ?? undefined), 'checkout.stripe.com');\n}\nfunction providerURL(value: string, hostname: string): string {\n const url = new URL(value);\n if ([url.protocol !== 'https:', url.hostname !== hostname, url.username, url.password].some(Boolean)) throw new Error('Unexpected billing provider URL.');\n return url.href;\n}\nexport async function createPortal(stripe: Stripe, account: Account, config: Config): Promise<string> {\n if (!account.stripeCustomerId) throw new Error('No web billing subscription for this account.');\n await verifyCustomer(stripe, account.stripeCustomerId, account.userId, config);\n const portal = await stripe.billingPortal.sessions.create({ customer: account.stripeCustomerId, return_url: config.origin + '/billing' });\n return providerURL(portal.url, 'billing.stripe.com');\n}\nexport async function stripeEventCustomer(stripe: Stripe, event: Stripe.Event): Promise<string | undefined> {\n const object = event.data.object as unknown as Record<string, unknown>;\n const customer = objectId(object.customer);\n if (customer) return customer;\n const charge = objectId(object.charge);\n if (!charge) return undefined;\n return objectId((await stripe.charges.retrieve(charge)).customer);\n}\n\nconst purchase = z.object({ is_sandbox: z.boolean(), store: z.string(), expires_date: z.string().nullable().optional(), grace_period_expires_date: z.string().nullable().optional() });\nconst rcSchema = z.object({ subscriber: z.object({\n entitlements: z.record(z.string(), z.object({ product_identifier: z.string(), expires_date: z.string().nullable(), grace_period_expires_date: z.string().nullable().optional() })),\n subscriptions: z.record(z.string(), purchase),\n non_subscriptions: z.record(z.string(), z.array(purchase)).optional(),\n}) });\ntype Subscriber = z.infer<typeof rcSchema>['subscriber'];\ntype Purchase = z.infer<typeof purchase>;\nfunction matchesPurchase(value: Purchase, config: Config, stripeEnabled: boolean): boolean {\n if (value.is_sandbox !== (config.environment === 'sandbox')) return false;\n return !(stripeEnabled && value.store === 'stripe');\n}\nfunction receiptForProduct(subscriber: Subscriber, productId: string, config: Config, stripeEnabled: boolean): Purchase | undefined {\n const candidates = [subscriber.subscriptions[productId], ...(subscriber.non_subscriptions?.[productId] ?? [])].filter((value): value is Purchase => Boolean(value));\n return candidates.find((value) => matchesPurchase(value, config, stripeEnabled));\n}\nfunction expires(value: string | null | undefined): number | null {\n if (value === null) return null;\n const parsed = Date.parse(value ?? '');\n if (!Number.isFinite(parsed)) throw new Error('Invalid provider entitlement expiry.');\n return parsed;\n}\nfunction revenueCatGrant(key: string, subscriber: Subscriber, config: Config, stripeEnabled: boolean): Grant[] {\n const entitlement = subscriber.entitlements[key];\n if (!entitlement) return [];\n const receipt = receiptForProduct(subscriber, entitlement.product_identifier, config, stripeEnabled);\n if (!receipt) return [];\n const expiry = entitlementExpiry(entitlement);\n if (!validExpiry(expiry)) return [];\n return [{ key, expiresAt: expiry, source: 'revenuecat' }];\n}\nfunction entitlementExpiry(entitlement: { expires_date: string | null; grace_period_expires_date?: string | null }): number | null {\n return expires(entitlement.grace_period_expires_date ?? entitlement.expires_date);\n}\nfunction validExpiry(expiry: number | null): boolean { return expiry === null || expiry > Date.now(); }\nfunction requireRevenueCatScope(config: Config): void {\n if (!config.projectId) throw new Error('Configure the RevenueCat project.');\n if (!config.appIds.length) throw new Error('Configure the RevenueCat app allowlist.');\n}\nexport async function revenueCatGrants(userId: string, env: BillingEnv, config: Config, stripeEnabled: boolean): Promise<Grant[]> {\n requireRevenueCatScope(config);\n const response = await fetch('https://api.revenuecat.com/v1/subscribers/' + encodeURIComponent(userId), {\n headers: { authorization: 'Bearer ' + requireValue(env.REVENUECAT_SECRET_KEY), accept: 'application/json' },\n signal: AbortSignal.timeout(timeout), redirect: 'error',\n });\n if (response.status === 404) return [];\n if (!response.ok) throw new Error('RevenueCat reconciliation failed.');\n const { subscriber } = rcSchema.parse(await response.json());\n return config.entitlements.flatMap((key) => revenueCatGrant(key, subscriber, config, stripeEnabled));\n}\n";
|