@gramlot/gramlot 0.2.18 → 0.2.20

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/dist/gramlot.js CHANGED
@@ -11159,16 +11159,16 @@ function toQs(value) {
11159
11159
  return value.map((item) => String(item)).join("&");
11160
11160
  }
11161
11161
  if (value !== null && typeof value === "object") {
11162
- const parts = [];
11162
+ const parts2 = [];
11163
11163
  for (const [k, v] of Object.entries(value)) {
11164
11164
  const [encoded, result] = rawEncode(v, true);
11165
11165
  if (encoded) {
11166
- parts.push(`${k}=${result}`);
11166
+ parts2.push(`${k}=${result}`);
11167
11167
  } else {
11168
- parts.push(`${k}=${v}`);
11168
+ parts2.push(`${k}=${v}`);
11169
11169
  }
11170
11170
  }
11171
- return parts.join("&");
11171
+ return parts2.join("&");
11172
11172
  }
11173
11173
  throw new TypeError(`toQs expects object or array, got ${typeof value}`);
11174
11174
  }
@@ -11176,18 +11176,18 @@ function fromQs(data) {
11176
11176
  if (!data) {
11177
11177
  return [];
11178
11178
  }
11179
- const parts = data.split("&");
11180
- const hasEq = parts.map((p) => p.includes("="));
11179
+ const parts2 = data.split("&");
11180
+ const hasEq = parts2.map((p) => p.includes("="));
11181
11181
  const allWithEq = hasEq.every(Boolean);
11182
11182
  const noneWithEq = !hasEq.some(Boolean);
11183
11183
  if (!allWithEq && !noneWithEq) {
11184
11184
  throw new Error("QS format error: mixed items with and without '='");
11185
11185
  }
11186
11186
  if (noneWithEq) {
11187
- return parts.map((p) => fromTytx(p));
11187
+ return parts2.map((p) => fromTytx(p));
11188
11188
  }
11189
11189
  const result = {};
11190
- for (const part of parts) {
11190
+ for (const part of parts2) {
11191
11191
  const eqIndex = part.indexOf("=");
11192
11192
  const key = part.slice(0, eqIndex);
11193
11193
  const value = part.slice(eqIndex + 1);
@@ -12983,15 +12983,15 @@ var Bag = class _Bag {
12983
12983
  * @returns {string|null} The relative path, or null if not a descendant.
12984
12984
  */
12985
12985
  relativePath(node) {
12986
- const parts = [];
12986
+ const parts2 = [];
12987
12987
  let current = node;
12988
12988
  while (current !== null) {
12989
12989
  if (current.parentBag === this) {
12990
- parts.push(current.label);
12991
- parts.reverse();
12992
- return parts.join(".");
12990
+ parts2.push(current.label);
12991
+ parts2.reverse();
12992
+ return parts2.join(".");
12993
12993
  }
12994
- parts.push(current.label);
12994
+ parts2.push(current.label);
12995
12995
  current = current.parentNode;
12996
12996
  }
12997
12997
  return null;
@@ -14723,11 +14723,11 @@ ${content}`;
14723
14723
  * @private
14724
14724
  */
14725
14725
  _bagToXml(selfClosedTags = null, pretty = false, depth = 0) {
14726
- const parts = [];
14726
+ const parts2 = [];
14727
14727
  for (const node of this._nodes) {
14728
- parts.push((pretty ? " ".repeat(depth) : "") + this._nodeToXml(node, selfClosedTags, pretty, depth));
14728
+ parts2.push((pretty ? " ".repeat(depth) : "") + this._nodeToXml(node, selfClosedTags, pretty, depth));
14729
14729
  }
14730
- return parts.join(pretty ? "\n" : "");
14730
+ return parts2.join(pretty ? "\n" : "");
14731
14731
  }
14732
14732
  /**
14733
14733
  * Convert a BagNode to XML string (internal).
@@ -15059,8 +15059,8 @@ ${" ".repeat(depth)}</${tag2}>`;
15059
15059
  let attrStr = "";
15060
15060
  const attrs = node.attr;
15061
15061
  if (attrs && Object.keys(attrs).length > 0) {
15062
- const parts = Object.entries(attrs).map(([k, v]) => `${k}=${JSON.stringify(v)}`);
15063
- attrStr = ` [${parts.join(", ")}]`;
15062
+ const parts2 = Object.entries(attrs).map(([k, v]) => `${k}=${JSON.stringify(v)}`);
15063
+ attrStr = ` [${parts2.join(", ")}]`;
15064
15064
  }
15065
15065
  const branch = isLast ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ";
15066
15066
  const childPrefix = _prefix + (isLast ? " " : "\u2502 ");
@@ -15745,13 +15745,13 @@ function declaration(value, path, isElement, customTypes) {
15745
15745
  function parents(value) {
15746
15746
  return value ? value.split(",").map((x) => x.trim()).filter(Boolean) : [];
15747
15747
  }
15748
- function inherit(base, own) {
15749
- const out = { ...own };
15748
+ function inherit(base, own2) {
15749
+ const out = { ...own2 };
15750
15750
  for (const [key, value] of Object.entries(base)) {
15751
15751
  if (key === "inherits_from" || key.startsWith("_")) continue;
15752
15752
  if (!out[key]) out[key] = value;
15753
15753
  }
15754
- out._meta = { ...base._meta || {}, ...own._meta || {} };
15754
+ out._meta = { ...base._meta || {}, ...own2._meta || {} };
15755
15755
  return out;
15756
15756
  }
15757
15757
  function compileDeclaration(value) {
@@ -15778,9 +15778,9 @@ function resolveGrammarDeclarations({ abstracts: rawAbstracts = {}, elements: ra
15778
15778
  const state = /* @__PURE__ */ new Map();
15779
15779
  for (const name of Object.keys(abstracts)) resolveAbstract(name, abstracts, state, `abstracts.${name}.inherits_from`);
15780
15780
  const elements = {};
15781
- for (const [name, own] of Object.entries(rawElements)) {
15782
- let out = { ...own };
15783
- for (const parent of parents(own.inherits_from)) {
15781
+ for (const [name, own2] of Object.entries(rawElements)) {
15782
+ let out = { ...own2 };
15783
+ for (const parent of parents(own2.inherits_from)) {
15784
15784
  const base = abstracts[parent];
15785
15785
  if (!base) fail(`elements.${name}.inherits_from`, `unknown abstract '${parent}'`);
15786
15786
  out = inherit(base, out);
@@ -17066,8 +17066,8 @@ function temporal(value, dtype) {
17066
17066
  return kind;
17067
17067
  }
17068
17068
  function patternDate(value, pattern, locale, kind) {
17069
- const parts = pattern.match(TOKENS) || [];
17070
- if (parts.join("") !== pattern) throw new RangeError("Unclosed format literal");
17069
+ const parts2 = pattern.match(TOKENS) || [];
17070
+ if (parts2.join("") !== pattern) throw new RangeError("Unclosed format literal");
17071
17071
  const pad = (v, n = 2) => String(v).padStart(n, "0");
17072
17072
  const name = (options) => new Intl.DateTimeFormat(locale, { timeZone: "UTC", ...options }).format(value);
17073
17073
  const date = {
@@ -17095,7 +17095,7 @@ function patternDate(value, pattern, locale, kind) {
17095
17095
  a: () => new Intl.DateTimeFormat(locale, { hour: "numeric", hour12: true, timeZone: "UTC" }).formatToParts(value).find((p) => p.type === "dayPeriod").value
17096
17096
  };
17097
17097
  const tokens = { ...kind === "H" ? {} : date, ...kind === "D" ? {} : time };
17098
- return parts.map((part) => {
17098
+ return parts2.map((part) => {
17099
17099
  if (part.startsWith("'")) return part === "''" ? "'" : part.slice(1, -1).replaceAll("''", "'");
17100
17100
  if (!/^[a-zA-Z]/.test(part)) return part;
17101
17101
  if (!tokens[part]) throw new RangeError(`Unsupported date format token: ${part}`);
@@ -17405,15 +17405,15 @@ var HtmlRenderer = class extends RendererBase {
17405
17405
  return [...css].map(([key, value]) => `${key}: ${value}`).join("; ");
17406
17406
  }
17407
17407
  _formatAttrs(attrs) {
17408
- const parts = [];
17408
+ const parts2 = [];
17409
17409
  for (const [name, value] of Object.entries(attrs || {})) {
17410
17410
  if (BOOLEAN_ATTRS.has(name)) {
17411
- if (value) parts.push(` ${name}`);
17411
+ if (value) parts2.push(` ${name}`);
17412
17412
  } else {
17413
- parts.push(` ${name}="${this._htmlAttrValue(value)}"`);
17413
+ parts2.push(` ${name}="${this._htmlAttrValue(value)}"`);
17414
17414
  }
17415
17415
  }
17416
- return parts.join("");
17416
+ return parts2.join("");
17417
17417
  }
17418
17418
  _htmlAttrValue(value) {
17419
17419
  const text = value === true ? "true" : value === false ? "false" : String(value);
@@ -17442,27 +17442,27 @@ var HtmlRenderer = class extends RendererBase {
17442
17442
  }
17443
17443
  }
17444
17444
  _macro_transform(value, subs, css) {
17445
- const parts = value === void 0 ? [] : [String(value)];
17445
+ const parts2 = value === void 0 ? [] : [String(value)];
17446
17446
  for (const [name, subValue] of Object.entries(subs)) {
17447
- if (name === "rotate") parts.push(`rotate(${subValue}deg)`);
17448
- else if (name === "scale" || name === "translate") parts.push(`${name}(${subValue})`);
17449
- else if (name === "translate_x") parts.push(`translateX(${px(subValue)})`);
17450
- else if (name === "translate_y") parts.push(`translateY(${px(subValue)})`);
17451
- else if (name === "skew_x") parts.push(`skewX(${subValue}deg)`);
17452
- else if (name === "skew_y") parts.push(`skewY(${subValue}deg)`);
17453
- else parts.push(`${name.replaceAll("_", "-")}(${subValue})`);
17447
+ if (name === "rotate") parts2.push(`rotate(${subValue}deg)`);
17448
+ else if (name === "scale" || name === "translate") parts2.push(`${name}(${subValue})`);
17449
+ else if (name === "translate_x") parts2.push(`translateX(${px(subValue)})`);
17450
+ else if (name === "translate_y") parts2.push(`translateY(${px(subValue)})`);
17451
+ else if (name === "skew_x") parts2.push(`skewX(${subValue}deg)`);
17452
+ else if (name === "skew_y") parts2.push(`skewY(${subValue}deg)`);
17453
+ else parts2.push(`${name.replaceAll("_", "-")}(${subValue})`);
17454
17454
  }
17455
- if (parts.length) css.set("transform", parts.join(" "));
17455
+ if (parts2.length) css.set("transform", parts2.join(" "));
17456
17456
  }
17457
17457
  _macro_filter(value, subs, css) {
17458
- const parts = value === void 0 ? [] : [String(value)];
17458
+ const parts2 = value === void 0 ? [] : [String(value)];
17459
17459
  for (const [name, subValue] of Object.entries(subs)) {
17460
- if (name === "rotate") parts.push(`hue-rotate(${subValue}deg)`);
17461
- else if (name === "blur") parts.push(`blur(${px(subValue)})`);
17462
- else if (name === "drop_shadow") parts.push(`drop-shadow(${subValue})`);
17463
- else parts.push(`${name.replaceAll("_", "-")}(${subValue})`);
17460
+ if (name === "rotate") parts2.push(`hue-rotate(${subValue}deg)`);
17461
+ else if (name === "blur") parts2.push(`blur(${px(subValue)})`);
17462
+ else if (name === "drop_shadow") parts2.push(`drop-shadow(${subValue})`);
17463
+ else parts2.push(`${name.replaceAll("_", "-")}(${subValue})`);
17464
17464
  }
17465
- if (parts.length) css.set("filter", parts.join(" "));
17465
+ if (parts2.length) css.set("filter", parts2.join(" "));
17466
17466
  }
17467
17467
  _macro_transition(value, subs, css) {
17468
17468
  if (value !== void 0) css.set("transition", String(value));
@@ -21878,6 +21878,211 @@ var Handler = class {
21878
21878
  }
21879
21879
  };
21880
21880
 
21881
+ // src/binding/pointer.js
21882
+ function pointerTransform(value) {
21883
+ if (typeof value !== "string" || !/^[\^=](?!=)/.test(value)) return null;
21884
+ const index = value.indexOf(":");
21885
+ if (index < 0) return null;
21886
+ const expression = value[index + 1] === "=";
21887
+ return { pointer: value.slice(0, index), expression, body: value.slice(index + (expression ? 2 : 1)) };
21888
+ }
21889
+ var SLOT = /^\{(\??[A-Za-z_][A-Za-z0-9_]*|\?)?\}/;
21890
+ function failure(node, name, message) {
21891
+ return new Error(`${node.nodeTag} '${node.label}': '${name}': ${message}`);
21892
+ }
21893
+ function pointerTemplate(body, read) {
21894
+ let result = "", blocked = false;
21895
+ for (let i = 0; i < body.length; ) {
21896
+ if (body[i] !== "{" && body[i] !== "}") {
21897
+ result += body[i++];
21898
+ continue;
21899
+ }
21900
+ const match = body.slice(i).match(SLOT);
21901
+ if (!match) throw new SyntaxError("Invalid pointer template placeholder");
21902
+ const slot = match[1] ?? "";
21903
+ const optional = slot.startsWith("?");
21904
+ const value = read(optional ? slot.slice(1) : slot);
21905
+ if (value == null || value === "" && !optional) blocked = true;
21906
+ else result += String(value);
21907
+ i += match[0].length;
21908
+ }
21909
+ return blocked ? null : result;
21910
+ }
21911
+ function pointerExpression(body) {
21912
+ const slots = [], identifiers = /* @__PURE__ */ new Set();
21913
+ let text = "", operand = true;
21914
+ for (let i = 0; i < body.length; ) {
21915
+ const start = i, c = body[i];
21916
+ if (c === '"' || c === "'" || c === "`") {
21917
+ i++;
21918
+ while (i < body.length) {
21919
+ if (body[i] === "\\") {
21920
+ i += 2;
21921
+ continue;
21922
+ }
21923
+ if (body[i++] === c) break;
21924
+ }
21925
+ text += body.slice(start, i);
21926
+ operand = false;
21927
+ continue;
21928
+ }
21929
+ if (body.startsWith("//", i)) {
21930
+ i = body.indexOf("\n", i);
21931
+ if (i < 0) i = body.length;
21932
+ text += body.slice(start, i);
21933
+ continue;
21934
+ }
21935
+ if (body.startsWith("/*", i)) {
21936
+ const end = body.indexOf("*/", i + 2);
21937
+ i = end < 0 ? body.length : end + 2;
21938
+ text += body.slice(start, i);
21939
+ continue;
21940
+ }
21941
+ if (c === "/" && operand) {
21942
+ let bracket = false;
21943
+ i++;
21944
+ while (i < body.length) {
21945
+ const current = body[i++];
21946
+ if (current === "\\") {
21947
+ i++;
21948
+ continue;
21949
+ }
21950
+ if (current === "[") bracket = true;
21951
+ else if (current === "]") bracket = false;
21952
+ else if (current === "/" && !bracket) break;
21953
+ }
21954
+ while (/[a-z]/i.test(body[i] ?? "") && i < body.length) i++;
21955
+ text += body.slice(start, i);
21956
+ operand = false;
21957
+ continue;
21958
+ }
21959
+ const slot = c === "{" ? body.slice(i).match(SLOT) : null;
21960
+ if (slot) {
21961
+ const name = slot[1] ?? "";
21962
+ if (name.startsWith("?")) throw new SyntaxError("Optional slots are supported in pointer templates only");
21963
+ text += `_pointerValues[${slots.length}]`;
21964
+ slots.push(name);
21965
+ i += slot[0].length;
21966
+ operand = false;
21967
+ continue;
21968
+ }
21969
+ const word = body.slice(i).match(/^[A-Za-z_$][\w$]*/);
21970
+ if (word) {
21971
+ identifiers.add(word[0]);
21972
+ text += word[0];
21973
+ i += word[0].length;
21974
+ operand = ["return", "typeof", "void", "delete", "new", "in", "instanceof", "yield", "await"].includes(word[0]);
21975
+ continue;
21976
+ }
21977
+ text += c;
21978
+ i++;
21979
+ if (!/\s/.test(c)) operand = /[([{,:;=!?&|+*%~<>\/-]/.test(c);
21980
+ }
21981
+ return { text, slots, identifiers };
21982
+ }
21983
+ function pointerDependencies(node, raw, seen = /* @__PURE__ */ new Set()) {
21984
+ const transform = pointerTransform(raw);
21985
+ const names = [];
21986
+ if (transform?.expression) names.push(...pointerExpression(transform.body).slots.filter(Boolean));
21987
+ else if (transform) pointerTemplate(transform.body, (name) => {
21988
+ if (name) names.push(name);
21989
+ return "";
21990
+ });
21991
+ else if (typeof raw === "string" && raw.startsWith("==")) names.push(...pointerExpression(raw.slice(2)).identifiers);
21992
+ else if (typeof raw === "string") names.push(...[...raw.matchAll(/(?<!\\)\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g)].map((match) => match[1]));
21993
+ const attrs = new Map(sourceAttributeItems(node.getAttr()));
21994
+ for (const name of names) {
21995
+ if (seen.has(name) || !attrs.has(name)) continue;
21996
+ seen.add(name);
21997
+ pointerDependencies(node, attrs.get(name), seen);
21998
+ }
21999
+ return seen;
22000
+ }
22001
+ function attributeReader(node, items, context = node) {
22002
+ const values = /* @__PURE__ */ new Map(), active = /* @__PURE__ */ new Set(), consumed = /* @__PURE__ */ new Set();
22003
+ const compiler = node.rootBuilder.binding?.inlineCompiler;
22004
+ const current = /* @__PURE__ */ new Map();
22005
+ for (const [name, raw] of items) {
22006
+ if (typeof name !== "string") continue;
22007
+ const pointer = pointerTransform(raw)?.pointer ?? raw;
22008
+ current.set(name, pointer instanceof BagResolver ? pointer.resolve() : node.pointerType(pointer) ? context.getRelativeData(pointer) : pointer);
22009
+ }
22010
+ const resolve = (name) => {
22011
+ if (values.has(name)) return values.get(name);
22012
+ if (!items.has(name)) throw failure(node, name, "referenced Source attribute does not exist");
22013
+ if (active.has(name)) throw failure(node, name, `cyclic attribute dependency: ${[...active, name].join(" -> ")}`);
22014
+ active.add(name);
22015
+ const raw = items.get(name), transform = pointerTransform(raw);
22016
+ const leading = transform ? current.get(name) : null;
22017
+ let result;
22018
+ const read = (key) => {
22019
+ if (!key) return leading;
22020
+ return resolve(key);
22021
+ };
22022
+ try {
22023
+ if (transform) {
22024
+ if (transform.expression) {
22025
+ const { text, slots } = pointerExpression(transform.body);
22026
+ const inputs = slots.map(read);
22027
+ result = compiler ? compiler.compilePointerExpression(node, name, raw, text)(inputs) : null;
22028
+ } else {
22029
+ result = pointerTemplate(transform.body, read);
22030
+ if (leading == null) result = null;
22031
+ }
22032
+ } else if (typeof raw === "string" && raw.startsWith("==")) {
22033
+ const names = pointerExpression(raw.slice(2)).identifiers;
22034
+ const args = {};
22035
+ for (const key of names) if (key !== name && key !== "_F" && items.has(key)) args[key] = resolve(key);
22036
+ result = compiler ? compiler.compile(
22037
+ node,
22038
+ name,
22039
+ raw,
22040
+ [...Object.keys(args), "_F"],
22041
+ `return (${raw.slice(2)}
22042
+ )`
22043
+ )({ ...args, _F: (value, options) => node.rootBuilder.binding.gramlot.format(value, options) }) : null;
22044
+ } else {
22045
+ result = current.get(name);
22046
+ if (typeof result === "string" && !node._getMeta("data_element")) {
22047
+ result = result.replace(/(\\)?\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (token, escaped, key) => {
22048
+ if (escaped) return token.slice(1);
22049
+ consumed.add(key);
22050
+ return String(resolve(key) ?? "");
22051
+ });
22052
+ }
22053
+ }
22054
+ values.set(name, result);
22055
+ return result;
22056
+ } finally {
22057
+ active.delete(name);
22058
+ }
22059
+ };
22060
+ return { resolve, consumed, current };
22061
+ }
22062
+ function preparePointerItems(node, items) {
22063
+ const transformed = [...items].filter(([name, raw]) => typeof name === "string" && pointerTransform(raw));
22064
+ if (!transformed.length) return items;
22065
+ const reader = attributeReader(node, items);
22066
+ const results = new Map(transformed.map(([name]) => [name, reader.resolve(name)]));
22067
+ for (const [name, raw] of items) {
22068
+ if (typeof name !== "string" || pointerTransform(raw)) continue;
22069
+ if (raw instanceof BagResolver || node.pointerType(raw)) {
22070
+ const result = reader.current.get(name);
22071
+ items.set(name, new BagCbResolver(() => result));
22072
+ }
22073
+ }
22074
+ for (const [name] of transformed) {
22075
+ const result = results.get(name);
22076
+ items.set(name, new BagCbResolver(() => result));
22077
+ }
22078
+ if (!node._getMeta("data_element")) for (const name of reader.consumed) items.delete(name);
22079
+ return items;
22080
+ }
22081
+ function resolvePointerAttribute(node, name, context = node) {
22082
+ const items = new Map([...Object.entries(node.getAttr()), ...sourceAttributeItems(node.getAttr())]);
22083
+ return attributeReader(node, items, context).resolve(name);
22084
+ }
22085
+
21881
22086
  // src/builder/source.js
21882
22087
  var CODE_ATTRIBUTES = {
21883
22088
  dataFormula: ["formula", "_if", "_else", "_ask_if", "_ask_onCancel"],
@@ -21905,13 +22110,13 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
21905
22110
  * every `==` attribute (canonical name) and a `==` node value (`''`).
21906
22111
  */
21907
22112
  codeAttributes() {
21908
- const own = [
22113
+ const own2 = [
21909
22114
  ...CODE_ATTRIBUTES[this.nodeTag] ?? [],
21910
22115
  ...typeof this.getAttr("remote") === "string" ? REMOTE_CODE_ATTRIBUTES : []
21911
22116
  ];
21912
22117
  const items = [];
21913
22118
  for (const [name, value] of Object.entries(this.getAttr() ?? {})) {
21914
- if (typeof value === "string" && (own.includes(name) || name.startsWith("connect_on") || name.startsWith("subscribe_") || name.startsWith("selfsubscribe_"))) items.push([name, value]);
22119
+ if (typeof value === "string" && (own2.includes(name) || name.startsWith("connect_on") || name.startsWith("subscribe_") || name.startsWith("selfsubscribe_"))) items.push([name, value]);
21915
22120
  }
21916
22121
  for (const attribute of ["ask", "_ask"]) {
21917
22122
  const spec = this.getAttr(attribute);
@@ -21941,6 +22146,9 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
21941
22146
  }
21942
22147
  code.set(name, text);
21943
22148
  }
22149
+ for (const [name, text] of [...sourceAttributeItems(this.getAttr()), ["datapath", this.getAttr("datapath")]]) {
22150
+ if (pointerTransform(text)?.expression) code.set(name, text);
22151
+ }
21944
22152
  this.#activatedCode = code;
21945
22153
  }
21946
22154
  /** The text of the inline code `name` received with the Source, or null when it was not received. */
@@ -21979,7 +22187,14 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
21979
22187
  }
21980
22188
  /** Builder's `^` pointers, except the attributes ending in `_path`, which hold a bare path. */
21981
22189
  pointers() {
21982
- return super.pointers().filter(([name, pointer]) => !this.#isPathAttribute(name, pointer));
22190
+ const datapath = this.getAttr("datapath");
22191
+ const dependencies = pointerTransform(datapath) ? pointerDependencies(this, datapath) : /* @__PURE__ */ new Set();
22192
+ const result = super.pointers().filter(([name, pointer]) => !dependencies.has(name) && !this.#isPathAttribute(name, pointer)).map(([name, pointer]) => [name, pointerTransform(pointer)?.pointer ?? pointer]);
22193
+ for (const name of dependencies) {
22194
+ const value = this.getAttr(name);
22195
+ if (this.pointerType(value) === "^") result.push(["datapath", pointerTransform(value)?.pointer ?? value]);
22196
+ }
22197
+ return result;
21983
22198
  }
21984
22199
  /**
21985
22200
  * Builder's items to resolve, with the Gramlot rules applied before Builder's runtimeValues:
@@ -21990,10 +22205,14 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
21990
22205
  const items = super.runtimeToEvaluate();
21991
22206
  for (const [name, value] of items) {
21992
22207
  if (!this.pointerType(value)) continue;
22208
+ if (pointerTransform(value)) {
22209
+ if (typeof name !== "string") throw new Error(`${this.nodeTag} '${this.label}': pointer suffixes belong to attributes; use format/mask for node text`);
22210
+ continue;
22211
+ }
21993
22212
  if (this.#isPathAttribute(name, value)) items.set(name, value.slice(1));
21994
22213
  else if (this.absDatapath(value) === null) items.set(name, null);
21995
22214
  }
21996
- return items;
22215
+ return preparePointerItems(this, items);
21997
22216
  }
21998
22217
  /**
21999
22218
  * The value of the attribute `name`; for an attribute ending in `_path` written as a pointer, the
@@ -22002,6 +22221,7 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
22002
22221
  */
22003
22222
  pathAttribute(name) {
22004
22223
  const value = this.getAttr(name);
22224
+ if (pointerTransform(value)) return resolvePointerAttribute(this, name);
22005
22225
  return this.pointerType(value) && this.#isPathAttribute(name, value) ? value.slice(1) : value;
22006
22226
  }
22007
22227
  /** Builder's read; null on a null path (Q7). */
@@ -22080,6 +22300,7 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
22080
22300
  }
22081
22301
  /** Builder's absDatapath, keeping `?attr` on symbolic paths. */
22082
22302
  absDatapath(path) {
22303
+ path = pointerTransform(path)?.pointer ?? path;
22083
22304
  const bare = this.pointerType(path) ? path.slice(1) : path;
22084
22305
  if (bare.startsWith("#") && bare.includes("?")) {
22085
22306
  const [target, attr] = bare.split("?", 2);
@@ -22132,6 +22353,10 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
22132
22353
  * the context of the carrier's parent; the value counts as if written in place of the pointer.
22133
22354
  */
22134
22355
  #variableDatapath(carrier, pointer) {
22356
+ if (pointerTransform(pointer)) {
22357
+ const value2 = resolvePointerAttribute(carrier, "datapath", carrier.parentNode);
22358
+ return value2 == null || value2 === "" ? null : value2;
22359
+ }
22135
22360
  const path = carrier.parentNode.absDatapath(pointer);
22136
22361
  if (path === null) return null;
22137
22362
  const value = this.data.getItem(path);
@@ -22139,6 +22364,7 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
22139
22364
  }
22140
22365
  /** Whether `name` ends in `_path`; a pointer there loses its symbol, with one warning per attribute. */
22141
22366
  #isPathAttribute(name, value) {
22367
+ if (pointerTransform(value)) return false;
22142
22368
  if (typeof name !== "string" || !name.endsWith("_path")) return false;
22143
22369
  if (!this.#reportedPathPointers.has(name)) {
22144
22370
  this.#reportedPathPointers.add(name);
@@ -22208,6 +22434,112 @@ if ((getSubtypeDict(GramlotBuilderBag.tytxSuffix).GramlotBuilderBag ?? GramlotBu
22208
22434
  }
22209
22435
  setSubtypeDict(GramlotBuilderBag.tytxSuffix, { ...getSubtypeDict(GramlotBuilderBag.tytxSuffix), GramlotBuilderBag });
22210
22436
 
22437
+ // src/format.js
22438
+ function validateMask(mask) {
22439
+ if (mask != null && (typeof mask !== "string" || /[{}]/.test(mask.replaceAll("{}", "")))) {
22440
+ throw new RangeError("This formatter mask supports only {} placeholders");
22441
+ }
22442
+ }
22443
+ function applyMask(text, mask) {
22444
+ validateMask(mask);
22445
+ return mask == null ? text : mask.replaceAll("{}", () => text);
22446
+ }
22447
+ function inferredType(value) {
22448
+ if (value instanceof Date) {
22449
+ const epochDay = value.getUTCFullYear() === 1970 && value.getUTCMonth() === 0 && value.getUTCDate() === 1;
22450
+ const midnight = value.getUTCHours() === 0 && value.getUTCMinutes() === 0 && value.getUTCSeconds() === 0 && value.getUTCMilliseconds() === 0;
22451
+ if (epochDay && !midnight) return "H";
22452
+ if (midnight && !epochDay) return "D";
22453
+ return "DHZ";
22454
+ }
22455
+ if (typeof value === "number") return Number.isInteger(value) ? "L" : "R";
22456
+ throw new TypeError("Formatting requires finite JavaScript numbers or valid Date objects");
22457
+ }
22458
+ function temporalText(value, dtype, { pattern = "short", locale, timeZone }) {
22459
+ if (!["short", "medium", "long", "full"].includes(pattern)) {
22460
+ throw new RangeError("Temporal formatting currently supports short, medium, long and full only");
22461
+ }
22462
+ if (dtype === "DHZ" && (typeof timeZone !== "string" || !timeZone)) {
22463
+ throw new TypeError("DHZ formatting currently requires an explicit timeZone");
22464
+ }
22465
+ const options = { timeZone: dtype === "DHZ" ? timeZone : "UTC" };
22466
+ if (dtype !== "H") options.dateStyle = pattern;
22467
+ if (dtype !== "D") options.timeStyle = pattern;
22468
+ return new Intl.DateTimeFormat(locale, options).format(value);
22469
+ }
22470
+ function numericSection(section) {
22471
+ const match = /^(-|\()?(#,##0|0+)(?:\.(0*#*))?(\))?$/.exec(section);
22472
+ if (!match || match[1] === "(" !== (match[4] === ")") || section.endsWith(".")) {
22473
+ throw new RangeError(`Unsupported numeric pattern section: ${section}`);
22474
+ }
22475
+ const fraction = match[3] ?? "";
22476
+ return {
22477
+ prefix: match[1] ?? "",
22478
+ suffix: match[4] ?? "",
22479
+ intl: {
22480
+ useGrouping: match[2].startsWith("#,##") ? "always" : false,
22481
+ minimumIntegerDigits: match[2].replace("#,##", "").length,
22482
+ minimumFractionDigits: fraction.replaceAll("#", "").length,
22483
+ maximumFractionDigits: fraction.length
22484
+ }
22485
+ };
22486
+ }
22487
+ function numericPattern(pattern) {
22488
+ const sections = pattern.split(";");
22489
+ if (sections.length > 3) throw new RangeError("Numeric patterns support at most three sections");
22490
+ const positive = numericSection(sections[0]);
22491
+ if (positive.prefix || positive.suffix) throw new RangeError("Positive-section affixes are not implemented");
22492
+ const zero = sections.length === 3 ? sections[1] : null;
22493
+ if (zero !== null && zero !== "" && zero !== "-") numericSection(zero);
22494
+ const negative = sections.length > 1 ? numericSection(sections.at(-1)) : null;
22495
+ return { positive, zero, negative };
22496
+ }
22497
+ function formatValue(value, options = {}, context = {}) {
22498
+ if (value === null) return "";
22499
+ if (typeof options === "string") options = { pattern: options };
22500
+ if (!options || typeof options !== "object" || Array.isArray(options)) {
22501
+ throw new TypeError("Format options must be a pattern string or an options object");
22502
+ }
22503
+ for (const key of Object.keys(options)) {
22504
+ if (!["pattern", "locale", "mask", "dtype", "timeZone"].includes(key)) throw new RangeError(`Unsupported format option: ${key}`);
22505
+ }
22506
+ options = { ...options, locale: options.locale ?? context.locale, timeZone: options.timeZone ?? context.timeZone };
22507
+ const dtype = options.dtype === void 0 ? inferredType(value) : options.dtype;
22508
+ const temporal2 = ["D", "H", "DHZ"].includes(dtype);
22509
+ if (!temporal2 && !["L", "R", "N"].includes(dtype)) throw new RangeError(`Unsupported format dtype: ${dtype}`);
22510
+ if (temporal2) {
22511
+ if (!(value instanceof Date) || !Number.isFinite(value.getTime())) throw new TypeError(`${dtype} requires a valid Date object`);
22512
+ } else if (typeof value !== "number" || !Number.isFinite(value)) {
22513
+ throw new TypeError(`${dtype} formatting requires finite JavaScript numbers`);
22514
+ }
22515
+ if (dtype === "L" && !Number.isInteger(value)) throw new TypeError("L formatting requires an integer");
22516
+ const { pattern, locale, mask } = options;
22517
+ if (!temporal2 && typeof pattern !== "string") throw new TypeError("Numeric formatting currently requires an explicit pattern");
22518
+ if (typeof locale !== "string" || !locale) throw new TypeError("Formatting currently requires an explicit locale");
22519
+ const intl = temporal2 ? Intl.DateTimeFormat : Intl.NumberFormat;
22520
+ if (!intl.supportedLocalesOf([locale]).length) throw new RangeError(`Unsupported format locale: ${locale}`);
22521
+ validateMask(mask);
22522
+ if (temporal2) {
22523
+ const text2 = temporalText(value, dtype, options);
22524
+ return applyMask(text2, mask);
22525
+ }
22526
+ const { positive, zero, negative } = numericPattern(pattern);
22527
+ let text;
22528
+ if (value === 0 && zero !== null) {
22529
+ if (zero === "") return "";
22530
+ if (zero === "-") text = "-";
22531
+ else {
22532
+ const section = numericSection(zero);
22533
+ text = section.prefix + new Intl.NumberFormat(locale, section.intl).format(0) + section.suffix;
22534
+ }
22535
+ } else {
22536
+ const affix = value < 0 && negative ? negative : positive;
22537
+ const number = value < 0 && negative ? -value : value === 0 ? 0 : value;
22538
+ text = affix.prefix + new Intl.NumberFormat(locale, positive.intl).format(number) + affix.suffix;
22539
+ }
22540
+ return applyMask(text, mask);
22541
+ }
22542
+
22211
22543
  // src/renderer/attributes.js
22212
22544
  var XHTML_NS = "http://www.w3.org/1999/xhtml";
22213
22545
  var SVG_NS = "http://www.w3.org/2000/svg";
@@ -22245,7 +22577,7 @@ var NATIVE_ATTRIBUTES = {
22245
22577
  canvas: ["width", "height"]
22246
22578
  };
22247
22579
  var TEMPLATE_REFERENCE = /(?<!\\)\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
22248
- var DISPLAY_ATTRIBUTES = ["format", "mask", "locale", "places", "dtype"];
22580
+ var DISPLAY_ATTRIBUTES = ["format", "mask", "locale", "timeZone", "places", "dtype"];
22249
22581
  var URL_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "src", "formaction", "xlink:href", "xlink_href"]);
22250
22582
  function withoutBindingAttributes(attrs) {
22251
22583
  return Object.fromEntries(Object.entries(attrs).filter(([name, value]) => !(value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef")) && !BINDING_ATTRIBUTES.has(name) && !BINDING_ATTRIBUTE_PREFIXES.some((prefix) => name.startsWith(prefix))));
@@ -22321,15 +22653,31 @@ function splitNativeAttributes(tag2, attrs) {
22321
22653
  function textValue(value) {
22322
22654
  return String(value);
22323
22655
  }
22324
- function displayItem(item, attrs) {
22656
+ function displayItem(item, attrs, format = null) {
22325
22657
  const rest = { ...attrs };
22326
- const mask = rest.mask;
22658
+ const { mask, format: pattern, locale, timeZone, dtype, places } = rest;
22327
22659
  for (const name of DISPLAY_ATTRIBUTES) delete rest[name];
22328
- if (Array.isArray(item)) return [item, rest];
22329
- if (typeof item === "boolean") item = textValue(item);
22330
- if (mask == null) return [item, rest];
22331
- const text = item == null ? "" : textValue(item);
22332
- return [text === "" ? text : String(mask).replaceAll("%s", () => text), rest];
22660
+ const display = (value) => {
22661
+ if (format && pattern != null) {
22662
+ if (places != null) throw new RangeError("places is not implemented; specify precision in format");
22663
+ return format(value, {
22664
+ pattern,
22665
+ mask,
22666
+ ...locale == null ? {} : { locale },
22667
+ ...timeZone == null ? {} : { timeZone },
22668
+ ...dtype == null ? {} : { dtype }
22669
+ });
22670
+ }
22671
+ if (typeof value === "boolean") value = textValue(value);
22672
+ if (mask == null) return value;
22673
+ const text = value == null ? "" : textValue(value);
22674
+ return text === "" ? text : applyMask(text, mask);
22675
+ };
22676
+ if (Array.isArray(item)) {
22677
+ if (Object.hasOwn(rest, "_text")) rest._text = display(rest._text);
22678
+ return [item, rest];
22679
+ }
22680
+ return [display(item), rest];
22333
22681
  }
22334
22682
  function templateParameters(value) {
22335
22683
  return typeof value === "string" ? [...value.matchAll(TEMPLATE_REFERENCE)].map(([, name]) => name) : [];
@@ -22531,14 +22879,14 @@ var GramlotHtmlRenderer = class extends HtmlRenderer {
22531
22879
  */
22532
22880
  adaptAttrs(attrs) {
22533
22881
  const { _meta, ...rest } = attrs;
22534
- const own = `${this.builder.constructor._name}_`;
22882
+ const own2 = `${this.builder.constructor._name}_`;
22535
22883
  const prefixes = this.builder.constructor.dialectPrefixes;
22536
22884
  const literal = {};
22537
22885
  const styled = {};
22538
22886
  for (const [name, value] of Object.entries(withoutBindingAttributes(rest))) {
22539
22887
  if (value == null) continue;
22540
- if (name.startsWith(own)) {
22541
- throw new Error(`${name}: the attribute prefix '${own}' is not accepted; use the prefix '${prefixes[0]}'`);
22888
+ if (name.startsWith(own2)) {
22889
+ throw new Error(`${name}: the attribute prefix '${own2}' is not accepted; use the prefix '${prefixes[0]}'`);
22542
22890
  }
22543
22891
  const prefix = prefixes.find((candidate) => name.startsWith(candidate));
22544
22892
  if (prefix) literal[name.slice(prefix.length)] = value;
@@ -22575,7 +22923,7 @@ var binding_default = {
22575
22923
  name: "binding",
22576
22924
  version: null,
22577
22925
  title: "Gramlot binding",
22578
- description: "Data-elements of Gramlot 0.2.0 with the signatures of decision P18; loaded after the HTML grammar."
22926
+ description: "Gramlot Data declarations and the plain HTML button; loaded after the HTML grammar."
22579
22927
  },
22580
22928
  abstracts: {},
22581
22929
  elements: {
@@ -22942,6 +23290,31 @@ var binding_default = {
22942
23290
  _meta: {
22943
23291
  data_element: true
22944
23292
  }
23293
+ },
23294
+ html_button: {
23295
+ doc: "Plain native HTML button without Gramlot click mechanisms.",
23296
+ sub_tags: "a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",
23297
+ parent_tags: null,
23298
+ inherits_from: null,
23299
+ ns: null,
23300
+ attributes: {
23301
+ parameters: [
23302
+ {
23303
+ name: "kwargs",
23304
+ kind: "var_keyword",
23305
+ role: "attribute",
23306
+ annotation: null,
23307
+ has_default: false
23308
+ }
23309
+ ],
23310
+ accepts_var_keyword: true,
23311
+ accepts_var_positional: false
23312
+ },
23313
+ node_label: null,
23314
+ collection_key: null,
23315
+ _meta: {
23316
+ render_tag: "button"
23317
+ }
22945
23318
  }
22946
23319
  }
22947
23320
  };
@@ -23012,6 +23385,12 @@ var DATA_PATH_ATTRIBUTES = {
23012
23385
  };
23013
23386
  var DATA_INLINE_ATTRIBUTES = { dataFormula: "formula", dataController: "script" };
23014
23387
  function dataElementError(tag2, attrs) {
23388
+ if (["input", "textarea", "select", "webcomponent"].includes(tag2) && pointerTransform(attrs.value)) {
23389
+ return "'value' does not accept pointer suffixes; use an ordinary value pointer";
23390
+ }
23391
+ if (tag2 === "html_button" && Object.keys(attrs).some((name) => ["action", "ask", "_delay", "fire"].includes(name) || name.startsWith("fire_"))) {
23392
+ return "plain HTML button: use button for action, ask, fire or _delay";
23393
+ }
23015
23394
  if (Object.hasOwn(attrs, "ask") && tag2 !== "button") return "'ask' is supported on buttons";
23016
23395
  if (Object.hasOwn(attrs, "_ask") && !["dataController", "dataFormula", "dataRpc"].includes(tag2)) return "'_ask' requires a controller, formula or RPC";
23017
23396
  if (["dataSetter", "dataRemote"].includes(tag2) && Object.keys(attrs).some((name) => name.startsWith("subscribe_") || name.startsWith("selfsubscribe_"))) {
@@ -23128,6 +23507,15 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
23128
23507
  if (error) throw new Error(`${node.nodeTag} '${node.label}': ${error}`);
23129
23508
  return super.validateNode(node, options);
23130
23509
  }
23510
+ /** Both button declarations occupy the native button slot in HTML content models. */
23511
+ _validateChildren(parentTag, info, tags, includeMinimum) {
23512
+ return super._validateChildren(
23513
+ parentTag,
23514
+ info,
23515
+ tags.map((tag2) => tag2 === "html_button" ? "button" : tag2),
23516
+ includeMinimum
23517
+ );
23518
+ }
23131
23519
  /** Custom elements are outside the native HTML child catalogue, as components are. */
23132
23520
  _countsForGrammar(info) {
23133
23521
  return info !== this.schema.webcomponent && super._countsForGrammar(info);
@@ -23815,7 +24203,7 @@ var AskDialog = class {
23815
24203
  let finished = false;
23816
24204
  let release = () => {
23817
24205
  };
23818
- const finish = (confirmed, failure = null) => {
24206
+ const finish = (confirmed, failure2 = null) => {
23819
24207
  if (finished) return;
23820
24208
  finished = true;
23821
24209
  const result = confirmed ? Object.fromEntries(fields.map((field) => [field.name, app.data.getItem(`${id}.${field.name}`)])) : null;
@@ -23824,7 +24212,7 @@ var AskDialog = class {
23824
24212
  try {
23825
24213
  app.src.source.popNode(id);
23826
24214
  if (app.data.getNode(id)) app.data.popNode(id);
23827
- if (failure) reject(failure);
24215
+ if (failure2) reject(failure2);
23828
24216
  else resolve(result);
23829
24217
  } catch (error) {
23830
24218
  reject(error);
@@ -23878,10 +24266,12 @@ var AskDialog = class {
23878
24266
  var ButtonBinding = class _ButtonBinding {
23879
24267
  #binding;
23880
24268
  #record;
23881
- /** The ButtonBinding of a built element, or null when the element is not a `<button>`. */
24269
+ #cancelDelay = null;
24270
+ #pendingCount = 0;
24271
+ /** The binding of a Gramlot button; html_button remains native despite its DOM tag. */
23882
24272
  static for(binding, record2) {
23883
24273
  const element = record2.element;
23884
- if (element?.namespaceURI !== XHTML_NS || element.localName !== "button") return null;
24274
+ if (binding.node.nodeTag !== "button" || element?.namespaceURI !== XHTML_NS || element.localName !== "button") return null;
23885
24275
  return new _ButtonBinding(binding, record2);
23886
24276
  }
23887
24277
  constructor(binding, record2) {
@@ -23940,6 +24330,7 @@ var ButtonBinding = class _ButtonBinding {
23940
24330
  }
23941
24331
  detach() {
23942
24332
  this.element.removeEventListener("click", this);
24333
+ this.#cancelDelay?.();
23943
24334
  }
23944
24335
  handleEvent(event) {
23945
24336
  this.onClick(event);
@@ -23956,6 +24347,36 @@ var ButtonBinding = class _ButtonBinding {
23956
24347
  event.stopPropagation();
23957
24348
  if (this.element.disabled) return;
23958
24349
  const counter = this.binding.countClick();
24350
+ let owner = this.node;
24351
+ while (owner && owner.getAttr("_delay") == null) owner = owner.parentNode;
24352
+ const delay = owner ? owner.builder.runtimeValues(owner)[1]._delay : 0;
24353
+ if (delay > 0) {
24354
+ const count = this.#pendingCount + 1;
24355
+ this.#cancelDelay?.();
24356
+ this.#pendingCount = count;
24357
+ const timer = setTimeout(() => {
24358
+ release();
24359
+ this.#cancelDelay = null;
24360
+ this.#pendingCount = 0;
24361
+ this.#execute(event, count);
24362
+ }, delay);
24363
+ const release = this.binding.track(() => this.#cancelDelay?.());
24364
+ this.#cancelDelay = () => {
24365
+ clearTimeout(timer);
24366
+ release();
24367
+ this.#cancelDelay = null;
24368
+ this.#pendingCount = 0;
24369
+ };
24370
+ return;
24371
+ }
24372
+ this.#cancelDelay?.();
24373
+ return this.#execute(event, counter);
24374
+ }
24375
+ /** Deliver the last event once; arguments are read when the mechanism executes. */
24376
+ #execute(event, counter) {
24377
+ if (this.binding.closed || this.element.disabled) return;
24378
+ const mechanism = this.mechanism;
24379
+ if (!mechanism) return;
23959
24380
  const node = this.node;
23960
24381
  const modifiers = eventToString(event);
23961
24382
  if (mechanism === "controller") {
@@ -24405,7 +24826,7 @@ var DataInstaller = class {
24405
24826
  const special = {};
24406
24827
  for (const [name, value] of Object.entries(attrs)) {
24407
24828
  if (name.startsWith("attr_")) {
24408
- special[name.slice(5)] = node.pointerType(value) ? node.getRelativeData(value) : value;
24829
+ special[name.slice(5)] = pointerTransform(value) ? resolvePointerAttribute(node, name) : node.pointerType(value) ? node.getRelativeData(value) : value;
24409
24830
  }
24410
24831
  }
24411
24832
  if (!Object.keys(special).length) return;
@@ -24467,7 +24888,7 @@ function requireProviderAttributes(node) {
24467
24888
  }
24468
24889
  return;
24469
24890
  }
24470
- const name = PROVIDER_ATTRIBUTES.find(isSet);
24891
+ const name = PROVIDER_ATTRIBUTES.find((name2) => isSet(name2) && !(name2 === "_delay" && !node._getMeta("data_element") && node.nodeTag !== "html_button"));
24471
24892
  if (!name) return;
24472
24893
  const tags = LIFECYCLE_ATTRIBUTES.includes(name) ? "dataFormula, dataController and dataRpc" : "dataFormula, dataController, dataRpc and dataRemote";
24473
24894
  throw new Error(`${node.nodeTag ?? "fragment"} '${node.label}': '${name}' is allowed only on ${tags}`);
@@ -24576,7 +24997,7 @@ var CONTROL_ATTRIBUTES = /* @__PURE__ */ new Set([
24576
24997
  var Provider = class {
24577
24998
  #binding;
24578
24999
  #registrations = [];
24579
- #timingRegistration = null;
25000
+ #timingRegistrations = /* @__PURE__ */ new Set();
24580
25001
  #stopTiming = null;
24581
25002
  #cancelDelay = null;
24582
25003
  // The AbortController of the in-flight call of a `dataRpc`: a new call aborts it (latest wins).
@@ -24617,6 +25038,7 @@ var Provider = class {
24617
25038
  }
24618
25039
  this.#closeRegistrations();
24619
25040
  const router = this.binding.runtime.router;
25041
+ const timingDependencies = pointerDependencies(node, node.getAttr("_timing"));
24620
25042
  for (const [name, pointer] of node.pointers()) {
24621
25043
  if (name === "datapath") continue;
24622
25044
  const absolute = node.absDatapath(pointer);
@@ -24624,7 +25046,7 @@ var Provider = class {
24624
25046
  const [path, attr = null] = absolute.split("?", 2);
24625
25047
  const registration = router.register({ path, attr, recipient: this });
24626
25048
  this.#registrations.push(registration);
24627
- if (name === "_timing") this.#timingRegistration = registration;
25049
+ if (name === "_timing" || timingDependencies.has(name)) this.#timingRegistrations.add(registration);
24628
25050
  }
24629
25051
  const subscriptions = this.binding.runtime.gramlot._subscriptions;
24630
25052
  for (const name of Object.keys(node.getAttr())) {
@@ -24649,7 +25071,7 @@ var Provider = class {
24649
25071
  * debounces, the last call wins, and the arguments are read when the body runs.
24650
25072
  */
24651
25073
  receive(change) {
24652
- if (change.registration === this.#timingRegistration) {
25074
+ if (this.#timingRegistrations.has(change.registration)) {
24653
25075
  this.#startTiming();
24654
25076
  return;
24655
25077
  }
@@ -24780,6 +25202,7 @@ var Provider = class {
24780
25202
  #resolved(name) {
24781
25203
  const node = this.node;
24782
25204
  const value = node.getAttr(name);
25205
+ if (pointerTransform(value)) return resolvePointerAttribute(node, name);
24783
25206
  return node.pointerType(value) ? node.getRelativeData(value) : value ?? null;
24784
25207
  }
24785
25208
  /**
@@ -24890,7 +25313,7 @@ var Provider = class {
24890
25313
  }
24891
25314
  #closeRegistrations() {
24892
25315
  for (const registration of this.#registrations.splice(0)) registration.close();
24893
- this.#timingRegistration = null;
25316
+ this.#timingRegistrations.clear();
24894
25317
  }
24895
25318
  };
24896
25319
  var FormulaProvider = class extends Provider {
@@ -25068,7 +25491,7 @@ var InlineCompiler = class {
25068
25491
  compileExpression(node, attr, code) {
25069
25492
  const expr = code.slice(2);
25070
25493
  const items = sourceAttributeItems(node.getAttr()).filter(([, raw]) => !isExpression2(raw));
25071
- const run = this.compile(node, attr, code, items.map(([name]) => name), `return ${expr}`);
25494
+ const run = this.compile(node, attr, code, [...items.map(([name]) => name).filter((name) => name !== "_F"), "_F"], `return ${expr}`);
25072
25495
  return (resolved2) => {
25073
25496
  const values = {};
25074
25497
  for (const [name, raw] of items) {
@@ -25082,9 +25505,15 @@ var InlineCompiler = class {
25082
25505
  values[name] = node.pointerType(raw) ? node.getRelativeData(raw) : raw;
25083
25506
  }
25084
25507
  }
25085
- return run(values);
25508
+ return run({ ...values, _F: (value, options) => this.runtime.gramlot.format(value, options) });
25086
25509
  };
25087
25510
  }
25511
+ /** Typed placeholder inputs, compiled under the exact declaration activated with Source. */
25512
+ compilePointerExpression(node, attr, code, expression) {
25513
+ const run = this.compile(node, attr, code, ["_pointerValues", "_F"], `return (${expression}
25514
+ )`);
25515
+ return (values) => run({ _pointerValues: values, _F: (value, options) => this.runtime.gramlot.format(value, options) });
25516
+ }
25088
25517
  /**
25089
25518
  * Release the compiled declarations of `node`: those of the attributes `names` (Source names; `''`
25090
25519
  * is the node value, `_if`/`_else`/`formula`/`script` their own), or all of them when `names` is null.
@@ -25536,7 +25965,7 @@ var NodeBinding = class {
25536
25965
  // The clicks of a button, counted for its whole semantic life: a rebuild keeps them (P9, S12).
25537
25966
  #clickCount = 0;
25538
25967
  // The registration of the node's own variable datapath, read in the parent's context.
25539
- #datapathRegistration = null;
25968
+ #datapathRegistrations = /* @__PURE__ */ new Set();
25540
25969
  constructor(runtime, node) {
25541
25970
  this.#runtime = runtime;
25542
25971
  this.#node = node;
@@ -25594,6 +26023,10 @@ var NodeBinding = class {
25594
26023
  const dataElement = node._getMeta("data_element");
25595
26024
  if (dataElement && !PROVIDERS[node.nodeTag]) return;
25596
26025
  if (!dataElement && typeof node.getAttr("remote") === "string") this.#remote ??= new RemoteBinding(this);
26026
+ const remoteDependencies = /* @__PURE__ */ new Set();
26027
+ if (this.remote) for (const [name, raw] of Object.entries(node.getAttr())) {
26028
+ if (name.startsWith("remote_")) for (const dependency of pointerDependencies(node, raw)) remoteDependencies.add(dependency);
26029
+ }
25597
26030
  for (const [name, pointer] of node.pointers()) {
25598
26031
  if (dataElement && name !== "datapath") continue;
25599
26032
  const context = name === "datapath" ? node.parentNode : node;
@@ -25602,8 +26035,8 @@ var NodeBinding = class {
25602
26035
  const [path, attr = null] = absolute.split("?", 2);
25603
26036
  const registration = this.runtime.router.register({ path, attr, recipient: this });
25604
26037
  this.#registrations.push(registration);
25605
- if (name === "datapath") this.#datapathRegistration = registration;
25606
- if (this.remote && (name === "remote" || name.startsWith("remote_"))) this.#remoteRegistrations.add(registration);
26038
+ if (name === "datapath") this.#datapathRegistrations.add(registration);
26039
+ if (this.remote && (name === "remote" || name.startsWith("remote_") || remoteDependencies.has(name))) this.#remoteRegistrations.add(registration);
25607
26040
  }
25608
26041
  if (!dataElement) {
25609
26042
  this.#registerTopics();
@@ -25645,7 +26078,7 @@ var NodeBinding = class {
25645
26078
  * after a registration of `remote` or of a `remote_<k>` parameter requested the fragment again.
25646
26079
  */
25647
26080
  receive(change) {
25648
- if (change.registration === this.#datapathRegistration) {
26081
+ if (this.#datapathRegistrations.has(change.registration)) {
25649
26082
  this.runtime.rebindBranch(this.node);
25650
26083
  return;
25651
26084
  }
@@ -25679,7 +26112,7 @@ var NodeBinding = class {
25679
26112
  }
25680
26113
  #closeRegistrations() {
25681
26114
  for (const registration of this.#registrations.splice(0)) registration.close();
25682
- this.#datapathRegistration = null;
26115
+ this.#datapathRegistrations.clear();
25683
26116
  this.#remoteRegistrations.clear();
25684
26117
  }
25685
26118
  };
@@ -25794,7 +26227,11 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
25794
26227
  let attrs = runtimeAttrs;
25795
26228
  item = this.expressionValue(node, item);
25796
26229
  if (this.getRender(node.builder) === this) {
25797
- [item, attrs] = displayItem(item, this.restoreNativeAttributes(node, runtimeAttrs));
26230
+ [item, attrs] = displayItem(
26231
+ item,
26232
+ this.restoreNativeAttributes(node, runtimeAttrs),
26233
+ (value, options) => this._binding.gramlot.format(value, options)
26234
+ );
25798
26235
  }
25799
26236
  const children = Array.isArray(item) ? item : [];
25800
26237
  const text = Array.isArray(item) ? attrs._text : item;
@@ -26133,7 +26570,11 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
26133
26570
  let attrs = node._getMeta("subbuilder") ? resolvedAttrs : renderer.adaptAttrs(resolvedAttrs);
26134
26571
  const branch = node.value instanceof SourceBag;
26135
26572
  let text = branch ? [] : this.expressionValue(node, value);
26136
- if (renderer === this) [text, attrs] = displayItem(text, this.restoreNativeAttributes(node, attrs));
26573
+ if (renderer === this) [text, attrs] = displayItem(
26574
+ text,
26575
+ this.restoreNativeAttributes(node, attrs),
26576
+ (value2, options) => this._binding.gramlot.format(value2, options)
26577
+ );
26137
26578
  this.html.update(record2, node, attrs, branch ? attrs._text : text, resolved2.visible ?? null);
26138
26579
  this.#projectControl(record2, node, attrs, change);
26139
26580
  record2.control?.refresh();
@@ -27051,9 +27492,14 @@ var Gramlot = class {
27051
27492
  element = null,
27052
27493
  document = element?.ownerDocument ?? globalThis.document,
27053
27494
  transport = null,
27054
- collections = []
27495
+ collections = [],
27496
+ locale = null,
27497
+ timeZone = null
27055
27498
  } = {}) {
27056
27499
  this.pageId = pageId;
27500
+ const browserContext = locale == null || timeZone == null ? document.defaultView.Intl.DateTimeFormat().resolvedOptions() : null;
27501
+ this.locale = locale ?? browserContext.locale;
27502
+ this.timeZone = timeZone ?? browserContext.timeZone;
27057
27503
  Object.defineProperty(this, "_subscriptions", { value: new SubscriptionsHandler(this) });
27058
27504
  this.capabilities = Object.freeze([...capabilities]);
27059
27505
  this.src = new SourceHandler(this, { collections, destination: element ?? document.getElementById(rootId) });
@@ -27081,6 +27527,9 @@ var Gramlot = class {
27081
27527
  unsubscribe(registration) {
27082
27528
  this._subscriptions.unsubscribe(registration);
27083
27529
  }
27530
+ format(value, options) {
27531
+ return formatValue(value, options, { locale: this.locale, timeZone: this.timeZone });
27532
+ }
27084
27533
  start() {
27085
27534
  if (this.state === "disposed") return Promise.reject(new Error("Gramlot is disposed"));
27086
27535
  if (!this.rpc.transport) return Promise.reject(new Error("This Gramlot instance has no server transport"));
@@ -27204,6 +27653,8 @@ function declare(PageClass, methodName, marker, auth) {
27204
27653
  }
27205
27654
  var Page = class {
27206
27655
  static title = "Gramlot";
27656
+ static locale = null;
27657
+ static timeZone = null;
27207
27658
  static installable = false;
27208
27659
  static appIcon = null;
27209
27660
  /** Default root manifest. appIcon is a 512px square PNG below the app root. */
@@ -27681,6 +28132,505 @@ var IndexLogic = class {
27681
28132
  this.index = mountIndexPage(renderer, renderer.elements.get(element).node);
27682
28133
  }
27683
28134
  };
28135
+
28136
+ // src/date-parser/civil.js
28137
+ function daysInMonth(year, month) {
28138
+ if (month === 2) return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
28139
+ return [4, 6, 9, 11].includes(month) ? 30 : 31;
28140
+ }
28141
+ function civil(year, month, day) {
28142
+ if (![year, month, day].every(Number.isInteger) || year < 1 || year > 9999 || month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) {
28143
+ throw new RangeError("Date must exist in Gregorian years 0001\u20139999.");
28144
+ }
28145
+ return `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
28146
+ }
28147
+ function parts(date) {
28148
+ if (typeof date !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(date)) {
28149
+ throw new RangeError("Expected a civil date in YYYY-MM-DD format.");
28150
+ }
28151
+ const result = date.split("-").map(Number);
28152
+ civil(...result);
28153
+ return result;
28154
+ }
28155
+ function ordinal(year, month, day) {
28156
+ const previous = year - 1;
28157
+ let result = 365 * previous + Math.floor(previous / 4) - Math.floor(previous / 100) + Math.floor(previous / 400) + day - 1;
28158
+ for (let m = 1; m < month; m++) result += daysInMonth(year, m);
28159
+ return result;
28160
+ }
28161
+ function addDays(date, offset) {
28162
+ let target = ordinal(...parts(date)) + offset;
28163
+ if (!Number.isSafeInteger(target) || target < 0 || target > ordinal(9999, 12, 31)) {
28164
+ throw new RangeError("Date offset exceeds Gregorian years 0001\u20139999.");
28165
+ }
28166
+ let low = 1, high = 1e4;
28167
+ while (high - low > 1) {
28168
+ const middle = Math.floor((low + high) / 2);
28169
+ if (ordinal(middle, 1, 1) <= target) low = middle;
28170
+ else high = middle;
28171
+ }
28172
+ target -= ordinal(low, 1, 1);
28173
+ let month = 1;
28174
+ while (target >= daysInMonth(low, month)) target -= daysInMonth(low, month++);
28175
+ return civil(low, month, target + 1);
28176
+ }
28177
+ function monday(date) {
28178
+ return addDays(date, -(ordinal(...parts(date)) % 7));
28179
+ }
28180
+ function monthPeriod(year, month, offset = 0, count = 1) {
28181
+ const index = year * 12 + month - 1 + offset;
28182
+ const y = Math.floor(index / 12), m = (index % 12 + 12) % 12 + 1;
28183
+ const endIndex = index + count - 1;
28184
+ const ey = Math.floor(endIndex / 12), em = (endIndex % 12 + 12) % 12 + 1;
28185
+ return { start: civil(y, m, 1), end: civil(ey, em, daysInMonth(ey, em)) };
28186
+ }
28187
+
28188
+ // src/date-parser/locales.js
28189
+ var locales = {
28190
+ "it": {
28191
+ "months": {
28192
+ "gennaio": 1,
28193
+ "febbraio": 2,
28194
+ "marzo": 3,
28195
+ "aprile": 4,
28196
+ "maggio": 5,
28197
+ "giugno": 6,
28198
+ "luglio": 7,
28199
+ "agosto": 8,
28200
+ "settembre": 9,
28201
+ "ottobre": 10,
28202
+ "novembre": 11,
28203
+ "dicembre": 12,
28204
+ "gen": 1,
28205
+ "feb": 2,
28206
+ "mar": 3,
28207
+ "apr": 4,
28208
+ "mag": 5,
28209
+ "giu": 6,
28210
+ "lug": 7,
28211
+ "ago": 8,
28212
+ "set": 9,
28213
+ "ott": 10,
28214
+ "nov": 11,
28215
+ "dic": 12
28216
+ },
28217
+ "weekdays": {
28218
+ "luned\xEC": 0,
28219
+ "marted\xEC": 1,
28220
+ "mercoled\xEC": 2,
28221
+ "gioved\xEC": 3,
28222
+ "venerd\xEC": 4,
28223
+ "sabato": 5,
28224
+ "domenica": 6,
28225
+ "lun": 0,
28226
+ "mar": 1,
28227
+ "mer": 2,
28228
+ "gio": 3,
28229
+ "ven": 4,
28230
+ "sab": 5,
28231
+ "dom": 6
28232
+ },
28233
+ "quarters": {
28234
+ "1\xBA trimestre": 1,
28235
+ "2\xBA trimestre": 2,
28236
+ "3\xBA trimestre": 3,
28237
+ "4\xBA trimestre": 4,
28238
+ "1\xB0 trimestre": 1,
28239
+ "2\xB0 trimestre": 2,
28240
+ "3\xB0 trimestre": 3,
28241
+ "4\xB0 trimestre": 4,
28242
+ "t1": 1,
28243
+ "t2": 2,
28244
+ "t3": 3,
28245
+ "t4": 4,
28246
+ "q1": 1,
28247
+ "q2": 2,
28248
+ "q3": 3,
28249
+ "q4": 4
28250
+ },
28251
+ "keywords": {
28252
+ "today": [
28253
+ "oggi"
28254
+ ],
28255
+ "yesterday": [
28256
+ "ieri"
28257
+ ],
28258
+ "tomorrow": [
28259
+ "domani"
28260
+ ],
28261
+ "this_week": [
28262
+ "questa settimana",
28263
+ "settimana"
28264
+ ],
28265
+ "last_week": [
28266
+ "settimana scorsa"
28267
+ ],
28268
+ "next_week": [
28269
+ "settimana prossima"
28270
+ ],
28271
+ "this_month": [
28272
+ "questo mese",
28273
+ "mese"
28274
+ ],
28275
+ "last_month": [
28276
+ "mese scorso"
28277
+ ],
28278
+ "next_month": [
28279
+ "mese prossimo"
28280
+ ],
28281
+ "last": [
28282
+ "scorso",
28283
+ "scorsa"
28284
+ ],
28285
+ "next": [
28286
+ "prossimo",
28287
+ "prossima"
28288
+ ],
28289
+ "articles": [
28290
+ "il",
28291
+ "lo",
28292
+ "la"
28293
+ ],
28294
+ "from": [
28295
+ "da",
28296
+ "dal",
28297
+ "dalla",
28298
+ "tra",
28299
+ "fra"
28300
+ ],
28301
+ "to": [
28302
+ "a",
28303
+ "al",
28304
+ "alla",
28305
+ "e"
28306
+ ],
28307
+ "no_period": [
28308
+ "-",
28309
+ "senza periodo",
28310
+ "sempre"
28311
+ ]
28312
+ },
28313
+ "date_order": {
28314
+ "default": "DMY"
28315
+ }
28316
+ },
28317
+ "en": {
28318
+ "months": {
28319
+ "january": 1,
28320
+ "february": 2,
28321
+ "march": 3,
28322
+ "april": 4,
28323
+ "may": 5,
28324
+ "june": 6,
28325
+ "july": 7,
28326
+ "august": 8,
28327
+ "september": 9,
28328
+ "october": 10,
28329
+ "november": 11,
28330
+ "december": 12,
28331
+ "jan": 1,
28332
+ "feb": 2,
28333
+ "mar": 3,
28334
+ "apr": 4,
28335
+ "jun": 6,
28336
+ "jul": 7,
28337
+ "aug": 8,
28338
+ "sep": 9,
28339
+ "oct": 10,
28340
+ "nov": 11,
28341
+ "dec": 12
28342
+ },
28343
+ "weekdays": {
28344
+ "monday": 0,
28345
+ "tuesday": 1,
28346
+ "wednesday": 2,
28347
+ "thursday": 3,
28348
+ "friday": 4,
28349
+ "saturday": 5,
28350
+ "sunday": 6,
28351
+ "mon": 0,
28352
+ "tue": 1,
28353
+ "wed": 2,
28354
+ "thu": 3,
28355
+ "fri": 4,
28356
+ "sat": 5,
28357
+ "sun": 6
28358
+ },
28359
+ "quarters": {
28360
+ "1st quarter": 1,
28361
+ "2nd quarter": 2,
28362
+ "3rd quarter": 3,
28363
+ "4th quarter": 4,
28364
+ "q1": 1,
28365
+ "q2": 2,
28366
+ "q3": 3,
28367
+ "q4": 4
28368
+ },
28369
+ "keywords": {
28370
+ "today": [
28371
+ "today"
28372
+ ],
28373
+ "yesterday": [
28374
+ "yesterday"
28375
+ ],
28376
+ "tomorrow": [
28377
+ "tomorrow"
28378
+ ],
28379
+ "this_week": [
28380
+ "this week",
28381
+ "week"
28382
+ ],
28383
+ "last_week": [
28384
+ "last week"
28385
+ ],
28386
+ "next_week": [
28387
+ "next week"
28388
+ ],
28389
+ "this_month": [
28390
+ "this month",
28391
+ "month"
28392
+ ],
28393
+ "last_month": [
28394
+ "last month"
28395
+ ],
28396
+ "next_month": [
28397
+ "next month"
28398
+ ],
28399
+ "last": [
28400
+ "last"
28401
+ ],
28402
+ "next": [
28403
+ "next"
28404
+ ],
28405
+ "articles": [
28406
+ "the"
28407
+ ],
28408
+ "from": [
28409
+ "from",
28410
+ "between"
28411
+ ],
28412
+ "to": [
28413
+ "to",
28414
+ "and"
28415
+ ],
28416
+ "no_period": [
28417
+ "no period",
28418
+ "always"
28419
+ ]
28420
+ },
28421
+ "date_order": {
28422
+ "default": "MDY",
28423
+ "GB": "DMY",
28424
+ "AU": "DMY",
28425
+ "IE": "DMY",
28426
+ "NZ": "DMY",
28427
+ "IN": "DMY"
28428
+ }
28429
+ }
28430
+ };
28431
+ function localeContext(locale) {
28432
+ if (typeof locale !== "string") throw new RangeError("A supported locale is required.");
28433
+ const tag2 = locale.replaceAll("-", "_");
28434
+ const split = tag2.indexOf("_");
28435
+ const language = (split < 0 ? tag2 : tag2.slice(0, split)).toLowerCase();
28436
+ const region = (split < 0 ? "" : tag2.slice(split + 1)).toUpperCase();
28437
+ if (!Object.hasOwn(locales, language)) throw new RangeError(`Unsupported locale: ${locale}`);
28438
+ const dictionary = locales[language];
28439
+ const phrases = (key) => [.../* @__PURE__ */ new Set([...dictionary.keywords[key], ...locales.en.keywords[key]])];
28440
+ return { dictionary, phrases, order: dictionary.date_order[region] ?? dictionary.date_order.default };
28441
+ }
28442
+
28443
+ // src/date-parser/index.js
28444
+ var yearPattern = /^(?:\d{4}|\d{2})$/;
28445
+ var dayPattern = /^\d{1,2}$/;
28446
+ var fail2 = (code, message) => ({ ok: false, error: { code, message } });
28447
+ var unrecognized = (code = "UNRECOGNIZED_EXPRESSION", message = "Text is not a supported date expression.") => {
28448
+ throw Object.assign(new SyntaxError(message), { code });
28449
+ };
28450
+ var own = (object, key) => Object.hasOwn(object, key);
28451
+ function decodeYear(text, context) {
28452
+ if (text.length === 4) return Number(text);
28453
+ const lowest = context.year + context.twoDigitYearAhead - 100;
28454
+ return lowest + ((Number(text) - lowest) % 100 + 100) % 100;
28455
+ }
28456
+ function boundTexts(text, context) {
28457
+ if (text.includes(";")) {
28458
+ const bounds = text.split(";").map((part) => part.trim());
28459
+ if (bounds.length !== 2) return unrecognized("INVALID_RANGE", "A range must have exactly two endpoints.");
28460
+ return { bounds, range: true };
28461
+ }
28462
+ if (context.phrases("no_period").includes(text)) return { bounds: ["", ""], range: true };
28463
+ const to = context.phrases("to"), from = context.phrases("from");
28464
+ for (const word of to) {
28465
+ if (text.startsWith(`${word} `)) return { bounds: ["", text.slice(word.length + 1).trim()], range: true };
28466
+ }
28467
+ for (const word of to) {
28468
+ const separator = ` ${word} `;
28469
+ if (!text.includes(separator)) continue;
28470
+ for (const prefix of from) {
28471
+ if (text.startsWith(`${prefix} `)) {
28472
+ text = text.slice(prefix.length + 1);
28473
+ break;
28474
+ }
28475
+ }
28476
+ const bounds = text.split(separator).map((part) => part.trim());
28477
+ if (bounds.length !== 2) return unrecognized("INVALID_RANGE", "A range must have exactly two endpoints.");
28478
+ return { bounds, range: true };
28479
+ }
28480
+ for (const word of from) {
28481
+ if (text.startsWith(`${word} `)) return { bounds: [text.slice(word.length + 1).trim(), ""], range: true };
28482
+ }
28483
+ return { bounds: [text, text], range: false };
28484
+ }
28485
+ function keywordDate(text, context, isEnd) {
28486
+ const candidates = [[text, 0]];
28487
+ const offset = /^(.+?)\s*([+-])\s*(\d+)$/.exec(text);
28488
+ if (offset) candidates.push([offset[1], Number(offset[2] + offset[3])]);
28489
+ const shifts = {
28490
+ today: 0,
28491
+ yesterday: -1,
28492
+ tomorrow: 1,
28493
+ this_week: 0,
28494
+ last_week: -1,
28495
+ next_week: 1,
28496
+ this_month: 0,
28497
+ last_month: -1,
28498
+ next_month: 1
28499
+ };
28500
+ for (const [body, amount] of candidates) {
28501
+ for (const [key, shift] of Object.entries(shifts)) {
28502
+ if (!context.phrases(key).includes(body)) continue;
28503
+ if (key.endsWith("_week")) return addDays(monday(context.workdate), (shift + amount) * 7 + (isEnd ? 6 : 0));
28504
+ if (key.endsWith("_month")) {
28505
+ const span = monthPeriod(context.year, context.month, shift + amount);
28506
+ return isEnd ? span.end : span.start;
28507
+ }
28508
+ return addDays(context.workdate, shift + amount);
28509
+ }
28510
+ }
28511
+ return null;
28512
+ }
28513
+ function quarter(text, context, isEnd) {
28514
+ const entries = Object.entries(context.dictionary.quarters).sort((a, b) => b[0].length - a[0].length);
28515
+ for (const [name, number] of entries) {
28516
+ let year;
28517
+ if (text === name) year = null;
28518
+ else if (text.startsWith(name) && yearPattern.test(text.slice(name.length).trim())) {
28519
+ year = decodeYear(text.slice(name.length).trim(), context);
28520
+ } else if (text.endsWith(name) && yearPattern.test(text.slice(0, -name.length).trim())) {
28521
+ year = decodeYear(text.slice(0, -name.length).trim(), context);
28522
+ } else continue;
28523
+ return { year, month: isEnd ? number * 3 : number * 3 - 2 };
28524
+ }
28525
+ return null;
28526
+ }
28527
+ function monthNumber(token, dictionary) {
28528
+ if (own(dictionary.months, token)) return dictionary.months[token];
28529
+ const match = /^m(\d{1,2})$/.exec(token);
28530
+ return match && Number(match[1]) >= 1 && Number(match[1]) <= 12 ? Number(match[1]) : null;
28531
+ }
28532
+ function namedMonth(text, context) {
28533
+ const tokens = text.split(/\s+/);
28534
+ const positions = tokens.map((token, i) => monthNumber(token, context.dictionary) ? i : -1).filter((i) => i >= 0);
28535
+ if (!positions.length) return null;
28536
+ if (positions.length !== 1) return unrecognized();
28537
+ const position = positions[0], month = monthNumber(tokens[position], context.dictionary);
28538
+ const before = tokens.slice(0, position), after = tokens.slice(position + 1), others = [...before, ...after];
28539
+ if (others.length === 1 && context.phrases("last").includes(others[0])) {
28540
+ return { year: context.year - (month > context.month ? 1 : 0), month };
28541
+ }
28542
+ if (others.length === 1 && context.phrases("next").includes(others[0])) {
28543
+ return { year: context.year + (month < context.month ? 1 : 0), month };
28544
+ }
28545
+ if (!others.length) return { year: null, month };
28546
+ if (!before.length && after.length === 1 && yearPattern.test(after[0])) return { year: decodeYear(after[0], context), month };
28547
+ if (before.length === 1 && dayPattern.test(before[0])) {
28548
+ if (!after.length) return civil(context.year, month, Number(before[0]));
28549
+ if (after.length === 1 && yearPattern.test(after[0])) return civil(decodeYear(after[0], context), month, Number(before[0]));
28550
+ }
28551
+ if (!before.length && after.length === 2 && dayPattern.test(after[0]) && yearPattern.test(after[1])) {
28552
+ return civil(decodeYear(after[1], context), month, Number(after[0]));
28553
+ }
28554
+ return unrecognized();
28555
+ }
28556
+ function numericDate(text, context) {
28557
+ const iso = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
28558
+ if (iso) return civil(...iso.slice(1).map(Number));
28559
+ const numeric = /^(\d{1,4})[/\-. ]+(\d{1,4})[/\-. ]+(\d{1,4})$/.exec(text);
28560
+ const values = {};
28561
+ if (numeric) context.order.split("").forEach((letter, i) => {
28562
+ values[letter] = numeric[i + 1];
28563
+ });
28564
+ else if (/^(?:\d{6}|\d{8})$/.test(text)) {
28565
+ const yearWidth = text.length === 8 ? 4 : 2;
28566
+ for (const letter of context.order) {
28567
+ const width = letter === "Y" ? yearWidth : 2;
28568
+ values[letter] = text.slice(0, width);
28569
+ text = text.slice(width);
28570
+ }
28571
+ } else return null;
28572
+ if (!yearPattern.test(values.Y) || values.D.length > 2 || values.M.length > 2) return unrecognized();
28573
+ let day = Number(values.D), month = Number(values.M);
28574
+ if (numeric && month > 12 && day <= 12) [day, month] = [month, day];
28575
+ return civil(decodeYear(values.Y, context), month, day);
28576
+ }
28577
+ function getBound(text, context, isEnd) {
28578
+ if (!text) return null;
28579
+ const articles = context.phrases("articles");
28580
+ text = text.split(/\s+/).filter((token) => !articles.includes(token)).join(" ");
28581
+ if (!text) return unrecognized();
28582
+ if (yearPattern.test(text)) return civil(decodeYear(text, context), isEnd ? 12 : 1, isEnd ? 31 : 1);
28583
+ const value = keywordDate(text, context, isEnd) ?? quarter(text, context, isEnd) ?? namedMonth(text, context);
28584
+ if (value !== null) return value;
28585
+ if (own(context.dictionary.weekdays, text)) return addDays(monday(context.workdate), context.dictionary.weekdays[text]);
28586
+ return numericDate(text, context) ?? unrecognized();
28587
+ }
28588
+ function startDate(start, end, context) {
28589
+ if (start === null || typeof start === "string") return start;
28590
+ let year = start.year ?? context.year;
28591
+ const endYear = typeof end === "string" ? parts(end)[0] : end?.year;
28592
+ const endMonth = typeof end === "string" ? parts(end)[1] : end?.month;
28593
+ if (endYear) {
28594
+ if (year > endYear) year = endYear;
28595
+ if (year === endYear && start.month > endMonth) year--;
28596
+ }
28597
+ return civil(year, start.month, 1);
28598
+ }
28599
+ function endDate(end, start, context) {
28600
+ if (end === null || typeof end === "string") return end;
28601
+ let year = end.year ?? context.year;
28602
+ if (start !== null) {
28603
+ const [startYear, startMonth] = parts(start);
28604
+ if (year < startYear) year = startYear;
28605
+ if (year === startYear && startMonth > end.month) year++;
28606
+ }
28607
+ return civil(year, end.month, daysInMonth(year, end.month));
28608
+ }
28609
+ function parseDateExpression(text, options = {}) {
28610
+ if (!options || typeof options !== "object" || Array.isArray(options)) return fail2("INVALID_CONTEXT", "Options must provide a civil workdate and supported locale.");
28611
+ let context;
28612
+ try {
28613
+ const { locale = "it-IT", workdate, twoDigitYearAhead = 20 } = options;
28614
+ const [year, month] = parts(workdate);
28615
+ if (!Number.isInteger(twoDigitYearAhead) || twoDigitYearAhead < 0 || twoDigitYearAhead > 99) throw new RangeError("twoDigitYearAhead must be an integer from 0 to 99.");
28616
+ context = { ...localeContext(locale), workdate, year, month, twoDigitYearAhead };
28617
+ } catch (error) {
28618
+ return fail2("INVALID_CONTEXT", error.message);
28619
+ }
28620
+ if (typeof text !== "string") return fail2("INVALID_INPUT", "Expression must be a string.");
28621
+ try {
28622
+ const expression = text.toLowerCase().trim().replaceAll(",", "");
28623
+ const { bounds, range } = boundTexts(expression, context);
28624
+ const right = getBound(bounds[1], context, true), left = getBound(bounds[0], context, false);
28625
+ const start = startDate(left, right, context), end = endDate(right, start, context);
28626
+ if (!range && typeof left === "string" && start === end) return { ok: true, kind: "date", date: start };
28627
+ return { ok: true, kind: "period", start, end };
28628
+ } catch (error) {
28629
+ if (error instanceof RangeError) return fail2("INVALID_DATE", error.message);
28630
+ if (error instanceof SyntaxError) return fail2(error.code, error.message);
28631
+ throw error;
28632
+ }
28633
+ }
27684
28634
  export {
27685
28635
  Bag,
27686
28636
  BagNode,
@@ -27702,5 +28652,6 @@ export {
27702
28652
  RpcHandler,
27703
28653
  SourceHandler,
27704
28654
  UtilitiesHandler,
27705
- mountIndexPage
28655
+ mountIndexPage,
28656
+ parseDateExpression
27706
28657
  };