@composable-os/sdk 0.0.0-stage → 0.1.0-beta.10
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/LICENSE +109 -0
- package/dist/allowance.d.ts +198 -0
- package/dist/allowance.js +374 -0
- package/dist/automation-check.d.ts +38 -0
- package/dist/automation-check.js +454 -0
- package/dist/automation.d.ts +767 -0
- package/dist/automation.js +303 -0
- package/dist/behaviour.d.ts +3 -0
- package/dist/behaviour.js +153 -0
- package/dist/capacity.d.ts +77 -0
- package/dist/capacity.js +127 -0
- package/dist/contract.d.ts +819 -0
- package/dist/contract.js +42 -0
- package/dist/document.d.ts +211 -0
- package/dist/document.js +726 -0
- package/dist/field-types.d.ts +11 -0
- package/dist/field-types.js +98 -0
- package/dist/formula/ast.d.ts +67 -0
- package/dist/formula/ast.js +22 -0
- package/dist/formula/compile.d.ts +37 -0
- package/dist/formula/compile.js +379 -0
- package/dist/formula/index.d.ts +3 -0
- package/dist/formula/index.js +4 -0
- package/dist/formula/parser.d.ts +13 -0
- package/dist/formula/parser.js +365 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +24 -0
- package/dist/manifest.d.ts +1596 -0
- package/dist/manifest.js +1420 -0
- package/dist/media.d.ts +41 -0
- package/dist/media.js +90 -0
- package/dist/permissions.d.ts +17 -0
- package/dist/permissions.js +44 -0
- package/dist/recurring.d.ts +114 -0
- package/dist/recurring.js +173 -0
- package/dist/renamed.d.ts +16 -0
- package/dist/renamed.js +59 -0
- package/dist/rich-text-fixture.d.ts +121 -0
- package/dist/rich-text-fixture.js +67 -0
- package/dist/rich-text.d.ts +48 -0
- package/dist/rich-text.js +184 -0
- package/dist/runtime.d.ts +95 -0
- package/dist/runtime.js +312 -0
- package/dist/sellable.d.ts +253 -0
- package/dist/sellable.js +593 -0
- package/dist/slug.d.ts +11 -0
- package/dist/slug.js +23 -0
- package/dist/states.d.ts +238 -0
- package/dist/states.js +315 -0
- package/dist/testing.d.ts +151 -0
- package/dist/testing.js +679 -0
- package/dist/unique.d.ts +20 -0
- package/dist/unique.js +58 -0
- package/package.json +34 -4
- package/src/allowance.ts +522 -0
- package/src/automation-check.ts +534 -0
- package/src/automation.ts +743 -0
- package/src/behaviour.ts +215 -0
- package/src/capacity.ts +201 -0
- package/src/contract.ts +884 -0
- package/src/document.ts +935 -0
- package/src/field-types.ts +111 -0
- package/src/formula/ast.ts +72 -0
- package/src/formula/compile.ts +454 -0
- package/src/formula/index.ts +4 -0
- package/src/formula/parser.ts +417 -0
- package/src/index.ts +36 -0
- package/src/manifest.ts +1709 -0
- package/src/media.ts +108 -0
- package/src/permissions.ts +60 -0
- package/src/recurring.ts +321 -0
- package/src/renamed.ts +63 -0
- package/src/rich-text-fixture.ts +68 -0
- package/src/rich-text.ts +221 -0
- package/src/runtime.ts +410 -0
- package/src/sellable.ts +888 -0
- package/src/slug.ts +25 -0
- package/src/states.ts +484 -0
- package/src/testing.ts +847 -0
- package/src/unique.ts +81 -0
- package/README.md +0 -3
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { FormulaType } from "./formula/ast.ts";
|
|
2
|
+
export declare const FIELD_TYPES: readonly ["text", "longText", "number", "currency", "percent", "date", "datetime", "boolean", "select", "multiSelect", "relation", "user", "email", "phone", "url", "formula", "document", "timezone", "richText", "slug", "image", "video"];
|
|
3
|
+
export type FieldTypeName = (typeof FIELD_TYPES)[number];
|
|
4
|
+
/** What a formula sees when it reads a field of this type (null: not readable from formulas). */
|
|
5
|
+
export declare function formulaTypeOf(type: FieldTypeName, many?: boolean): Exclude<FormulaType, "null"> | null;
|
|
6
|
+
/**
|
|
7
|
+
* Type changes the reconciler accepts: the stored values stay valid and keep their meaning.
|
|
8
|
+
* Anything else is refused with a suggestion to add a new field and migrate.
|
|
9
|
+
*/
|
|
10
|
+
export declare const LOSSLESS_TYPE_CHANGES: Readonly<Record<FieldTypeName, readonly FieldTypeName[]>>;
|
|
11
|
+
export declare function isLosslessChange(from: FieldTypeName, to: FieldTypeName): boolean;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
export const FIELD_TYPES = [
|
|
2
|
+
"text",
|
|
3
|
+
"longText",
|
|
4
|
+
"number",
|
|
5
|
+
"currency",
|
|
6
|
+
"percent",
|
|
7
|
+
"date",
|
|
8
|
+
"datetime",
|
|
9
|
+
"boolean",
|
|
10
|
+
"select",
|
|
11
|
+
"multiSelect",
|
|
12
|
+
"relation",
|
|
13
|
+
"user",
|
|
14
|
+
"email",
|
|
15
|
+
"phone",
|
|
16
|
+
"url",
|
|
17
|
+
"formula",
|
|
18
|
+
// A JSON document checked against a schema the field declares (stage 41, ADR 0445).
|
|
19
|
+
"document",
|
|
20
|
+
// An IANA time zone name (`Asia/Bangkok`), checked against the runtime's list of zones. Left
|
|
21
|
+
// empty on a new record, the host fills in the deployment's zone (ADR 0460).
|
|
22
|
+
"timezone",
|
|
23
|
+
// Structured prose: a document with the platform's one rich text schema (stage 28, ADR 0440).
|
|
24
|
+
"richText",
|
|
25
|
+
// A record's address in its object (`summer-launch`): lowercase words joined by hyphens,
|
|
26
|
+
// unique among the object's live records, made from the title when left empty (ADR 0442).
|
|
27
|
+
"slug",
|
|
28
|
+
// A picture from the media library, with alt text and a focal point (stage 28, ADR 0444).
|
|
29
|
+
"image",
|
|
30
|
+
// A video from the media library, held in Cloudflare Stream, played only with a token the host
|
|
31
|
+
// signs (stage 42, ADR 0475).
|
|
32
|
+
"video",
|
|
33
|
+
];
|
|
34
|
+
/** What a formula sees when it reads a field of this type (null: not readable from formulas). */
|
|
35
|
+
export function formulaTypeOf(type, many = false) {
|
|
36
|
+
switch (type) {
|
|
37
|
+
case "text":
|
|
38
|
+
case "longText":
|
|
39
|
+
case "select":
|
|
40
|
+
case "user":
|
|
41
|
+
case "email":
|
|
42
|
+
case "phone":
|
|
43
|
+
case "url":
|
|
44
|
+
case "timezone":
|
|
45
|
+
case "slug":
|
|
46
|
+
return "text";
|
|
47
|
+
case "relation":
|
|
48
|
+
return many ? null : "text";
|
|
49
|
+
case "number":
|
|
50
|
+
case "currency":
|
|
51
|
+
case "percent":
|
|
52
|
+
return "number";
|
|
53
|
+
case "boolean":
|
|
54
|
+
return "boolean";
|
|
55
|
+
case "date":
|
|
56
|
+
return "date";
|
|
57
|
+
case "datetime":
|
|
58
|
+
return "datetime";
|
|
59
|
+
case "multiSelect":
|
|
60
|
+
case "formula":
|
|
61
|
+
case "document":
|
|
62
|
+
case "richText":
|
|
63
|
+
case "image":
|
|
64
|
+
case "video":
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Type changes the reconciler accepts: the stored values stay valid and keep their meaning.
|
|
70
|
+
* Anything else is refused with a suggestion to add a new field and migrate.
|
|
71
|
+
*/
|
|
72
|
+
export const LOSSLESS_TYPE_CHANGES = {
|
|
73
|
+
text: ["longText"],
|
|
74
|
+
longText: [],
|
|
75
|
+
number: ["currency", "percent"],
|
|
76
|
+
currency: ["number"],
|
|
77
|
+
percent: ["number"],
|
|
78
|
+
date: ["datetime"],
|
|
79
|
+
datetime: [],
|
|
80
|
+
boolean: [],
|
|
81
|
+
select: ["text", "longText"],
|
|
82
|
+
multiSelect: [],
|
|
83
|
+
relation: [],
|
|
84
|
+
user: [],
|
|
85
|
+
email: ["text", "longText"],
|
|
86
|
+
phone: ["text", "longText"],
|
|
87
|
+
url: ["text", "longText"],
|
|
88
|
+
formula: [],
|
|
89
|
+
document: [],
|
|
90
|
+
timezone: ["text", "longText"],
|
|
91
|
+
richText: [],
|
|
92
|
+
slug: ["text", "longText"],
|
|
93
|
+
image: [],
|
|
94
|
+
video: [],
|
|
95
|
+
};
|
|
96
|
+
export function isLosslessChange(from, to) {
|
|
97
|
+
return from === to || LOSSLESS_TYPE_CHANGES[from].includes(to);
|
|
98
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/** The value types a formula expression can have. `null` is the type of the literal `null`. */
|
|
2
|
+
export type FormulaType = "number" | "text" | "boolean" | "date" | "datetime" | "null";
|
|
3
|
+
export interface Span {
|
|
4
|
+
start: number;
|
|
5
|
+
end: number;
|
|
6
|
+
}
|
|
7
|
+
export type FormulaErrorCode = "formula_syntax" | "formula_type" | "formula_unknown_field" | "formula_unknown_function" | "formula_cycle" | "formula_too_complex";
|
|
8
|
+
/** A structured formula error, with the character span it points at. */
|
|
9
|
+
export interface FormulaIssue {
|
|
10
|
+
code: FormulaErrorCode;
|
|
11
|
+
message: string;
|
|
12
|
+
span: Span;
|
|
13
|
+
}
|
|
14
|
+
export declare class FormulaError extends Error {
|
|
15
|
+
readonly issue: FormulaIssue;
|
|
16
|
+
name: string;
|
|
17
|
+
constructor(issue: FormulaIssue);
|
|
18
|
+
}
|
|
19
|
+
export declare function formulaError(code: FormulaErrorCode, message: string, span: Span): FormulaError;
|
|
20
|
+
export type BinaryOperator = "+" | "-" | "*" | "/" | "%" | "&" | "=" | "!=" | "<" | "<=" | ">" | ">=" | "and" | "or";
|
|
21
|
+
export type FormulaNode = {
|
|
22
|
+
kind: "number";
|
|
23
|
+
value: number;
|
|
24
|
+
text: string;
|
|
25
|
+
span: Span;
|
|
26
|
+
} | {
|
|
27
|
+
kind: "string";
|
|
28
|
+
value: string;
|
|
29
|
+
span: Span;
|
|
30
|
+
} | {
|
|
31
|
+
kind: "boolean";
|
|
32
|
+
value: boolean;
|
|
33
|
+
span: Span;
|
|
34
|
+
} | {
|
|
35
|
+
kind: "null";
|
|
36
|
+
span: Span;
|
|
37
|
+
} | {
|
|
38
|
+
kind: "field";
|
|
39
|
+
name: string;
|
|
40
|
+
span: Span;
|
|
41
|
+
} | {
|
|
42
|
+
kind: "unary";
|
|
43
|
+
op: "-" | "not";
|
|
44
|
+
operand: FormulaNode;
|
|
45
|
+
span: Span;
|
|
46
|
+
} | {
|
|
47
|
+
kind: "binary";
|
|
48
|
+
op: BinaryOperator;
|
|
49
|
+
left: FormulaNode;
|
|
50
|
+
right: FormulaNode;
|
|
51
|
+
span: Span;
|
|
52
|
+
} | {
|
|
53
|
+
kind: "call";
|
|
54
|
+
name: string;
|
|
55
|
+
args: FormulaNode[];
|
|
56
|
+
span: Span;
|
|
57
|
+
};
|
|
58
|
+
export declare const FORMULA_LIMITS: {
|
|
59
|
+
/** Characters in one expression. */
|
|
60
|
+
readonly maxLength: 2000;
|
|
61
|
+
/** Nodes in one parsed expression. */
|
|
62
|
+
readonly maxNodes: 400;
|
|
63
|
+
/** Nesting depth. */
|
|
64
|
+
readonly maxDepth: 40;
|
|
65
|
+
/** Characters in one string literal. */
|
|
66
|
+
readonly maxStringLength: 500;
|
|
67
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Formula language: tokens, AST and errors. See the SDK README for the grammar.
|
|
2
|
+
export class FormulaError extends Error {
|
|
3
|
+
issue;
|
|
4
|
+
name = "FormulaError";
|
|
5
|
+
constructor(issue) {
|
|
6
|
+
super(issue.message);
|
|
7
|
+
this.issue = issue;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export function formulaError(code, message, span) {
|
|
11
|
+
return new FormulaError({ code, message, span });
|
|
12
|
+
}
|
|
13
|
+
export const FORMULA_LIMITS = {
|
|
14
|
+
/** Characters in one expression. */
|
|
15
|
+
maxLength: 2000,
|
|
16
|
+
/** Nodes in one parsed expression. */
|
|
17
|
+
maxNodes: 400,
|
|
18
|
+
/** Nesting depth. */
|
|
19
|
+
maxDepth: 40,
|
|
20
|
+
/** Characters in one string literal. */
|
|
21
|
+
maxStringLength: 500,
|
|
22
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type FormulaIssue, type FormulaType } from "./ast.ts";
|
|
2
|
+
/** A field a formula may reference: its formula type and a trusted SQL expression for it. */
|
|
3
|
+
export type FormulaFieldRef = {
|
|
4
|
+
type: Exclude<FormulaType, "null">;
|
|
5
|
+
sql: string;
|
|
6
|
+
}
|
|
7
|
+
/** Another formula field, compiled on demand (cycles are reported). */
|
|
8
|
+
| {
|
|
9
|
+
expression: string;
|
|
10
|
+
};
|
|
11
|
+
export interface FormulaEnvironment {
|
|
12
|
+
/** Fields of the same record, by name. Names are case-sensitive. */
|
|
13
|
+
fields: Record<string, FormulaFieldRef>;
|
|
14
|
+
}
|
|
15
|
+
export interface CompiledFormula {
|
|
16
|
+
/** The expression's type. A bare `null` formula is refused, so this is never "null". */
|
|
17
|
+
type: Exclude<FormulaType, "null">;
|
|
18
|
+
/** A SQLite expression. Booleans are 0/1 integers, dates ISO-8601 text. */
|
|
19
|
+
sql: string;
|
|
20
|
+
/** Field names the formula reads (directly). */
|
|
21
|
+
fields: string[];
|
|
22
|
+
}
|
|
23
|
+
/** Function signatures, for error messages and the README. */
|
|
24
|
+
export declare const FORMULA_FUNCTIONS: Record<string, string>;
|
|
25
|
+
/**
|
|
26
|
+
* Parses, type-checks and compiles a formula against the fields of one record. Throws
|
|
27
|
+
* FormulaError (see `issue` for the code and span).
|
|
28
|
+
*/
|
|
29
|
+
export declare function compileFormula(expression: string, env: FormulaEnvironment, self?: string): CompiledFormula;
|
|
30
|
+
/** Like compileFormula, but returns the issue instead of throwing. */
|
|
31
|
+
export declare function checkFormula(expression: string, env: FormulaEnvironment, self?: string): {
|
|
32
|
+
ok: true;
|
|
33
|
+
formula: CompiledFormula;
|
|
34
|
+
} | {
|
|
35
|
+
ok: false;
|
|
36
|
+
issue: FormulaIssue;
|
|
37
|
+
};
|
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
// Formula type checker and SQLite compiler. One pass over the AST: every node gets a type, and
|
|
2
|
+
// compiles to a SQLite expression only once its operands type-check.
|
|
3
|
+
//
|
|
4
|
+
// Safety: the only SQL text that does not come from this file is the field references, which the
|
|
5
|
+
// host supplies from validated identifiers. Numbers are re-printed from parsed values, strings are
|
|
6
|
+
// single-quoted with quotes doubled, and function names map to a fixed table. Nothing from the
|
|
7
|
+
// source is spliced into SQL verbatim.
|
|
8
|
+
import { FormulaError, formulaError, } from "./ast.js";
|
|
9
|
+
import { parseFormula } from "./parser.js";
|
|
10
|
+
const DATE_UNITS = ["day", "week", "month", "year"];
|
|
11
|
+
/** Function signatures, for error messages and the README. */
|
|
12
|
+
export const FORMULA_FUNCTIONS = {
|
|
13
|
+
if: "if(condition, then, else)",
|
|
14
|
+
coalesce: "coalesce(value, fallback, ...)",
|
|
15
|
+
isBlank: "isBlank(value)",
|
|
16
|
+
concat: "concat(value, ...)",
|
|
17
|
+
length: "length(text)",
|
|
18
|
+
lower: "lower(text)",
|
|
19
|
+
upper: "upper(text)",
|
|
20
|
+
trim: "trim(text)",
|
|
21
|
+
round: "round(number, digits?)",
|
|
22
|
+
floor: "floor(number)",
|
|
23
|
+
ceil: "ceil(number)",
|
|
24
|
+
abs: "abs(number)",
|
|
25
|
+
min: "min(number, number, ...)",
|
|
26
|
+
max: "max(number, number, ...)",
|
|
27
|
+
today: "today()",
|
|
28
|
+
now: "now()",
|
|
29
|
+
dateAdd: 'dateAdd(date, amount, "day" | "week" | "month" | "year")',
|
|
30
|
+
dateDiff: 'dateDiff(start, end, "day" | "week" | "month" | "year")',
|
|
31
|
+
};
|
|
32
|
+
const FUNCTION_LOOKUP = new Map(Object.keys(FORMULA_FUNCTIONS).map((n) => [n.toLowerCase(), n]));
|
|
33
|
+
function sqlString(value) {
|
|
34
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
35
|
+
}
|
|
36
|
+
function sqlNumber(value) {
|
|
37
|
+
// Re-printed from the parsed value, so only digits, '.', 'e', '+', '-' can appear.
|
|
38
|
+
const text = Number.isInteger(value) ? value.toFixed(0) : String(value);
|
|
39
|
+
return /^-?[0-9.e+-]+$/i.test(text) ? text : "NULL";
|
|
40
|
+
}
|
|
41
|
+
function typeError(message, span) {
|
|
42
|
+
return formulaError("formula_type", message, span);
|
|
43
|
+
}
|
|
44
|
+
function isTemporal(type) {
|
|
45
|
+
return type === "date" || type === "datetime";
|
|
46
|
+
}
|
|
47
|
+
/** The common type of two operands (null fits anything; date and datetime meet at datetime). */
|
|
48
|
+
function unify(a, b) {
|
|
49
|
+
if (a === "null")
|
|
50
|
+
return b;
|
|
51
|
+
if (b === "null")
|
|
52
|
+
return a;
|
|
53
|
+
if (a === b)
|
|
54
|
+
return a;
|
|
55
|
+
if (isTemporal(a) && isTemporal(b))
|
|
56
|
+
return "datetime";
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
/** Text form of a value, for concatenation: numbers without a trailing ".0". */
|
|
60
|
+
function asText(value) {
|
|
61
|
+
switch (value.type) {
|
|
62
|
+
case "text":
|
|
63
|
+
return value.sql;
|
|
64
|
+
case "number":
|
|
65
|
+
return `(CASE WHEN ${value.sql} = CAST(${value.sql} AS INTEGER) THEN CAST(CAST(${value.sql} AS INTEGER) AS TEXT) ELSE CAST(${value.sql} AS TEXT) END)`;
|
|
66
|
+
case "boolean":
|
|
67
|
+
return `(CASE WHEN ${value.sql} IS NULL THEN NULL WHEN ${value.sql} THEN 'true' ELSE 'false' END)`;
|
|
68
|
+
case "null":
|
|
69
|
+
return "NULL";
|
|
70
|
+
default:
|
|
71
|
+
return value.sql;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
class Compiler {
|
|
75
|
+
env;
|
|
76
|
+
resolving;
|
|
77
|
+
fieldsRead = new Set();
|
|
78
|
+
constructor(env, resolving) {
|
|
79
|
+
this.env = env;
|
|
80
|
+
this.resolving = resolving;
|
|
81
|
+
}
|
|
82
|
+
expect(node, allowed, what) {
|
|
83
|
+
const value = this.compile(node);
|
|
84
|
+
if (value.type !== "null" && !allowed.includes(value.type)) {
|
|
85
|
+
throw typeError(`${what} must be ${allowed.join(" or ")}, not ${value.type}`, node.span);
|
|
86
|
+
}
|
|
87
|
+
return value;
|
|
88
|
+
}
|
|
89
|
+
/** A date argument: a date/datetime expression, or a literal such as "2026-03-01". */
|
|
90
|
+
temporal(node, what) {
|
|
91
|
+
if (node.kind === "string") {
|
|
92
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(node.value))
|
|
93
|
+
return { type: "date", sql: sqlString(node.value) };
|
|
94
|
+
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?Z$/.test(node.value)) {
|
|
95
|
+
return { type: "datetime", sql: sqlString(node.value) };
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return this.expect(node, ["date", "datetime"], what);
|
|
99
|
+
}
|
|
100
|
+
compile(node) {
|
|
101
|
+
switch (node.kind) {
|
|
102
|
+
case "number":
|
|
103
|
+
return { type: "number", sql: sqlNumber(node.value) };
|
|
104
|
+
case "string":
|
|
105
|
+
return { type: "text", sql: sqlString(node.value) };
|
|
106
|
+
case "boolean":
|
|
107
|
+
return { type: "boolean", sql: node.value ? "1" : "0" };
|
|
108
|
+
case "null":
|
|
109
|
+
return { type: "null", sql: "NULL" };
|
|
110
|
+
case "field":
|
|
111
|
+
return this.field(node.name, node.span);
|
|
112
|
+
case "unary": {
|
|
113
|
+
if (node.op === "-") {
|
|
114
|
+
const operand = this.expect(node.operand, ["number"], "The operand of -");
|
|
115
|
+
return { type: "number", sql: `(-${operand.sql})` };
|
|
116
|
+
}
|
|
117
|
+
const operand = this.expect(node.operand, ["boolean"], "The operand of not");
|
|
118
|
+
return { type: "boolean", sql: `(NOT ${operand.sql})` };
|
|
119
|
+
}
|
|
120
|
+
case "binary":
|
|
121
|
+
return this.binary(node);
|
|
122
|
+
case "call":
|
|
123
|
+
return this.call(node);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
field(name, span) {
|
|
127
|
+
if (!Object.hasOwn(this.env.fields, name)) {
|
|
128
|
+
const known = Object.keys(this.env.fields);
|
|
129
|
+
const hint = known.find((k) => k.toLowerCase() === name.toLowerCase());
|
|
130
|
+
throw formulaError("formula_unknown_field", hint
|
|
131
|
+
? `Unknown field "${name}". Did you mean "${hint}"? Names are case-sensitive.`
|
|
132
|
+
: `Unknown field "${name}". Fields on this record: ${known.join(", ") || "none"}`, span);
|
|
133
|
+
}
|
|
134
|
+
this.fieldsRead.add(name);
|
|
135
|
+
const ref = this.env.fields[name];
|
|
136
|
+
if ("sql" in ref)
|
|
137
|
+
return { type: ref.type, sql: ref.sql };
|
|
138
|
+
if (this.resolving.has(name)) {
|
|
139
|
+
throw formulaError("formula_cycle", `Formula field "${name}" refers back to itself (through ${[...this.resolving].join(" → ")})`, span);
|
|
140
|
+
}
|
|
141
|
+
const inner = new Compiler(this.env, new Set([...this.resolving, name]));
|
|
142
|
+
let compiled;
|
|
143
|
+
try {
|
|
144
|
+
compiled = inner.compile(parseFormula(ref.expression));
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
if (error instanceof FormulaError && error.issue.code === "formula_cycle")
|
|
148
|
+
throw error;
|
|
149
|
+
throw typeError(`Formula field "${name}" has errors of its own`, span);
|
|
150
|
+
}
|
|
151
|
+
return { type: compiled.type, sql: `(${compiled.sql})` };
|
|
152
|
+
}
|
|
153
|
+
binary(node) {
|
|
154
|
+
const { op } = node;
|
|
155
|
+
if (op === "and" || op === "or") {
|
|
156
|
+
const left = this.expect(node.left, ["boolean"], `The left side of ${op}`);
|
|
157
|
+
const right = this.expect(node.right, ["boolean"], `The right side of ${op}`);
|
|
158
|
+
return { type: "boolean", sql: `(${left.sql} ${op.toUpperCase()} ${right.sql})` };
|
|
159
|
+
}
|
|
160
|
+
if (op === "&") {
|
|
161
|
+
const left = this.compile(node.left);
|
|
162
|
+
const right = this.compile(node.right);
|
|
163
|
+
return {
|
|
164
|
+
type: "text",
|
|
165
|
+
sql: `(coalesce(${asText(left)}, '') || coalesce(${asText(right)}, ''))`,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
if (op === "+" || op === "-" || op === "*" || op === "/" || op === "%") {
|
|
169
|
+
const left = this.compile(node.left);
|
|
170
|
+
const right = this.compile(node.right);
|
|
171
|
+
if (op === "+" && (left.type === "text" || right.type === "text")) {
|
|
172
|
+
throw typeError("Use & or concat() to join text, not +", node.span);
|
|
173
|
+
}
|
|
174
|
+
if ((op === "+" || op === "-") && isTemporal(left.type)) {
|
|
175
|
+
throw typeError(`Use dateAdd() to move a date, not ${op}`, node.span);
|
|
176
|
+
}
|
|
177
|
+
for (const [side, value] of [
|
|
178
|
+
["left", left],
|
|
179
|
+
["right", right],
|
|
180
|
+
]) {
|
|
181
|
+
if (value.type !== "number" && value.type !== "null") {
|
|
182
|
+
throw typeError(`The ${side} side of ${op} must be a number, not ${value.type}`, side === "left" ? node.left.span : node.right.span);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (op === "/") {
|
|
186
|
+
return { type: "number", sql: `(CAST(${left.sql} AS REAL) / NULLIF(${right.sql}, 0))` };
|
|
187
|
+
}
|
|
188
|
+
if (op === "%")
|
|
189
|
+
return { type: "number", sql: `(${left.sql} % NULLIF(${right.sql}, 0))` };
|
|
190
|
+
return { type: "number", sql: `(${left.sql} ${op} ${right.sql})` };
|
|
191
|
+
}
|
|
192
|
+
// Comparisons.
|
|
193
|
+
const left = this.compile(node.left);
|
|
194
|
+
const right = this.compile(node.right);
|
|
195
|
+
if (left.type === "null" || right.type === "null") {
|
|
196
|
+
throw typeError("Compare with null using isBlank(value)", node.span);
|
|
197
|
+
}
|
|
198
|
+
const common = unify(left.type, right.type);
|
|
199
|
+
if (!common) {
|
|
200
|
+
throw typeError(`Cannot compare ${left.type} with ${right.type}`, node.span);
|
|
201
|
+
}
|
|
202
|
+
if (common === "boolean" && op !== "=" && op !== "!=") {
|
|
203
|
+
throw typeError(`Booleans can only be compared with = and !=`, node.span);
|
|
204
|
+
}
|
|
205
|
+
const sqlOp = op === "!=" ? "<>" : op;
|
|
206
|
+
if (common === "datetime" && left.type !== right.type) {
|
|
207
|
+
return {
|
|
208
|
+
type: "boolean",
|
|
209
|
+
sql: `(julianday(${left.sql}) ${sqlOp} julianday(${right.sql}))`,
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
return { type: "boolean", sql: `(${left.sql} ${sqlOp} ${right.sql})` };
|
|
213
|
+
}
|
|
214
|
+
arity(node, name, min, max) {
|
|
215
|
+
if (node.args.length < min || node.args.length > max) {
|
|
216
|
+
throw typeError(`${name} takes ${min === max ? min : `${min} to ${max === Infinity ? "any number of" : max}`} argument${max === 1 ? "" : "s"}: ${FORMULA_FUNCTIONS[name]}`, node.span);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
unit(node, fn, span) {
|
|
220
|
+
if (node?.kind !== "string" || !DATE_UNITS.includes(node.value)) {
|
|
221
|
+
throw typeError(`The unit of ${fn} must be a quoted literal: "day", "week", "month" or "year"`, node?.span ?? span);
|
|
222
|
+
}
|
|
223
|
+
return node.value;
|
|
224
|
+
}
|
|
225
|
+
call(node) {
|
|
226
|
+
const name = FUNCTION_LOOKUP.get(node.name.toLowerCase());
|
|
227
|
+
if (!name) {
|
|
228
|
+
throw formulaError("formula_unknown_function", `Unknown function "${node.name}". Available: ${Object.keys(FORMULA_FUNCTIONS).join(", ")}`, node.span);
|
|
229
|
+
}
|
|
230
|
+
const args = node.args;
|
|
231
|
+
switch (name) {
|
|
232
|
+
case "if": {
|
|
233
|
+
this.arity(node, name, 3, 3);
|
|
234
|
+
const condition = this.expect(args[0], ["boolean"], "The condition of if");
|
|
235
|
+
const then = this.compile(args[1]);
|
|
236
|
+
const otherwise = this.compile(args[2]);
|
|
237
|
+
const type = unify(then.type, otherwise.type);
|
|
238
|
+
if (!type) {
|
|
239
|
+
throw typeError(`Both branches of if must have the same type (got ${then.type} and ${otherwise.type})`, node.span);
|
|
240
|
+
}
|
|
241
|
+
return {
|
|
242
|
+
type,
|
|
243
|
+
sql: `(CASE WHEN ${condition.sql} THEN ${then.sql} ELSE ${otherwise.sql} END)`,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
case "coalesce": {
|
|
247
|
+
this.arity(node, name, 2, 20);
|
|
248
|
+
const values = args.map((arg) => this.compile(arg));
|
|
249
|
+
let type = "null";
|
|
250
|
+
for (const value of values) {
|
|
251
|
+
const next = unify(type, value.type);
|
|
252
|
+
if (!next) {
|
|
253
|
+
throw typeError("All arguments of coalesce must have the same type", node.span);
|
|
254
|
+
}
|
|
255
|
+
type = next;
|
|
256
|
+
}
|
|
257
|
+
return { type, sql: `coalesce(${values.map((v) => v.sql).join(", ")})` };
|
|
258
|
+
}
|
|
259
|
+
case "isBlank": {
|
|
260
|
+
this.arity(node, name, 1, 1);
|
|
261
|
+
const value = this.compile(args[0]);
|
|
262
|
+
const blank = value.type === "text"
|
|
263
|
+
? `(${value.sql} IS NULL OR trim(${value.sql}) = '')`
|
|
264
|
+
: `(${value.sql} IS NULL)`;
|
|
265
|
+
return { type: "boolean", sql: blank };
|
|
266
|
+
}
|
|
267
|
+
case "concat": {
|
|
268
|
+
this.arity(node, name, 1, 20);
|
|
269
|
+
const parts = args.map((arg) => `coalesce(${asText(this.compile(arg))}, '')`);
|
|
270
|
+
return { type: "text", sql: `(${parts.join(" || ")})` };
|
|
271
|
+
}
|
|
272
|
+
case "length":
|
|
273
|
+
case "lower":
|
|
274
|
+
case "upper":
|
|
275
|
+
case "trim": {
|
|
276
|
+
this.arity(node, name, 1, 1);
|
|
277
|
+
const value = this.expect(args[0], ["text"], `The argument of ${name}`);
|
|
278
|
+
return { type: name === "length" ? "number" : "text", sql: `${name}(${value.sql})` };
|
|
279
|
+
}
|
|
280
|
+
case "round": {
|
|
281
|
+
this.arity(node, name, 1, 2);
|
|
282
|
+
const value = this.expect(args[0], ["number"], "The value to round");
|
|
283
|
+
const digitsNode = args[1];
|
|
284
|
+
let digits = 0;
|
|
285
|
+
if (digitsNode) {
|
|
286
|
+
if (digitsNode.kind !== "number" || !Number.isInteger(digitsNode.value)) {
|
|
287
|
+
throw typeError("round's digits must be a whole number literal", digitsNode.span);
|
|
288
|
+
}
|
|
289
|
+
digits = digitsNode.value;
|
|
290
|
+
if (digits < 0 || digits > 10) {
|
|
291
|
+
throw typeError("round's digits must be between 0 and 10", digitsNode.span);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
return { type: "number", sql: `round(${value.sql}, ${digits})` };
|
|
295
|
+
}
|
|
296
|
+
case "floor":
|
|
297
|
+
case "ceil": {
|
|
298
|
+
this.arity(node, name, 1, 1);
|
|
299
|
+
const v = this.expect(args[0], ["number"], `The argument of ${name}`).sql;
|
|
300
|
+
// SQLite's math functions are optional, so floor/ceil are built from CAST (truncation).
|
|
301
|
+
const sql = name === "floor"
|
|
302
|
+
? `(CASE WHEN ${v} IS NULL THEN NULL WHEN ${v} >= 0 OR ${v} = CAST(${v} AS INTEGER) THEN CAST(${v} AS INTEGER) ELSE CAST(${v} AS INTEGER) - 1 END)`
|
|
303
|
+
: `(CASE WHEN ${v} IS NULL THEN NULL WHEN ${v} <= 0 OR ${v} = CAST(${v} AS INTEGER) THEN CAST(${v} AS INTEGER) ELSE CAST(${v} AS INTEGER) + 1 END)`;
|
|
304
|
+
return { type: "number", sql };
|
|
305
|
+
}
|
|
306
|
+
case "abs": {
|
|
307
|
+
this.arity(node, name, 1, 1);
|
|
308
|
+
const v = this.expect(args[0], ["number"], "The argument of abs");
|
|
309
|
+
return { type: "number", sql: `abs(${v.sql})` };
|
|
310
|
+
}
|
|
311
|
+
case "min":
|
|
312
|
+
case "max": {
|
|
313
|
+
this.arity(node, name, 2, 20);
|
|
314
|
+
const values = args.map((arg) => this.expect(arg, ["number"], `Arguments of ${name}`));
|
|
315
|
+
return { type: "number", sql: `${name}(${values.map((v) => v.sql).join(", ")})` };
|
|
316
|
+
}
|
|
317
|
+
case "today":
|
|
318
|
+
this.arity(node, name, 0, 0);
|
|
319
|
+
return { type: "date", sql: "date('now')" };
|
|
320
|
+
case "now":
|
|
321
|
+
this.arity(node, name, 0, 0);
|
|
322
|
+
return { type: "datetime", sql: "strftime('%Y-%m-%dT%H:%M:%fZ', 'now')" };
|
|
323
|
+
case "dateAdd": {
|
|
324
|
+
this.arity(node, name, 3, 3);
|
|
325
|
+
const date = this.temporal(args[0], "dateAdd's date");
|
|
326
|
+
const amount = this.expect(args[1], ["number"], "dateAdd's amount");
|
|
327
|
+
const unit = this.unit(args[2], name, node.span);
|
|
328
|
+
const n = unit === "week" ? `(${amount.sql}) * 7` : amount.sql;
|
|
329
|
+
const modifier = `printf('%+d ${unit === "week" ? "day" : unit}s', CAST(${n} AS INTEGER))`;
|
|
330
|
+
const sql = date.type === "date"
|
|
331
|
+
? `date(${date.sql}, ${modifier})`
|
|
332
|
+
: `strftime('%Y-%m-%dT%H:%M:%fZ', ${date.sql}, ${modifier})`;
|
|
333
|
+
return { type: date.type === "null" ? "date" : date.type, sql };
|
|
334
|
+
}
|
|
335
|
+
case "dateDiff": {
|
|
336
|
+
this.arity(node, name, 3, 3);
|
|
337
|
+
const start = this.temporal(args[0], "dateDiff's start");
|
|
338
|
+
const end = this.temporal(args[1], "dateDiff's end");
|
|
339
|
+
const unit = this.unit(args[2], name, node.span);
|
|
340
|
+
const days = `(julianday(${end.sql}) - julianday(${start.sql}))`;
|
|
341
|
+
let sql;
|
|
342
|
+
if (unit === "day")
|
|
343
|
+
sql = `CAST(${days} AS INTEGER)`;
|
|
344
|
+
else if (unit === "week")
|
|
345
|
+
sql = `CAST(${days} / 7 AS INTEGER)`;
|
|
346
|
+
else {
|
|
347
|
+
const months = `((CAST(strftime('%Y', ${end.sql}) AS INTEGER) * 12 + CAST(strftime('%m', ${end.sql}) AS INTEGER)) - (CAST(strftime('%Y', ${start.sql}) AS INTEGER) * 12 + CAST(strftime('%m', ${start.sql}) AS INTEGER)))`;
|
|
348
|
+
sql = unit === "month" ? months : `(${months} / 12)`;
|
|
349
|
+
}
|
|
350
|
+
return { type: "number", sql };
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
throw formulaError("formula_unknown_function", `Unknown function "${node.name}"`, node.span);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Parses, type-checks and compiles a formula against the fields of one record. Throws
|
|
358
|
+
* FormulaError (see `issue` for the code and span).
|
|
359
|
+
*/
|
|
360
|
+
export function compileFormula(expression, env, self) {
|
|
361
|
+
const ast = parseFormula(expression);
|
|
362
|
+
const compiler = new Compiler(env, new Set(self ? [self] : []));
|
|
363
|
+
const result = compiler.compile(ast);
|
|
364
|
+
if (result.type === "null") {
|
|
365
|
+
throw typeError("A formula cannot always be null", ast.span);
|
|
366
|
+
}
|
|
367
|
+
return { type: result.type, sql: result.sql, fields: [...compiler.fieldsRead] };
|
|
368
|
+
}
|
|
369
|
+
/** Like compileFormula, but returns the issue instead of throwing. */
|
|
370
|
+
export function checkFormula(expression, env, self) {
|
|
371
|
+
try {
|
|
372
|
+
return { ok: true, formula: compileFormula(expression, env, self) };
|
|
373
|
+
}
|
|
374
|
+
catch (error) {
|
|
375
|
+
if (error instanceof FormulaError)
|
|
376
|
+
return { ok: false, issue: error.issue };
|
|
377
|
+
throw error;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type FormulaNode, type Span } from "./ast.ts";
|
|
2
|
+
type TokenKind = "number" | "string" | "ident" | "op" | "lparen" | "rparen" | "comma" | "eof";
|
|
3
|
+
interface Token {
|
|
4
|
+
kind: TokenKind;
|
|
5
|
+
text: string;
|
|
6
|
+
/** Decoded value for string tokens. */
|
|
7
|
+
value?: string;
|
|
8
|
+
span: Span;
|
|
9
|
+
}
|
|
10
|
+
export declare function tokenize(source: string): Token[];
|
|
11
|
+
/** Parses a formula expression into an AST. Throws FormulaError. */
|
|
12
|
+
export declare function parseFormula(source: string): FormulaNode;
|
|
13
|
+
export {};
|