@colixsystems/widget-sdk 0.340.0 → 0.342.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -78,6 +78,31 @@ export type WidgetPropertyType =
78
78
  // an array `value` of at most 100 members and no `valueMode`.
79
79
  | "filterList";
80
80
 
81
+ /** One operation a widget calls on its connector (`useConnector(...).call(key, …)`). */
82
+ export interface WidgetConnectorAppOperation {
83
+ key: string;
84
+ method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
85
+ /** Starts with "/"; each `{name}` segment is one `params` value. */
86
+ path: string;
87
+ /** The query names a call may send. */
88
+ query?: string[];
89
+ /** Whether a call sends a body; never on GET. */
90
+ body?: boolean;
91
+ }
92
+
93
+ /** A REST connector a widget ships, as an Action's `connectorTemplates` entry plus `appOperations`. */
94
+ export interface WidgetConnectorTemplate {
95
+ key: string;
96
+ name: string;
97
+ baseUrl: string;
98
+ authType?: "none" | "bearer" | "basic" | "apiKey" | "oauth2_client_credentials" | "oauth2_authorization_code";
99
+ /** Non-secret prefill only: never a token, password, API key value or client secret. */
100
+ authConfig?: Record<string, unknown>;
101
+ defaultHeaders?: Record<string, string>;
102
+ description?: string;
103
+ appOperations: WidgetConnectorAppOperation[];
104
+ }
105
+
81
106
  export interface WidgetPropertyDef {
82
107
  type: WidgetPropertyType;
83
108
  label: string;
@@ -96,6 +121,11 @@ export interface WidgetPropertyDef {
96
121
  // a styleSchema field keeps its only-when-set contract. Prefer this over a
97
122
  // literal `default` whenever the fallback is a theme token.
98
123
  themeDefault?: string;
124
+ /**
125
+ * `connectorRef` only: the key of one of the manifest's `connectorTemplates`.
126
+ * Placing the widget binds the property to the connector its install created.
127
+ */
128
+ template?: string;
99
129
  ui?: {
100
130
  widget?: "textarea" | "slider" | "code";
101
131
  group?: string;
@@ -472,6 +502,11 @@ export interface WidgetManifest {
472
502
  * structural constraints enforced at submission time.
473
503
  */
474
504
  datastoreTemplate?: WidgetDatastoreTemplate;
505
+ /**
506
+ * REST connectors created in the installing workspace at install, callable
507
+ * from the app with exactly the listed `appOperations`. Never a credential.
508
+ */
509
+ connectorTemplates?: WidgetConnectorTemplate[];
475
510
  /**
476
511
  * @deprecated Refused by `validateManifest` and at publish: ship the
477
512
  * automation as a marketplace Action (`@colixsystems/action-sdk`).
@@ -2479,6 +2514,13 @@ export interface AppLanguage {
2479
2514
  * visitor's stays on the device, and `null` returns to the app's default.
2480
2515
  * Rejects with an Error whose `.code` is `INVALID_LOCALE` or `UNSUPPORTED`
2481
2516
  * (`canSetLocale` is false on a host that cannot switch).
2517
+ *
2518
+ * `formatDate(value, { time }?)` shows a date in the app's language with its
2519
+ * month named (`Jan 3, 2027`, `3 jan. 2027`); `{ time: true }` adds the time of
2520
+ * a date-and-time value. Without `time`, a value at exactly midnight UTC is
2521
+ * read as a calendar date (a DATE column's form), so an instant stored then
2522
+ * shows its UTC day. A null, empty or unreadable value gives `"—"`; it never
2523
+ * throws.
2482
2524
  */
2483
2525
  export function useI18n(): {
2484
2526
  locale: string;
@@ -2486,6 +2528,7 @@ export function useI18n(): {
2486
2528
  languages: AppLanguage[];
2487
2529
  canSetLocale: boolean;
2488
2530
  setLocale(code: string | null): Promise<void>;
2531
+ formatDate(value: string | Date | number | null | undefined, options?: { time?: boolean }): string;
2489
2532
  };
2490
2533
 
2491
2534
  /** What an app follows: a fixed palette, or the device's setting. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@colixsystems/widget-sdk",
3
- "version": "0.340.0",
3
+ "version": "0.342.0",
4
4
  "description": "Common widget interface for AppStudio. Implements WidgetManifest, WidgetContext, property schema, and helper hooks.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -39,6 +39,10 @@
39
39
  "import": "./dist/text-scale.js",
40
40
  "default": "./dist/text-scale.js"
41
41
  },
42
+ "./connector-template": {
43
+ "require": "./dist/connector-template.cjs",
44
+ "default": "./dist/connector-template.cjs"
45
+ },
42
46
  "./contract": {
43
47
  "types": "./dist/index.d.ts",
44
48
  "require": "./dist/contract.cjs",
@@ -64,7 +68,8 @@
64
68
  "src/dev-shims.js",
65
69
  "src/contract.js",
66
70
  "src/component-props.js",
67
- "src/sdk-texts.js"
71
+ "src/sdk-texts.js",
72
+ "src/date-label.js"
68
73
  ],
69
74
  "scripts": {
70
75
  "build": "node scripts/build.js",
package/src/contract.js CHANGED
@@ -10,6 +10,7 @@
10
10
  // `useTheme().elevation` — so a widget shadow and a container shadow match.
11
11
  import { COMPONENT_PROPS, COMPONENT_PROPS_ERROR_PREFIX, componentPropsError, tabItemKey } from "./component-props.js";
12
12
  import { COMPONENT_TEXTS, fillSdkText, textInLanguage } from "./sdk-texts.js";
13
+ import { formatDateForDisplay } from "./date-label.js";
13
14
 
14
15
  const ELEVATION = Object.freeze({
15
16
  none: Object.freeze({}),
@@ -923,6 +924,11 @@ const HOOKS = [
923
924
  "setLocale(null) returns to the app's default language. setLocale resolves once the choice is saved and rejects with " +
924
925
  "an Error whose .code is INVALID_LOCALE (the code is not one of languages) or UNSUPPORTED (this host cannot switch, " +
925
926
  "e.g. the Builder canvas) — always catch it. canSetLocale is false on such a host: render the choices disabled then, never a dead button. " +
927
+ "formatDate(value, { time }?) shows a date in the app's language with its month named, as the Studio and <DateTimePicker> do " +
928
+ "(\"Jan 3, 2027\" in English, \"3 jan. 2027\" in Swedish); { time: true } adds the time of a date-and-time value. Without time, a value at " +
929
+ "exactly midnight UTC is read as a calendar date (how a DATE column arrives), so an instant stored then shows its UTC day. It takes an ISO string, " +
930
+ "a Date or a timestamp, and returns \"—\" for a null, empty or unreadable value instead of throwing, so it is the one way to show a date: " +
931
+ "never a fixed numeric pattern such as dd/MM/yyyy, which reads as a different day in another country. " +
926
932
  "Identical on web (Player) and the Expo export.",
927
933
  returnShape: {
928
934
  t: "(key: string, fallback?: string) => string",
@@ -930,6 +936,7 @@ const HOOKS = [
930
936
  languages: "Array<{ code: string, name: string, is_base: boolean }>",
931
937
  canSetLocale: "boolean",
932
938
  setLocale: "(code: string | null) => Promise<void> // rejects with Error .code INVALID_LOCALE | UNSUPPORTED",
939
+ formatDate: "(value: string | Date | number | null, options?: { time?: boolean }) => string // \"—\" when empty or unreadable",
933
940
  },
934
941
  requiredContextSlice: ["i18n.t", "i18n.locale"],
935
942
  scopes: null,
@@ -4370,6 +4377,13 @@ const MANIFEST_SCHEMA = {
4370
4377
  "Optional (REQ-L10N-WIDGET). Translation strings the widget ships. Shape { <key>: { en: string, <locale>?: string, ... } } — `en` is REQUIRED per key. At install the host merges these into the tenant's localization dictionary under a per-widget namespace (`widget.<manifest.id>.<key>`); `useI18n().t(\"<key>\")` resolves the namespaced key automatically, so authors never type the prefix. Non-destructive: an existing admin-edited value is never overwritten, and a language the tenant has not added is never created (values for absent locales are dropped; the widget's `en` seeds the tenant's base language so every key renders). Keys persist across uninstalls; admins prune them from the Translations admin (bulk delete by `widget.<id>.` prefix). Limits: ≤500 keys; each key matches /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/; each value ≤1 KB; the namespaced key must fit the dictionary key cap (128 chars).",
4371
4378
  default: {},
4372
4379
  },
4380
+ connectorTemplates: {
4381
+ type: "array",
4382
+ required: false,
4383
+ description:
4384
+ "Optional. The REST connectors the widget calls, created in the installing workspace at install so the installer only adds the credential. Each entry is { key, name, baseUrl, authType?, authConfig?, defaultHeaders?, description?, appOperations }, the same contract an Action's connectorTemplates follow, plus `appOperations` (required): the operations the widget calls with `useConnector(connectorId).call(\"<operation>\", { params, query, body })`, each { key, method, path, query?, body? }. The connector is created callable from the app with exactly those operations. A manifest never carries a credential (a token, password, API key value or client secret): publishing one is refused, and the installer enters it on the connector. Declare `connectors.call:*` in requestedScopes, and give the widget a `connectorRef` property with `template: \"<key>\"` so placing it binds the property to the connector its install created. A reinstall or an upgrade keeps the installer's credential and creates no second connector. An upgrade that adds or changes an operation, asks its token for more, or moves the connector to another host is not applied to an installed connector, so keep the operations an earlier version listed working. At most 4 templates.",
4385
+ default: [],
4386
+ },
4373
4387
  };
4374
4388
 
4375
4389
  const WIDGET_CONTEXT_SHAPE = {
@@ -5370,8 +5384,8 @@ const CHARGE_CURRENCY = "SEK";
5370
5384
  // which reads this table.
5371
5385
  //
5372
5386
  // Deliberately NOT `Intl.NumberFormat`: the exported Expo app and
5373
- // react-native-web do not agree on its output (the same reason widgets format
5374
- // dates with `date-fns` rather than `toLocaleDateString`), and this string ends
5387
+ // react-native-web do not agree on its output (dates differ only in spacing, so
5388
+ // `useI18n().formatDate` uses Intl; a price must match exactly), and this string ends
5375
5389
  // up on a price the buyer compares against the amount they are charged. An
5376
5390
  // explicit table renders byte-identically on both hosts.
5377
5391
  //
@@ -7118,7 +7132,14 @@ const CONTRACT = deepFreeze({
7118
7132
  // script's own run, inside a 1 s cap on the whole press, so a press can
7119
7133
  // wait up to about 1 s before ACTION_TIMEOUT. A press that never started
7120
7134
  // its script rejects RATE_LIMITED (429, Retry-After: 1): nothing ran.
7121
- version: "1.277.0",
7135
+ // 1.278.0: additive (sc-17829) — manifest `connectorTemplates`: the REST
7136
+ // connectors a widget ships, provisioned at install with the
7137
+ // `appOperations` it calls; a `connectorRef` property may name one with
7138
+ // `template`. Checked by `appstudio-widget lint --manifest`. The template
7139
+ // contract is shared with the action SDK (`./connector-template`).
7140
+ // 1.279.0: additive (sc-18049) — useI18n() returns formatDate(value, { time }?),
7141
+ // a date in the app's language with its month named; "—" when empty.
7142
+ version: "1.279.0",
7122
7143
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7123
7144
  hooks: HOOKS,
7124
7145
  primitives: PRIMITIVES,
@@ -7727,4 +7748,5 @@ export {
7727
7748
  SDK_TEXTS,
7728
7749
  sdkText,
7729
7750
  fillSdkText,
7751
+ formatDateForDisplay,
7730
7752
  };
@@ -0,0 +1,150 @@
1
+ // The value-to-text half of the date contract, shared by `<DateTimePicker>`'s
2
+ // field label and `useI18n().formatDate`. No imports, so the CommonJS copy the
3
+ // backend loads through contract.cjs stays standalone.
4
+
5
+ const DATE_ONLY = /^(\d{4})-(\d{2})-(\d{2})/;
6
+ const TIME_ONLY = /^(\d{2}):(\d{2})/;
7
+
8
+ export function formatToIso(date, mode) {
9
+ if (!(date instanceof Date) || Number.isNaN(date.getTime())) return null;
10
+ if (mode === "date") {
11
+ // Calendar dates are timezone-free: May 28 in Stockholm stays May 28 in NYC.
12
+ const y = String(date.getFullYear()).padStart(4, "0");
13
+ const m = String(date.getMonth() + 1).padStart(2, "0");
14
+ const d = String(date.getDate()).padStart(2, "0");
15
+ return `${y}-${m}-${d}`;
16
+ }
17
+ if (mode === "time") {
18
+ const h = String(date.getHours()).padStart(2, "0");
19
+ const mm = String(date.getMinutes()).padStart(2, "0");
20
+ return `${h}:${mm}`;
21
+ }
22
+ // datetime — full UTC ISO so the wire format round-trips through a DATE column.
23
+ return date.toISOString();
24
+ }
25
+
26
+ export function normaliseMode(mode) {
27
+ return mode === "time" || mode === "datetime" ? mode : "date";
28
+ }
29
+
30
+ /**
31
+ * A stored value as the local wall-clock parts the picker edits, or null when
32
+ * it is empty or unreadable. `month` is 0-based, as `Date` counts it.
33
+ *
34
+ * @returns {{year: number, month: number, day: number, hours: number, minutes: number} | null}
35
+ */
36
+ export function valueToParts(value, mode) {
37
+ if (value == null || value === "") return null;
38
+ const text = String(value);
39
+ const effectiveMode = normaliseMode(mode);
40
+ if (effectiveMode === "time") {
41
+ const match = TIME_ONLY.exec(text);
42
+ if (!match) return null;
43
+ const hours = Number(match[1]);
44
+ const minutes = Number(match[2]);
45
+ if (hours > 23 || minutes > 59) return null;
46
+ return { year: null, month: null, day: null, hours, minutes };
47
+ }
48
+ // A date column holds a calendar date, never an instant: read its head as is.
49
+ const dateOnly = DATE_ONLY.exec(text);
50
+ if (effectiveMode === "date" || (dateOnly && text.length === 10)) {
51
+ if (!dateOnly) return null;
52
+ return checkedParts(Number(dateOnly[1]), Number(dateOnly[2]) - 1, Number(dateOnly[3]), 0, 0);
53
+ }
54
+ const d = new Date(text);
55
+ if (Number.isNaN(d.getTime())) return null;
56
+ return {
57
+ year: d.getFullYear(),
58
+ month: d.getMonth(),
59
+ day: d.getDate(),
60
+ hours: d.getHours(),
61
+ minutes: d.getMinutes(),
62
+ };
63
+ }
64
+
65
+ function checkedParts(year, month, day, hours, minutes) {
66
+ const d = new Date(year, month, day, hours, minutes);
67
+ if (d.getFullYear() !== year || d.getMonth() !== month || d.getDate() !== day) return null;
68
+ return { year, month, day, hours, minutes };
69
+ }
70
+
71
+ export function partsToDate(parts) {
72
+ return new Date(parts.year, parts.month, parts.day, parts.hours || 0, parts.minutes || 0);
73
+ }
74
+
75
+ export function nowParts(now = new Date()) {
76
+ return {
77
+ year: now.getFullYear(),
78
+ month: now.getMonth(),
79
+ day: now.getDate(),
80
+ hours: now.getHours(),
81
+ minutes: now.getMinutes(),
82
+ };
83
+ }
84
+
85
+ // Built once per locale and options: construction is slow on Hermes. Each
86
+ // formats the wall-clock time in UTC, so a cached one never keeps a stale zone.
87
+ const FORMATTERS = new Map();
88
+
89
+ // Hermes ships a partial Intl; any refusal falls back to the ISO shape.
90
+ function intlFormat(locale, options, date) {
91
+ const key = `${locale || ""}|${JSON.stringify(options)}`;
92
+ try {
93
+ let formatter = FORMATTERS.get(key);
94
+ if (!formatter) {
95
+ formatter = new Intl.DateTimeFormat(locale || undefined, { ...options, timeZone: "UTC" });
96
+ FORMATTERS.set(key, formatter);
97
+ }
98
+ const wallClock = new Date(0);
99
+ wallClock.setUTCFullYear(date.getFullYear(), date.getMonth(), date.getDate());
100
+ wallClock.setUTCHours(date.getHours(), date.getMinutes(), 0, 0);
101
+ return formatter.format(wallClock);
102
+ } catch {
103
+ return null;
104
+ }
105
+ }
106
+
107
+ const DATE_LABEL = { year: "numeric", month: "short", day: "numeric" };
108
+ const TIME_LABEL = { hour: "2-digit", minute: "2-digit" };
109
+
110
+ export function partsLabel(parts, mode, locale) {
111
+ if (mode === "time") {
112
+ const date = new Date(2000, 0, 1, parts.hours, parts.minutes);
113
+ return intlFormat(locale, TIME_LABEL, date) || formatToIso(date, "time");
114
+ }
115
+ const date = partsToDate(parts);
116
+ if (mode === "date") {
117
+ return intlFormat(locale, DATE_LABEL, date) || formatToIso(date, "date");
118
+ }
119
+ return (
120
+ intlFormat(locale, { ...DATE_LABEL, ...TIME_LABEL }, date) ||
121
+ `${formatToIso(date, "date")} ${formatToIso(date, "time")}`
122
+ );
123
+ }
124
+
125
+ export const NO_DATE = "—";
126
+
127
+ // A DATE column answers as UTC midnight, so without `time` that is a calendar date.
128
+ const UTC_MIDNIGHT = /^\d{4}-\d{2}-\d{2}T00:00(:00(\.0+)?)?Z$/;
129
+
130
+ /**
131
+ * `useI18n().formatDate`: a value in the app's language with its month named
132
+ * (`Jan 3, 2027`, `3 jan. 2027`), plus the time when `options.time` is set. A
133
+ * bare `YYYY-MM-DD` never shows a time. Without `time`, an instant at exactly
134
+ * midnight UTC shows its UTC day. Empty or unreadable input gives `NO_DATE`;
135
+ * it never throws.
136
+ */
137
+ export function formatDateForDisplay(value, locale, options) {
138
+ const withTime = Boolean(options && options.time);
139
+ if (value instanceof Date || typeof value === "number") {
140
+ const instant = new Date(value);
141
+ if (Number.isNaN(instant.getTime())) return NO_DATE;
142
+ return partsLabel(nowParts(instant), withTime ? "datetime" : "date", locale);
143
+ }
144
+ if (typeof value !== "string" || !value) return NO_DATE;
145
+ const calendarDate =
146
+ value.length === 10 || (!withTime && UTC_MIDNIGHT.test(value)) ? value.slice(0, 10) : null;
147
+ const parts = valueToParts(calendarDate || value, "datetime");
148
+ if (!parts) return NO_DATE;
149
+ return partsLabel(parts, withTime && !calendarDate ? "datetime" : "date", locale);
150
+ }