@lango-project/lango-client 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/LICENSE +1 -0
  2. package/NOTICE +5 -1
  3. package/README.md +571 -855
  4. package/cli/.lango/localization.mjs +108 -0
  5. package/{dist/node → cli}/.lango/runtime.mjs +112 -19
  6. package/cli/.lango/vendor/i18next.LICENSE +21 -0
  7. package/cli/.lango/vendor/i18next.mjs +2434 -0
  8. package/cli/create.mjs +62 -0
  9. package/cli/create.mjs.map +1 -0
  10. package/dist/.lango/localization.mjs +108 -0
  11. package/dist/.lango/runtime.mjs +112 -19
  12. package/dist/.lango/vendor/i18next.LICENSE +21 -0
  13. package/dist/.lango/vendor/i18next.mjs +2434 -0
  14. package/dist/accordion.mjs +277 -0
  15. package/dist/accordion.mjs.map +1 -0
  16. package/dist/activities.mjs +185 -0
  17. package/dist/activities.mjs.map +1 -0
  18. package/dist/app.mjs +636 -0
  19. package/dist/app.mjs.map +1 -0
  20. package/dist/boot.mjs +24 -0
  21. package/dist/boot.mjs.map +1 -0
  22. package/dist/bootstrap-LICENSE +21 -0
  23. package/dist/bootstrap.min.css +6 -0
  24. package/dist/bootstrap.min.css.map +1 -0
  25. package/dist/button.mjs +77 -0
  26. package/dist/button.mjs.map +1 -0
  27. package/dist/chip.mjs +134 -0
  28. package/dist/chip.mjs.map +1 -0
  29. package/dist/client.css +95 -0
  30. package/dist/collections.mjs +77 -0
  31. package/dist/collections.mjs.map +1 -0
  32. package/dist/combo_box.mjs +408 -0
  33. package/dist/combo_box.mjs.map +1 -0
  34. package/dist/content.mjs +123 -0
  35. package/dist/content.mjs.map +1 -0
  36. package/dist/control.mjs +139 -0
  37. package/dist/control.mjs.map +1 -0
  38. package/dist/date_input.mjs +242 -0
  39. package/dist/date_input.mjs.map +1 -0
  40. package/dist/error_reporter.mjs +136 -0
  41. package/dist/error_reporter.mjs.map +1 -0
  42. package/dist/fields.mjs +454 -0
  43. package/dist/fields.mjs.map +1 -0
  44. package/dist/file_input.mjs +227 -0
  45. package/dist/file_input.mjs.map +1 -0
  46. package/dist/form.mjs +272 -0
  47. package/dist/form.mjs.map +1 -0
  48. package/dist/heartbeat.mjs +167 -254
  49. package/dist/heartbeat.mjs.map +1 -1
  50. package/dist/index.html +18 -0
  51. package/dist/indicators.mjs +127 -0
  52. package/dist/indicators.mjs.map +1 -0
  53. package/dist/input_changes.mjs +58 -0
  54. package/dist/input_changes.mjs.map +1 -0
  55. package/dist/input_group.mjs +38 -0
  56. package/dist/input_group.mjs.map +1 -0
  57. package/dist/layouts.mjs +195 -0
  58. package/dist/layouts.mjs.map +1 -0
  59. package/dist/library.mjs +130 -775
  60. package/dist/library.mjs.map +1 -1
  61. package/dist/longpoll.mjs +254 -0
  62. package/dist/longpoll.mjs.map +1 -0
  63. package/dist/main.mjs +138 -0
  64. package/dist/main.mjs.map +1 -0
  65. package/dist/markdown.mjs +61 -0
  66. package/dist/markdown.mjs.map +1 -0
  67. package/dist/menus.mjs +468 -0
  68. package/dist/menus.mjs.map +1 -0
  69. package/dist/navigation.mjs +260 -410
  70. package/dist/navigation.mjs.map +1 -1
  71. package/dist/numeric_input.mjs +181 -0
  72. package/dist/numeric_input.mjs.map +1 -0
  73. package/dist/otp_input.mjs +113 -0
  74. package/dist/otp_input.mjs.map +1 -0
  75. package/dist/presentations.mjs +852 -0
  76. package/dist/presentations.mjs.map +1 -0
  77. package/dist/renderer.mjs +293 -0
  78. package/dist/renderer.mjs.map +1 -0
  79. package/dist/rich_content.mjs +99 -0
  80. package/dist/rich_content.mjs.map +1 -0
  81. package/dist/tables.mjs +369 -0
  82. package/dist/tables.mjs.map +1 -0
  83. package/dist/tabs.mjs +205 -0
  84. package/dist/tabs.mjs.map +1 -0
  85. package/dist/templates.mjs +46 -0
  86. package/dist/templates.mjs.map +1 -0
  87. package/dist/vendor/DOMPurify-LICENSE +202 -0
  88. package/dist/vendor/dompurify.mjs +2540 -0
  89. package/dist/vendor/flatpickr-LICENSE.md +21 -0
  90. package/dist/vendor/flatpickr.min.css +13 -0
  91. package/dist/vendor/flatpickr.mjs +2340 -0
  92. package/dist/vendor/flatpickr.mjs.map +7 -0
  93. package/dist/vendor/marked-LICENSE.md +44 -0
  94. package/dist/vendor/marked.esm.js.map +7 -0
  95. package/dist/vendor/marked.mjs +85 -0
  96. package/dist/vendor/purify.es.mjs.map +1 -0
  97. package/dist/widgets.mjs +197 -0
  98. package/dist/widgets.mjs.map +1 -0
  99. package/docs/implementation.md +42 -0
  100. package/package.json +26 -40
  101. package/src/accordion.lango +198 -0
  102. package/src/activities.lango +132 -0
  103. package/src/app.lango +508 -0
  104. package/src/boot.lango +12 -0
  105. package/src/button.lango +49 -0
  106. package/src/chip.lango +94 -0
  107. package/src/collections.lango +46 -0
  108. package/src/combo_box.lango +298 -0
  109. package/src/content.lango +75 -0
  110. package/src/control.lango +100 -0
  111. package/src/create.lango +42 -0
  112. package/src/date_input.lango +215 -0
  113. package/src/error_reporter.lango +95 -0
  114. package/src/fields.lango +327 -0
  115. package/src/file_input.lango +175 -0
  116. package/src/form.lango +195 -0
  117. package/src/heartbeat.lango +136 -199
  118. package/src/indicators.lango +94 -0
  119. package/src/input_changes.lango +33 -0
  120. package/src/input_group.lango +22 -0
  121. package/src/layouts.lango +137 -0
  122. package/src/library.lango +194 -571
  123. package/src/longpoll.lango +187 -0
  124. package/src/main.lango +109 -0
  125. package/src/markdown.lango +48 -0
  126. package/src/menus.lango +336 -0
  127. package/src/navigation.lango +209 -299
  128. package/src/numeric_input.lango +131 -0
  129. package/src/otp_input.lango +83 -0
  130. package/src/presentations.lango +617 -0
  131. package/src/renderer.lango +288 -0
  132. package/src/rich_content.lango +66 -0
  133. package/src/tables.lango +271 -0
  134. package/src/tabs.lango +144 -0
  135. package/src/templates.lango +29 -0
  136. package/src/widgets.lango +141 -0
  137. package/web/client.css +95 -0
  138. package/web/index.html +18 -0
  139. package/dist/application.mjs +0 -429
  140. package/dist/application.mjs.map +0 -1
  141. package/dist/coordinator.mjs +0 -91
  142. package/dist/coordinator.mjs.map +0 -1
  143. package/dist/demo.mjs +0 -110
  144. package/dist/demo.mjs.map +0 -1
  145. package/dist/demo_controls.mjs +0 -59
  146. package/dist/demo_controls.mjs.map +0 -1
  147. package/dist/errors.mjs +0 -201
  148. package/dist/errors.mjs.map +0 -1
  149. package/dist/form_state.mjs +0 -266
  150. package/dist/form_state.mjs.map +0 -1
  151. package/dist/inheritance.mjs +0 -240
  152. package/dist/inheritance.mjs.map +0 -1
  153. package/dist/input_values.mjs +0 -65
  154. package/dist/input_values.mjs.map +0 -1
  155. package/dist/node/.lango/xmldom/conventions.js +0 -429
  156. package/dist/node/.lango/xmldom/dom-parser.js +0 -591
  157. package/dist/node/.lango/xmldom/dom.js +0 -3759
  158. package/dist/node/.lango/xmldom/entities.js +0 -2171
  159. package/dist/node/.lango/xmldom/errors.js +0 -205
  160. package/dist/node/.lango/xmldom/grammar.js +0 -559
  161. package/dist/node/.lango/xmldom/index.js +0 -41
  162. package/dist/node/.lango/xmldom/package.json +0 -1
  163. package/dist/node/.lango/xmldom/sax.js +0 -983
  164. package/dist/node/.lango/xmldom.LICENSE.md +0 -8
  165. package/dist/node/browser_host.mjs +0 -351
  166. package/dist/node/browser_host.mjs.map +0 -1
  167. package/dist/node/create_app.mjs +0 -118
  168. package/dist/node/create_app.mjs.map +0 -1
  169. package/dist/presentation.mjs +0 -89
  170. package/dist/presentation.mjs.map +0 -1
  171. package/dist/protocol.mjs +0 -706
  172. package/dist/protocol.mjs.map +0 -1
  173. package/dist/session.mjs +0 -431
  174. package/dist/session.mjs.map +0 -1
  175. package/dist/tokens.mjs +0 -298
  176. package/dist/tokens.mjs.map +0 -1
  177. package/examples/contacts.lango +0 -302
  178. package/examples/contacts_flow.lango +0 -174
  179. package/examples/contacts_store.lango +0 -109
  180. package/examples/contacts_store_test.lango +0 -65
  181. package/examples/demo.css +0 -72
  182. package/examples/demo_test.lango +0 -356
  183. package/examples/index.html +0 -28
  184. package/examples/pages.lango +0 -180
  185. package/examples/server.lango +0 -189
  186. package/examples/worker.lango +0 -142
  187. package/src/application.lango +0 -327
  188. package/src/browser_host.lango +0 -276
  189. package/src/coordinator.lango +0 -57
  190. package/src/demo.lango +0 -110
  191. package/src/demo_controls.lango +0 -53
  192. package/src/errors.lango +0 -149
  193. package/src/errors_test.lango +0 -157
  194. package/src/form_state.lango +0 -168
  195. package/src/heartbeat_test.lango +0 -479
  196. package/src/inheritance.lango +0 -167
  197. package/src/input_values.lango +0 -37
  198. package/src/logout_test.lango +0 -564
  199. package/src/navigation_test.lango +0 -556
  200. package/src/presentation.lango +0 -55
  201. package/src/protocol.lango +0 -787
  202. package/src/renderer_test.lango +0 -1986
  203. package/src/session.lango +0 -313
  204. package/src/session_test.lango +0 -455
  205. package/src/tabs_test.lango +0 -216
  206. package/src/tokens.lango +0 -215
  207. package/template/.vscode/extensions.json +0 -3
  208. package/template/.vscode/settings.json +0 -9
  209. package/template/README.md +0 -40
  210. package/template/gitignore +0 -4
  211. package/template/package.json +0 -22
  212. package/template/public/app.css +0 -4
  213. package/template/public/index.html +0 -24
  214. package/template/src/client.lango +0 -78
  215. package/template/src/pages.lango +0 -55
  216. package/template/src/server.lango +0 -24
  217. package/template/src/worker.lango +0 -77
  218. package/template/test/app.lango +0 -9
  219. package/tools/create_app.lango +0 -88
  220. package/tools/create_app_test.lango +0 -43
  221. package/tools/starter_test.lango +0 -227
  222. /package/{dist/node → cli}/.lango/bignumber.mjs +0 -0
  223. /package/{dist → cli}/.lango/xmldom/conventions.js +0 -0
  224. /package/{dist → cli}/.lango/xmldom/dom-parser.js +0 -0
  225. /package/{dist → cli}/.lango/xmldom/dom.js +0 -0
  226. /package/{dist → cli}/.lango/xmldom/entities.js +0 -0
  227. /package/{dist → cli}/.lango/xmldom/errors.js +0 -0
  228. /package/{dist → cli}/.lango/xmldom/grammar.js +0 -0
  229. /package/{dist → cli}/.lango/xmldom/index.js +0 -0
  230. /package/{dist → cli}/.lango/xmldom/package.json +0 -0
  231. /package/{dist → cli}/.lango/xmldom/sax.js +0 -0
  232. /package/{dist → cli}/.lango/xmldom.LICENSE.md +0 -0
package/cli/create.mjs ADDED
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env node
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import {
5
+ hostGlobal as __hostGlobal,
6
+ println as __println,
7
+ requireBoolean as __requireBoolean,
8
+ normalize as __normalize,
9
+ boundary as __boundary,
10
+ requireArity as __requireArity,
11
+ } from "./.lango/runtime.mjs";
12
+
13
+ export function copyClient(source, destination, update = false) {
14
+ __requireArity(arguments.length, [0, 1], "copyClient");
15
+ source = __boundary(source);
16
+ destination = __boundary(destination);
17
+ update = __boundary(update);
18
+ source = __normalize(path.resolve(source));
19
+ destination = __normalize(path.resolve(destination));
20
+ let relative = __normalize(path.relative(source, destination));
21
+ if (__requireBoolean(__requireBoolean(relative === "") || __requireBoolean(__requireBoolean(__requireBoolean(relative !== "..") && __requireBoolean(!__requireBoolean(__normalize(relative.startsWith(`..${__normalize(path.sep)}`))))) && __requireBoolean(!__requireBoolean(__normalize(path.isAbsolute(relative))))))) {
22
+ throw "Destination must be outside the client distribution";
23
+ }
24
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(fs.existsSync(__normalize(path.join(source, "index.html")))))) || __requireBoolean(!__requireBoolean(__normalize(fs.existsSync(__normalize(path.join(source, "boot.mjs")))))))) {
25
+ throw "Client distribution is missing; build the package first";
26
+ }
27
+ if (__requireBoolean(__normalize(fs.existsSync(destination)))) {
28
+ if (__requireBoolean(!__requireBoolean(__normalize(__normalize(fs.statSync(destination)).isDirectory())))) {
29
+ throw "Client destination must be a directory";
30
+ }
31
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(update)) && __requireBoolean(__normalize(__normalize(fs.readdirSync(destination)).length) > 0))) {
32
+ throw "Client destination is not empty; --update refreshes generated assets";
33
+ }
34
+ }
35
+ __normalize(fs.mkdirSync(destination, { recursive: true }));
36
+ __normalize(fs.cpSync(source, destination, { recursive: true, force: update, errorOnExist: !__requireBoolean(update) }));
37
+ return destination;
38
+ return null;
39
+ }
40
+
41
+ export function main(args) {
42
+ __requireArity(arguments.length, [0], "main");
43
+ args = __boundary(args);
44
+ if (__requireBoolean(__requireBoolean(__normalize(args.length) === 0) || __requireBoolean(__normalize(args[0]) === "--help"))) {
45
+ __println("Usage: lango-client <directory> [--update]");
46
+ __println("Write the same-origin Web/Bootstrap browser application to a static directory.");
47
+ return null;
48
+ }
49
+ if (__requireBoolean(__requireBoolean(__normalize(args.length) > 2) || __requireBoolean(__requireBoolean(__normalize(args.length) === 2) && __requireBoolean(__normalize(args[1]) !== "--update")))) {
50
+ throw "Usage: lango-client <directory> [--update]";
51
+ }
52
+ let executable = __normalize(fs.realpathSync(__normalize(__hostGlobal(["process"]).argv[1])));
53
+ let source = __normalize(path.resolve(__normalize(path.dirname(executable)), "../dist"));
54
+ let directory = copyClient(source, __normalize(args[0]), __normalize(args.length) === 2);
55
+ __println(`Browser assets written to ${directory}`);
56
+ return null;
57
+ return null;
58
+ }
59
+ const { configure } = await import("./.lango/runtime.mjs");
60
+ configure({ output: (value) => console.log(value) });
61
+ await main(process.argv.slice(2));
62
+ //# sourceMappingURL=create.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create.mjs","sources":["create.lango"],"sourcesContent":["import js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js global process\n\nexport main(args)\nexport copyClient(source, destination, update = false)\n\ncopyClient(source, destination, update = false)\n source = path/resolve(source)\n destination = path/resolve(destination)\n relative = path/relative(source, destination)\n if relative == \"\" or (relative != \"..\" and !relative.startsWith(\"..${path.sep}\") and !path/isAbsolute(relative))\n throw \"Destination must be outside the client distribution\"\n if !fs/existsSync(path/join(source, \"index.html\")) or !fs/existsSync(path/join(source, \"boot.mjs\"))\n throw \"Client distribution is missing; build the package first\"\n if fs/existsSync(destination)\n if !fs/statSync(destination).isDirectory()\n throw \"Client destination must be a directory\"\n if !update and fs/readdirSync(destination).length > 0\n throw \"Client destination is not empty; --update refreshes generated assets\"\n fs/mkdirSync(destination, {\n recursive: true\n })\n fs/cpSync(source, destination, {\n recursive: true\n force: update\n errorOnExist: !update\n })\n return destination\n\nmain(args)\n if args.length == 0 or args[0] == \"--help\"\n println(\"Usage: lango-client <directory> [--update]\")\n println(\"Write the same-origin Web/Bootstrap browser application to a static directory.\")\n return null\n if args.length > 2 or (args.length == 2 and args[1] != \"--update\")\n throw \"Usage: lango-client <directory> [--update]\"\n executable = fs/realpathSync(process.argv[1])\n source = path/resolve(path/dirname(executable), \"../dist\")\n directory = copyClient(source, args[0], args.length == 2)\n println(\"Browser assets written to ${directory}\")\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA;;;;;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,108 @@
1
+ import i18next from "./vendor/i18next.mjs";
2
+
3
+ function record(value, label) {
4
+ if (value === null || typeof value !== "object" || Array.isArray(value))
5
+ throw new TypeError(`${label} must be a map`);
6
+ return value;
7
+ }
8
+
9
+ function language(value) {
10
+ if (typeof value !== "string" || value === "") throw new TypeError("locale must be a language tag");
11
+ return Intl.getCanonicalLocales(value)[0];
12
+ }
13
+
14
+ function numeric(value) {
15
+ // Decimal instances from independently generated runtimes share this backend marker.
16
+ if (value?._isBigNumber === true && typeof value.toFixed === "function") {
17
+ if (!value.isFinite()) throw new TypeError("formatNumber requires a finite value");
18
+ return value.toFixed();
19
+ }
20
+ if (typeof value === "bigint") return value;
21
+ if (typeof value !== "number" || !Number.isFinite(value))
22
+ throw new TypeError("formatNumber requires a finite number or Decimal");
23
+ return value;
24
+ }
25
+
26
+ function dateValue(value) {
27
+ if (typeof value === "string") {
28
+ const parts = /^(\d{4})-(\d{2})-(\d{2})(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2}))?$/.exec(value);
29
+ if (!parts) throw new TypeError("formatDate requires an ISO date or an instant with a time-zone offset");
30
+ const calendar = new Date(0);
31
+ calendar.setUTCFullYear(Number(parts[1]), Number(parts[2]) - 1, Number(parts[3]));
32
+ if (calendar.getUTCMonth() !== Number(parts[2]) - 1 || calendar.getUTCDate() !== Number(parts[3]))
33
+ throw new TypeError("formatDate requires a valid date");
34
+ }
35
+ if (!(value instanceof Date) && typeof value !== "string" && typeof value !== "number")
36
+ throw new TypeError("formatDate requires a Date, ISO string or epoch milliseconds");
37
+ const date = new Date(value);
38
+ if (!Number.isFinite(date.getTime())) throw new TypeError("formatDate requires a valid date");
39
+ return date;
40
+ }
41
+
42
+ /** Create an immutable, synchronous translator; catalogs are application-owned data. */
43
+ export function createI18n(options = {}) {
44
+ record(options, "i18n options");
45
+ const locale = language(options.locale ?? "en");
46
+ const fallbackLocale = language(options.fallbackLocale ?? "en");
47
+ const timeZone = new Intl.DateTimeFormat("en", { timeZone: options.timeZone ?? "UTC" }).resolvedOptions().timeZone;
48
+ const currency = options.currency == null ? null : options.currency;
49
+ if (currency !== null) new Intl.NumberFormat("en", { style: "currency", currency });
50
+ const resources = Object.create(null);
51
+ const catalogs = { ...record(options.catalogs ?? {}, "catalogs") };
52
+ if (options.catalog != null) catalogs[locale] = { ...catalogs[locale], ...record(options.catalog, "catalog") };
53
+ for (const [tag, catalog] of Object.entries(catalogs)) {
54
+ const messages = record(catalog, "translation catalog");
55
+ if (Object.values(messages).some(value => typeof value !== "string"))
56
+ throw new TypeError("translation catalog entries must be strings");
57
+ resources[language(tag)] = { translation: { ...messages } };
58
+ }
59
+ const engine = i18next.createInstance();
60
+ // All resources are in memory: no async backend, network lookup, or global language mutation.
61
+ engine.init({
62
+ lng: locale, fallbackLng: fallbackLocale, resources, initAsync: false,
63
+ keySeparator: false, nsSeparator: false, returnNull: false,
64
+ interpolation: { escapeValue: false },
65
+ });
66
+ const fixed = engine.getFixedT(locale);
67
+ const formatNumber = (value, options = null) => {
68
+ const settings = { ...record(options ?? {}, "number format options") };
69
+ if (settings.style === "currency" && settings.currency == null && currency !== null)
70
+ settings.currency = currency;
71
+ return new Intl.NumberFormat(locale, settings).format(numeric(value));
72
+ };
73
+ const formatDate = (value, options = null) => {
74
+ const settings = { timeZone, ...record(options ?? {}, "date format options") };
75
+ return new Intl.DateTimeFormat(locale, settings).format(dateValue(value));
76
+ };
77
+ const translate = (template, values = [], options = null) => {
78
+ if (typeof template !== "string" || !Array.isArray(values))
79
+ throw new TypeError("translation requires a template and a values array");
80
+ const settings = record(options ?? {}, "translation options");
81
+ if (settings.count != null && (typeof settings.count !== "number" || !Number.isFinite(settings.count)))
82
+ throw new TypeError("translation count must be a finite number");
83
+ if (settings.context != null && typeof settings.context !== "string")
84
+ throw new TypeError("translation context must be a string");
85
+ const params = record(settings.formatParams ?? {}, "formatParams");
86
+ const message = fixed(template, {
87
+ defaultValue: template, skipInterpolation: true,
88
+ ...(settings.count == null ? {} : { count: settings.count }),
89
+ ...(settings.context == null ? {} : { context: settings.context }),
90
+ });
91
+ // Render once: values are data and can never introduce further placeholders or code.
92
+ return message.replace(/{{|}}|{(\d+)(?:,\s*(number|currency|percent|date|datetime))?}/g, (token, index, format) => {
93
+ if (token === "{{") return "{";
94
+ if (token === "}}") return "}";
95
+ if (Number(index) >= values.length) throw new RangeError(`missing translation parameter {${index}}`);
96
+ const value = values[index];
97
+ const options = record(params[index] ?? {}, "parameter format options");
98
+ switch (format) {
99
+ case "number": return formatNumber(value, options);
100
+ case "currency": return formatNumber(value, { ...options, style: "currency" });
101
+ case "percent": return formatNumber(value, { ...options, style: "percent" });
102
+ case "date": case "datetime": return formatDate(value, options);
103
+ default: return String(value);
104
+ }
105
+ });
106
+ };
107
+ return Object.freeze({ locale, fallbackLocale, timeZone, currency, translate, formatNumber, formatDate });
108
+ }
@@ -1,4 +1,6 @@
1
1
  import BigNumber from "./bignumber.mjs";
2
+ import { createI18n } from "./localization.mjs";
3
+ export { createI18n };
2
4
  const DOMParser = globalThis.DOMParser;
3
5
 
4
6
  const Decimal = BigNumber.clone({
@@ -29,10 +31,72 @@ export function toJsNumber(value) {
29
31
  return new Decimal(value).toNumber();
30
32
  }
31
33
 
32
- let catalog = {};
34
+ let defaultI18n = null;
33
35
  let output = null;
34
36
  let database = null;
35
- let failedTransaction = false;
37
+ const failureStore = Symbol.for("lango.databaseFailures");
38
+ const failedTransactions = globalThis[failureStore] ?? new WeakSet();
39
+ globalThis[failureStore] = failedTransactions;
40
+
41
+ function sqlBindings(sql) {
42
+ const bindings = [];
43
+ for (let i = 0; i < sql.length;) {
44
+ if (sql.startsWith("--", i)) {
45
+ const end = sql.indexOf("\n", i + 2);
46
+ i = end < 0 ? sql.length : end + 1;
47
+ } else if (sql.startsWith("/*", i)) {
48
+ let depth = 1;
49
+ i += 2;
50
+ while (i < sql.length && depth) {
51
+ if (sql.startsWith("/*", i)) { depth++; i += 2; }
52
+ else if (sql.startsWith("*/", i)) { depth--; i += 2; }
53
+ else i++;
54
+ }
55
+ } else if ("'\"`[".includes(sql[i])) {
56
+ const start = sql[i];
57
+ const end = start === "[" ? "]" : start;
58
+ const escape = start === "'" && /[eE]/.test(sql[i - 1] ?? "") &&
59
+ !/[\w$]/.test(sql[i - 2] ?? "");
60
+ i++;
61
+ while (i < sql.length) {
62
+ if (escape && sql[i] === "\\") i += 2;
63
+ else if (sql[i] === end) {
64
+ i++;
65
+ if (sql[i] !== end) break;
66
+ i++;
67
+ } else i++;
68
+ }
69
+ } else if (sql[i] === "$" && !/[\w$]/.test(sql[i - 1] ?? "")) {
70
+ const tag = /^\$(?:[A-Za-z_]\w*)?\$/.exec(sql.slice(i))?.[0];
71
+ if (tag) {
72
+ const end = sql.indexOf(tag, i + tag.length);
73
+ i = end < 0 ? sql.length : end + tag.length;
74
+ } else i++;
75
+ } else if (sql[i] === ":" && sql[i - 1] !== ":" && /[A-Za-z_]/.test(sql[i + 1] ?? "")) {
76
+ const start = i++;
77
+ while (/\w/.test(sql[i] ?? "")) i++;
78
+ bindings.push({ name: sql.slice(start + 1, i), start, end: i });
79
+ } else i++;
80
+ }
81
+ return bindings;
82
+ }
83
+ function postgresQuery(sql, parameters) {
84
+ const positions = new Map();
85
+ const values = [];
86
+ let text = "";
87
+ let at = 0;
88
+ for (const binding of sqlBindings(sql)) {
89
+ if (!Object.hasOwn(parameters, binding.name))
90
+ throw new Error(`SqlParameterNotBound: ${binding.name}`);
91
+ if (!positions.has(binding.name)) {
92
+ values.push(parameters[binding.name]);
93
+ positions.set(binding.name, values.length);
94
+ }
95
+ text += sql.slice(at, binding.start) + "$" + positions.get(binding.name);
96
+ at = binding.end;
97
+ }
98
+ return { text: text + sql.slice(at), values };
99
+ }
36
100
  export const DB = Object.freeze({ Active: "active", RollbackOnly: "rollback_only", Failed: "failed" });
37
101
  const contextStore = Symbol.for("lango.contexts");
38
102
  const contexts = globalThis[contextStore] ?? new Map();
@@ -57,38 +121,56 @@ export function configure(options = {}) {
57
121
  throw new RuntimeConfigurationError("runtime output must be a function or null");
58
122
  if (nextDatabase !== null && (typeof nextDatabase !== "object" && typeof nextDatabase !== "function"))
59
123
  throw new RuntimeConfigurationError("runtime database_adapter must be an object or null");
60
- catalog = nextCatalog;
124
+ let nextI18n;
125
+ try {
126
+ nextI18n = options.i18n ?? createI18n({
127
+ catalog: nextCatalog, catalogs: options.catalogs,
128
+ locale: options.locale, fallbackLocale: options.fallbackLocale,
129
+ timeZone: options.timeZone, currency: options.currency,
130
+ });
131
+ if (typeof nextI18n.translate !== "function" || typeof nextI18n.formatNumber !== "function" || typeof nextI18n.formatDate !== "function")
132
+ throw new TypeError("i18n requires translate, formatNumber and formatDate methods");
133
+ } catch (error) {
134
+ throw new RuntimeConfigurationError(error.message);
135
+ }
136
+ defaultI18n = nextI18n;
61
137
  output = nextOutput;
138
+ if (database !== null) failedTransactions.delete(database);
62
139
  database = nextDatabase;
63
- failedTransaction = false;
140
+ if (database !== null) failedTransactions.delete(database);
64
141
  contexts.clear();
65
142
  return null;
66
143
  }
67
144
 
68
145
  function requireDatabase() {
69
- if (database === null) throw new Error("DatabaseNotConfigured");
70
- return database;
146
+ const stack = contexts.get("db");
147
+ const adapter = stack?.length ? stack.at(-1) : database;
148
+ if (adapter === null || adapter === undefined) throw new Error("DatabaseNotConfigured");
149
+ return adapter;
71
150
  }
72
151
 
73
152
  export function startTrans() {
74
- if (failedTransaction) throw new Error("TransactionFailed");
75
- requireDatabase().begin();
153
+ const adapter = requireDatabase();
154
+ if (failedTransactions.has(adapter)) throw new Error("TransactionFailed");
155
+ adapter.begin();
76
156
  return null;
77
157
  }
78
158
  export function commitTrans() {
79
- if (failedTransaction) throw new Error("TransactionFailed");
80
- requireDatabase().commit();
159
+ const adapter = requireDatabase();
160
+ if (failedTransactions.has(adapter)) throw new Error("TransactionFailed");
161
+ adapter.commit();
81
162
  return null;
82
163
  }
83
164
  export function rollbackTrans() {
84
165
  const adapter = requireDatabase();
85
166
  adapter.rollback();
86
- if (adapter.transactionState() === null) failedTransaction = false;
167
+ if (adapter.transactionState() === null) failedTransactions.delete(adapter);
87
168
  return null;
88
169
  }
89
170
  export function transState() {
90
- const state = requireDatabase().transactionState();
91
- return failedTransaction && state !== null ? DB.Failed : state;
171
+ const adapter = requireDatabase();
172
+ const state = adapter.transactionState();
173
+ return failedTransactions.has(adapter) && state !== null ? DB.Failed : state;
92
174
  }
93
175
 
94
176
  export class SqlError extends Error {
@@ -116,10 +198,16 @@ export function query(sql, parameterNames) {
116
198
  ]),
117
199
  );
118
200
  try {
119
- result = adapter.execute(sql, boundParameters);
201
+ if (failedTransactions.has(adapter)) throw new Error("TransactionFailed");
202
+ if (adapter.parameterStyle === "postgresql") {
203
+ const prepared = postgresQuery(sql, boundParameters);
204
+ result = adapter.execute(prepared.text, prepared.values);
205
+ } else result = adapter.execute(sql, boundParameters);
206
+ if (result && typeof result.then === "function")
207
+ throw new Error("SynchronousDatabaseAdapterRequired");
120
208
  } catch (error) {
121
209
  if (error?.transactionUnusable === true && adapter.transactionState() !== null)
122
- failedTransaction = true;
210
+ failedTransactions.add(adapter);
123
211
  throw new SqlError(error, sql);
124
212
  }
125
213
  rows = result.rows;
@@ -153,10 +241,14 @@ export function query(sql, parameterNames) {
153
241
  return proxy;
154
242
  }
155
243
 
156
- export function translate(template, values) {
157
- const translated = catalog[template] ?? template;
158
-
159
- return translated.replace(/\{(\d+)\}/g, (_, index) => String(values[index]));
244
+ export function translate(template, values, options = null) {
245
+ return contextGet("i18n").translate(template, values, options);
246
+ }
247
+ export function formatNumber(value, options = null) {
248
+ return contextGet("i18n").formatNumber(value, options);
249
+ }
250
+ export function formatDate(value, options = null) {
251
+ return contextGet("i18n").formatDate(value, options);
160
252
  }
161
253
 
162
254
  export function xmlEscape(value) {
@@ -584,6 +676,7 @@ export function withArity(callback, requiredPositions, name) {
584
676
  export function contextGet(name) {
585
677
  const stack = contexts.get(name);
586
678
  if ((!stack || stack.length === 0) && name === "log") return defaultLog;
679
+ if ((!stack || stack.length === 0) && name === "i18n") return defaultI18n ??= createI18n();
587
680
  if (!stack || stack.length === 0) {
588
681
  throw new Error(`Lango context is unavailable: ${name}`);
589
682
  }
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2011-present i18next
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.