@aitoroses/telar 0.0.0 → 0.2.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 (94) hide show
  1. package/README.md +457 -3
  2. package/dist/compile.d.ts +48 -0
  3. package/dist/compile.js +1240 -0
  4. package/dist/contract.d.ts +109 -0
  5. package/dist/contract.js +491 -0
  6. package/dist/evaluator.d.ts +23 -0
  7. package/dist/evaluator.js +40 -0
  8. package/dist/evidence.d.ts +23 -0
  9. package/dist/evidence.js +74 -0
  10. package/dist/guide.d.ts +8 -0
  11. package/dist/guide.js +16 -0
  12. package/dist/install.d.ts +104 -0
  13. package/dist/install.js +402 -0
  14. package/dist/iso.d.ts +10 -0
  15. package/dist/iso.js +73 -0
  16. package/dist/node/build.d.ts +2 -0
  17. package/dist/node/build.js +56 -0
  18. package/dist/node/telar-module.d.ts +2 -0
  19. package/dist/node/telar-module.js +28 -0
  20. package/dist/observer.d.ts +38 -0
  21. package/dist/observer.js +53 -0
  22. package/dist/pieces.d.ts +230 -0
  23. package/dist/pieces.js +178 -0
  24. package/dist/powers.d.ts +46 -0
  25. package/dist/powers.js +126 -0
  26. package/dist/protocol.d.ts +220 -0
  27. package/dist/protocol.js +243 -0
  28. package/dist/query.d.ts +67 -0
  29. package/dist/query.js +102 -0
  30. package/dist/read.d.ts +37 -0
  31. package/dist/read.js +27 -0
  32. package/dist/runner.d.ts +113 -0
  33. package/dist/runner.js +134 -0
  34. package/dist/scenario/builder.d.ts +25 -0
  35. package/dist/scenario/builder.js +603 -0
  36. package/dist/scenario/templates.d.ts +35 -0
  37. package/dist/scenario/templates.js +64 -0
  38. package/dist/scenario/types.d.ts +432 -0
  39. package/dist/scenario/types.js +10 -0
  40. package/dist/scenario/validate.d.ts +7 -0
  41. package/dist/scenario/validate.js +19 -0
  42. package/dist/scenario.d.ts +4 -0
  43. package/dist/scenario.js +4 -0
  44. package/dist/schema.d.ts +221 -0
  45. package/dist/schema.js +227 -0
  46. package/dist/seating.d.ts +47 -0
  47. package/dist/seating.js +26 -0
  48. package/dist/send-hook.d.ts +46 -0
  49. package/dist/send-hook.js +123 -0
  50. package/dist/show.d.ts +34 -0
  51. package/dist/show.js +1 -0
  52. package/dist/source.d.ts +85 -0
  53. package/dist/source.js +104 -0
  54. package/dist/spec.d.ts +21 -0
  55. package/dist/spec.js +18 -0
  56. package/dist/standard-schema.d.ts +21 -0
  57. package/dist/standard-schema.js +1 -0
  58. package/dist/std/accuracy.d.ts +12 -0
  59. package/dist/std/accuracy.js +122 -0
  60. package/dist/std/ack.d.ts +14 -0
  61. package/dist/std/ack.js +43 -0
  62. package/dist/std/actions.d.ts +105 -0
  63. package/dist/std/actions.js +153 -0
  64. package/dist/std/brief.d.ts +36 -0
  65. package/dist/std/brief.js +78 -0
  66. package/dist/std/claude-code.d.ts +9 -0
  67. package/dist/std/claude-code.js +113 -0
  68. package/dist/std/compare.d.ts +29 -0
  69. package/dist/std/compare.js +36 -0
  70. package/dist/std/git-workspace.d.ts +44 -0
  71. package/dist/std/git-workspace.js +184 -0
  72. package/dist/std/judgment.d.ts +85 -0
  73. package/dist/std/judgment.js +462 -0
  74. package/dist/std/observe-command.d.ts +23 -0
  75. package/dist/std/observe-command.js +151 -0
  76. package/dist/std/observe-github-checks.d.ts +24 -0
  77. package/dist/std/observe-github-checks.js +289 -0
  78. package/dist/std/observe-http-status.d.ts +27 -0
  79. package/dist/std/observe-http-status.js +193 -0
  80. package/dist/std/plan.d.ts +7 -0
  81. package/dist/std/plan.js +28 -0
  82. package/dist/std/queries.d.ts +31 -0
  83. package/dist/std/queries.js +318 -0
  84. package/dist/std/reading.d.ts +17 -0
  85. package/dist/std/reading.js +88 -0
  86. package/dist/std/schedule.d.ts +19 -0
  87. package/dist/std/schedule.js +122 -0
  88. package/dist/std.d.ts +15 -0
  89. package/dist/std.js +15 -0
  90. package/dist/types.d.ts +370 -0
  91. package/dist/types.js +1 -0
  92. package/dist/values.d.ts +81 -0
  93. package/dist/values.js +129 -0
  94. package/package.json +62 -5
package/dist/iso.js ADDED
@@ -0,0 +1,73 @@
1
+ const ISO_UTC_RE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{3}))?Z$/;
2
+ const CANONICAL_ISO_UTC_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
3
+ const DAY_MS = 86_400_000;
4
+ function daysFromCivil(year, month, day) {
5
+ const y = month <= 2 ? year - 1 : year;
6
+ const era = Math.floor(y / 400);
7
+ const yoe = y - era * 400;
8
+ const doy = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1;
9
+ const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;
10
+ return era * 146_097 + doe - 719_468;
11
+ }
12
+ function civilFromDays(days) {
13
+ const z = days + 719_468;
14
+ const era = Math.floor(z / 146_097);
15
+ const doe = z - era * 146_097;
16
+ const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36_524) - Math.floor(doe / 146_096)) / 365);
17
+ const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
18
+ const mp = Math.floor((5 * doy + 2) / 153);
19
+ const day = doy - Math.floor((153 * mp + 2) / 5) + 1;
20
+ const month = mp < 10 ? mp + 3 : mp - 9;
21
+ return [yoe + era * 400 + (month <= 2 ? 1 : 0), month, day];
22
+ }
23
+ /** Milliseconds since the epoch of an ISO-UTC instant, or undefined. Pure: telar's QuickJS has no `Date`. */
24
+ export function parseIsoUtc(value) {
25
+ const m = ISO_UTC_RE.exec(value);
26
+ if (m === null)
27
+ return undefined;
28
+ const [year, month, day, hour, minute, second] = m.slice(1, 7).map(Number);
29
+ const ms = Number(m[7] ?? "0");
30
+ if (year === undefined ||
31
+ month === undefined ||
32
+ day === undefined ||
33
+ hour === undefined ||
34
+ minute === undefined ||
35
+ second === undefined ||
36
+ month < 1 ||
37
+ month > 12 ||
38
+ day < 1 ||
39
+ hour > 23 ||
40
+ minute > 59 ||
41
+ second > 59) {
42
+ return undefined;
43
+ }
44
+ const days = daysFromCivil(year, month, day);
45
+ if (civilFromDays(days)[2] !== day)
46
+ return undefined;
47
+ return days * DAY_MS + ((hour * 60 + minute) * 60 + second) * 1000 + ms;
48
+ }
49
+ function pad(n, width = 2) {
50
+ return String(n).padStart(width, "0");
51
+ }
52
+ /** True iff `value` is the single canonical UTC form (`YYYY-MM-DDTHH:MM:SS.sssZ`) and a real instant. */
53
+ export function isCanonicalIsoUtc(value) {
54
+ return CANONICAL_ISO_UTC_RE.test(value) && parseIsoUtc(value) !== undefined;
55
+ }
56
+ export function formatIsoUtc(ms) {
57
+ const days = Math.floor(ms / DAY_MS);
58
+ const [year, month, day] = civilFromDays(days);
59
+ const rest = ms - days * DAY_MS;
60
+ const time = `${pad(Math.floor(rest / 3_600_000))}:${pad(Math.floor(rest / 60_000) % 60)}:${pad(Math.floor(rest / 1000) % 60)}.${pad(rest % 1000, 3)}`;
61
+ return `${pad(year, 4)}-${pad(month)}-${pad(day)}T${time}Z`;
62
+ }
63
+ /**
64
+ * The UTC offset of an IANA zone at an instant, in minutes, or undefined for an unknown zone.
65
+ * telar's host answers it from the tzdb bundled with the telar release.
66
+ */
67
+ export function zoneOffset(zone, epochMs) {
68
+ const host = Reflect.get(globalThis, "__telar_zone_offset");
69
+ if (typeof host !== "function")
70
+ return undefined;
71
+ const minutes = Reflect.apply(host, undefined, [zone, Math.trunc(epochMs)]);
72
+ return typeof minutes === "number" && Number.isFinite(minutes) ? minutes : undefined;
73
+ }
@@ -0,0 +1,2 @@
1
+ export declare const SDK_STAMP = "// telar-sdk ";
2
+ export declare function buildModule(entry: string): Promise<string>;
@@ -0,0 +1,56 @@
1
+ import { readFileSync } from "node:fs";
2
+ const SDK_SPECIFIERS = ["telar/spec", "telar/std", "telar/scenario"];
3
+ const ROLLDOWN_PEER = "rolldown@^1.3.4";
4
+ const SDK_PACKAGE = "@aitoroses/telar";
5
+ export const SDK_STAMP = "// telar-sdk ";
6
+ function sdkVersion() {
7
+ for (const candidate of ["../package.json", "../../package.json"]) {
8
+ try {
9
+ const manifest = JSON.parse(readFileSync(new URL(candidate, import.meta.url), "utf8"));
10
+ if (typeof manifest === "object" &&
11
+ manifest !== null &&
12
+ "name" in manifest &&
13
+ manifest.name === SDK_PACKAGE &&
14
+ "version" in manifest &&
15
+ typeof manifest.version === "string") {
16
+ return manifest.version;
17
+ }
18
+ }
19
+ catch {
20
+ continue;
21
+ }
22
+ }
23
+ throw new Error(`telar-module cannot find its own ${SDK_PACKAGE} package.json`);
24
+ }
25
+ async function loadRolldown() {
26
+ try {
27
+ return (await import("rolldown")).rolldown;
28
+ }
29
+ catch (error) {
30
+ if (error instanceof Error && "code" in error && error.code === "ERR_MODULE_NOT_FOUND") {
31
+ throw new Error(`TELAR_MODULE_NO_ROLLDOWN: telar-module bundles with rolldown, an optional peer of telar that is not installed. Fix: pnpm add -D ${ROLLDOWN_PEER}`, { cause: error });
32
+ }
33
+ throw error;
34
+ }
35
+ }
36
+ export async function buildModule(entry) {
37
+ const rolldown = await loadRolldown();
38
+ const bundle = await rolldown({
39
+ input: entry,
40
+ platform: "neutral",
41
+ external: [...SDK_SPECIFIERS],
42
+ treeshake: { moduleSideEffects: false },
43
+ checks: { unresolvedImport: false },
44
+ });
45
+ try {
46
+ const { output } = await bundle.generate({ format: "esm", minify: true });
47
+ const [chunk, ...rest] = output;
48
+ if (chunk === undefined || chunk.type !== "chunk" || rest.length > 0) {
49
+ throw new Error(`${entry} must bundle into one module`);
50
+ }
51
+ return `${SDK_STAMP}${SDK_PACKAGE}@${sdkVersion()}\n${chunk.code}`;
52
+ }
53
+ finally {
54
+ await bundle.close();
55
+ }
56
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env node
2
+ import { writeFile } from "node:fs/promises";
3
+ import { argv, exit, stderr, stdout } from "node:process";
4
+ import { buildModule } from "./build.js";
5
+ const USAGE = "usage: telar-module <entry> [--out <file>]";
6
+ async function main(args) {
7
+ const [entry, flag, out, ...rest] = args;
8
+ const outValid = flag === undefined || (flag === "--out" && out !== undefined);
9
+ if (entry === undefined || entry.startsWith("-") || !outValid || rest.length > 0) {
10
+ stderr.write(`${USAGE}\n`);
11
+ return 2;
12
+ }
13
+ try {
14
+ const code = await buildModule(entry);
15
+ if (out === undefined) {
16
+ stdout.write(code);
17
+ }
18
+ else {
19
+ await writeFile(out, code);
20
+ }
21
+ return 0;
22
+ }
23
+ catch (error) {
24
+ stderr.write(`telar-module: ${error instanceof Error ? error.message : String(error)}\n`);
25
+ return 1;
26
+ }
27
+ }
28
+ exit(await main(argv.slice(2)));
@@ -0,0 +1,38 @@
1
+ import type { Evidence, EvidenceRef } from "./evidence.js";
2
+ import type { WorldPowers } from "./powers.js";
3
+ import { type RunnerOptionValidation } from "./runner.js";
4
+ import type { StandardSchema } from "./standard-schema.js";
5
+ export type { Evidence, EvidenceRef };
6
+ export type ObserverId = `${string}/observe/${string}/${number}`;
7
+ /** What the world says about a check: `ok: null` means "not yet" and writes nothing. */
8
+ export interface Observed {
9
+ readonly ok: boolean | null;
10
+ readonly evidence?: Evidence;
11
+ }
12
+ export interface ObserveInput<Params> {
13
+ readonly check: string;
14
+ readonly args: Readonly<Record<string, unknown>>;
15
+ readonly params: Params;
16
+ }
17
+ export interface DefineObserverInput<Id extends ObserverId, Params> {
18
+ readonly id: Id;
19
+ readonly params: StandardSchema<Params>;
20
+ readonly observe: (input: ObserveInput<Params>, powers: WorldPowers) => Observed;
21
+ }
22
+ export interface AnyObserver {
23
+ readonly id: ObserverId;
24
+ readonly admitParams: (raw: unknown) => RunnerOptionValidation<unknown>;
25
+ readonly dispatch: (args: unknown, powers: WorldPowers) => Observed;
26
+ }
27
+ export interface Observer<Id extends ObserverId = ObserverId, Params = unknown> extends AnyObserver {
28
+ readonly id: Id;
29
+ readonly params: StandardSchema<Params>;
30
+ readonly observe: DefineObserverInput<Id, Params>["observe"];
31
+ }
32
+ export declare class ObserverError extends Error {
33
+ readonly name: string;
34
+ readonly code: string;
35
+ constructor(code: string, message: string);
36
+ }
37
+ export declare function isValidObserverId(id: string): boolean;
38
+ export declare function defineObserver<const Id extends ObserverId, Params>(input: DefineObserverInput<Id, Params>): Observer<Id, Params>;
@@ -0,0 +1,53 @@
1
+ import { validateStandard } from "./runner.js";
2
+ export class ObserverError extends Error {
3
+ name = "ObserverError";
4
+ code;
5
+ constructor(code, message) {
6
+ super(message);
7
+ this.code = code;
8
+ }
9
+ }
10
+ const OBSERVER_ID_RE = /^[a-z][a-z0-9.-]*\/observe\/[a-z][a-z0-9-]*\/[1-9][0-9]*$/;
11
+ export function isValidObserverId(id) {
12
+ return OBSERVER_ID_RE.test(id);
13
+ }
14
+ function isRec(value) {
15
+ return typeof value === "object" && value !== null && !Array.isArray(value);
16
+ }
17
+ function issueText(issues) {
18
+ const first = issues[0];
19
+ if (first === undefined)
20
+ return "invalid";
21
+ return first.path.length > 0 ? `${first.path.join(".")}: ${first.message}` : first.message;
22
+ }
23
+ export function defineObserver(input) {
24
+ if (!isValidObserverId(input.id)) {
25
+ throw new ObserverError("INVALID_OBSERVER", `observer id ${JSON.stringify(input.id)} must match <namespace>/observe/<name>/<v>`);
26
+ }
27
+ const admitParams = (raw) => {
28
+ const checked = validateStandard(input.params, raw === undefined ? {} : raw);
29
+ if (checked.ok === "async") {
30
+ throw new ObserverError("INVALID_OBSERVER", `observer ${input.id} params must validate synchronously`);
31
+ }
32
+ return checked;
33
+ };
34
+ const dispatch = (args, powers) => {
35
+ const check = isRec(args) ? args["check"] : undefined;
36
+ const checkArgs = isRec(args) ? args["args"] : undefined;
37
+ if (typeof check !== "string" || !isRec(checkArgs)) {
38
+ throw new ObserverError("INVALID_INPUT", "observer:observe requires a check id and its args");
39
+ }
40
+ const params = admitParams(isRec(args) ? args["params"] : undefined);
41
+ if (!params.ok) {
42
+ throw new ObserverError("INVALID_OBSERVER_PARAMS", issueText(params.issues));
43
+ }
44
+ return input.observe({ check, args: checkArgs, params: params.value }, powers);
45
+ };
46
+ return Object.freeze({
47
+ id: input.id,
48
+ params: input.params,
49
+ observe: input.observe,
50
+ admitParams,
51
+ dispatch,
52
+ });
53
+ }
@@ -0,0 +1,230 @@
1
+ import type { EvaluatorId, StdEvaluatorId } from "./evaluator.js";
2
+ import type { Guide } from "./guide.js";
3
+ import type { WorldPowers } from "./powers.js";
4
+ import type { AnyContract, AnyStructContract, FieldHandlesOf, FieldSchemaMap, Infer, OptionalType, StructContract, StructFieldsOfContract } from "./schema.js";
5
+ import type { BriefPiece, CheckObserveDecl, JsonValue, MessageFieldName, NonEmpty, Rec, ViewKind } from "./types.js";
6
+ import type { ArgInput, FieldRef, LiteralRef } from "./values.js";
7
+ export type SeatLabelsDef = Readonly<Record<string, NonEmpty<string>>>;
8
+ export type NoSeatLabels = {
9
+ readonly [key: string]: never;
10
+ };
11
+ export interface Role<Name extends string = string, Labels extends SeatLabelsDef = SeatLabelsDef> {
12
+ readonly kind: "role";
13
+ readonly name: Name;
14
+ readonly view: ViewKind;
15
+ readonly includePredecessor?: boolean;
16
+ readonly seatLabels?: Labels;
17
+ readonly guide?: string;
18
+ readonly brief?: readonly BriefPiece[];
19
+ }
20
+ export type AnyRole = Role;
21
+ export interface RoleViewOverride {
22
+ readonly kind: "role-view";
23
+ readonly role: AnyRole;
24
+ readonly view: ViewKind;
25
+ readonly includePredecessor?: boolean;
26
+ }
27
+ export interface RoleBriefOverride {
28
+ readonly kind: "role-brief";
29
+ readonly role: AnyRole;
30
+ readonly pieces: readonly BriefPiece[];
31
+ }
32
+ export interface DelegationInput {
33
+ readonly role: AnyRole;
34
+ readonly for: AnyRole;
35
+ }
36
+ export interface AuthClass<Name extends string = string> {
37
+ readonly kind: "class";
38
+ readonly name: Name;
39
+ readonly authorized: NonEmpty<AnyRole>;
40
+ readonly delegatedWhenAway?: readonly DelegationInput[];
41
+ readonly requires: readonly AnyCheck[];
42
+ readonly admitsImpossible: boolean;
43
+ readonly guide?: string;
44
+ }
45
+ export type AnyAuthClass = AuthClass;
46
+ export type ArgsForContract<C extends AnyStructContract> = C extends StructContract<string, infer F> ? {
47
+ readonly [K in keyof F as F[K] extends OptionalType ? never : K]: ArgInput<Infer<F[K]>>;
48
+ } & {
49
+ readonly [K in keyof F as F[K] extends OptionalType ? K : never]?: ArgInput<F[K] extends OptionalType<infer Inner> ? Infer<Inner> : never>;
50
+ } : never;
51
+ export interface CheckNeedNode {
52
+ readonly kind: "check-need";
53
+ readonly check: AnyCheck;
54
+ readonly args: Rec<unknown>;
55
+ readonly guide?: string;
56
+ }
57
+ export interface Check<Id extends string = string, In extends AnyStructContract = AnyStructContract> {
58
+ readonly kind: "check";
59
+ readonly id: Id;
60
+ readonly input: In;
61
+ readonly evaluator?: string;
62
+ readonly observe?: CheckObserveDecl;
63
+ readonly guide?: string;
64
+ (args: ArgsForContract<In>, opts?: {
65
+ readonly guide?: Guide | ((input: FieldHandlesOf<StructFieldsOfContract<In>>) => Guide) | undefined;
66
+ }): CheckNeedNode;
67
+ }
68
+ export type AnyCheck = Check;
69
+ export interface CallActionEffectNode {
70
+ readonly kind: "call-action-effect";
71
+ readonly action: AnyAction;
72
+ readonly args: Rec<unknown>;
73
+ }
74
+ export interface Action<Id extends string = string, In extends AnyStructContract = AnyStructContract, Out extends AnyContract = AnyContract> {
75
+ readonly kind: "action";
76
+ readonly id: Id;
77
+ readonly input: In;
78
+ readonly output: Out;
79
+ readonly class?: AnyAuthClass;
80
+ readonly revert?: AnyAction;
81
+ readonly release?: AnyAction;
82
+ readonly reversible?: boolean;
83
+ readonly guide?: string;
84
+ run?(input: Infer<In>, powers: WorldPowers): Infer<Out>;
85
+ (args: ArgsForContract<In>): CallActionEffectNode;
86
+ }
87
+ export type AnyAction = Action;
88
+ export interface RunnableAction<Id extends string = string, In extends AnyStructContract = AnyStructContract, Out extends AnyContract = AnyContract> extends Action<Id, In, Out> {
89
+ run(input: Infer<In>, powers: WorldPowers): Infer<Out>;
90
+ }
91
+ export interface MessageArgRef {
92
+ readonly kind: "message-arg";
93
+ readonly field: MessageFieldName;
94
+ }
95
+ export type MissArgInput = MessageArgRef | LiteralRef | JsonValue;
96
+ export interface ProtocolTarget {
97
+ readonly kind: "protocol" | "protocol-ref";
98
+ readonly name: string;
99
+ }
100
+ export type MissActionDef = {
101
+ readonly kind: "redeliver";
102
+ } | {
103
+ readonly kind: "open-on-miss";
104
+ readonly protocol: ProtocolTarget;
105
+ readonly forRole: AnyRole;
106
+ readonly data: Rec<MissArgInput>;
107
+ };
108
+ export type AckDef = {
109
+ readonly kind: "none";
110
+ } | {
111
+ readonly kind: "read";
112
+ readonly within: number;
113
+ readonly onMiss: NonEmpty<MissActionDef>;
114
+ } | {
115
+ readonly kind: "answer";
116
+ readonly shape: "ack" | AnyContract;
117
+ readonly within: number;
118
+ readonly onMiss: NonEmpty<MissActionDef>;
119
+ };
120
+ export interface MessageKind<Name extends string = string, P extends AnyStructContract = AnyStructContract> {
121
+ readonly kind: "message-kind";
122
+ readonly name: Name;
123
+ readonly payload: P;
124
+ readonly template: Guide;
125
+ readonly ack: AckDef;
126
+ }
127
+ export type AnyMessageKind = MessageKind;
128
+ export interface BoundByFieldInput {
129
+ readonly field: string | FieldRef;
130
+ readonly values: Rec<number>;
131
+ }
132
+ export interface BoundSpecInput {
133
+ readonly max: number;
134
+ readonly byField?: BoundByFieldInput | undefined;
135
+ readonly onLimit: AnyRole;
136
+ readonly guide?: Guide | undefined;
137
+ }
138
+ export interface InlineBound {
139
+ readonly kind: "inline-bound";
140
+ readonly spec: BoundSpecInput;
141
+ }
142
+ export interface NamedBound<Name extends string = string> {
143
+ readonly kind: "named-bound";
144
+ readonly name: Name;
145
+ readonly spec: BoundSpecInput;
146
+ }
147
+ export type AnyNamedBound = NamedBound;
148
+ export type StepBoundInput = InlineBound | AnyNamedBound;
149
+ export declare function role<const Name extends string, const Labels extends SeatLabelsDef = NoSeatLabels>(name: Name, def: {
150
+ readonly view: ViewKind;
151
+ readonly includePredecessor?: boolean | undefined;
152
+ readonly seatLabels?: Labels | undefined;
153
+ readonly guide?: Guide | undefined;
154
+ readonly brief?: readonly BriefPiece[] | undefined;
155
+ }): Role<Name, Labels>;
156
+ export declare function roleView(target: AnyRole, view: ViewKind, opts?: {
157
+ readonly includePredecessor?: boolean | undefined;
158
+ }): RoleViewOverride;
159
+ export declare function roleBrief(target: AnyRole, pieces: readonly BriefPiece[]): RoleBriefOverride;
160
+ export declare function defineClass<const Name extends string>(name: Name, def: {
161
+ readonly authorized: NonEmpty<AnyRole>;
162
+ readonly delegatedWhenAway?: readonly DelegationInput[] | undefined;
163
+ readonly requires?: readonly AnyCheck[] | undefined;
164
+ readonly admitsImpossible?: boolean | undefined;
165
+ readonly guide?: Guide | undefined;
166
+ }): AuthClass<Name>;
167
+ export declare function check<const Id extends string, InName extends string, F extends FieldSchemaMap>(id: Id, def: {
168
+ readonly input: StructContract<InName, F>;
169
+ readonly evaluator?: EvaluatorId | StdEvaluatorId | undefined;
170
+ readonly observe?: CheckObserveDecl | undefined;
171
+ readonly guide?: Guide | ((input: FieldHandlesOf<F>) => Guide) | undefined;
172
+ }): Check<Id, StructContract<InName, F>>;
173
+ export type ActionId = `${string}/action/${string}/${number}`;
174
+ export declare class ActionError extends Error {
175
+ readonly name: string;
176
+ readonly code: string;
177
+ constructor(code: string, detail: string);
178
+ }
179
+ export declare function isValidActionId(id: string): boolean;
180
+ interface ActionShape<Id extends ActionId, InName extends string, F extends FieldSchemaMap, Out> {
181
+ readonly id: Id;
182
+ readonly input: StructContract<InName, F>;
183
+ readonly output: Out;
184
+ readonly class?: AnyAuthClass | undefined;
185
+ readonly revert?: AnyAction | undefined;
186
+ readonly release?: AnyAction | undefined;
187
+ readonly reversible?: boolean | undefined;
188
+ readonly guide?: Guide | ((input: FieldHandlesOf<F>) => Guide) | undefined;
189
+ }
190
+ /** The step handle of an action the host runs itself: the std actions still in Rust. */
191
+ export declare function declareAction<const Id extends ActionId, InName extends string, F extends FieldSchemaMap, Out extends AnyContract>(def: ActionShape<Id, InName, F, Out>): Action<Id, StructContract<InName, F>, Out>;
192
+ /**
193
+ * An action is its step handle and its implementation. List it in `defineInstallation({ actions })`;
194
+ * the host calls `run` with the requested input and records what it returns. Refuse with
195
+ * `throw new ActionError(code, message)`.
196
+ */
197
+ export declare function defineAction<const Id extends ActionId, InName extends string, F extends FieldSchemaMap, Out extends AnyContract>(def: ActionShape<Id, InName, F, Out> & {
198
+ readonly run: (input: Infer<StructContract<InName, F>>, powers: WorldPowers) => Infer<Out>;
199
+ }): RunnableAction<Id, StructContract<InName, F>, Out>;
200
+ export declare const msg: {
201
+ readonly id: MessageArgRef;
202
+ readonly kind: MessageArgRef;
203
+ readonly toRole: MessageArgRef;
204
+ readonly case: MessageArgRef;
205
+ };
206
+ export declare function redeliver(): MissActionDef;
207
+ export declare function openOnMiss(target: ProtocolTarget, opts: {
208
+ readonly for: AnyRole;
209
+ readonly data: Rec<MissArgInput>;
210
+ }): MissActionDef;
211
+ export declare const ack: {
212
+ readonly none: () => AckDef;
213
+ readonly read: (opts: {
214
+ readonly within: number;
215
+ readonly onMiss: NonEmpty<MissActionDef>;
216
+ }) => AckDef;
217
+ readonly answer: (opts: {
218
+ readonly shape: "ack" | AnyContract;
219
+ readonly within: number;
220
+ readonly onMiss: NonEmpty<MissActionDef>;
221
+ }) => AckDef;
222
+ };
223
+ export declare function message<const Name extends string, F extends FieldSchemaMap>(name: Name, def: {
224
+ readonly payload: StructContract<string, F>;
225
+ readonly template: Guide | ((payload: FieldHandlesOf<F>) => Guide);
226
+ readonly ack: AckDef;
227
+ }): MessageKind<Name, StructContract<string, F>>;
228
+ export declare function bound(def: BoundSpecInput): InlineBound;
229
+ export declare function bound<const Name extends string>(name: Name, def: BoundSpecInput): NamedBound<Name>;
230
+ export {};
package/dist/pieces.js ADDED
@@ -0,0 +1,178 @@
1
+ export function role(name, def) {
2
+ return Object.freeze({
3
+ kind: "role",
4
+ name,
5
+ view: def.view,
6
+ ...(def.includePredecessor !== undefined ? { includePredecessor: def.includePredecessor } : {}),
7
+ ...(def.seatLabels !== undefined ? { seatLabels: def.seatLabels } : {}),
8
+ ...(def.guide !== undefined ? { guide: def.guide.template } : {}),
9
+ ...(def.brief !== undefined ? { brief: Object.freeze([...def.brief]) } : {}),
10
+ });
11
+ }
12
+ export function roleView(target, view, opts) {
13
+ return Object.freeze({
14
+ kind: "role-view",
15
+ role: target,
16
+ view,
17
+ ...(opts?.includePredecessor !== undefined
18
+ ? { includePredecessor: opts.includePredecessor }
19
+ : {}),
20
+ });
21
+ }
22
+ export function roleBrief(target, pieces) {
23
+ return Object.freeze({
24
+ kind: "role-brief",
25
+ role: target,
26
+ pieces: Object.freeze([...pieces]),
27
+ });
28
+ }
29
+ function freezeNonEmpty(items) {
30
+ const [first, ...rest] = items;
31
+ return Object.freeze([first, ...rest]);
32
+ }
33
+ export function defineClass(name, def) {
34
+ return Object.freeze({
35
+ kind: "class",
36
+ name,
37
+ authorized: freezeNonEmpty(def.authorized),
38
+ ...(def.delegatedWhenAway !== undefined
39
+ ? { delegatedWhenAway: Object.freeze([...def.delegatedWhenAway]) }
40
+ : {}),
41
+ requires: Object.freeze([...(def.requires ?? [])]),
42
+ admitsImpossible: def.admitsImpossible ?? false,
43
+ ...(def.guide !== undefined ? { guide: def.guide.template } : {}),
44
+ });
45
+ }
46
+ export function check(id, def) {
47
+ const resolveCheckGuide = (raw) => {
48
+ if (raw === undefined)
49
+ return undefined;
50
+ if (typeof raw === "function") {
51
+ return raw(def.input.fields).template;
52
+ }
53
+ return raw.template;
54
+ };
55
+ const fn = (args, opts) => {
56
+ const g = resolveCheckGuide(opts?.guide);
57
+ return Object.freeze({
58
+ kind: "check-need",
59
+ check: callable,
60
+ args,
61
+ ...(g !== undefined ? { guide: g } : {}),
62
+ });
63
+ };
64
+ const declGuide = resolveCheckGuide(def.guide);
65
+ const callable = Object.freeze(Object.assign(fn, {
66
+ kind: "check",
67
+ id,
68
+ input: def.input,
69
+ ...(def.evaluator !== undefined ? { evaluator: def.evaluator } : {}),
70
+ ...(def.observe !== undefined ? { observe: def.observe } : {}),
71
+ ...(declGuide !== undefined ? { guide: declGuide } : {}),
72
+ }));
73
+ return callable;
74
+ }
75
+ export class ActionError extends Error {
76
+ name = "ActionError";
77
+ code;
78
+ constructor(code, detail) {
79
+ super(detail);
80
+ this.code = code;
81
+ }
82
+ }
83
+ const ACTION_ID_RE = /^[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)*\/action\/[a-z][a-z0-9-]*\/[1-9][0-9]*$/;
84
+ export function isValidActionId(id) {
85
+ return ACTION_ID_RE.test(id);
86
+ }
87
+ function buildAction(def, extra) {
88
+ if (!isValidActionId(def.id)) {
89
+ throw new ActionError("INVALID_ACTION", `action id ${JSON.stringify(def.id)} must match <installation>/action/<name>/<version>`);
90
+ }
91
+ const declGuide = def.guide === undefined
92
+ ? undefined
93
+ : typeof def.guide === "function"
94
+ ? def.guide(def.input.fields).template
95
+ : def.guide.template;
96
+ const fn = (args) => Object.freeze({ kind: "call-action-effect", action: callable, args });
97
+ const callable = Object.freeze(Object.assign(fn, {
98
+ kind: "action",
99
+ id: def.id,
100
+ input: def.input,
101
+ output: def.output,
102
+ ...(def.class !== undefined ? { class: def.class } : {}),
103
+ ...(def.revert !== undefined ? { revert: def.revert } : {}),
104
+ ...(def.release !== undefined ? { release: def.release } : {}),
105
+ ...(def.reversible !== undefined ? { reversible: def.reversible } : {}),
106
+ ...(declGuide !== undefined ? { guide: declGuide } : {}),
107
+ ...extra,
108
+ }));
109
+ return callable;
110
+ }
111
+ /** The step handle of an action the host runs itself: the std actions still in Rust. */
112
+ export function declareAction(def) {
113
+ return buildAction(def, {});
114
+ }
115
+ /**
116
+ * An action is its step handle and its implementation. List it in `defineInstallation({ actions })`;
117
+ * the host calls `run` with the requested input and records what it returns. Refuse with
118
+ * `throw new ActionError(code, message)`.
119
+ */
120
+ export function defineAction(def) {
121
+ return buildAction(def, { run: def.run });
122
+ }
123
+ export const msg = Object.freeze({
124
+ id: Object.freeze({ kind: "message-arg", field: "id" }),
125
+ kind: Object.freeze({ kind: "message-arg", field: "kind" }),
126
+ toRole: Object.freeze({ kind: "message-arg", field: "toRole" }),
127
+ case: Object.freeze({ kind: "message-arg", field: "case" }),
128
+ });
129
+ export function redeliver() {
130
+ return Object.freeze({ kind: "redeliver" });
131
+ }
132
+ export function openOnMiss(target, opts) {
133
+ return Object.freeze({
134
+ kind: "open-on-miss",
135
+ protocol: target,
136
+ forRole: opts.for,
137
+ data: opts.data,
138
+ });
139
+ }
140
+ export const ack = Object.freeze({
141
+ none() {
142
+ return Object.freeze({ kind: "none" });
143
+ },
144
+ read(opts) {
145
+ return Object.freeze({
146
+ kind: "read",
147
+ within: opts.within,
148
+ onMiss: freezeNonEmpty(opts.onMiss),
149
+ });
150
+ },
151
+ answer(opts) {
152
+ return Object.freeze({
153
+ kind: "answer",
154
+ shape: opts.shape,
155
+ within: opts.within,
156
+ onMiss: freezeNonEmpty(opts.onMiss),
157
+ });
158
+ },
159
+ });
160
+ export function message(name, def) {
161
+ const resolved = typeof def.template === "function" ? def.template(def.payload.fields) : def.template;
162
+ return Object.freeze({
163
+ kind: "message-kind",
164
+ name,
165
+ payload: def.payload,
166
+ template: resolved,
167
+ ack: def.ack,
168
+ });
169
+ }
170
+ export function bound(nameOrDef, maybeDef) {
171
+ if (typeof nameOrDef === "string") {
172
+ if (maybeDef === undefined) {
173
+ throw new Error(`bound(${JSON.stringify(nameOrDef)}) requires a bound definition`);
174
+ }
175
+ return Object.freeze({ kind: "named-bound", name: nameOrDef, spec: maybeDef });
176
+ }
177
+ return Object.freeze({ kind: "inline-bound", spec: nameOrDef });
178
+ }