@di-framework/cli-plugin-platform 0.0.1 → 6.0.2

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 (169) hide show
  1. package/README.md +408 -0
  2. package/dist/actor-protocol.d.ts +4 -0
  3. package/dist/actor-protocol.js +162 -0
  4. package/dist/actors.d.ts +31 -0
  5. package/dist/actors.js +296 -0
  6. package/dist/args.d.ts +15 -0
  7. package/dist/args.js +66 -0
  8. package/dist/assets/http-adapter.js +876 -0
  9. package/dist/assets/platform/.gitignore.tmpl +6 -0
  10. package/dist/assets/platform/Pulumi.yaml.tmpl +6 -0
  11. package/dist/assets/platform/README.md +208 -0
  12. package/dist/assets/platform/index.ts.tmpl +2 -0
  13. package/dist/assets/platform/package.json.tmpl +18 -0
  14. package/dist/assets/platform/tsconfig.json +11 -0
  15. package/dist/assets/queue-adapter.js +60 -0
  16. package/dist/assets/sqlite/BUILD-INFO.txt +13 -0
  17. package/dist/assets/sqlite/SHA256SUMS +2 -0
  18. package/dist/assets/sqlite/di-framework-sqlite.wasm +0 -0
  19. package/dist/assets/sqlite/di-framework-sqlite.wit +337 -0
  20. package/dist/assets/wit/deps/LICENSE.md +8 -0
  21. package/dist/assets/wit/deps/di-framework-queues/package.wit +18 -0
  22. package/dist/assets/wit/deps/di-framework-sqlite/package.wit +211 -0
  23. package/dist/assets/wit/deps/wasi-cli/package.wit +70 -0
  24. package/dist/assets/wit/deps/wasi-clocks/package.wit +42 -0
  25. package/dist/assets/wit/deps/wasi-config/package.wit +15 -0
  26. package/dist/assets/wit/deps/wasi-filesystem/package.wit +184 -0
  27. package/dist/assets/wit/deps/wasi-http/package.wit +170 -0
  28. package/dist/assets/wit/deps/wasi-random/package.wit +17 -0
  29. package/dist/assets/wit/deps/wasi-sockets/package.wit +105 -0
  30. package/dist/assets/wit/deps/wasi-tls/package.wit +26 -0
  31. package/dist/assets/wit/deps/wasmcloud-blobstore/package.wit +153 -0
  32. package/dist/assets/wit/deps/wasmcloud-keyvalue/package.wit +370 -0
  33. package/dist/assets/wit/deps/wasmcloud-messaging/package.wit +125 -0
  34. package/dist/assets/wit/deps/wasmcloud-postgres/package.wit +435 -0
  35. package/dist/assets/wit/deps/wasmcloud-secrets/package.wit +80 -0
  36. package/dist/async-transform.d.ts +3 -0
  37. package/dist/async-transform.js +60 -0
  38. package/dist/bindings.d.ts +34 -0
  39. package/dist/bindings.js +307 -0
  40. package/dist/build.d.ts +29 -0
  41. package/dist/build.js +325 -0
  42. package/dist/command.d.ts +3 -0
  43. package/dist/command.js +141 -0
  44. package/dist/control/auth.d.ts +18 -0
  45. package/dist/control/auth.js +89 -0
  46. package/dist/control/cron.d.ts +7 -0
  47. package/dist/control/cron.js +86 -0
  48. package/dist/control/index.d.ts +4 -0
  49. package/dist/control/index.js +4 -0
  50. package/dist/control/network.d.ts +12 -0
  51. package/dist/control/network.js +49 -0
  52. package/dist/control/queues.d.ts +15 -0
  53. package/dist/control/queues.js +77 -0
  54. package/dist/cron.d.ts +26 -0
  55. package/dist/cron.js +239 -0
  56. package/dist/deploy.d.ts +29 -0
  57. package/dist/deploy.js +57 -0
  58. package/dist/deps.d.ts +96 -0
  59. package/dist/deps.js +303 -0
  60. package/dist/destroy.d.ts +3 -0
  61. package/dist/destroy.js +24 -0
  62. package/dist/dev-runner.d.ts +24 -0
  63. package/dist/dev-runner.js +83 -0
  64. package/dist/dev.d.ts +8 -0
  65. package/dist/dev.js +76 -0
  66. package/dist/discovery.d.ts +15 -0
  67. package/dist/discovery.js +182 -0
  68. package/dist/doctor.d.ts +8 -0
  69. package/dist/doctor.js +82 -0
  70. package/dist/guests.d.ts +9 -0
  71. package/dist/guests.js +56 -0
  72. package/dist/host-interface.d.ts +29 -0
  73. package/dist/host-interface.js +142 -0
  74. package/dist/index.d.ts +33 -0
  75. package/dist/index.js +39 -0
  76. package/dist/kubernetes.d.ts +9 -0
  77. package/dist/kubernetes.js +17 -0
  78. package/dist/managed-bindings.d.ts +9 -0
  79. package/dist/managed-bindings.js +150 -0
  80. package/dist/manifest.d.ts +36 -0
  81. package/dist/manifest.js +257 -0
  82. package/dist/namespace.d.ts +2 -0
  83. package/dist/namespace.js +4 -0
  84. package/dist/node-compat/async-hooks.d.ts +29 -0
  85. package/dist/node-compat/async-hooks.js +80 -0
  86. package/dist/node-compat/bootstrap.d.ts +1 -0
  87. package/dist/node-compat/bootstrap.js +9 -0
  88. package/dist/node-compat/bytes.d.ts +7 -0
  89. package/dist/node-compat/bytes.js +41 -0
  90. package/dist/node-compat/crypto-hash.d.ts +27 -0
  91. package/dist/node-compat/crypto-hash.js +108 -0
  92. package/dist/node-compat/crypto-subtle.d.ts +59 -0
  93. package/dist/node-compat/crypto-subtle.js +288 -0
  94. package/dist/node-compat/crypto.d.ts +136 -0
  95. package/dist/node-compat/crypto.js +142 -0
  96. package/dist/node-compat/dgram.d.ts +49 -0
  97. package/dist/node-compat/dgram.js +197 -0
  98. package/dist/node-compat/env.d.ts +6 -0
  99. package/dist/node-compat/env.js +88 -0
  100. package/dist/node-compat/fetch-runtime.d.ts +80 -0
  101. package/dist/node-compat/fetch-runtime.js +314 -0
  102. package/dist/node-compat/fs.d.ts +84 -0
  103. package/dist/node-compat/fs.js +285 -0
  104. package/dist/node-compat/http-parser.d.ts +40 -0
  105. package/dist/node-compat/http-parser.js +185 -0
  106. package/dist/node-compat/http.d.ts +130 -0
  107. package/dist/node-compat/http.js +688 -0
  108. package/dist/node-compat/https.d.ts +28 -0
  109. package/dist/node-compat/https.js +88 -0
  110. package/dist/node-compat/module.d.ts +11 -0
  111. package/dist/node-compat/module.js +35 -0
  112. package/dist/node-compat/net.d.ts +119 -0
  113. package/dist/node-compat/net.js +441 -0
  114. package/dist/node-compat/process.d.ts +25 -0
  115. package/dist/node-compat/process.js +63 -0
  116. package/dist/node-compat/runtime-application.d.ts +4 -0
  117. package/dist/node-compat/runtime-application.js +24 -0
  118. package/dist/node-compat/seed-virtual.d.ts +6 -0
  119. package/dist/node-compat/seed-virtual.js +6 -0
  120. package/dist/node-compat/seed.d.ts +20 -0
  121. package/dist/node-compat/seed.js +106 -0
  122. package/dist/node-compat/socket-address.d.ts +35 -0
  123. package/dist/node-compat/socket-address.js +162 -0
  124. package/dist/node-compat/timers.d.ts +32 -0
  125. package/dist/node-compat/timers.js +96 -0
  126. package/dist/node-compat/tls.d.ts +57 -0
  127. package/dist/node-compat/tls.js +290 -0
  128. package/dist/node-compat/wasi-random.d.ts +2 -0
  129. package/dist/node-compat/wasi-random.js +25 -0
  130. package/dist/node-compat/wasi-sockets.d.ts +47 -0
  131. package/dist/node-compat/wasi-sockets.js +134 -0
  132. package/dist/oci.d.ts +9 -0
  133. package/dist/oci.js +9 -0
  134. package/dist/paths.d.ts +7 -0
  135. package/dist/paths.js +13 -0
  136. package/dist/platform-init.d.ts +13 -0
  137. package/dist/platform-init.js +265 -0
  138. package/dist/platform.d.ts +22 -0
  139. package/dist/platform.js +170 -0
  140. package/dist/project.d.ts +39 -0
  141. package/dist/project.js +130 -0
  142. package/dist/publish.d.ts +15 -0
  143. package/dist/publish.js +57 -0
  144. package/dist/pulumi.d.ts +4 -0
  145. package/dist/pulumi.js +27 -0
  146. package/dist/queues-module.d.ts +4 -0
  147. package/dist/queues-module.js +89 -0
  148. package/dist/queues.d.ts +16 -0
  149. package/dist/queues.js +167 -0
  150. package/dist/registry.d.ts +16 -0
  151. package/dist/registry.js +27 -0
  152. package/dist/service.d.ts +162 -0
  153. package/dist/service.js +678 -0
  154. package/dist/support.d.ts +14 -0
  155. package/dist/support.js +37 -0
  156. package/dist/target.d.ts +18 -0
  157. package/dist/target.js +45 -0
  158. package/dist/toml.d.ts +6 -0
  159. package/dist/toml.js +245 -0
  160. package/dist/wash-dev.d.ts +18 -0
  161. package/dist/wash-dev.js +80 -0
  162. package/dist/wit.d.ts +76 -0
  163. package/dist/wit.js +248 -0
  164. package/dist/workload-members.d.ts +12 -0
  165. package/dist/workload-members.js +136 -0
  166. package/dist/workload.d.ts +45 -0
  167. package/dist/workload.js +457 -0
  168. package/package.json +55 -8
  169. package/src/index.ts +0 -2
@@ -0,0 +1,307 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { CommandFailure } from '@di-framework/cli-extension';
4
+ import ts from 'typescript';
5
+ import { asWitIdentifier } from './project.js';
6
+ function importedDecoratorNames(source) {
7
+ const names = new Set(['WasmCloudBinding']);
8
+ for (const statement of source.statements) {
9
+ if (!ts.isImportDeclaration(statement) || statement.importClause == null)
10
+ continue;
11
+ const module = stringLiteral(statement.moduleSpecifier);
12
+ if (module !== '@di-framework/bindings')
13
+ continue;
14
+ const named = statement.importClause.namedBindings;
15
+ if (named === undefined || !ts.isNamedImports(named))
16
+ continue;
17
+ for (const element of named.elements) {
18
+ const imported = (element.propertyName ?? element.name).text;
19
+ if (imported === 'WasmCloudBinding')
20
+ names.add(element.name.text);
21
+ }
22
+ }
23
+ return names;
24
+ }
25
+ function bindingsFailure(code, message, details = {}) {
26
+ throw new CommandFailure(code, message, 2, details);
27
+ }
28
+ export function defaultSecretName(applicationName, bindingName) {
29
+ return `${asWitIdentifier(applicationName)}-${bindingName}`;
30
+ }
31
+ const SECRET_CONFIG_KEYS = new Set([
32
+ 'password',
33
+ 'secret',
34
+ 'token',
35
+ 'uri',
36
+ 'url',
37
+ 'connectionstring',
38
+ 'connection-string',
39
+ ]);
40
+ export function rejectsPlaintextSecret(config) {
41
+ if (config === undefined)
42
+ return undefined;
43
+ for (const [key, value] of Object.entries(config)) {
44
+ if (SECRET_CONFIG_KEYS.has(key.toLowerCase())) {
45
+ return `config key "${key}" must not carry a secret value; use secretFrom`;
46
+ }
47
+ if (/:\/\//.test(value) || /password=/i.test(value)) {
48
+ return `config value for "${key}" looks like a secret or connection string; use secretFrom`;
49
+ }
50
+ }
51
+ return undefined;
52
+ }
53
+ export function bindingsPath(project) {
54
+ return project.bindingsPath;
55
+ }
56
+ export function loadBindingCatalog(projectRoot, deps) {
57
+ const catalogJson = deps.resolveFromProject(projectRoot, '@di-framework/bindings/catalog.json');
58
+ if (catalogJson !== undefined)
59
+ return JSON.parse(readFileSync(catalogJson, 'utf8'));
60
+ const pkg = deps.resolveFromProject(projectRoot, '@di-framework/bindings');
61
+ if (pkg === undefined)
62
+ return undefined;
63
+ const candidate = join(dirname(pkg), 'catalog.json');
64
+ if (!existsSync(candidate))
65
+ return undefined;
66
+ return JSON.parse(readFileSync(candidate, 'utf8'));
67
+ }
68
+ function decoratorName(expression) {
69
+ let current = expression;
70
+ while (ts.isCallExpression(current))
71
+ current = current.expression;
72
+ if (ts.isIdentifier(current))
73
+ return current.text;
74
+ if (!ts.isPropertyAccessExpression(current) || !ts.isIdentifier(current.name))
75
+ return undefined;
76
+ return current.name.text;
77
+ }
78
+ function stringLiteral(node) {
79
+ if (node === undefined)
80
+ return undefined;
81
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
82
+ return node.text;
83
+ return undefined;
84
+ }
85
+ function objectLiteral(node) {
86
+ if (node === undefined || !ts.isObjectLiteralExpression(node))
87
+ return undefined;
88
+ const result = {};
89
+ for (const property of node.properties) {
90
+ if (!ts.isPropertyAssignment(property) || !ts.isIdentifier(property.name))
91
+ return undefined;
92
+ const name = property.name.text;
93
+ const value = property.initializer;
94
+ if (ts.isStringLiteral(value) || ts.isNoSubstitutionTemplateLiteral(value)) {
95
+ result[name] = value.text;
96
+ continue;
97
+ }
98
+ if (ts.isArrayLiteralExpression(value)) {
99
+ const items = [];
100
+ for (const element of value.elements) {
101
+ const text = stringLiteral(element);
102
+ if (text === undefined)
103
+ return undefined;
104
+ items.push(text);
105
+ }
106
+ result[name] = items;
107
+ continue;
108
+ }
109
+ if (ts.isObjectLiteralExpression(value)) {
110
+ const nested = objectLiteral(value);
111
+ if (nested === undefined)
112
+ return undefined;
113
+ result[name] = nested;
114
+ continue;
115
+ }
116
+ return undefined;
117
+ }
118
+ return result;
119
+ }
120
+ function classDecorators(node) {
121
+ const fromModifiers = (node.modifiers ?? []).filter((modifier) => ts.isDecorator(modifier));
122
+ const legacy = node
123
+ .decorators;
124
+ return [...fromModifiers, ...(legacy ?? [])];
125
+ }
126
+ function importedKinds(source) {
127
+ const aliases = new Map();
128
+ for (const statement of source.statements) {
129
+ if (!ts.isImportDeclaration(statement) || statement.importClause == null)
130
+ continue;
131
+ const module = stringLiteral(statement.moduleSpecifier);
132
+ if (module !== '@di-framework/bindings')
133
+ continue;
134
+ const named = statement.importClause.namedBindings;
135
+ if (named === undefined || !ts.isNamedImports(named))
136
+ continue;
137
+ for (const element of named.elements) {
138
+ const imported = (element.propertyName ?? element.name).text;
139
+ if (imported === 'Postgres' ||
140
+ imported === 'KeyValue' ||
141
+ imported === 'Blobstore' ||
142
+ imported === 'Messaging' ||
143
+ imported === 'Config' ||
144
+ imported === 'Secrets' ||
145
+ imported === 'OutgoingHttp') {
146
+ aliases.set(element.name.text, imported);
147
+ }
148
+ }
149
+ }
150
+ return aliases;
151
+ }
152
+ export function parseBindingsFile(filePath, catalog, applicationName) {
153
+ let text;
154
+ try {
155
+ text = readFileSync(filePath, 'utf8');
156
+ }
157
+ catch (error) {
158
+ bindingsFailure('WASMCLOUD_BINDINGS_UNREADABLE', `Could not read bindings file ${filePath}: ${error instanceof Error ? error.message : String(error)}`, { filePath });
159
+ }
160
+ const source = ts.createSourceFile(filePath, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
161
+ const kinds = importedKinds(source);
162
+ const decoratorNames = importedDecoratorNames(source);
163
+ const records = [];
164
+ const names = new Set();
165
+ for (const statement of source.statements) {
166
+ if (!ts.isClassDeclaration(statement) || statement.name === undefined)
167
+ continue;
168
+ const exported = statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) ===
169
+ true;
170
+ if (!exported)
171
+ continue;
172
+ const heritage = statement.heritageClauses?.find((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword);
173
+ const superName = heritage?.types[0]?.expression;
174
+ if (superName === undefined || !ts.isIdentifier(superName))
175
+ continue;
176
+ const kind = kinds.get(superName.text);
177
+ if (kind === undefined) {
178
+ bindingsFailure('WASMCLOUD_BINDING_UNKNOWN_TYPE', `${statement.name.text} extends ${superName.text}, which is not a @di-framework/bindings binding class`, { className: statement.name.text, superClass: superName.text });
179
+ }
180
+ const entry = catalog[kind];
181
+ if (entry === undefined) {
182
+ bindingsFailure('WASMCLOUD_BINDING_UNKNOWN_TYPE', `No catalog entry for binding class ${kind}`, { className: statement.name.text, kind });
183
+ }
184
+ let bindingName;
185
+ let options = {};
186
+ for (const decorator of classDecorators(statement)) {
187
+ if (!ts.isCallExpression(decorator.expression))
188
+ continue;
189
+ if (!decoratorNames.has(decoratorName(decorator.expression) ?? ''))
190
+ continue;
191
+ const [nameArg, optionsArg] = decorator.expression.arguments;
192
+ const name = stringLiteral(nameArg);
193
+ if (name === undefined) {
194
+ bindingsFailure('WASMCLOUD_BINDING_INVALID_NAME', `${statement.name.text} @WasmCloudBinding name must be a string literal`, { className: statement.name.text });
195
+ }
196
+ bindingName = name;
197
+ const parsed = objectLiteral(optionsArg);
198
+ if (optionsArg !== undefined && parsed === undefined) {
199
+ bindingsFailure('WASMCLOUD_BINDING_INVALID_OPTIONS', `${statement.name.text} @WasmCloudBinding options must be an object literal of string values`, { className: statement.name.text });
200
+ }
201
+ if (parsed !== undefined) {
202
+ if (parsed.serviceName !== undefined && typeof parsed.serviceName !== 'string')
203
+ bindingsFailure('WASMCLOUD_BINDING_INVALID_SERVICE', 'serviceName must be a string literal');
204
+ if (parsed.serviceName !== undefined &&
205
+ ['config', 'configFrom', 'secretFrom'].some((key) => parsed[key] !== undefined))
206
+ bindingsFailure('WASMCLOUD_BINDING_INVALID_OPTIONS', 'serviceName cannot be combined with manual connection configuration');
207
+ options = {
208
+ interfaces: Array.isArray(parsed.interfaces)
209
+ ? parsed.interfaces
210
+ : undefined,
211
+ serviceName: typeof parsed.serviceName === 'string' ? parsed.serviceName : undefined,
212
+ secretFrom: typeof parsed.secretFrom === 'string' ? parsed.secretFrom : undefined,
213
+ configFrom: typeof parsed.configFrom === 'string' ? parsed.configFrom : undefined,
214
+ config: parsed.config !== undefined &&
215
+ typeof parsed.config === 'object' &&
216
+ !Array.isArray(parsed.config)
217
+ ? parsed.config
218
+ : undefined,
219
+ };
220
+ const secretProblem = rejectsPlaintextSecret(options.config);
221
+ if (secretProblem !== undefined) {
222
+ bindingsFailure('WASMCLOUD_BINDING_PLAINTEXT_SECRET', `${statement.name.text} @WasmCloudBinding: ${secretProblem}`, { className: statement.name.text, name: bindingName });
223
+ }
224
+ }
225
+ }
226
+ if (bindingName === undefined) {
227
+ bindingsFailure('WASMCLOUD_BINDING_INVALID_NAME', `${statement.name.text} must be decorated with @WasmCloudBinding('name')`, { className: statement.name.text });
228
+ }
229
+ if (!/^[a-z][a-z0-9-]*$/.test(bindingName)) {
230
+ bindingsFailure('WASMCLOUD_BINDING_INVALID_NAME', `${statement.name.text} binding name "${bindingName}" must be a WIT identifier`, { className: statement.name.text, name: bindingName });
231
+ }
232
+ if (names.has(bindingName)) {
233
+ bindingsFailure('WASMCLOUD_BINDING_DUPLICATE_NAME', `Duplicate wasmCloud binding name "${bindingName}"`, { name: bindingName, className: statement.name.text });
234
+ }
235
+ names.add(bindingName);
236
+ if (options.serviceName !== undefined) {
237
+ if (kind !== 'Postgres' ||
238
+ !/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(options.serviceName) ||
239
+ options.serviceName.length > 40)
240
+ bindingsFailure('WASMCLOUD_BINDING_INVALID_SERVICE', 'serviceName requires Postgres and a DNS label of at most 40 characters');
241
+ if (bindingName.length > 54 || !/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(bindingName))
242
+ bindingsFailure('WASMCLOUD_BINDING_INVALID_NAME', 'Managed PostgreSQL binding names must be DNS labels of at most 54 characters');
243
+ }
244
+ const interfaces = options.interfaces ?? entry.interfaces;
245
+ for (const iface of interfaces) {
246
+ if (!entry.interfaces.includes(iface)) {
247
+ bindingsFailure('WASMCLOUD_BINDING_UNSUPPORTED_INTERFACE', `${statement.name.text} requests unsupported interface "${iface}" on ${kind}`, { className: statement.name.text, iface, kind });
248
+ }
249
+ }
250
+ if (interfaces.length === 0) {
251
+ bindingsFailure('WASMCLOUD_BINDING_UNSUPPORTED_INTERFACE', `${statement.name.text} must declare at least one interface`, { className: statement.name.text });
252
+ }
253
+ const ordered = [
254
+ entry.primaryInterface,
255
+ ...interfaces.filter((iface) => iface !== entry.primaryInterface),
256
+ ].filter((iface) => interfaces.includes(iface));
257
+ records.push({
258
+ className: statement.name.text,
259
+ name: bindingName,
260
+ kind,
261
+ requirement: {
262
+ package: entry.package,
263
+ version: entry.version,
264
+ interfaces: ordered,
265
+ direction: 'import',
266
+ instanceName: entry.namedInstance ? bindingName : undefined,
267
+ source: statement.name.text,
268
+ },
269
+ serviceName: options.serviceName,
270
+ secretFrom: options.serviceName
271
+ ? `di-binding-${bindingName}-creds`
272
+ : (options.secretFrom ??
273
+ (entry.usesSecret ? defaultSecretName(applicationName, bindingName) : undefined)),
274
+ configFrom: options.configFrom,
275
+ config: options.config,
276
+ });
277
+ }
278
+ return records;
279
+ }
280
+ export function discoverBindings(project, deps) {
281
+ const path = project.bindingsPath;
282
+ if (path === undefined)
283
+ return [];
284
+ if (!existsSync(path)) {
285
+ if (project.bindingsConfigured) {
286
+ bindingsFailure('WASMCLOUD_BINDINGS_NOT_FOUND', `bindings "${project.bindingsRelative}" is not readable`, { configPath: project.configPath });
287
+ }
288
+ return [];
289
+ }
290
+ const catalog = loadBindingCatalog(project.projectRoot, deps);
291
+ if (catalog === undefined) {
292
+ bindingsFailure('WASMCLOUD_BINDING_CATALOG_MISSING', 'src/bindings.ts requires @di-framework/bindings in the project', { className: path, application: project.applicationName });
293
+ }
294
+ return parseBindingsFile(path, catalog, project.applicationName);
295
+ }
296
+ export function requirementsFromBindings(bindings) {
297
+ return bindings.flatMap((binding) => {
298
+ if (!binding.serviceName)
299
+ return [{ ...binding.requirement, interfaces: [...binding.requirement.interfaces] }];
300
+ return binding.requirement.interfaces.map((iface) => ({
301
+ ...binding.requirement,
302
+ interfaces: [iface],
303
+ instanceName: iface === 'types' ? undefined : `${binding.name}-${iface}`,
304
+ namedImport: iface !== 'types',
305
+ }));
306
+ });
307
+ }
@@ -0,0 +1,29 @@
1
+ import { type CliIo, type CommandResult } from '@di-framework/cli-extension';
2
+ import { type WasmcloudDeps } from './deps.js';
3
+ import { type WasmcloudProject } from './project.js';
4
+ import { COMPONENT_MODEL, WASI_HTTP_INTERFACE, WASI_HTTP_VERSION, type WitLock, type WitRequirement } from './wit.js';
5
+ export { COMPONENT_MODEL, WASI_HTTP_INTERFACE, WASI_HTTP_VERSION };
6
+ export declare const BUILD_PROFILE_NAME = "wasmcloud-http";
7
+ export declare const CRON_BUILD_PROFILE_NAME = "wasmcloud-cron";
8
+ export { BUILD_PROFILE_NAME as BUILD_PROFILE };
9
+ export type BuildSummary = {
10
+ application: string;
11
+ artifactDigest: string;
12
+ component: string;
13
+ componentModel: string;
14
+ deploymentDigest: string;
15
+ entry: string;
16
+ profile: string;
17
+ actors?: string[];
18
+ };
19
+ export declare function requirementsForProject(project: WasmcloudProject, deps?: WasmcloudDeps): WitRequirement[];
20
+ /** The disposable `.di-framework/` build directory: WIT world, bundle, and manifests. */
21
+ export declare function buildComponent(project: WasmcloudProject, io: CliIo, deps: WasmcloudDeps): Promise<BuildSummary>;
22
+ /**
23
+ * Stable logical version for deployment. ComponentizeJS snapshots can contain
24
+ * nondeterministic engine bytes, so the rollout key is the canonical bundle,
25
+ * WIT lock, OCI configuration, pinned build profile, and (when composed) the
26
+ * pinned SQLite provider artifact — not the final componentize output bytes.
27
+ */
28
+ export declare function canonicalBuildDigest(bundledJavaScript: string, witDirectory: string, ociConfig: string, lock: WitLock, profile?: string, sqliteProvider?: string): string;
29
+ export declare function runWasmcloudBuild(args: readonly string[], io: CliIo, deps?: WasmcloudDeps): Promise<CommandResult>;
package/dist/build.js ADDED
@@ -0,0 +1,325 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync, } from 'node:fs';
3
+ import { dirname, join, relative, sep } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { CommandFailure } from '@di-framework/cli-extension';
6
+ import { discoverActors, renderActorsModule } from './actors.js';
7
+ import { discoverBindings, requirementsFromBindings } from './bindings.js';
8
+ import { discoverScheduledJobs, renderCronAdapterModule, renderCronInvokerModule } from './cron.js';
9
+ import { DEFAULT_DEPS } from './deps.js';
10
+ import { renderGuestsModule } from './guests.js';
11
+ import { OCI_ARTIFACT_PLATFORM } from './oci.js';
12
+ import { loadProject } from './project.js';
13
+ import { discoverQueueHandlers, isQueueWorkerProject } from './queues.js';
14
+ import { renderQueuesModule } from './queues-module.js';
15
+ import { invalidUsage, requireNodeBinary, toolFailed } from './support.js';
16
+ import { buildWitLock, COMPONENT_MODEL, defaultProjectRequirements, digestBytes, queueProjectRequirements, renderWorldWit, runtimeRequirementsFromJavaScript, sqliteProjectRequirements, WASI_HTTP_INTERFACE, WASI_HTTP_VERSION, } from './wit.js';
17
+ import { renderWorkloadServiceAdapter } from './workload-members.js';
18
+ export { COMPONENT_MODEL, WASI_HTTP_INTERFACE, WASI_HTTP_VERSION };
19
+ export const BUILD_PROFILE_NAME = 'wasmcloud-http';
20
+ export const CRON_BUILD_PROFILE_NAME = 'wasmcloud-cron';
21
+ export { BUILD_PROFILE_NAME as BUILD_PROFILE };
22
+ export function requirementsForProject(project, deps = DEFAULT_DEPS) {
23
+ const bindings = discoverBindings(project, deps);
24
+ const queueHandlers = discoverQueueHandlers(project);
25
+ const isWorker = isQueueWorkerProject(project, queueHandlers);
26
+ const cronJobs = discoverScheduledJobs(project.projectRoot);
27
+ const actors = discoverActors(project);
28
+ const needsControlHttp = isWorker || cronJobs.length > 0 || queueHandlers.length > 0 || actors.length > 0;
29
+ const hasHttp = (project.ingress !== false && !isWorker) || needsControlHttp;
30
+ const service = project.workloadEntry?.kind === 'service' ? project.workloadEntry : undefined;
31
+ const baseRequirements = service?.subscriptions
32
+ ? [
33
+ {
34
+ package: 'wasmcloud:messaging',
35
+ version: '0.3.0',
36
+ interfaces: ['handler'],
37
+ direction: 'export',
38
+ source: 'workload-service',
39
+ },
40
+ ]
41
+ : isWorker
42
+ ? queueProjectRequirements()
43
+ : hasHttp
44
+ ? defaultProjectRequirements()
45
+ : [
46
+ {
47
+ package: 'wasi:cli',
48
+ version: '0.3.0',
49
+ interfaces: ['run'],
50
+ direction: 'export',
51
+ source: 'cron-adapter',
52
+ },
53
+ ];
54
+ return [...baseRequirements, ...requirementsFromBindings(bindings)];
55
+ }
56
+ function writeGuestsModule(generatedDirectory, bindings) {
57
+ writeFileSync(join(generatedDirectory, 'guests.js'), renderGuestsModule(bindings));
58
+ }
59
+ async function runComponentize(project, generatedWit, bundledJavaScript, deps) {
60
+ const qjsCli = deps.componentizeQjsPath();
61
+ if (qjsCli !== undefined) {
62
+ const result = await deps.runner(qjsCli, [
63
+ '--wit',
64
+ generatedWit,
65
+ '--js',
66
+ bundledJavaScript,
67
+ '-n',
68
+ 'application',
69
+ '-o',
70
+ project.outputPath,
71
+ ], { cwd: project.projectRoot });
72
+ return { exitCode: result.exitCode, tool: 'componentize-qjs' };
73
+ }
74
+ const result = await deps.runner(requireNodeBinary(deps.nodeBinaryPath()), [
75
+ deps.jcoCliPath(),
76
+ 'componentize',
77
+ '--backend',
78
+ 'qjs',
79
+ '-w',
80
+ generatedWit,
81
+ '-n',
82
+ 'application',
83
+ '-o',
84
+ project.outputPath,
85
+ bundledJavaScript,
86
+ ], { cwd: project.projectRoot });
87
+ return { exitCode: result.exitCode, tool: 'jco componentize' };
88
+ }
89
+ function isWasmMagic(path) {
90
+ const header = readFileSync(path).subarray(0, 4);
91
+ return (header.length === 4 &&
92
+ header[0] === 0 &&
93
+ header[1] === 0x61 &&
94
+ header[2] === 0x73 &&
95
+ header[3] === 0x6d);
96
+ }
97
+ function sqliteToolsBin() {
98
+ const here = dirname(fileURLToPath(import.meta.url));
99
+ const fromEnv = process.env.DF_SQLITE_TOOLS_DIR;
100
+ const candidates = [
101
+ fromEnv ? join(fromEnv, 'bin') : undefined,
102
+ join(here, '..', '..', 'di-framework-sqlite-component', '.tools', 'bin'),
103
+ join(here, '..', '..', '..', '..', 'platform', 'platform', 'sqlite-component', '.tools', 'bin'),
104
+ join(here, '..', '..', '..', '..', 'di-framework', 'packages', 'di-framework-sqlite-component', '.tools', 'bin'),
105
+ ].filter((path) => path !== undefined);
106
+ return candidates.find((path) => existsSync(join(path, 'wac')));
107
+ }
108
+ async function composeSqliteProvider(project, deps, io, namedImports = false) {
109
+ const provider = join(deps.assetsDirectory(), 'sqlite', 'di-framework-sqlite.wasm');
110
+ if (!existsSync(provider)) {
111
+ throw new CommandFailure('WASMCLOUD_SQLITE_PROVIDER_MISSING', `Packaged SQLite provider missing at ${provider}`, 3, { application: project.applicationName });
112
+ }
113
+ const composed = `${project.outputPath}.composed`;
114
+ const toolsBin = sqliteToolsBin();
115
+ const envPath = [toolsBin, process.env.PATH ?? ''].filter(Boolean).join(':');
116
+ const wac = deps.capture('wac', ['--version']) !== undefined
117
+ ? 'wac'
118
+ : toolsBin
119
+ ? join(toolsBin, 'wac')
120
+ : 'wac';
121
+ io.stdout.write('Composing di-framework:sqlite provider...\n');
122
+ const compiler = namedImports ? deps.componentizeQjsPath() : undefined;
123
+ if (namedImports && !compiler)
124
+ throw new CommandFailure('WASMCLOUD_COMPILER_REQUIRED', 'Managed PostgreSQL requires componentize-qjs 0.4.4-di.3 or newer', 3);
125
+ const result = await deps.runCaptured(compiler ?? wac, compiler
126
+ ? ['compose', project.outputPath, '--definition', provider, '-o', composed]
127
+ : ['plug', '--plug', provider, project.outputPath, '-o', composed], { cwd: project.projectRoot, env: { ...process.env, PATH: envPath } });
128
+ if (result.exitCode !== 0) {
129
+ throw new CommandFailure('WASMCLOUD_SQLITE_COMPOSE_FAILED', `SQLite composition failed: ${result.stderr || result.stdout}`, 3, { application: project.applicationName, exitCode: result.exitCode });
130
+ }
131
+ writeFileSync(project.outputPath, readFileSync(composed));
132
+ rmSync(composed, { force: true });
133
+ }
134
+ async function inspectComponentImports(project, requirements, deps) {
135
+ if (!isWasmMagic(project.outputPath))
136
+ return;
137
+ const captured = await deps.runCaptured(requireNodeBinary(deps.nodeBinaryPath()), [deps.jcoCliPath(), 'wit', project.outputPath], { cwd: project.projectRoot });
138
+ if (captured.exitCode !== 0) {
139
+ throw new CommandFailure('WASMCLOUD_COMPONENT_IMPORTS_UNREADABLE', `Could not inspect component imports for ${project.applicationName}`, 3, { application: project.applicationName });
140
+ }
141
+ const wit = `${captured.stdout}\n${captured.stderr}`;
142
+ for (const requirement of requirements) {
143
+ if (requirement.direction !== 'import')
144
+ continue;
145
+ for (const iface of requirement.interfaces) {
146
+ const needle = `${requirement.package}/${iface}@${requirement.version}`;
147
+ if (!wit.includes(needle)) {
148
+ throw new CommandFailure('WASMCLOUD_COMPONENT_IMPORTS_MISMATCH', `Compiled component is missing declared import ${needle} (binding ${requirement.source})`, 3, { application: project.applicationName, source: requirement.source, iface });
149
+ }
150
+ }
151
+ }
152
+ }
153
+ /** The disposable `.di-framework/` build directory: WIT world, bundle, and manifests. */
154
+ export async function buildComponent(project, io, deps) {
155
+ const generatedDirectory = join(project.projectRoot, '.di-framework');
156
+ const generatedWit = join(generatedDirectory, 'wit');
157
+ const bundledJavaScript = join(generatedDirectory, 'component.js');
158
+ const bindings = discoverBindings(project, deps);
159
+ const cronJobs = discoverScheduledJobs(project.projectRoot);
160
+ const isWorker = isQueueWorkerProject(project, discoverQueueHandlers(project));
161
+ const queueHandlers = discoverQueueHandlers(project);
162
+ const needsControlHttp = isWorker || cronJobs.length > 0;
163
+ const hasHttp = (project.ingress !== false && !isWorker) || needsControlHttp;
164
+ const profile = project.workloadEntry?.kind === 'service'
165
+ ? 'wasmcloud-service'
166
+ : isWorker
167
+ ? 'wasmcloud-worker'
168
+ : hasHttp
169
+ ? BUILD_PROFILE_NAME
170
+ : CRON_BUILD_PROFILE_NAME;
171
+ const actors = discoverActors(project);
172
+ const requirements = requirementsForProject(project, deps);
173
+ if (actors.length > 0) {
174
+ for (const requirement of sqliteProjectRequirements()) {
175
+ if (!requirements.some((entry) => entry.package === requirement.package &&
176
+ entry.interfaces.join(',') === requirement.interfaces.join(','))) {
177
+ requirements.push(requirement);
178
+ }
179
+ }
180
+ }
181
+ rmSync(generatedDirectory, { recursive: true, force: true });
182
+ mkdirSync(join(generatedWit, 'deps'), { recursive: true });
183
+ mkdirSync(dirname(project.outputPath), { recursive: true });
184
+ cpSync(join(deps.assetsDirectory(), 'wit', 'deps'), join(generatedWit, 'deps'), {
185
+ recursive: true,
186
+ });
187
+ writeFileSync(join(generatedWit, 'world.wit'), renderWorldWit(project.witName, project.version, requirements));
188
+ let lock = buildWitLock(requirements, join(generatedWit, 'deps'));
189
+ writeFileSync(join(generatedDirectory, 'wit.lock.json'), `${JSON.stringify(lock, null, 2)}\n`);
190
+ writeFileSync(join(generatedDirectory, 'oci-config.json'), `${JSON.stringify(OCI_ARTIFACT_PLATFORM, null, 2)}\n`);
191
+ if (bindings.length > 0)
192
+ writeGuestsModule(generatedDirectory, bindings);
193
+ if (cronJobs.length > 0) {
194
+ writeFileSync(join(generatedDirectory, 'cron.json'), `${JSON.stringify(cronJobs, null, 2)}\n`);
195
+ }
196
+ if (cronJobs.length > 0 || !hasHttp) {
197
+ writeFileSync(join(generatedDirectory, 'cron-invoker.js'), renderCronInvokerModule(cronJobs));
198
+ }
199
+ if (!hasHttp && !isWorker) {
200
+ const service = project.workloadEntry?.kind === 'service' ? project.workloadEntry : undefined;
201
+ writeFileSync(join(generatedDirectory, 'cron-adapter.js'), service ? renderWorkloadServiceAdapter(service) : renderCronAdapterModule(cronJobs));
202
+ }
203
+ if (actors.length > 0)
204
+ writeFileSync(join(generatedDirectory, 'actors.js'), renderActorsModule(actors));
205
+ if (queueHandlers.length > 0) {
206
+ writeFileSync(join(generatedDirectory, 'queues.js'), renderQueuesModule(queueHandlers));
207
+ }
208
+ let applicationEntry = project.entryPath;
209
+ if (project.workloadEntry?.kind === 'component') {
210
+ applicationEntry = join(generatedDirectory, 'application-entry.js');
211
+ const entry = project.workloadEntry;
212
+ writeFileSync(applicationEntry, [
213
+ `import { ${entry.exportName} as invoke } from ${JSON.stringify(project.entryPath)};`,
214
+ `export * from ${JSON.stringify(project.entryPath)};`,
215
+ `export default function fetch(request) {`,
216
+ ...(entry.path
217
+ ? [
218
+ ` if (new URL(request.url).pathname !== ${JSON.stringify(entry.path)}) return new Response(null, { status: 404 });`,
219
+ ]
220
+ : []),
221
+ ` return invoke(request);`,
222
+ `}`,
223
+ '',
224
+ ].join('\n'));
225
+ }
226
+ io.stdout.write(`Building ${project.applicationName}...\n`);
227
+ try {
228
+ await deps.bundler({
229
+ adapterPath: hasHttp
230
+ ? join(deps.assetsDirectory(), 'http-adapter.js')
231
+ : join(generatedDirectory, 'cron-adapter.js'),
232
+ entryPath: applicationEntry,
233
+ outFile: bundledJavaScript,
234
+ guestsPath: bindings.length > 0 ? join(generatedDirectory, 'guests.js') : undefined,
235
+ actorsPath: actors.length > 0 ? join(generatedDirectory, 'actors.js') : undefined,
236
+ cronPath: cronJobs.length > 0 ? join(generatedDirectory, 'cron-invoker.js') : undefined,
237
+ queuesPath: queueHandlers.length > 0 ? join(generatedDirectory, 'queues.js') : undefined,
238
+ projectRoot: project.projectRoot,
239
+ });
240
+ }
241
+ catch (error) {
242
+ throw new CommandFailure('WASMCLOUD_BUILD_FAILED', `Bundling failed: ${error instanceof Error ? error.message : String(error)}`, 3, { entry: relative(project.projectRoot, project.entryPath) });
243
+ }
244
+ const runtimeRequirements = runtimeRequirementsFromJavaScript(readFileSync(bundledJavaScript, 'utf8'));
245
+ const finalRequirements = [...requirements, ...runtimeRequirements];
246
+ if (runtimeRequirements.length > 0) {
247
+ writeFileSync(join(generatedWit, 'world.wit'), renderWorldWit(project.witName, project.version, finalRequirements));
248
+ lock = buildWitLock(finalRequirements, join(generatedWit, 'deps'));
249
+ writeFileSync(join(generatedDirectory, 'wit.lock.json'), `${JSON.stringify(lock, null, 2)}\n`);
250
+ }
251
+ const componentize = await runComponentize(project, generatedWit, bundledJavaScript, deps);
252
+ if (componentize.exitCode !== 0) {
253
+ throw toolFailed(componentize.tool, componentize.exitCode);
254
+ }
255
+ const needsSqliteCompose = finalRequirements.some((requirement) => requirement.package === 'di-framework:sqlite' && requirement.direction === 'import');
256
+ if (needsSqliteCompose) {
257
+ await composeSqliteProvider(project, deps, io, finalRequirements.some((r) => r.namedImport));
258
+ }
259
+ await inspectComponentImports(project, finalRequirements.filter((requirement) => !(requirement.package === 'di-framework:sqlite' && requirement.direction === 'import')), deps);
260
+ const deploymentDigest = canonicalBuildDigest(bundledJavaScript, generatedWit, join(generatedDirectory, 'oci-config.json'), lock, profile, needsSqliteCompose
261
+ ? join(deps.assetsDirectory(), 'sqlite', 'di-framework-sqlite.wasm')
262
+ : undefined);
263
+ const artifactDigest = digestBytes(readFileSync(project.outputPath));
264
+ const summary = {
265
+ application: project.applicationName,
266
+ artifactDigest,
267
+ component: relative(project.projectRoot, project.outputPath),
268
+ componentModel: COMPONENT_MODEL,
269
+ deploymentDigest,
270
+ entry: relative(project.projectRoot, project.entryPath),
271
+ profile,
272
+ ...(actors.length > 0 ? { actors: actors.map((a) => a.actorName) } : {}),
273
+ };
274
+ writeFileSync(join(generatedDirectory, 'build.json'), `${JSON.stringify({ schemaVersion: 1, ...summary }, null, 2)}\n`);
275
+ io.stdout.write(`Built ${summary.component}\n`);
276
+ return summary;
277
+ }
278
+ /**
279
+ * Stable logical version for deployment. ComponentizeJS snapshots can contain
280
+ * nondeterministic engine bytes, so the rollout key is the canonical bundle,
281
+ * WIT lock, OCI configuration, pinned build profile, and (when composed) the
282
+ * pinned SQLite provider artifact — not the final componentize output bytes.
283
+ */
284
+ export function canonicalBuildDigest(bundledJavaScript, witDirectory, ociConfig, lock, profile = BUILD_PROFILE_NAME, sqliteProvider) {
285
+ const hash = createHash('sha256');
286
+ addDigestEntry(hash, 'profile', `${profile}\n${COMPONENT_MODEL}`);
287
+ addDigestEntry(hash, 'wit-lock', JSON.stringify(lock));
288
+ addDigestEntry(hash, 'bundle', readFileSync(bundledJavaScript));
289
+ addDigestEntry(hash, 'oci-config', readFileSync(ociConfig));
290
+ for (const file of listFiles(witDirectory)) {
291
+ const name = relative(witDirectory, file).split(sep).join('/');
292
+ addDigestEntry(hash, `wit/${name}`, readFileSync(file));
293
+ }
294
+ if (sqliteProvider !== undefined) {
295
+ addDigestEntry(hash, 'sqlite-provider', readFileSync(sqliteProvider));
296
+ }
297
+ return hash.digest('hex');
298
+ }
299
+ function addDigestEntry(hash, name, content) {
300
+ const bytes = typeof content === 'string' ? Buffer.from(content) : content;
301
+ hash.update(`${name.length}:${name}:${bytes.length}:`);
302
+ hash.update(bytes);
303
+ }
304
+ function listFiles(root) {
305
+ const files = [];
306
+ const walk = (directory) => {
307
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
308
+ const path = join(directory, entry.name);
309
+ if (entry.isDirectory())
310
+ walk(path);
311
+ else if (entry.isFile())
312
+ files.push(path);
313
+ }
314
+ };
315
+ walk(root);
316
+ return files.sort();
317
+ }
318
+ export async function runWasmcloudBuild(args, io, deps = DEFAULT_DEPS) {
319
+ if (args.length > 0) {
320
+ invalidUsage(`platform build does not accept arguments: ${args[0]}`, args[0] ?? '');
321
+ }
322
+ const project = loadProject(deps.cwd());
323
+ const summary = await buildComponent(project, io, deps);
324
+ return { data: { ...summary }, text: `Built ${summary.component}` };
325
+ }
@@ -0,0 +1,3 @@
1
+ import type { CommandNode } from '@di-framework/cli-extension';
2
+ import { type WasmcloudDeps } from './deps.js';
3
+ export declare function createWasmcloudCommand(deps?: WasmcloudDeps): CommandNode;