@arbol-ai/maximus 8.1.0 → 8.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/analytics/analytics.d.ts +16 -16
  2. package/dist/analytics/analytics.js +3 -3
  3. package/dist/body.d.ts +2 -2
  4. package/dist/body.js +2 -2
  5. package/dist/capture/index.d.ts +1 -1
  6. package/dist/capture/index.js +3 -4
  7. package/dist/chunks/{define-app-BxGZdNmS.js → define-app-CQpWqqqE.js} +33 -14
  8. package/dist/chunks/{json-B14evE6-.js → destination-DIkn8W6K.js} +65 -1
  9. package/dist/chunks/{digest-C7UGt760.js → digest-C51F1bhA.js} +1 -2
  10. package/dist/chunks/{errors-CWgE9uvM.js → errors-BoutSmiy.js} +2 -3
  11. package/dist/chunks/{execution-BTiAWA4n.js → execution-Bpq6s4nA.js} +9 -8
  12. package/dist/chunks/{generate-C-9FKW0o.js → generate-Dg88LzLU.js} +1 -1
  13. package/dist/chunks/{handler-iebR-urt.js → handler-DSpyrWc-.js} +6 -2
  14. package/dist/chunks/{http-layout-BvlbD__1.js → http-layout-BcYH4I2w.js} +1 -1
  15. package/dist/chunks/{http-paths-DMBxwpp6.js → http-paths-D043DkJv.js} +50 -81
  16. package/dist/chunks/http-routes-B6tCsnxB.js +29 -0
  17. package/dist/chunks/{openapi-BF3eCpux.js → openapi-D2rds7vy.js} +27 -116
  18. package/dist/chunks/{openapi-file-RcXoq0AF.js → openapi-file-BK8zET5U.js} +24 -6
  19. package/dist/chunks/{pages-BCksUeRf.js → pages-B7ysoFAM.js} +1 -1
  20. package/dist/chunks/result-CF4OzG9O.js +29 -0
  21. package/dist/chunks/{runtime-D5eR9-Es.js → runtime-CGtS2rOb.js} +132 -7
  22. package/dist/chunks/schemas-_UJcx_uY.js +813 -0
  23. package/dist/chunks/{server-B9C8KPwa.js → server-CVhTLNj2.js} +37 -101
  24. package/dist/chunks/{src-C-4z443M.js → src-D67OfW9B.js} +40 -19
  25. package/dist/chunks/tasks-C873C3le.js +100 -0
  26. package/dist/chunks/tasks-DYdY-dBI.js +267 -0
  27. package/dist/chunks/{types-Dqo3oGig.d.ts → types-BfGa2aJT.d.ts} +346 -138
  28. package/dist/chunks/validation-CpzAxj2_.js +201 -0
  29. package/dist/chunks/{workers-types-BgjyDtGd.d.ts → workers-types-Cxf-5cH7.d.ts} +6 -1
  30. package/dist/diagnostics.d.ts +1 -1
  31. package/dist/errors.d.ts +1 -1
  32. package/dist/errors.js +1 -1
  33. package/dist/http-paths.d.ts +1 -1
  34. package/dist/http-paths.js +1 -1
  35. package/dist/index.d.ts +2 -2
  36. package/dist/index.js +11 -10
  37. package/dist/internals.d.ts +1 -1
  38. package/dist/internals.js +4 -4
  39. package/dist/mcp/index.d.ts +1 -1
  40. package/dist/mcp/index.js +1 -1
  41. package/dist/mcp/tasks.d.ts +33 -0
  42. package/dist/mcp/tasks.js +3 -0
  43. package/dist/project/config.d.ts +2 -2
  44. package/dist/project/config.js +3 -2
  45. package/dist/project/index.d.ts +2 -2
  46. package/dist/project/index.js +3 -3
  47. package/dist/schemas.d.ts +2 -2
  48. package/dist/schemas.js +3 -3
  49. package/dist/standard-failures.d.ts +1 -1
  50. package/dist/tooling/cli.js +2 -2
  51. package/dist/vite/index.d.ts +1 -1
  52. package/dist/vite/index.js +6 -5
  53. package/dist/webhooks.d.ts +13 -2
  54. package/dist/webhooks.js +38 -1
  55. package/dist/workers/runtime.d.ts +1 -1
  56. package/dist/workers/runtime.js +1 -1
  57. package/package.json +11 -3
  58. package/skills/maximus/SKILL.md +7 -4
  59. package/skills/maximus/references/routes-and-tools.md +9 -1
  60. package/dist/chunks/result-CKgZHrnj.js +0 -56
  61. package/dist/chunks/schemas-BOFxZP1c.js +0 -227
  62. package/dist/chunks/validation-DMu0rkMQ.js +0 -670
@@ -1,114 +1,16 @@
1
- import { t as STANDARD_FAILURES } from "./standard-failures-Lh4mSfwG.js";
2
- import { C as wireInput, T as withoutSecretKeyword, i as parseInput } from "./validation-DMu0rkMQ.js";
1
+ import { i as parseInput } from "./validation-CpzAxj2_.js";
2
+ import { L as wireInput, i as UuidSchema, n as OrganizationIdSchema, z as withoutSecretKeyword } from "./schemas-_UJcx_uY.js";
3
3
  import { t as isRecord } from "./record-DQUDTpEA.js";
4
- import { i as standardErrors } from "./errors-CWgE9uvM.js";
5
- import { a as operationPathParameters } from "./http-paths-DMBxwpp6.js";
6
- import { a as routeGroup, i as pathParameterSchemas, r as ok, t as err } from "./result-CKgZHrnj.js";
7
- import { i as UuidSchema, n as OrganizationIdSchema } from "./schemas-BOFxZP1c.js";
4
+ import { i as standardErrors } from "./errors-BoutSmiy.js";
5
+ import { a as operationPathParameters } from "./http-paths-D043DkJv.js";
6
+ import { n as routeGroup, t as pathParameterSchemas } from "./http-routes-B6tCsnxB.js";
7
+ import { S as matchesScopes, _ as operationBodyLimit, b as operationScopes, f as STANDARD_CODES, h as mcpOpenWorld, l as BODY_CODES, m as isPublicOperation, n as TASK_GROUP, r as TASK_GROUP_DESCRIPTION, x as isNamespacedScope, y as operationOutputLimit } from "./tasks-DYdY-dBI.js";
8
+ import { r as ok, t as err } from "./result-CF4OzG9O.js";
8
9
  import { t as queryKind } from "./query-kind-CWKAXEME.js";
9
- import { t as sha256Hex } from "./digest-C7UGt760.js";
10
- import { Type } from "@sinclair/typebox";
10
+ import { t as sha256Hex } from "./digest-C51F1bhA.js";
11
+ import { Type } from "typebox";
11
12
  import { createRemoteJWKSet, jwtVerify } from "jose";
12
13
 
13
- // src/scopes.ts
14
- /** `<namespace>:<resource>:<action>`, or deeper, in lowercase kebab-case segments. */
15
- const SCOPE_NAME = /^[a-z][a-z0-9-]*(?::[a-z][a-z0-9-]*){2,}$/;
16
- /** Whether `scope` is a well-formed scope of the service whose namespace is `namespace`. */
17
- function isNamespacedScope(scope, namespace) {
18
- return scope.startsWith(`${namespace}:`) && SCOPE_NAME.test(scope);
19
- }
20
- /**
21
- * Whether granted scopes admit a requirement: any one of the required scopes, or all of them with `all`.
22
- * An empty requirement admits nobody.
23
- */
24
- function matchesScopes(required, granted, match = "any") {
25
- if (!required.length) return false;
26
- const has = (scope) => granted.includes(scope);
27
- return match === "all" ? required.every(has) : match === "any" && required.some(has);
28
- }
29
-
30
- // src/manifest.ts
31
- /** Whether an operation belongs in public contracts: the OpenAPI document and the discovery metadata. */
32
- function isPublicOperation(declaration) {
33
- return declaration.visibility !== "internal";
34
- }
35
- /** The scopes of an operation as a list. */
36
- function operationScopes(declaration) {
37
- return typeof declaration.scope === "string" ? [declaration.scope] : declaration.scope;
38
- }
39
- /**
40
- * Whether granted scopes admit an operation: any one of its scopes, or every one under `scopeMatch: 'all'`.
41
- * HTTP admission, MCP listing and calls, and execution share it.
42
- */
43
- function operationMatchesScopes(declaration, granted) {
44
- return matchesScopes(operationScopes(declaration), granted, declaration.scopeMatch);
45
- }
46
- /**
47
- * Declares one operation on its own, keeping its literal types. The builder's `.operation()` is the usual way
48
- * to declare one. As there, `execute` receives the decoded input, `StaticDecode<typeof input>`.
49
- */
50
- function operation(definition) {
51
- return definition;
52
- }
53
- /** Where an operation is served, for a refusal that names it: its HTTP route, else its MCP tool. */
54
- function servedAs(declared) {
55
- if (declared?.http) return `${declared.http.method} ${declared.http.path}`;
56
- return declared?.mcp && `the tool ${declared.mcp.name}`;
57
- }
58
- /**
59
- * Merges groups of operations into one, never overwriting: a name two groups declare throws a TypeError,
60
- * `Duplicate operation: <name>`, which names the route or tool of each when both have one.
61
- */
62
- function composeOperations(...groups) {
63
- const result = {};
64
- for (const group of groups) for (const [name, op] of Object.entries(group)) {
65
- if (Object.hasOwn(result, name)) {
66
- const first = servedAs(result[name]);
67
- const second = servedAs(op);
68
- throw new TypeError(first && second ? `Duplicate operation: ${name} names both ${first} and ${second}; give one of them its own operationId.` : `Duplicate operation: ${name}`);
69
- }
70
- Object.defineProperty(result, name, {
71
- value: op,
72
- enumerable: true
73
- });
74
- }
75
- return result;
76
- }
77
- /** The failure codes every operation may answer without declaring them. */
78
- const STANDARD_CODES = new Set(Object.values(STANDARD_FAILURES).map(({ code }) => code));
79
- /**
80
- * The standard failures only routing and admission answer, before an operation runs: an unknown path or
81
- * method, and a missing or refused token. An operation's context, middleware or handler never answers them.
82
- */
83
- const ADMISSION_CODES = /* @__PURE__ */ new Set([
84
- STANDARD_FAILURES.notFound.code,
85
- STANDARD_FAILURES.methodNotAllowed.code,
86
- STANDARD_FAILURES.unauthorized.code
87
- ]);
88
- /**
89
- * The standard failures of reading a request body: admission answers them for a JSON body, and a byte body's
90
- * `read()` for the operation that reads one.
91
- */
92
- const BODY_CODES = /* @__PURE__ */ new Set([STANDARD_FAILURES.tooLarge.code, STANDARD_FAILURES.unsupportedMedia.code]);
93
- /** Default request body limit when neither the operation nor the application sets one. */
94
- const DEFAULT_MAX_BODY_BYTES = 32768;
95
- /** Default output limit when neither the operation nor the application sets one. */
96
- const DEFAULT_MAX_OUTPUT_BYTES = 262144;
97
- /** Largest body limit an application or operation may declare: the body is buffered in memory. */
98
- const MAX_BODY_BYTES_CEILING = 16777216;
99
- /** The request body limit an operation is held to: its own, else the application's, else the default. */
100
- function operationBodyLimit(application, declaration) {
101
- return declaration.maxBodyBytes ?? application.maxBodyBytes ?? 32768;
102
- }
103
- /** The output limit an operation is held to: its own, else the application's, else the default. */
104
- function operationOutputLimit(application, declaration) {
105
- return declaration.maxOutputBytes ?? application.maxOutputBytes ?? 262144;
106
- }
107
- /** Whether an operation's MCP tool reaches outside the service: it does unless it declares otherwise. */
108
- function mcpOpenWorld(tool) {
109
- return tool.openWorld ?? true;
110
- }
111
-
112
14
  // src/internal/claims.ts
113
15
  /**
114
16
  * Reading a verified token's claims, which token verification and Cloudflare Access share.
@@ -372,7 +274,7 @@ function queryInput(kinds, params) {
372
274
  * Schema bundling: named schemas (`$id`) become shared components for an OpenAPI document, or are written
373
275
  * in place for a reader without components, such as an MCP tool listing.
374
276
  */
375
- /** Plain identifiers TypeBox uses for Recursive/Ref schemas; URLs and pointers are left untouched. */
277
+ /** Plain identifiers TypeBox uses for Cyclic/Ref schemas; URLs and pointers are left untouched. */
376
278
  const SCHEMA_ID = /^[A-Za-z][A-Za-z0-9_.-]{0,127}$/;
377
279
  /** Use-site annotations: they describe one occurrence and do not change which values validate. */
378
280
  const ANNOTATIONS = /* @__PURE__ */ new Set([
@@ -422,7 +324,7 @@ function replaceReferences(value, replace) {
422
324
  return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, key === "$ref" && typeof child === "string" ? replace(child) : replaceReferences(child, replace)]));
423
325
  }
424
326
  /**
425
- * Bundles `$id`-named schemas (TypeBox Recursive/Ref) into components so that every reference in an
327
+ * Bundles `$id`-named schemas (TypeBox Cyclic/Ref) into components so that every reference in an
426
328
  * OpenAPI document is a local `#/components/schemas/<name>` pointer. A plain-name reference resolves
427
329
  * against its enclosing `$id`, as in JSON Schema; structurally different definitions that share an
428
330
  * `$id` (for example a normalized input projection and its output) become distinct components. A
@@ -444,6 +346,15 @@ function bundleSchemas(sources, existing) {
444
346
  if (Array.isArray(value)) return value.map((item) => rewrite(item, scope));
445
347
  if (!value || typeof value !== "object") return value;
446
348
  const record = value;
349
+ const definitions = record.$defs;
350
+ if (definitions && typeof record.$ref === "string" && Object.hasOwn(definitions, record.$ref)) {
351
+ for (const [name, definition] of Object.entries(definitions)) if (name !== record.$ref) rewrite(definition, scope);
352
+ const annotations = Object.fromEntries(Object.entries(record).filter(([key]) => ANNOTATIONS.has(key)));
353
+ return {
354
+ ...rewrite(definitions[record.$ref], scope),
355
+ ...annotations
356
+ };
357
+ }
447
358
  if (typeof record.$id === "string" && ids.has(record.$id)) {
448
359
  const { $id: id, ...rest } = record;
449
360
  const definition = Object.fromEntries(Object.entries(rest).filter(([key]) => !ANNOTATIONS.has(key)));
@@ -508,7 +419,7 @@ function collectReferences(value, references) {
508
419
  /**
509
420
  * The schema with every `$id` nothing refers to removed, the definition left in place: what a reader
510
421
  * that resolves no components meets, the same as before the schema was named. A definition a `$ref`
511
- * names (TypeBox Recursive or Ref) keeps its `$id`, so the reference still resolves.
422
+ * names (TypeBox Cyclic or Ref) keeps its `$id`, so the reference still resolves.
512
423
  */
513
424
  function inlineSchemaNames(value) {
514
425
  const references = /* @__PURE__ */ new Set();
@@ -1092,7 +1003,7 @@ function bodyWithoutPathParameters(input, names) {
1092
1003
  const { $id: _id, ...union } = input;
1093
1004
  return {
1094
1005
  ...union,
1095
- anyOf: input.anyOf.map((schema) => bodyWithoutPathParameters(schema, names))
1006
+ anyOf: (input.anyOf ?? []).map((schema) => bodyWithoutPathParameters(schema, names))
1096
1007
  };
1097
1008
  }
1098
1009
  const carried = Object.keys(input.properties ?? {}).filter((name) => names.has(name)).length;
@@ -1100,7 +1011,7 @@ function bodyWithoutPathParameters(input, names) {
1100
1011
  const { $id: _id, minProperties, maxProperties, ...object } = input;
1101
1012
  return {
1102
1013
  ...object,
1103
- properties: Object.fromEntries(Object.entries(input.properties).filter(([name]) => !names.has(name))),
1014
+ properties: Object.fromEntries(Object.entries(input.properties ?? {}).filter(([name]) => !names.has(name))),
1104
1015
  required: (input.required ?? []).filter((name) => !names.has(name)),
1105
1016
  ...typeof minProperties === "number" && minProperties > carried ? { minProperties: minProperties - carried } : {},
1106
1017
  ...typeof maxProperties === "number" ? { maxProperties: maxProperties - carried } : {}
@@ -1113,7 +1024,7 @@ function bodyWithoutPathParameters(input, names) {
1113
1024
  * effect, limits in force, MCP tool hints and native RPC as `x-*` extensions.
1114
1025
  *
1115
1026
  * Every schema reference in it is a local `#/components/schemas/<name>` pointer: the `$id`-named
1116
- * schemas of its paths and components (TypeBox Recursive/Ref) become components, as `bundleSchemas`
1027
+ * schemas of its paths and components (TypeBox Cyclic/Ref) become components, as `bundleSchemas`
1117
1028
  * describes. A schema `$id` that takes the name of a component the document writes itself, and a component
1118
1029
  * named as a generator names an operation's own types, such as `CreateNoteResponse`, throw a TypeError.
1119
1030
  */
@@ -1258,7 +1169,7 @@ function openApiDocument(manifest, kind) {
1258
1169
  },
1259
1170
  ...rpc ? {} : { servers: [{ url: manifest.origin }] },
1260
1171
  tags: groups.map((group) => {
1261
- const description = manifest.groups?.[group];
1172
+ const description = manifest.groups?.[group] ?? (group === "Operation tasks" ? "The tasks of operations that answer before they finish: read one you started, or cancel one that has not started running." : void 0);
1262
1173
  return description ? {
1263
1174
  name: group,
1264
1175
  description
@@ -1495,7 +1406,7 @@ function failureResponse(name, status, failures, components) {
1495
1406
  }
1496
1407
  /** A failure as its component, `<Code>Failure`, with its data: the schema its definition declares, else `Empty`. */
1497
1408
  function addFailure(definition, components) {
1498
- const { dataSchema } = definition;
1409
+ const dataSchema = definition.dataSchema;
1499
1410
  let data;
1500
1411
  if (dataSchema === void 0 || isEmptyObject(dataSchema)) data = components.add("Empty", EMPTY_OBJECT);
1501
1412
  else if (typeof dataSchema.$id === "string") data = dataSchema;
@@ -1576,4 +1487,4 @@ function securitySchemes(tokens, scopes) {
1576
1487
  };
1577
1488
  }
1578
1489
 
1579
- export { operationOutputLimit as A, MAX_BODY_BYTES_CEILING as C, mcpOpenWorld as D, isPublicOperation as E, isNamespacedScope as M, matchesScopes as N, operation as O, DEFAULT_MAX_BODY_BYTES as S, composeOperations as T, projectAccessToken as _, createTokenVerifier as a, ADMISSION_CODES as b, tokenAudiences as c, canonical as d, hasSchemaReferences as f, isCrossSiteWrite as g, queryKinds as h, createTokenAuthorization as i, operationScopes as j, operationMatchesScopes as k, tokenIssuer as l, queryInput as m, createRpcOpenApi as n, presentedToken as o, standaloneSchema as p, checkTokenAuthority as r, projectToken as s, createOpenApi as t, usesOwnBearer as u, usesCloudflareAccess as v, STANDARD_CODES as w, BODY_CODES as x, PrincipalSchema as y };
1490
+ export { projectAccessToken as _, createTokenVerifier as a, tokenAudiences as c, canonical as d, hasSchemaReferences as f, isCrossSiteWrite as g, queryKinds as h, createTokenAuthorization as i, tokenIssuer as l, queryInput as m, createRpcOpenApi as n, presentedToken as o, standaloneSchema as p, checkTokenAuthority as r, projectToken as s, createOpenApi as t, usesOwnBearer as u, usesCloudflareAccess as v, PrincipalSchema as y };
@@ -1,15 +1,15 @@
1
- import { n as createRpcOpenApi } from "./openapi-BF3eCpux.js";
1
+ import { n as createRpcOpenApi } from "./openapi-D2rds7vy.js";
2
2
  import { t as prepareConfiguredProject } from "./prepare-configured-Cithjf80.js";
3
3
  import { t as packageDirectory } from "./scaffold-DZD6dfoZ.js";
4
4
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
- import { dirname, join, resolve } from "node:path";
5
+ import { dirname, join, relative, resolve } from "node:path";
6
6
 
7
7
  // src/tooling/internal/openapi-file.ts
8
8
  /**
9
9
  * `maximus openapi`: the OpenAPI documents of a project's Worker, as files beside its sources. The HTTP
10
10
  * document, the one the Worker serves, is the contract the project's clients are generated from; the RPC
11
11
  * document, of the operations it serves over native RPC, is the one other services type their bindings from.
12
- * `--check` keeps both current in CI.
12
+ * `--check` keeps both current and valid OpenAPI 3.1 in CI.
13
13
  */
14
14
  /** The file `maximus openapi` writes the HTTP document to unless `--out` names another, at the project's root. */
15
15
  const OPENAPI_FILE = "openapi.json";
@@ -49,6 +49,19 @@ function operationCount(document) {
49
49
  const paths = document.paths ?? {};
50
50
  return Object.values(paths).reduce((count, methods) => count + Object.keys(methods).length, 0);
51
51
  }
52
+ /** The most problems a refused document names. */
53
+ const MAX_PROBLEMS = 5;
54
+ /**
55
+ * Throws when a document is not valid OpenAPI 3.1, naming its file and its first problems. The validator is
56
+ * build-time tooling: it loads for the check alone, never in a Worker.
57
+ */
58
+ async function assertValidOpenApi(name, document) {
59
+ const { validate } = await import("@scalar/openapi-parser");
60
+ const result = await validate(structuredClone(document));
61
+ if (result.valid && result.version === "3.1") return;
62
+ const problems = result.valid ? [`it declares OpenAPI ${result.version}`] : result.errors.slice(0, MAX_PROBLEMS).map(({ path, message }) => path?.length ? `${[path].flat().join("/")}: ${message}` : message);
63
+ throw new Error(`${name} is not valid OpenAPI 3.1: ${problems.join("; ")}.`);
64
+ }
52
65
  /** Writes a document to a file as JSON with two-space indentation, unless `check` asks only whether it differs. */
53
66
  function writeDocument(file, document, check) {
54
67
  const text = `${JSON.stringify(document, null, 2)}\n`;
@@ -66,14 +79,19 @@ function writeDocument(file, document, check) {
66
79
  /**
67
80
  * Writes the documents of the project's Worker: the HTTP one to `out`, `openapi.json` at its root by default,
68
81
  * and, when an operation declares `rpc`, the RPC one beside it, `openapi.rpc.json`. With `check`, writes
69
- * nothing and answers whether each file differs.
82
+ * nothing, throws for a document that is not valid OpenAPI 3.1 and answers whether each file differs.
70
83
  */
71
84
  async function writeOpenApi(directory, { out = OPENAPI_FILE, check = false } = {}) {
72
85
  const documents = await projectDocuments(directory);
73
86
  const file = resolve(directory, out);
74
- const written = writeDocument(file, documents.http, check);
75
- if (!operationCount(documents.rpc)) return written;
76
87
  const rpcFile = file.endsWith(".json") ? `${file.slice(0, -5)}.rpc.json` : `${file}.rpc.json`;
88
+ const servesRpc = operationCount(documents.rpc) > 0;
89
+ if (check) {
90
+ await assertValidOpenApi(relative(directory, file), documents.http);
91
+ if (servesRpc) await assertValidOpenApi(relative(directory, rpcFile), documents.rpc);
92
+ }
93
+ const written = writeDocument(file, documents.http, check);
94
+ if (!servesRpc) return written;
77
95
  return {
78
96
  ...written,
79
97
  rpc: writeDocument(rpcFile, documents.rpc, check)
@@ -1,4 +1,4 @@
1
- import { a as ownsPrefix, i as nativePaths, t as VERSIONED_PATH } from "./http-layout-BvlbD__1.js";
1
+ import { a as ownsPrefix, i as nativePaths, t as VERSIONED_PATH } from "./http-layout-BcYH4I2w.js";
2
2
 
3
3
  // src/project/pages.ts
4
4
  /**
@@ -0,0 +1,29 @@
1
+ import { t as isRecord } from "./record-DQUDTpEA.js";
2
+
3
+ // src/result.ts
4
+ /** A success carrying `value`. */
5
+ function ok(value) {
6
+ return {
7
+ ok: true,
8
+ value
9
+ };
10
+ }
11
+ /** A failure carrying `error`, usually `catalog.someFailure.create()`. */
12
+ function err(error) {
13
+ return {
14
+ ok: false,
15
+ error
16
+ };
17
+ }
18
+ /**
19
+ * Whether an untrusted answer (a Service Binding's, a stored one) is a Maximus Result: a success with
20
+ * its value, or a failure with a well-formed error. Anything else is not an answer at all.
21
+ */
22
+ function isResult(value) {
23
+ if (!isRecord(value)) return false;
24
+ if (value.ok === true) return "value" in value;
25
+ const { error } = value;
26
+ return value.ok === false && isRecord(error) && typeof error.code === "string" && typeof error.message === "string" && typeof error.retryable === "boolean" && isRecord(error.data);
27
+ }
28
+
29
+ export { isResult as n, ok as r, err as t };
@@ -1,11 +1,12 @@
1
- import { i as parseInput } from "./validation-DMu0rkMQ.js";
1
+ import { i as parseInput } from "./validation-CpzAxj2_.js";
2
2
  import { r as isRequestId } from "./correlation-4b23a-a4.js";
3
- import { i as standardErrors } from "./errors-CWgE9uvM.js";
4
- import { r as ok, t as err } from "./result-CKgZHrnj.js";
5
- import { y as PrincipalSchema } from "./openapi-BF3eCpux.js";
6
- import { r as createHttpHandler } from "./src-C-4z443M.js";
3
+ import { i as standardErrors } from "./errors-BoutSmiy.js";
4
+ import { y as PrincipalSchema } from "./openapi-D2rds7vy.js";
5
+ import { r as ok, t as err } from "./result-CF4OzG9O.js";
6
+ import { r as createHttpHandler } from "./src-D67OfW9B.js";
7
+ import { t as delay } from "./delay-BsKQP_lF.js";
7
8
  import { a as recordExecution, l as withTelemetry, o as reportUnexpected, s as telemetryEnabled } from "./telemetry-BtxJh69Q.js";
8
- import { n as recordCapture, t as executeOperation } from "./execution-BTiAWA4n.js";
9
+ import { n as recordCapture, t as executeOperation } from "./execution-Bpq6s4nA.js";
9
10
  import { DurableObject, WorkerEntrypoint, tracing } from "cloudflare:workers";
10
11
 
11
12
  // src/workers/assets.ts
@@ -149,6 +150,129 @@ function annotateInvocation(service, operation, requestId, attributeNames = {
149
150
  } catch {}
150
151
  }
151
152
 
153
+ // src/workers/tasks.ts
154
+ /**
155
+ * The task store and its executor: one SQLite Durable Object per task keeps it and runs it from its alarm, at
156
+ * once and at most once, so no task waits for another. The input is never stored: it stays in the object's
157
+ * memory until the alarm starts the task. A task found started but still working, after the object restarted
158
+ * mid-run, settles as OUTCOME_UNKNOWN and never runs again; one whose input went with a restart before it
159
+ * started settles as INTERNAL_ERROR, never having run. The object deletes everything once the task's TTL has
160
+ * passed since its call.
161
+ */
162
+ /** Where the object keeps its task. */
163
+ const KEY = "task";
164
+ /** Whether `principal` started the task: the same organization and the same actor. */
165
+ const owns = (task, principal) => task.principal.organizationId === principal.organizationId && task.principal.actorId === principal.actorId && task.principal.actorKind === principal.actorKind;
166
+ /** The task store class of an application, which a Worker exports for its `MAXIMUS_TASKS` binding. */
167
+ function tasksObject(manifest) {
168
+ return class MaximusTasks extends DurableObject {
169
+ /** The task's input, in memory alone, until the task starts. */
170
+ #input;
171
+ /** Answers the call waiting for the task to settle. */
172
+ #settled;
173
+ /** Whether this instance is running the task: a task found started otherwise was interrupted. */
174
+ #running = false;
175
+ /** Keeps the task, has the alarm start it at once, and answers it once it settles or `waitMs` passes. */
176
+ async run(task, input, waitMs) {
177
+ const settled = new Promise((resolve) => {
178
+ this.#settled = resolve;
179
+ });
180
+ this.#input = { value: input };
181
+ await this.ctx.storage.put(KEY, task);
182
+ await this.ctx.storage.setAlarm(Date.now());
183
+ await Promise.race([settled, delay(waitMs)]);
184
+ return await this.ctx.storage.get(KEY) ?? task;
185
+ }
186
+ /** The task, when `principal` started it and it has not expired. */
187
+ async get(taskId, principal) {
188
+ const task = await this.ctx.storage.get(KEY);
189
+ if (!task || task.taskId !== taskId || task.createdAt + task.ttlMs <= Date.now()) return;
190
+ return owns(task, principal) ? task : void 0;
191
+ }
192
+ /** Cancels a task `principal` started that has not started running; one that has runs to its end. */
193
+ async cancel(taskId, principal) {
194
+ const task = await this.get(taskId, principal);
195
+ if (task?.status !== "working" || task.started) return task;
196
+ this.#input = void 0;
197
+ const cancelled = {
198
+ ...task,
199
+ status: "cancelled",
200
+ lastUpdatedAt: Date.now()
201
+ };
202
+ await this.ctx.storage.put(KEY, cancelled);
203
+ return cancelled;
204
+ }
205
+ /** Runs the task, or settles one a restart interrupted, then wakes once more to delete it when it expires. */
206
+ async alarm() {
207
+ const input = this.#input;
208
+ this.#input = void 0;
209
+ const task = await this.ctx.storage.get(KEY);
210
+ if (!task || task.createdAt + task.ttlMs <= Date.now()) {
211
+ await this.ctx.storage.deleteAll();
212
+ return;
213
+ }
214
+ if (task.status === "working" && !this.#running) {
215
+ if (task.started) await this.#settle(task, err(standardErrors.outcomeUnknown.create()));
216
+ else if (input) await this.#execute(task, input.value);
217
+ else await this.#settle(task, err(standardErrors.internal.create()));
218
+ }
219
+ await this.ctx.storage.setAlarm(task.createdAt + task.ttlMs);
220
+ }
221
+ /** Marks the task started, then runs its operation as its caller and keeps the result. */
222
+ async #execute(task, input) {
223
+ const pending = [];
224
+ const background = { waitUntil: (promise) => {
225
+ pending.push(promise);
226
+ } };
227
+ this.#running = true;
228
+ try {
229
+ await this.ctx.storage.put(KEY, {
230
+ ...task,
231
+ started: true
232
+ });
233
+ const operation = manifest.operations[task.operation];
234
+ const surface = task.authority?.surface ?? "http";
235
+ const call = { taskId: task.taskId };
236
+ const started = performance.now();
237
+ const result = operation ? await executeOperation(manifest, operation, this.env, task.principal, input, task.authority, background, void 0, call) : err(standardErrors.notFound.create());
238
+ recordExecution(manifest, this.env, background, {
239
+ principal: task.principal,
240
+ operation: task.operation,
241
+ surface,
242
+ started,
243
+ result
244
+ });
245
+ recordCapture(manifest, this.env, background, {
246
+ operation: task.operation,
247
+ surface,
248
+ requestId: task.principal.requestId,
249
+ principal: task.principal,
250
+ requestStarted: started,
251
+ executionStarted: started,
252
+ result,
253
+ call
254
+ });
255
+ await this.#settle(task, result);
256
+ } finally {
257
+ this.#running = false;
258
+ }
259
+ await Promise.allSettled(pending);
260
+ }
261
+ /** Keeps how the task ended and answers the call waiting for it. */
262
+ async #settle(task, result) {
263
+ const status = result.ok ? "completed" : "failed";
264
+ await this.ctx.storage.put(KEY, {
265
+ ...task,
266
+ started: true,
267
+ status,
268
+ result,
269
+ lastUpdatedAt: Date.now()
270
+ });
271
+ this.#settled?.();
272
+ }
273
+ };
274
+ }
275
+
152
276
  // src/workers/credentials.ts
153
277
  /**
154
278
  * Reads one organization's credential from its own store, such as a Durable Object per organization, and
@@ -270,7 +394,8 @@ function createWorker(application, options = {}) {
270
394
  service,
271
395
  durableObject(implementation) {
272
396
  return instrumentDurableObject(implementation, manifest.telemetry);
273
- }
397
+ },
398
+ tasks: instrumentDurableObject(tasksObject(manifest), manifest.telemetry)
274
399
  };
275
400
  }
276
401