kizunajs 2.0.0-beta.2 → 2.0.0-beta.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/dist/{adapter-CZW-unqX.mjs → adapter-BSqNrxhq.mjs} +522 -104
- package/dist/adapter-C3WYdSfx.d.cts +2754 -0
- package/dist/{adapter-DDR_yo9L.cjs → adapter-ClaFZoab.cjs} +638 -196
- package/dist/adapter-D4bTPElA.d.mts +2754 -0
- package/dist/adapter.cjs +37 -29
- package/dist/adapter.d.cts +3 -5
- package/dist/adapter.d.mts +3 -5
- package/dist/adapter.mjs +5 -5
- package/dist/{error-response-C8Ragjcd.cjs → error-response-C9ymqSU4.cjs} +25 -5
- package/dist/{error-response-C839d8By.mjs → error-response-CNQaKVYd.mjs} +20 -6
- package/dist/{security-scheme-BrszwGD5.d.cts → error-response-NoOGdh8H.d.mts} +151 -24
- package/dist/{security-scheme-D3nb4XKj.d.mts → error-response-YbkRMKno.d.cts} +151 -24
- package/dist/generator.cjs +190 -95
- package/dist/generator.d.cts +189 -28
- package/dist/generator.d.mts +189 -28
- package/dist/generator.mjs +151 -60
- package/dist/index.cjs +159 -84
- package/dist/index.d.cts +193 -253
- package/dist/index.d.mts +193 -253
- package/dist/index.mjs +112 -38
- package/dist/jobs-entry.cjs +12 -11
- package/dist/jobs-entry.d.cts +1 -1
- package/dist/jobs-entry.d.mts +1 -1
- package/dist/jobs-entry.mjs +3 -2
- package/dist/plugin-Dw-yCjTY.cjs +233 -0
- package/dist/{cache-CLN5y0Xp.mjs → plugin-server-BztlE1fz.mjs} +188 -49
- package/dist/{cache-BgohRj0i.cjs → plugin-server-kUsK7thV.cjs} +238 -93
- package/dist/plugin-xxCxibmu.mjs +138 -0
- package/dist/plugin.cjs +8 -72
- package/dist/plugin.d.cts +3 -3
- package/dist/plugin.d.mts +3 -3
- package/dist/plugin.mjs +2 -68
- package/dist/{protected-resource-metadata-CA0v5cjg.d.mts → protected-resource-metadata-B9hMFQ9N.d.cts} +1 -1
- package/dist/{protected-resource-metadata-Cprrv0mt.d.cts → protected-resource-metadata-CfBVsqIk.d.mts} +1 -1
- package/dist/{schemas-C56no6bv.cjs → schemas-DNPVDvkd.cjs} +28 -1
- package/dist/{schemas-CJQcc97N.mjs → schemas-HW2FDsvz.mjs} +23 -2
- package/dist/schemas.cjs +3 -2
- package/dist/schemas.d.cts +24 -3
- package/dist/schemas.d.mts +24 -3
- package/dist/schemas.mjs +3 -3
- package/package.json +1 -1
- package/src/adapter.ts +245 -29
- package/src/api-definition.ts +12 -16
- package/src/api.ts +7 -3
- package/src/brand.ts +29 -0
- package/src/config.ts +51 -10
- package/src/configured.ts +13 -6
- package/src/define-config.ts +118 -39
- package/src/generator.ts +363 -46
- package/src/group-routes.ts +106 -0
- package/src/groups.ts +140 -0
- package/src/handler-pipeline.ts +78 -19
- package/src/index.ts +15 -6
- package/src/job-runner.ts +5 -0
- package/src/job-transport.ts +3 -3
- package/src/job.ts +8 -6
- package/src/jobs-dev-runner.ts +6 -0
- package/src/jobs.ts +61 -8
- package/src/kizuna.ts +56 -33
- package/src/plugin-server.ts +129 -19
- package/src/plugin.ts +269 -127
- package/src/routes.ts +80 -32
- package/src/schemas.ts +1 -0
- package/src/tool-answer.ts +21 -0
- package/src/tool-definitions.ts +166 -0
- package/src/tool-events.ts +90 -18
- package/src/tool-records.ts +11 -3
- package/src/tool-runner.ts +298 -0
- package/src/types.ts +90 -24
- package/src/zod-internals.ts +22 -5
- package/src/zod-meta.ts +7 -2
- package/dist/adapter-BGfMqEkM.d.cts +0 -563
- package/dist/adapter-Ci3cfcoT.d.mts +0 -563
- package/dist/api-definition-BHnh15zD.d.mts +0 -803
- package/dist/api-definition-DQj-ewHy.d.cts +0 -803
- package/dist/error-response-BBGSdgYw.d.mts +0 -67
- package/dist/error-response-Do38sr-9.d.cts +0 -67
- package/dist/plugin-Cz0kn6Lk.d.mts +0 -830
- package/dist/plugin-DhKvx_T0.d.cts +0 -830
- package/src/tags.ts +0 -67
package/dist/index.mjs
CHANGED
|
@@ -1,9 +1,29 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as isProblemDetails, r as createModel, t as ProblemDetailsSchema
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
1
|
+
import { a as definePlugin, c as createRoute, d as AUTO_RESPONSES_BRAND, f as DECLARATION, g as ROUTES_GROUP, h as METHODS, l as AUTO_GUARD_BRAND, m as HANDLER_CONTEXT_BRAND, o as pluginRouteTree, p as HANDLER, u as AUTO_GUARD_WRITTEN_BRAND } from "./plugin-xxCxibmu.mjs";
|
|
2
|
+
import { T as readObjectShape, m as readDef, n as isProblemDetails, r as createModel, t as ProblemDetailsSchema } from "./error-response-CNQaKVYd.mjs";
|
|
3
|
+
import { B as streamStatuses, C as firesBetween, D as scheduleExpression, E as parseCron, F as routeStreams, G as isZodSchema, I as soleStreamResponse, J as resolveResponseBody, L as streamContentType, O as scheduleTimezone, P as isNamedStream, R as streamMode, S as dueSchedules, T as nextRuns, U as isStreamResponse, _ as jobAt, b as assertValidSchedule, dt as isRouteDefinition, f as assertJobRunner, g as isJobDefinition, h as isCompiledJob, j as EVENT_STREAM_MEDIA_TYPE, l as assertValidDeprecationDates, lt as flattenRoutes, m as flattenJobs, o as resolvePlugins, ot as buildPath, p as buildJobs, r as pluginExportsOf, s as assertValidCache, st as parsePath, t as createApiReference, v as jobClaims, w as nextRun, x as cron } from "./plugin-server-BztlE1fz.mjs";
|
|
4
|
+
import { a as assertCanonicalResourceUri, c as isValidationError, d as declaredScopes, f as isSecurityScheme, l as authenticationChallenge, o as buildProtectedResourceMetadata, p as resolveSecurityRequirements, u as authorizationServerIssuer } from "./schemas-HW2FDsvz.mjs";
|
|
5
|
+
import { $ as dispatchSucceeded, G as defineJobTransport, J as jobFnAt, K as JobInputError, L as assertNoPathCollisions, P as warnUnsupportedJobOptions, Q as dispatchDueJobs, R as routeClaims, W as JobDispatchError, X as DispatchFailedSchema, Y as ResponseError, Z as DispatchResultSchema, at as getStatusText, ct as isPermissions, dt as createGroups, et as dueJobs, gt as toolEvents, ht as expandStreamTools, it as STATUS_TITLES, j as routerFromRoutes, lt as isRoles, mt as groupRoutes, nt as problemDetails, o as JOBS_META, ot as createPermissions, p as assembleApi, pt as assembleRoutes, q as createJobRunner, rt as problemFromBody, st as createRoles, tt as failedJobs, ut as permissionNames, x as getHeaderValue } from "./adapter-BSqNrxhq.mjs";
|
|
6
6
|
import { z } from "zod";
|
|
7
|
+
//#region src/group-routes.ts
|
|
8
|
+
/**
|
|
9
|
+
* The runtime half of {@link GroupRoutes}. `k` never sees the groups, so
|
|
10
|
+
* `defineConfig` checks each path.
|
|
11
|
+
*/
|
|
12
|
+
const createGroupRoutes = () => {
|
|
13
|
+
const accessors = /* @__PURE__ */ new Map();
|
|
14
|
+
const accessorAt = (path) => {
|
|
15
|
+
const cached = accessors.get(path);
|
|
16
|
+
if (cached !== void 0) return cached;
|
|
17
|
+
const accessor = new Proxy(() => {}, {
|
|
18
|
+
apply: (_target, _this, [routes]) => groupRoutes(path, routes),
|
|
19
|
+
get: (_target, key) => typeof key === "string" ? accessorAt(path === "" ? key : `${path}.${key}`) : void 0
|
|
20
|
+
});
|
|
21
|
+
accessors.set(path, accessor);
|
|
22
|
+
return accessor;
|
|
23
|
+
};
|
|
24
|
+
return accessorAt("");
|
|
25
|
+
};
|
|
26
|
+
//#endregion
|
|
7
27
|
//#region src/coded-issue.ts
|
|
8
28
|
/**
|
|
9
29
|
* Emit a single validation issue with a custom machine-readable `code`.
|
|
@@ -164,15 +184,27 @@ const identityFactories = {
|
|
|
164
184
|
custom: (config) => buildable(createIdentity.custom(config))
|
|
165
185
|
};
|
|
166
186
|
//#endregion
|
|
167
|
-
//#region src/
|
|
168
|
-
const
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
187
|
+
//#region src/brand.ts
|
|
188
|
+
const BRANDABLE_TYPES = new Set([
|
|
189
|
+
"string",
|
|
190
|
+
"number",
|
|
191
|
+
"bigint",
|
|
192
|
+
"boolean",
|
|
193
|
+
"date"
|
|
194
|
+
]);
|
|
195
|
+
/**
|
|
196
|
+
* Brand a Zod schema, so the server and every generated client type its values
|
|
197
|
+
* as that brand. The schema is a string, number, bigint, boolean or date.
|
|
198
|
+
*
|
|
199
|
+
* ```ts
|
|
200
|
+
* const UserId = Kizuna.brand('UserId', z.string());
|
|
201
|
+
* ```
|
|
202
|
+
*/
|
|
203
|
+
const createBrand = (brand, schema) => {
|
|
204
|
+
const type = readDef(schema).type;
|
|
205
|
+
if (type === void 0 || !BRANDABLE_TYPES.has(type)) throw new Error(`Kizuna.brand('${brand}') takes a string, number, bigint, boolean or date schema, not \`${type ?? "unknown"}\`. Put .optional() or .nullable() on the brand instead.`);
|
|
206
|
+
return schema.meta({ brand });
|
|
207
|
+
};
|
|
176
208
|
//#endregion
|
|
177
209
|
//#region src/job.ts
|
|
178
210
|
const createJob = (definition) => ({
|
|
@@ -186,12 +218,11 @@ const createJob = (definition) => ({
|
|
|
186
218
|
//#endregion
|
|
187
219
|
//#region src/kizuna.ts
|
|
188
220
|
const createSurface = () => {
|
|
189
|
-
const routes = ((tagOrDefs, defs) => defs === void 0 ? tagRoutes(tagOrDefs) : tagRoutes(tagOrDefs, defs));
|
|
190
221
|
const jobs = ((identityOrDefinitions, definitions) => definitions === void 0 ? buildJobs(void 0, identityOrDefinitions) : buildJobs(identityOrDefinitions, definitions));
|
|
191
222
|
return {
|
|
192
|
-
|
|
223
|
+
groups: createGroups,
|
|
193
224
|
route: createRoute,
|
|
194
|
-
routes,
|
|
225
|
+
routes: createGroupRoutes(),
|
|
195
226
|
job: createJob,
|
|
196
227
|
jobs,
|
|
197
228
|
identity: identityFactories,
|
|
@@ -204,7 +235,7 @@ const createSurface = () => {
|
|
|
204
235
|
* `kizuna generate` writes, which is what every name on `k` is checked against
|
|
205
236
|
* and what types everything a handler receives.
|
|
206
237
|
*
|
|
207
|
-
* `k.route` declares a route with its handler, `k.routes`
|
|
238
|
+
* `k.route` declares a route with its handler, `k.routes` files them into groups, and
|
|
208
239
|
* `k.job` and `k.jobs` do the same for jobs.
|
|
209
240
|
* `defineConfig` assembles them.
|
|
210
241
|
*
|
|
@@ -220,6 +251,11 @@ var Kizuna = class {
|
|
|
220
251
|
*/
|
|
221
252
|
static model = createModel;
|
|
222
253
|
/**
|
|
254
|
+
* Brand a schema, so the server and every generated client type its values
|
|
255
|
+
* as that brand.
|
|
256
|
+
*/
|
|
257
|
+
static brand = createBrand;
|
|
258
|
+
/**
|
|
223
259
|
* Declare the permissions callers hold, as a catalog of resources and the
|
|
224
260
|
* verbs each allows.
|
|
225
261
|
*/
|
|
@@ -277,6 +313,7 @@ const readToolCalls = (messages) => {
|
|
|
277
313
|
case "tool_call": {
|
|
278
314
|
const call = at(data.id, data.name);
|
|
279
315
|
call.input = data.input;
|
|
316
|
+
if (data.needsApproval === true && call.state === "running") call.state = "needs-approval";
|
|
280
317
|
break;
|
|
281
318
|
}
|
|
282
319
|
case "tool_result": {
|
|
@@ -298,7 +335,7 @@ const readToolCalls = (messages) => {
|
|
|
298
335
|
//#endregion
|
|
299
336
|
//#region src/api-definition.ts
|
|
300
337
|
/**
|
|
301
|
-
* Internal helper that builds a {@link ApiDefinition} from routes,
|
|
338
|
+
* Internal helper that builds a {@link ApiDefinition} from routes, groups, identities,
|
|
302
339
|
* and issue codes. Called by `defineConfig`. Not part of the public surface;
|
|
303
340
|
* author contracts through `k`.
|
|
304
341
|
*/
|
|
@@ -309,7 +346,7 @@ function buildApiDefinition(config) {
|
|
|
309
346
|
plugins: config.plugins,
|
|
310
347
|
jobs: config.jobs,
|
|
311
348
|
jobsConfig: config.jobsConfig,
|
|
312
|
-
|
|
349
|
+
groups: config.groups,
|
|
313
350
|
securitySchemes: config.securitySchemes,
|
|
314
351
|
requestContext: config.requestContext,
|
|
315
352
|
validation: config.validation
|
|
@@ -402,18 +439,19 @@ const handlersFrom = (declarations) => {
|
|
|
402
439
|
*/
|
|
403
440
|
const buildApi = (contract, implementations, adapter) => {
|
|
404
441
|
warnUnsupportedJobOptions(contract.jobs, implementations.jobTransport);
|
|
405
|
-
const
|
|
442
|
+
const assembled = assembleApi(contract, {
|
|
406
443
|
router: routerFromRoutes(contract.routes),
|
|
407
444
|
guards: implementations.guards,
|
|
408
445
|
requestContext: implementations.requestContext,
|
|
409
446
|
plugins: implementations.plugins
|
|
410
|
-
};
|
|
411
|
-
const api = Object.assign(
|
|
447
|
+
});
|
|
448
|
+
const api = Object.assign(assembled, contract, { [JOBS_META]: contract.jobs ? {
|
|
412
449
|
jobs: contract.jobs,
|
|
413
450
|
handlers: handlersFrom(contract.jobs),
|
|
414
451
|
config: contract.jobsConfig,
|
|
415
452
|
transport: implementations.jobTransport,
|
|
416
|
-
onError: implementations.onJobError
|
|
453
|
+
onError: implementations.onJobError,
|
|
454
|
+
plugins: pluginExportsOf(assembled)
|
|
417
455
|
} : void 0 });
|
|
418
456
|
api.mount = (...args) => {
|
|
419
457
|
if (!adapter) throw new Error("This api has no adapter to mount on. Name one under `adapter` in `defineConfig`.");
|
|
@@ -511,6 +549,15 @@ const handlersOf = (declarations, key) => {
|
|
|
511
549
|
return handlers;
|
|
512
550
|
};
|
|
513
551
|
/**
|
|
552
|
+
* Throw on a route in a group the config does not declare.
|
|
553
|
+
*/
|
|
554
|
+
const assertDeclaredGroups = (routes, groups) => {
|
|
555
|
+
for (const { routeKey, routeGroups } of flattenRoutes(routes)) for (const group of routeGroups) {
|
|
556
|
+
if (groups?.groups.has(group)) continue;
|
|
557
|
+
throw new Error(groups === void 0 ? `Route '${routeKey}' is filed under the group '${group}', but the config declares no groups. Pass \`groups\` to defineConfig.` : `Route '${routeKey}' is filed under the group '${group}', which \`groups\` does not declare.`);
|
|
558
|
+
}
|
|
559
|
+
};
|
|
560
|
+
/**
|
|
514
561
|
* Everything kizuna knows about one API, written in `kizuna.config.ts`. Every
|
|
515
562
|
* route's `auth` resolves onto its `security`, `roles` and `requires`, the
|
|
516
563
|
* routes, jobs, tools and plugins are checked against one another, and the
|
|
@@ -530,17 +577,29 @@ const handlersOf = (declarations, key) => {
|
|
|
530
577
|
const defineConfig = (options) => {
|
|
531
578
|
const guardSchema = options.auth?.guardSchema;
|
|
532
579
|
if (guardSchema) assertFillableGuardSchema(guardSchema);
|
|
533
|
-
const routes = options.routes ??
|
|
580
|
+
const routes = assembleRoutes(options.routes ?? []);
|
|
534
581
|
const jobs = options.jobs;
|
|
535
582
|
const identities = options.auth?.identities;
|
|
536
|
-
const
|
|
583
|
+
const apiReference = createApiReference();
|
|
584
|
+
const plugins = resolvePlugins(options.plugins, apiReference.api);
|
|
585
|
+
const pluginRoutes = pluginRouteTree(plugins);
|
|
537
586
|
assertNoPathCollisions([
|
|
538
587
|
...routeClaims(routes),
|
|
539
|
-
...routeClaims(
|
|
588
|
+
...routeClaims(pluginRoutes, "Plugin route"),
|
|
540
589
|
...jobClaims(jobs, options.jobRunner)
|
|
541
590
|
]);
|
|
591
|
+
assertJobRunner(jobs, options.jobRunner);
|
|
542
592
|
assertValidDeprecationDates(routes);
|
|
543
|
-
assertValidDeprecationDates(
|
|
593
|
+
assertValidDeprecationDates(pluginRoutes);
|
|
594
|
+
assertDeclaredGroups(routes, options.groups);
|
|
595
|
+
for (const { route, routeKey } of flattenRoutes(pluginRoutes)) {
|
|
596
|
+
if (route.tool !== void 0 && route.tool !== false) throw new Error(`Plugin route '${routeKey}' declares \`tool\`. Plugin routes are hidden, so they never publish.`);
|
|
597
|
+
route.hidden = true;
|
|
598
|
+
}
|
|
599
|
+
for (const { route, routeKey } of [...flattenRoutes(routes), ...flattenRoutes(pluginRoutes)]) {
|
|
600
|
+
if (route.hidden === true && route.tool !== void 0 && route.tool !== false) throw new Error(`Route '${routeKey}' is \`hidden\` and declares \`tool\`. A hidden route never publishes, so remove one of them.`);
|
|
601
|
+
if (route.rawBody === true && route.contentType === "multipart/form-data") throw new Error(`Route '${routeKey}' declares \`rawBody\` on a \`multipart/form-data\` body. A multipart body is read as a stream of parts, so kizuna cannot keep it as text. Remove \`rawBody\`, or take the body as JSON.`);
|
|
602
|
+
}
|
|
544
603
|
const declaresIdentities = Object.keys(identities ?? {}).length > 0;
|
|
545
604
|
for (const { route, routeKey } of flattenRoutes(routes)) {
|
|
546
605
|
if (route.auth === void 0) {
|
|
@@ -550,13 +609,21 @@ const defineConfig = (options) => {
|
|
|
550
609
|
}
|
|
551
610
|
resolveRouteAuth(route, route.auth, identities, routeKey);
|
|
552
611
|
}
|
|
612
|
+
for (const { route, routeKey } of flattenRoutes(pluginRoutes)) {
|
|
613
|
+
if (route.auth === void 0) {
|
|
614
|
+
route.security = [];
|
|
615
|
+
continue;
|
|
616
|
+
}
|
|
617
|
+
resolveRouteAuth(route, route.auth, identities, routeKey);
|
|
618
|
+
}
|
|
553
619
|
injectGuardResponses(routes, identities, guardSchema);
|
|
620
|
+
injectGuardResponses(pluginRoutes, identities, guardSchema);
|
|
554
621
|
assertValidCache(routes);
|
|
555
|
-
assertValidCache(
|
|
622
|
+
assertValidCache(pluginRoutes);
|
|
556
623
|
const contract = buildApiDefinition({
|
|
557
624
|
routes,
|
|
558
625
|
jobs,
|
|
559
|
-
|
|
626
|
+
groups: options.groups,
|
|
560
627
|
securitySchemes: identities,
|
|
561
628
|
guardSchema,
|
|
562
629
|
requestContext: options.requestContext,
|
|
@@ -569,14 +636,19 @@ const defineConfig = (options) => {
|
|
|
569
636
|
if (guards?.[name] !== void 0) continue;
|
|
570
637
|
throw new Error(`Identity '${name}' has no guard. Add \`.guard(...)\` to its declaration, so something authenticates it.`);
|
|
571
638
|
}
|
|
639
|
+
const api = buildApi(contract, {
|
|
640
|
+
guards,
|
|
641
|
+
requestContext: handlersOf(options.requestContext, RESOLVER),
|
|
642
|
+
jobTransport: options.jobRunner?.transport,
|
|
643
|
+
onJobError: options.jobRunner?.onError
|
|
644
|
+
}, options.adapter);
|
|
645
|
+
apiReference.bind(api);
|
|
646
|
+
for (const plugin of Object.values(plugins)) plugin.validate?.();
|
|
572
647
|
return {
|
|
573
|
-
api
|
|
574
|
-
guards,
|
|
575
|
-
requestContext: handlersOf(options.requestContext, RESOLVER),
|
|
576
|
-
jobTransport: options.jobRunner?.transport,
|
|
577
|
-
onJobError: options.jobRunner?.onError
|
|
578
|
-
}, options.adapter),
|
|
648
|
+
api,
|
|
579
649
|
clients: options.clients ?? [],
|
|
650
|
+
generators: Object.values(plugins).flatMap((plugin) => plugin.generators),
|
|
651
|
+
diff: options.diff,
|
|
580
652
|
typescript: options.typescript
|
|
581
653
|
};
|
|
582
654
|
};
|
|
@@ -592,8 +664,10 @@ const apiEntries = (module) => {
|
|
|
592
664
|
return [["default", {
|
|
593
665
|
api: config.api,
|
|
594
666
|
clients: config.clients ?? [],
|
|
595
|
-
|
|
667
|
+
generators: config.generators ?? [],
|
|
668
|
+
typescript: config.typescript,
|
|
669
|
+
diff: config.diff
|
|
596
670
|
}]];
|
|
597
671
|
};
|
|
598
672
|
//#endregion
|
|
599
|
-
export { AUTO_GUARD_BRAND, AUTO_GUARD_WRITTEN_BRAND, AUTO_RESPONSES_BRAND, DECLARATION, DispatchFailedSchema, DispatchResultSchema, EVENT_STREAM_MEDIA_TYPE, GUARD, HANDLER_CONTEXT_BRAND, JobDispatchError, JobInputError, Kizuna, METHODS, RESOLVER, ResponseError, STATUS_TITLES, apiEntries, assertCanonicalResourceUri, assertValidSchedule, authorizationServerIssuer, buildPath, buildProtectedResourceMetadata, createJobRunner,
|
|
673
|
+
export { AUTO_GUARD_BRAND, AUTO_GUARD_WRITTEN_BRAND, AUTO_RESPONSES_BRAND, DECLARATION, DispatchFailedSchema, DispatchResultSchema, EVENT_STREAM_MEDIA_TYPE, GUARD, HANDLER_CONTEXT_BRAND, JobDispatchError, JobInputError, Kizuna, METHODS, RESOLVER, ROUTES_GROUP, ResponseError, STATUS_TITLES, apiEntries, assertCanonicalResourceUri, assertValidSchedule, authorizationServerIssuer, buildPath, buildProtectedResourceMetadata, createJobRunner, cron, declaredScopes, defineConfig, defineJobTransport, definePlugin, dispatchDueJobs, dispatchSucceeded, dueJobs, dueSchedules, expandStreamTools, failedJobs, firesBetween, flattenJobs, getHeaderValue, getStatusText, isCompiledJob, isJobDefinition, isNamedStream, isPermissions, isProblemDetails, isRoles, isRouteDefinition, isSecurityScheme, isStreamResponse, isValidationError, isZodSchema, jobAt, jobFnAt, nextRun, nextRuns, parseCron, parsePath, problemDetails, problemFromBody, readToolCalls, routeStreams, scheduleExpression, scheduleTimezone, soleStreamResponse, streamContentType, streamMode, streamStatuses, toolEvents };
|
package/dist/jobs-entry.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const
|
|
3
|
-
const require_adapter = require("./adapter-
|
|
2
|
+
const require_plugin_server = require("./plugin-server-kUsK7thV.cjs");
|
|
3
|
+
const require_adapter = require("./adapter-ClaFZoab.cjs");
|
|
4
4
|
//#region src/start-jobs.ts
|
|
5
5
|
/**
|
|
6
6
|
* The dedupe key an occurrence gets. Every instance ticking the same minute
|
|
@@ -25,7 +25,7 @@ const startJobs = (api, options) => {
|
|
|
25
25
|
const logger = options?.logger ?? console;
|
|
26
26
|
const meta = api?.[require_adapter.JOBS_META];
|
|
27
27
|
if (!meta) throw new Error("startJobs was given an api with no jobs. Declare them with `k.jobs` and name them under `jobs` in `defineConfig`.");
|
|
28
|
-
const scheduled =
|
|
28
|
+
const scheduled = require_plugin_server.flattenJobs(meta.jobs).filter(({ jobKey, job }) => {
|
|
29
29
|
if (job.schedule === void 0) return false;
|
|
30
30
|
if (options?.only && !options.only.includes(jobKey)) return false;
|
|
31
31
|
return !options?.exclude?.includes(jobKey);
|
|
@@ -37,8 +37,8 @@ const startJobs = (api, options) => {
|
|
|
37
37
|
if (transport?.register) {
|
|
38
38
|
const schedules = scheduled.map(({ jobKey, schedule }) => ({
|
|
39
39
|
job: jobKey,
|
|
40
|
-
cron:
|
|
41
|
-
timezone:
|
|
40
|
+
cron: require_plugin_server.scheduleExpression(schedule),
|
|
41
|
+
timezone: require_plugin_server.scheduleTimezone(schedule)
|
|
42
42
|
}));
|
|
43
43
|
Promise.resolve(transport.register(schedules)).catch((error) => {
|
|
44
44
|
logger.error(`[kizuna] The "${transport.name}" transport could not take the schedules over:`, error);
|
|
@@ -51,9 +51,9 @@ const startJobs = (api, options) => {
|
|
|
51
51
|
let stopped = false;
|
|
52
52
|
const scheduleNext = (jobKey, schedule, from) => {
|
|
53
53
|
if (stopped) return;
|
|
54
|
-
const occurrence =
|
|
54
|
+
const occurrence = require_plugin_server.nextRun(schedule, from);
|
|
55
55
|
if (occurrence === void 0) {
|
|
56
|
-
logger.warn(`[kizuna] Job "${jobKey}" has a schedule that never fires: ${
|
|
56
|
+
logger.warn(`[kizuna] Job "${jobKey}" has a schedule that never fires: ${require_plugin_server.scheduleExpression(schedule)}`);
|
|
57
57
|
return;
|
|
58
58
|
}
|
|
59
59
|
const timer = setTimeout(() => {
|
|
@@ -76,8 +76,8 @@ const startJobs = (api, options) => {
|
|
|
76
76
|
};
|
|
77
77
|
const now = /* @__PURE__ */ new Date();
|
|
78
78
|
for (const { jobKey, schedule } of scheduled) {
|
|
79
|
-
const occurrence =
|
|
80
|
-
logger.log(`[kizuna] ${jobKey} on "${
|
|
79
|
+
const occurrence = require_plugin_server.nextRun(schedule, now);
|
|
80
|
+
logger.log(`[kizuna] ${jobKey} on "${require_plugin_server.scheduleExpression(schedule)}"` + (occurrence ? `, next at ${occurrence.toISOString()}` : ", which never fires"));
|
|
81
81
|
scheduleNext(jobKey, schedule, now);
|
|
82
82
|
}
|
|
83
83
|
return { stop: () => {
|
|
@@ -111,7 +111,7 @@ const startJobWorker = async (api, options) => {
|
|
|
111
111
|
if (!runner) return void 0;
|
|
112
112
|
const bound = require_adapter.boundJobKeys(meta);
|
|
113
113
|
const jobs = [];
|
|
114
|
-
for (const { jobKey } of
|
|
114
|
+
for (const { jobKey } of require_plugin_server.flattenJobs(meta.jobs)) {
|
|
115
115
|
if (options?.only && !options.only.includes(jobKey)) continue;
|
|
116
116
|
if (options?.exclude?.includes(jobKey)) continue;
|
|
117
117
|
if (!bound.has(jobKey)) {
|
|
@@ -151,6 +151,7 @@ const stripTrailingSlash = (url) => url.endsWith("/") ? url.slice(0, -1) : url;
|
|
|
151
151
|
const startJobsDevRunner = (contract, options) => {
|
|
152
152
|
const logger = options.logger ?? console;
|
|
153
153
|
if (process.env.NODE_ENV === "production") logger.warn("[kizuna/schedule] startJobsDevRunner is running with NODE_ENV=production. It ticks on an interval held in memory, so any tick during a restart or deploy is missed silently. Use your platform scheduler in production.");
|
|
154
|
+
if (contract.jobsConfig?.mode === "in-process") throw new Error("[kizuna/schedule] startJobsDevRunner ticks the dispatch endpoint, which `mode: 'in-process'` does not serve. Run the schedules in this process with `startJobs` instead.");
|
|
154
155
|
const method = contract.jobsConfig?.method ?? "POST";
|
|
155
156
|
const path = `${options.basePath ?? ""}${contract.jobsConfig?.path ?? "/jobs"}/dispatch`;
|
|
156
157
|
const url = `${stripTrailingSlash(options.baseUrl)}${path}`;
|
|
@@ -171,7 +172,7 @@ const startJobsDevRunner = (contract, options) => {
|
|
|
171
172
|
});
|
|
172
173
|
}, intervalMs);
|
|
173
174
|
timer.unref?.();
|
|
174
|
-
const scheduled =
|
|
175
|
+
const scheduled = require_plugin_server.flattenJobs(contract.jobs ?? {}).filter(({ job }) => job.schedule !== void 0).length;
|
|
175
176
|
logger.warn(`[kizuna/schedule] Dev runner ticking ${method} ${path} every ${intervalMs}ms for ${scheduled} scheduled job(s). Ticks are missed while the process is down.`);
|
|
176
177
|
return {
|
|
177
178
|
stop: () => {
|
package/dist/jobs-entry.d.cts
CHANGED
package/dist/jobs-entry.d.mts
CHANGED
package/dist/jobs-entry.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { D as jobRunnerFrom,
|
|
1
|
+
import { D as scheduleExpression, O as scheduleTimezone, m as flattenJobs, w as nextRun } from "./plugin-server-BztlE1fz.mjs";
|
|
2
|
+
import { D as jobRunnerFrom, J as jobFnAt, h as boundJobKeys, o as JOBS_META } from "./adapter-BSqNrxhq.mjs";
|
|
3
3
|
//#region src/start-jobs.ts
|
|
4
4
|
/**
|
|
5
5
|
* The dedupe key an occurrence gets. Every instance ticking the same minute
|
|
@@ -150,6 +150,7 @@ const stripTrailingSlash = (url) => url.endsWith("/") ? url.slice(0, -1) : url;
|
|
|
150
150
|
const startJobsDevRunner = (contract, options) => {
|
|
151
151
|
const logger = options.logger ?? console;
|
|
152
152
|
if (process.env.NODE_ENV === "production") logger.warn("[kizuna/schedule] startJobsDevRunner is running with NODE_ENV=production. It ticks on an interval held in memory, so any tick during a restart or deploy is missed silently. Use your platform scheduler in production.");
|
|
153
|
+
if (contract.jobsConfig?.mode === "in-process") throw new Error("[kizuna/schedule] startJobsDevRunner ticks the dispatch endpoint, which `mode: 'in-process'` does not serve. Run the schedules in this process with `startJobs` instead.");
|
|
153
154
|
const method = contract.jobsConfig?.method ?? "POST";
|
|
154
155
|
const path = `${options.basePath ?? ""}${contract.jobsConfig?.path ?? "/jobs"}/dispatch`;
|
|
155
156
|
const url = `${stripTrailingSlash(options.baseUrl)}${path}`;
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
let zod = require("zod");
|
|
2
|
+
//#region src/types.ts
|
|
3
|
+
const METHODS = [
|
|
4
|
+
"GET",
|
|
5
|
+
"HEAD",
|
|
6
|
+
"POST",
|
|
7
|
+
"PUT",
|
|
8
|
+
"PATCH",
|
|
9
|
+
"DELETE",
|
|
10
|
+
"OPTIONS"
|
|
11
|
+
];
|
|
12
|
+
/**
|
|
13
|
+
* Key under which every declaration says what it is, so `kizuna generate` can
|
|
14
|
+
* tell a route from a job from any other export. A symbol, so nothing that
|
|
15
|
+
* walks a declaration's own entries sees it.
|
|
16
|
+
*/
|
|
17
|
+
const DECLARATION = Symbol.for("kizuna.declaration");
|
|
18
|
+
/**
|
|
19
|
+
* Where a declaration stores what answers it. Off the string keys, so a builder
|
|
20
|
+
* can carry both the declaration and the `handler` that attaches one.
|
|
21
|
+
*/
|
|
22
|
+
const HANDLER = Symbol.for("kizuna.handler");
|
|
23
|
+
/**
|
|
24
|
+
* Where a tree from `k.routes` carries its group's dotted path.
|
|
25
|
+
*/
|
|
26
|
+
const ROUTES_GROUP = Symbol.for("kizuna.routes.group");
|
|
27
|
+
/**
|
|
28
|
+
* Type-only key under which `defineConfig` brands each route with its resolved
|
|
29
|
+
* handler context. Never written at runtime.
|
|
30
|
+
*/
|
|
31
|
+
const HANDLER_CONTEXT_BRAND = Symbol.for("kizuna.route.handlerContext");
|
|
32
|
+
/**
|
|
33
|
+
* Type-only key under which `defineConfig` brands a guarded route with the
|
|
34
|
+
* statuses its guard answers for it. Never written at runtime.
|
|
35
|
+
*/
|
|
36
|
+
const AUTO_RESPONSES_BRAND = Symbol.for("kizuna.route.autoResponses");
|
|
37
|
+
const AUTO_GUARD_BRAND = Symbol.for("kizuna.route.guardBody");
|
|
38
|
+
const AUTO_GUARD_WRITTEN_BRAND = Symbol.for("kizuna.route.guardBodyWritten");
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region src/route.ts
|
|
41
|
+
const createRoute = (definition) => ({
|
|
42
|
+
...definition,
|
|
43
|
+
handler: (fn) => ({
|
|
44
|
+
...definition,
|
|
45
|
+
[HANDLER]: fn,
|
|
46
|
+
[DECLARATION]: "route"
|
|
47
|
+
})
|
|
48
|
+
});
|
|
49
|
+
//#endregion
|
|
50
|
+
//#region src/plugin.ts
|
|
51
|
+
const PLUGIN_ROUTES_META_KEY = Symbol.for("kizuna.plugin-routes");
|
|
52
|
+
const PLUGIN_SERVERS_META_KEY = Symbol.for("kizuna.plugin-servers");
|
|
53
|
+
/**
|
|
54
|
+
* Declare a plugin: its slug, the options an app passes it, and the `setup` that
|
|
55
|
+
* builds what it brings. Returns the function an app installs it with.
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* export const emailPlugin = definePlugin({
|
|
59
|
+
* slug: 'email',
|
|
60
|
+
* options: z.object({
|
|
61
|
+
* apiKey: z.string(),
|
|
62
|
+
* from: z.string(),
|
|
63
|
+
* }),
|
|
64
|
+
* setup: ({ options }) => {
|
|
65
|
+
* const resend = new Resend(options.apiKey);
|
|
66
|
+
*
|
|
67
|
+
* return {
|
|
68
|
+
* exports: {
|
|
69
|
+
* send: (email: Email) =>
|
|
70
|
+
* resend.emails.send({
|
|
71
|
+
* from: options.from,
|
|
72
|
+
* ...email,
|
|
73
|
+
* }),
|
|
74
|
+
* },
|
|
75
|
+
* };
|
|
76
|
+
* },
|
|
77
|
+
* });
|
|
78
|
+
*/
|
|
79
|
+
const definePlugin = (definition) => ((input) => {
|
|
80
|
+
const { slug, basePath, ...options } = input ?? {};
|
|
81
|
+
return {
|
|
82
|
+
slug: typeof slug === "string" ? slug : definition.slug,
|
|
83
|
+
...typeof basePath === "string" ? { basePath } : {},
|
|
84
|
+
definition,
|
|
85
|
+
input: options
|
|
86
|
+
};
|
|
87
|
+
});
|
|
88
|
+
/**
|
|
89
|
+
* Declare one of a plugin's routes and the handler that answers it, the way
|
|
90
|
+
* `k.route` does for an app's own.
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* check: route({
|
|
94
|
+
* method: 'GET',
|
|
95
|
+
* path: '/status',
|
|
96
|
+
* auth: false,
|
|
97
|
+
* responses: {
|
|
98
|
+
* 200: StatusSchema,
|
|
99
|
+
* },
|
|
100
|
+
* }).handler(() => ({
|
|
101
|
+
* status: 200,
|
|
102
|
+
* body: {
|
|
103
|
+
* status: 'ok',
|
|
104
|
+
* },
|
|
105
|
+
* })),
|
|
106
|
+
*/
|
|
107
|
+
const route = createRoute;
|
|
108
|
+
/**
|
|
109
|
+
* Accepts a route path, for a plugin that takes one of its routes' paths as an
|
|
110
|
+
* option.
|
|
111
|
+
*/
|
|
112
|
+
const RoutePathSchema = zod.z.custom((value) => typeof value === "string" && value.startsWith("/"), { error: "must start with /" });
|
|
113
|
+
/**
|
|
114
|
+
* Accepts exactly what a route's `auth` does, for a plugin that takes one of its
|
|
115
|
+
* routes' `auth` as an option. `defineConfig` checks the value against the app's
|
|
116
|
+
* identities.
|
|
117
|
+
*/
|
|
118
|
+
const RouteAuthSchema = zod.z.union([
|
|
119
|
+
zod.z.literal(false),
|
|
120
|
+
zod.z.string(),
|
|
121
|
+
zod.z.array(zod.z.string()),
|
|
122
|
+
zod.z.object({
|
|
123
|
+
identity: zod.z.union([zod.z.string(), zod.z.array(zod.z.string())]),
|
|
124
|
+
roles: zod.z.union([zod.z.string(), zod.z.array(zod.z.string())]).optional(),
|
|
125
|
+
requires: zod.z.record(zod.z.string(), zod.z.array(zod.z.string())).optional()
|
|
126
|
+
})
|
|
127
|
+
]);
|
|
128
|
+
/**
|
|
129
|
+
* Every plugin's routes as one tree, keyed by slug, for the adapter to walk as
|
|
130
|
+
* it walks the api's own.
|
|
131
|
+
*/
|
|
132
|
+
const pluginRouteTree = (plugins) => {
|
|
133
|
+
const tree = {};
|
|
134
|
+
for (const [slug, plugin] of Object.entries(plugins ?? {})) tree[slug] = plugin.routes;
|
|
135
|
+
return tree;
|
|
136
|
+
};
|
|
137
|
+
//#endregion
|
|
138
|
+
Object.defineProperty(exports, "AUTO_GUARD_BRAND", {
|
|
139
|
+
enumerable: true,
|
|
140
|
+
get: function() {
|
|
141
|
+
return AUTO_GUARD_BRAND;
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
Object.defineProperty(exports, "AUTO_GUARD_WRITTEN_BRAND", {
|
|
145
|
+
enumerable: true,
|
|
146
|
+
get: function() {
|
|
147
|
+
return AUTO_GUARD_WRITTEN_BRAND;
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
Object.defineProperty(exports, "AUTO_RESPONSES_BRAND", {
|
|
151
|
+
enumerable: true,
|
|
152
|
+
get: function() {
|
|
153
|
+
return AUTO_RESPONSES_BRAND;
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
Object.defineProperty(exports, "DECLARATION", {
|
|
157
|
+
enumerable: true,
|
|
158
|
+
get: function() {
|
|
159
|
+
return DECLARATION;
|
|
160
|
+
}
|
|
161
|
+
});
|
|
162
|
+
Object.defineProperty(exports, "HANDLER", {
|
|
163
|
+
enumerable: true,
|
|
164
|
+
get: function() {
|
|
165
|
+
return HANDLER;
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
Object.defineProperty(exports, "HANDLER_CONTEXT_BRAND", {
|
|
169
|
+
enumerable: true,
|
|
170
|
+
get: function() {
|
|
171
|
+
return HANDLER_CONTEXT_BRAND;
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
Object.defineProperty(exports, "METHODS", {
|
|
175
|
+
enumerable: true,
|
|
176
|
+
get: function() {
|
|
177
|
+
return METHODS;
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
Object.defineProperty(exports, "PLUGIN_ROUTES_META_KEY", {
|
|
181
|
+
enumerable: true,
|
|
182
|
+
get: function() {
|
|
183
|
+
return PLUGIN_ROUTES_META_KEY;
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
Object.defineProperty(exports, "PLUGIN_SERVERS_META_KEY", {
|
|
187
|
+
enumerable: true,
|
|
188
|
+
get: function() {
|
|
189
|
+
return PLUGIN_SERVERS_META_KEY;
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
Object.defineProperty(exports, "ROUTES_GROUP", {
|
|
193
|
+
enumerable: true,
|
|
194
|
+
get: function() {
|
|
195
|
+
return ROUTES_GROUP;
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
Object.defineProperty(exports, "RouteAuthSchema", {
|
|
199
|
+
enumerable: true,
|
|
200
|
+
get: function() {
|
|
201
|
+
return RouteAuthSchema;
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
Object.defineProperty(exports, "RoutePathSchema", {
|
|
205
|
+
enumerable: true,
|
|
206
|
+
get: function() {
|
|
207
|
+
return RoutePathSchema;
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
Object.defineProperty(exports, "createRoute", {
|
|
211
|
+
enumerable: true,
|
|
212
|
+
get: function() {
|
|
213
|
+
return createRoute;
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
Object.defineProperty(exports, "definePlugin", {
|
|
217
|
+
enumerable: true,
|
|
218
|
+
get: function() {
|
|
219
|
+
return definePlugin;
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
Object.defineProperty(exports, "pluginRouteTree", {
|
|
223
|
+
enumerable: true,
|
|
224
|
+
get: function() {
|
|
225
|
+
return pluginRouteTree;
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
Object.defineProperty(exports, "route", {
|
|
229
|
+
enumerable: true,
|
|
230
|
+
get: function() {
|
|
231
|
+
return route;
|
|
232
|
+
}
|
|
233
|
+
});
|