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/service-deletion.js
DELETED
|
@@ -1,195 +0,0 @@
|
|
|
1
|
-
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
-
import { existsSync, mkdirSync, realpathSync, writeFileSync } from 'node:fs';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import { z } from 'zod';
|
|
5
|
-
import { readBoundedFile } from './bounded-file.js';
|
|
6
|
-
import { atomicJson, readApplication, withApplicationLock } from './project-state.js';
|
|
7
|
-
import { inspectApplication } from './project-inspector.js';
|
|
8
|
-
import { resolveService } from './service-descriptor.js';
|
|
9
|
-
import { observeService, record, serviceEndpoint } from './service-readers.js';
|
|
10
|
-
const digest = (value) => createHash('sha256').update(value).digest('hex');
|
|
11
|
-
const actionSchema = z
|
|
12
|
-
.object({
|
|
13
|
-
schemaVersion: z.literal(1),
|
|
14
|
-
root: z.string(),
|
|
15
|
-
serviceKey: z.string().max(1024),
|
|
16
|
-
fingerprint: z.string().regex(/^[a-f0-9]{64}$/),
|
|
17
|
-
name: z.string().max(256),
|
|
18
|
-
expiresAt: z.number(),
|
|
19
|
-
state: z.enum(['prepared', 'pending', 'deleted', 'uncertain', 'rejected']),
|
|
20
|
-
})
|
|
21
|
-
.strict();
|
|
22
|
-
function fingerprint(root, service) {
|
|
23
|
-
const inspection = inspectApplication(root);
|
|
24
|
-
return digest(JSON.stringify({
|
|
25
|
-
service,
|
|
26
|
-
project: readApplication(root),
|
|
27
|
-
configuration: inspection.configuration,
|
|
28
|
-
receipts: inspection.cloudflareResources,
|
|
29
|
-
}));
|
|
30
|
-
}
|
|
31
|
-
async function assertDeletionScope(root, service, request) {
|
|
32
|
-
if (service.kind !== 'd1' ||
|
|
33
|
-
service.ownership !== 'created' ||
|
|
34
|
-
!service.name ||
|
|
35
|
-
service.applications.length > 1)
|
|
36
|
-
throw new Error('Deletion requires a supported, recorded project-created resource with at most one owning application. Reused, shared, or unverified resources cannot be deleted here.');
|
|
37
|
-
const observation = await observeService(service, request);
|
|
38
|
-
if (observation.state !== 'available' || observation.name !== service.name)
|
|
39
|
-
throw new Error('The exact resource identity must be confirmed before deletion.');
|
|
40
|
-
const scripts = await request('GET', '/workers/scripts?per_page=100');
|
|
41
|
-
if (!Array.isArray(scripts.result) ||
|
|
42
|
-
scripts.result.length >= 100 ||
|
|
43
|
-
(scripts.result_info?.total_pages ?? 1) > 1)
|
|
44
|
-
throw new Error('Worker dependency listing is incomplete; deletion is blocked.');
|
|
45
|
-
const project = readApplication(root);
|
|
46
|
-
const allowed = new Set(project.targets
|
|
47
|
-
.filter((target) => service.applications.includes(target.directory))
|
|
48
|
-
.map((target) => target.workerName));
|
|
49
|
-
for (const raw of scripts.result) {
|
|
50
|
-
const script = record(raw);
|
|
51
|
-
if (typeof script.id !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,62}$/.test(script.id))
|
|
52
|
-
throw new Error('Worker dependency identity is unavailable.');
|
|
53
|
-
const settings = record((await request('GET', `/workers/scripts/${script.id}/settings`)).result);
|
|
54
|
-
if (!Array.isArray(settings.bindings) || settings.bindings.length > 500)
|
|
55
|
-
throw new Error('Worker dependencies could not be verified.');
|
|
56
|
-
for (const rawBinding of settings.bindings) {
|
|
57
|
-
const binding = record(rawBinding);
|
|
58
|
-
if ((binding.type === 'd1' && typeof binding.id !== 'string') ||
|
|
59
|
-
(binding.type === 'kv_namespace' && typeof binding.namespace_id !== 'string'))
|
|
60
|
-
throw new Error('Worker dependency identities are incomplete.');
|
|
61
|
-
const uses = service.kind === 'd1'
|
|
62
|
-
? binding.type === 'd1' && binding.id === service.id
|
|
63
|
-
: binding.type === 'kv_namespace' && binding.namespace_id === service.id;
|
|
64
|
-
if (uses && !allowed.has(script.id))
|
|
65
|
-
throw new Error('Another Worker uses this resource. Shared resources cannot be deleted here.');
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
export class ServiceDeletionStore {
|
|
70
|
-
directory;
|
|
71
|
-
constructor(directory) {
|
|
72
|
-
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
73
|
-
this.directory = realpathSync(directory);
|
|
74
|
-
}
|
|
75
|
-
async plan(root, key, request) {
|
|
76
|
-
root = realpathSync(root);
|
|
77
|
-
const service = resolveService(root, key);
|
|
78
|
-
const before = fingerprint(root, service);
|
|
79
|
-
await assertDeletionScope(root, service, request);
|
|
80
|
-
if (before !== fingerprint(root, resolveService(root, key)))
|
|
81
|
-
throw new Error('Source changed during deletion planning.');
|
|
82
|
-
const token = randomBytes(32).toString('base64url');
|
|
83
|
-
const expiresAt = Date.now() + 5 * 60_000;
|
|
84
|
-
writeFileSync(path.join(this.directory, `${digest(token)}.json`), JSON.stringify({
|
|
85
|
-
schemaVersion: 1,
|
|
86
|
-
root,
|
|
87
|
-
serviceKey: key,
|
|
88
|
-
fingerprint: before,
|
|
89
|
-
name: service.name,
|
|
90
|
-
expiresAt,
|
|
91
|
-
state: 'prepared',
|
|
92
|
-
}), { mode: 0o600, flag: 'wx' });
|
|
93
|
-
return {
|
|
94
|
-
token,
|
|
95
|
-
name: service.name,
|
|
96
|
-
accountId: service.accountId,
|
|
97
|
-
resourceId: service.id,
|
|
98
|
-
kind: service.kind,
|
|
99
|
-
applications: service.applications,
|
|
100
|
-
expiresAt: new Date(expiresAt).toISOString(),
|
|
101
|
-
impact: 'Permanently removes this resource and its stored data. Existing source bindings remain and must be reviewed before shipping.',
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
async execute(root, key, token, typedName, request) {
|
|
105
|
-
if (!/^[a-zA-Z0-9_-]{43}$/.test(token))
|
|
106
|
-
throw new Error('Invalid deletion confirmation.');
|
|
107
|
-
const file = path.join(this.directory, `${digest(token)}.json`);
|
|
108
|
-
return withApplicationLock(root, async () => {
|
|
109
|
-
const saved = actionSchema.parse(JSON.parse(readBoundedFile(file, 16384).toString('utf8')));
|
|
110
|
-
root = realpathSync(root);
|
|
111
|
-
if (saved.root !== root ||
|
|
112
|
-
saved.serviceKey !== key ||
|
|
113
|
-
saved.name !== typedName ||
|
|
114
|
-
saved.expiresAt < Date.now() ||
|
|
115
|
-
saved.state !== 'prepared')
|
|
116
|
-
throw new Error('Deletion confirmation is expired, already used, or does not match this resource.');
|
|
117
|
-
const service = resolveService(root, key);
|
|
118
|
-
if (saved.fingerprint !== fingerprint(root, service))
|
|
119
|
-
throw new Error('Service identity or dependencies changed. Review a new deletion plan.');
|
|
120
|
-
await assertDeletionScope(root, service, request);
|
|
121
|
-
if (saved.fingerprint !== fingerprint(root, resolveService(root, key)))
|
|
122
|
-
throw new Error('Source changed before deletion.');
|
|
123
|
-
saved.state = 'pending';
|
|
124
|
-
atomicJson(file, saved);
|
|
125
|
-
const journal = path.join(root, '.anhedral/service-deletions.json');
|
|
126
|
-
const writeReceipt = (state) => {
|
|
127
|
-
let entries = [];
|
|
128
|
-
if (existsSync(journal)) {
|
|
129
|
-
const previous = record(JSON.parse(readBoundedFile(journal, 256 * 1024).toString('utf8')));
|
|
130
|
-
if (previous.projectId !== service.projectId ||
|
|
131
|
-
previous.accountId !== service.accountId ||
|
|
132
|
-
!Array.isArray(previous.entries) ||
|
|
133
|
-
previous.entries.length >= 500)
|
|
134
|
-
throw new Error('Deletion journal is invalid or full.');
|
|
135
|
-
entries = previous.entries.filter((entry) => record(entry).resourceId !== service.id);
|
|
136
|
-
}
|
|
137
|
-
atomicJson(journal, {
|
|
138
|
-
schemaVersion: 1,
|
|
139
|
-
projectId: service.projectId,
|
|
140
|
-
accountId: service.accountId,
|
|
141
|
-
entries: [
|
|
142
|
-
...entries,
|
|
143
|
-
{
|
|
144
|
-
resourceId: service.id,
|
|
145
|
-
kind: service.kind,
|
|
146
|
-
name: service.name,
|
|
147
|
-
state,
|
|
148
|
-
recordedAt: new Date().toISOString(),
|
|
149
|
-
},
|
|
150
|
-
],
|
|
151
|
-
});
|
|
152
|
-
};
|
|
153
|
-
writeReceipt('pending');
|
|
154
|
-
try {
|
|
155
|
-
await request('DELETE', serviceEndpoint(service));
|
|
156
|
-
if ((await observeService(service, request)).state !== 'not-found')
|
|
157
|
-
throw new Error('Deletion could not be confirmed.');
|
|
158
|
-
saved.state = 'deleted';
|
|
159
|
-
atomicJson(file, saved);
|
|
160
|
-
writeReceipt('deleted');
|
|
161
|
-
return {
|
|
162
|
-
state: 'deleted',
|
|
163
|
-
resourceId: service.id,
|
|
164
|
-
message: 'Provider confirmed deletion. Review the remaining source bindings before shipping.',
|
|
165
|
-
};
|
|
166
|
-
}
|
|
167
|
-
catch {
|
|
168
|
-
saved.state = 'uncertain';
|
|
169
|
-
atomicJson(file, saved);
|
|
170
|
-
writeReceipt('uncertain');
|
|
171
|
-
return {
|
|
172
|
-
state: 'uncertain',
|
|
173
|
-
resourceId: service.id,
|
|
174
|
-
message: 'Deletion outcome is uncertain. Refresh provider status; no automatic deletion retry is performed.',
|
|
175
|
-
};
|
|
176
|
-
}
|
|
177
|
-
});
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
export function assertNoDeletedServices(root, resources) {
|
|
181
|
-
const file = path.join(root, '.anhedral/service-deletions.json');
|
|
182
|
-
if (!existsSync(file))
|
|
183
|
-
return;
|
|
184
|
-
const saved = record(JSON.parse(readBoundedFile(file, 256 * 1024).toString('utf8')));
|
|
185
|
-
const project = readApplication(root);
|
|
186
|
-
if (saved.projectId !== project.id ||
|
|
187
|
-
saved.accountId !== project.accountId ||
|
|
188
|
-
!Array.isArray(saved.entries))
|
|
189
|
-
throw new Error('Deletion history cannot be verified before provisioning.');
|
|
190
|
-
for (const raw of saved.entries) {
|
|
191
|
-
const entry = record(raw);
|
|
192
|
-
if (resources.some((resource) => resource.kind === entry.kind && resource.name === entry.name))
|
|
193
|
-
throw new Error('A selected resource has a recorded deletion attempt. Review source bindings and remote state before provisioning; deleted services are not recreated automatically.');
|
|
194
|
-
}
|
|
195
|
-
}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import type { ServiceDescriptor, ServiceKind } from './service-model.js';
|
|
2
|
-
import type { ProjectInspection } from './inspector-model.js';
|
|
3
|
-
export declare function unboundResourceSelectors(inspection: ProjectInspection): string[];
|
|
4
|
-
export declare function resolveService(root: string, key: string): ServiceDescriptor;
|
|
5
|
-
export declare function serviceCapabilities(kind: ServiceKind): {
|
|
6
|
-
status: boolean;
|
|
7
|
-
metrics: boolean;
|
|
8
|
-
data: boolean;
|
|
9
|
-
delete: boolean;
|
|
10
|
-
};
|
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
import { inspectApplication } from './project-inspector.js';
|
|
2
|
-
import { readApplication } from './project-state.js';
|
|
3
|
-
const kinds = {
|
|
4
|
-
D1: 'd1',
|
|
5
|
-
R2: 'r2',
|
|
6
|
-
};
|
|
7
|
-
export function unboundResourceSelectors(inspection) {
|
|
8
|
-
return inspection.cloudflareResources.data
|
|
9
|
-
.filter((resource) => !inspection.configuration.data.bindings.some((binding) => kinds[binding.kind] === resource.kind &&
|
|
10
|
-
(binding.resourceId === resource.id ||
|
|
11
|
-
(resource.kind === 'r2' && binding.resourceId === resource.name))))
|
|
12
|
-
.map((resource) => `receipt:${resource.kind}:${resource.id}`);
|
|
13
|
-
}
|
|
14
|
-
export function resolveService(root, key) {
|
|
15
|
-
const inspection = inspectApplication(root);
|
|
16
|
-
const project = readApplication(root);
|
|
17
|
-
if (!project.accountId ||
|
|
18
|
-
inspection.targets.state !== 'available' ||
|
|
19
|
-
inspection.configuration.state !== 'available')
|
|
20
|
-
throw new Error('Validated service configuration and a connected account are required.');
|
|
21
|
-
const target = inspection.targets.data.find((item) => key === `target:${item.provider}:${item.id}` && item.provider === 'cloudflare' && !item.error);
|
|
22
|
-
if (target) {
|
|
23
|
-
const configured = project.targets.find((item) => item.directory === target.application);
|
|
24
|
-
if (!configured)
|
|
25
|
-
throw new Error('Service target identity changed.');
|
|
26
|
-
return {
|
|
27
|
-
key,
|
|
28
|
-
kind: 'worker',
|
|
29
|
-
id: configured.workerName,
|
|
30
|
-
name: configured.workerName,
|
|
31
|
-
accountId: project.accountId,
|
|
32
|
-
projectId: project.id,
|
|
33
|
-
applications: [target.application],
|
|
34
|
-
ownership: 'unknown',
|
|
35
|
-
};
|
|
36
|
-
}
|
|
37
|
-
const binding = inspection.configuration.data.bindings.find((item) => key === `binding:${item.application}:${item.kind}:${item.name}`);
|
|
38
|
-
const record = inspection.cloudflareResources.data.find((item) => key === `receipt:${item.kind}:${item.id}`);
|
|
39
|
-
const kind = binding ? kinds[binding.kind] : record?.kind;
|
|
40
|
-
const id = binding?.resourceId ?? record?.id;
|
|
41
|
-
if (!kind || !['d1', 'r2'].includes(kind) || !id || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,254}$/.test(id))
|
|
42
|
-
throw new Error('This service has no supported provider resource identity.');
|
|
43
|
-
const receipt = record ??
|
|
44
|
-
inspection.cloudflareResources.data.find((item) => item.kind === kind && (item.id === id || (kind === 'r2' && item.name === id)));
|
|
45
|
-
const references = inspection.configuration.data.bindings.filter((item) => kinds[item.kind] === kind &&
|
|
46
|
-
(item.resourceId === id ||
|
|
47
|
-
(receipt && [receipt.name, receipt.id].includes(item.resourceId ?? ''))));
|
|
48
|
-
return {
|
|
49
|
-
key,
|
|
50
|
-
kind,
|
|
51
|
-
id: receipt?.id ?? id,
|
|
52
|
-
name: receipt?.name ?? (kind === 'r2' ? id : null),
|
|
53
|
-
accountId: project.accountId,
|
|
54
|
-
projectId: project.id,
|
|
55
|
-
applications: [...new Set(references.map((item) => item.application))].sort(),
|
|
56
|
-
ownership: inspection.cloudflareResources.state === 'available' &&
|
|
57
|
-
(receipt?.createdByProject === true || receipt?.reused === false)
|
|
58
|
-
? 'created'
|
|
59
|
-
: receipt?.reused === true
|
|
60
|
-
? 'reused'
|
|
61
|
-
: 'unknown',
|
|
62
|
-
};
|
|
63
|
-
}
|
|
64
|
-
export function serviceCapabilities(kind) {
|
|
65
|
-
return {
|
|
66
|
-
status: true,
|
|
67
|
-
metrics: kind === 'd1' || kind === 'worker',
|
|
68
|
-
data: kind === 'd1' || kind === 'r2',
|
|
69
|
-
delete: kind === 'd1',
|
|
70
|
-
};
|
|
71
|
-
}
|
package/dist/service-model.d.ts
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
export declare const SERVICE_TOOL_ACTIONS: {
|
|
2
|
-
readonly refresh_service: "status";
|
|
3
|
-
readonly get_service_metrics: "metrics";
|
|
4
|
-
readonly list_service_tables: "tables";
|
|
5
|
-
readonly browse_service_data: "data";
|
|
6
|
-
readonly plan_service_deletion: "delete-plan";
|
|
7
|
-
readonly delete_service: "delete";
|
|
8
|
-
};
|
|
9
|
-
export type ServiceAction = (typeof SERVICE_TOOL_ACTIONS)[keyof typeof SERVICE_TOOL_ACTIONS];
|
|
10
|
-
export type ServiceKind = 'worker' | 'd1' | 'r2';
|
|
11
|
-
export interface ServiceDescriptor {
|
|
12
|
-
key: string;
|
|
13
|
-
kind: ServiceKind;
|
|
14
|
-
id: string;
|
|
15
|
-
name: string | null;
|
|
16
|
-
accountId: string;
|
|
17
|
-
projectId: string;
|
|
18
|
-
applications: string[];
|
|
19
|
-
ownership: 'created' | 'reused' | 'unknown';
|
|
20
|
-
}
|
|
21
|
-
export interface ServiceObservation {
|
|
22
|
-
state: 'available' | 'not-found' | 'permission-required' | 'unavailable';
|
|
23
|
-
fetchedAt: string;
|
|
24
|
-
name?: string;
|
|
25
|
-
storageBytes?: number;
|
|
26
|
-
message: string;
|
|
27
|
-
}
|
|
28
|
-
export interface ServiceMetrics {
|
|
29
|
-
fetchedAt: string;
|
|
30
|
-
start: string;
|
|
31
|
-
end: string;
|
|
32
|
-
timezone: 'UTC';
|
|
33
|
-
source: string;
|
|
34
|
-
sampled: boolean;
|
|
35
|
-
points: {
|
|
36
|
-
time: string;
|
|
37
|
-
values: Record<string, number>;
|
|
38
|
-
}[];
|
|
39
|
-
units: Record<string, string>;
|
|
40
|
-
}
|
|
41
|
-
export interface ServiceData {
|
|
42
|
-
fetchedAt: string;
|
|
43
|
-
columns: string[];
|
|
44
|
-
rows: (string | number | boolean | null)[][];
|
|
45
|
-
offset: number;
|
|
46
|
-
hasMore: boolean;
|
|
47
|
-
masked: boolean;
|
|
48
|
-
nextCursor?: string;
|
|
49
|
-
}
|
package/dist/service-model.js
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import { type CloudflareRequest } from './cloudflare.js';
|
|
2
|
-
import type { ServiceDeletionStore, DeletionPlan } from './service-deletion.js';
|
|
3
|
-
import type { ServiceData, ServiceMetrics, ServiceObservation, ServiceAction } from './service-model.js';
|
|
4
|
-
export interface ServiceOptions {
|
|
5
|
-
hours?: number;
|
|
6
|
-
table?: string;
|
|
7
|
-
offset?: number;
|
|
8
|
-
cursor?: string;
|
|
9
|
-
token?: string;
|
|
10
|
-
typedName?: string;
|
|
11
|
-
}
|
|
12
|
-
export interface ServiceResult {
|
|
13
|
-
status?: ServiceObservation;
|
|
14
|
-
metrics?: ServiceMetrics;
|
|
15
|
-
tables?: string[];
|
|
16
|
-
data?: ServiceData;
|
|
17
|
-
plan?: DeletionPlan;
|
|
18
|
-
deletion?: {
|
|
19
|
-
state: 'deleted' | 'uncertain';
|
|
20
|
-
resourceId: string;
|
|
21
|
-
message: string;
|
|
22
|
-
};
|
|
23
|
-
}
|
|
24
|
-
export type ServiceRequestFactory = (root: string, analytics: boolean) => Promise<CloudflareRequest>;
|
|
25
|
-
/** Shared operations; transports decide how private results are presented. */
|
|
26
|
-
export declare function serviceOperation(root: string, action: ServiceAction, key: string, options?: ServiceOptions, context?: {
|
|
27
|
-
request?: ServiceRequestFactory;
|
|
28
|
-
deletions?: ServiceDeletionStore;
|
|
29
|
-
}): Promise<ServiceResult>;
|
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
import { resolveIntegrationService, integrationRequest, observeIntegrationService, } from './integration-service-readers.js';
|
|
2
|
-
import { browseR2Objects } from './r2-service-data.js';
|
|
3
|
-
import { readApplication, defaultRunner, targetDirectory } from './project-state.js';
|
|
4
|
-
import { cloudflareRequest } from './cloudflare.js';
|
|
5
|
-
import { resolveService } from './service-descriptor.js';
|
|
6
|
-
import { observeService, readServiceMetrics, listServiceTables, browseServiceData, } from './service-readers.js';
|
|
7
|
-
const requestFor = async (root, analytics) => {
|
|
8
|
-
const project = readApplication(root);
|
|
9
|
-
return cloudflareRequest(project, targetDirectory(root, project.targets[0]), defaultRunner, { ...process.env, ANHEDRAL_COMMAND_TIMEOUT_MS: '10000' }, { analytics, timeoutMs: 10000 });
|
|
10
|
-
};
|
|
11
|
-
/** Shared operations; transports decide how private results are presented. */
|
|
12
|
-
export async function serviceOperation(root, action, key, options = {}, context = {}) {
|
|
13
|
-
if (key.startsWith('provider:') || key.startsWith('integration:')) {
|
|
14
|
-
const service = resolveIntegrationService(root, key);
|
|
15
|
-
const api = integrationRequest(service);
|
|
16
|
-
if (action === 'status')
|
|
17
|
-
return { status: await observeIntegrationService(service, api) };
|
|
18
|
-
throw new Error('This integration does not support that operation.');
|
|
19
|
-
}
|
|
20
|
-
const service = resolveService(root, key);
|
|
21
|
-
if (service.kind === 'r2' && action === 'tables')
|
|
22
|
-
return { tables: ['objects'] };
|
|
23
|
-
if (service.kind === 'r2' && action === 'data') {
|
|
24
|
-
if (options.table !== 'objects')
|
|
25
|
-
throw new Error('Choose object metadata.');
|
|
26
|
-
return { data: await browseR2Objects(service, options.cursor) };
|
|
27
|
-
}
|
|
28
|
-
const request = await (context.request ?? requestFor)(root, action === 'metrics');
|
|
29
|
-
if (action === 'status')
|
|
30
|
-
return { status: await observeService(service, request) };
|
|
31
|
-
if (action === 'metrics')
|
|
32
|
-
return { metrics: await readServiceMetrics(service, request, options.hours ?? 24) };
|
|
33
|
-
if (action === 'tables')
|
|
34
|
-
return { tables: await listServiceTables(service, request) };
|
|
35
|
-
if (action === 'data')
|
|
36
|
-
return {
|
|
37
|
-
data: await browseServiceData(service, request, options.table ?? '', options.offset ?? 0, 25, options.cursor),
|
|
38
|
-
};
|
|
39
|
-
if (!context.deletions)
|
|
40
|
-
throw new Error('A deletion confirmation store is required.');
|
|
41
|
-
if (action === 'delete-plan')
|
|
42
|
-
return { plan: await context.deletions.plan(root, key, request) };
|
|
43
|
-
if (!options.token || !options.typedName)
|
|
44
|
-
throw new Error('Review a deletion plan and type the exact resource name.');
|
|
45
|
-
return {
|
|
46
|
-
deletion: await context.deletions.execute(root, key, options.token, options.typedName, request),
|
|
47
|
-
};
|
|
48
|
-
}
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { type CloudflareRequest } from './cloudflare.js';
|
|
2
|
-
import type { ServiceData, ServiceDescriptor, ServiceMetrics, ServiceObservation } from './service-model.js';
|
|
3
|
-
export declare const serviceEndpoint: (service: ServiceDescriptor) => string;
|
|
4
|
-
export declare function record(value: unknown): Record<string, unknown>;
|
|
5
|
-
export declare function observeService(service: ServiceDescriptor, request: CloudflareRequest): Promise<ServiceObservation>;
|
|
6
|
-
export declare function listServiceTables(service: ServiceDescriptor, request: CloudflareRequest): Promise<string[]>;
|
|
7
|
-
export declare function browseServiceData(service: ServiceDescriptor, request: CloudflareRequest, table: string, offset?: number, limit?: number, cursor?: string): Promise<ServiceData>;
|
|
8
|
-
export declare function readServiceMetrics(service: ServiceDescriptor, analytics: CloudflareRequest, hours?: number): Promise<ServiceMetrics>;
|
package/dist/service-readers.js
DELETED
|
@@ -1,216 +0,0 @@
|
|
|
1
|
-
import { CloudflareRequestError } from './cloudflare.js';
|
|
2
|
-
export const serviceEndpoint = (service) => {
|
|
3
|
-
const id = encodeURIComponent(service.kind === 'r2' ? (service.name ?? service.id) : service.id);
|
|
4
|
-
return {
|
|
5
|
-
d1: `/d1/database/${id}`,
|
|
6
|
-
r2: `/r2/buckets/${id}`,
|
|
7
|
-
worker: `/workers/scripts/${id}/settings`,
|
|
8
|
-
}[service.kind];
|
|
9
|
-
};
|
|
10
|
-
export function record(value) {
|
|
11
|
-
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
12
|
-
throw new Error('Unsupported service response.');
|
|
13
|
-
return value;
|
|
14
|
-
}
|
|
15
|
-
export async function observeService(service, request) {
|
|
16
|
-
const fetchedAt = new Date().toISOString();
|
|
17
|
-
try {
|
|
18
|
-
const value = record((await request('GET', serviceEndpoint(service))).result);
|
|
19
|
-
const id = service.kind === 'd1' ? value.uuid : undefined;
|
|
20
|
-
if (service.kind !== 'worker' && service.kind !== 'r2' && id !== service.id)
|
|
21
|
-
throw new Error('Provider resource identity differs from the source.');
|
|
22
|
-
const name = value.name ?? value.title ?? value.queue_name;
|
|
23
|
-
if (name !== undefined &&
|
|
24
|
-
(typeof name !== 'string' ||
|
|
25
|
-
name.length > 256 ||
|
|
26
|
-
(service.name !== null && name !== service.name)))
|
|
27
|
-
throw new Error('Provider resource name differs from the source.');
|
|
28
|
-
return {
|
|
29
|
-
state: 'available',
|
|
30
|
-
fetchedAt,
|
|
31
|
-
...(typeof name === 'string' ? { name } : {}),
|
|
32
|
-
...(service.kind === 'd1' &&
|
|
33
|
-
typeof value.file_size === 'number' &&
|
|
34
|
-
Number.isSafeInteger(value.file_size) &&
|
|
35
|
-
value.file_size >= 0
|
|
36
|
-
? { storageBytes: value.file_size }
|
|
37
|
-
: {}),
|
|
38
|
-
message: 'Provider confirmed this resource exists. Application health is separate.',
|
|
39
|
-
};
|
|
40
|
-
}
|
|
41
|
-
catch (error) {
|
|
42
|
-
const status = error instanceof CloudflareRequestError ? error.status : undefined;
|
|
43
|
-
return {
|
|
44
|
-
state: status === 404
|
|
45
|
-
? 'not-found'
|
|
46
|
-
: status === 401 || status === 403
|
|
47
|
-
? 'permission-required'
|
|
48
|
-
: 'unavailable',
|
|
49
|
-
fetchedAt,
|
|
50
|
-
message: status === 404
|
|
51
|
-
? 'Resource not found in the selected account.'
|
|
52
|
-
: status === 401 || status === 403
|
|
53
|
-
? 'Sign in with the required resource-read permissions.'
|
|
54
|
-
: 'Service could not be verified. Check identity, connectivity, and provider availability.',
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
async function d1Query(service, request, sql, params = []) {
|
|
59
|
-
const value = (await request('POST', `${serviceEndpoint(service)}/query`, { sql, params }))
|
|
60
|
-
.result;
|
|
61
|
-
if (!Array.isArray(value) || value.length !== 1)
|
|
62
|
-
throw new Error('Unsupported database response.');
|
|
63
|
-
const result = record(value[0]);
|
|
64
|
-
const meta = record(result.meta ?? {});
|
|
65
|
-
if (result.success !== true ||
|
|
66
|
-
meta.changed_db === true ||
|
|
67
|
-
(typeof meta.changes === 'number' && meta.changes !== 0))
|
|
68
|
-
throw new Error('Read-only data operation did not complete safely.');
|
|
69
|
-
if (!Array.isArray(result.results) || result.results.length > 1001)
|
|
70
|
-
throw new Error('Database output exceeded its row limit.');
|
|
71
|
-
return result.results.map(record);
|
|
72
|
-
}
|
|
73
|
-
export async function listServiceTables(service, request) {
|
|
74
|
-
if (service.kind !== 'd1')
|
|
75
|
-
throw new Error('Schema browsing is supported for D1 databases.');
|
|
76
|
-
const rows = await d1Query(service, request, "SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT GLOB 'sqlite_*' AND name NOT GLOB '_cf_*' ORDER BY name LIMIT 1001");
|
|
77
|
-
if (rows.length > 1000)
|
|
78
|
-
throw new Error('Database schema exceeds its table limit.');
|
|
79
|
-
return rows.map((row) => {
|
|
80
|
-
if (typeof row.name !== 'string' || !/^[a-zA-Z_][a-zA-Z0-9_]{0,127}$/.test(row.name))
|
|
81
|
-
throw new Error('Unsupported table identifier.');
|
|
82
|
-
return row.name;
|
|
83
|
-
});
|
|
84
|
-
}
|
|
85
|
-
export async function browseServiceData(service, request, table, offset = 0, limit = 25, cursor) {
|
|
86
|
-
if (!Number.isSafeInteger(offset) ||
|
|
87
|
-
offset < 0 ||
|
|
88
|
-
offset > 10_000 ||
|
|
89
|
-
!Number.isInteger(limit) ||
|
|
90
|
-
limit < 1 ||
|
|
91
|
-
limit > 100)
|
|
92
|
-
throw new Error('Choose a bounded data page.');
|
|
93
|
-
if (cursor !== undefined && (cursor.length > 4096 || /[\x00-\x1f\x7f]/.test(cursor)))
|
|
94
|
-
throw new Error('Choose a bounded metadata cursor.');
|
|
95
|
-
if (cursor !== undefined)
|
|
96
|
-
throw new Error('Database pages use offsets, not metadata cursors.');
|
|
97
|
-
if (service.kind !== 'd1' ||
|
|
98
|
-
!/^[a-zA-Z_][a-zA-Z0-9_]{0,127}$/.test(table) ||
|
|
99
|
-
!(await listServiceTables(service, request)).includes(table))
|
|
100
|
-
throw new Error('Choose an existing supported database table.');
|
|
101
|
-
const fields = await d1Query(service, request, `PRAGMA table_info("${table}")`);
|
|
102
|
-
if (!fields.length || fields.length > 50)
|
|
103
|
-
throw new Error('Table exceeds its supported column limit.');
|
|
104
|
-
const columns = fields.map((field) => {
|
|
105
|
-
if (typeof field.name !== 'string' || !/^[a-zA-Z_][a-zA-Z0-9_]{0,127}$/.test(field.name))
|
|
106
|
-
throw new Error('Unsupported database column.');
|
|
107
|
-
return field.name;
|
|
108
|
-
});
|
|
109
|
-
const sensitive = /password|secret|token|email|phone|address|authorization|cookie|session|private|credential/i;
|
|
110
|
-
const projection = columns
|
|
111
|
-
.map((column) => sensitive.test(column)
|
|
112
|
-
? `'[masked]' AS "${column}"`
|
|
113
|
-
: `CASE WHEN typeof("${column}") IN ('text', 'blob') THEN substr(CAST("${column}" AS TEXT), 1, 1000) ELSE "${column}" END AS "${column}"`)
|
|
114
|
-
.join(', ');
|
|
115
|
-
const ordering = columns.map((_, index) => index + 1).join(', ');
|
|
116
|
-
const rows = await d1Query(service, request, `SELECT ${projection} FROM "${table}" ORDER BY ${ordering} LIMIT ? OFFSET ?`, [limit + 1, offset]);
|
|
117
|
-
let masked = columns.some((column) => sensitive.test(column));
|
|
118
|
-
const outputRows = rows.slice(0, limit).map((row) => columns.map((column) => {
|
|
119
|
-
const value = row[column];
|
|
120
|
-
if (sensitive.test(column)) {
|
|
121
|
-
masked = true;
|
|
122
|
-
return '[masked]';
|
|
123
|
-
}
|
|
124
|
-
if (value === null || typeof value === 'boolean' || typeof value === 'number')
|
|
125
|
-
return value;
|
|
126
|
-
if (typeof value === 'string') {
|
|
127
|
-
if (/^(?:sk[-_]|rk[-_]|whsec[-_]|Bearer )/i.test(value)) {
|
|
128
|
-
masked = true;
|
|
129
|
-
return '[masked]';
|
|
130
|
-
}
|
|
131
|
-
return value.slice(0, 1000);
|
|
132
|
-
}
|
|
133
|
-
return '[complex value]';
|
|
134
|
-
}));
|
|
135
|
-
return {
|
|
136
|
-
fetchedAt: new Date().toISOString(),
|
|
137
|
-
columns,
|
|
138
|
-
offset,
|
|
139
|
-
hasMore: rows.length > limit,
|
|
140
|
-
masked,
|
|
141
|
-
rows: outputRows,
|
|
142
|
-
};
|
|
143
|
-
}
|
|
144
|
-
export async function readServiceMetrics(service, analytics, hours = 24) {
|
|
145
|
-
if (![1, 24, 168].includes(hours) ||
|
|
146
|
-
!['worker', 'd1'].includes(service.kind) ||
|
|
147
|
-
(service.kind === 'd1' && hours === 1))
|
|
148
|
-
throw new Error('Unsupported service or analytics window.');
|
|
149
|
-
const worker = service.kind === 'worker';
|
|
150
|
-
const end = worker
|
|
151
|
-
? new Date().toISOString()
|
|
152
|
-
: new Date(new Date().toISOString().slice(0, 10) + 'T00:00:00.000Z').toISOString();
|
|
153
|
-
const start = new Date(Date.parse(end) - hours * 3600000).toISOString();
|
|
154
|
-
const query = worker
|
|
155
|
-
? `query($accountTag: string!, $id: string!, $start: string!, $end: string!) { viewer { accounts(filter: {accountTag: $accountTag}) { workersInvocationsAdaptive(limit: 1000, filter: {scriptName: $id, datetime_geq: $start, datetime_leq: $end}) { dimensions { datetime scriptName } sum { requests errors } quantiles { cpuTimeP50 cpuTimeP99 } } } } }`
|
|
156
|
-
: `query($accountTag: string!, $id: string!, $start: Date!, $end: Date!) { viewer { accounts(filter: {accountTag: $accountTag}) { d1AnalyticsAdaptiveGroups(limit: 1000, filter: {databaseId: $id, date_geq: $start, date_leq: $end}, orderBy: [date_ASC]) { dimensions { date databaseId } sum { readQueries writeQueries } quantiles { queryBatchTimeMsP90 } } } } }`;
|
|
157
|
-
const response = record((await analytics('POST', '/graphql', {
|
|
158
|
-
query,
|
|
159
|
-
variables: {
|
|
160
|
-
accountTag: service.accountId,
|
|
161
|
-
id: service.id,
|
|
162
|
-
start: worker ? start : start.slice(0, 10),
|
|
163
|
-
end: worker ? end : new Date(Date.parse(end) - 1).toISOString().slice(0, 10),
|
|
164
|
-
},
|
|
165
|
-
})).result);
|
|
166
|
-
const accounts = record(response.viewer).accounts;
|
|
167
|
-
if (!Array.isArray(accounts) || accounts.length !== 1)
|
|
168
|
-
throw new Error('Analytics account response is unavailable.');
|
|
169
|
-
const rows = record(accounts[0])[worker ? 'workersInvocationsAdaptive' : 'd1AnalyticsAdaptiveGroups'];
|
|
170
|
-
if (!Array.isArray(rows) || rows.length >= 1000)
|
|
171
|
-
throw new Error('Analytics is truncated or unavailable; choose a smaller window.');
|
|
172
|
-
const names = worker ? ['requests', 'errors'] : ['readQueries', 'writeQueries'];
|
|
173
|
-
const points = rows
|
|
174
|
-
.map((entry) => {
|
|
175
|
-
const value = record(entry);
|
|
176
|
-
const dimensions = record(value.dimensions);
|
|
177
|
-
const sum = record(value.sum);
|
|
178
|
-
if (dimensions[worker ? 'scriptName' : 'databaseId'] !== service.id)
|
|
179
|
-
throw new Error('Analytics resource identity differs from the selection.');
|
|
180
|
-
const time = dimensions[worker ? 'datetime' : 'date'];
|
|
181
|
-
if (typeof time !== 'string' ||
|
|
182
|
-
!Number.isFinite(Date.parse(time)) ||
|
|
183
|
-
Date.parse(time) < Date.parse(start) ||
|
|
184
|
-
Date.parse(time) > Date.parse(end))
|
|
185
|
-
throw new Error('Invalid analytics time.');
|
|
186
|
-
const values = {};
|
|
187
|
-
for (const name of names) {
|
|
188
|
-
if (typeof sum[name] !== 'number' || !Number.isFinite(sum[name]) || Number(sum[name]) < 0)
|
|
189
|
-
throw new Error('Invalid analytics count.');
|
|
190
|
-
values[name] = Number(sum[name]);
|
|
191
|
-
}
|
|
192
|
-
const quantiles = record(value.quantiles ?? {});
|
|
193
|
-
for (const name of worker ? ['cpuTimeP50', 'cpuTimeP99'] : ['queryBatchTimeMsP90'])
|
|
194
|
-
if (typeof quantiles[name] === 'number' &&
|
|
195
|
-
Number.isFinite(quantiles[name]) &&
|
|
196
|
-
Number(quantiles[name]) >= 0)
|
|
197
|
-
values[name] = Number(quantiles[name]);
|
|
198
|
-
return { time, values };
|
|
199
|
-
})
|
|
200
|
-
.sort((a, b) => a.time.localeCompare(b.time));
|
|
201
|
-
return {
|
|
202
|
-
fetchedAt: new Date().toISOString(),
|
|
203
|
-
start,
|
|
204
|
-
end,
|
|
205
|
-
timezone: 'UTC',
|
|
206
|
-
source: worker ? 'Cloudflare Workers GraphQL' : 'Cloudflare D1 GraphQL (daily buckets)',
|
|
207
|
-
sampled: true,
|
|
208
|
-
points,
|
|
209
|
-
units: {
|
|
210
|
-
...Object.fromEntries(names.map((name) => [name, 'count'])),
|
|
211
|
-
...(worker
|
|
212
|
-
? { cpuTimeP50: 'microseconds', cpuTimeP99: 'microseconds' }
|
|
213
|
-
: { queryBatchTimeMsP90: 'milliseconds' }),
|
|
214
|
-
},
|
|
215
|
-
};
|
|
216
|
-
}
|