@blinkhost/cli 2.6.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +534 -2
  3. package/dist/api.d.ts +2 -2
  4. package/dist/api.js +57 -8
  5. package/dist/assistant.js +6 -1
  6. package/dist/cli.js +162 -9
  7. package/dist/design.d.ts +5 -0
  8. package/dist/design.js +82 -0
  9. package/dist/guidance.d.ts +1 -1
  10. package/dist/guidance.js +55 -12
  11. package/dist/javascript-runtime/resource-limits.js +3 -0
  12. package/dist/javascript-runtime/resource-profiles.js +2 -0
  13. package/dist/local-dev.d.ts +3 -0
  14. package/dist/local-dev.js +145 -0
  15. package/dist/local-development/README.md +410 -0
  16. package/dist/local-development/artifact-watch.mjs +36 -0
  17. package/dist/local-development/blinkhost.local.example.json +15 -0
  18. package/dist/local-development/frontend-proxy.mjs +189 -0
  19. package/dist/local-development/hello.rs +24 -0
  20. package/dist/local-development/local-stack.mjs +511 -0
  21. package/dist/local-development/native-database.mjs +37 -0
  22. package/dist/local-development/provider-fixtures.example.json +36 -0
  23. package/dist/local-development/provider-fixtures.mjs +203 -0
  24. package/dist/local-development/provider-grants.mjs +36 -0
  25. package/dist/local-development/test-provider-example.mjs +74 -0
  26. package/dist/local-source-build.d.ts +39 -0
  27. package/dist/local-source-build.js +225 -0
  28. package/dist/local-source-watch.d.ts +24 -0
  29. package/dist/local-source-watch.js +87 -0
  30. package/dist/local-test-command.d.ts +49 -0
  31. package/dist/local-test-command.js +128 -0
  32. package/dist/local-test-config.d.ts +37 -0
  33. package/dist/local-test-config.js +174 -0
  34. package/dist/local-test-gates.d.ts +71 -0
  35. package/dist/local-test-gates.js +247 -0
  36. package/dist/local-test-go-runner.d.ts +27 -0
  37. package/dist/local-test-go-runner.js +209 -0
  38. package/dist/local-test-node-arguments.d.ts +2 -0
  39. package/dist/local-test-node-arguments.js +14 -0
  40. package/dist/local-test-node-reporter.d.ts +7 -0
  41. package/dist/local-test-node-reporter.js +159 -0
  42. package/dist/local-test-results.d.ts +65 -0
  43. package/dist/local-test-results.js +163 -0
  44. package/dist/local-test-rust-runner.d.ts +18 -0
  45. package/dist/local-test-rust-runner.js +252 -0
  46. package/dist/local-test-starters.d.ts +3 -0
  47. package/dist/local-test-starters.js +157 -0
  48. package/dist/logs.d.ts +43 -0
  49. package/dist/logs.js +417 -0
  50. package/dist/module-build-diagnostics.d.ts +10 -0
  51. package/dist/module-build-diagnostics.js +208 -0
  52. package/dist/module-build.js +4 -0
  53. package/dist/release-preparation-diagnostics.d.ts +38 -0
  54. package/dist/release-preparation-diagnostics.js +204 -0
  55. package/dist/remote.js +14 -0
  56. package/dist/templates.d.ts +1 -0
  57. package/dist/templates.js +4 -1
  58. package/dist/test-credentials.d.ts +7 -0
  59. package/dist/test-credentials.js +236 -0
  60. package/dist/version.d.ts +1 -1
  61. package/dist/version.js +1 -1
  62. package/dist/workflows.d.ts +39 -2
  63. package/dist/workflows.js +241 -14
  64. package/package.json +4 -3
  65. package/test-runners/python-unittest.py +266 -0
@@ -0,0 +1,208 @@
1
+ // Build rejection facts explain a failed request; they never authorize a build.
2
+ // Only closed labels and bounded numeric measurements may reach the terminal.
3
+ const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
4
+ const BUILD_PATH = new RegExp(`^/api/idam/projects/${UUID}/module-builds/(?:review/|reviews/${UUID}/(?:apply/)?)?$`, 'i');
5
+ export function isModuleBuildPath(path) {
6
+ return BUILD_PATH.test(path);
7
+ }
8
+ export function moduleBuildPortableFailureGuidance(payload) {
9
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload))
10
+ return;
11
+ const envelope = payload;
12
+ if (envelope.build_state !== 'failed_user' || envelope.artifact_id !== null || !envelope.build_id)
13
+ return;
14
+ const value = envelope.failure_diagnostic;
15
+ if (!value || typeof value !== 'object' || Array.isArray(value))
16
+ return;
17
+ const row = value;
18
+ const fields = ['schema_version', 'stage', 'resource', 'observed', 'limit', 'unit', 'measurement'];
19
+ if (Object.keys(row).length !== fields.length || fields.some(field => !Object.hasOwn(row, field))
20
+ || row.schema_version !== 1 || row.stage !== 'portable_compilation' || row.resource !== 'portable_artifact'
21
+ || row.unit !== 'bytes' || row.measurement !== 'lower_bound'
22
+ || !Number.isSafeInteger(row.observed) || !Number.isSafeInteger(row.limit)
23
+ || row.limit <= 0 || row.limit > 80_000_000
24
+ || row.observed <= row.limit)
25
+ return;
26
+ return `The compiled portable WebAssembly module contains at least ${row.observed} bytes; `
27
+ + `its admitted maximum is ${row.limit} bytes. Reduce bundled code or dependencies and build again.`;
28
+ }
29
+ const RESOURCES = {
30
+ source_expanded_bytes: { label: 'Backend module source', unit: 'bytes' },
31
+ source_archive_bytes: { label: 'Backend module source archive', unit: 'bytes' },
32
+ source_files: { label: 'Backend module source', unit: 'files' },
33
+ };
34
+ export function moduleBuildGuestMemoryFailureGuidance(payload) {
35
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload))
36
+ return;
37
+ const envelope = payload;
38
+ if (envelope.build_state !== 'failed_user' || envelope.artifact_id !== null
39
+ || typeof envelope.build_id !== 'string'
40
+ || new RegExp(`^${UUID}$`, 'i').exec(envelope.build_id)?.[0] !== envelope.build_id)
41
+ return;
42
+ const value = envelope.failure_diagnostic;
43
+ if (!value || typeof value !== 'object' || Array.isArray(value))
44
+ return;
45
+ const row = value;
46
+ const fields = ['schema_version', 'stage', 'resource', 'observed', 'limit', 'unit', 'measurement',
47
+ 'minimum_memory_bytes', 'maximum_memory_bytes'];
48
+ const memory = (n) => typeof n === 'number' && Number.isSafeInteger(n)
49
+ && n >= 0 && n <= 2 ** 32 && n % 65536 === 0;
50
+ if (Object.keys(row).length !== fields.length || fields.some(field => !Object.hasOwn(row, field))
51
+ || row.schema_version !== 1 || row.stage !== 'portable_validation' || row.resource !== 'guest_memory'
52
+ || row.unit !== 'bytes' || row.measurement !== 'declared_memory'
53
+ || (row.limit !== 134217728 && row.limit !== 536870912)
54
+ || !memory(row.minimum_memory_bytes)
55
+ || (row.maximum_memory_bytes !== null && (!memory(row.maximum_memory_bytes)
56
+ || row.maximum_memory_bytes < row.minimum_memory_bytes))
57
+ || row.observed !== (row.maximum_memory_bytes ?? row.minimum_memory_bytes)
58
+ || !memory(row.observed) || row.observed <= row.limit)
59
+ return;
60
+ const maximum = row.maximum_memory_bytes === null ? 'no declared maximum'
61
+ : `a declared maximum of ${row.maximum_memory_bytes} bytes`;
62
+ return `The portable WebAssembly module declares ${row.minimum_memory_bytes} bytes of initial guest memory and ${maximum}; `
63
+ + `its admitted guest-memory cap is ${row.limit} bytes. Reduce the module's initial or maximum memory settings and build again. `
64
+ + 'This is a module declaration, not measured runtime or compiler memory. Paid shared plans do not increase the guest-memory cap.';
65
+ }
66
+ const packageMessages = Object.freeze({
67
+ BHPY_DEPENDENCIES_UNSUPPORTED: "This Python build does not install dependencies from package manifests. Use the shipped libraries or supported local Python modules and build again.",
68
+ BHPY_NATIVE_PACKAGE_UNSUPPORTED: "This Python build does not accept wheels, native extensions, object files or prebuilt WebAssembly. Use supported Python source and shipped libraries and build again.",
69
+ BHPY_UNSUPPORTED_IMPORT: "This Python build imports a module outside the supported import set. Use shipped libraries, supported customer helpers or local Python modules and build again.",
70
+ BHPY_DYNAMIC_IMPORT_UNSUPPORTED: "This Python build uses an unsupported dynamic import. Use explicit supported imports and build again.",
71
+ BHJS_PACKAGE_MANIFEST: "This build has an invalid package manifest. Correct the dependency and script declarations in package.json and build again.",
72
+ BHJS_LIFECYCLE_SCRIPT_UNSUPPORTED: "This build declares a package lifecycle script that function builds do not allow. Remove the lifecycle script and use dependencies that work without install scripts, then build again.",
73
+ BHJS_PACKAGE_VERSION_UNCERTIFIED: "This build declares or resolves a dependency version outside the compatibility registry. Choose an exact supported version, update package.json and package-lock.json together, and build again.",
74
+ BHJS_LOCKFILE_REQUIRED: "This build is missing package-lock.json. Generate and commit a lockfile using supported exact dependency versions, then build again.",
75
+ BHJS_LOCKFILE_INVALID: "This build has an invalid dependency lockfile. Regenerate and commit package-lock.json using supported exact dependency versions, then build again.",
76
+ BHJS_NATIVE_ADDON_UNSUPPORTED: "This module's JavaScript runtime does not load native addons. Use a compatible JavaScript dependency and build again.",
77
+ BHJS_PACKAGE_UNCERTIFIED: "This build resolves a dependency outside the compatibility registry. Use a supported dependency and build again.",
78
+ BHJS_NODE_API_UNSUPPORTED: "This module's JavaScript runtime does not provide the requested Node.js operating-system API. Use supported runtime APIs or a compatible dependency and build again.",
79
+ BHJS_EXTERNAL_IMPORT_UNSUPPORTED: "This build contains an unavailable external import. Bundle supported dependencies or use supported runtime APIs and build again.",
80
+ BHJS_DYNAMIC_IMPORT_UNSUPPORTED: "This build uses an unsupported dynamic import. Use static imports of supported dependencies and build again.",
81
+ });
82
+ export function moduleBuildPackageFailureGuidance(payload) {
83
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload))
84
+ return;
85
+ const envelope = payload;
86
+ if (envelope.build_state !== 'failed_user' || envelope.artifact_id !== null
87
+ || typeof envelope.build_id !== 'string'
88
+ || new RegExp(`^${UUID}$`, 'i').exec(envelope.build_id)?.[0] !== envelope.build_id)
89
+ return;
90
+ const diagnostic = envelope.failure_diagnostic;
91
+ if (!diagnostic || typeof diagnostic !== 'object' || Array.isArray(diagnostic))
92
+ return;
93
+ const row = diagnostic;
94
+ const packageFields = ['schema_version', 'stage', 'resource', 'language', 'code'];
95
+ if (Object.keys(row).length !== packageFields.length || packageFields.some(field => !Object.hasOwn(row, field))
96
+ || row.schema_version !== 1 || row.stage !== 'source_compatibility' || row.resource !== 'package_compatibility'
97
+ || typeof row.code !== 'string' || !Object.hasOwn(packageMessages, row.code)
98
+ || !((row.language === 'python-wasi' && row.code.startsWith('BHPY_'))
99
+ || (['javascript-wasi', 'typescript-wasi'].includes(row.language) && row.code.startsWith('BHJS_'))))
100
+ return;
101
+ return packageMessages[row.code];
102
+ }
103
+ export function moduleBuildFailureGuidance(payload) {
104
+ return moduleBuildPortableFailureGuidance(payload) ?? moduleBuildGuestMemoryFailureGuidance(payload)
105
+ ?? moduleBuildPackageFailureGuidance(payload);
106
+ }
107
+ export function moduleBuildSourceGuidance(payload) {
108
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload))
109
+ return;
110
+ const envelope = payload;
111
+ const value = envelope.source_limit;
112
+ if (!value || typeof value !== 'object' || Array.isArray(value))
113
+ return;
114
+ const row = value;
115
+ if (row.schema_version !== 1 || typeof row.resource !== 'string' || !Object.hasOwn(RESOURCES, row.resource)
116
+ || typeof row.stage !== 'string' || !['source_collection', 'source_archive', 'source_admission'].includes(row.stage)
117
+ || typeof row.measurement !== 'string' || !['exact', 'lower_bound', 'attempted_write'].includes(row.measurement)
118
+ || !Number.isSafeInteger(row.observed) || !Number.isSafeInteger(row.limit)
119
+ || row.limit <= 0 || row.observed <= row.limit)
120
+ return;
121
+ const resource = row.resource;
122
+ if (row.unit !== RESOURCES[resource].unit
123
+ || (row.stage === 'source_archive') !== (row.measurement === 'attempted_write')
124
+ || row.stage === 'source_archive' && resource !== 'source_archive_bytes')
125
+ return;
126
+ const code = row.stage === 'source_admission' ? 'build_authorization_changed'
127
+ : row.stage === 'source_archive' ? 'module_source_archive_too_large'
128
+ : resource === 'source_files' ? 'module_source_file_limit'
129
+ : resource === 'source_expanded_bytes' ? 'module_source_too_large' : undefined;
130
+ if (!code || envelope.code !== code)
131
+ return;
132
+ const amount = row.measurement === 'exact' ? String(row.observed) : `at least ${row.observed}`;
133
+ const verb = row.measurement === 'attempted_write' ? 'would contain' : 'contains';
134
+ return `${RESOURCES[resource].label} ${verb} ${amount} ${row.unit}; the maximum is ${row.limit} ${row.unit}. `
135
+ + 'Reduce the source size or file count and try again.';
136
+ }
137
+ export function moduleBuildQuotaGuidance(payload) {
138
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload))
139
+ return;
140
+ const envelope = payload;
141
+ if (envelope.code !== 'concurrent_build_limit_reached')
142
+ return;
143
+ const value = envelope.build_limit;
144
+ if (!value || typeof value !== 'object' || Array.isArray(value))
145
+ return;
146
+ const row = value;
147
+ const fields = ['schema_version', 'stage', 'resource', 'scope', 'observed', 'limit', 'unit', 'measurement'];
148
+ if (Object.keys(row).length !== fields.length || fields.some(field => !Object.hasOwn(row, field))
149
+ || row.schema_version !== 1 || row.stage !== 'build_admission' || row.resource !== 'concurrent_builds'
150
+ || row.scope !== 'workspace' || row.unit !== 'builds' || row.measurement !== 'occupied_slots_snapshot'
151
+ || !Number.isSafeInteger(row.observed) || !Number.isSafeInteger(row.limit)
152
+ || row.limit < 0 || row.observed < row.limit)
153
+ return;
154
+ const remedy = row.limit === 0
155
+ ? 'Builds are disabled by this workspace\'s current concurrent-build limit. Check workspace build access before trying again.'
156
+ : 'Wait for an existing build to stop, then retry.';
157
+ return `This workspace had ${row.observed} occupied build slots when this build was rejected; `
158
+ + `its concurrent-build limit is ${row.limit}. ${remedy} This limit applies to builds, not backend requests.`;
159
+ }
160
+ export function moduleBuildRejectionGuidance(payload) {
161
+ return moduleBuildQuotaGuidance(payload) ?? moduleBuildSourceGuidance(payload);
162
+ }
163
+ export async function readModuleBuildRejection(response) {
164
+ if (!response.body)
165
+ return;
166
+ const reader = response.body.getReader();
167
+ let complete = false;
168
+ try {
169
+ // The reviewed-build API uses HTTP 409 for confirmed lifecycle rejection.
170
+ // Unconfirmed errors, auth failures and HTML never supply limit guidance.
171
+ if (response.status !== 409
172
+ || response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() !== 'application/json')
173
+ return;
174
+ const length = response.headers.get('content-length');
175
+ if (length !== null && (!/^\d+$/.test(length) || Number(length) > 2048))
176
+ return;
177
+ const chunks = [];
178
+ let size = 0;
179
+ for (let reads = 0; reads < 64; reads++) {
180
+ const chunk = await reader.read();
181
+ if (chunk.done) {
182
+ complete = true;
183
+ break;
184
+ }
185
+ size += chunk.value.byteLength;
186
+ if (size > 2048)
187
+ return;
188
+ chunks.push(chunk.value);
189
+ }
190
+ if (!complete || length !== null && Number(length) !== size)
191
+ return;
192
+ return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks, size)));
193
+ }
194
+ catch {
195
+ // Broken or malformed error bodies retain the generic confirmed HTTP error.
196
+ return;
197
+ }
198
+ finally {
199
+ if (!complete)
200
+ void reader.cancel().catch(() => undefined);
201
+ reader.releaseLock();
202
+ }
203
+ }
204
+ export function moduleBuildRequestId(candidate, fallback) {
205
+ const safe = (value) => /^[a-z0-9_.:-]{1,128}$/i.test(value);
206
+ return candidate !== null && safe(candidate) ? candidate : safe(fallback) ? fallback : 'unavailable';
207
+ }
208
+ //# sourceMappingURL=module-build-diagnostics.js.map
@@ -1,4 +1,5 @@
1
1
  import { CliError, EXIT } from './errors.js';
2
+ import { moduleBuildFailureGuidance } from './module-build-diagnostics.js';
2
3
  const uuid = (value) => typeof value === 'string' && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.exec(value)?.[0] === value;
3
4
  const hash = (value) => typeof value === 'string' && /^[a-f0-9]{64}$/.exec(value)?.[0] === value;
4
5
  const date = (value) => typeof value === 'string' && Number.isFinite(Date.parse(value));
@@ -33,5 +34,8 @@ export function validateModuleBuild(value, expected, action) {
33
34
  : !date(item.applied_at) || item.verification !== 'build_requested_not_published')
34
35
  || (action === 'build-approve' && !item.applied_at))
35
36
  return fail();
37
+ if (item.failure_diagnostic !== undefined && item.failure_diagnostic !== null
38
+ && !moduleBuildFailureGuidance(item))
39
+ return fail();
36
40
  }
37
41
  //# sourceMappingURL=module-build.js.map
@@ -0,0 +1,38 @@
1
+ import type { ApiClient } from './api.js';
2
+ export interface PreparationRelease {
3
+ id: string;
4
+ artifact_digest: string;
5
+ backend_modules_digest: string;
6
+ environment: {
7
+ root_project_id: string;
8
+ };
9
+ backend_modules_snapshot: Array<{
10
+ module_id: string;
11
+ name: string;
12
+ artifact_digest: string;
13
+ artifact_size_bytes: number;
14
+ }>;
15
+ }
16
+ export interface PreparationAttempt {
17
+ preparationId: string;
18
+ moduleName: string;
19
+ recordedAt: string;
20
+ explanation: string;
21
+ }
22
+ export interface ReleasePreparationDiagnostics {
23
+ state: 'available' | 'unavailable';
24
+ attempts: PreparationAttempt[];
25
+ truncated: boolean;
26
+ }
27
+ export declare function parseReleasePreparationDiagnostics(value: unknown, release: PreparationRelease): ReleasePreparationDiagnostics | undefined;
28
+ export declare function isPreparationDiagnosticsRead(path: string): boolean;
29
+ export declare function readPreparationDiagnosticsResponse(response: Response, limit: number): Promise<unknown>;
30
+ export declare function loadReleasePreparationDiagnostics(client: ApiClient, id: string, project: string): Promise<{
31
+ deploymentId: string;
32
+ projectId: string;
33
+ kind: 'recorded_attempt_failures';
34
+ explanation: string;
35
+ state: ReleasePreparationDiagnostics['state'];
36
+ attempts: PreparationAttempt[];
37
+ truncated: boolean;
38
+ }>;
@@ -0,0 +1,204 @@
1
+ import { CliError, EXIT } from './errors.js';
2
+ const uuid = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
3
+ const releaseId = /^[1-9]\d{0,18}$/;
4
+ const sha256 = /^[0-9a-f]{64}$/;
5
+ const moduleName = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
6
+ const timestamp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})$/;
7
+ const envelopeKeys = ['schema_version', 'kind', 'deployment_id', 'project_id', 'release_digest',
8
+ 'backend_modules_digest', 'state', 'serving_readiness', 'attempts', 'truncated'];
9
+ const attemptKeys = ['schema_version', 'state', 'preparation_id', 'request_id', 'project_id',
10
+ 'release_digest', 'portable_sha256', 'portable_size_bytes', 'failure_diagnostic',
11
+ 'module_id', 'module_name', 'recorded_at'];
12
+ const diagnosticKeys = ['schema_version', 'stage', 'code', 'responsibility', 'resource', 'unit',
13
+ 'limit', 'observed', 'measurement', 'remediation'];
14
+ const policy = {
15
+ memory: 8_589_934_592, cpu: 720_000_000_000, wall: 720,
16
+ portable: 80_000_000, nativeMinimum: 67_108_864, nativeCeiling: 536_870_912, expansion: 4,
17
+ };
18
+ const currentWorker = { cpu: 600_000_000_000, wall: 600 };
19
+ function record(value) {
20
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
21
+ ? value : undefined;
22
+ }
23
+ function exact(row, keys) {
24
+ return Object.keys(row).length === keys.length && keys.every(key => Object.hasOwn(row, key));
25
+ }
26
+ function matches(value, expression) {
27
+ return typeof value === 'string' && expression.exec(value)?.[0] === value;
28
+ }
29
+ function integer(value, minimum = 0, maximum = Number.MAX_SAFE_INTEGER) {
30
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= minimum && value <= maximum;
31
+ }
32
+ function explanation(value, portable) {
33
+ const row = record(value);
34
+ if (!row || ![1, 2].includes(row.schema_version) || row.stage !== 'native_preparation'
35
+ || row.responsibility !== 'platform' || row.remediation !== 'contact_support')
36
+ return undefined;
37
+ const output = row.code === 'native_output_budget_exceeded';
38
+ if (output && row.schema_version !== 1)
39
+ return undefined;
40
+ const worker = row.schema_version === 1 ? policy : currentWorker;
41
+ if (!exact(row, output ? [...diagnosticKeys, 'portable_size_bytes'] : diagnosticKeys))
42
+ return undefined;
43
+ const guidance = ' Contact BlinkHost support. Changing plans does not increase platform preparation limits.';
44
+ if (output) {
45
+ const limit = Math.min(policy.nativeCeiling, Math.max(policy.nativeMinimum, policy.expansion * portable));
46
+ if (row.resource !== 'native_artifact' || row.unit !== 'bytes' || row.measurement !== 'measured_size'
47
+ || row.portable_size_bytes !== portable || row.limit !== limit || !integer(row.observed, limit + 1))
48
+ return undefined;
49
+ return `The platform native compiler generated ${row.observed} bytes, exceeding its ${limit}-byte output budget `
50
+ + `for this ${portable}-byte portable module.` + guidance;
51
+ }
52
+ if (row.code === 'native_preparation_memory_exceeded') {
53
+ if (row.resource !== 'compiler_memory' || row.unit !== 'bytes' || row.limit !== policy.memory
54
+ || row.measurement !== (row.observed === null ? 'unavailable' : 'sampled_peak')
55
+ || row.observed !== null && !integer(row.observed))
56
+ return undefined;
57
+ return `The platform native compiler was stopped at its ${policy.memory}-byte memory allowance.`
58
+ + (row.observed === null ? '' : ` Its sampled worker peak was ${row.observed} bytes.`) + guidance;
59
+ }
60
+ if (row.code === 'native_preparation_cpu_exceeded') {
61
+ if (row.resource !== 'compiler_cpu' || row.unit !== 'nanoseconds' || row.limit !== worker.cpu
62
+ || row.measurement !== (row.observed === null ? 'unavailable' : 'sampled_aggregate')
63
+ || row.observed !== null && !integer(row.observed, worker.cpu + 1))
64
+ return undefined;
65
+ let measured = '';
66
+ if (typeof row.observed === 'number') {
67
+ const whole = Math.floor(row.observed / 1_000_000_000);
68
+ const fraction = String(row.observed % 1_000_000_000).padStart(9, '0').replace(/0+$/, '');
69
+ measured = ` Its sampled aggregate CPU time was ${whole}${fraction ? '.' + fraction : ''} seconds.`;
70
+ }
71
+ return `The platform native compiler exceeded its ${worker.cpu / 1_000_000_000}-second aggregate CPU allowance.`
72
+ + measured + guidance;
73
+ }
74
+ if (row.observed !== null || row.measurement !== 'unavailable')
75
+ return undefined;
76
+ if (row.code === 'native_preparation_deadline_exceeded') {
77
+ if (row.resource !== 'compiler_wall_time' || row.unit !== 'seconds' || row.limit !== worker.wall)
78
+ return undefined;
79
+ return `The platform native compiler reached its ${worker.wall}-second preparation deadline.` + guidance;
80
+ }
81
+ if (row.code === 'native_preparation_child_failed' && row.resource === null && row.unit === null && row.limit === null) {
82
+ return 'The platform native compiler could not finish preparing this module.' + guidance;
83
+ }
84
+ return undefined;
85
+ }
86
+ export function parseReleasePreparationDiagnostics(value, release) {
87
+ const row = record(value);
88
+ if (!row || !exact(row, envelopeKeys) || row.schema_version !== 1 || row.kind !== 'recorded_attempt_failures'
89
+ || row.serving_readiness !== 'not_evaluated' || !matches(row.deployment_id, releaseId) || row.deployment_id !== release.id
90
+ || !matches(row.project_id, uuid) || row.project_id !== release.environment.root_project_id
91
+ || !matches(row.release_digest, sha256) || row.release_digest !== release.artifact_digest
92
+ || !matches(row.backend_modules_digest, sha256) || row.backend_modules_digest !== release.backend_modules_digest
93
+ || !['available', 'unavailable'].includes(row.state) || typeof row.truncated !== 'boolean'
94
+ || !Array.isArray(row.attempts) || row.attempts.length > 50
95
+ || row.state === 'unavailable' && (row.attempts.length !== 0 || row.truncated))
96
+ return undefined;
97
+ if (!Array.isArray(release.backend_modules_snapshot) || release.backend_modules_snapshot.length > 100)
98
+ return undefined;
99
+ const modules = new Map();
100
+ for (const artifact of release.backend_modules_snapshot) {
101
+ if (!artifact || !matches(artifact.module_id, uuid) || modules.has(artifact.module_id) || !matches(artifact.name, moduleName)
102
+ || !matches(artifact.artifact_digest, sha256) || !integer(artifact.artifact_size_bytes, 1, policy.portable))
103
+ return undefined;
104
+ modules.set(artifact.module_id, artifact);
105
+ }
106
+ const preparations = new Set();
107
+ const requests = new Set();
108
+ const attempts = [];
109
+ for (const value of row.attempts) {
110
+ const attempt = record(value);
111
+ if (!attempt || !exact(attempt, attemptKeys) || attempt.schema_version !== 1 || attempt.state !== 'failed_preparation'
112
+ || !matches(attempt.preparation_id, uuid) || preparations.has(attempt.preparation_id)
113
+ || !matches(attempt.request_id, uuid) || requests.has(attempt.request_id)
114
+ || attempt.project_id !== row.project_id || attempt.release_digest !== row.release_digest
115
+ || !matches(attempt.module_id, uuid) || !matches(attempt.recorded_at, timestamp)
116
+ || !Number.isFinite(Date.parse(attempt.recorded_at)))
117
+ return undefined;
118
+ const artifact = modules.get(attempt.module_id);
119
+ if (!artifact || attempt.module_name !== artifact.name || attempt.portable_sha256 !== artifact.artifact_digest
120
+ || attempt.portable_size_bytes !== artifact.artifact_size_bytes)
121
+ return undefined;
122
+ const text = explanation(attempt.failure_diagnostic, artifact.artifact_size_bytes);
123
+ if (!text)
124
+ return undefined;
125
+ preparations.add(attempt.preparation_id);
126
+ requests.add(attempt.request_id);
127
+ attempts.push({ preparationId: attempt.preparation_id, moduleName: artifact.name,
128
+ recordedAt: attempt.recorded_at, explanation: text });
129
+ }
130
+ return { state: row.state, attempts, truncated: row.truncated };
131
+ }
132
+ export function isPreparationDiagnosticsRead(path) {
133
+ return /^\/api\/deployments\/[1-9]\d{0,18}\/(?:preparation-diagnostics\/)?$/.exec(path)?.[0] === path;
134
+ }
135
+ function unavailable() {
136
+ return new CliError('Preparation failure details are unavailable for this release.', EXIT.remote, 'preparation_diagnostics_unavailable');
137
+ }
138
+ // This bounded transport is used only by the explicit historical read command.
139
+ // Failed HTTP bodies never supply error text, limits or request identities.
140
+ export async function readPreparationDiagnosticsResponse(response, limit) {
141
+ const reader = response.body?.getReader();
142
+ let complete = false;
143
+ try {
144
+ if (response.status !== 200)
145
+ return null;
146
+ if (!reader || response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() !== 'application/json')
147
+ throw unavailable();
148
+ const length = response.headers.get('content-length');
149
+ if (length !== null && (!/^\d+$/.test(length) || Number(length) > limit))
150
+ throw unavailable();
151
+ const chunks = [];
152
+ let size = 0;
153
+ for (let reads = 0; reads < 1024; reads++) {
154
+ const chunk = await reader.read();
155
+ if (chunk.done) {
156
+ complete = true;
157
+ break;
158
+ }
159
+ size += chunk.value.byteLength;
160
+ if (size > limit)
161
+ throw unavailable();
162
+ chunks.push(chunk.value);
163
+ }
164
+ if (!complete || length !== null && Number(length) !== size)
165
+ throw unavailable();
166
+ return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks, size)));
167
+ }
168
+ catch {
169
+ throw unavailable();
170
+ }
171
+ finally {
172
+ if (!complete)
173
+ void reader?.cancel().catch(() => undefined);
174
+ reader?.releaseLock();
175
+ }
176
+ }
177
+ export async function loadReleasePreparationDiagnostics(client, id, project) {
178
+ try {
179
+ const value = record(await client.request(`/api/deployments/${id}/`, {}, 512 * 1024));
180
+ const environment = record(value?.environment);
181
+ if (!value || value.id !== id || environment?.root_project_id !== project
182
+ || !matches(value.artifact_digest, sha256) || !matches(value.backend_modules_digest, sha256)
183
+ || !Array.isArray(value.backend_modules_snapshot))
184
+ throw unavailable();
185
+ const release = {
186
+ id, artifact_digest: value.artifact_digest, backend_modules_digest: value.backend_modules_digest,
187
+ environment: { root_project_id: project }, backend_modules_snapshot: value.backend_modules_snapshot,
188
+ };
189
+ const data = await client.request(`/api/deployments/${id}/preparation-diagnostics/`, {}, 128 * 1024);
190
+ const facts = parseReleasePreparationDiagnostics(data, release);
191
+ if (!facts)
192
+ throw unavailable();
193
+ return { deploymentId: id, projectId: project, kind: 'recorded_attempt_failures',
194
+ explanation: 'Past preparation failures do not describe current serving health or confirm native readiness.', ...facts };
195
+ }
196
+ catch (error) {
197
+ if (error instanceof CliError) {
198
+ const details = error.details.filter(detail => /^Request ID: [a-z0-9_.:-]{1,128}$/i.exec(detail)?.[0] === detail);
199
+ throw new CliError('Preparation failure details are unavailable for this release.', error.exitCode, error.code, details);
200
+ }
201
+ throw unavailable();
202
+ }
203
+ }
204
+ //# sourceMappingURL=release-preparation-diagnostics.js.map
package/dist/remote.js CHANGED
@@ -7,6 +7,7 @@ import { spawn } from 'node:child_process';
7
7
  import { ApiClient, encodeQuery } from './api.js';
8
8
  import { CliError, EXIT } from './errors.js';
9
9
  import { resolveLocalPath } from './project.js';
10
+ import { loadReleasePreparationDiagnostics } from './release-preparation-diagnostics.js';
10
11
  const COLLECTIONS = {
11
12
  projects: '/api/sites/',
12
13
  repositories: '/api/source-control/repositories/',
@@ -124,6 +125,17 @@ export async function runRemote(group, input, profile) {
124
125
  if (publicationKeyOption !== undefined && key === undefined) {
125
126
  throw new CliError('--idempotency-key is supported here only for activate, promote, retry and rollback.', EXIT.usage, 'unexpected_argument');
126
127
  }
128
+ if (group === 'deployments' && action === 'preparation-diagnostics') {
129
+ const id = args.shift();
130
+ if (!id || /^[1-9]\d{0,18}$/.exec(id)?.[0] !== id
131
+ || !project || /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.exec(project)?.[0] !== project) {
132
+ throw new CliError('Use deployments preparation-diagnostics DEPLOYMENT_ID --project PROJECT_UUID.', EXIT.usage, 'invalid_preparation_scope');
133
+ }
134
+ if (query.length || dataOption !== undefined)
135
+ throw new CliError('Preparation history accepts only its release and project IDs.', EXIT.usage, 'unexpected_argument');
136
+ noExtra(args);
137
+ return loadReleasePreparationDiagnostics(await ApiClient.create(profile), id, project);
138
+ }
127
139
  const client = await ApiClient.create(profile);
128
140
  const base = collectionPath(group, project);
129
141
  const data = await readPayload(dataOption);
@@ -398,6 +410,8 @@ export async function rawApi(input, profile) {
398
410
  throw new CliError('Internal, staff, and authentication API paths are unavailable.', EXIT.usage, 'invalid_api_path');
399
411
  if (method !== 'GET' && parsed.pathname.startsWith('/api/project-secrets/'))
400
412
  throw new CliError('Use the dedicated `blinkhost secrets` commands so values never enter shell history.', EXIT.usage, 'unsafe_secret_command');
413
+ if (method !== 'GET' && parsed.pathname.startsWith('/api/source-control/test-credential-fixtures/'))
414
+ throw new CliError('Use `blinkhost test-credentials` with --stdin for test credential writes.', EXIT.usage, 'unsafe_secret_command');
401
415
  const client = await ApiClient.create(profile);
402
416
  return client.request(path, { method, ...(method === 'GET' ? {} : { body: JSON.stringify(data) }) });
403
417
  }
@@ -9,6 +9,7 @@ export interface ScaffoldOptions {
9
9
  packageManager: PackageManager;
10
10
  modules: ScaffoldModule[];
11
11
  database?: string;
12
+ tests?: boolean;
12
13
  }
13
14
  export interface Scaffold {
14
15
  manifest: BlinkHostManifest;
package/dist/templates.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { addLocalTestStarters } from './local-test-starters.js';
1
2
  const VERSIONS = {
2
3
  vite: '6.4.3', typescript: '5.9.3', react: '19.2.8', vue: '3.5.40',
3
4
  svelte: '5.56.8', solid: '1.9.14', astro: '7.1.6',
@@ -96,13 +97,15 @@ export function createScaffold(options) {
96
97
  files.set(path, contents);
97
98
  modules.push({ name: item.name, path: `_server_islands/${item.name}`, language: item.language, entrypoint: generated.entrypoint, abi: 'blinkhost-wasi-1', sdk: '1.1.0' });
98
99
  }
100
+ if (options.tests)
101
+ addLocalTestStarters(files, options);
99
102
  const databases = options.database ? [{ binding: options.database, schema: `database/${options.database}/schema.sql`, migrations: `database/${options.database}/migrations` }] : [];
100
103
  if (options.database) {
101
104
  files.set(`database/${options.database}/schema.sql`, '-- Keep the current reviewable schema here.\n');
102
105
  files.set(`database/${options.database}/migrations/README.md`, 'Add ordered, forward-only SQL migrations in this directory.\n');
103
106
  }
104
107
  files.set('.gitignore', 'node_modules/\ndist/\n.env\n.env.*\n!.env.example\n.blinkhost/\n');
105
- files.set('README.md', `# ${options.name}\n\nCreated with the BlinkHost CLI. Run \`blinkhost validate\` before connecting this repository.\n`);
108
+ files.set('README.md', `# ${options.name}\n\nCreated with the BlinkHost CLI. Run \`blinkhost validate\` before connecting this repository.\n${options.tests ? '\nRun `blinkhost test . --json` before preview; see [TESTING.md](TESTING.md).\n' : ''}`);
106
109
  return {
107
110
  manifest: {
108
111
  schema: 'blinkhost/v1', application: { root: '.' },
@@ -0,0 +1,7 @@
1
+ import type { Readable } from 'node:stream';
2
+ export declare function readTestCredentialInput(input?: Readable & {
3
+ isTTY?: boolean;
4
+ }, timeoutMs?: number): Promise<string>;
5
+ export declare function runTestCredentials(input: string[], profile?: string, source?: Readable & {
6
+ isTTY?: boolean;
7
+ }): Promise<unknown>;