@velarscript/node 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +148 -0
  3. package/dist/compiler.d.ts +12 -0
  4. package/dist/compiler.d.ts.map +1 -0
  5. package/dist/compiler.js +954 -0
  6. package/dist/compiler.js.map +1 -0
  7. package/dist/environment-runtime.d.ts +2 -0
  8. package/dist/environment-runtime.d.ts.map +1 -0
  9. package/dist/environment-runtime.js +53 -0
  10. package/dist/environment-runtime.js.map +1 -0
  11. package/dist/filesystem-runtime.d.ts +2 -0
  12. package/dist/filesystem-runtime.d.ts.map +1 -0
  13. package/dist/filesystem-runtime.js +329 -0
  14. package/dist/filesystem-runtime.js.map +1 -0
  15. package/dist/host-runtime.d.ts +2 -0
  16. package/dist/host-runtime.d.ts.map +1 -0
  17. package/dist/host-runtime.js +149 -0
  18. package/dist/host-runtime.js.map +1 -0
  19. package/dist/http-runtime.d.ts +2 -0
  20. package/dist/http-runtime.d.ts.map +1 -0
  21. package/dist/http-runtime.js +612 -0
  22. package/dist/http-runtime.js.map +1 -0
  23. package/dist/index.d.ts +9 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +18 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/node-host-runtime.d.ts +2 -0
  28. package/dist/node-host-runtime.d.ts.map +1 -0
  29. package/dist/node-host-runtime.js +314 -0
  30. package/dist/node-host-runtime.js.map +1 -0
  31. package/dist/node-host-worker-runtime.d.ts +2 -0
  32. package/dist/node-host-worker-runtime.d.ts.map +1 -0
  33. package/dist/node-host-worker-runtime.js +1144 -0
  34. package/dist/node-host-worker-runtime.js.map +1 -0
  35. package/dist/process-runtime.d.ts +2 -0
  36. package/dist/process-runtime.d.ts.map +1 -0
  37. package/dist/process-runtime.js +167 -0
  38. package/dist/process-runtime.js.map +1 -0
  39. package/dist/process-worker-runtime.d.ts +2 -0
  40. package/dist/process-worker-runtime.d.ts.map +1 -0
  41. package/dist/process-worker-runtime.js +473 -0
  42. package/dist/process-worker-runtime.js.map +1 -0
  43. package/dist/serve-runtime.d.ts +2 -0
  44. package/dist/serve-runtime.d.ts.map +1 -0
  45. package/dist/serve-runtime.js +463 -0
  46. package/dist/serve-runtime.js.map +1 -0
  47. package/dist/sqlite-runtime.d.ts +3 -0
  48. package/dist/sqlite-runtime.d.ts.map +1 -0
  49. package/dist/sqlite-runtime.js +92 -0
  50. package/dist/sqlite-runtime.js.map +1 -0
  51. package/dist/terminal-runtime.d.ts +2 -0
  52. package/dist/terminal-runtime.d.ts.map +1 -0
  53. package/dist/terminal-runtime.js +290 -0
  54. package/dist/terminal-runtime.js.map +1 -0
  55. package/dist/terminal-worker-runtime.d.ts +2 -0
  56. package/dist/terminal-worker-runtime.d.ts.map +1 -0
  57. package/dist/terminal-worker-runtime.js +311 -0
  58. package/dist/terminal-worker-runtime.js.map +1 -0
  59. package/dist/websocket-runtime.d.ts +2 -0
  60. package/dist/websocket-runtime.d.ts.map +1 -0
  61. package/dist/websocket-runtime.js +46 -0
  62. package/dist/websocket-runtime.js.map +1 -0
  63. package/dist/worker-runtime.d.ts +2 -0
  64. package/dist/worker-runtime.d.ts.map +1 -0
  65. package/dist/worker-runtime.js +160 -0
  66. package/dist/worker-runtime.js.map +1 -0
  67. package/package.json +41 -0
@@ -0,0 +1,954 @@
1
+ import { optionalOf as optional } from "@velarscript/compiler";
2
+ import { VELAR_ERROR_NORMALIZATION_MODULE, VELAR_STRICT_JSON_RUNTIME, VELAR_TYPE_REGISTRY_RUNTIME, VELAR_UTF8_RUNTIME } from "@velarscript/compiler/extension";
3
+ import { VELAR_NODE_ENV_RUNTIME } from "./environment-runtime.js";
4
+ import { VELAR_NODE_FILESYSTEM_RUNTIME } from "./filesystem-runtime.js";
5
+ import { VELAR_NODE_HTTP_RUNTIME } from "./http-runtime.js";
6
+ import { VELAR_NODE_HOST_RUNTIME } from "./host-runtime.js";
7
+ import { VELAR_NODE_HOST_RUNTIME as VELAR_SHARED_NODE_HOST_RUNTIME } from "./node-host-runtime.js";
8
+ import { VELAR_NODE_HOST_WORKER_SOURCE } from "./node-host-worker-runtime.js";
9
+ import { VELAR_PROCESS_HOST_RUNTIME } from "./process-runtime.js";
10
+ import { VELAR_NODE_PROCESS_WORKER_SOURCE } from "./process-worker-runtime.js";
11
+ import { VELAR_NODE_SERVE_RUNTIME } from "./serve-runtime.js";
12
+ import { VELAR_NODE_TERMINAL_RUNTIME } from "./terminal-runtime.js";
13
+ import { VELAR_NODE_TERMINAL_WORKER_SOURCE } from "./terminal-worker-runtime.js";
14
+ import { VELAR_NODE_WORKER_RUNTIME } from "./worker-runtime.js";
15
+ import { VELAR_NODE_WEBSOCKET_RUNTIME } from "./websocket-runtime.js";
16
+ import { VELAR_NODE_SQLITE_RUNTIME, VELAR_NODE_SQLITE_WORKER_SOURCE } from "./sqlite-runtime.js";
17
+ export { VELAR_PROCESS_HOST_RUNTIME } from "./process-runtime.js";
18
+ export const VELAR_NODE_API_VERSION = "0.10";
19
+ export const VELAR_NODE_HOST_MODULE = "velar/node-host-v1";
20
+ const anyType = { kind: "any" };
21
+ const unknownType = { kind: "unknown" };
22
+ const nullType = { kind: "null" };
23
+ const stringType = { kind: "string" };
24
+ const numberType = { kind: "number" };
25
+ const boolType = { kind: "bool" };
26
+ const bytesType = { kind: "named", name: "Bytes", identity: "velar/binary#type:Bytes" };
27
+ const listStringType = { kind: "list", element: stringType };
28
+ const listUnknownType = { kind: "list", element: unknownType };
29
+ const stringMapType = { kind: "map", key: stringType, value: stringType };
30
+ function promise(value) {
31
+ return { kind: "promise", value };
32
+ }
33
+ function functionType(parameterNames, parameters, result, requiredParameters = parameters.length) {
34
+ return { kind: "function", parameterNames, parameters, requiredParameters, result };
35
+ }
36
+ function namedIntrinsic(name, parameterNames, parameters, result, requiredParameters = parameters.length) {
37
+ return { kind: "intrinsic", name, parameterNames, parameters, requiredParameters, result };
38
+ }
39
+ /** A structurally declared standard capability handle; see ValueType.capabilityHandle. */
40
+ function capabilityHandle(fields) {
41
+ return { kind: "object", fields: new Map(Object.entries(fields)), capabilityHandle: true };
42
+ }
43
+ function object(fields, optionalFields = []) {
44
+ return {
45
+ kind: "object",
46
+ fields: new Map(Object.entries(fields)),
47
+ ...(optionalFields.length > 0 ? { optionalFields: new Set(optionalFields) } : {}),
48
+ };
49
+ }
50
+ function moduleInterface(exports, namedTypes = new Map(), namedTypeIdentities = new Map(), typeAliases = new Map(), classes = new Map(), enums = new Map()) {
51
+ return {
52
+ exports,
53
+ mutableExports: new Set(),
54
+ reactiveExports: new Map(),
55
+ reExports: new Map(),
56
+ namedTypes,
57
+ namedTypeIdentities,
58
+ typeAliases,
59
+ enums,
60
+ classes,
61
+ tests: [],
62
+ extensionExports: new Map(),
63
+ extensionData: new Map(),
64
+ };
65
+ }
66
+ const serveRequestType = { kind: "named", name: "ServeRequest", identity: "velar/serve#type:ServeRequest" };
67
+ const serverType = { kind: "named", name: "Server", identity: "velar/serve#type:Server" };
68
+ const requestBodyTooLargeErrorIdentity = "velar/serve#class:RequestBodyTooLargeError";
69
+ const requestBodyTooLargeErrorClass = {
70
+ identity: requestBodyTooLargeErrorIdentity,
71
+ parameters: [],
72
+ requiredParameters: 0,
73
+ base: "Error",
74
+ abstract: true,
75
+ fields: new Map([["maxBytes", { mutable: false, type: numberType }]]),
76
+ getters: new Set(),
77
+ abstractGetters: new Set(),
78
+ methods: new Map(),
79
+ abstractMethods: new Set(),
80
+ staticFields: new Map(),
81
+ staticGetters: new Set(),
82
+ staticMethods: new Map(),
83
+ };
84
+ const writeChunkType = functionType(["chunk"], [stringType], promise(nullType));
85
+ const streamProducerType = functionType(["write"], [writeChunkType], promise(nullType));
86
+ const responseHeadersType = stringMapType;
87
+ const jsonResponseType = object({ status: numberType, json: anyType, headers: responseHeadersType }, ["headers"]);
88
+ const textResponseType = object({ status: numberType, text: stringType, contentType: stringType, headers: responseHeadersType }, ["contentType", "headers"]);
89
+ const streamResponseType = object({ status: numberType, stream: streamProducerType, headers: responseHeadersType }, ["headers"]);
90
+ const serveResponseAlias = { kind: "union", members: [jsonResponseType, textResponseType, streamResponseType] };
91
+ const handlerType = functionType(["request"], [serveRequestType], promise(serveResponseAlias));
92
+ const fileInfoType = object({
93
+ name: stringType,
94
+ kind: stringType,
95
+ size: numberType,
96
+ modifiedAt: numberType,
97
+ });
98
+ const fileWatchBatchType = object({
99
+ paths: listStringType,
100
+ rescan: boolType,
101
+ });
102
+ const fileWatcherType = { kind: "named", name: "FileWatcher", identity: "velar/fs#type:FileWatcher" };
103
+ const processResultType = object({
104
+ code: optional(numberType),
105
+ signal: optional(stringType),
106
+ stdout: stringType,
107
+ stderr: stringType,
108
+ });
109
+ const processOutputChannelIdentity = "velar/process#enum:ProcessOutputChannel";
110
+ const processOutputChannelMembers = new Set(["stdout", "stderr"]);
111
+ const processOutputChannelType = { kind: "enum", name: "ProcessOutputChannel", identity: processOutputChannelIdentity };
112
+ const processOutputType = object({
113
+ channel: processOutputChannelType,
114
+ text: stringType,
115
+ });
116
+ const processOptionsType = object({
117
+ cwd: optional(stringType),
118
+ env: optional(stringMapType),
119
+ stdin: optional(stringType),
120
+ timeout: optional(numberType),
121
+ maxOutputBytes: optional(numberType),
122
+ }, ["cwd", "env", "stdin", "timeout", "maxOutputBytes"]);
123
+ const processType = { kind: "named", name: "Process", identity: "velar/process#type:Process" };
124
+ const httpChunkConsumerType = functionType(["chunk"], [stringType], promise(nullType));
125
+ const httpSecretHeaderType = object({
126
+ name: stringType,
127
+ environment: stringType,
128
+ prefix: stringType,
129
+ });
130
+ const httpSecretHeadersType = { kind: "list", element: httpSecretHeaderType };
131
+ const nodeHttpResponseType = object({
132
+ ok: boolType,
133
+ status: numberType,
134
+ statusText: stringType,
135
+ url: stringType,
136
+ headers: stringMapType,
137
+ json: functionType([], [], promise(unknownType)),
138
+ text: functionType([], [], promise(stringType)),
139
+ bytes: functionType([], [], promise(bytesType)),
140
+ streamText: functionType(["consume"], [httpChunkConsumerType], promise(nullType)),
141
+ parse: namedIntrinsic("runtime.parseAsync", ["target"], [anyType], promise(anyType)),
142
+ });
143
+ const nodeHttpRequestType = object({
144
+ response: functionType([], [], promise(nodeHttpResponseType)),
145
+ json: functionType([], [], promise(unknownType)),
146
+ text: functionType([], [], promise(stringType)),
147
+ bytes: functionType([], [], promise(bytesType)),
148
+ streamText: functionType(["consume"], [httpChunkConsumerType], promise(nullType)),
149
+ parse: namedIntrinsic("runtime.parseAsync", ["target"], [anyType], promise(anyType)),
150
+ cancel: functionType([], [], nullType),
151
+ });
152
+ const nodeHttpOptionsType = object({
153
+ headers: optional(stringMapType),
154
+ secretHeaders: optional(httpSecretHeadersType),
155
+ body: optional(unknownType),
156
+ timeout: optional(numberType),
157
+ maxBytes: optional(numberType),
158
+ }, ["headers", "secretHeaders", "body", "timeout", "maxBytes"]);
159
+ // D51 (audit 12): the terminal is a standard capability handle that publishes
160
+ // `close()`, so `using` supplies its release contract (charter section 16). The
161
+ // marker is set by this target, never inferred from the shape.
162
+ const terminalType = capabilityHandle({
163
+ args: functionType([], [], listStringType),
164
+ isInteractive: functionType([], [], boolType),
165
+ readLine: functionType(["prompt"], [stringType], promise(optional(stringType)), 0),
166
+ write: functionType(["text"], [stringType], promise(nullType)),
167
+ writeError: functionType(["text"], [stringType], promise(nullType)),
168
+ close: functionType([], [], nullType),
169
+ });
170
+ const nodeHttpType = object({
171
+ request: functionType(["method", "url", "options"], [stringType, stringType, nodeHttpOptionsType], nodeHttpRequestType, 2),
172
+ get: functionType(["url", "options"], [stringType, nodeHttpOptionsType], nodeHttpRequestType, 1),
173
+ post: functionType(["url", "options"], [stringType, nodeHttpOptionsType], nodeHttpRequestType, 1),
174
+ put: functionType(["url", "options"], [stringType, nodeHttpOptionsType], nodeHttpRequestType, 1),
175
+ patch: functionType(["url", "options"], [stringType, nodeHttpOptionsType], nodeHttpRequestType, 1),
176
+ delete: functionType(["url", "options"], [stringType, nodeHttpOptionsType], nodeHttpRequestType, 1),
177
+ head: functionType(["url", "options"], [stringType, nodeHttpOptionsType], nodeHttpRequestType, 1),
178
+ });
179
+ const sqliteDatabaseIdentity = "velar/sqlite#type:Database";
180
+ const sqliteStatementIdentity = "velar/sqlite#type:Statement";
181
+ const sqliteTransactionIdentity = "velar/sqlite#type:Transaction";
182
+ const sqliteErrorIdentity = "velar/sqlite#class:SqliteError";
183
+ const sqliteBackpressureErrorIdentity = "velar/sqlite#class:SqliteBackpressureError";
184
+ const sqliteDatabaseType = { kind: "named", name: "Database", identity: sqliteDatabaseIdentity };
185
+ const sqliteStatementType = { kind: "named", name: "Statement", identity: sqliteStatementIdentity };
186
+ const sqliteTransactionType = { kind: "named", name: "Transaction", identity: sqliteTransactionIdentity };
187
+ const sqliteRowType = { kind: "parameter", name: "Row", index: 0 };
188
+ const sqliteRead = (name, withSql) => ({
189
+ kind: "function", typeParameterNames: ["Row"], parameterNames: withSql ? ["sql", "params", "RowType"] : ["params", "RowType"],
190
+ parameters: [
191
+ ...(withSql ? [stringType] : []), listUnknownType, { kind: "runtimeType", value: sqliteRowType },
192
+ ],
193
+ requiredParameters: withSql ? 3 : 2,
194
+ result: promise(name === "one" ? optional(sqliteRowType) : { kind: "list", element: sqliteRowType }),
195
+ });
196
+ const sqliteDatabaseFields = new Map([
197
+ ["execute", functionType(["sql", "params"], [stringType, listUnknownType], promise(numberType), 1)],
198
+ ["one", sqliteRead("one", true)], ["all", sqliteRead("all", true)],
199
+ ["prepare", functionType(["sql"], [stringType], promise(sqliteStatementType))],
200
+ ["transaction", functionType([], [], promise(sqliteTransactionType))],
201
+ ["close", functionType([], [], promise(nullType))],
202
+ ]);
203
+ const sqliteStatementFields = new Map([
204
+ ["execute", functionType(["params"], [listUnknownType], promise(numberType), 0)],
205
+ ["one", sqliteRead("one", false)], ["all", sqliteRead("all", false)],
206
+ ["close", functionType([], [], promise(nullType))],
207
+ ]);
208
+ const sqliteTransactionFields = new Map([
209
+ ["execute", functionType(["sql", "params"], [stringType, listUnknownType], promise(numberType), 1)],
210
+ ["one", sqliteRead("one", true)], ["all", sqliteRead("all", true)],
211
+ ["prepare", functionType(["sql"], [stringType], promise(sqliteStatementType))],
212
+ ["commit", functionType([], [], promise(nullType))], ["rollback", functionType([], [], promise(nullType))],
213
+ ["close", functionType([], [], promise(nullType))],
214
+ ]);
215
+ const sqliteOptionsType = object({
216
+ busyTimeout: optional(numberType), queueCapacity: optional(numberType), maxRows: optional(numberType), maxResultBytes: optional(numberType),
217
+ });
218
+ const sqliteErrorClass = {
219
+ identity: sqliteErrorIdentity,
220
+ parameters: [stringType, optional(stringType)], parameterNames: ["message", "code"], requiredParameters: 0,
221
+ base: "Error", abstract: false,
222
+ fields: new Map([["code", { mutable: false, type: optional(stringType) }]]),
223
+ getters: new Set(), abstractGetters: new Set(), methods: new Map(), abstractMethods: new Set(),
224
+ staticFields: new Map(), staticGetters: new Set(), staticMethods: new Map(),
225
+ };
226
+ const sqliteBackpressureErrorClass = {
227
+ identity: sqliteBackpressureErrorIdentity,
228
+ parameters: [stringType], parameterNames: ["message"], requiredParameters: 0,
229
+ base: "Error", abstract: false, fields: new Map(),
230
+ getters: new Set(), abstractGetters: new Set(), methods: new Map(), abstractMethods: new Set(),
231
+ staticFields: new Map(), staticGetters: new Set(), staticMethods: new Map(),
232
+ };
233
+ const httpTransportPhaseIdentity = "velar/http#enum:HttpTransportPhase";
234
+ const httpTransportPhaseMembers = new Set(["request", "response"]);
235
+ const httpTransportPhaseType = { kind: "enum", name: "HttpTransportPhase", identity: httpTransportPhaseIdentity };
236
+ const httpAbortErrorIdentity = "velar/http#class:HttpAbortError";
237
+ const httpErrorIdentity = "velar/http#class:HttpError";
238
+ const httpTransportErrorIdentity = "velar/http#class:HttpTransportError";
239
+ const httpAbortErrorClass = {
240
+ identity: httpAbortErrorIdentity,
241
+ parameters: [stringType], parameterNames: ["reason"], requiredParameters: 1,
242
+ base: "Error", abstract: false,
243
+ fields: new Map([["reason", { mutable: false, type: stringType }]]),
244
+ getters: new Set(), abstractGetters: new Set(), methods: new Map(), abstractMethods: new Set(),
245
+ staticFields: new Map(), staticGetters: new Set(), staticMethods: new Map(),
246
+ };
247
+ const httpErrorClass = {
248
+ identity: httpErrorIdentity,
249
+ parameters: [stringType, numberType, stringType, unknownType], parameterNames: ["message", "status", "url", "body"], requiredParameters: 3,
250
+ base: "Error", abstract: false,
251
+ fields: new Map([
252
+ ["status", { mutable: false, type: numberType }],
253
+ ["url", { mutable: false, type: stringType }],
254
+ ["body", { mutable: false, type: unknownType }],
255
+ ]),
256
+ getters: new Set(), abstractGetters: new Set(), methods: new Map(), abstractMethods: new Set(),
257
+ staticFields: new Map(), staticGetters: new Set(), staticMethods: new Map(),
258
+ };
259
+ const httpTransportErrorClass = {
260
+ identity: httpTransportErrorIdentity,
261
+ parameters: [stringType, httpTransportPhaseType], parameterNames: ["message", "phase"], requiredParameters: 2,
262
+ base: "Error", abstract: false,
263
+ fields: new Map([["phase", { mutable: false, type: httpTransportPhaseType }]]),
264
+ getters: new Set(), abstractGetters: new Set(), methods: new Map(), abstractMethods: new Set(),
265
+ staticFields: new Map(), staticGetters: new Set(), staticMethods: new Map(),
266
+ };
267
+ export const nodeModuleInterfaces = new Map([
268
+ ["velar/sqlite", moduleInterface(new Map([
269
+ ["Database", { kind: "typeObject", name: "Database", value: sqliteDatabaseType }],
270
+ ["Statement", { kind: "typeObject", name: "Statement", value: sqliteStatementType }],
271
+ ["Transaction", { kind: "typeObject", name: "Transaction", value: sqliteTransactionType }],
272
+ ["SqliteError", { kind: "classConstructor", name: "SqliteError", identity: sqliteErrorIdentity }],
273
+ ["SqliteBackpressureError", { kind: "classConstructor", name: "SqliteBackpressureError", identity: sqliteBackpressureErrorIdentity }],
274
+ ["open", functionType(["path", "options"], [stringType, sqliteOptionsType], promise(sqliteDatabaseType), 1)],
275
+ ]), new Map([
276
+ ["Database", sqliteDatabaseFields], ["Statement", sqliteStatementFields], ["Transaction", sqliteTransactionFields],
277
+ ]), new Map([
278
+ ["Database", sqliteDatabaseIdentity], ["Statement", sqliteStatementIdentity], ["Transaction", sqliteTransactionIdentity],
279
+ ]), new Map(), new Map([["SqliteError", sqliteErrorClass], ["SqliteBackpressureError", sqliteBackpressureErrorClass]]))],
280
+ ["velar/serve", moduleInterface(new Map([
281
+ ["ServeRequest", { kind: "typeObject", name: "ServeRequest" }],
282
+ ["ServeResponse", { kind: "typeObject", name: "ServeResponse" }],
283
+ ["Server", { kind: "typeObject", name: "Server" }],
284
+ ["RequestBodyTooLargeError", { kind: "classConstructor", name: "RequestBodyTooLargeError", identity: requestBodyTooLargeErrorIdentity }],
285
+ ["serve", functionType(["handler", "port", "host"], [handlerType, numberType, stringType], promise(serverType), 2)],
286
+ ["fileResponse", functionType(["root", "path", "fallback"], [stringType, stringType, optional(stringType)], serveResponseAlias, 2)],
287
+ ]), new Map([
288
+ ["ServeRequest", new Map([
289
+ ["method", stringType],
290
+ ["path", stringType],
291
+ ["query", stringMapType],
292
+ ["headers", stringMapType],
293
+ ["text", functionType(["maxBytes"], [numberType], promise(stringType), 0)],
294
+ ["json", functionType(["maxBytes"], [numberType], promise(unknownType), 0)],
295
+ ["parse", namedIntrinsic("runtime.parseAsync", ["target", "maxBytes"], [anyType, numberType], promise(anyType), 1)],
296
+ ])],
297
+ ["Server", new Map([
298
+ ["port", numberType],
299
+ ["stop", functionType([], [], promise(nullType))],
300
+ ])],
301
+ ]), new Map([
302
+ ["ServeRequest", "velar/serve#type:ServeRequest"],
303
+ ["Server", "velar/serve#type:Server"],
304
+ ]), new Map([["ServeResponse", serveResponseAlias]]), new Map([["RequestBodyTooLargeError", requestBodyTooLargeErrorClass]]))],
305
+ ["velar/fs", moduleInterface(new Map([
306
+ ["FileWatchBatch", { kind: "typeObject", name: "FileWatchBatch" }],
307
+ ["FileWatcher", { kind: "typeObject", name: "FileWatcher" }],
308
+ ["readText", functionType(["path", "maxBytes"], [stringType, numberType], promise(stringType), 1)],
309
+ ["readBytes", functionType(["path", "maxBytes"], [stringType, numberType], promise(bytesType), 1)],
310
+ ["createText", functionType(["path", "text"], [stringType, stringType], promise(nullType))],
311
+ ["createBytes", functionType(["path", "bytes"], [stringType, bytesType], promise(nullType))],
312
+ ["replaceTextIfMatches", functionType(["path", "expected", "replacement"], [stringType, stringType, stringType], promise(boolType))],
313
+ ["writeText", functionType(["path", "text"], [stringType, stringType], promise(nullType))],
314
+ ["writeBytes", functionType(["path", "bytes"], [stringType, bytesType], promise(nullType))],
315
+ ["appendText", functionType(["path", "text"], [stringType, stringType], promise(nullType))],
316
+ ["exists", functionType(["path"], [stringType], promise(boolType))],
317
+ ["list", functionType(["path", "maxItems"], [stringType, numberType], promise(listStringType), 1)],
318
+ ["info", functionType(["path"], [stringType], promise(optional(fileInfoType)))],
319
+ ["canonical", functionType(["path"], [stringType], promise(stringType))],
320
+ ["makeDirectory", functionType(["path"], [stringType], promise(nullType))],
321
+ ["copyFile", functionType(["source", "target", "replace"], [stringType, stringType, boolType], promise(nullType), 2)],
322
+ ["move", functionType(["source", "target", "replace"], [stringType, stringType, boolType], promise(nullType), 2)],
323
+ ["removeFile", functionType(["path"], [stringType], promise(nullType))],
324
+ ["watchFiles", functionType(["path", "recursive"], [stringType, boolType], promise(fileWatcherType), 1)],
325
+ ]), new Map([
326
+ ["FileWatcher", new Map([
327
+ ["next", functionType([], [], promise(optional(fileWatchBatchType)))],
328
+ ["close", functionType([], [], promise(nullType))],
329
+ ])],
330
+ ]), new Map([["FileWatcher", "velar/fs#type:FileWatcher"]]), new Map([["FileWatchBatch", fileWatchBatchType]]))],
331
+ ["velar/env", moduleInterface(new Map([
332
+ ["get", functionType(["name"], [stringType], optional(stringType))],
333
+ ["require", functionType(["name"], [stringType], stringType)],
334
+ ]))],
335
+ ["velar/host", moduleInterface(new Map([
336
+ ["exit", functionType(["code"], [numberType], nullType, 0)],
337
+ ["onShutdown", functionType(["cleanup"], [functionType([], [], promise(nullType))], nullType)],
338
+ ]))],
339
+ ["velar/terminal", moduleInterface(new Map([
340
+ ["terminal", terminalType],
341
+ ]))],
342
+ ["velar/path", moduleInterface(new Map([
343
+ ["resolve", functionType(["parts"], [listStringType], stringType, 0)],
344
+ ["join", functionType(["parts"], [listStringType], stringType, 0)],
345
+ ["normalize", functionType(["path"], [stringType], stringType)],
346
+ ["relative", functionType(["from", "to"], [stringType, stringType], stringType)],
347
+ ["dirname", functionType(["path"], [stringType], stringType)],
348
+ ["basename", functionType(["path"], [stringType], stringType)],
349
+ ["extension", functionType(["path"], [stringType], stringType)],
350
+ ["isAbsolute", functionType(["path"], [stringType], boolType)],
351
+ ["contains", functionType(["root", "target"], [stringType, stringType], boolType)],
352
+ ["toFileUrl", functionType(["path"], [stringType], stringType)],
353
+ ["fromFileUrl", functionType(["url"], [stringType], stringType)],
354
+ ]))],
355
+ ["velar/process", moduleInterface(new Map([
356
+ ["Process", { kind: "typeObject", name: "Process" }],
357
+ ["ProcessOutputChannel", { kind: "enumObject", name: "ProcessOutputChannel", identity: processOutputChannelIdentity, members: processOutputChannelMembers }],
358
+ ["start", functionType(["command", "args", "options"], [stringType, listStringType, processOptionsType], promise(processType), 1)],
359
+ ["run", functionType(["command", "args", "options"], [stringType, listStringType, processOptionsType], promise(processResultType), 1)],
360
+ ]), new Map([
361
+ ["Process", new Map([
362
+ ["pid", numberType],
363
+ ["next", functionType([], [], promise(optional(processOutputType)))],
364
+ ["wait", functionType([], [], promise(processResultType))],
365
+ ["stop", functionType([], [], promise(nullType))],
366
+ ])],
367
+ ]), new Map([["Process", "velar/process#type:Process"]]), new Map(), new Map(), new Map([["ProcessOutputChannel", { identity: processOutputChannelIdentity, members: processOutputChannelMembers }]]))],
368
+ ["velar/http", moduleInterface(new Map([
369
+ ["http", nodeHttpType],
370
+ ["secretHeader", functionType(["name", "environment", "prefix"], [stringType, stringType, stringType], httpSecretHeaderType, 2)],
371
+ ["HttpTransportPhase", { kind: "enumObject", name: "HttpTransportPhase", identity: httpTransportPhaseIdentity, members: httpTransportPhaseMembers }],
372
+ ["HttpAbortError", { kind: "classConstructor", name: "HttpAbortError", identity: httpAbortErrorIdentity }],
373
+ ["HttpError", { kind: "classConstructor", name: "HttpError", identity: httpErrorIdentity }],
374
+ ["HttpTransportError", { kind: "classConstructor", name: "HttpTransportError", identity: httpTransportErrorIdentity }],
375
+ ]), new Map(), new Map(), new Map(), new Map([
376
+ ["HttpAbortError", httpAbortErrorClass],
377
+ ["HttpError", httpErrorClass],
378
+ ["HttpTransportError", httpTransportErrorClass],
379
+ ]), new Map([["HttpTransportPhase", { identity: httpTransportPhaseIdentity, members: httpTransportPhaseMembers }]]))],
380
+ ]);
381
+ export const nodeModuleSources = new Map([
382
+ ["velar/sqlite", VELAR_NODE_SQLITE_RUNTIME.replace("WORKER_SOURCE", JSON.stringify(VELAR_NODE_SQLITE_WORKER_SOURCE))],
383
+ ["velar/websocket", VELAR_NODE_WEBSOCKET_RUNTIME],
384
+ ["velar/worker", VELAR_NODE_WORKER_RUNTIME],
385
+ [VELAR_NODE_HOST_MODULE, VELAR_SHARED_NODE_HOST_RUNTIME.replace("WORKER_SOURCE", JSON.stringify(VELAR_NODE_HOST_WORKER_SOURCE))],
386
+ ["velar/fs", String.raw `
387
+ ${VELAR_UTF8_RUNTIME}
388
+ ${VELAR_NODE_FILESYSTEM_RUNTIME}
389
+ `.trimStart()],
390
+ ["velar/path", String.raw `
391
+ import { basename as nodeBasename, dirname as nodeDirname, extname, isAbsolute as nodeIsAbsolute, join as nodeJoin, normalize as nodeNormalize, relative as nodeRelative, resolve as nodeResolve } from "node:path";
392
+ import { fileURLToPath, pathToFileURL } from "node:url";
393
+
394
+ const maxPathCodeUnits = 4096;
395
+ const pathApply = Reflect.apply;
396
+ const pathArrayIsArray = Array.isArray;
397
+ const pathGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
398
+ const pathStringIncludes = String.prototype.includes;
399
+ const pathStringStartsWith = String.prototype.startsWith;
400
+ const pathSeparator = process.platform === "win32" ? "\\" : "/";
401
+ function stringIncludes(value, search) { return pathApply(pathStringIncludes, value, [search]); }
402
+ function stringStartsWith(value, search) { return pathApply(pathStringStartsWith, value, [search]); }
403
+ function pathValue(value, operation) {
404
+ if (typeof value !== "string" || value.length === 0) throw new TypeError(operation + " requires a non-empty path string");
405
+ if (value.length > maxPathCodeUnits || stringIncludes(value, "\0")) throw new RangeError(operation + " path is outside the supported bounds");
406
+ return value;
407
+ }
408
+ function pathParts(values, operation) {
409
+ if (!pathArrayIsArray(values) || values.length > 256) throw new TypeError(operation + " requires a bounded List<string>");
410
+ const output = [];
411
+ for (let index = 0; index < values.length; index += 1) {
412
+ const descriptor = pathGetOwnPropertyDescriptor(values, index);
413
+ if (!descriptor?.enumerable || !("value" in descriptor)) throw new TypeError(operation + " path parts must contain enumerable data values");
414
+ output[output.length] = pathValue(descriptor.value, operation);
415
+ }
416
+ return output;
417
+ }
418
+ function bounded(value, operation) {
419
+ if (value.length > maxPathCodeUnits) throw new RangeError(operation + " result is outside the supported bounds");
420
+ return value;
421
+ }
422
+
423
+ export function resolve(parts = []) { return bounded(pathApply(nodeResolve, undefined, pathParts(parts, "resolve")), "resolve"); }
424
+ export function join(parts = []) { return bounded(pathApply(nodeJoin, undefined, pathParts(parts, "join")), "join"); }
425
+ export function normalize(path) { return bounded(nodeNormalize(pathValue(path, "normalize")), "normalize"); }
426
+ export function relative(from, to) { return bounded(nodeRelative(pathValue(from, "relative"), pathValue(to, "relative")), "relative"); }
427
+ export function dirname(path) { return bounded(nodeDirname(pathValue(path, "dirname")), "dirname"); }
428
+ export function basename(path) { return nodeBasename(pathValue(path, "basename")); }
429
+ export function extension(path) { return extname(pathValue(path, "extension")); }
430
+ export function isAbsolute(path) { return nodeIsAbsolute(pathValue(path, "isAbsolute")); }
431
+ export function contains(root, target) {
432
+ root = nodeResolve(pathValue(root, "contains"));
433
+ target = nodeResolve(pathValue(target, "contains"));
434
+ const path = nodeRelative(root, target);
435
+ return path === "" || (path !== ".." && !stringStartsWith(path, ".." + pathSeparator) && !nodeIsAbsolute(path));
436
+ }
437
+ export function toFileUrl(path) { return pathToFileURL(nodeResolve(pathValue(path, "toFileUrl"))).href; }
438
+ export function fromFileUrl(url) {
439
+ url = pathValue(url, "fromFileUrl");
440
+ if (!stringStartsWith(url, "file:")) throw new TypeError("fromFileUrl requires a file URL");
441
+ return bounded(fileURLToPath(url), "fromFileUrl");
442
+ }
443
+ `.trimStart()],
444
+ ["velar/process", String.raw `
445
+ import { EventEmitter } from "node:events";
446
+ import { MessageChannel, MessagePort, Worker } from "node:worker_threads";
447
+ ${VELAR_TYPE_REGISTRY_RUNTIME}
448
+ ${VELAR_UTF8_RUNTIME}
449
+ ${VELAR_PROCESS_HOST_RUNTIME}
450
+
451
+ const maxTextBytes = 16 * 1024 * 1024;
452
+ const safeEnvironmentNames = ["HOME", "LANG", "LC_ALL", "PATH", "SHELL", "TERM", "TMPDIR", "USER", "SystemRoot", "WINDIR"];
453
+ const processOptionFields = new __velarProcessNativeSet(["cwd", "env", "stdin", "timeout", "maxOutputBytes"]);
454
+ const processStartFields = new __velarProcessNativeSet(["handle", "pid"]);
455
+ const processResultFields = new __velarProcessNativeSet(["code", "signal", "stdout", "stderr"]);
456
+ const processOutputFields = new __velarProcessNativeSet(["channel", "text"]);
457
+ const processStopFields = new __velarProcessNativeSet(["result", "error"]);
458
+ const processWaitFields = new __velarProcessNativeSet(["result", "error", "retained"]);
459
+ const processErrorFields = new __velarProcessNativeSet(["name", "message"]);
460
+ const processHostMessageFields = new __velarProcessNativeSet(["kind", "id", "ok", "value", "error", "handle", "pid"]);
461
+ const __velarNodeProcessToken = Symbol("velar.node.process");
462
+ const __velarNodeProcessNativeProcess = process;
463
+ const __velarNodeProcessEnvironment = __velarNodeProcessNativeProcess.env;
464
+ const __velarNodeProcessKill = __velarProcessDataOperation(__velarNodeProcessNativeProcess, "kill");
465
+ const __velarNodeProcessPlatform = __velarNodeProcessNativeProcess.platform;
466
+ export const ProcessOutputChannel = __velarRegisterRuntimeType(__velarProcessFreeze({
467
+ stdout: "stdout",
468
+ stderr: "stderr",
469
+ is(value) { return value === "stdout" || value === "stderr"; },
470
+ parse(value) {
471
+ if (!ProcessOutputChannel.is(value)) throw new __velarProcessNativeTypeError("Value does not match ProcessOutputChannel");
472
+ return value;
473
+ },
474
+ // D60 rule 149: values() is the third name charter section 6 reserves on
475
+ // every enum, and it returns a fresh mutable List in declaration order.
476
+ values() { return ["stdout", "stderr"]; },
477
+ }));
478
+
479
+ function boundedText(value, name, maxCodeUnits = 4096) {
480
+ if (typeof value !== "string" || value.length === 0) throw new __velarProcessNativeTypeError(name + " must be non-empty text");
481
+ if (value.length > maxCodeUnits || __velarProcessIncludes(value, "\0")) throw new __velarProcessNativeRangeError(name + " is outside the supported bounds");
482
+ return value;
483
+ }
484
+ function argumentsOf(value) {
485
+ if (value == null) return [];
486
+ if (!__velarProcessIsArray(value) || value.length > 1000) throw new __velarProcessNativeTypeError("Process args must be a bounded List<string>");
487
+ let units = 0;
488
+ const output = [];
489
+ for (let index = 0; index < value.length; index += 1) {
490
+ const descriptor = __velarProcessOwnDescriptor(value, __velarProcessNativeString(index));
491
+ if (!descriptor?.enumerable || !("value" in descriptor)) throw new __velarProcessNativeTypeError("Process args must contain enumerable data values");
492
+ const item = descriptor.value;
493
+ units += boundedText(item, "Process argument", 1024 * 1024).length;
494
+ if (units > 1024 * 1024) throw new __velarProcessNativeRangeError("Process arguments cannot exceed 1 MiB");
495
+ output[output.length] = item;
496
+ }
497
+ return output;
498
+ }
499
+ function plainRecord(value) {
500
+ return __velarProcessRecord(value == null ? {} : value, "Process options", processOptionFields);
501
+ }
502
+ function environmentValue(name) {
503
+ const descriptor = __velarProcessOwnDescriptor(__velarNodeProcessEnvironment, name);
504
+ return descriptor && "value" in descriptor && typeof descriptor.value === "string" ? descriptor.value : null;
505
+ }
506
+ function environmentOf(value) {
507
+ const output = __velarProcessCreate(null);
508
+ for (const name of safeEnvironmentNames) {
509
+ const item = environmentValue(name);
510
+ if (item !== null) output[name] = item;
511
+ }
512
+ if (value == null) return output;
513
+ const snapshot = __velarProcessMapSnapshot(value);
514
+ if (snapshot.size > 1000) throw new __velarProcessNativeRangeError("Process env cannot exceed 1000 entries");
515
+ let units = 0;
516
+ for (let index = 0; index < snapshot.entries.length; index += 1) {
517
+ const name = snapshot.entries[index][0];
518
+ const item = snapshot.entries[index][1];
519
+ if (!__velarProcessEnvironmentName(name) || typeof item !== "string" || __velarProcessIncludes(item, "\0")) throw new __velarProcessNativeTypeError("Process env must contain valid string variables");
520
+ units += name.length + item.length;
521
+ if (units > 1024 * 1024) throw new __velarProcessNativeRangeError("Process env cannot exceed 1 MiB");
522
+ output[name] = item;
523
+ }
524
+ return output;
525
+ }
526
+ function optionsOf(value) {
527
+ value = plainRecord(value);
528
+ const cwd = value.cwd == null ? undefined : boundedText(value.cwd, "Process cwd");
529
+ const stdin = value.stdin ?? "";
530
+ if (typeof stdin !== "string" || __velarUtf8ByteLength(stdin) > maxTextBytes) throw new __velarProcessNativeRangeError("Process stdin cannot exceed 16 MiB");
531
+ const timeout = value.timeout ?? 120000;
532
+ if (!__velarProcessIsSafeInteger(timeout) || timeout < 0 || timeout > 600000) throw new __velarProcessNativeRangeError("Process timeout must be an integer from 0 through 600000 milliseconds");
533
+ const maxOutputBytes = value.maxOutputBytes ?? 4 * 1024 * 1024;
534
+ if (!__velarProcessIsSafeInteger(maxOutputBytes) || maxOutputBytes < 1 || maxOutputBytes > maxTextBytes) throw new __velarProcessNativeRangeError("Process maxOutputBytes must be an integer from 1 through 16777216");
535
+ return { cwd, env: environmentOf(value.env), stdin, timeout, maxOutputBytes };
536
+ }
537
+
538
+ function processErrorOf(value) {
539
+ value = __velarProcessRecord(value, "Node process host error", processErrorFields);
540
+ if (typeof value.name !== "string" || value.name !== "Error" && value.name !== "RangeError" && value.name !== "TypeError"
541
+ || typeof value.message !== "string" || value.message.length === 0 || value.message.length > 65536) {
542
+ throw new __velarProcessNativeTypeError("Node process host returned an invalid error");
543
+ }
544
+ if (value.name === "RangeError") return new __velarProcessNativeRangeError(value.message);
545
+ if (value.name === "TypeError") return new __velarProcessNativeTypeError(value.message);
546
+ return new __velarProcessNativeError(value.message);
547
+ }
548
+ function startValueOf(value) {
549
+ value = __velarProcessRecord(value, "Node process start result", processStartFields);
550
+ if (!__velarProcessIsSafeInteger(value.handle) || value.handle < 1
551
+ || !__velarProcessIsSafeInteger(value.pid) || value.pid < 0) {
552
+ throw new __velarProcessNativeTypeError("Node process host returned an invalid start result");
553
+ }
554
+ return value;
555
+ }
556
+ function resultOf(value, maxOutputBytes) {
557
+ value = __velarProcessRecord(value, "Node process result", processResultFields);
558
+ if ((value.code !== null && !__velarProcessIsSafeInteger(value.code))
559
+ || (value.signal !== null && (typeof value.signal !== "string" || value.signal.length === 0 || value.signal.length > 128))
560
+ || typeof value.stdout !== "string" || typeof value.stderr !== "string") {
561
+ throw new __velarProcessNativeTypeError("Node process host returned an invalid result");
562
+ }
563
+ if (__velarUtf8ByteLength(value.stdout) + __velarUtf8ByteLength(value.stderr) > maxOutputBytes) {
564
+ throw new __velarProcessNativeRangeError("Node process result exceeded maxOutputBytes");
565
+ }
566
+ return __velarProcessFreeze({code: value.code, signal: value.signal, stdout: value.stdout, stderr: value.stderr});
567
+ }
568
+ function outputOf(value, maxOutputBytes) {
569
+ if (value === null) return null;
570
+ value = __velarProcessRecord(value, "Node process output", processOutputFields);
571
+ if (!ProcessOutputChannel.is(value.channel) || typeof value.text !== "string" || value.text.length === 0) {
572
+ throw new __velarProcessNativeTypeError("Node process host returned invalid output");
573
+ }
574
+ const bytes = __velarUtf8ByteLength(value.text);
575
+ if (bytes > maxOutputBytes) throw new __velarProcessNativeRangeError("Node process output exceeded maxOutputBytes");
576
+ return __velarProcessFreeze({channel: value.channel, text: value.text, bytes});
577
+ }
578
+ function stopValueOf(value, maxOutputBytes) {
579
+ value = __velarProcessRecord(value, "Node process stop result", processStopFields);
580
+ if (value.result !== null && value.error !== null) throw new __velarProcessNativeTypeError("Node process stop result is contradictory");
581
+ return {
582
+ result: value.result === null ? null : resultOf(value.result, maxOutputBytes),
583
+ error: value.error === null ? null : processErrorOf(value.error),
584
+ };
585
+ }
586
+ function waitValueOf(value, maxOutputBytes) {
587
+ value = __velarProcessRecord(value, "Node process wait result", processWaitFields);
588
+ if (typeof value.retained !== "boolean"
589
+ || value.result !== null && value.error !== null
590
+ || value.retained && (value.result !== null || value.error === null)
591
+ || !value.retained && value.result === null && value.error === null) {
592
+ throw new __velarProcessNativeTypeError("Node process wait result is invalid or contradictory");
593
+ }
594
+ return {
595
+ result: value.result === null ? null : resultOf(value.result, maxOutputBytes),
596
+ error: value.error === null ? null : processErrorOf(value.error),
597
+ retained: value.retained,
598
+ };
599
+ }
600
+
601
+ const __velarNodeProcessMessagePortPost = __velarProcessDataOperation(MessagePort.prototype, "postMessage");
602
+ const __velarNodeProcessMessagePortStart = __velarProcessDataOperation(MessagePort.prototype, "start");
603
+ const __velarNodeProcessMessagePortRef = __velarProcessDataOperation(MessagePort.prototype, "ref");
604
+ const __velarNodeProcessMessagePortUnref = __velarProcessDataOperation(MessagePort.prototype, "unref");
605
+ const __velarNodeProcessMessagePortClose = __velarProcessDataOperation(MessagePort.prototype, "close");
606
+ const __velarNodeProcessWorkerUnref = __velarProcessDataOperation(Worker.prototype, "unref");
607
+ const __velarNodeProcessEventOn = __velarProcessDataOperation(EventEmitter.prototype, "on");
608
+ const __velarNodeProcessMessageData = __velarProcessOwnDescriptor(globalThis.MessageEvent.prototype, "data")?.get;
609
+ if (typeof __velarNodeProcessMessageData !== "function") throw new __velarProcessNativeError("Node process MessageEvent data operation is unavailable");
610
+ const __velarNodeProcessPending = __velarProcessCreate(null);
611
+ const __velarNodeProcessOwners = __velarProcessCreate(null);
612
+ const __velarNodeProcessUnconfirmedOwners = __velarProcessCreate(null);
613
+ const __velarNodeProcessSettledOwners = __velarProcessCreate(null);
614
+ const __velarNodeProcessMaxPending = 1024;
615
+ let __velarNodeProcessNextRequest = 1;
616
+ let __velarNodeProcessPendingCount = 0;
617
+ let __velarNodeProcessRunningCount = 0;
618
+ let __velarNodeProcessReady = false;
619
+ let __velarNodeProcessFailure = null;
620
+ let __velarNodeProcessReaper = null;
621
+ let __velarNodeProcessReaperAttempts = 0;
622
+ let __velarNodeProcessReadyResolve;
623
+ let __velarNodeProcessReadyReject;
624
+ const __velarNodeProcessReadyPromise = new __velarProcessNativePromise((resolve, reject) => {
625
+ __velarNodeProcessReadyResolve = resolve;
626
+ __velarNodeProcessReadyReject = reject;
627
+ });
628
+ const __velarNodeProcessChannel = new MessageChannel();
629
+ const __velarNodeProcessPort = __velarNodeProcessChannel.port1;
630
+
631
+ function __velarNodeProcessUpdateReference() {
632
+ const operation = __velarNodeProcessPendingCount > 0 || __velarNodeProcessRunningCount > 0
633
+ ? __velarNodeProcessMessagePortRef
634
+ : __velarNodeProcessMessagePortUnref;
635
+ __velarProcessCall(operation, __velarNodeProcessPort, []);
636
+ }
637
+ function __velarNodeProcessSignal(pid, signal) {
638
+ try {
639
+ __velarProcessCall(__velarNodeProcessKill, __velarNodeProcessNativeProcess, [__velarNodeProcessPlatform === "win32" ? pid : -pid, signal]);
640
+ } catch {
641
+ try { __velarProcessCall(__velarNodeProcessKill, __velarNodeProcessNativeProcess, [pid, signal]); }
642
+ catch {}
643
+ }
644
+ }
645
+ function __velarNodeProcessOwnerAlive(pid) {
646
+ try {
647
+ __velarProcessCall(__velarNodeProcessKill, __velarNodeProcessNativeProcess, [__velarNodeProcessPlatform === "win32" ? pid : -pid, 0]);
648
+ return true;
649
+ } catch (error) {
650
+ const code = error && typeof error === "object" ? __velarProcessOwnDescriptor(error, "code") : null;
651
+ return !code || !("value" in code) || code.value !== "ESRCH";
652
+ }
653
+ }
654
+ function __velarNodeProcessReapOwners() {
655
+ __velarNodeProcessReaper = null;
656
+ __velarNodeProcessReaperAttempts += 1;
657
+ const keys = __velarProcessKeys(__velarNodeProcessOwners);
658
+ for (let index = 0; index < keys.length; index += 1) {
659
+ const key = keys[index];
660
+ const descriptor = __velarProcessOwnDescriptor(__velarNodeProcessOwners, key);
661
+ if (!descriptor || !("value" in descriptor)) continue;
662
+ const pid = descriptor.value;
663
+ __velarNodeProcessSignal(pid, "SIGKILL");
664
+ if (!__velarNodeProcessOwnerAlive(pid)) delete __velarNodeProcessOwners[key];
665
+ }
666
+ if (__velarProcessKeys(__velarNodeProcessOwners).length > 0 && __velarNodeProcessReaperAttempts < 100) {
667
+ __velarNodeProcessReaper = __velarProcessCall(__velarProcessSetTimeout, globalThis, [__velarNodeProcessReapOwners, 50]);
668
+ } else if (__velarNodeProcessReaperAttempts >= 100) {
669
+ const abandonedKeys = __velarProcessKeys(__velarNodeProcessOwners);
670
+ for (let index = 0; index < abandonedKeys.length; index += 1) delete __velarNodeProcessOwners[abandonedKeys[index]];
671
+ }
672
+ }
673
+ function __velarNodeProcessBeginReaping() {
674
+ if (__velarNodeProcessReaper === null && __velarProcessKeys(__velarNodeProcessOwners).length > 0) {
675
+ __velarNodeProcessReaperAttempts = 0;
676
+ __velarNodeProcessReapOwners();
677
+ }
678
+ }
679
+ function __velarNodeProcessFail(error) {
680
+ if (__velarNodeProcessFailure) return;
681
+ const failure = error instanceof __velarProcessNativeError ? error : new __velarProcessNativeError("Node process worker failed");
682
+ __velarNodeProcessFailure = failure;
683
+ if (!__velarNodeProcessReady) __velarNodeProcessReadyReject(failure);
684
+ const keys = __velarProcessKeys(__velarNodeProcessPending);
685
+ for (let index = 0; index < keys.length; index += 1) {
686
+ const key = keys[index];
687
+ const descriptor = __velarProcessOwnDescriptor(__velarNodeProcessPending, key);
688
+ if (descriptor && "value" in descriptor) descriptor.value.reject(failure);
689
+ delete __velarNodeProcessPending[key];
690
+ }
691
+ __velarNodeProcessPendingCount = 0;
692
+ __velarNodeProcessRunningCount = 0;
693
+ const settledKeys = __velarProcessKeys(__velarNodeProcessSettledOwners);
694
+ for (let index = 0; index < settledKeys.length; index += 1) delete __velarNodeProcessSettledOwners[settledKeys[index]];
695
+ const unconfirmedKeys = __velarProcessKeys(__velarNodeProcessUnconfirmedOwners);
696
+ for (let index = 0; index < unconfirmedKeys.length; index += 1) delete __velarNodeProcessUnconfirmedOwners[unconfirmedKeys[index]];
697
+ __velarNodeProcessUpdateReference();
698
+ __velarNodeProcessBeginReaping();
699
+ __velarProcessCall(__velarNodeProcessMessagePortClose, __velarNodeProcessPort, []);
700
+ }
701
+ function __velarNodeProcessMessage(value) {
702
+ const message = __velarProcessRecord(value, "Node process host message", processHostMessageFields);
703
+ if (message.kind === "ready") {
704
+ if (__velarNodeProcessReady) throw new __velarProcessNativeError("Node process worker sent duplicate readiness");
705
+ __velarNodeProcessReady = true;
706
+ __velarNodeProcessReadyResolve(null);
707
+ return;
708
+ }
709
+ if (message.kind === "owned") {
710
+ if (!__velarProcessIsSafeInteger(message.handle) || message.handle < 1
711
+ || !__velarProcessIsSafeInteger(message.pid) || message.pid < 1
712
+ || __velarProcessOwnDescriptor(__velarNodeProcessOwners, __velarProcessNativeString(message.handle))
713
+ || __velarProcessOwnDescriptor(__velarNodeProcessSettledOwners, __velarProcessNativeString(message.handle))) {
714
+ throw new __velarProcessNativeTypeError("Node process worker returned an invalid owned handle");
715
+ }
716
+ __velarNodeProcessOwners[message.handle] = message.pid;
717
+ __velarNodeProcessUnconfirmedOwners[message.handle] = true;
718
+ __velarNodeProcessRunningCount += 1;
719
+ __velarNodeProcessUpdateReference();
720
+ return;
721
+ }
722
+ if (message.kind === "settled") {
723
+ const owner = __velarProcessIsSafeInteger(message.handle) && message.handle > 0
724
+ ? __velarProcessOwnDescriptor(__velarNodeProcessOwners, __velarProcessNativeString(message.handle))
725
+ : null;
726
+ if (!owner || !("value" in owner) || __velarNodeProcessRunningCount < 1) {
727
+ throw new __velarProcessNativeTypeError("Node process worker returned an invalid settled handle");
728
+ }
729
+ delete __velarNodeProcessOwners[message.handle];
730
+ if (__velarProcessOwnDescriptor(__velarNodeProcessUnconfirmedOwners, __velarProcessNativeString(message.handle))) {
731
+ __velarNodeProcessSettledOwners[message.handle] = owner.value;
732
+ }
733
+ __velarNodeProcessRunningCount -= 1;
734
+ __velarNodeProcessUpdateReference();
735
+ return;
736
+ }
737
+ if (message.kind !== "response" || !__velarProcessIsSafeInteger(message.id) || message.id < 1 || typeof message.ok !== "boolean") {
738
+ throw new __velarProcessNativeTypeError("Node process worker returned an invalid response");
739
+ }
740
+ const descriptor = __velarProcessOwnDescriptor(__velarNodeProcessPending, __velarProcessNativeString(message.id));
741
+ if (!descriptor || !("value" in descriptor)) throw new __velarProcessNativeError("Node process worker returned an unknown response");
742
+ const pending = descriptor.value;
743
+ let responseValue = message.value;
744
+ let responseError = null;
745
+ if (message.ok) {
746
+ if (pending.operation === "start") {
747
+ const started = startValueOf(message.value);
748
+ const owner = __velarProcessOwnDescriptor(__velarNodeProcessOwners, __velarProcessNativeString(started.handle))
749
+ ?? __velarProcessOwnDescriptor(__velarNodeProcessSettledOwners, __velarProcessNativeString(started.handle));
750
+ if (!owner || !("value" in owner) || owner.value !== started.pid) {
751
+ throw new __velarProcessNativeError("Node process worker resolved start without transferring cleanup ownership");
752
+ }
753
+ delete __velarNodeProcessUnconfirmedOwners[started.handle];
754
+ delete __velarNodeProcessSettledOwners[started.handle];
755
+ responseValue = started;
756
+ }
757
+ } else responseError = processErrorOf(message.error);
758
+ delete __velarNodeProcessPending[message.id];
759
+ __velarNodeProcessPendingCount -= 1;
760
+ __velarNodeProcessUpdateReference();
761
+ if (responseError) pending.reject(responseError);
762
+ else pending.resolve(responseValue);
763
+ }
764
+
765
+ __velarNodeProcessPort.onmessage = event => {
766
+ try {
767
+ __velarNodeProcessMessage(__velarProcessCall(__velarNodeProcessMessageData, event, []));
768
+ } catch (error) { __velarNodeProcessFail(error); }
769
+ };
770
+ __velarNodeProcessPort.onmessageerror = () => __velarNodeProcessFail(new __velarProcessNativeError("Node process worker returned an unreadable message"));
771
+ __velarProcessCall(__velarNodeProcessMessagePortStart, __velarNodeProcessPort, []);
772
+ const __velarNodeProcessWorker = new Worker(${JSON.stringify(VELAR_NODE_PROCESS_WORKER_SOURCE)}, {
773
+ eval: true,
774
+ workerData: __velarNodeProcessChannel.port2,
775
+ transferList: [__velarNodeProcessChannel.port2],
776
+ });
777
+ __velarProcessCall(__velarNodeProcessEventOn, __velarNodeProcessWorker, ["error", () => __velarNodeProcessFail(new __velarProcessNativeError("Node process worker failed"))]);
778
+ __velarProcessCall(__velarNodeProcessEventOn, __velarNodeProcessWorker, ["exit", code => {
779
+ __velarNodeProcessFail(new __velarProcessNativeError("Node process worker exited unexpectedly with code " + code));
780
+ }]);
781
+ const __velarNodeProcessReadyTimer = __velarProcessCall(__velarProcessSetTimeout, globalThis, [
782
+ () => __velarNodeProcessReadyReject(new __velarProcessNativeError("Node process worker did not become ready")),
783
+ 10000,
784
+ ]);
785
+
786
+ try { await __velarNodeProcessReadyPromise; }
787
+ finally { __velarProcessCall(__velarProcessClearTimeout, globalThis, [__velarNodeProcessReadyTimer]); }
788
+ __velarProcessCall(__velarNodeProcessWorkerUnref, __velarNodeProcessWorker, []);
789
+ __velarProcessCall(__velarNodeProcessMessagePortUnref, __velarNodeProcessPort, []);
790
+
791
+ function invoke(operation, args) {
792
+ if (__velarNodeProcessFailure) return __velarProcessReject(__velarNodeProcessFailure);
793
+ if (__velarNodeProcessPendingCount >= __velarNodeProcessMaxPending) {
794
+ return __velarProcessReject(new __velarProcessNativeRangeError("Node process host cannot have more than 1024 pending operations"));
795
+ }
796
+ let attempts = 0;
797
+ while (__velarProcessOwnDescriptor(__velarNodeProcessPending, __velarProcessNativeString(__velarNodeProcessNextRequest))) {
798
+ __velarNodeProcessNextRequest = __velarNodeProcessNextRequest >= __velarProcessNativeNumber.MAX_SAFE_INTEGER ? 1 : __velarNodeProcessNextRequest + 1;
799
+ attempts += 1;
800
+ if (attempts > __velarNodeProcessMaxPending) return __velarProcessReject(new __velarProcessNativeRangeError("Node process request identity space is unavailable"));
801
+ }
802
+ const id = __velarNodeProcessNextRequest;
803
+ __velarNodeProcessNextRequest = id >= __velarProcessNativeNumber.MAX_SAFE_INTEGER ? 1 : id + 1;
804
+ return new __velarProcessNativePromise((resolve, reject) => {
805
+ __velarNodeProcessPending[id] = {operation, resolve, reject};
806
+ __velarNodeProcessPendingCount += 1;
807
+ __velarNodeProcessUpdateReference();
808
+ try {
809
+ __velarProcessCall(__velarNodeProcessMessagePortPost, __velarNodeProcessPort, [{id, operation, args}]);
810
+ } catch (error) {
811
+ delete __velarNodeProcessPending[id];
812
+ __velarNodeProcessPendingCount -= 1;
813
+ __velarNodeProcessUpdateReference();
814
+ reject(error);
815
+ }
816
+ });
817
+ }
818
+
819
+ class ProcessHandle {
820
+ constructor(token, handle, pid, maxOutputBytes) {
821
+ if (token !== __velarNodeProcessToken || !__velarProcessIsSafeInteger(handle) || handle < 1
822
+ || !__velarProcessIsSafeInteger(pid) || pid < 0) {
823
+ throw new __velarProcessNativeTypeError("Process values are created only by velar/process.start");
824
+ }
825
+ this.handle = handle;
826
+ this.pid = pid;
827
+ this.maxOutputBytes = maxOutputBytes;
828
+ this.outputBytes = 0;
829
+ this.outputReading = false;
830
+ this.waitStarted = false;
831
+ this.result = null;
832
+ this.stopping = null;
833
+ this.stopRequested = false;
834
+ this.cleanup = null;
835
+ this.next = async () => {
836
+ if (this.waitStarted) throw new __velarProcessNativeError("Process output must be consumed before wait()");
837
+ if (this.stopRequested) throw new __velarProcessNativeError("Process output is unavailable after stop()");
838
+ if (this.outputReading) throw new __velarProcessNativeError("Process.next() allows only one active pull");
839
+ this.outputReading = true;
840
+ try {
841
+ const output = outputOf(await invoke("read", [this.handle]), this.maxOutputBytes);
842
+ if (output === null) return null;
843
+ this.outputBytes += output.bytes;
844
+ if (this.outputBytes > this.maxOutputBytes) throw new __velarProcessNativeRangeError("Process output exceeded maxOutputBytes");
845
+ return __velarProcessFreeze({channel: output.channel, text: output.text});
846
+ } finally {
847
+ this.outputReading = false;
848
+ }
849
+ };
850
+ __velarProcessSeal(this);
851
+ }
852
+ wait() {
853
+ if (this.outputReading) return __velarProcessReject(new __velarProcessNativeError("Process wait() cannot run while next() is pending"));
854
+ this.waitStarted = true;
855
+ if (!this.result) {
856
+ let result;
857
+ result = __velarProcessThen(invoke("wait", [this.handle]), value => {
858
+ let outcome;
859
+ try { outcome = waitValueOf(value, this.maxOutputBytes); }
860
+ catch (error) {
861
+ if (this.result === result) this.result = null;
862
+ throw error;
863
+ }
864
+ if (outcome.retained) {
865
+ if (this.result === result) this.result = null;
866
+ throw outcome.error;
867
+ }
868
+ if (outcome.error) throw outcome.error;
869
+ return outcome.result;
870
+ }, error => {
871
+ if (this.result === result) this.result = null;
872
+ throw error;
873
+ });
874
+ this.result = result;
875
+ }
876
+ return this.result;
877
+ }
878
+ async stop() {
879
+ return await __velarProcessRetryableStop(this, () => __velarProcessThen(invoke("stop", [this.handle]), value => {
880
+ const outcome = stopValueOf(value, this.maxOutputBytes);
881
+ if (outcome.error) this.result = __velarProcessObservedReject(outcome.error);
882
+ else if (outcome.result) this.result = __velarProcessResolve(outcome.result);
883
+ return null;
884
+ }));
885
+ }
886
+ }
887
+
888
+ export const Process = __velarProcessFreeze({
889
+ is(value) { return value instanceof ProcessHandle; },
890
+ parse(value) { if (!(value instanceof ProcessHandle)) throw new __velarProcessNativeTypeError("Process values are created only by velar/process.start"); return value; },
891
+ });
892
+ export async function start(command, args = [], options = {}) {
893
+ const wire = optionsOf(options);
894
+ const value = startValueOf(await invoke("start", [boundedText(command, "Process command"), argumentsOf(args), wire]));
895
+ return new ProcessHandle(__velarNodeProcessToken, value.handle, value.pid, wire.maxOutputBytes);
896
+ }
897
+ export async function run(command, args = [], options = {}) {
898
+ const owner = await start(command, args, options);
899
+ try { return await owner.wait(); }
900
+ catch (error) {
901
+ if (!owner.result) __velarProcessRetainRun(owner);
902
+ throw error;
903
+ }
904
+ }
905
+ `.trimStart()],
906
+ ["velar/http", VELAR_NODE_HTTP_RUNTIME],
907
+ ["velar/env", VELAR_NODE_ENV_RUNTIME],
908
+ ["velar/host", VELAR_NODE_HOST_RUNTIME],
909
+ ["velar/terminal", String.raw `
910
+ ${VELAR_UTF8_RUNTIME}
911
+ ${VELAR_NODE_TERMINAL_RUNTIME.replace("WORKER_SOURCE", JSON.stringify(VELAR_NODE_TERMINAL_WORKER_SOURCE))}
912
+ `.trimStart()],
913
+ ["velar/serve", String.raw `
914
+ ${VELAR_STRICT_JSON_RUNTIME}
915
+ ${VELAR_TYPE_REGISTRY_RUNTIME}
916
+ ${VELAR_UTF8_RUNTIME}
917
+ ${VELAR_NODE_SERVE_RUNTIME}
918
+ `.trimStart()],
919
+ ]);
920
+ export const nodeModuleDependencies = new Map([
921
+ ["velar/worker", ["velar/worker-manifest", "velar/task"]],
922
+ ["velar/websocket", ["velar/serve"]],
923
+ ["velar/http", [VELAR_NODE_HOST_MODULE, "velar/binary"]],
924
+ ["velar/fs", [VELAR_NODE_HOST_MODULE, "velar/binary"]],
925
+ ["velar/serve", [VELAR_NODE_HOST_MODULE]],
926
+ // D50 rule 89: the host proxy rebuilds the compiler-owned capability error
927
+ // classes, so its module carries that dependency edge.
928
+ [VELAR_NODE_HOST_MODULE, [VELAR_ERROR_NORMALIZATION_MODULE]],
929
+ ]);
930
+ const nodeModules = new Set(nodeModuleInterfaces.keys());
931
+ const sharedPlatformModules = new Set(["velar/http"]);
932
+ export function isNodeModule(source) {
933
+ return nodeModules.has(source);
934
+ }
935
+ export function isNodeOnlyModule(source) {
936
+ return nodeModules.has(source) && !sharedPlatformModules.has(source);
937
+ }
938
+ export function nodeModuleDiagnostic(source) {
939
+ if (source === "velar/serve")
940
+ return "velar/serve is a local runtime module; web applications use the dev server and velar/http";
941
+ return `${source} is a local runtime module and cannot run in a web application`;
942
+ }
943
+ export const velarNodeCompilerExtension = Object.freeze({
944
+ id: "@velarscript/node",
945
+ contract: Object.freeze({ protocolVersion: 1, apiVersion: VELAR_NODE_API_VERSION, kind: "capability", extends: Object.freeze({}) }),
946
+ capabilities: Object.freeze(["node"]),
947
+ modules: Object.freeze({
948
+ apiVersion: VELAR_NODE_API_VERSION,
949
+ interfaces: nodeModuleInterfaces,
950
+ sources: nodeModuleSources,
951
+ dependencies: nodeModuleDependencies,
952
+ }),
953
+ });
954
+ //# sourceMappingURL=compiler.js.map