@graphenedata/cli 0.0.1

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 (123) hide show
  1. package/LICENSE.md +100 -0
  2. package/THIRD_PARTY_NOTICES.md +12 -0
  3. package/cli.ts +157 -0
  4. package/dist/cli/cli.js +43 -0
  5. package/dist/docs/data_apps/components/charts/annotations.md +673 -0
  6. package/dist/docs/data_apps/components/charts/area-chart.md +202 -0
  7. package/dist/docs/data_apps/components/charts/bar-chart.md +317 -0
  8. package/dist/docs/data_apps/components/charts/box-plot.md +190 -0
  9. package/dist/docs/data_apps/components/charts/bubble-chart.md +151 -0
  10. package/dist/docs/data_apps/components/charts/calendar-heatmap.md +112 -0
  11. package/dist/docs/data_apps/components/charts/custom-echarts.md +308 -0
  12. package/dist/docs/data_apps/components/charts/echarts-options.md +217 -0
  13. package/dist/docs/data_apps/components/charts/funnel-chart.md +106 -0
  14. package/dist/docs/data_apps/components/charts/heatmap.md +180 -0
  15. package/dist/docs/data_apps/components/charts/histogram.md +107 -0
  16. package/dist/docs/data_apps/components/charts/line-chart.md +265 -0
  17. package/dist/docs/data_apps/components/charts/mixed-type-charts.md +240 -0
  18. package/dist/docs/data_apps/components/charts/sankey-diagram.md +301 -0
  19. package/dist/docs/data_apps/components/charts/scatter-plot.md +134 -0
  20. package/dist/docs/data_apps/components/charts/sparkline.md +68 -0
  21. package/dist/docs/data_apps/components/data/big-value.md +153 -0
  22. package/dist/docs/data_apps/components/data/delta.md +89 -0
  23. package/dist/docs/data_apps/components/data/table.md +470 -0
  24. package/dist/docs/data_apps/components/data/value.md +97 -0
  25. package/dist/docs/data_apps/components/inputs/button-group.md +154 -0
  26. package/dist/docs/data_apps/components/inputs/checkbox.md +52 -0
  27. package/dist/docs/data_apps/components/inputs/date-input.md +131 -0
  28. package/dist/docs/data_apps/components/inputs/date-range.md +124 -0
  29. package/dist/docs/data_apps/components/inputs/dimension-grid.md +67 -0
  30. package/dist/docs/data_apps/components/inputs/dropdown.md +199 -0
  31. package/dist/docs/data_apps/components/inputs/index.md +3 -0
  32. package/dist/docs/data_apps/components/inputs/slider.md +126 -0
  33. package/dist/docs/data_apps/components/inputs/text-input.md +86 -0
  34. package/dist/docs/data_apps/components/maps/area-map.md +397 -0
  35. package/dist/docs/data_apps/components/maps/base-map.md +269 -0
  36. package/dist/docs/data_apps/components/maps/bubble-map.md +361 -0
  37. package/dist/docs/data_apps/components/maps/point-map.md +326 -0
  38. package/dist/docs/data_apps/components/maps/us-map.md +167 -0
  39. package/dist/docs/data_apps/components/ui/accordion.md +116 -0
  40. package/dist/docs/data_apps/components/ui/alert.md +37 -0
  41. package/dist/docs/data_apps/components/ui/big-link.md +19 -0
  42. package/dist/docs/data_apps/components/ui/details.md +58 -0
  43. package/dist/docs/data_apps/components/ui/download-data.md +41 -0
  44. package/dist/docs/data_apps/components/ui/embed.md +47 -0
  45. package/dist/docs/data_apps/components/ui/grid.md +45 -0
  46. package/dist/docs/data_apps/components/ui/image.md +61 -0
  47. package/dist/docs/data_apps/components/ui/info.md +47 -0
  48. package/dist/docs/data_apps/components/ui/last-refreshed.md +28 -0
  49. package/dist/docs/data_apps/components/ui/link-button.md +20 -0
  50. package/dist/docs/data_apps/components/ui/link.md +40 -0
  51. package/dist/docs/data_apps/components/ui/modal.md +57 -0
  52. package/dist/docs/data_apps/components/ui/note.md +32 -0
  53. package/dist/docs/data_apps/components/ui/print-format-components.md +85 -0
  54. package/dist/docs/data_apps/components/ui/tabs.md +122 -0
  55. package/dist/docs/graphene.md +129 -0
  56. package/dist/ui/app.css +332 -0
  57. package/dist/ui/assets/favicon.ico +0 -0
  58. package/dist/ui/component-utilities/autoFormatting.js +301 -0
  59. package/dist/ui/component-utilities/builtInFormats.js +482 -0
  60. package/dist/ui/component-utilities/chartContext.js +12 -0
  61. package/dist/ui/component-utilities/chartWindowDebug.js +21 -0
  62. package/dist/ui/component-utilities/checkInputs.js +95 -0
  63. package/dist/ui/component-utilities/convert.js +15 -0
  64. package/dist/ui/component-utilities/dateParsing.js +57 -0
  65. package/dist/ui/component-utilities/dropdownContext.ts +1 -0
  66. package/dist/ui/component-utilities/echarts.js +262 -0
  67. package/dist/ui/component-utilities/echartsThemes.js +453 -0
  68. package/dist/ui/component-utilities/formatTitle.js +24 -0
  69. package/dist/ui/component-utilities/formatting.js +258 -0
  70. package/dist/ui/component-utilities/getColumnExtents.js +79 -0
  71. package/dist/ui/component-utilities/getColumnSummary.js +67 -0
  72. package/dist/ui/component-utilities/getCompletedData.js +114 -0
  73. package/dist/ui/component-utilities/getDistinctCount.js +7 -0
  74. package/dist/ui/component-utilities/getDistinctValues.js +15 -0
  75. package/dist/ui/component-utilities/getSeriesConfig.js +236 -0
  76. package/dist/ui/component-utilities/getSortedData.js +7 -0
  77. package/dist/ui/component-utilities/getStackPercentages.js +43 -0
  78. package/dist/ui/component-utilities/getStackedData.js +17 -0
  79. package/dist/ui/component-utilities/getYAxisIndex.js +15 -0
  80. package/dist/ui/component-utilities/globalContexts.js +1 -0
  81. package/dist/ui/component-utilities/helpers/getCompletedData.helpers.js +119 -0
  82. package/dist/ui/component-utilities/inputUtils.ts +25 -0
  83. package/dist/ui/component-utilities/replaceNulls.js +14 -0
  84. package/dist/ui/component-utilities/tableUtils.ts +120 -0
  85. package/dist/ui/component-utilities/themeStores.ts +116 -0
  86. package/dist/ui/components/Area.svelte +174 -0
  87. package/dist/ui/components/AreaChart.svelte +150 -0
  88. package/dist/ui/components/Bar.svelte +326 -0
  89. package/dist/ui/components/BarChart.svelte +194 -0
  90. package/dist/ui/components/BigValue.svelte +69 -0
  91. package/dist/ui/components/Chart.svelte +1070 -0
  92. package/dist/ui/components/Column.svelte +172 -0
  93. package/dist/ui/components/DateRange.svelte +324 -0
  94. package/dist/ui/components/Dropdown.svelte +738 -0
  95. package/dist/ui/components/DropdownOption.svelte +21 -0
  96. package/dist/ui/components/ECharts.svelte +77 -0
  97. package/dist/ui/components/ErrorChart.svelte +54 -0
  98. package/dist/ui/components/GrapheneQuery.svelte +12 -0
  99. package/dist/ui/components/InlineDelta.svelte +150 -0
  100. package/dist/ui/components/Line.svelte +210 -0
  101. package/dist/ui/components/LineChart.svelte +178 -0
  102. package/dist/ui/components/PieChart.svelte +36 -0
  103. package/dist/ui/components/QueryLoad.svelte +82 -0
  104. package/dist/ui/components/Row.svelte +14 -0
  105. package/dist/ui/components/SortIcon.svelte +32 -0
  106. package/dist/ui/components/Table.svelte +19 -0
  107. package/dist/ui/components/TableCell.svelte +75 -0
  108. package/dist/ui/components/TableGroupRow.svelte +136 -0
  109. package/dist/ui/components/TableGroupToggle.svelte +42 -0
  110. package/dist/ui/components/TableHeader.svelte +242 -0
  111. package/dist/ui/components/TableRow.svelte +283 -0
  112. package/dist/ui/components/TableSubtotalRow.svelte +62 -0
  113. package/dist/ui/components/TableTotalRow.svelte +88 -0
  114. package/dist/ui/components/TextInput.svelte +92 -0
  115. package/dist/ui/components/_Table.svelte +516 -0
  116. package/dist/ui/internal/clientCache.ts +43 -0
  117. package/dist/ui/internal/queryEngine.ts +169 -0
  118. package/dist/ui/internal/telemetry.ts +28 -0
  119. package/dist/ui/internal/theme.ts +88 -0
  120. package/dist/ui/layout.svelte +3 -0
  121. package/dist/ui/playwright.config.ts +30 -0
  122. package/dist/ui/web.js +106 -0
  123. package/package.json +71 -0
package/LICENSE.md ADDED
@@ -0,0 +1,100 @@
1
+ Copyright 2025 Graphene Systems, Inc.
2
+
3
+ Source code in this repository is covered by the Elastic License 2.0. The
4
+ default throughout the repository is a license under the Elastic License 2.0,
5
+ unless a file header or a license file in a subdirectory specifies another
6
+ license.
7
+
8
+ --------------------------------------------------------------------------------
9
+
10
+ Elastic License 2.0
11
+
12
+ ## Acceptance
13
+
14
+ By using the software, you agree to all of the terms and conditions below.
15
+
16
+ ## Copyright License
17
+
18
+ The licensor grants you a non-exclusive, royalty-free, worldwide,
19
+ non-sublicensable, non-transferable license to use, copy, distribute, make
20
+ available, and prepare derivative works of the software, in each case subject to
21
+ the limitations and conditions below.
22
+
23
+ ## Limitations
24
+
25
+ You may not provide the software to third parties as a hosted or managed
26
+ service, where the service provides users with access to any substantial set of
27
+ the features or functionality of the software.
28
+
29
+ You may not move, change, disable, or circumvent the license key functionality
30
+ in the software, and you may not remove or obscure any functionality in the
31
+ software that is protected by the license key.
32
+
33
+ You may not alter, remove, or obscure any licensing, copyright, or other notices
34
+ of the licensor in the software. Any use of the licensor’s trademarks is subject
35
+ to applicable law.
36
+
37
+ ## Patents
38
+
39
+ The licensor grants you a license, under any patent claims the licensor can
40
+ license, or becomes able to license, to make, have made, use, sell, offer for
41
+ sale, import and have imported the software, in each case subject to the
42
+ limitations and conditions in this license. This license does not cover any
43
+ patent claims that you cause to be infringed by modifications or additions to
44
+ the software. If you or your company make any written claim that the software
45
+ infringes or contributes to infringement of any patent, your patent license for
46
+ the software granted under these terms ends immediately. If your company makes
47
+ such a claim, your patent license ends immediately for work on behalf of your
48
+ company.
49
+
50
+ ## Notices
51
+
52
+ You must ensure that anyone who gets a copy of any part of the software from you
53
+ also gets a copy of these terms.
54
+
55
+ If you modify the software, you must include in any modified copies of the
56
+ software prominent notices stating that you have modified the software.
57
+
58
+ ## No Other Rights
59
+
60
+ These terms do not imply any licenses other than those expressly granted in
61
+ these terms.
62
+
63
+ ## Termination
64
+
65
+ If you use the software in violation of these terms, such use is not licensed,
66
+ and your licenses will automatically terminate. If the licensor provides you
67
+ with a notice of your violation, and you cease all violation of this license no
68
+ later than 30 days after you receive that notice, your licenses will be
69
+ reinstated retroactively. However, if you violate these terms after such
70
+ reinstatement, any additional violation of these terms will cause your licenses
71
+ to terminate automatically and permanently.
72
+
73
+ ## No Liability
74
+
75
+ *As far as the law allows, the software comes as is, without any warranty or
76
+ condition, and the licensor will not be liable to you for any damages arising
77
+ out of these terms or the use or nature of the software, under any kind of
78
+ legal claim.*
79
+
80
+ ## Definitions
81
+
82
+ The **licensor** is the entity offering these terms, and the **software** is the
83
+ software the licensor makes available under these terms, including any portion
84
+ of it.
85
+
86
+ **you** refers to the individual or entity agreeing to these terms.
87
+
88
+ **your company** is any legal entity, sole proprietorship, or other kind of
89
+ organization that you work for, plus all organizations that have control over,
90
+ are under the control of, or are under common control with that
91
+ organization. **control** means ownership of substantially all the assets of an
92
+ entity, or the power to direct its management and policies by vote, contract, or
93
+ otherwise. Control can be direct or indirect.
94
+
95
+ **your licenses** are all the licenses granted to you for the software under
96
+ these terms.
97
+
98
+ **use** means anything you do with the software requiring one of your licenses.
99
+
100
+ **trademark** means trademarks, service marks, and similar rights.
@@ -0,0 +1,12 @@
1
+ This project includes code from the [Evidence](https://github.com/evidence-dev/evidence) open source project.
2
+
3
+ ---
4
+ MIT License
5
+ Copyright (c) 2023 Evidence
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
7
+
8
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
9
+
10
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11
+
12
+ ---
package/cli.ts ADDED
@@ -0,0 +1,157 @@
1
+ #!/usr/bin/env node
2
+
3
+ import {Command} from 'commander'
4
+ import {printDiagnostics, printTable} from './printer.ts'
5
+ import {analyze, getDiagnostics, loadWorkspace, toSql, type Query} from '../lang/core.ts'
6
+ import fs from 'fs-extra'
7
+ import path from 'path'
8
+ import os from 'os'
9
+ import {loadConfig} from '../lang/config.ts'
10
+ import {runServeInBackground, stopGrapheneIfRunning} from './background.ts'
11
+ import {getConnection} from './connections/index.ts'
12
+
13
+ const program = new Command()
14
+
15
+ program
16
+ .name('graphene')
17
+ .description('Graphene CLI')
18
+ .version('1.0.0')
19
+
20
+ program.hook('preAction', async () => {
21
+ if (process.env.CLI_DELAY) { // useful if you want to attach a debugger
22
+ await new Promise(r => setTimeout(r, 1000))
23
+ }
24
+ loadConfig(process.cwd())
25
+ })
26
+
27
+ program
28
+ .command('compile')
29
+ .description('Translate a query to SQL and print it')
30
+ .argument('[input]', 'Path to file, a raw string, or "-" for stdin')
31
+ .action(async (input: string | undefined) => {
32
+ await loadWorkspace(process.cwd(), false)
33
+ let sql = await readInput(input)
34
+ let queries = analyze(sql)
35
+ if (!validQuery(queries)) return
36
+ console.log(toSql(queries[0]))
37
+ })
38
+
39
+ program
40
+ .command('run')
41
+ .description('Run a query against your database')
42
+ .argument('[input]', 'Path to file, a raw string, or "-" for stdin')
43
+ .action(async (input: string | undefined) => {
44
+ await loadWorkspace(process.cwd(), false)
45
+ let gsql = await readInput(input)
46
+ let queries = analyze(gsql)
47
+ if (!validQuery(queries)) return
48
+ let sql = toSql(queries[0])
49
+ let connection = await getConnection()
50
+ let res = await connection.runQuery(sql)
51
+ printTable(res.rows)
52
+ })
53
+
54
+ program
55
+ .command('serve')
56
+ .description('Run the local server')
57
+ .option('--fg', 'Run the server in the foreground')
58
+ .action(async (options: {fg?: boolean}) => {
59
+ if (options.fg || process.env.DEBUG) {
60
+ let mod = await import('./serve2.ts') // load dynamically, so we're not pulling in a bunch of deps we might not need
61
+ await mod.serve2()
62
+ } else {
63
+ await runServeInBackground()
64
+ process.exit(0)
65
+ }
66
+ })
67
+
68
+ program
69
+ .command('stop')
70
+ .description('Stop the local server')
71
+ .action(async () => {
72
+ await stopGrapheneIfRunning(process.cwd())
73
+ })
74
+
75
+ program
76
+ .command('check')
77
+ .description('Check the project for errors')
78
+ .action(async () => {
79
+ await loadWorkspace(process.cwd(), true)
80
+ analyze()
81
+ if (getDiagnostics().length) {
82
+ printDiagnostics(getDiagnostics())
83
+ process.exit(1)
84
+ }
85
+ console.log('No errors found 💎')
86
+ })
87
+
88
+ program
89
+ .command('view')
90
+ .description('Capture a screenshot of a rendered markdown file')
91
+ .argument('<mdFile>', 'Markdown file to view (e.g., index.md)')
92
+ .option('-c, --chart <chartName>', 'Name of specific chart to capture')
93
+ .action(async (mdFile: string, options: {chart?: string}) => {
94
+ let response = await fetch('http://localhost:4000/graphene/view', {
95
+ method: 'POST',
96
+ headers: {'Content-Type': 'application/json'},
97
+ body: JSON.stringify({mdFile, chart: options.chart}),
98
+ })
99
+ if (!response.ok) throw new Error(`View request failed: ${await response.text()}`)
100
+ let result = await response.json()
101
+
102
+ if (result.errors && result.errors.length > 0) {
103
+ console.error('Errors found:')
104
+ result.errors.forEach(error => console.error(JSON.stringify(error)))
105
+ }
106
+
107
+ if (result.stillLoading) {
108
+ console.error('Warning: Queries were still loading when the screenshot was taken')
109
+ }
110
+
111
+ // Save screenshot to temp file
112
+ if (result.screenshot) {
113
+ let filename = `graphene-screenshot-${new Date().toISOString().replace(/[:.]/g, '-')}.png`
114
+ let screenshotPath = path.join(os.tmpdir(), filename)
115
+ let base64Data = result.screenshot.replace(/^data:image\/png;base64,/, '')
116
+ await fs.writeFile(screenshotPath, base64Data, 'base64')
117
+ console.log('Screenshot saved to', screenshotPath)
118
+ }
119
+ })
120
+
121
+ if (process.env.GRAPHENE_DEBUG) {
122
+ let cmd = (program.commands as any[]).find(c => c._name == process.argv[2])
123
+ cmd._actionHandler
124
+ }
125
+
126
+ program.parse(process.argv)
127
+
128
+ async function readInput (arg): Promise<string> {
129
+ if (!arg || arg === '-') {
130
+ return await new Promise<string>((resolve) => {
131
+ let data = ''
132
+ process.stdin.setEncoding('utf-8')
133
+ process.stdin.on('data', (chunk) => (data += chunk))
134
+ process.stdin.on('end', () => resolve(data))
135
+ process.stdin.resume()
136
+ })
137
+ }
138
+
139
+ let absolutePath = path.resolve(arg)
140
+ if (fs.existsSync(absolutePath)) {
141
+ return await fs.promises.readFile(absolutePath, 'utf-8')
142
+ }
143
+
144
+ return arg
145
+ }
146
+
147
+ function validQuery (queries: Query[]): boolean {
148
+ if (getDiagnostics().length) {
149
+ printDiagnostics(getDiagnostics())
150
+ process.exit(1)
151
+ }
152
+ if (queries.length == 0) {
153
+ console.warn('No queries found')
154
+ process.exit(1)
155
+ }
156
+ return true
157
+ }
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env node
2
+ var Qt=Object.defineProperty;var E=(e,n)=>()=>(e&&(n=e(e=0)),n);var ae=(e,n)=>{for(var t in n)Qt(e,t,{get:n[t],enumerable:!0})};function bt(e,n){let t=n.virtualToMarkdownOffset;return!t||t.length===0?e:e<=0?t[0]??0:e>=t.length?t[t.length-1]:t[e]}function se(e,n){let t=bt(e,n),r=n.contents.split(/\r?\n/),i=0;for(let a=0;a<r.length;a++){let s=r[a],o=i+s.length+1;if(t<o||a===r.length-1){let l=Math.max(0,t-i);return{offset:t,line:a,col:l,lineStart:i,lineText:s}}i=o}return{offset:t,line:1,col:0}}function A(e){e.node&&(e=e.node);let n=e;for(;n.parent;)n=n.parent;return n.tree.fileInfo}function c(e){if(!e)return"";let n=A(e);return(n.virtualContents??n.contents).substring(e.from,e.to)||""}function Fe(e){return Object.fromEntries(Object.entries(e).filter(([n,t])=>t!==void 0))}function R(e,n,t=null){e&&(n(e,t),e.e&&R(e.e,n,e),e.kids&&Object.values(e.kids).forEach(r=>{Array.isArray(r)?r.forEach(i=>R(i,n,e)):R(r,n,e)}))}var Z=E(()=>{});function z(e){let n=A(e).contents;if(!n)return{};let t=e.from,r=n.lastIndexOf(`
3
+ `,Math.max(0,t-1))+1,i=r-1,a=n.slice(r,t),s=!/[^\s]/.test(a),o=[];if(s&&i>=0){let p=i;for(;p>=0;){let w=n.lastIndexOf(`
4
+ `,Math.max(0,p-1))+1,f=n.slice(w,p).trimEnd().trim();if(f.length===0||!f.startsWith("--"))break;o.push(f),p=w-1}}o.reverse();let l={},m=[];for(let p of o){let w=p.slice(2).trimStart();if(w.startsWith("#")){let C=w.slice(1).trim(),f=C.indexOf("=");if(f>0){let h=C.slice(0,f).trim(),u=C.slice(f+1).trim();h&&(l[h]=u)}continue}w&&m.push(w)}let d=e.to,P=n.indexOf(`
5
+ `,d);P===-1&&(P=n.length);let T=n.slice(d,P);if(T.length){let p=T.indexOf("--");if(p>=0){let w=T.slice(0,p);if(/^[\s,]*$/.test(w)){let C=T.slice(p+2).trimStart(),f=/#([A-Za-z0-9_-]+)=([^\s#]+)/g,h=C.replace(f,(u,O,k)=>(O&&(l[O]=String(k)),"")).trim();h&&m.push(h)}}}return m.length&&(l.description=m.join(" ")),l}var De=E(()=>{Z()});import*as Ie from"fs";import wt from"path";function Tt(e){Object.keys(y).forEach(n=>delete y[n]),Object.assign(y,e)}function oe(e){if(y.root)return;let n={};try{let t=Ie.readFileSync(wt.join(e,"package.json"),"utf8");n=JSON.parse(t).graphene||{}}catch{console.warn("No package.json found in current directory")}Tt({...n,dialect:n.dialect||"duckdb",port:process.env.GRAPHENE_PORT||n.port||4e3,root:n.root||process.cwd()})}var y,N=E(()=>{y={dialect:"duckdb"}});import{DUCKDB_DIALECT_FUNCTIONS as ue,GlobalNameSpace as kt,DialectNameSpace as Et,getDialect as xt}from"@graphenedata/malloy";function Ne(e,n){if(!le.has(n)){let r=xt(n);le.set(n,new Et(r))}let t=le.get(n).getEntry(e)||Ct.getEntry(e);return t?.entry?t.entry.overloads:[]}var Ct,le,Ue,Oe=E(()=>{Ct=new kt,le=new Map;Object.assign(ue,{count_if:{takes:{value:"boolean"},returns:{measure:"number"},impl:{function:"COUNT_IF"}},if:{takes:{condition:"boolean",trueValue:{generic:"T"},falseValue:{generic:"T"}},generic:{T:["any"]},returns:{generic:"T"},impl:{function:"IF"}},date_trunc:{takes:{unit:"string",date:"timestamp"},returns:"timestamp",impl:{sql:"DATE_TRUNC(${unit}, ${date})"}},current_date:{takes:{},returns:"date",impl:{function:"CURRENT_DATE"}},current_time:{takes:{},returns:"timestamp",impl:{function:"CURRENT_TIME"}},current_timestamp:{default_precision:{takes:{},returns:"timestamp",impl:{function:"CURRENT_TIMESTAMP"}},precision:{takes:{precision:"number"},returns:"timestamp",impl:{function:"CURRENT_TIMESTAMP"}}},local_timestamp:{default_precision:{takes:{},returns:"timestamp",impl:{function:"LOCALTIMESTAMP"}},precision:{takes:{precision:"number"},returns:"timestamp",impl:{function:"LOCALTIMESTAMP"}}}});Ue={count_if:{...ue.count_if},if:{...ue.if},safe_divide:{takes:{numerator:"number",denominator:"number"},returns:"number",impl:{function:"SAFE_DIVIDE"}},timestamp_diff:{takes:{start:"timestamp",end:"timestamp",unit:{sql_native:"kw"}},returns:"number",impl:{function:"TIMESTAMP_DIFF"}},date_trunc:{takes:{date:"timestamp",unit:{sql_native:"kw"}},returns:"timestamp",impl:{sql:"DATE_TRUNC(${date}, ${unit})"}},current_date:{default_timezone:{takes:{},returns:"date",impl:{function:"CURRENT_DATE"}},timezone:{takes:{timezone:"string"},returns:"date",impl:{function:"CURRENT_DATE"}}},current_time:{default_timezone:{takes:{},returns:"timestamp",impl:{function:"CURRENT_TIME"}},timezone:{takes:{timezone:"string"},returns:"timestamp",impl:{function:"CURRENT_TIME"}}},current_timestamp:{default_timezone:{takes:{},returns:"timestamp",impl:{function:"CURRENT_TIMESTAMP"}},timezone:{takes:{timezone:"string"},returns:"timestamp",impl:{function:"CURRENT_TIMESTAMP"}}},local_timestamp:{takes:{},returns:"timestamp",impl:{function:"CURRENT_DATETIME"}},current_datetime:{default_timezone:{takes:{},returns:"timestamp",impl:{function:"CURRENT_DATETIME"}},timezone:{takes:{timezone:"string"},returns:"timestamp",impl:{function:"CURRENT_DATETIME"}}}}});function Ae(e){let n=new WeakMap,t=r=>{r&&R(r,(i,a)=>{if(n.set(i,a??null),i.node!=="parameter")return;let s=Rt(i,n);s&&(i.type=s)})};for(let r of e.pipeline||[])(r?.filterList||[]).forEach(s=>t(s?.e)),(r?.queryFields||[]).forEach(s=>t(s?.e))}function Rt(e,n){let t=n.get(e)||null;for(;t;){let r=qt(e,t);if(r)return r;t=n.get(t)||null}}function qt(e,n){let t=typeof n.node=="string"?n.node:"";if(St.has(t)){let i=_t(n,e)?.type;if(i)return q(i)}if(t==="in"){let r=n?.kids||{},i=r.e,a=Array.isArray(r.oneOf)?r.oneOf:[];if(a.includes(e)){if(a.length===1){let s=i?.type&&q(i.type);return s&&(e.paramElementType=s),"array"}return i?.type&&q(i.type)||void 0}if(i===e&&a.length){let s=a.find(l=>l!==e),o=s?.type&&q(s.type);if(o)return o}}if(Xt.has(t)||t==="not")return"boolean";if(vt.has(t))return"number";if(t==="function_call"){let r=n?.kids||{},a=(Array.isArray(r.args)?r.args:[]).indexOf(e);if(a>=0){let s=n?.overload,o=s?.params?.[a];if(!o&&s?.params?.length){let m=s.params[s.params.length-1];m?.isVariadic&&(o=m)}let l=typeof o?.type=="string"?q(o.type):void 0;if(l)return l}}if(t==="aggregate"&&n?.e===e){let r=(n?.function||"").toLowerCase();if(r==="sum"||r==="avg"||r==="count")return"number"}if(t==="case"){let r=n?.kids||{};if((Array.isArray(r.caseWhen)?r.caseWhen:[]).includes(e))return"boolean";if(r.caseElse===e)return q(n.type)||void 0;let a=Array.isArray(r.caseThen)?r.caseThen:[];if(a.includes(e))return q(n.type)||void 0;if(r.caseValue===e){let s=a[0];if(s?.type)return q(s.type)}}}function _t(e,n){if(!e?.kids)return;let t=e.kids,r=t.left,i=t.right;if(r===n)return i;if(i===n)return r}function q(e){if(typeof e=="string"&&Ft.has(e)&&e!=="fieldref")return e}function ce(e,n){let t=structuredClone(e),r=t.pipeline[0].filterList||[];for(let i of r)R(i.e,a=>{if(a.node!=="parameter")return;let s=n[a.path[0]];if(s===void 0)throw new Error(`Missing param $${a.path[0]}`);if(s==null)Object.assign(a,{node:"null",type:"string"});else if(a.type=="string")Object.assign(a,{node:"stringLiteral",literal:s});else if(a.type=="number")Object.assign(a,{node:"numberLiteral",literal:s.toString()});else if(a.type=="boolean")Object.assign(a,{node:s?"true":"false"});else throw new Error(`Unsupported param type ${a.type}`)});return t}var St,Xt,vt,Ft,pe=E(()=>{Z();St=new Set(["=","!=","<>",">",">=","<","<=","like","ilike"]),Xt=new Set(["and","or"]),vt=new Set(["unary-"]);Ft=new Set(["string","number","boolean","date","timestamp","json","sql native","error","fieldref","array","record","null"])});import{NodeWeakMap as Dt}from"@lezer/common";import{isExtractUnit as It,isTemporalType as Nt}from"@graphenedata/malloy";function We(e){let n=e.tree.topNode;e.tables=[];let t=n.getChildren("TableStatement").concat(n.getChildren("ViewStatement"));for(let r of t){let i=c(r.getChild("Identifier"));Object.values(x).find(s=>s.tables.find(o=>o.name==i))&&g(r.getChild("Identifier"),`Table "${i}" is already defined`);let a=Ve(i,r.getChild("QueryStatement")?"query_source":"table");a.metadata=z(r);for(let s of r.getChildren("ColumnDef")){let o=c(s.getChild("Identifier"));s.getChild("PrimaryKey")&&(a.primaryKey&&g(s,`Table ${a.name} has multiple primary keys`),a.primaryKey=o);let l=Wt(c(s.getChild("DataType")));l||g(s,`Unsupported data type: ${c(s.getChild("DataType"))}`);let m={name:o,type:l,metadata:z(s)};a.fields.push(m),M.set(m,s)}for(let s of r.getChildren("JoinDef")){let o=s.getChild("Alias")||s.getChild("Identifier"),l={name:c(o)};a.fields.push(l),M.set(l,s)}for(let s of r.getChildren("ComputedDef")){let o={name:c(s.getChild("Alias")),metadata:z(s)};a.fields.push(o),M.set(o,s)}a.fields.reduce((s,o)=>(s[o.name]?g(M.get(o),`Table already has a field called "${o.name}"`):s[o.name]=!0,s),{}),J.set(a,r),e.tables.push(a)}}function Ve(e,n){let t=y.namespace?`${y.namespace}.${e}`:e;return{name:e,type:n,fields:[],connection:y.dialect,dialect:y.dialect,tableName:e,tablePath:t,metadata:{}}}function Ze(e){if(e.type=="query_source")return ge(e);for(let n of e.fields)n.type||me(n,e)}function me(e,n){if(e.type)return;let t=M.get(e);if(de.has(e)&&g(t,"Cycles are not allowed between computed columns"),de.add(e),t.name=="JoinDef"){e=e;let r=H(c(t.getChild("Identifier")),t);if(!r)return g(t,"Unknown table to join");r.type=="query_source"&&ge(r);let i={join_many:"many",join_one:"one"}[c(t.getChild("JoinType"))];if(!i)return g(t,"Unknown join type");Object.assign(e,r,{name:e.name,join:i}),e.onExpression=b(t.getChild("Expression"),{table:n,outputFields:[]})}if(t.name=="ComputedDef"){let r=b(t.getChild("Expression"),{table:n,outputFields:[]}),i=z(t);Object.assign(e,{e:r,metadata:i,type:r.type,isAgg:r.isAgg})}de.delete(e)}function ge(e){if(e.query)return;let n=J.get(e),t=he(n.getChild("QueryStatement"));if(!t)throw new Error("Couldnt find query in QueryStatement");e.fields=t.fields.map(r=>({type:r.type,name:r.name,metadata:r.metadata})),e.query=t.malloyQuery,typeof e.query.structRef=="string"&&(e.query.structRef=H(e.query.structRef,n))}function he(e){let n,t={table:null,outputFields:[]},r=!1,i=[];if(!c(e))return;let a=e.getChild("FromClause")?.getChildren("TablePrimary")||[];if(a.find(u=>u.name=="JoinClause")&&g(a[0],"Query joins not yet supported"),a.length==0&&g(e,"No tables in FROM clause"),a.length>1&&g(a[0],"Multiple tables/joins in FROM clause not yet supported"),a[0].name=="Subquery")n=c(a[0].getChild("Alias"))||"subquery",t.table=Ve(n,"query_source"),J.set(t.table,a[0].getChild("SubqueryExpression")),ge(t.table),i.push(t.table);else{if(n=c(a[0].getChild("Identifier")),t.table=H(n,a[0]),!t.table)return g(a[0],`could not find table "${n}"`);fe.set(a[0],{entityType:"table",table:t.table})}let s=e.getChild("SelectClause")?.getChildren("SelectItem")||[],o=e.getChild("SelectClause")?.getChildren("Kw").find(u=>c(u).toLowerCase()=="distinct");r||=!!o,s.forEach(u=>{if(u.getChild("Wildcard")){let O=u.getChild("Wildcard").getChildren("Identifier"),k=O.map(Q=>c(Q)),$=ze(O,t.table);if(!$)return;$.fields.forEach(Q=>{G(Q)||Q.isAgg||t.outputFields.push({...Q,e:{node:"field",path:[...k,Q.name],type:Q.type}})})}else{let O=b(u.getChild("Expression"),t),k=je(O,t,u.getChild("Alias"));r||=!!O.isAgg;let $={};O.isAgg?t.outputFields.push({type:O.type,name:k,metadata:$,e:O,expressionType:"aggregate",isAgg:!0}):t.outputFields.push({type:O.type,name:k,metadata:$,e:O})}});let l=e.getChild("WhereClause")?.getChild("Expression"),m=e.getChild("HavingClause")?.getChild("Expression"),d=[l,m].flatMap(u=>u?Le(b(u,t)).map(k=>({node:"filterCondition",expressionType:k.isAgg?"aggregate":"scalar",e:k})):[]),P=e.getChild("GroupByClause")?.getChildren("SelectItem")||[];r||=!!P.length,P.forEach(u=>{let O=b(u.getChild("Expression"),t),k=je(O,t,u.getChild("Alias"));if(O.isAgg)return g(u,"Cannot group by aggregate expressions");t.outputFields.find($=>$.name==k)||t.outputFields.unshift({type:O.type,name:k,metadata:{},e:O})});let p=(e.getChild("OrderByClause")?.getChildren("OrderItem")||[]).map(u=>{let O=c(u.getChild("Identifier"))||Number(c(u.getChild("Number"))),k=c(u.getChild("Kw")).toLowerCase()=="desc"?"desc":"asc";return{field:O,dir:k}}),w=e.getChild("LimitClause")?.getChildren("Number")||[],C=w[0]?Number(c(w[0])):void 0;(w[1]?Number(c(w[1])):void 0)&&g(w[1],"OFFSET is not supported yet"),t.outputFields.length==0&&t.table.fields.forEach(u=>{G(u)||u.isAgg||t.outputFields.push({...u,e:{node:"field",path:[u.name],type:u.type}})});let h={fields:t.outputFields,subQuerySources:i,malloyQuery:{type:"query",structRef:n,pipeline:[{type:r?"reduce":"project",queryFields:t.outputFields,filterList:d,outputStruct:null,isRepeated:!1,orderBy:p.length?p:void 0,limit:C}]}};return Ae(h.malloyQuery),h}function b(e,n){if(e.type.isError)return g(e,"Invalid expression",X);switch(e.name){case"Number":return{node:"numberLiteral",literal:c(e),type:"number"};case"Boolean":return{node:c(e).toLowerCase()=="true"?"true":"false",type:"boolean"};case"Null":return{node:"null",type:"string"};case"String":return{node:"stringLiteral",literal:c(e).slice(1,-1),type:"string"};case"Param":return{node:"parameter",path:[c(e).slice(1)],type:"string"};case"Ref":{let t=jt(e,n);if(!t)return X;let r=t.type||"unknown",i={type:r};return(r==="date"||r==="timestamp")&&(i.typeDef={type:r}),n.outputFields.includes(t)&&t.isAgg?{node:"outputField",name:t.name,...i,isAgg:t.isAgg}:{node:"field",path:e.getChildren("Identifier").map(s=>c(s)),...i,isAgg:t.isAgg}}case"ExtractExpression":{let t=b(e.getChild("Expression"),n);if(!Nt(t.type)||!t.typeDef)return g(e,"Expression must be a date or timestamp",X);let r=c(e.getChild("ExtractUnit")).replace(/^['"]|['"]$/g,"").toLowerCase();return It(r)?{node:"extract",type:"number",units:r,e:t,isAgg:!1}:g(e,"Not a valid unit to extract",X)}case"FunctionCall":return Ut(e,n);case"Parenthetical":return b(e.getChild("Expression"),n);case"Count":{let t=e.getChild("Expression");return t?{node:"aggregate",function:"distinct",e:b(t,n),type:"number",isAgg:!0}:{node:"aggregate",function:"count",e:{node:""},type:"number",isAgg:!0}}case"BinaryExpression":{let t=b(e.firstChild,n),r=b(e.lastChild,n);return{node:c(e.firstChild?.nextSibling).toLowerCase(),kids:{left:t,right:r},type:t.type,isAgg:t.isAgg||r.isAgg}}case"NullTestExpression":{let t=e.getChildren("Kw").find(i=>c(i).toLowerCase()=="not")?"is-not-null":"is-null",r=b(e.firstChild,n);return{node:t,type:"boolean",isAgg:r.isAgg,e:r}}case"UnaryExpression":{let t=c(e.firstChild).toLowerCase(),r=b(e.lastChild,n);return t==="not"?{node:"not",e:r,type:"boolean",isAgg:r.isAgg}:t==="-"?{node:"unary-",e:r,type:r.type,isAgg:r.isAgg}:t==="+"?{node:"()",e:r,type:r.type,isAgg:r.isAgg}:g(e,`Unknown unary operator: ${t}`,X)}case"CaseExpression":{let t=e.getChild("Expression"),r=e.getChildren("WhenClause"),i=e.getChild("ElseClause"),a={caseValue:t?b(t,n):void 0,caseElse:i?b(i.getChild("Expression"),n):void 0,caseWhen:r.map(o=>b(o.getChildren("Expression")[0],n)),caseThen:r.map(o=>b(o.getChildren("Expression")[1],n))},s=a.caseThen[0]?.type||"string";return{node:"case",kids:Fe(a),type:s,isAgg:!1}}case"InExpression":{let t=c(e.getChild("Kw")).toLowerCase()=="not",r=b(e.firstChild,n),i=[],a=e.getChild("InValueList");a?i=a.getChildren("Expression").map(o=>b(o,n)):i=[{node:"genericSQLExpr",kids:{args:[]},type:"array"}];let s=r.isAgg||i.some(o=>o.isAgg);return{node:"in",not:t,kids:{e:r,oneOf:i},type:"boolean",isAgg:s}}case"SubqueryExpression":default:return g(e,`Unsupported expression "${e.name}": ${c(e)}`,X)}}function Ut(e,n){let t=c(e.getChild("Identifier")).toLowerCase(),r=e.getChildren("Expression"),i=Ne(t,y.dialect).find(d=>d.params.length==r.length||!!d.params.find(P=>P.isVariadic)),a=r.map((d,P)=>{let T=i?.params[P]?.allowedTypes[0];return T?.type==="sql native"&&T?.rawType==="kw"?{node:"genericSQLExpr",kids:{args:[]},type:"sql native",src:[c(d)],isAgg:!1}:b(d,n)}),s=i?.returnType.type;if(s=="generic"&&(s=a[0]?.type||"string"),s&&!At(s))return g(e,`Unsupported function return type ${s} from function ${t}`,X);let o=new Set;a.forEach(d=>R(d,P=>{P.node=="field"&&o.add(P.path.slice(0,-1).join(".")||n.table.name)}));let l;if(["count","min","max","avg","sum"].includes(t.toLowerCase()))l={node:"aggregate",function:t,e:a[0],type:"number",isAgg:!0};else if(i&&s)l={node:"function_call",type:s,name:t,overload:i,expressionType:i.returnType.expressionType||"scalar",kids:{args:a},isAgg:i.returnType.expressionType=="aggregate"||a.some(d=>d.isAgg)};else return g(e,`Unknown function: ${t}`,X);if(o.size>1&&(l.node=="aggregate"||l.expressionType=="aggregate"))return g(e,"Graphene only supports a single table within aggregates. This one has: "+Array.from(o).join(", "),X);let m=Array.from(o).filter(d=>d!=n.table.name);return m.length>0&&(l.structPath=m[0].split(".")),l}function At(e){return["string","number","boolean","date","timestamp","json","sql native","error","array","record","null","generic"].includes(e)}function jt(e,n){let t=e.getChildren("Identifier"),r=t.pop();if(!r)return g(e,"Missing identifiers in ref",null);let i=c(r),a=n.outputFields.find(l=>l.name==i);if(t.length==0&&a)return a;let s=ze(t,n.table);if(!s)return null;let o=s.fields.find(l=>l.name==i);return o?G(o)?g(r,`${i} is a join, but is used as a column here`,null):(me(o,s),fe.set(r,{entityType:"field",field:o,table:s}),o):g(r,`Could not find "${i}" on ${s.name}`,null)}function ze(e,n){for(let t of e){let r=c(t),i=n.fields.find(a=>a.name==r);if(r!=n.name){if(!i){let a=n.fields.find(o=>G(o)&&o.tableName==r),s=a?`. Did you mean "${a.name}"?`:"";return g(t,`Join "${r}" does not exist on table "${n.name}"${s}`,null)}if(me(i,n),!G(i))return g(t,`"${r}" is not a join on "${n.name}"`,null);if(n=H(i.tableName||"",t),!n)return g(t,"Following valid join but we couldnt find the table",null);fe.set(t,{entityType:"table",table:n})}}return n}function H(e,n){let t=A(n).path;for(let r of Object.values(x))if(r.path.endsWith(".gsql")||r.path==t){let i=r.tables.find(a=>a.name==e);if(i)return i}}function ye(){x={},J=new WeakMap,L=[]}function Me(){L=[]}function je(e,n,t){return t?c(t):e.node=="field"?e.path.join("_"):`col_${n.outputFields.length}`}function g(e,n,t){let r=A(e),i=se(e.from,r),a=se(e.to,r);return L.push({from:i,to:a,message:n,severity:"error",file:r.path}),t}function Ge(e){e.tree.topNode.cursor().iterate(n=>{n.type.isError&&g(n.node,"Syntax error")})}function Le(e){return e.node=="and"?[e.kids.left,e.kids.right].flatMap(Le):[e]}function G(e){return e.type=="table"||e.type=="query_source"}function Wt(e){switch(e.toUpperCase()){case"INT":return"number";case"INT64":return"number";case"TEXT":return"string";case"STRING":return"string";case"VARCHAR":return"string";case"INTEGER":return"number";case"FLOAT":return"number";case"FLOAT64":return"number";case"BOOLEAN":return"boolean";case"DATE":return"date";case"DATETIME":return"timestamp";case"TIME":return"timestamp";case"TIMESTAMP":return"timestamp";case"DECIMAL":return"number";case"DOUBLE":return"number";case"BIGINT":return"number";case"SMALLINT":return"number";case"TINYINT":return"number";case"BYTEINT":return"number";case"BIGDECIMAL":return"number";case"GEOGRAPHY":return"string";default:return null}}var x,L,J,M,fe,de,X,Ye=E(()=>{Z();De();N();Oe();pe();x={},L=[],J=new WeakMap,M=new WeakMap,fe=new Dt;de=new Set;X={node:"error",type:"error"}});var Ke=E(()=>{});function $e(e){let n=e.toLowerCase();return Pn[n]||-1}var Pn,Be=E(()=>{Ke();Pn={select:72,not:31,true:115,false:117,null:111,like:141,in:105,is:109,and:132,or:130,as:19,from:53,inner:59,left:61,right:63,full:65,cross:67,join:69,on:22,where:80,group:83,by:85,order:91,asc:95,desc:97,limit:100,offset:102,table:6,exists:49,primary_key:11}});import{LRParser as Qn}from"@lezer/lr";var bn,ee,Pe=E(()=>{Be();bn={__proto__:null,table:12,primary_key:22,join_one:30,join_many:34,as:38,on:44,not:62,case:72,when:78,then:82,else:88,end:92,exists:98,from:106,inner:118,left:122,right:126,full:130,cross:134,join:138,select:144,distinct:148,where:160,group:166,by:170,having:176,order:182,asc:190,desc:194,limit:200,offset:204,in:210,is:218,null:222,true:230,false:234,count:244,extract:250,or:260,and:264,like:282},ee=Qn.deserialize({version:14,states:"BbQYQPOOOOQO'#C`'#C`OOQO'#Db'#DbOtQPO'#DaOOQO'#Du'#DuO#QQPO'#DtOOQO'#D}'#D}O#XQPO'#D|OOQO'#EQ'#EQO$YQPO'#EPOOQO'#EV'#EVO#XQPO'#EUOOQO'#EY'#EYO$YQPO'#EXOOQO'#Ec'#EcO$_QPO'#EbOOQO'#Fi'#FiO$dQPO'#D`O$qQPO'#C_O$vQPO'#FeQYQPOOQ%hQPO'#FeO%mQPO'#DdO]QPO'#DfO&zQPO'#DeOOQO'#Fv'#FvO(mQPO,59{O*tQPO'#CtO,^QPO'#CtOOQO'#Cz'#CzOOQO'#Cy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&R&[u#`v!X![#O#P#w#z$Z$e$x%Z%^%f%t%v%z&R&[w#av!X![#O#P#w#z$Z$[$e$x%Z%^%f%t%v%z&R&[v#[v!X![#O#P#w#z$Z$[$e$x%Z%^%f%t%v%z&R&[R$W#Uy#bv!X![#O#P#w#z$Z$[$]$e$x%Z%^%f%t%v%z&R&[{#cv!X![#O#P#w#z$Z$[$]$^$e$x%Z%^%f%t%v%z&R&[QdOR!bdQ%P#oR%q%PblTy!Z#d$a$k%b%c%h!`!WVZoqs!u!{#_#`#a#b#c#h#o#}$U$h%P%S%U%Y%`%g%u%x%|&W&^&_&f&gT!wl!WQ!}qS#{!}$RR$R#O`aOdgs#g$U%Q%`R!_aQ!sjR#v!sQ#exU$b#e$c$lQ$c#fR$l#jQ$q#lR%k$qQ%V#wS%y%V%}R%}%^T%O#o%PT$|#o%PbvTy!Z#d$a$k%b%c%hQ!XVQ![ZQ!yoQ#OqQ#PsQ#w!uQ#z!{Q$Z#_Q$[#`Q$]#aQ$^#bQ$_#cQ$e#hS$x#o%PQ%Z#}S%^$U%`Q%f$hQ%t%SY%v%U%x%|&^&_Q%z%YQ&R%gR&[%uQjRQ#t!pR%T#uT${#o%P",nodeNames:"\u26A0 Comment Program TableStatement Kw Identifier table ColumnDef DataType PrimaryKey Kw primary_key JoinDef JoinType Kw join_one Kw join_many Kw as Alias Kw on BinaryExpression Ref = ComputedDef BinaryExpression UnaryExpression UnaryOperator Kw not - + CaseExpression Kw case WhenClause Kw when Kw then ElseClause Kw else Kw end ExistsExpression Kw exists QueryStatement FromClause Kw from TableName Subquery SubqueryExpression JoinClause Kw inner Kw left Kw right Kw full Kw cross Kw join SelectClause Kw select Kw distinct SelectItem Wildcard * WhereClause Kw where GroupByClause Kw group Kw by HavingClause Kw having OrderByClause Kw order OrderItem Number Kw asc Kw desc LimitClause Kw limit Kw offset InExpression Kw in InValueList NullTestExpression Kw is Kw null String Boolean Kw true Kw false Null Param Count Kw count ExtractExpression Kw extract ExtractUnit FunctionCall Parenthetical Kw or Kw and ComparisonOp != <> < > <= >= Kw like AddOp MulOp / % ViewStatement",maxTerm:169,nodeProps:[["group",-6,23,56,107,119,123,128,"Expression",-12,24,27,28,34,47,93,103,112,113,118,120,127,"Expression Expression",-2,54,55,"TablePrimary"]],skippedNodes:[0,1],repeatNodeCount:9,tokenData:"*g~RnX^#Ppq#Pqr#trs$Ptu$nuv%`wx%exy%}yz&Sz{&X{|&^|}&c}!O&h!O!P'X!P!Q'^!Q![(m!]!^)W!^!_)]!_!`)r!`!a)w!c!}*U#T#o*U#y#z#P$f$g#P#BY#BZ#P$IS$I_#P$I|$JO#P$JT$JU#P$KV$KW#P&FU&FV#P~#UY$d~X^#Ppq#P#y#z#P$f$g#P#BY#BZ#P$IS$I_#P$I|$JO#P$JT$JU#P$KV$KW#P&FU&FV#P~#wP!_!`#z~$PO#z~~$STOr$Prs$cs;'S$P;'S;=`$h<%lO$P~$hO#d~~$kP;=`<%l$P~$qS!Q![$}!c!}$}#R#S$}#T#o$}~%SS#k~!Q![$}!c!}$}#R#S$}#T#o$}~%eO$V~~%hTOw%ewx$cx;'S%e;'S;=`%w<%lO%e~%zP;=`<%l%e~&SO$e~~&XO$k~~&^O!o~~&cOq~~&hO$l~~&mPp~}!O&p~&uSP~OY&pZ;'S&p;'S;=`'R<%lO&p~'UP;=`<%l&p~'^O$g~~'cP$U~z{'f~'iTOz'fz{'x{;'S'f;'S;=`(g<%lO'f~'{VOz'fz{'x{!P'f!P!Q(b!Q;'S'f;'S;=`(g<%lO'f~(gOP~~(jP;=`<%l'f~(rQ#P~!O!P(x!Q![(m~({P!Q![)O~)TP#P~!Q![)O~)]O$o~~)bQ#|~!_!`)h!`!a)m~)mO$O~~)rO#{~~)wOi~~)|P#}~!_!`*P~*UO$P~~*ZST~!Q![*U!c!}*U#R#S*U#T#o*U",tokenizers:[0],topRules:{Program:[0,2]},specialized:[{term:5,get:(e,n)=>$e(e,n)<<1,external:$e},{term:5,get:e=>bn[e]||-1}],tokenPrec:2599})});function tt(e){let n=e.contents,t=wn(n),r=Tn(n,t),i=[...t,...r].sort((f,h)=>f.start-h.start),a=[],s=[],o=0,l=-1,m=n.length,d=(f,h)=>{let u=h;u<=l&&(u=l+1),u>m&&(u=m),a.push(f),s.push(u),l=u},P=f=>{l=f},T=(f,h)=>{P(f-1);for(let u=f;u<h;u++){let O=n[u];d(O===`
6
+ `||O==="\r"?O:" ",u)}},p=(f,h,u)=>{u?.reset!==void 0&&P(u.reset);for(let O=0;O<f.length;O++)d(f[O],h(O))},w=(f,h)=>{P(h-1);for(let u=0;u<f.length;u++){let O=h+u;a.push(f[u]),s.push(O),l=O}};for(let f of i){if(f.start<o)continue;if(T(o,f.start),o=f.start,Cn(f)){let $=f,Q=$.contentStart,I=$.content;$.name?(p(`table ${$.name} as (
7
+ `,()=>Q,{reset:Q-1}),w(I,Q),I.endsWith(`
8
+ `)||p(`
9
+ `,()=>Q+I.length,{reset:Q+I.length-1}),p(`)
10
+ `,()=>$.end-1,{reset:$.end-2})):w(I,Q),o=$.end;continue}let h=f,{data:u,attributes:O}=h,k=Qe.some($=>O[$]!==void 0);if(u&&k){p("from ",()=>h.start,{reset:h.start-1}),p(u.value,W=>u.start+W,{reset:u.start-1}),p(" select ",()=>h.start);let $=null;for(let W of Qe){let V=O[W];if(V){if($){let ie=$.start+$.value.length;p(", ",()=>ie)}p(V.value,ie=>V.start+ie,{reset:V.start-1}),$=V}}let Q=$,I=Q?Q.start+Q.value.length:u.start+u.value.length,Pt=Q?Q.start+Q.value.length-1:u.start+u.value.length-1;p(`;
11
+ `,W=>W===0?I:h.end,{reset:Pt})}o=h.end}T(o,n.length);let C=a.join("");return e.virtualContents=C,e.virtualToMarkdownOffset=[...s,n.length],ee.parse(C)}function wn(e){let n=[];Je.lastIndex=0;let t;for(;t=Je.exec(e);){let r=t.index??0,i=t[0],a=i.indexOf(`
12
+ `);if(a===-1)continue;a+=1;let s=t[3]||"",o=r+a,l=kn(i.slice(0,a));n.push({start:r,end:r+i.length,headerLength:a,contentStart:o,content:s,name:l})}return n}function Tn(e,n){let t=[];He.lastIndex=0;let r;for(;r=He.exec(e);){let i=r.index??0,a=i+r[0].length;if(xn(i,n))continue;let s=En(r[0],i),o={};for(let l of Qe)s[l]&&(o[l]=s[l]);t.push({start:i,end:a,data:s.data||null,attributes:o})}return t}function kn(e){let n=e.trim().split(/\s+/);if(n.length>1)return n[1]}function En(e,n){let t={};et.lastIndex=0;let r;for(;r=et.exec(e);){let i=r[1],a=r[2],s=n+r.index+i.length+2;t[i]={value:a,start:s}}return t}function xn(e,n){return n.some(t=>e>=t.start&&e<t.end)}function Cn(e){return e.content!==void 0}var Qe,Je,He,et,nt=E(()=>{Pe();Qe=["x","y","y2","series","value","category"],Je=/^([ \t]*)(`{3,})g?sql[^\n]*\n([\s\S]*?)^\1\2[ \t]*$/gim,He=/<([A-Z][A-Za-z0-9]*)\s+[^>]*\/>/g,et=/(\w+)="([^"]*)"/g});import{registerDialect as Sn,StandardSQLDialect as Xn,QueryModel as vn,expandBlueprintMap as Rn}from"@graphenedata/malloy";import{readFile as qn}from"node:fs/promises";import{glob as _n}from"glob";import Fn from"node:path";function rt(e){return x[e]}function _(){return L}async function U(e,n){let t=await _n(n?"**/*.{gsql,md}":"**/*.gsql",{cwd:e,ignore:["node_modules/**"]});for await(let r of t){let i=await qn(Fn.join(e,r),"utf-8");it(i,r)}}function it(e,n){return x[n]||={path:n,contents:e,tree:null,tables:[],queries:[]},x[n].contents=e,x[n].tree=null,x[n]}function j(e,n){if(Me(),delete x.input,e&&it(e,"input"),Object.values(x).forEach(t=>{let r=t.path.endsWith(".md")||t.path=="input"&&n=="md";t.tree||=r?tt(t):ee.parse(t.contents),t.tree.fileInfo=t,Ge(t),We(t)}),Object.values(x).flatMap(t=>t.tables).forEach(Ze),e){let t=x.input,r=t.tree.topNode.getChildren("QueryStatement")||[];return t.queries=r.map(he).filter(i=>!!i),t.queries}else return[]}function Y(e,n={}){let t={};Object.values(x).filter(o=>o.path!=="input").flatMap(o=>o.tables).forEach(o=>t[o.name]=o),[...x.input?.tables||[],...e.subQuerySources].forEach(o=>t[o.name]={...o,query:o.query&&ce(o.query,n)});let a=ce(e.malloyQuery,n);return new vn({name:"generated_model",contents:t,queryList:[],dependencies:{},exports:[]}).compileQuery(a).sql}var be,te=E(()=>{Ye();pe();Z();N();Oe();Pe();nt();be=class extends Xn{constructor(){super(),this.name="bigquery"}getDialectFunctions(){return Rn(Ue)}};Sn(new be)});var Ot={};ae(Ot,{BigQueryConnection:()=>Ce});import{BigQuery as Wn,BigQueryDate as Vn,BigQueryTimestamp as Zn}from"@google-cloud/bigquery";var Ce,ct=E(()=>{N();Ce=class{client;constructor(n={}){if(n.projectId||=y.googleProjectId,n.maxRetries||=3,n.userAgent||="Graphene",!n.projectId)throw new Error("googleProjectId must be set in config or provided in service account credentials");this.client=new Wn(n)}async runQuery(n){let[t]=await this.client.createQueryJob({query:n,useLegacySql:!1}),[r]=await t.getQueryResults({maxResults:1e4}),i=t.metadata||(await t.getMetadata())[0],a=Number(i?.statistics?.query?.totalRows??r.length);return r.forEach(s=>{Object.entries(s).forEach(([o,l])=>{l instanceof Zn&&(s[o]=l.value),l instanceof Vn&&(s[o]=l.value)})}),{rows:r,totalRows:a}}}});var pt={};ae(pt,{DuckDBConnection:()=>Se});import{promises as zn}from"fs";import Mn from"path";import{DuckDBTimestampValue as Gn,DuckDBInstance as Ln,DuckDBDateValue as Yn}from"@duckdb/node-api";var Se,dt=E(()=>{N();Se=class{ready;connection=null;constructor(){this.ready=this.initialize()}async initialize(){let t=(await zn.readdir(y.root)).find(a=>a.endsWith(".duckdb"));if(!t)throw new Error("No .duckdb file found in current directory");t=Mn.resolve(y.root,t);let r=await Ln.create(":memory:");this.connection=await r.connect();let i=t.replace(/'/g,"''");await this.connection.run(`attach '${i}' as graphene_cli (READ_ONLY);`),await this.connection.run("use graphene_cli;")}async runQuery(n){return await this.ready,{rows:(await this.connection.runAndReadAll(n)).getRowObjects().map(i=>{let a={};for(let[s,o]of Object.entries(i))if(typeof o=="bigint")a[s]=Number(o);else if(o===null)a[s]=null;else if(o instanceof Gn)a[s]=new Date(Number(o.micros/1000n)).toUTCString();else if(o instanceof Yn)a[s]=o.toString();else{if(typeof o=="object")throw new Error(`Unsupported datatype ${o.constructor?.name}`);a[s]=o}return a})}}}});async function ne(){if(y.dialect==="bigquery"){let e=await Promise.resolve().then(()=>(ct(),Ot));return new e.BigQueryConnection}else if(y.dialect==="duckdb"){let e=await Promise.resolve().then(()=>(dt(),pt));return new e.DuckDBConnection}else throw new Error(`Unsupported dialect: ${y.dialect}`)}var Xe=E(()=>{N()});var mt={};ae(mt,{mockFileMap:()=>qe,serve2:()=>sr});import{createServer as Kn,optimizeDeps as Bn}from"vite";import{svelte as Jn,vitePreprocess as Hn}from"@sveltejs/vite-plugin-svelte";import{visit as er}from"unist-util-visit";import re from"fs-extra";import tr from"crypto";import{mdsvex as nr}from"mdsvex";import F from"path";import{fileURLToPath as rr}from"url";import{WebSocketServer as ir}from"ws";import{spawn as ar}from"child_process";async function sr(){D=y.root,K=F.join(rr(import.meta.url),"../../ui"),await re.ensureDir(F.resolve(D,"node_modules/.graphene")),await re.writeFile(F.resolve(D,`node_modules/.graphene/${process.env.NODE_ENV=="test"?"test":"serve"}.pid`),String(process.pid));let e=await Kn({root:y.root,plugins:[Jn({extensions:[".svelte",".md"],preprocess:[Hn(),nr({extensions:[".md"],remarkPlugins:[cr],layout:F.resolve(K,"layout.svelte")}),pr()]}),lr,or,dr()],server:{port:y.port,fs:{strict:!1},strictPort:!0},optimizeDeps:{},resolve:{alias:{graphene:F.resolve(K,"web.js")}}});return await Bn(e.config),await e.listen(),console.log(`Server running at http://localhost:${y.port}`),e}async function ur(e,n){let t=[];for await(let p of e)t.push(p);let{gsql:r,params:i,hashes:a}=JSON.parse(Buffer.concat(t).toString());n.setHeader("Content-Type","application/json"),await ve;let s=j(r);if(_().length){n.statusCode=400,n.end(JSON.stringify(_()));return}if(s.length>1)throw new Error("Found multiple queries, which could be a parsing error");let o=Y(s[0],i),l=tr.createHash("SHA1").update(o).digest("hex");if(n.setHeader("ETag",l),a.includes(l)&&e.headers["cache-control"]!="no-cache")return n.statusCode=304,n.end();let d=await(await ne()).runQuery(o);if((d.totalRows??d.rows.length)>d.rows.length)throw new Error("Query returns too many rows");let T=s[0].fields.map(p=>({name:p.name,type:p.type}));n.end(JSON.stringify({rows:d.rows,hash:l,fields:T,sql:o}))}async function Or(e,n){let t=[];for await(let l of e)t.push(l);let{mdFile:r,chart:i}=JSON.parse(Buffer.concat(t).toString()),a=Math.random().toString(36).slice(2);n.setHeader("Content-Type","application/json"),Re[a]={response:n};let s="/"+r.replace(/\.md$/,"").replace(/^\//,"");s==="/index"&&(s="/"),s=`http://localhost:${y.port||4e3}${s}`;let o=B.find(l=>l.url===s);if(!o){ar("open",[s]);let l=Date.now()+5e3;for(;Date.now()<l&&!o;)o=B.find(m=>m.url===s),await new Promise(m=>setTimeout(m,100));if(!o)return n.statusCode=500,n.end(JSON.stringify({error:"No browser tab available and failed to open one"}))}o.socket.send(JSON.stringify({type:"view",chart:i,requestId:a}))}async function ft(e,n,t,r){n.setHeader("Content-Type","text/html");let i=r?`
13
+ import Page from ${JSON.stringify(t)};
14
+ new Page({ target: document.getElementById('app'), props: {} })
15
+ `:"",a=await e.transformIndexHtml(t,`<!doctype html>
16
+ <html lang="en">
17
+ <head>
18
+ <meta charset="UTF-8" />
19
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
20
+ <title>Graphene</title>
21
+ <link rel="icon" href="@graphenedata/ui/assets/favicon.ico" />
22
+ <link rel="preconnect" href="https://fonts.googleapis.com">
23
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
24
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap" rel="stylesheet">
25
+ </head>
26
+ <body>
27
+ <div id="app"></div>
28
+ <script type="module">
29
+ // do this first so we can track errors caused by importing the md file
30
+ import 'graphene'
31
+ // import '${K}/web.js'
32
+ console.log('imported graphene')
33
+ </script>
34
+ <script type="module">
35
+ console.log('starting mount')
36
+ ${i}
37
+ </script>
38
+ </body>
39
+ </html>`);return n.end(a)}function cr(){function e(n){return n.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}return function(t){er(t,"code",(r,i,a)=>{i!==null&&(a.children[i]={type:"html",value:`<GrapheneQuery name="${e(r.meta)}" code="${e(r.value.trim())}" />`})})}}function pr(){let t=`const {${re.readdirSync(F.join(K,"components")).map(r=>F.basename(r,".svelte")).filter(r=>!r.startsWith("_")).join(", ")}} = window.$GRAPHENE.components`;return{markup:({content:r,filename:i})=>{if(i.endsWith(".md"))return r=r.replace("<script>",`<script>
40
+ ${t}`),{code:r}},style:()=>{},script:()=>{}}}function dr(){return process.env.NODE_ENV!=="test"?null:{name:"mock-files-for-tests",enforce:"pre",resolveId(e){if(qe[e.replace(D,"")])return e+"?mock"},load(e){return e.endsWith("?mock")?qe[e.replace(D,"").replace(/\?mock$/,"")]:null}}}var D,K,ve,or,lr,B,Re,qe,gt=E(()=>{te();Xe();or={name:"updateWorkspace",configureServer:e=>{e.watcher.add("**/*.gsql"),e.watcher.on("change",()=>{ye(),ve=U(D,!1)}),ve=U(D,!1)}},lr={name:"handleRequest",configureServer:e=>{let n=new ir({noServer:!0});e.httpServer.on("upgrade",(t,r,i)=>{t.url?.endsWith("/graphene-ws")&&n.handleUpgrade(t,r,i,a=>{n.emit("connection",a,t)})}),n.on("connection",t=>{t.on("message",r=>{let i=JSON.parse(r.toString());i.type==="register"&&B.push({url:i.url,socket:t}),i.type==="viewResponse"&&(Re[i.requestId].response.end(JSON.stringify(i)),delete Re[i.requestId])}),t.on("close",()=>B=B.filter(r=>r.socket!==t))}),e.middlewares.use(async function(r,i,a){try{let[s]=(r.url||"").split("?");if(s=="/_api/query")return await ur(r,i);if(s=="/graphene/view")return await Or(r,i);if(s=="/__ct")return await ft(e,i,"__ct",!1);(!s||s=="/")&&(s="index");let o=F.join(D,s+".md");await re.exists(o)?await ft(e,i,o,!0):a()}catch(s){console.error(s),i.statusCode=500,i.end(JSON.stringify([{message:s.message,stack:s.stack}]))}})}};B=[],Re={};qe={}});import{Command as fr}from"commander";te();import{styleText as at}from"node:util";import Dn from"cli-table3";import we from"chalk";var st=(e,n)=>{try{return at?at(e,n):n}catch{return n}};function In(e,n){let t=e.split(/\r?\n/),r=0;for(let i=0;i<t.length;i++){let a=t[i],s=r+a.length+1;if(n<s||i===t.length-1){let o=Math.max(0,n-r);return{line:i+1,col:o,lineStart:r,lineText:a}}r=s}return{line:1,col:0,lineStart:0,lineText:t[0]||""}}function Te(e){let n=[];for(let t of e){let r=rt(t.file)?.contents||"",{line:i,col:a,lineStart:s,lineText:o}=In(r,t.from.offset),l=Math.max(a+1,Math.min(o.length,t.to.offset-s)),m=Math.max(1,l-a),d=t.severity==="error"?"red":"yellow",P=`${st(d,t.severity.toUpperCase())}: ${t.file} line ${i}: ${t.message}`,T=" | ",p=`${" ".repeat(a)}${st(d,"^".repeat(m))}`;n.push([P,`${T}${o}`,`${T}${p}`].join(`
41
+ `))}n.length&&console.error(n.join(`
42
+ `))}function ot(e){if(!e||e.length===0){console.log(we.yellow("No results returned"));return}let n=Object.keys(e[0]),t=new Dn({head:n.map(a=>we.blue(a))}),r=200;e.slice(0,r).forEach(a=>t.push(n.map(s=>a[s]?.toString()||""))),console.log(t.toString()),e.length>r&&console.log(we.yellow(`Displayed first ${r} rows (of ${e.length} total).`))}te();N();import _e from"fs-extra";import ht from"path";import mr from"os";import{spawn as Nn}from"child_process";import{fileURLToPath as Un}from"url";import v from"fs-extra";import Ee from"path";async function lt(){let e=process.cwd(),n=ut(e),t=Ee.join(n,"serve.log");await v.ensureDir(n),await xe(e);let r=v.openSync(t,"w"),i=process.argv[1]||Un(import.meta.url),a=[...process.execArgv,i,"serve","--fg",...process.argv.slice(3)],s=Nn(process.execPath,a,{cwd:e,detached:!0,env:{...process.env},stdio:["ignore",r,r]});if(!s.pid)throw new Error("Failed to start server process");await new Promise((o,l)=>{let m="";v.watchFile(t,{interval:200},(d,P)=>{d.size>P.size&&v.createReadStream(t,{start:0,end:d.size-1}).on("data",p=>{process.stdout.write(p),m=(m+p.toString()).slice(-200),m.includes("Server running at http://localhost:")&&o()})}),s.once("exit",()=>{process.stdout.write(v.readFileSync(t)),l(new Error("Exited before server started"))}),s.once("error",d=>l(d))})}function ut(e){return Ee.join(e,"node_modules",".graphene")}function An(e){return Ee.join(ut(e),process.env.NODE_ENV=="test"?"test.pid":"serve.pid")}async function xe(e){let n=An(e),t=await jn(n);if(!t)return!0;if(!ke(t))return await v.remove(n),!0;try{console.log(`Stopping server (${t})`),process.kill(t,"SIGTERM")}catch(i){return i.code==="ESRCH"}let r=Date.now()+5e3;for(;Date.now()<r&&ke(t);)await new Promise(i=>setTimeout(i,100));return await v.remove(n),!ke(t)}async function jn(e){if(!await v.pathExists(e))return;let n=(await v.readFile(e,"utf8")).trim();if(!n)return;let t=Number.parseInt(n,10);if(!Number.isNaN(t))return t}function ke(e){try{return process.kill(e,0),!0}catch{return!1}}Xe();var S=new fr;S.name("graphene").description("Graphene CLI").version("1.0.0");S.hook("preAction",async()=>{process.env.CLI_DELAY&&await new Promise(e=>setTimeout(e,1e3)),oe(process.cwd())});S.command("compile").description("Translate a query to SQL and print it").argument("[input]",'Path to file, a raw string, or "-" for stdin').action(async e=>{await U(process.cwd(),!1);let n=await yt(e),t=j(n);$t(t)&&console.log(Y(t[0]))});S.command("run").description("Run a query against your database").argument("[input]",'Path to file, a raw string, or "-" for stdin').action(async e=>{await U(process.cwd(),!1);let n=await yt(e),t=j(n);if(!$t(t))return;let r=Y(t[0]),a=await(await ne()).runQuery(r);ot(a.rows)});S.command("serve").description("Run the local server").option("--fg","Run the server in the foreground").action(async e=>{e.fg||process.env.DEBUG?await(await Promise.resolve().then(()=>(gt(),mt))).serve2():(await lt(),process.exit(0))});S.command("stop").description("Stop the local server").action(async()=>{await xe(process.cwd())});S.command("check").description("Check the project for errors").action(async()=>{await U(process.cwd(),!0),j(),_().length&&(Te(_()),process.exit(1)),console.log("No errors found \u{1F48E}")});S.command("view").description("Capture a screenshot of a rendered markdown file").argument("<mdFile>","Markdown file to view (e.g., index.md)").option("-c, --chart <chartName>","Name of specific chart to capture").action(async(e,n)=>{let t=await fetch("http://localhost:4000/graphene/view",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mdFile:e,chart:n.chart})});if(!t.ok)throw new Error(`View request failed: ${await t.text()}`);let r=await t.json();if(r.errors&&r.errors.length>0&&(console.error("Errors found:"),r.errors.forEach(i=>console.error(JSON.stringify(i)))),r.stillLoading&&console.error("Warning: Queries were still loading when the screenshot was taken"),r.screenshot){let i=`graphene-screenshot-${new Date().toISOString().replace(/[:.]/g,"-")}.png`,a=ht.join(mr.tmpdir(),i),s=r.screenshot.replace(/^data:image\/png;base64,/,"");await _e.writeFile(a,s,"base64"),console.log("Screenshot saved to",a)}});process.env.GRAPHENE_DEBUG&&S.commands.find(n=>n._name==process.argv[2])._actionHandler;S.parse(process.argv);async function yt(e){if(!e||e==="-")return await new Promise(t=>{let r="";process.stdin.setEncoding("utf-8"),process.stdin.on("data",i=>r+=i),process.stdin.on("end",()=>t(r)),process.stdin.resume()});let n=ht.resolve(e);return _e.existsSync(n)?await _e.promises.readFile(n,"utf-8"):e}function $t(e){return _().length&&(Te(_()),process.exit(1)),e.length==0&&(console.warn("No queries found"),process.exit(1)),!0}
43
+ //# sourceMappingURL=cli.js.map