philipgreat commited on
Commit
f8491b7
·
verified ·
1 Parent(s): 9096da5

feat: enrich order line items

Browse files

Rename Product details to Line Items, seed two five-item orders, and show the queried total alongside three previews.

.gitattributes CHANGED
@@ -38,6 +38,3 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
38
  # the static Space is self-contained and reproducible without Git LFS tooling.
39
  assets/*.wasm -filter -diff -merge -text
40
  dist/assets/*.wasm -filter -diff -merge -text
41
- dist/tracechain-openobserve.png filter=lfs diff=lfs merge=lfs -text
42
- source/teaql-ts/examples/browser-sqlite/public/tracechain-openobserve.png filter=lfs diff=lfs merge=lfs -text
43
- tracechain-openobserve.png filter=lfs diff=lfs merge=lfs -text
 
38
  # the static Space is self-contained and reproducible without Git LFS tooling.
39
  assets/*.wasm -filter -diff -merge -text
40
  dist/assets/*.wasm -filter -diff -merge -text
 
 
 
README.md CHANGED
@@ -38,6 +38,11 @@ request whose search parameters change without changing the query shape. Results
38
  can be inspected as a table or a tree. The evidence table shows execution time,
39
  request identity, the runtime-provided TraceChain and executed SQL.
40
 
 
 
 
 
 
41
  Additional entry points are retained independently:
42
 
43
  - [`/orders.html`](./orders.html): generated Order model and request-tree conformance view.
@@ -51,7 +56,7 @@ cross-origin isolation.
51
 
52
  The exact runtime, tests, model, generated Order library and browser application
53
  source are retained under [`source/teaql-ts`](./source/teaql-ts). They correspond to
54
- TeaQL TypeScript commit `1b08ed83aaac37a8ebaed7306e646630a8ea0aec` on `main`.
55
 
56
  ```bash
57
  cd source/teaql-ts
 
38
  can be inspected as a table or a tree. The evidence table shows execution time,
39
  request identity, the runtime-provided TraceChain and executed SQL.
40
 
41
+ The Line Items column previews at most three queried items per order while a
42
+ separate generated count reports the true total. Two seeded orders contain five
43
+ line items, so the page visibly demonstrates the `5 items` result without
44
+ hard-coded presentation data.
45
+
46
  Additional entry points are retained independently:
47
 
48
  - [`/orders.html`](./orders.html): generated Order model and request-tree conformance view.
 
56
 
57
  The exact runtime, tests, model, generated Order library and browser application
58
  source are retained under [`source/teaql-ts`](./source/teaql-ts). They correspond to
59
+ TeaQL TypeScript commit `1e1f50e7a54f2f47753a24cdd988e53fbde78180` on `main`.
60
 
61
  ```bash
62
  cd source/teaql-ts
assets/{main-C1ZloXXC.js → main-DKg7I1TH.js} RENAMED
@@ -1,6 +1,6 @@
1
- import{S as x,m as Pe,a as qe,e as xe,O as $,B as Qe,b as Re,R as $e,U as Be,D as Fe,c as ke,M as We}from"./dynamic-search-Ch_QcWVU.js";/* empty css */const C=t=>({columnName:t,modelName:t,logicalType:"integer",decode:"string"}),y=t=>({columnName:t,modelName:t,logicalType:"text",decode:"native"}),ze=t=>({columnName:t,modelName:t,logicalType:"date",decode:"date"}),K=t=>({columnName:t,modelName:t,logicalType:"datetime",decode:"date"}),I=(t,e="decimal")=>({columnName:t,modelName:t,logicalType:e,decode:"number"}),f=Object.freeze({PENDING_PAYMENT:"1001",PAID:"1002",SHIPPED:"1003",DELIVERED:"1004",CANCELLED:"1005"}),Me=[{entity:"OrderStatus",id:f.PENDING_PAYMENT,values:{name:"Pending payment",code:"PENDING_PAYMENT",color:"#D97706",displayOrder:10}},{entity:"OrderStatus",id:f.PAID,values:{name:"Paid",code:"PAID",color:"#2563EB",displayOrder:20}},{entity:"OrderStatus",id:f.SHIPPED,values:{name:"Shipped",code:"SHIPPED",color:"#16A34A",displayOrder:30}},{entity:"OrderStatus",id:f.DELIVERED,values:{name:"Delivered",code:"DELIVERED",color:"#047857",displayOrder:40}},{entity:"OrderStatus",id:f.CANCELLED,values:{name:"Cancelled",code:"CANCELLED",color:"#9F1239",displayOrder:50}}],ie={Platform:{table:"platform_data",columns:{id:C("id"),name:y("name"),code:y("code"),region:y("region"),currency:y("currency"),version:I("version","integer")},relations:{customerList:{targetEntity:"Customer",localKey:"id",foreignKey:"platformId",many:!0},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"platformId",many:!0}}},Customer:{table:"customer_data",columns:{id:C("id"),name:y("name"),email:y("email"),city:y("city"),tier:y("tier"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"customerId",many:!0}}},CustomerOrder:{table:"customer_order_data",columns:{id:C("id"),orderNumber:y("order_number"),orderDate:ze("order_date"),status:C("status_id"),totalAmount:I("total_amount"),currency:y("currency"),customerId:C("customer_id"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},customer:{targetEntity:"Customer",localKey:"customerId",foreignKey:"id",many:!1},status:{targetEntity:"OrderStatus",localKey:"status",foreignKey:"id",many:!1},itemList:{targetEntity:"OrderItem",localKey:"id",foreignKey:"orderId",many:!0},paymentList:{targetEntity:"Payment",localKey:"id",foreignKey:"orderId",many:!0},shipmentList:{targetEntity:"Shipment",localKey:"id",foreignKey:"orderId",many:!0}}},OrderStatus:{table:"order_status_data",columns:{id:C("id"),name:y("name"),code:y("code"),color:y("color"),displayOrder:I("display_order","integer"),version:I("version","integer")},relations:{orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"status",many:!0}}},OrderItem:{table:"order_item_data",columns:{id:C("id"),orderId:C("order_id"),productName:y("product_name"),sku:y("sku"),quantity:I("quantity","integer"),unitPrice:I("unit_price"),lineAmount:I("line_amount"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Payment:{table:"payment_data",columns:{id:C("id"),orderId:C("order_id"),provider:y("provider"),status:y("status"),amount:I("amount"),currency:y("currency"),transactionId:y("transaction_id"),paidAt:K("paid_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Shipment:{table:"shipment_data",columns:{id:C("id"),orderId:C("order_id"),carrier:y("carrier"),status:y("status"),trackingNumber:y("tracking_number"),shipToCity:y("ship_to_city"),shippedAt:K("shipped_at"),deliveredAt:K("delivered_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}}},pe=[{entity:"Platform",id:"1",payload:{name:"TeaQL Store",code:"TEAQL-CN",region:"China",currency:"CNY"}},{entity:"Platform",id:"2",payload:{name:"TeaQL Global",code:"TEAQL-GLOBAL",region:"Global",currency:"USD"}},{entity:"Customer",id:"101",payload:{name:"Lin Xiao",email:"lin.xiao@example.com",city:"Shanghai",tier:"GOLD",platformId:"1"}},{entity:"Customer",id:"102",payload:{name:"Zhou Ran",email:"zhou.ran@example.com",city:"Hangzhou",tier:"SILVER",platformId:"1"}},{entity:"Customer",id:"103",payload:{name:"Maya Patel",email:"maya.patel@example.com",city:"Singapore",tier:"GOLD",platformId:"2"}},{entity:"Customer",id:"104",payload:{name:"Lucas Martin",email:"lucas.martin@example.com",city:"Paris",tier:"SILVER",platformId:"2"}},{entity:"Customer",id:"105",payload:{name:"Wang Ning",email:"wang.ning@example.com",city:"Chengdu",tier:"BRONZE",platformId:"1"}},{entity:"CustomerOrder",id:"1001",payload:{orderNumber:"TQL-2026-1001",orderDate:"2026-08-28",status:f.DELIVERED,totalAmount:499,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1002",payload:{orderNumber:"TQL-2026-1002",orderDate:"2026-09-02",status:f.SHIPPED,totalAmount:1299,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1003",payload:{orderNumber:"TQL-2026-1003",orderDate:"2026-09-06",status:f.PAID,totalAmount:328.8,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1004",payload:{orderNumber:"TQL-2026-1004",orderDate:"2026-09-11",status:f.PENDING_PAYMENT,totalAmount:79.9,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"CustomerOrder",id:"1005",payload:{orderNumber:"TQL-2026-1005",orderDate:"2026-09-14",status:f.DELIVERED,totalAmount:219,currency:"USD",customerId:"103",platformId:"2"}},{entity:"CustomerOrder",id:"1006",payload:{orderNumber:"TQL-2026-1006",orderDate:"2026-09-18",status:f.PAID,totalAmount:640,currency:"USD",customerId:"104",platformId:"2"}},{entity:"CustomerOrder",id:"1007",payload:{orderNumber:"TQL-2026-1007",orderDate:"2026-09-21",status:f.CANCELLED,totalAmount:159,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1008",payload:{orderNumber:"TQL-2026-1008",orderDate:"2026-09-25",status:f.SHIPPED,totalAmount:268,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"OrderItem",id:"2001",payload:{orderId:"1001",productName:"TeaQL Mechanical Keyboard",sku:"KB-TQL-87",quantity:1,unitPrice:299,lineAmount:299}},{entity:"OrderItem",id:"2002",payload:{orderId:"1001",productName:"Silent Wireless Mouse",sku:"MS-SILENT",quantity:2,unitPrice:100,lineAmount:200}},{entity:"OrderItem",id:"2003",payload:{orderId:"1002",productName:"27-inch Developer Monitor",sku:"MON-27-4K",quantity:1,unitPrice:1299,lineAmount:1299}},{entity:"OrderItem",id:"2004",payload:{orderId:"1003",productName:"White Porcelain Travel Tea Set",sku:"TEA-TRAVEL",quantity:1,unitPrice:168.8,lineAmount:168.8}},{entity:"OrderItem",id:"2005",payload:{orderId:"1003",productName:"Pre-Qingming Longjing Tea",sku:"TEA-LJ-100",quantity:2,unitPrice:80,lineAmount:160}},{entity:"OrderItem",id:"2006",payload:{orderId:"1004",productName:"Double-wall Glass Tumbler",sku:"CUP-GLASS",quantity:1,unitPrice:79.9,lineAmount:79.9}},{entity:"OrderItem",id:"2007",payload:{orderId:"1005",productName:"Travel Brew Kit",sku:"BREW-KIT",quantity:1,unitPrice:219,lineAmount:219}},{entity:"OrderItem",id:"2008",payload:{orderId:"1006",productName:"Desktop Studio Speaker",sku:"SPK-STUDIO",quantity:2,unitPrice:260,lineAmount:520}},{entity:"OrderItem",id:"2009",payload:{orderId:"1006",productName:"Speaker Stand",sku:"SPK-STAND",quantity:1,unitPrice:120,lineAmount:120}},{entity:"OrderItem",id:"2010",payload:{orderId:"1007",productName:"Desktop Reading Lamp",sku:"LAMP-DESK",quantity:1,unitPrice:159,lineAmount:159}},{entity:"OrderItem",id:"2011",payload:{orderId:"1008",productName:"TeaQL Portable Keyboard",sku:"KB-TQL-68",quantity:1,unitPrice:268,lineAmount:268}},{entity:"Payment",id:"3001",payload:{orderId:"1001",provider:"Alipay",status:"CAPTURED",amount:499,currency:"CNY",transactionId:"ALI-260828-01",paidAt:"2026-08-28T10:14:00Z"}},{entity:"Payment",id:"3002",payload:{orderId:"1002",provider:"WeChat Pay",status:"CAPTURED",amount:1299,currency:"CNY",transactionId:"WX-260902-08",paidAt:"2026-09-02T03:20:00Z"}},{entity:"Payment",id:"3003",payload:{orderId:"1003",provider:"Alipay",status:"CAPTURED",amount:328.8,currency:"CNY",transactionId:"ALI-260906-11",paidAt:"2026-09-06T11:42:00Z"}},{entity:"Payment",id:"3004",payload:{orderId:"1004",provider:"WeChat Pay",status:"PENDING",amount:79.9,currency:"CNY",transactionId:"WX-260911-02",paidAt:null}},{entity:"Payment",id:"3005",payload:{orderId:"1005",provider:"Stripe",status:"CAPTURED",amount:219,currency:"USD",transactionId:"PI-260914-05",paidAt:"2026-09-14T06:10:00Z"}},{entity:"Payment",id:"3006",payload:{orderId:"1006",provider:"Stripe",status:"CAPTURED",amount:640,currency:"USD",transactionId:"PI-260918-03",paidAt:"2026-09-18T15:08:00Z"}},{entity:"Payment",id:"3007",payload:{orderId:"1007",provider:"Alipay",status:"REFUNDED",amount:159,currency:"CNY",transactionId:"ALI-260921-07",paidAt:"2026-09-21T02:55:00Z"}},{entity:"Payment",id:"3008",payload:{orderId:"1008",provider:"WeChat Pay",status:"CAPTURED",amount:268,currency:"CNY",transactionId:"WX-260925-06",paidAt:"2026-09-25T08:31:00Z"}},{entity:"Shipment",id:"4001",payload:{orderId:"1001",carrier:"SF Express",status:"DELIVERED",trackingNumber:"SF2608281001",shipToCity:"Shanghai",shippedAt:"2026-08-29T02:00:00Z",deliveredAt:"2026-08-30T07:26:00Z"}},{entity:"Shipment",id:"4002",payload:{orderId:"1002",carrier:"JD Logistics",status:"IN_TRANSIT",trackingNumber:"JD2609021002",shipToCity:"Hangzhou",shippedAt:"2026-09-03T04:12:00Z",deliveredAt:null}},{entity:"Shipment",id:"4003",payload:{orderId:"1003",carrier:"SF Express",status:"READY",trackingNumber:"SF2609061003",shipToCity:"Shanghai",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4004",payload:{orderId:"1005",carrier:"DHL",status:"DELIVERED",trackingNumber:"DHL2609141005",shipToCity:"Singapore",shippedAt:"2026-09-15T01:10:00Z",deliveredAt:"2026-09-17T09:22:00Z"}},{entity:"Shipment",id:"4005",payload:{orderId:"1006",carrier:"DHL",status:"READY",trackingNumber:"DHL2609181006",shipToCity:"Paris",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4006",payload:{orderId:"1008",carrier:"SF Express",status:"IN_TRANSIT",trackingNumber:"SF2609251008",shipToCity:"Chengdu",shippedAt:"2026-09-26T03:18:00Z",deliveredAt:null}}],N=t=>`'${t.replaceAll("\\","\\\\").replaceAll("'","\\'").replaceAll(`
2
- `,"\\n")}'`,U=t=>t.toQExpression().replace(/\s*\n\s*/g,""),_e={CustomerOrder:{fields:{id:"integer",orderNumber:"string",orderDate:"date",status:"integer",totalAmount:"decimal",currency:"string",customerId:"integer",platformId:"integer"},relations:{status:"OrderStatus",itemList:"OrderItem"}},OrderStatus:{fields:{id:"integer",name:"string",code:"string",color:"string",displayOrder:"integer"},relations:{}},OrderItem:{fields:{id:"integer",orderId:"integer",productName:"string",sku:"string"},relations:{}}};function Ke(t){if(!t||typeof t!="object"||Array.isArray(t))return t;const e=structuredClone(t),r=e.filter;if(!r||typeof r!="object"||Array.isArray(r)||!("status"in r))return e;const n=r,s=n.status,o=a=>{const i=f[String(a)];return i===void 0?a:Number(i)};return s&&typeof s=="object"&&!Array.isArray(s)&&"$in"in s?n.status={$in:Array.isArray(s.$in)?s.$in.map(o):s.$in}:n.status=o(s),e}class T{query;filters=[];qRoot;qSteps=[];auditComment="";queryPurpose="";pageTotalAlias;constructor(e,r){this.query=new x(e),this.qRoot=r}comment(e){return this.auditComment=e,this.query.comment(e),this.record(`comment(${N(e)})`),this}purpose(e){return this.queryPurpose=e,this.query.purpose(e),this.record(`purpose(${N(e)})`),this}limit(e){return this.query.limit(e),this.record(`limit(${e})`),this}offset(e){return this.query.offset(e),this.record(`offset(${e})`),this}toQExpression(e){const r=e?[...this.qSteps,e]:this.qSteps;return[this.qRoot,...r.map(n=>` .${n}`)].join(`
3
- `)}toQuery(){const e=this.query.clone();return this.filters.length&&e.filter({$and:[...this.filters]}),e}async executeForList(e){return this.executeList(e,this.pageTotalAlias!==void 0)}async executeForRows(e){return this.executeList(e,!1)}async executeList(e,r){this.ensureIntent();const n=this.service(e),s=this.toQuery(),o=r?await n.executeCount(s,this.pageTotalAlias,{kind:"named-count",method:"countAs",alias:this.pageTotalAlias}):void 0,a=s.clone();r&&(a.aggregateItems=a.aggregateItems.filter(l=>!(String(l.function).toLowerCase()==="count"&&l.alias===this.pageTotalAlias)));const i=await n.executeQuery(e.prepareQuery(a)),c=new qe(i,{totalCount:o});return r&&this.pageTotalAlias!==void 0&&(c.aggregations[this.pageTotalAlias]=o),s.facets.length&&(c.facets=await xe(n,l=>e.prepareQuery(l),s,s.facets)),c}addFilter(e){return this.filters.push(e),this}select(...e){return this.query.select(e),this}order(e,r){return this.query.order(r==="asc"?$.asc(e):$.desc(e)),this}group(e){return this.query.groupBy(e),this}aggregate(e,r,n){return this.query.aggregate(e,r,n),this}record(e){return this.qSteps.push(e),this}includePageTotalAs(e){return this.pageTotalAlias=e,this}service(e){return e.requireResource("dataService")}ensureIntent(){if(!this.auditComment.trim()||!this.queryPurpose.trim())throw new Error("Generated Q requests require comment() and purpose() before execution")}}class Ue extends T{constructor(){super("Platform","Q.platforms()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCode(){return this.select("code")}withIdIs(e){return this.addFilter({id:{$eq:e}})}}class Ye extends T{constructor(){super("Customer","Q.customers()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCity(){return this.select("city")}selectTier(){return this.select("tier")}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}countOrderListAs(e){return this.query.relationAggregate("orderList",e,new x("CustomerOrder").aggregate("Count","id",e)),this}orderByNameAscending(){return this.order("name","asc")}}class Ge extends T{constructor(){super("OrderItem","Q.orderItems()")}selectId(){return this.select("id"),this.record("selectId()")}selectOrderId(){return this.select("orderId"),this.record("selectOrderId()")}selectProductName(){return this.select("productName"),this.record("selectProductName()")}selectSku(){return this.select("sku"),this.record("selectSku()")}selectQuantity(){return this.select("quantity"),this.record("selectQuantity()")}withProductNameContaining(e){return this.addFilter({productName:{$contains:e}})}orderByIdAscending(){return this.order("id","asc"),this.record("orderByIdAscending()")}groupByProductName(){return this.group("productName")}sumQuantityAs(e){return this.aggregate("Sum","quantity",e)}sumLineAmountAs(e){return this.aggregate("Sum","lineAmount",e)}countAs(e){return this.aggregate("Count","id",e)}}class je extends T{constructor(){super("OrderStatus","Q.orderStatuses()")}selectId(){return this.select("id"),this.record("selectId()")}selectName(){return this.select("name"),this.record("selectName()")}selectCode(){return this.select("code"),this.record("selectCode()")}selectColor(){return this.select("color"),this.record("selectColor()")}selectDisplayOrder(){return this.select("displayOrder"),this.record("selectDisplayOrder()")}withCodeIs(e){return this.addFilter({code:{$eq:e}})}countAs(e){return this.aggregate("Count","id",e),this.record(`countAs(${N(e)})`)}sumOrderTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e),this.record(`sumOrderTotalAmountAs(${N(e)})`)}orderByDisplayOrderAscending(){return this.order("displayOrder","asc"),this.record("orderByDisplayOrderAscending()")}}class Ve extends T{constructor(){super("Payment","Q.payments()")}groupByCurrency(){return this.group("currency")}groupByProvider(){return this.group("provider")}groupByStatus(){return this.group("status")}countAs(e){return this.aggregate("Count","id",e)}sumAmountAs(e){return this.aggregate("Sum","amount",e)}orderByCurrencyAscending(){return this.order("currency","asc")}orderByProviderAscending(){return this.order("provider","asc")}orderByIdAscending(){return this.order("id","asc")}}class He extends T{constructor(){super("Shipment","Q.shipments()")}withStatusIn(...e){return this.addFilter({status:{$in:e}})}selectOrderWith(e){return this.query.relationQuery("order",e.toQuery(),"orderId","id",!1),this}orderByStatusAscending(){return this.order("status","asc")}orderByIdAscending(){return this.order("id","asc")}}class de extends T{dynamicWarnings=[];countAlias;rowCountApplied=!1;constructor(e=!1){super("CustomerOrder",e?"Q.customerOrdersWithMinimalFields()":"Q.customerOrders()"),e?this.query.select(["id","version"]):this.query.select(["id","orderNumber","orderDate","status","totalAmount","currency","customerId","platformId","version"])}selectId(){return this.select("id")}selectOrderNumber(){return this.select("orderNumber"),this.record("selectOrderNumber()")}selectOrderDate(){return this.select("orderDate"),this.record("selectOrderDate()")}selectStatus(){return this.select("status")}selectTotalAmount(){return this.select("totalAmount")}selectCurrency(){return this.select("currency")}withOrderNumberIs(e){return this.addFilter({orderNumber:{$eq:e}})}withOrderNumberContaining(e){return this.addFilter({orderNumber:{$contains:e}})}withStatusMatching(e){return this.addFilter({status:{$inSubquery:{query:e.toQuery(),field:"id"}}})}withStatusIsPendingPayment(){return this.addFilter({status:{$eq:f.PENDING_PAYMENT}})}withStatusIsPaid(){return this.addFilter({status:{$eq:f.PAID}})}withStatusIsShipped(){return this.addFilter({status:{$eq:f.SHIPPED}})}withStatusIsDelivered(){return this.addFilter({status:{$eq:f.DELIVERED}})}withStatusIsCancelled(){return this.addFilter({status:{$eq:f.CANCELLED}})}withCurrencyIs(e){return this.addFilter({currency:{$eq:e}})}withTotalAmountGreaterThanOrEqualTo(e){return this.addFilter({totalAmount:{$gte:e}})}withOrderDateGreaterThanOrEqualTo(e){return this.addFilter({orderDate:{$gte:e}})}withPlatformIdIs(e){return this.addFilter({platformId:{$eq:e}})}withItemListMatching(e){return this.addFilter({id:{$inSubquery:{query:e.toQuery(),field:"orderId"}}})}filterByJson(e){const{query:r,warnings:n}=Pe(this.toQuery(),Ke(e),_e,{filter:(s,o)=>s==="status.code"?{status:{$inSubquery:{query:new x("OrderStatus").filter({code:o}),field:"id"}}}:s==="itemList.productName"?{id:{$inSubquery:{query:new x("OrderItem").filter({productName:o}),field:"orderId"}}}:{[s]:o},order:(s,o)=>o==="asc"?$.asc(s):$.desc(s)});return this.dynamicWarnings=n,this.query.filterCondition=r.filterCondition,this.query.orderItems=[...r.orderItems],this.record("filterByJson(searchParams)"),this}warnings(){return this.dynamicWarnings}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}selectCustomerWith(e){return this.query.relationQuery("customer",e.toQuery(),"customerId","id",!1),this}selectStatusWith(e){return this.query.select(["status"]),this.query.relationQuery("status",e.toQuery(),"status","id",!1,{kind:"relation-select",method:"selectStatusWith",relation:"status"}),this.record(`selectStatusWith(${U(e)})`)}selectItemListWith(e){return this.query.relationQuery("itemList",e.toQuery(),"id","orderId",!0,{kind:"relation-select",method:"selectItemListWith",relation:"itemList"}),this.record(`selectItemListWith(${U(e)})`)}selectPaymentListWith(e){return this.query.relationQuery("paymentList",e.toQuery(),"id","orderId",!0),this}selectShipmentListWith(e){return this.query.relationQuery("shipmentList",e.toQuery(),"id","orderId",!0),this}countItemListAs(e){return this.query.relationAggregate("itemList",e,new x("OrderItem").aggregate("Count","id",e).comment("count items"),!0,{kind:"relation-count",method:"countItemListAs",relation:"itemList",alias:e}),this.record(`countItemListAs(${N(e)})`)}facetByStatusAs(e,r,n=!0){const s=r.toQuery();return s.commentText||s.comment("load status facets"),this.query.facetBy(e,"status",{toQuery:()=>s},n,{kind:"facet",method:"facetByStatusAs",relation:"status",alias:e}),this.record(`facetByStatusAs(${N(e)}, ${U(r)})`)}orderByOrderDateDescending(){return this.order("orderDate","desc"),this.record("orderByOrderDateDescending()")}orderByOrderDateAscending(){return this.order("orderDate","asc")}orderByIdDescending(){return this.order("id","desc"),this.record("orderByIdDescending()")}orderByTotalAmountDescending(){return this.order("totalAmount","desc")}groupByCurrency(){return this.group("currency")}groupByStatus(){return this.group("status")}countAs(e){return this.countAlias=e,this.record(`countAs(${N(e)})`)}sumTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e)}averageTotalAmountAs(e){return this.aggregate("Avg","totalAmount",e)}executeForList(e){return this.countAlias&&this.includePageTotalAs(this.countAlias),super.executeForList(e)}executeForRows(e){return this.applyRowCount(),super.executeForRows(e)}applyRowCount(){!this.countAlias||this.rowCountApplied||(this.query.aggregate("Count","id",this.countAlias),this.rowCountApplied=!0)}}class u{static platforms(){return new Ue}static customers(){return new Ye}static customerOrders(){return new de}static customerOrdersWithMinimalFields(){return new de(!0)}static orderItems(){return new Ge}static orderStatuses(){return new je}static payments(){return new Ve}static shipments(){return new He}}const k=document.querySelector("#status"),B=document.querySelector("#persist"),Y=document.querySelector("#reset"),F=document.querySelector("#query-catalog"),w=document.querySelector("#result"),ye=document.querySelector("#result-title"),he=document.querySelector("#result-description"),J=document.querySelector("#result-meta"),ce=document.querySelector("#query-code"),Ze=document.querySelector("#query-params-block"),Je=document.querySelector("#query-params-code"),Xe=document.querySelector("#result-grid"),R=document.querySelector("#result-view-label"),et=document.querySelector("#sql-count"),ue=document.querySelector("#sql-output"),X=document.querySelector("#expand-all"),tt=document.querySelector("#collapse-all"),Q=document.querySelector("#view-table"),V=document.querySelector("#view-tree"),ge=Array.from(document.querySelectorAll("[data-locale]")),rt={heroTitle:{en:"Understand TeaQL queries through a familiar order model.",zh:"用一个熟悉的订单模型,看懂 TeaQL 查询。"},heroIntro:{en:"Platform, customer, order, item, payment, and shipment data all run in the browser. Order status is backed by a constant model. Choose a query below to inspect real SQLite/WASM results.",zh:"平台、用户、订单、明细、支付和物流数据都在浏览器中运行;订单状态由常数模型提供。选择下面的查询,查看真实的 SQLite/WASM 结果。"},runtimeCoverage:{en:"RUNTIME COVERAGE",zh:"RUNTIME 覆盖"},runtimeTitle:{en:"This demo runs TypeScript in your browser.",zh:"这个演示在浏览器中运行 TypeScript。"},runtimeIntro:{en:"The same model-driven Q and TraceChain contract is supported by seven TeaQL runtimes. Select a language to inspect its runtime source.",zh:"同一套模型驱动的 Q 与 TraceChain 契约支持七种 TeaQL runtime。选择一种语言,可以查看对应的 runtime 源码。"},currentBrowserRuntime:{en:"Current browser runtime",zh:"当前浏览器 runtime"},supportedRuntime:{en:"Supported runtime",zh:"已支持 runtime"},observabilityTitle:{en:"TraceChain in OpenObserve",zh:"OpenObserve 中的 TraceChain"},observabilityIntro:{en:"A captured Order query rendered as business lineage: page purpose, nested request comments, and the actual SQL executions remain connected.",zh:"一条真实采集的订单查询被呈现为业务谱系:页面目的、嵌套 request 的 comment 与实际执行的 SQL 始终保持连接。"},observabilityCaption:{en:"OpenObserve dashboard showing one verified trace and its eight actual SQL executions.",zh:"OpenObserve 仪表盘展示一条已验证的 trace,以及它实际执行的八条 SQL。"},platform:{en:"Platform",zh:"平台"},customer:{en:"Customer",zh:"用户"},order:{en:"Order",zh:"订单"},item:{en:"Item",zh:"明细"},payment:{en:"Payment",zh:"支付"},shipment:{en:"Shipment",zh:"物流"},constantModel:{en:"Constant model",zh:"常数模型"},persist:{en:"Persist locally with OPFS",zh:"使用 OPFS 保存在本地"},reset:{en:"Reset demo data",zh:"重置演示数据"},chooseQuery:{en:"Choose a query",zh:"选择一个查询"},queryIntro:{en:"Queries are grouped by purpose and share the same order dataset.",zh:"查询按用途分组,并共用同一份订单数据。"},table:{en:"Table",zh:"表格"},resultTree:{en:"Result Tree",zh:"结果树"},expandAll:{en:"Expand all",zh:"全部展开"},collapseAll:{en:"Collapse all",zh:"全部折叠"},waiting:{en:"Waiting for query…",zh:"等待查询…"},queryNote:{en:"The Q expression stays fixed; search, status cards, and pagination only update dynamic parameters. The underlying SelectQuery remains inside the generated request implementation.",zh:"Q 表达式保持不变;搜索、状态卡片和分页只更新动态参数。底层 SelectQuery 仍封装在生成的请求实现中。"},executionEvidence:{en:"EXECUTION EVIDENCE",zh:"执行证据"},evidenceTime:{en:"Time",zh:"时间"},identity:{en:"Identity",zh:"身份"},traceChain:{en:"Trace chain",zh:"追踪链"},sqlNote:{en:"One plain-text line per statement: time, identity, trace chain, and the SQL SQLite executed.",zh:"每条语句使用一行纯文本:��间、身份、追踪链,以及 SQLite 实际执行的 SQL。"},localData:{en:"Data stays in this browser",zh:"数据只保留在当前浏览器中"}},nt={基本查询:"Basic queries","从订单、用户和关联对象开始":"Start with orders, customers, and related objects",汇总查询:"Aggregations","分组、计数、求和与平均值":"Grouping, counts, sums, and averages",过滤查询:"Filtered queries","精确、范围与组合条件":"Exact, range, and combined predicates",动态查询:"Dynamic queries","由页面条件安全生成,不使用 eval":"Safely generated from page criteria without eval","综合:订单管理中心":"Comprehensive: Order management center","一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。":"A real composite query page: status metrics, search, product previews, and pagination are all driven by TeaQL.",最近订单:"Recent orders","按下单日期倒序浏览全部订单,并带出所属平台与用户。":"Browse all orders by date descending, including their platform and customer.",完整订单详情:"Complete order details","查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。":"Inspect one order with its customer, items, payments, and shipments as a complete object graph.",用户与订单数:"Customers with order counts","列出用户,并通过关联汇总显示每位用户的订单数量。":"List customers and show each customer’s order count through a relation aggregate.",订单状态汇总:"Orders by status","按币种与订单状态统计订单数、总额和平均客单价。":"Aggregate order count, gross amount, and average order value by currency and status.",商品销售汇总:"Product sales summary","按商品汇总销量与销售额,找出最受欢迎的订单明细。":"Aggregate units and revenue by product to identify the most popular order items.",支付渠道对账:"Payment reconciliation","按币种、支付渠道和状态汇总笔数与金额。":"Aggregate transaction count and amount by currency, payment provider, and status.",待支付订单:"Orders awaiting payment","筛选尚未完成付款的订单,并带出对应支付记录。":"Find orders that have not completed payment and include their payment records.",国内大额订单:"High-value domestic orders","组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。":"Combine platform and amount filters to find TeaQL Store orders worth at least CNY 500.",运输中的包裹:"Active shipments","筛选待揽收和运输中的物流单,并关联订单信息。":"Find shipments that are ready or in transit and include their order information.","动态:已付款国内订单":"Dynamic: paid domestic orders","从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。":"Build a query from dynamic criteria: CNY, at least 250, and status PAID or SHIPPED.","动态:九月新订单":"Dynamic: new September orders","运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。":"Pass a date range and sort order at runtime to find orders after September 15.","动态:字段白名单":"Dynamic: field allowlist","未知字段会被报告并忽略;合法条件仍可安全执行。":"Unknown fields are reported and ignored while valid predicates still execute safely."};let d=localStorage.getItem("teaql-browser-locale")==="zh"?"zh":"en";function st(t){return rt[t]?.[d]??t}function O(t){return d==="en"?nt[t]??t:t}let E,W=window.location.hash.slice(1)||"order-center";window.location.hash||history.replaceState(null,"","#order-center");let b="tree",D,fe=0,ee;const A={search:"",page:0,pageSize:4},Ae=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";B.checked=Ae==="opfs";async function G(t,e){const r=u.customerOrders().filterByJson(e).limit(20).comment("what: execute a validated browser search").purpose("why: demonstrate safe dynamic order discovery"),n=await r.executeForList(t.context);return{request:e,warnings:r.warnings(),data:n}}const ot=Object.fromEntries(Object.entries(f).map(([t,e])=>[e,t]));function te(t){const e=String(t.code??"");return e&&e in f?e:"color"in t?ot[String(t.id??"")]??"":""}function Se(t){const e=t.trim();if(!e)return{filter:{}};const r=e.toUpperCase(),n=["PENDING_PAYMENT","PAID","SHIPPED","DELIVERED","CANCELLED"].find(s=>s.includes(r));return n?{filter:{"status.code":n}}:/^(TQL-|\d)/i.test(e)?{filter:{orderNumber:{$contains:r}}}:{filter:{"itemList.productName":{$contains:e}}}}async function at(t){const e=Se(A.search),r=u.customerOrdersWithMinimalFields().filterByJson(e).countAs("totalOrders").facetByStatusAs("statusCounts",u.orderStatuses().selectName().selectColor().countAs("orderCount").sumOrderTotalAmountAs("orderTotalAmount").orderByDisplayOrderAscending().comment("load status facets")).selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor().comment("load status")).selectItemListWith(u.orderItems().selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews")).countItemListAs("itemCount").orderByOrderDateDescending().orderByIdDescending().comment("load order list").purpose("render order list page"),n=r.toQExpression(`offset(pageOffset)
4
  .limit(pageSize)
5
  .executeForList(ctx);`),s=await r.offset(A.page*A.pageSize).limit(A.pageSize).executeForList(t.context),o=s.facet("statusCounts")??[];return{orders:s,totalOrders:Number(s.aggregations.totalOrders??s.totalCount),filteredOrders:s.totalCount??0,statusFacets:o.map(a=>({code:te(a),name:String(a.name??""),color:String(a.color??""),orderCount:Number(a.orderCount??0),orderTotalAmount:Number(a.orderTotalAmount??0)})).filter(a=>a.code&&a.name),search:A.search,page:A.page,pageSize:A.pageSize,queryExpression:n}}const Ce=[{label:"基本查询",description:"从订单、用户和关联对象开始",queries:[{id:"order-center",title:"综合:订单管理中心",description:"一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。",code:"",view:"dashboard",run:at},{id:"recent-orders",title:"最近订单",description:"按下单日期倒序浏览全部订单,并带出所属平台与用户。",code:`await Q.customerOrders()
6
  .selectPlatformWith(Q.platforms().selectName())
@@ -101,4 +101,4 @@ const data = await request
101
  .comment('what: execute a validated browser search')
102
  .purpose('why: demonstrate safe dynamic order discovery')
103
  .executeForList(ctx);
104
- const warnings = request.warnings();`,run:t=>G(t,{filter:{status:"DELIVERED",internalNote:{$contains:"not queryable"}}})}]}],le=Ce.flatMap(t=>t.queries);async function it(t){const e=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),r=await Qe.open(e,{...ie},{storage:t,databaseName:"teaql-order-playground-v3.sqlite3"}),n=new Re().enableSelect();r.install(new $e(ie,{},{constants:Me})),r.setRuntimeTelemetrySink(n).setDiagnosticSQLLogSink(void 0);const s=Object.freeze({policyId:"browser-order-demo-seed",version:"1",fingerprint:"sha256:browser-order-demo-seed-v1"}),o=new Be().insertResource("dataService",r).withMutationPolicyRegistry(new Fe(()=>({identity:s,review:(a,i)=>i.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new ke(a=>({policy:a,approvedBy:"browser-demo-owner",approvedAt:new Date})));return r.setUserContext(o),await o.ensureSchema(),{client:r,context:o,evidence:n}}async function Ie(t){if((await u.customerOrders().selectId().limit(1).comment("what: detect existing order playground data").purpose("why: keep deterministic browser bootstrap idempotent").executeForList(t.context)).length)return;const r=new We("Seed deterministic order playground data");await t.client.executeGraphSave(r,async n=>{const s=pe.map(o=>n.request({entity:o.entity,action:"Create",id:o.id,payload:o.payload}));for(const o of s)t.client.preflightMutation(o);for(const o of s)await t.client.executeMutation(o)})}function dt(){F.replaceChildren();for(const t of Ce){const e=document.createElement("section");e.className="query-group";const r=document.createElement("div");r.className="query-group-heading";const n=document.createElement("h2");n.textContent=O(t.label);const s=document.createElement("p");s.textContent=O(t.description),r.append(n,s);const o=document.createElement("div");o.className="query-links";for(const a of t.queries){const i=document.createElement("a");i.href=`#${a.id}`,i.dataset.queryId=a.id,i.textContent=O(a.title),i.addEventListener("click",c=>{c.preventDefault(),W=a.id,history.replaceState(null,"",`#${a.id}`),H(),E&&v(a,E).catch(L)}),o.append(i)}e.append(r,o),F.append(e)}H()}function H(){F.querySelectorAll("a[data-query-id]").forEach(t=>{const e=t.dataset.queryId===W;t.classList.toggle("active",e),e?t.setAttribute("aria-current","page"):t.removeAttribute("aria-current")})}async function v(t,e){const r=performance.now(),n=new Date;e.evidence.enableSelect(),w.classList.add("loading"),w.setAttribute("aria-busy","true"),ye.textContent=O(t.title),he.textContent=O(t.description),ce.textContent=t.code,Ze.classList.toggle("hidden",t.view!=="dashboard"),Je.textContent=t.view==="dashboard"?JSON.stringify({searchParams:Se(A.search),pageOffset:A.page*A.pageSize,pageSize:A.pageSize},null,2):"",Xe.classList.toggle("dashboard-mode",t.view==="dashboard"),w.classList.toggle("dashboard-result",t.view==="dashboard"),X.closest(".tree-actions")?.classList.toggle("hidden",t.view==="dashboard"),R.textContent=t.view==="dashboard"?d==="en"?"Order management center":"订单管理中心":d==="en"?"Result tree":"结果树",J.textContent=d==="en"?"Running query…":"查询中…";try{const s=await t.run(e);t.view==="dashboard"&&(ce.textContent=s.queryExpression),D={data:s,query:t,active:e},b=t.view==="dashboard"||Z(s)?"table":"tree",z();const o=Math.max(1,Math.round(performance.now()-r));fe=o,ee=n;const a=e.evidence.snapshot();be(a,n),Ne(s,t,o)}finally{w.classList.remove("loading"),w.removeAttribute("aria-busy")}}function be(t,e=ee){ue.replaceChildren(),et.textContent=d==="en"?`${t.length} statement${t.length===1?"":"s"}`:`${t.length} 条语句`,t.forEach((r,n)=>{const s=document.createElement("tr");s.className="evidence-row";const o=[...r.tracePath].reverse().find(m=>m.kind==="relation"||m.kind==="request"||m.kind==="entity"),a=document.createElement("td");a.className="evidence-time",a.dataset.executedAt=e?.toISOString()??"",a.textContent=`${e?.toISOString()??"—"} · ${Math.max(.01,r.elapsedMicros/1e3).toFixed(2)} ms`;const i=document.createElement("td");i.textContent=`${D?.query.id??"query"} · #${n+1} · ${o?.name??"query"}`;const c=document.createElement("td");if(c.className="evidence-trace",r.traceChain?.length){const m=r.traceChain.find(g=>g.kind==="purpose"),S=r.traceChain.filter(g=>g.kind==="comment").map(g=>g.detail||g.name);c.textContent=`${m?.detail||m?.name||""}: ${S.join(" → ")}`}else c.textContent=r.tracePath.map(m=>m.detail||m.name).join(" → ");const l=document.createElement("td");l.className="evidence-sql";const h=r.parameters.length?r.parameters.map(m=>String(m)).join(", "):"none";l.textContent=`${r.parameterizedSQL} · bindings: ${h}`,s.append(a,i,c,l),ue.append(s)})}function Z(t){return Array.isArray(t)&&t.every(e=>e!==null&&typeof e=="object"&&!Array.isArray(e))}function z(){if(!D)return;const{data:t,query:e,active:r}=D,n=e.view==="dashboard"||Z(t);if(n||(b="tree"),Q.disabled=!n,Q.classList.toggle("active",b==="table"),V.classList.toggle("active",b==="tree"),Q.setAttribute("aria-pressed",String(b==="table")),V.setAttribute("aria-pressed",String(b==="tree")),X.closest(".tree-actions")?.classList.toggle("hidden",b!=="tree"),b==="table"&&e.view==="dashboard"){R.textContent=d==="en"?"Result table":"结果表格",mt(t,r,e);return}if(b==="table"&&Z(t)){R.textContent=d==="en"?"Result table":"结果表格",ut(t);return}R.textContent=d==="en"?"Result tree":"结果树",Ee(e.view==="dashboard"?ct(t):t)}function ct(t){return{orders:t.orders,totalOrders:t.totalOrders,filteredOrders:t.filteredOrders,statusFacets:t.statusFacets,search:t.search,page:t.page,pageSize:t.pageSize}}function ut(t){const e=document.createElement("div");if(e.className="result-table-shell",!t.length){const i=document.createElement("p");i.className="result-table-empty",i.textContent=d==="en"?"The query returned no records.":"查询没有返回记录。",e.append(i),w.replaceChildren(e);return}const r=[...new Set(t.flatMap(i=>Object.keys(i)))],n=document.createElement("table");n.className="result-table";const s=document.createElement("thead"),o=document.createElement("tr");for(const i of r){const c=document.createElement("th");c.scope="col",c.textContent=i,o.append(c)}s.append(o);const a=document.createElement("tbody");for(const i of t){const c=document.createElement("tr");for(const l of r){const h=document.createElement("td");h.textContent=lt(i[l]),c.append(h)}a.append(c)}n.append(s,a),e.append(n),w.replaceChildren(e)}function lt(t){if(t==null)return"—";if(Array.isArray(t))return d==="en"?`${t.length} items`:`${t.length} 项`;if(t instanceof Date)return t.toISOString();if(typeof t=="object"){const e=t,r=te(e);if(r)return we(r);const n=e.name??e.orderNumber??e.code??e.id;return n===void 0?d==="en"?`${Object.keys(e).length} fields`:`${Object.keys(e).length} 个字段`:String(n)}return String(t)}function mt(t,e,r){const n=document.createElement("div");n.className="order-center";const s=document.createElement("div");s.className="order-center-toolbar";const o=document.createElement("div"),a=document.createElement("h3");a.textContent=d==="en"?"Order Management Center":"订单管理中心";const i=document.createElement("p");i.textContent=d==="en"?"One generated Q expression describes the entire page":"一个生成式 Q 表达式描述整个页面",o.append(a,i);const c=document.createElement("form");c.className="order-search";const l=document.createElement("input");l.type="search",l.placeholder=d==="en"?"Order number, status, or product…":"订单号、状态或商品名称…",l.value=t.search,l.setAttribute("aria-label",d==="en"?"Search orders":"搜索订单");const h=document.createElement("button");h.type="submit",h.className="order-search-submit",h.setAttribute("aria-label",d==="en"?"Run order query":"执行订单查询"),h.title=d==="en"?"Search":"查询";const m=document.createElement("span");m.className="search-icon",m.setAttribute("aria-hidden","true"),h.append(m),c.append(l,h),c.addEventListener("submit",p=>{p.preventDefault(),A.search=l.value.trim(),A.page=0,v(r,e).catch(L)}),s.append(o,c);const S=document.createElement("div");S.className="order-metrics",S.append(me(d==="en"?"All orders":"全部订单",t.totalOrders,"total","#2B66D9",!t.search,()=>{A.search="",A.page=0,v(r,e).catch(L)}));for(const p of t.statusFacets)S.append(me(p.name,p.orderCount,p.code.toLowerCase(),p.color,t.search.toUpperCase()===p.code,()=>{A.search=p.code,A.page=0,v(r,e).catch(L)},`${d==="en"?"Total":"总额"} ${pt(p.orderTotalAmount)}`));const g=document.createElement("div");g.className="order-table";const M=document.createElement("div");M.className="order-row order-row-head";const De=d==="en"?["Order number","Order date","Status","Product details"]:["订单号","订单日期","状态","商品明细"];for(const p of De){const q=document.createElement("span");q.textContent=p,M.append(q)}if(g.append(M),!t.orders.length){const p=document.createElement("div");p.className="order-empty",p.textContent=d==="en"?"No matching orders. Try an order number, status code, or product name.":"没有匹配的订单,请尝试订单号、状态英文或商品名称。",g.append(p)}for(const p of t.orders)g.append(yt(p));const _=document.createElement("div");_.className="order-center-footer";const ne=document.createElement("p"),se=t.filteredOrders?t.page*t.pageSize+1:0,oe=Math.min(t.filteredOrders,(t.page+1)*t.pageSize);ne.textContent=d==="en"?`Showing ${se}–${oe} of ${t.filteredOrders} orders`:`显示 ${se}–${oe},共 ${t.filteredOrders} 条订单`;const P=document.createElement("div");P.className="pagination";const ae=Math.max(1,Math.ceil(t.filteredOrders/t.pageSize));P.append(j("‹",t.page-1,t.page===0,e,r));for(let p=0;p<ae;p+=1){const q=j(String(p+1),p,!1,e,r);q.classList.toggle("active",p===t.page),P.append(q)}P.append(j("›",t.page+1,t.page>=ae-1,e,r)),_.append(ne,P),n.append(s,S,g,_),w.replaceChildren(n)}function me(t,e,r,n,s,o,a){const i=document.createElement("button");i.type="button",i.className=`metric-card metric-${r}`,n&&i.style.setProperty("--metric-color",n),i.classList.toggle("active",s);const c=document.createElement("span");c.textContent=t;const l=document.createElement("strong");if(l.textContent=String(e),i.append(c,l),a){const h=document.createElement("small");h.textContent=a,i.append(h)}return i.addEventListener("click",o),i}function pt(t){return new Intl.NumberFormat(d==="en"?"en-US":"zh-CN",{minimumFractionDigits:2,maximumFractionDigits:2}).format(t)}function yt(t){const e=document.createElement("div");e.className="order-row";const r=t.status??{},n=Array.isArray(t.itemList)?t.itemList:[];[String(t.orderNumber??""),String(t.orderDate??"")].forEach(m=>{const S=document.createElement("span");S.className="order-primary",S.textContent=m,e.append(S)});const o=document.createElement("span"),a=document.createElement("span"),i=te(r);a.className=`status-badge status-${i.toLowerCase()}`,a.textContent=we(i)||String(r.name??i);const c=String(r.color??"");c&&(a.style.color=c,a.style.backgroundColor=`${c}18`),o.append(a),e.append(o);const l=document.createElement("span");l.className="product-preview",n.forEach((m,S)=>{const g=document.createElement("span");g.className=`product-thumb product-tone-${S%3}`,g.textContent=String(m.productName??"?").slice(0,1),g.title=`${String(m.productName??"")} × ${String(m.quantity??1)}`,l.append(g)});const h=Number(t.itemCount??n.length)-n.length;if(h>0){const m=document.createElement("small");m.textContent=`+${h}`,l.append(m)}return e.append(l),e}function j(t,e,r,n,s){const o=document.createElement("button");return o.type="button",o.textContent=t,o.disabled=r,o.addEventListener("click",()=>{A.page=e,v(s,n).catch(L)}),o}function we(t){return(d==="en"?{PENDING_PAYMENT:"Pending payment",PAID:"Paid",SHIPPED:"Shipped",DELIVERED:"Delivered",CANCELLED:"Cancelled"}:{PENDING_PAYMENT:"待支付",PAID:"已支付",SHIPPED:"运输中",DELIVERED:"已完成",CANCELLED:"已取消"})[t]??t}function Ee(t){w.replaceChildren(Le(t,"result",0))}function Le(t,e,r){if(t!==null&&typeof t=="object"){const a=Array.isArray(t)?t.map((S,g)=>[String(g),S]):Object.entries(t),i=document.createElement("details");i.className="tree-branch",i.open=r===0;const c=document.createElement("summary"),l=document.createElement("span");l.className="tree-key",l.textContent=e;const h=document.createElement("span");h.className="tree-preview",h.textContent=ht(t,a.length),c.append(l,h),i.append(c);const m=document.createElement("div");m.className="tree-children";for(const[S,g]of a)m.append(Le(g,Array.isArray(t)?`#${Number(S)+1}`:S,r+1));return i.append(m),i}const n=document.createElement("div");n.className="tree-leaf";const s=document.createElement("span");s.className="tree-key",s.textContent=e;const o=document.createElement("span");return o.className=`tree-value tree-${t===null?"null":typeof t}`,o.textContent=t===null?"null":typeof t=="string"?`“${t}”`:String(t),n.append(s,o),n}function ht(t,e){if(Array.isArray(t))return d==="en"?`${e} items`:`${e} 项`;const r=t,n=r.orderNumber??r.name??r.productName??r.transactionId??r.trackingNumber;return n?String(n):d==="en"?`${e} fields`:`${e} 个字段`}function gt(t){return Array.isArray(t)?t.length:Array.isArray(t?.data)?t.data.length:1}function Ne(t,e,r){const n=e.view==="dashboard"?t.filteredOrders:gt(t),s=d==="en"?`${n} ${e.view==="dashboard"?`matching order${n===1?"":"s"}`:`result${n===1?"":"s"}`}`:`${n} 条${e.view==="dashboard"?"匹配订单":"结果"}`;J.textContent=`${s} · ${r} ms · ${d==="en"?"in-browser SQLite":"浏览器内 SQLite"}`}function Oe(t){const e=pe.filter(r=>r.entity==="CustomerOrder").length;k.textContent=d==="en"?`${t.toUpperCase()} · ${e} orders · 7 entities · policy installed · ready`:`${t.toUpperCase()} · ${e} 个订单 · 7 个实体 · 已安装策略 · 就绪`}function ve(){document.documentElement.lang=d==="en"?"en":"zh-CN",document.title=d==="en"?"TeaQL Order Query Playground":"TeaQL 订单查询演练场";const t=document.querySelector('meta[name="description"]');if(t&&(t.content=d==="en"?"A TeaQL order-query playground running entirely in the browser":"完全运行在浏览器中的 TeaQL 订单查询演练场"),document.querySelectorAll("[data-i18n]").forEach(e=>{const r=e.dataset.i18n;r&&(e.textContent=st(r))}),ge.forEach(e=>{const r=e.dataset.locale===d;e.classList.toggle("active",r),e.setAttribute("aria-pressed",String(r))}),document.querySelector(".language-switch")?.setAttribute("aria-label",d==="en"?"Language":"语言"),document.querySelector(".brand")?.setAttribute("aria-label",d==="en"?"TeaQL Playground home":"TeaQL 演练场首页"),document.querySelector(".model-map")?.setAttribute("aria-label",d==="en"?"Order domain model":"订单领域模型"),document.querySelector(".runtime-language-selector")?.setAttribute("aria-label",d==="en"?"TeaQL runtimes":"TeaQL 运行时"),document.querySelector(".runtime-bar")?.setAttribute("aria-label",d==="en"?"Runtime settings":"运行时设置"),F.setAttribute("aria-label",d==="en"?"Example queries":"示例查询"),document.querySelector(".result-view-switch")?.setAttribute("aria-label",d==="en"?"Result views":"结果视图"),document.querySelector(".tree-actions")?.setAttribute("aria-label",d==="en"?"Result tree actions":"结果树操作"),dt(),D){const{data:e,query:r,active:n}=D;ye.textContent=O(r.title),he.textContent=O(r.description),z(),be(n.evidence.snapshot(),ee),Ne(e,r,fe),Oe(B.checked?"opfs":"memory")}else k.textContent=d==="en"?"Starting SQLite/WASM…":"正在启动 SQLite/WASM…"}function re(){return le.find(t=>t.id===W)??le[0]}async function Te(t){k.textContent=d==="en"?`Opening ${t.toUpperCase()} SQLite/WASM…`:`正在打开 ${t.toUpperCase()} SQLite/WASM…`;const e=E;E=void 0,await e?.client.close();const r=await it(t);E=r,await Ie(r),await v(re(),r),Oe(t)}B.addEventListener("change",()=>{const t=B.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",t),Te(t).catch(L)});Y.addEventListener("click",async()=>{if(E){Y.disabled=!0;try{await E.client.reset(E.context),await Ie(E),await v(re(),E)}catch(t){L(t)}finally{Y.disabled=!1}}});X.addEventListener("click",()=>{w.querySelectorAll("details").forEach(t=>{t.open=!0})});Q.addEventListener("click",()=>{Q.disabled||(b="table",z())});V.addEventListener("click",()=>{b="tree",z()});tt.addEventListener("click",()=>{w.querySelectorAll("details").forEach((t,e)=>{t.open=e===0})});ge.forEach(t=>{t.addEventListener("click",()=>{d=t.dataset.locale==="zh"?"zh":"en",localStorage.setItem("teaql-browser-locale",d),ve()})});function L(t){const e=t instanceof Error?t:new Error(String(t));k.textContent=`${e.name}: ${e.message}`,J.textContent=d==="en"?"Query failed":"查询失败",Ee({error:e.name,message:e.message})}ve();W=re().id;H();Te(Ae).catch(L);
 
1
+ import{S as x,m as Te,a as qe,e as xe,O as R,B as Qe,b as $e,R as Re,U as Be,D as ke,c as Fe,M as We}from"./dynamic-search-Ch_QcWVU.js";/* empty css */const C=t=>({columnName:t,modelName:t,logicalType:"integer",decode:"string"}),h=t=>({columnName:t,modelName:t,logicalType:"text",decode:"native"}),ze=t=>({columnName:t,modelName:t,logicalType:"date",decode:"date"}),K=t=>({columnName:t,modelName:t,logicalType:"datetime",decode:"date"}),I=(t,e="decimal")=>({columnName:t,modelName:t,logicalType:e,decode:"number"}),f=Object.freeze({PENDING_PAYMENT:"1001",PAID:"1002",SHIPPED:"1003",DELIVERED:"1004",CANCELLED:"1005"}),Me=[{entity:"OrderStatus",id:f.PENDING_PAYMENT,values:{name:"Pending payment",code:"PENDING_PAYMENT",color:"#D97706",displayOrder:10}},{entity:"OrderStatus",id:f.PAID,values:{name:"Paid",code:"PAID",color:"#2563EB",displayOrder:20}},{entity:"OrderStatus",id:f.SHIPPED,values:{name:"Shipped",code:"SHIPPED",color:"#16A34A",displayOrder:30}},{entity:"OrderStatus",id:f.DELIVERED,values:{name:"Delivered",code:"DELIVERED",color:"#047857",displayOrder:40}},{entity:"OrderStatus",id:f.CANCELLED,values:{name:"Cancelled",code:"CANCELLED",color:"#9F1239",displayOrder:50}}],ie={Platform:{table:"platform_data",columns:{id:C("id"),name:h("name"),code:h("code"),region:h("region"),currency:h("currency"),version:I("version","integer")},relations:{customerList:{targetEntity:"Customer",localKey:"id",foreignKey:"platformId",many:!0},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"platformId",many:!0}}},Customer:{table:"customer_data",columns:{id:C("id"),name:h("name"),email:h("email"),city:h("city"),tier:h("tier"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"customerId",many:!0}}},CustomerOrder:{table:"customer_order_data",columns:{id:C("id"),orderNumber:h("order_number"),orderDate:ze("order_date"),status:C("status_id"),totalAmount:I("total_amount"),currency:h("currency"),customerId:C("customer_id"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},customer:{targetEntity:"Customer",localKey:"customerId",foreignKey:"id",many:!1},status:{targetEntity:"OrderStatus",localKey:"status",foreignKey:"id",many:!1},itemList:{targetEntity:"OrderItem",localKey:"id",foreignKey:"orderId",many:!0},paymentList:{targetEntity:"Payment",localKey:"id",foreignKey:"orderId",many:!0},shipmentList:{targetEntity:"Shipment",localKey:"id",foreignKey:"orderId",many:!0}}},OrderStatus:{table:"order_status_data",columns:{id:C("id"),name:h("name"),code:h("code"),color:h("color"),displayOrder:I("display_order","integer"),version:I("version","integer")},relations:{orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"status",many:!0}}},OrderItem:{table:"order_item_data",columns:{id:C("id"),orderId:C("order_id"),productName:h("product_name"),sku:h("sku"),quantity:I("quantity","integer"),unitPrice:I("unit_price"),lineAmount:I("line_amount"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Payment:{table:"payment_data",columns:{id:C("id"),orderId:C("order_id"),provider:h("provider"),status:h("status"),amount:I("amount"),currency:h("currency"),transactionId:h("transaction_id"),paidAt:K("paid_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Shipment:{table:"shipment_data",columns:{id:C("id"),orderId:C("order_id"),carrier:h("carrier"),status:h("status"),trackingNumber:h("tracking_number"),shipToCity:h("ship_to_city"),shippedAt:K("shipped_at"),deliveredAt:K("delivered_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}}},pe=[{entity:"Platform",id:"1",payload:{name:"TeaQL Store",code:"TEAQL-CN",region:"China",currency:"CNY"}},{entity:"Platform",id:"2",payload:{name:"TeaQL Global",code:"TEAQL-GLOBAL",region:"Global",currency:"USD"}},{entity:"Customer",id:"101",payload:{name:"Lin Xiao",email:"lin.xiao@example.com",city:"Shanghai",tier:"GOLD",platformId:"1"}},{entity:"Customer",id:"102",payload:{name:"Zhou Ran",email:"zhou.ran@example.com",city:"Hangzhou",tier:"SILVER",platformId:"1"}},{entity:"Customer",id:"103",payload:{name:"Maya Patel",email:"maya.patel@example.com",city:"Singapore",tier:"GOLD",platformId:"2"}},{entity:"Customer",id:"104",payload:{name:"Lucas Martin",email:"lucas.martin@example.com",city:"Paris",tier:"SILVER",platformId:"2"}},{entity:"Customer",id:"105",payload:{name:"Wang Ning",email:"wang.ning@example.com",city:"Chengdu",tier:"BRONZE",platformId:"1"}},{entity:"CustomerOrder",id:"1001",payload:{orderNumber:"TQL-2026-1001",orderDate:"2026-08-28",status:f.DELIVERED,totalAmount:499,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1002",payload:{orderNumber:"TQL-2026-1002",orderDate:"2026-09-02",status:f.SHIPPED,totalAmount:1299,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1003",payload:{orderNumber:"TQL-2026-1003",orderDate:"2026-09-06",status:f.PAID,totalAmount:328.8,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1004",payload:{orderNumber:"TQL-2026-1004",orderDate:"2026-09-11",status:f.PENDING_PAYMENT,totalAmount:79.9,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"CustomerOrder",id:"1005",payload:{orderNumber:"TQL-2026-1005",orderDate:"2026-09-14",status:f.DELIVERED,totalAmount:219,currency:"USD",customerId:"103",platformId:"2"}},{entity:"CustomerOrder",id:"1006",payload:{orderNumber:"TQL-2026-1006",orderDate:"2026-09-18",status:f.PAID,totalAmount:640,currency:"USD",customerId:"104",platformId:"2"}},{entity:"CustomerOrder",id:"1007",payload:{orderNumber:"TQL-2026-1007",orderDate:"2026-09-21",status:f.CANCELLED,totalAmount:159,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1008",payload:{orderNumber:"TQL-2026-1008",orderDate:"2026-09-25",status:f.SHIPPED,totalAmount:268,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"OrderItem",id:"2001",payload:{orderId:"1001",productName:"TeaQL Mechanical Keyboard",sku:"KB-TQL-87",quantity:1,unitPrice:299,lineAmount:299}},{entity:"OrderItem",id:"2002",payload:{orderId:"1001",productName:"Silent Wireless Mouse",sku:"MS-SILENT",quantity:2,unitPrice:100,lineAmount:200}},{entity:"OrderItem",id:"2003",payload:{orderId:"1002",productName:"27-inch Developer Monitor",sku:"MON-27-4K",quantity:1,unitPrice:1299,lineAmount:1299}},{entity:"OrderItem",id:"2004",payload:{orderId:"1003",productName:"White Porcelain Travel Tea Set",sku:"TEA-TRAVEL",quantity:1,unitPrice:168.8,lineAmount:168.8}},{entity:"OrderItem",id:"2005",payload:{orderId:"1003",productName:"Pre-Qingming Longjing Tea",sku:"TEA-LJ-100",quantity:2,unitPrice:80,lineAmount:160}},{entity:"OrderItem",id:"2006",payload:{orderId:"1004",productName:"Double-wall Glass Tumbler",sku:"CUP-GLASS",quantity:1,unitPrice:79.9,lineAmount:79.9}},{entity:"OrderItem",id:"2007",payload:{orderId:"1005",productName:"Travel Brew Kit",sku:"BREW-KIT",quantity:1,unitPrice:219,lineAmount:219}},{entity:"OrderItem",id:"2008",payload:{orderId:"1006",productName:"Desktop Studio Speaker",sku:"SPK-STUDIO",quantity:2,unitPrice:200,lineAmount:400}},{entity:"OrderItem",id:"2009",payload:{orderId:"1006",productName:"Speaker Stand",sku:"SPK-STAND",quantity:1,unitPrice:80,lineAmount:80}},{entity:"OrderItem",id:"2010",payload:{orderId:"1007",productName:"Desktop Reading Lamp",sku:"LAMP-DESK",quantity:1,unitPrice:159,lineAmount:159}},{entity:"OrderItem",id:"2011",payload:{orderId:"1008",productName:"TeaQL Portable Keyboard",sku:"KB-TQL-68",quantity:1,unitPrice:168,lineAmount:168}},{entity:"OrderItem",id:"2012",payload:{orderId:"1008",productName:"Keyboard Protective Case",sku:"KB-CASE-68",quantity:1,unitPrice:30,lineAmount:30}},{entity:"OrderItem",id:"2013",payload:{orderId:"1008",productName:"Foldable Travel Stand",sku:"KB-STAND-FOLD",quantity:1,unitPrice:25,lineAmount:25}},{entity:"OrderItem",id:"2014",payload:{orderId:"1008",productName:"Braided USB-C Cable",sku:"CABLE-USBC",quantity:1,unitPrice:20,lineAmount:20}},{entity:"OrderItem",id:"2015",payload:{orderId:"1008",productName:"Accent Keycap Set",sku:"KEYCAP-ACCENT",quantity:1,unitPrice:25,lineAmount:25}},{entity:"OrderItem",id:"2016",payload:{orderId:"1006",productName:"Balanced Audio Cable",sku:"AUDIO-XLR",quantity:1,unitPrice:40,lineAmount:40}},{entity:"OrderItem",id:"2017",payload:{orderId:"1006",productName:"Speaker Isolation Pads",sku:"SPK-PADS",quantity:1,unitPrice:60,lineAmount:60}},{entity:"OrderItem",id:"2018",payload:{orderId:"1006",productName:"USB DAC Adapter",sku:"AUDIO-DAC-USB",quantity:1,unitPrice:60,lineAmount:60}},{entity:"Payment",id:"3001",payload:{orderId:"1001",provider:"Alipay",status:"CAPTURED",amount:499,currency:"CNY",transactionId:"ALI-260828-01",paidAt:"2026-08-28T10:14:00Z"}},{entity:"Payment",id:"3002",payload:{orderId:"1002",provider:"WeChat Pay",status:"CAPTURED",amount:1299,currency:"CNY",transactionId:"WX-260902-08",paidAt:"2026-09-02T03:20:00Z"}},{entity:"Payment",id:"3003",payload:{orderId:"1003",provider:"Alipay",status:"CAPTURED",amount:328.8,currency:"CNY",transactionId:"ALI-260906-11",paidAt:"2026-09-06T11:42:00Z"}},{entity:"Payment",id:"3004",payload:{orderId:"1004",provider:"WeChat Pay",status:"PENDING",amount:79.9,currency:"CNY",transactionId:"WX-260911-02",paidAt:null}},{entity:"Payment",id:"3005",payload:{orderId:"1005",provider:"Stripe",status:"CAPTURED",amount:219,currency:"USD",transactionId:"PI-260914-05",paidAt:"2026-09-14T06:10:00Z"}},{entity:"Payment",id:"3006",payload:{orderId:"1006",provider:"Stripe",status:"CAPTURED",amount:640,currency:"USD",transactionId:"PI-260918-03",paidAt:"2026-09-18T15:08:00Z"}},{entity:"Payment",id:"3007",payload:{orderId:"1007",provider:"Alipay",status:"REFUNDED",amount:159,currency:"CNY",transactionId:"ALI-260921-07",paidAt:"2026-09-21T02:55:00Z"}},{entity:"Payment",id:"3008",payload:{orderId:"1008",provider:"WeChat Pay",status:"CAPTURED",amount:268,currency:"CNY",transactionId:"WX-260925-06",paidAt:"2026-09-25T08:31:00Z"}},{entity:"Shipment",id:"4001",payload:{orderId:"1001",carrier:"SF Express",status:"DELIVERED",trackingNumber:"SF2608281001",shipToCity:"Shanghai",shippedAt:"2026-08-29T02:00:00Z",deliveredAt:"2026-08-30T07:26:00Z"}},{entity:"Shipment",id:"4002",payload:{orderId:"1002",carrier:"JD Logistics",status:"IN_TRANSIT",trackingNumber:"JD2609021002",shipToCity:"Hangzhou",shippedAt:"2026-09-03T04:12:00Z",deliveredAt:null}},{entity:"Shipment",id:"4003",payload:{orderId:"1003",carrier:"SF Express",status:"READY",trackingNumber:"SF2609061003",shipToCity:"Shanghai",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4004",payload:{orderId:"1005",carrier:"DHL",status:"DELIVERED",trackingNumber:"DHL2609141005",shipToCity:"Singapore",shippedAt:"2026-09-15T01:10:00Z",deliveredAt:"2026-09-17T09:22:00Z"}},{entity:"Shipment",id:"4005",payload:{orderId:"1006",carrier:"DHL",status:"READY",trackingNumber:"DHL2609181006",shipToCity:"Paris",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4006",payload:{orderId:"1008",carrier:"SF Express",status:"IN_TRANSIT",trackingNumber:"SF2609251008",shipToCity:"Chengdu",shippedAt:"2026-09-26T03:18:00Z",deliveredAt:null}}],L=t=>`'${t.replaceAll("\\","\\\\").replaceAll("'","\\'").replaceAll(`
2
+ `,"\\n")}'`,U=t=>t.toQExpression().replace(/\s*\n\s*/g,""),_e={CustomerOrder:{fields:{id:"integer",orderNumber:"string",orderDate:"date",status:"integer",totalAmount:"decimal",currency:"string",customerId:"integer",platformId:"integer"},relations:{status:"OrderStatus",itemList:"OrderItem"}},OrderStatus:{fields:{id:"integer",name:"string",code:"string",color:"string",displayOrder:"integer"},relations:{}},OrderItem:{fields:{id:"integer",orderId:"integer",productName:"string",sku:"string"},relations:{}}};function Ke(t){if(!t||typeof t!="object"||Array.isArray(t))return t;const e=structuredClone(t),r=e.filter;if(!r||typeof r!="object"||Array.isArray(r)||!("status"in r))return e;const n=r,s=n.status,o=a=>{const d=f[String(a)];return d===void 0?a:Number(d)};return s&&typeof s=="object"&&!Array.isArray(s)&&"$in"in s?n.status={$in:Array.isArray(s.$in)?s.$in.map(o):s.$in}:n.status=o(s),e}class v{query;filters=[];qRoot;qSteps=[];auditComment="";queryPurpose="";pageTotalAlias;constructor(e,r){this.query=new x(e),this.qRoot=r}comment(e){return this.auditComment=e,this.query.comment(e),this.record(`comment(${L(e)})`),this}purpose(e){return this.queryPurpose=e,this.query.purpose(e),this.record(`purpose(${L(e)})`),this}limit(e){return this.query.limit(e),this.record(`limit(${e})`),this}offset(e){return this.query.offset(e),this.record(`offset(${e})`),this}toQExpression(e){const r=e?[...this.qSteps,e]:this.qSteps;return[this.qRoot,...r.map(n=>` .${n}`)].join(`
3
+ `)}toQuery(){const e=this.query.clone();return this.filters.length&&e.filter({$and:[...this.filters]}),e}async executeForList(e){return this.executeList(e,this.pageTotalAlias!==void 0)}async executeForRows(e){return this.executeList(e,!1)}async executeList(e,r){this.ensureIntent();const n=this.service(e),s=this.toQuery(),o=r?await n.executeCount(s,this.pageTotalAlias,{kind:"named-count",method:"countAs",alias:this.pageTotalAlias}):void 0,a=s.clone();r&&(a.aggregateItems=a.aggregateItems.filter(m=>!(String(m.function).toLowerCase()==="count"&&m.alias===this.pageTotalAlias)));const d=await n.executeQuery(e.prepareQuery(a)),c=new qe(d,{totalCount:o});return r&&this.pageTotalAlias!==void 0&&(c.aggregations[this.pageTotalAlias]=o),s.facets.length&&(c.facets=await xe(n,m=>e.prepareQuery(m),s,s.facets)),c}addFilter(e){return this.filters.push(e),this}select(...e){return this.query.select(e),this}order(e,r){return this.query.order(r==="asc"?R.asc(e):R.desc(e)),this}group(e){return this.query.groupBy(e),this}aggregate(e,r,n){return this.query.aggregate(e,r,n),this}record(e){return this.qSteps.push(e),this}includePageTotalAs(e){return this.pageTotalAlias=e,this}service(e){return e.requireResource("dataService")}ensureIntent(){if(!this.auditComment.trim()||!this.queryPurpose.trim())throw new Error("Generated Q requests require comment() and purpose() before execution")}}class Ue extends v{constructor(){super("Platform","Q.platforms()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCode(){return this.select("code")}withIdIs(e){return this.addFilter({id:{$eq:e}})}}class Ye extends v{constructor(){super("Customer","Q.customers()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCity(){return this.select("city")}selectTier(){return this.select("tier")}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}countOrderListAs(e){return this.query.relationAggregate("orderList",e,new x("CustomerOrder").aggregate("Count","id",e)),this}orderByNameAscending(){return this.order("name","asc")}}class Ge extends v{constructor(){super("OrderItem","Q.orderItems()")}selectId(){return this.select("id"),this.record("selectId()")}selectOrderId(){return this.select("orderId"),this.record("selectOrderId()")}selectProductName(){return this.select("productName"),this.record("selectProductName()")}selectSku(){return this.select("sku"),this.record("selectSku()")}selectQuantity(){return this.select("quantity"),this.record("selectQuantity()")}withProductNameContaining(e){return this.addFilter({productName:{$contains:e}})}orderByIdAscending(){return this.order("id","asc"),this.record("orderByIdAscending()")}groupByProductName(){return this.group("productName")}sumQuantityAs(e){return this.aggregate("Sum","quantity",e)}sumLineAmountAs(e){return this.aggregate("Sum","lineAmount",e)}countAs(e){return this.aggregate("Count","id",e)}}class je extends v{constructor(){super("OrderStatus","Q.orderStatuses()")}selectId(){return this.select("id"),this.record("selectId()")}selectName(){return this.select("name"),this.record("selectName()")}selectCode(){return this.select("code"),this.record("selectCode()")}selectColor(){return this.select("color"),this.record("selectColor()")}selectDisplayOrder(){return this.select("displayOrder"),this.record("selectDisplayOrder()")}withCodeIs(e){return this.addFilter({code:{$eq:e}})}countAs(e){return this.aggregate("Count","id",e),this.record(`countAs(${L(e)})`)}sumOrderTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e),this.record(`sumOrderTotalAmountAs(${L(e)})`)}orderByDisplayOrderAscending(){return this.order("displayOrder","asc"),this.record("orderByDisplayOrderAscending()")}}class Ve extends v{constructor(){super("Payment","Q.payments()")}groupByCurrency(){return this.group("currency")}groupByProvider(){return this.group("provider")}groupByStatus(){return this.group("status")}countAs(e){return this.aggregate("Count","id",e)}sumAmountAs(e){return this.aggregate("Sum","amount",e)}orderByCurrencyAscending(){return this.order("currency","asc")}orderByProviderAscending(){return this.order("provider","asc")}orderByIdAscending(){return this.order("id","asc")}}class He extends v{constructor(){super("Shipment","Q.shipments()")}withStatusIn(...e){return this.addFilter({status:{$in:e}})}selectOrderWith(e){return this.query.relationQuery("order",e.toQuery(),"orderId","id",!1),this}orderByStatusAscending(){return this.order("status","asc")}orderByIdAscending(){return this.order("id","asc")}}class de extends v{dynamicWarnings=[];countAlias;rowCountApplied=!1;constructor(e=!1){super("CustomerOrder",e?"Q.customerOrdersWithMinimalFields()":"Q.customerOrders()"),e?this.query.select(["id","version"]):this.query.select(["id","orderNumber","orderDate","status","totalAmount","currency","customerId","platformId","version"])}selectId(){return this.select("id")}selectOrderNumber(){return this.select("orderNumber"),this.record("selectOrderNumber()")}selectOrderDate(){return this.select("orderDate"),this.record("selectOrderDate()")}selectStatus(){return this.select("status")}selectTotalAmount(){return this.select("totalAmount")}selectCurrency(){return this.select("currency")}withOrderNumberIs(e){return this.addFilter({orderNumber:{$eq:e}})}withOrderNumberContaining(e){return this.addFilter({orderNumber:{$contains:e}})}withStatusMatching(e){return this.addFilter({status:{$inSubquery:{query:e.toQuery(),field:"id"}}})}withStatusIsPendingPayment(){return this.addFilter({status:{$eq:f.PENDING_PAYMENT}})}withStatusIsPaid(){return this.addFilter({status:{$eq:f.PAID}})}withStatusIsShipped(){return this.addFilter({status:{$eq:f.SHIPPED}})}withStatusIsDelivered(){return this.addFilter({status:{$eq:f.DELIVERED}})}withStatusIsCancelled(){return this.addFilter({status:{$eq:f.CANCELLED}})}withCurrencyIs(e){return this.addFilter({currency:{$eq:e}})}withTotalAmountGreaterThanOrEqualTo(e){return this.addFilter({totalAmount:{$gte:e}})}withOrderDateGreaterThanOrEqualTo(e){return this.addFilter({orderDate:{$gte:e}})}withPlatformIdIs(e){return this.addFilter({platformId:{$eq:e}})}withItemListMatching(e){return this.addFilter({id:{$inSubquery:{query:e.toQuery(),field:"orderId"}}})}filterByJson(e){const{query:r,warnings:n}=Te(this.toQuery(),Ke(e),_e,{filter:(s,o)=>s==="status.code"?{status:{$inSubquery:{query:new x("OrderStatus").filter({code:o}),field:"id"}}}:s==="itemList.productName"?{id:{$inSubquery:{query:new x("OrderItem").filter({productName:o}),field:"orderId"}}}:{[s]:o},order:(s,o)=>o==="asc"?R.asc(s):R.desc(s)});return this.dynamicWarnings=n,this.query.filterCondition=r.filterCondition,this.query.orderItems=[...r.orderItems],this.record("filterByJson(searchParams)"),this}warnings(){return this.dynamicWarnings}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}selectCustomerWith(e){return this.query.relationQuery("customer",e.toQuery(),"customerId","id",!1),this}selectStatusWith(e){return this.query.select(["status"]),this.query.relationQuery("status",e.toQuery(),"status","id",!1,{kind:"relation-select",method:"selectStatusWith",relation:"status"}),this.record(`selectStatusWith(${U(e)})`)}selectItemListWith(e){return this.query.relationQuery("itemList",e.toQuery(),"id","orderId",!0,{kind:"relation-select",method:"selectItemListWith",relation:"itemList"}),this.record(`selectItemListWith(${U(e)})`)}selectPaymentListWith(e){return this.query.relationQuery("paymentList",e.toQuery(),"id","orderId",!0),this}selectShipmentListWith(e){return this.query.relationQuery("shipmentList",e.toQuery(),"id","orderId",!0),this}countItemListAs(e){return this.query.relationAggregate("itemList",e,new x("OrderItem").aggregate("Count","id",e).comment("count items"),!0,{kind:"relation-count",method:"countItemListAs",relation:"itemList",alias:e}),this.record(`countItemListAs(${L(e)})`)}facetByStatusAs(e,r,n=!0){const s=r.toQuery();return s.commentText||s.comment("load status facets"),this.query.facetBy(e,"status",{toQuery:()=>s},n,{kind:"facet",method:"facetByStatusAs",relation:"status",alias:e}),this.record(`facetByStatusAs(${L(e)}, ${U(r)})`)}orderByOrderDateDescending(){return this.order("orderDate","desc"),this.record("orderByOrderDateDescending()")}orderByOrderDateAscending(){return this.order("orderDate","asc")}orderByIdDescending(){return this.order("id","desc"),this.record("orderByIdDescending()")}orderByTotalAmountDescending(){return this.order("totalAmount","desc")}groupByCurrency(){return this.group("currency")}groupByStatus(){return this.group("status")}countAs(e){return this.countAlias=e,this.record(`countAs(${L(e)})`)}sumTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e)}averageTotalAmountAs(e){return this.aggregate("Avg","totalAmount",e)}executeForList(e){return this.countAlias&&this.includePageTotalAs(this.countAlias),super.executeForList(e)}executeForRows(e){return this.applyRowCount(),super.executeForRows(e)}applyRowCount(){!this.countAlias||this.rowCountApplied||(this.query.aggregate("Count","id",this.countAlias),this.rowCountApplied=!0)}}class u{static platforms(){return new Ue}static customers(){return new Ye}static customerOrders(){return new de}static customerOrdersWithMinimalFields(){return new de(!0)}static orderItems(){return new Ge}static orderStatuses(){return new je}static payments(){return new Ve}static shipments(){return new He}}const F=document.querySelector("#status"),B=document.querySelector("#persist"),Y=document.querySelector("#reset"),k=document.querySelector("#query-catalog"),w=document.querySelector("#result"),ye=document.querySelector("#result-title"),he=document.querySelector("#result-description"),J=document.querySelector("#result-meta"),ce=document.querySelector("#query-code"),Ze=document.querySelector("#query-params-block"),Je=document.querySelector("#query-params-code"),Xe=document.querySelector("#result-grid"),$=document.querySelector("#result-view-label"),et=document.querySelector("#sql-count"),ue=document.querySelector("#sql-output"),X=document.querySelector("#expand-all"),tt=document.querySelector("#collapse-all"),Q=document.querySelector("#view-table"),V=document.querySelector("#view-tree"),ge=Array.from(document.querySelectorAll("[data-locale]")),rt={heroTitle:{en:"Understand TeaQL queries through a familiar order model.",zh:"用一个熟悉的订单模型,看懂 TeaQL 查询。"},heroIntro:{en:"Platform, customer, order, item, payment, and shipment data all run in the browser. Order status is backed by a constant model. Choose a query below to inspect real SQLite/WASM results.",zh:"平台、用户、订单、明细、支付和物流数据都在浏览器中运行;订单状态由常数模型提供。选择下面的查询,查看真实的 SQLite/WASM 结果。"},runtimeCoverage:{en:"RUNTIME COVERAGE",zh:"RUNTIME 覆盖"},runtimeTitle:{en:"This demo runs TypeScript in your browser.",zh:"这个演示在浏览器中运行 TypeScript。"},runtimeIntro:{en:"The same model-driven Q and TraceChain contract is supported by seven TeaQL runtimes. Select a language to inspect its runtime source.",zh:"同一套模型驱动的 Q 与 TraceChain 契约支持七种 TeaQL runtime。选择一种语言,可以查看对应的 runtime 源码。"},currentBrowserRuntime:{en:"Current browser runtime",zh:"当前浏览器 runtime"},supportedRuntime:{en:"Supported runtime",zh:"已支持 runtime"},observabilityTitle:{en:"TraceChain in OpenObserve",zh:"OpenObserve 中的 TraceChain"},observabilityIntro:{en:"A captured Order query rendered as business lineage: page purpose, nested request comments, and the actual SQL executions remain connected.",zh:"一条真实采集的订单查询被呈现为业务谱系:页面目的、嵌套 request 的 comment 与实际执行的 SQL 始终保持连接。"},observabilityCaption:{en:"OpenObserve dashboard showing one verified trace and its eight actual SQL executions.",zh:"OpenObserve 仪表盘展示一条已验证的 trace,以及它实际执行的八条 SQL。"},platform:{en:"Platform",zh:"平台"},customer:{en:"Customer",zh:"用户"},order:{en:"Order",zh:"订单"},item:{en:"Item",zh:"明细"},payment:{en:"Payment",zh:"支付"},shipment:{en:"Shipment",zh:"物流"},constantModel:{en:"Constant model",zh:"常数模型"},persist:{en:"Persist locally with OPFS",zh:"使用 OPFS 保存在本地"},reset:{en:"Reset demo data",zh:"重置演示数据"},chooseQuery:{en:"Choose a query",zh:"选择一个查询"},queryIntro:{en:"Queries are grouped by purpose and share the same order dataset.",zh:"查询按用途分组,并共用同一份订单数据。"},table:{en:"Table",zh:"表格"},resultTree:{en:"Result Tree",zh:"结果树"},expandAll:{en:"Expand all",zh:"全部展开"},collapseAll:{en:"Collapse all",zh:"全部折叠"},waiting:{en:"Waiting for query…",zh:"等待查询…"},queryNote:{en:"The Q expression stays fixed; search, status cards, and pagination only update dynamic parameters. The underlying SelectQuery remains inside the generated request implementation.",zh:"Q 表达式保持不变;搜索、状态卡片和分页只更新动态参数。底层 SelectQuery 仍封装在生成的请求实现中。"},executionEvidence:{en:"EXECUTION EVIDENCE",zh:"执行证据"},evidenceTime:{en:"Time",zh:"时间"},identity:{en:"Identity",zh:"身份"},traceChain:{en:"Trace chain",zh:"追踪链"},sqlNote:{en:"One plain-text line per statement: time, identity, trace chain, and the SQL SQLite executed.",zh:"每条语句使用一行纯文本:时间、身份、追踪链,以及 SQLite 实际执行的 SQL。"},localData:{en:"Data stays in this browser",zh:"数据只保留在当前浏览器中"}},nt={基本查询:"Basic queries","从订单、用户和关联对象开始":"Start with orders, customers, and related objects",汇总查询:"Aggregations","分组、计数、求和与平均值":"Grouping, counts, sums, and averages",过滤查询:"Filtered queries","精确、范围与组合条件":"Exact, range, and combined predicates",动态查询:"Dynamic queries","由页面条件安全生成,不使用 eval":"Safely generated from page criteria without eval","综合:订单管理中心":"Comprehensive: Order management center","一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。":"A real composite query page: status metrics, search, product previews, and pagination are all driven by TeaQL.",最近订单:"Recent orders","按下单日期倒序浏览全部订单,并带出所属平台与用户。":"Browse all orders by date descending, including their platform and customer.",完整订单详情:"Complete order details","查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。":"Inspect one order with its customer, items, payments, and shipments as a complete object graph.",用户与订单数:"Customers with order counts","列出用户,并通过关联汇总显示每位用户的订单数量。":"List customers and show each customer’s order count through a relation aggregate.",订单状态汇总:"Orders by status","按币种与订单状态统计订单数、总额和平均客单价。":"Aggregate order count, gross amount, and average order value by currency and status.",商品销售汇总:"Product sales summary","按商品汇总销量与销售额,找出最受欢迎的订单明细。":"Aggregate units and revenue by product to identify the most popular order items.",支付渠道对账:"Payment reconciliation","按币种、支付渠道和状态汇总笔数与金额。":"Aggregate transaction count and amount by currency, payment provider, and status.",待支付订单:"Orders awaiting payment","筛选尚未完成付款的订单,并带出对应支付记录。":"Find orders that have not completed payment and include their payment records.",国内大额订单:"High-value domestic orders","组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。":"Combine platform and amount filters to find TeaQL Store orders worth at least CNY 500.",运输中的包裹:"Active shipments","筛选待揽收和运输中的物流单,并关联订单信息。":"Find shipments that are ready or in transit and include their order information.","动态:已付款国内订单":"Dynamic: paid domestic orders","从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。":"Build a query from dynamic criteria: CNY, at least 250, and status PAID or SHIPPED.","动态:九月新订单":"Dynamic: new September orders","运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。":"Pass a date range and sort order at runtime to find orders after September 15.","动态:字段白名单":"Dynamic: field allowlist","未知字段会被报告并忽略;合法条件仍可安全执行。":"Unknown fields are reported and ignored while valid predicates still execute safely."};let i=localStorage.getItem("teaql-browser-locale")==="zh"?"zh":"en";function st(t){return rt[t]?.[i]??t}function O(t){return i==="en"?nt[t]??t:t}let E,W=window.location.hash.slice(1)||"order-center";window.location.hash||history.replaceState(null,"","#order-center");let b="tree",D,fe=0,ee;const A={search:"",page:0,pageSize:4},Ae=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";B.checked=Ae==="opfs";async function G(t,e){const r=u.customerOrders().filterByJson(e).limit(20).comment("what: execute a validated browser search").purpose("why: demonstrate safe dynamic order discovery"),n=await r.executeForList(t.context);return{request:e,warnings:r.warnings(),data:n}}const ot=Object.fromEntries(Object.entries(f).map(([t,e])=>[e,t]));function te(t){const e=String(t.code??"");return e&&e in f?e:"color"in t?ot[String(t.id??"")]??"":""}function Se(t){const e=t.trim();if(!e)return{filter:{}};const r=e.toUpperCase(),n=["PENDING_PAYMENT","PAID","SHIPPED","DELIVERED","CANCELLED"].find(s=>s.includes(r));return n?{filter:{"status.code":n}}:/^(TQL-|\d)/i.test(e)?{filter:{orderNumber:{$contains:r}}}:{filter:{"itemList.productName":{$contains:e}}}}async function at(t){const e=Se(A.search),r=u.customerOrdersWithMinimalFields().filterByJson(e).countAs("totalOrders").facetByStatusAs("statusCounts",u.orderStatuses().selectName().selectColor().countAs("orderCount").sumOrderTotalAmountAs("orderTotalAmount").orderByDisplayOrderAscending().comment("load status facets")).selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor().comment("load status")).selectItemListWith(u.orderItems().selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews")).countItemListAs("itemCount").orderByOrderDateDescending().orderByIdDescending().comment("load order list").purpose("render order list page"),n=r.toQExpression(`offset(pageOffset)
4
  .limit(pageSize)
5
  .executeForList(ctx);`),s=await r.offset(A.page*A.pageSize).limit(A.pageSize).executeForList(t.context),o=s.facet("statusCounts")??[];return{orders:s,totalOrders:Number(s.aggregations.totalOrders??s.totalCount),filteredOrders:s.totalCount??0,statusFacets:o.map(a=>({code:te(a),name:String(a.name??""),color:String(a.color??""),orderCount:Number(a.orderCount??0),orderTotalAmount:Number(a.orderTotalAmount??0)})).filter(a=>a.code&&a.name),search:A.search,page:A.page,pageSize:A.pageSize,queryExpression:n}}const Ce=[{label:"基本查询",description:"从订单、用户和关联对象开始",queries:[{id:"order-center",title:"综合:订单管理中心",description:"一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。",code:"",view:"dashboard",run:at},{id:"recent-orders",title:"最近订单",description:"按下单日期倒序浏览全部订单,并带出所属平台与用户。",code:`await Q.customerOrders()
6
  .selectPlatformWith(Q.platforms().selectName())
 
101
  .comment('what: execute a validated browser search')
102
  .purpose('why: demonstrate safe dynamic order discovery')
103
  .executeForList(ctx);
104
+ const warnings = request.warnings();`,run:t=>G(t,{filter:{status:"DELIVERED",internalNote:{$contains:"not queryable"}}})}]}],le=Ce.flatMap(t=>t.queries);async function it(t){const e=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),r=await Qe.open(e,{...ie},{storage:t,databaseName:"teaql-order-playground-v4.sqlite3"}),n=new $e().enableSelect();r.install(new Re(ie,{},{constants:Me})),r.setRuntimeTelemetrySink(n).setDiagnosticSQLLogSink(void 0);const s=Object.freeze({policyId:"browser-order-demo-seed",version:"1",fingerprint:"sha256:browser-order-demo-seed-v2"}),o=new Be().insertResource("dataService",r).withMutationPolicyRegistry(new ke(()=>({identity:s,review:(a,d)=>d.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new Fe(a=>({policy:a,approvedBy:"browser-demo-owner",approvedAt:new Date})));return r.setUserContext(o),await o.ensureSchema(),{client:r,context:o,evidence:n}}async function Ie(t){if((await u.customerOrders().selectId().limit(1).comment("what: detect existing order playground data").purpose("why: keep deterministic browser bootstrap idempotent").executeForList(t.context)).length)return;const r=new We("Seed deterministic order playground data");await t.client.executeGraphSave(r,async n=>{const s=pe.map(o=>n.request({entity:o.entity,action:"Create",id:o.id,payload:o.payload}));for(const o of s)t.client.preflightMutation(o);for(const o of s)await t.client.executeMutation(o)})}function dt(){k.replaceChildren();for(const t of Ce){const e=document.createElement("section");e.className="query-group";const r=document.createElement("div");r.className="query-group-heading";const n=document.createElement("h2");n.textContent=O(t.label);const s=document.createElement("p");s.textContent=O(t.description),r.append(n,s);const o=document.createElement("div");o.className="query-links";for(const a of t.queries){const d=document.createElement("a");d.href=`#${a.id}`,d.dataset.queryId=a.id,d.textContent=O(a.title),d.addEventListener("click",c=>{c.preventDefault(),W=a.id,history.replaceState(null,"",`#${a.id}`),H(),E&&P(a,E).catch(N)}),o.append(d)}e.append(r,o),k.append(e)}H()}function H(){k.querySelectorAll("a[data-query-id]").forEach(t=>{const e=t.dataset.queryId===W;t.classList.toggle("active",e),e?t.setAttribute("aria-current","page"):t.removeAttribute("aria-current")})}async function P(t,e){const r=performance.now(),n=new Date;e.evidence.enableSelect(),w.classList.add("loading"),w.setAttribute("aria-busy","true"),ye.textContent=O(t.title),he.textContent=O(t.description),ce.textContent=t.code,Ze.classList.toggle("hidden",t.view!=="dashboard"),Je.textContent=t.view==="dashboard"?JSON.stringify({searchParams:Se(A.search),pageOffset:A.page*A.pageSize,pageSize:A.pageSize},null,2):"",Xe.classList.toggle("dashboard-mode",t.view==="dashboard"),w.classList.toggle("dashboard-result",t.view==="dashboard"),X.closest(".tree-actions")?.classList.toggle("hidden",t.view==="dashboard"),$.textContent=t.view==="dashboard"?i==="en"?"Order management center":"订单管理中心":i==="en"?"Result tree":"结果树",J.textContent=i==="en"?"Running query…":"查询中…";try{const s=await t.run(e);t.view==="dashboard"&&(ce.textContent=s.queryExpression),D={data:s,query:t,active:e},b=t.view==="dashboard"||Z(s)?"table":"tree",z();const o=Math.max(1,Math.round(performance.now()-r));fe=o,ee=n;const a=e.evidence.snapshot();be(a,n),Le(s,t,o)}finally{w.classList.remove("loading"),w.removeAttribute("aria-busy")}}function be(t,e=ee){ue.replaceChildren(),et.textContent=i==="en"?`${t.length} statement${t.length===1?"":"s"}`:`${t.length} 条语句`,t.forEach((r,n)=>{const s=document.createElement("tr");s.className="evidence-row";const o=[...r.tracePath].reverse().find(l=>l.kind==="relation"||l.kind==="request"||l.kind==="entity"),a=document.createElement("td");a.className="evidence-time",a.dataset.executedAt=e?.toISOString()??"",a.textContent=`${e?.toISOString()??"—"} · ${Math.max(.01,r.elapsedMicros/1e3).toFixed(2)} ms`;const d=document.createElement("td");d.textContent=`${D?.query.id??"query"} · #${n+1} · ${o?.name??"query"}`;const c=document.createElement("td");if(c.className="evidence-trace",r.traceChain?.length){const l=r.traceChain.find(g=>g.kind==="purpose"),S=r.traceChain.filter(g=>g.kind==="comment").map(g=>g.detail||g.name);c.textContent=`${l?.detail||l?.name||""}: ${S.join(" → ")}`}else c.textContent=r.tracePath.map(l=>l.detail||l.name).join(" → ");const m=document.createElement("td");m.className="evidence-sql";const p=r.parameters.length?r.parameters.map(l=>String(l)).join(", "):"none";m.textContent=`${r.parameterizedSQL} · bindings: ${p}`,s.append(a,d,c,m),ue.append(s)})}function Z(t){return Array.isArray(t)&&t.every(e=>e!==null&&typeof e=="object"&&!Array.isArray(e))}function z(){if(!D)return;const{data:t,query:e,active:r}=D,n=e.view==="dashboard"||Z(t);if(n||(b="tree"),Q.disabled=!n,Q.classList.toggle("active",b==="table"),V.classList.toggle("active",b==="tree"),Q.setAttribute("aria-pressed",String(b==="table")),V.setAttribute("aria-pressed",String(b==="tree")),X.closest(".tree-actions")?.classList.toggle("hidden",b!=="tree"),b==="table"&&e.view==="dashboard"){$.textContent=i==="en"?"Result table":"结果表格",mt(t,r,e);return}if(b==="table"&&Z(t)){$.textContent=i==="en"?"Result table":"结果表格",ut(t);return}$.textContent=i==="en"?"Result tree":"结果树",Ee(e.view==="dashboard"?ct(t):t)}function ct(t){return{orders:t.orders,totalOrders:t.totalOrders,filteredOrders:t.filteredOrders,statusFacets:t.statusFacets,search:t.search,page:t.page,pageSize:t.pageSize}}function ut(t){const e=document.createElement("div");if(e.className="result-table-shell",!t.length){const d=document.createElement("p");d.className="result-table-empty",d.textContent=i==="en"?"The query returned no records.":"查询没有返回记录。",e.append(d),w.replaceChildren(e);return}const r=[...new Set(t.flatMap(d=>Object.keys(d)))],n=document.createElement("table");n.className="result-table";const s=document.createElement("thead"),o=document.createElement("tr");for(const d of r){const c=document.createElement("th");c.scope="col",c.textContent=d,o.append(c)}s.append(o);const a=document.createElement("tbody");for(const d of t){const c=document.createElement("tr");for(const m of r){const p=document.createElement("td");p.textContent=lt(d[m]),c.append(p)}a.append(c)}n.append(s,a),e.append(n),w.replaceChildren(e)}function lt(t){if(t==null)return"—";if(Array.isArray(t))return i==="en"?`${t.length} items`:`${t.length} 项`;if(t instanceof Date)return t.toISOString();if(typeof t=="object"){const e=t,r=te(e);if(r)return we(r);const n=e.name??e.orderNumber??e.code??e.id;return n===void 0?i==="en"?`${Object.keys(e).length} fields`:`${Object.keys(e).length} 个字段`:String(n)}return String(t)}function mt(t,e,r){const n=document.createElement("div");n.className="order-center";const s=document.createElement("div");s.className="order-center-toolbar";const o=document.createElement("div"),a=document.createElement("h3");a.textContent=i==="en"?"Order Management Center":"订单管理中心";const d=document.createElement("p");d.textContent=i==="en"?"One generated Q expression describes the entire page":"一个生成式 Q 表达式描述整个页面",o.append(a,d);const c=document.createElement("form");c.className="order-search";const m=document.createElement("input");m.type="search",m.placeholder=i==="en"?"Order number, status, or product…":"订单号、状态或商品名称…",m.value=t.search,m.setAttribute("aria-label",i==="en"?"Search orders":"搜索订单");const p=document.createElement("button");p.type="submit",p.className="order-search-submit",p.setAttribute("aria-label",i==="en"?"Run order query":"执行订单查询"),p.title=i==="en"?"Search":"查询";const l=document.createElement("span");l.className="search-icon",l.setAttribute("aria-hidden","true"),p.append(l),c.append(m,p),c.addEventListener("submit",y=>{y.preventDefault(),A.search=m.value.trim(),A.page=0,P(r,e).catch(N)}),s.append(o,c);const S=document.createElement("div");S.className="order-metrics",S.append(me(i==="en"?"All orders":"全部订单",t.totalOrders,"total","#2B66D9",!t.search,()=>{A.search="",A.page=0,P(r,e).catch(N)}));for(const y of t.statusFacets)S.append(me(y.name,y.orderCount,y.code.toLowerCase(),y.color,t.search.toUpperCase()===y.code,()=>{A.search=y.code,A.page=0,P(r,e).catch(N)},`${i==="en"?"Total":"总额"} ${pt(y.orderTotalAmount)}`));const g=document.createElement("div");g.className="order-table";const M=document.createElement("div");M.className="order-row order-row-head";const De=i==="en"?["Order number","Order date","Status","Line Items"]:["订单号","订单日期","状态","订单明细"];for(const y of De){const q=document.createElement("span");q.textContent=y,M.append(q)}if(g.append(M),!t.orders.length){const y=document.createElement("div");y.className="order-empty",y.textContent=i==="en"?"No matching orders. Try an order number, status code, or product name.":"没有匹配的订单,请尝试订单号、状态英文或商品名称。",g.append(y)}for(const y of t.orders)g.append(yt(y));const _=document.createElement("div");_.className="order-center-footer";const ne=document.createElement("p"),se=t.filteredOrders?t.page*t.pageSize+1:0,oe=Math.min(t.filteredOrders,(t.page+1)*t.pageSize);ne.textContent=i==="en"?`Showing ${se}–${oe} of ${t.filteredOrders} orders`:`显示 ${se}–${oe},共 ${t.filteredOrders} 条订单`;const T=document.createElement("div");T.className="pagination";const ae=Math.max(1,Math.ceil(t.filteredOrders/t.pageSize));T.append(j("‹",t.page-1,t.page===0,e,r));for(let y=0;y<ae;y+=1){const q=j(String(y+1),y,!1,e,r);q.classList.toggle("active",y===t.page),T.append(q)}T.append(j("›",t.page+1,t.page>=ae-1,e,r)),_.append(ne,T),n.append(s,S,g,_),w.replaceChildren(n)}function me(t,e,r,n,s,o,a){const d=document.createElement("button");d.type="button",d.className=`metric-card metric-${r}`,n&&d.style.setProperty("--metric-color",n),d.classList.toggle("active",s);const c=document.createElement("span");c.textContent=t;const m=document.createElement("strong");if(m.textContent=String(e),d.append(c,m),a){const p=document.createElement("small");p.textContent=a,d.append(p)}return d.addEventListener("click",o),d}function pt(t){return new Intl.NumberFormat(i==="en"?"en-US":"zh-CN",{minimumFractionDigits:2,maximumFractionDigits:2}).format(t)}function yt(t){const e=document.createElement("div");e.className="order-row";const r=t.status??{},n=Array.isArray(t.itemList)?t.itemList:[];[String(t.orderNumber??""),String(t.orderDate??"")].forEach(l=>{const S=document.createElement("span");S.className="order-primary",S.textContent=l,e.append(S)});const o=document.createElement("span"),a=document.createElement("span"),d=te(r);a.className=`status-badge status-${d.toLowerCase()}`,a.textContent=we(d)||String(r.name??d);const c=String(r.color??"");c&&(a.style.color=c,a.style.backgroundColor=`${c}18`),o.append(a),e.append(o);const m=document.createElement("span");m.className="product-preview",n.forEach((l,S)=>{const g=document.createElement("span");g.className=`product-thumb product-tone-${S%3}`,g.textContent=String(l.productName??"?").slice(0,1),g.title=`${String(l.productName??"")} × ${String(l.quantity??1)}`,m.append(g)});const p=Number(t.itemCount??n.length);if(p>n.length){const l=document.createElement("small");l.className="line-item-count",l.textContent=i==="en"?`${p} items`:`共 ${p} 项`,l.title=i==="en"?`Showing ${n.length} of ${p} line items`:`显示 ${n.length} 项,共 ${p} 项订单明细`,m.append(l)}return e.append(m),e}function j(t,e,r,n,s){const o=document.createElement("button");return o.type="button",o.textContent=t,o.disabled=r,o.addEventListener("click",()=>{A.page=e,P(s,n).catch(N)}),o}function we(t){return(i==="en"?{PENDING_PAYMENT:"Pending payment",PAID:"Paid",SHIPPED:"Shipped",DELIVERED:"Delivered",CANCELLED:"Cancelled"}:{PENDING_PAYMENT:"待支付",PAID:"已支付",SHIPPED:"运输中",DELIVERED:"已完成",CANCELLED:"已取消"})[t]??t}function Ee(t){w.replaceChildren(Ne(t,"result",0))}function Ne(t,e,r){if(t!==null&&typeof t=="object"){const a=Array.isArray(t)?t.map((S,g)=>[String(g),S]):Object.entries(t),d=document.createElement("details");d.className="tree-branch",d.open=r===0;const c=document.createElement("summary"),m=document.createElement("span");m.className="tree-key",m.textContent=e;const p=document.createElement("span");p.className="tree-preview",p.textContent=ht(t,a.length),c.append(m,p),d.append(c);const l=document.createElement("div");l.className="tree-children";for(const[S,g]of a)l.append(Ne(g,Array.isArray(t)?`#${Number(S)+1}`:S,r+1));return d.append(l),d}const n=document.createElement("div");n.className="tree-leaf";const s=document.createElement("span");s.className="tree-key",s.textContent=e;const o=document.createElement("span");return o.className=`tree-value tree-${t===null?"null":typeof t}`,o.textContent=t===null?"null":typeof t=="string"?`“${t}”`:String(t),n.append(s,o),n}function ht(t,e){if(Array.isArray(t))return i==="en"?`${e} items`:`${e} 项`;const r=t,n=r.orderNumber??r.name??r.productName??r.transactionId??r.trackingNumber;return n?String(n):i==="en"?`${e} fields`:`${e} 个字段`}function gt(t){return Array.isArray(t)?t.length:Array.isArray(t?.data)?t.data.length:1}function Le(t,e,r){const n=e.view==="dashboard"?t.filteredOrders:gt(t),s=i==="en"?`${n} ${e.view==="dashboard"?`matching order${n===1?"":"s"}`:`result${n===1?"":"s"}`}`:`${n} 条${e.view==="dashboard"?"匹配订单":"结果"}`;J.textContent=`${s} · ${r} ms · ${i==="en"?"in-browser SQLite":"浏览器内 SQLite"}`}function Oe(t){const e=pe.filter(r=>r.entity==="CustomerOrder").length;F.textContent=i==="en"?`${t.toUpperCase()} · ${e} orders · 7 entities · policy installed · ready`:`${t.toUpperCase()} · ${e} 个订单 · 7 个实体 · 已安装策略 · 就绪`}function Pe(){document.documentElement.lang=i==="en"?"en":"zh-CN",document.title=i==="en"?"TeaQL Order Query Playground":"TeaQL 订单查询演练场";const t=document.querySelector('meta[name="description"]');if(t&&(t.content=i==="en"?"A TeaQL order-query playground running entirely in the browser":"完全运行在浏览器中的 TeaQL 订单查询演练场"),document.querySelectorAll("[data-i18n]").forEach(e=>{const r=e.dataset.i18n;r&&(e.textContent=st(r))}),ge.forEach(e=>{const r=e.dataset.locale===i;e.classList.toggle("active",r),e.setAttribute("aria-pressed",String(r))}),document.querySelector(".language-switch")?.setAttribute("aria-label",i==="en"?"Language":"语言"),document.querySelector(".brand")?.setAttribute("aria-label",i==="en"?"TeaQL Playground home":"TeaQL 演练场首页"),document.querySelector(".model-map")?.setAttribute("aria-label",i==="en"?"Order domain model":"订单领域模型"),document.querySelector(".runtime-language-selector")?.setAttribute("aria-label",i==="en"?"TeaQL runtimes":"TeaQL 运行时"),document.querySelector(".runtime-bar")?.setAttribute("aria-label",i==="en"?"Runtime settings":"运行时设置"),k.setAttribute("aria-label",i==="en"?"Example queries":"示例查询"),document.querySelector(".result-view-switch")?.setAttribute("aria-label",i==="en"?"Result views":"结果视图"),document.querySelector(".tree-actions")?.setAttribute("aria-label",i==="en"?"Result tree actions":"结果树操作"),dt(),D){const{data:e,query:r,active:n}=D;ye.textContent=O(r.title),he.textContent=O(r.description),z(),be(n.evidence.snapshot(),ee),Le(e,r,fe),Oe(B.checked?"opfs":"memory")}else F.textContent=i==="en"?"Starting SQLite/WASM…":"正在启动 SQLite/WASM…"}function re(){return le.find(t=>t.id===W)??le[0]}async function ve(t){F.textContent=i==="en"?`Opening ${t.toUpperCase()} SQLite/WASM…`:`正在打开 ${t.toUpperCase()} SQLite/WASM…`;const e=E;E=void 0,await e?.client.close();const r=await it(t);E=r,await Ie(r),await P(re(),r),Oe(t)}B.addEventListener("change",()=>{const t=B.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",t),ve(t).catch(N)});Y.addEventListener("click",async()=>{if(E){Y.disabled=!0;try{await E.client.reset(E.context),await Ie(E),await P(re(),E)}catch(t){N(t)}finally{Y.disabled=!1}}});X.addEventListener("click",()=>{w.querySelectorAll("details").forEach(t=>{t.open=!0})});Q.addEventListener("click",()=>{Q.disabled||(b="table",z())});V.addEventListener("click",()=>{b="tree",z()});tt.addEventListener("click",()=>{w.querySelectorAll("details").forEach((t,e)=>{t.open=e===0})});ge.forEach(t=>{t.addEventListener("click",()=>{i=t.dataset.locale==="zh"?"zh":"en",localStorage.setItem("teaql-browser-locale",i),Pe()})});function N(t){const e=t instanceof Error?t:new Error(String(t));F.textContent=`${e.name}: ${e.message}`,J.textContent=i==="en"?"Query failed":"查询失败",Ee({error:e.name,message:e.message})}Pe();W=re().id;H();ve(Ae).catch(N);
dist/assets/{main-C1ZloXXC.js → main-DKg7I1TH.js} RENAMED
@@ -1,6 +1,6 @@
1
- import{S as x,m as Pe,a as qe,e as xe,O as $,B as Qe,b as Re,R as $e,U as Be,D as Fe,c as ke,M as We}from"./dynamic-search-Ch_QcWVU.js";/* empty css */const C=t=>({columnName:t,modelName:t,logicalType:"integer",decode:"string"}),y=t=>({columnName:t,modelName:t,logicalType:"text",decode:"native"}),ze=t=>({columnName:t,modelName:t,logicalType:"date",decode:"date"}),K=t=>({columnName:t,modelName:t,logicalType:"datetime",decode:"date"}),I=(t,e="decimal")=>({columnName:t,modelName:t,logicalType:e,decode:"number"}),f=Object.freeze({PENDING_PAYMENT:"1001",PAID:"1002",SHIPPED:"1003",DELIVERED:"1004",CANCELLED:"1005"}),Me=[{entity:"OrderStatus",id:f.PENDING_PAYMENT,values:{name:"Pending payment",code:"PENDING_PAYMENT",color:"#D97706",displayOrder:10}},{entity:"OrderStatus",id:f.PAID,values:{name:"Paid",code:"PAID",color:"#2563EB",displayOrder:20}},{entity:"OrderStatus",id:f.SHIPPED,values:{name:"Shipped",code:"SHIPPED",color:"#16A34A",displayOrder:30}},{entity:"OrderStatus",id:f.DELIVERED,values:{name:"Delivered",code:"DELIVERED",color:"#047857",displayOrder:40}},{entity:"OrderStatus",id:f.CANCELLED,values:{name:"Cancelled",code:"CANCELLED",color:"#9F1239",displayOrder:50}}],ie={Platform:{table:"platform_data",columns:{id:C("id"),name:y("name"),code:y("code"),region:y("region"),currency:y("currency"),version:I("version","integer")},relations:{customerList:{targetEntity:"Customer",localKey:"id",foreignKey:"platformId",many:!0},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"platformId",many:!0}}},Customer:{table:"customer_data",columns:{id:C("id"),name:y("name"),email:y("email"),city:y("city"),tier:y("tier"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"customerId",many:!0}}},CustomerOrder:{table:"customer_order_data",columns:{id:C("id"),orderNumber:y("order_number"),orderDate:ze("order_date"),status:C("status_id"),totalAmount:I("total_amount"),currency:y("currency"),customerId:C("customer_id"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},customer:{targetEntity:"Customer",localKey:"customerId",foreignKey:"id",many:!1},status:{targetEntity:"OrderStatus",localKey:"status",foreignKey:"id",many:!1},itemList:{targetEntity:"OrderItem",localKey:"id",foreignKey:"orderId",many:!0},paymentList:{targetEntity:"Payment",localKey:"id",foreignKey:"orderId",many:!0},shipmentList:{targetEntity:"Shipment",localKey:"id",foreignKey:"orderId",many:!0}}},OrderStatus:{table:"order_status_data",columns:{id:C("id"),name:y("name"),code:y("code"),color:y("color"),displayOrder:I("display_order","integer"),version:I("version","integer")},relations:{orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"status",many:!0}}},OrderItem:{table:"order_item_data",columns:{id:C("id"),orderId:C("order_id"),productName:y("product_name"),sku:y("sku"),quantity:I("quantity","integer"),unitPrice:I("unit_price"),lineAmount:I("line_amount"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Payment:{table:"payment_data",columns:{id:C("id"),orderId:C("order_id"),provider:y("provider"),status:y("status"),amount:I("amount"),currency:y("currency"),transactionId:y("transaction_id"),paidAt:K("paid_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Shipment:{table:"shipment_data",columns:{id:C("id"),orderId:C("order_id"),carrier:y("carrier"),status:y("status"),trackingNumber:y("tracking_number"),shipToCity:y("ship_to_city"),shippedAt:K("shipped_at"),deliveredAt:K("delivered_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}}},pe=[{entity:"Platform",id:"1",payload:{name:"TeaQL Store",code:"TEAQL-CN",region:"China",currency:"CNY"}},{entity:"Platform",id:"2",payload:{name:"TeaQL Global",code:"TEAQL-GLOBAL",region:"Global",currency:"USD"}},{entity:"Customer",id:"101",payload:{name:"Lin Xiao",email:"lin.xiao@example.com",city:"Shanghai",tier:"GOLD",platformId:"1"}},{entity:"Customer",id:"102",payload:{name:"Zhou Ran",email:"zhou.ran@example.com",city:"Hangzhou",tier:"SILVER",platformId:"1"}},{entity:"Customer",id:"103",payload:{name:"Maya Patel",email:"maya.patel@example.com",city:"Singapore",tier:"GOLD",platformId:"2"}},{entity:"Customer",id:"104",payload:{name:"Lucas Martin",email:"lucas.martin@example.com",city:"Paris",tier:"SILVER",platformId:"2"}},{entity:"Customer",id:"105",payload:{name:"Wang Ning",email:"wang.ning@example.com",city:"Chengdu",tier:"BRONZE",platformId:"1"}},{entity:"CustomerOrder",id:"1001",payload:{orderNumber:"TQL-2026-1001",orderDate:"2026-08-28",status:f.DELIVERED,totalAmount:499,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1002",payload:{orderNumber:"TQL-2026-1002",orderDate:"2026-09-02",status:f.SHIPPED,totalAmount:1299,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1003",payload:{orderNumber:"TQL-2026-1003",orderDate:"2026-09-06",status:f.PAID,totalAmount:328.8,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1004",payload:{orderNumber:"TQL-2026-1004",orderDate:"2026-09-11",status:f.PENDING_PAYMENT,totalAmount:79.9,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"CustomerOrder",id:"1005",payload:{orderNumber:"TQL-2026-1005",orderDate:"2026-09-14",status:f.DELIVERED,totalAmount:219,currency:"USD",customerId:"103",platformId:"2"}},{entity:"CustomerOrder",id:"1006",payload:{orderNumber:"TQL-2026-1006",orderDate:"2026-09-18",status:f.PAID,totalAmount:640,currency:"USD",customerId:"104",platformId:"2"}},{entity:"CustomerOrder",id:"1007",payload:{orderNumber:"TQL-2026-1007",orderDate:"2026-09-21",status:f.CANCELLED,totalAmount:159,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1008",payload:{orderNumber:"TQL-2026-1008",orderDate:"2026-09-25",status:f.SHIPPED,totalAmount:268,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"OrderItem",id:"2001",payload:{orderId:"1001",productName:"TeaQL Mechanical Keyboard",sku:"KB-TQL-87",quantity:1,unitPrice:299,lineAmount:299}},{entity:"OrderItem",id:"2002",payload:{orderId:"1001",productName:"Silent Wireless Mouse",sku:"MS-SILENT",quantity:2,unitPrice:100,lineAmount:200}},{entity:"OrderItem",id:"2003",payload:{orderId:"1002",productName:"27-inch Developer Monitor",sku:"MON-27-4K",quantity:1,unitPrice:1299,lineAmount:1299}},{entity:"OrderItem",id:"2004",payload:{orderId:"1003",productName:"White Porcelain Travel Tea Set",sku:"TEA-TRAVEL",quantity:1,unitPrice:168.8,lineAmount:168.8}},{entity:"OrderItem",id:"2005",payload:{orderId:"1003",productName:"Pre-Qingming Longjing Tea",sku:"TEA-LJ-100",quantity:2,unitPrice:80,lineAmount:160}},{entity:"OrderItem",id:"2006",payload:{orderId:"1004",productName:"Double-wall Glass Tumbler",sku:"CUP-GLASS",quantity:1,unitPrice:79.9,lineAmount:79.9}},{entity:"OrderItem",id:"2007",payload:{orderId:"1005",productName:"Travel Brew Kit",sku:"BREW-KIT",quantity:1,unitPrice:219,lineAmount:219}},{entity:"OrderItem",id:"2008",payload:{orderId:"1006",productName:"Desktop Studio Speaker",sku:"SPK-STUDIO",quantity:2,unitPrice:260,lineAmount:520}},{entity:"OrderItem",id:"2009",payload:{orderId:"1006",productName:"Speaker Stand",sku:"SPK-STAND",quantity:1,unitPrice:120,lineAmount:120}},{entity:"OrderItem",id:"2010",payload:{orderId:"1007",productName:"Desktop Reading Lamp",sku:"LAMP-DESK",quantity:1,unitPrice:159,lineAmount:159}},{entity:"OrderItem",id:"2011",payload:{orderId:"1008",productName:"TeaQL Portable Keyboard",sku:"KB-TQL-68",quantity:1,unitPrice:268,lineAmount:268}},{entity:"Payment",id:"3001",payload:{orderId:"1001",provider:"Alipay",status:"CAPTURED",amount:499,currency:"CNY",transactionId:"ALI-260828-01",paidAt:"2026-08-28T10:14:00Z"}},{entity:"Payment",id:"3002",payload:{orderId:"1002",provider:"WeChat Pay",status:"CAPTURED",amount:1299,currency:"CNY",transactionId:"WX-260902-08",paidAt:"2026-09-02T03:20:00Z"}},{entity:"Payment",id:"3003",payload:{orderId:"1003",provider:"Alipay",status:"CAPTURED",amount:328.8,currency:"CNY",transactionId:"ALI-260906-11",paidAt:"2026-09-06T11:42:00Z"}},{entity:"Payment",id:"3004",payload:{orderId:"1004",provider:"WeChat Pay",status:"PENDING",amount:79.9,currency:"CNY",transactionId:"WX-260911-02",paidAt:null}},{entity:"Payment",id:"3005",payload:{orderId:"1005",provider:"Stripe",status:"CAPTURED",amount:219,currency:"USD",transactionId:"PI-260914-05",paidAt:"2026-09-14T06:10:00Z"}},{entity:"Payment",id:"3006",payload:{orderId:"1006",provider:"Stripe",status:"CAPTURED",amount:640,currency:"USD",transactionId:"PI-260918-03",paidAt:"2026-09-18T15:08:00Z"}},{entity:"Payment",id:"3007",payload:{orderId:"1007",provider:"Alipay",status:"REFUNDED",amount:159,currency:"CNY",transactionId:"ALI-260921-07",paidAt:"2026-09-21T02:55:00Z"}},{entity:"Payment",id:"3008",payload:{orderId:"1008",provider:"WeChat Pay",status:"CAPTURED",amount:268,currency:"CNY",transactionId:"WX-260925-06",paidAt:"2026-09-25T08:31:00Z"}},{entity:"Shipment",id:"4001",payload:{orderId:"1001",carrier:"SF Express",status:"DELIVERED",trackingNumber:"SF2608281001",shipToCity:"Shanghai",shippedAt:"2026-08-29T02:00:00Z",deliveredAt:"2026-08-30T07:26:00Z"}},{entity:"Shipment",id:"4002",payload:{orderId:"1002",carrier:"JD Logistics",status:"IN_TRANSIT",trackingNumber:"JD2609021002",shipToCity:"Hangzhou",shippedAt:"2026-09-03T04:12:00Z",deliveredAt:null}},{entity:"Shipment",id:"4003",payload:{orderId:"1003",carrier:"SF Express",status:"READY",trackingNumber:"SF2609061003",shipToCity:"Shanghai",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4004",payload:{orderId:"1005",carrier:"DHL",status:"DELIVERED",trackingNumber:"DHL2609141005",shipToCity:"Singapore",shippedAt:"2026-09-15T01:10:00Z",deliveredAt:"2026-09-17T09:22:00Z"}},{entity:"Shipment",id:"4005",payload:{orderId:"1006",carrier:"DHL",status:"READY",trackingNumber:"DHL2609181006",shipToCity:"Paris",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4006",payload:{orderId:"1008",carrier:"SF Express",status:"IN_TRANSIT",trackingNumber:"SF2609251008",shipToCity:"Chengdu",shippedAt:"2026-09-26T03:18:00Z",deliveredAt:null}}],N=t=>`'${t.replaceAll("\\","\\\\").replaceAll("'","\\'").replaceAll(`
2
- `,"\\n")}'`,U=t=>t.toQExpression().replace(/\s*\n\s*/g,""),_e={CustomerOrder:{fields:{id:"integer",orderNumber:"string",orderDate:"date",status:"integer",totalAmount:"decimal",currency:"string",customerId:"integer",platformId:"integer"},relations:{status:"OrderStatus",itemList:"OrderItem"}},OrderStatus:{fields:{id:"integer",name:"string",code:"string",color:"string",displayOrder:"integer"},relations:{}},OrderItem:{fields:{id:"integer",orderId:"integer",productName:"string",sku:"string"},relations:{}}};function Ke(t){if(!t||typeof t!="object"||Array.isArray(t))return t;const e=structuredClone(t),r=e.filter;if(!r||typeof r!="object"||Array.isArray(r)||!("status"in r))return e;const n=r,s=n.status,o=a=>{const i=f[String(a)];return i===void 0?a:Number(i)};return s&&typeof s=="object"&&!Array.isArray(s)&&"$in"in s?n.status={$in:Array.isArray(s.$in)?s.$in.map(o):s.$in}:n.status=o(s),e}class T{query;filters=[];qRoot;qSteps=[];auditComment="";queryPurpose="";pageTotalAlias;constructor(e,r){this.query=new x(e),this.qRoot=r}comment(e){return this.auditComment=e,this.query.comment(e),this.record(`comment(${N(e)})`),this}purpose(e){return this.queryPurpose=e,this.query.purpose(e),this.record(`purpose(${N(e)})`),this}limit(e){return this.query.limit(e),this.record(`limit(${e})`),this}offset(e){return this.query.offset(e),this.record(`offset(${e})`),this}toQExpression(e){const r=e?[...this.qSteps,e]:this.qSteps;return[this.qRoot,...r.map(n=>` .${n}`)].join(`
3
- `)}toQuery(){const e=this.query.clone();return this.filters.length&&e.filter({$and:[...this.filters]}),e}async executeForList(e){return this.executeList(e,this.pageTotalAlias!==void 0)}async executeForRows(e){return this.executeList(e,!1)}async executeList(e,r){this.ensureIntent();const n=this.service(e),s=this.toQuery(),o=r?await n.executeCount(s,this.pageTotalAlias,{kind:"named-count",method:"countAs",alias:this.pageTotalAlias}):void 0,a=s.clone();r&&(a.aggregateItems=a.aggregateItems.filter(l=>!(String(l.function).toLowerCase()==="count"&&l.alias===this.pageTotalAlias)));const i=await n.executeQuery(e.prepareQuery(a)),c=new qe(i,{totalCount:o});return r&&this.pageTotalAlias!==void 0&&(c.aggregations[this.pageTotalAlias]=o),s.facets.length&&(c.facets=await xe(n,l=>e.prepareQuery(l),s,s.facets)),c}addFilter(e){return this.filters.push(e),this}select(...e){return this.query.select(e),this}order(e,r){return this.query.order(r==="asc"?$.asc(e):$.desc(e)),this}group(e){return this.query.groupBy(e),this}aggregate(e,r,n){return this.query.aggregate(e,r,n),this}record(e){return this.qSteps.push(e),this}includePageTotalAs(e){return this.pageTotalAlias=e,this}service(e){return e.requireResource("dataService")}ensureIntent(){if(!this.auditComment.trim()||!this.queryPurpose.trim())throw new Error("Generated Q requests require comment() and purpose() before execution")}}class Ue extends T{constructor(){super("Platform","Q.platforms()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCode(){return this.select("code")}withIdIs(e){return this.addFilter({id:{$eq:e}})}}class Ye extends T{constructor(){super("Customer","Q.customers()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCity(){return this.select("city")}selectTier(){return this.select("tier")}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}countOrderListAs(e){return this.query.relationAggregate("orderList",e,new x("CustomerOrder").aggregate("Count","id",e)),this}orderByNameAscending(){return this.order("name","asc")}}class Ge extends T{constructor(){super("OrderItem","Q.orderItems()")}selectId(){return this.select("id"),this.record("selectId()")}selectOrderId(){return this.select("orderId"),this.record("selectOrderId()")}selectProductName(){return this.select("productName"),this.record("selectProductName()")}selectSku(){return this.select("sku"),this.record("selectSku()")}selectQuantity(){return this.select("quantity"),this.record("selectQuantity()")}withProductNameContaining(e){return this.addFilter({productName:{$contains:e}})}orderByIdAscending(){return this.order("id","asc"),this.record("orderByIdAscending()")}groupByProductName(){return this.group("productName")}sumQuantityAs(e){return this.aggregate("Sum","quantity",e)}sumLineAmountAs(e){return this.aggregate("Sum","lineAmount",e)}countAs(e){return this.aggregate("Count","id",e)}}class je extends T{constructor(){super("OrderStatus","Q.orderStatuses()")}selectId(){return this.select("id"),this.record("selectId()")}selectName(){return this.select("name"),this.record("selectName()")}selectCode(){return this.select("code"),this.record("selectCode()")}selectColor(){return this.select("color"),this.record("selectColor()")}selectDisplayOrder(){return this.select("displayOrder"),this.record("selectDisplayOrder()")}withCodeIs(e){return this.addFilter({code:{$eq:e}})}countAs(e){return this.aggregate("Count","id",e),this.record(`countAs(${N(e)})`)}sumOrderTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e),this.record(`sumOrderTotalAmountAs(${N(e)})`)}orderByDisplayOrderAscending(){return this.order("displayOrder","asc"),this.record("orderByDisplayOrderAscending()")}}class Ve extends T{constructor(){super("Payment","Q.payments()")}groupByCurrency(){return this.group("currency")}groupByProvider(){return this.group("provider")}groupByStatus(){return this.group("status")}countAs(e){return this.aggregate("Count","id",e)}sumAmountAs(e){return this.aggregate("Sum","amount",e)}orderByCurrencyAscending(){return this.order("currency","asc")}orderByProviderAscending(){return this.order("provider","asc")}orderByIdAscending(){return this.order("id","asc")}}class He extends T{constructor(){super("Shipment","Q.shipments()")}withStatusIn(...e){return this.addFilter({status:{$in:e}})}selectOrderWith(e){return this.query.relationQuery("order",e.toQuery(),"orderId","id",!1),this}orderByStatusAscending(){return this.order("status","asc")}orderByIdAscending(){return this.order("id","asc")}}class de extends T{dynamicWarnings=[];countAlias;rowCountApplied=!1;constructor(e=!1){super("CustomerOrder",e?"Q.customerOrdersWithMinimalFields()":"Q.customerOrders()"),e?this.query.select(["id","version"]):this.query.select(["id","orderNumber","orderDate","status","totalAmount","currency","customerId","platformId","version"])}selectId(){return this.select("id")}selectOrderNumber(){return this.select("orderNumber"),this.record("selectOrderNumber()")}selectOrderDate(){return this.select("orderDate"),this.record("selectOrderDate()")}selectStatus(){return this.select("status")}selectTotalAmount(){return this.select("totalAmount")}selectCurrency(){return this.select("currency")}withOrderNumberIs(e){return this.addFilter({orderNumber:{$eq:e}})}withOrderNumberContaining(e){return this.addFilter({orderNumber:{$contains:e}})}withStatusMatching(e){return this.addFilter({status:{$inSubquery:{query:e.toQuery(),field:"id"}}})}withStatusIsPendingPayment(){return this.addFilter({status:{$eq:f.PENDING_PAYMENT}})}withStatusIsPaid(){return this.addFilter({status:{$eq:f.PAID}})}withStatusIsShipped(){return this.addFilter({status:{$eq:f.SHIPPED}})}withStatusIsDelivered(){return this.addFilter({status:{$eq:f.DELIVERED}})}withStatusIsCancelled(){return this.addFilter({status:{$eq:f.CANCELLED}})}withCurrencyIs(e){return this.addFilter({currency:{$eq:e}})}withTotalAmountGreaterThanOrEqualTo(e){return this.addFilter({totalAmount:{$gte:e}})}withOrderDateGreaterThanOrEqualTo(e){return this.addFilter({orderDate:{$gte:e}})}withPlatformIdIs(e){return this.addFilter({platformId:{$eq:e}})}withItemListMatching(e){return this.addFilter({id:{$inSubquery:{query:e.toQuery(),field:"orderId"}}})}filterByJson(e){const{query:r,warnings:n}=Pe(this.toQuery(),Ke(e),_e,{filter:(s,o)=>s==="status.code"?{status:{$inSubquery:{query:new x("OrderStatus").filter({code:o}),field:"id"}}}:s==="itemList.productName"?{id:{$inSubquery:{query:new x("OrderItem").filter({productName:o}),field:"orderId"}}}:{[s]:o},order:(s,o)=>o==="asc"?$.asc(s):$.desc(s)});return this.dynamicWarnings=n,this.query.filterCondition=r.filterCondition,this.query.orderItems=[...r.orderItems],this.record("filterByJson(searchParams)"),this}warnings(){return this.dynamicWarnings}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}selectCustomerWith(e){return this.query.relationQuery("customer",e.toQuery(),"customerId","id",!1),this}selectStatusWith(e){return this.query.select(["status"]),this.query.relationQuery("status",e.toQuery(),"status","id",!1,{kind:"relation-select",method:"selectStatusWith",relation:"status"}),this.record(`selectStatusWith(${U(e)})`)}selectItemListWith(e){return this.query.relationQuery("itemList",e.toQuery(),"id","orderId",!0,{kind:"relation-select",method:"selectItemListWith",relation:"itemList"}),this.record(`selectItemListWith(${U(e)})`)}selectPaymentListWith(e){return this.query.relationQuery("paymentList",e.toQuery(),"id","orderId",!0),this}selectShipmentListWith(e){return this.query.relationQuery("shipmentList",e.toQuery(),"id","orderId",!0),this}countItemListAs(e){return this.query.relationAggregate("itemList",e,new x("OrderItem").aggregate("Count","id",e).comment("count items"),!0,{kind:"relation-count",method:"countItemListAs",relation:"itemList",alias:e}),this.record(`countItemListAs(${N(e)})`)}facetByStatusAs(e,r,n=!0){const s=r.toQuery();return s.commentText||s.comment("load status facets"),this.query.facetBy(e,"status",{toQuery:()=>s},n,{kind:"facet",method:"facetByStatusAs",relation:"status",alias:e}),this.record(`facetByStatusAs(${N(e)}, ${U(r)})`)}orderByOrderDateDescending(){return this.order("orderDate","desc"),this.record("orderByOrderDateDescending()")}orderByOrderDateAscending(){return this.order("orderDate","asc")}orderByIdDescending(){return this.order("id","desc"),this.record("orderByIdDescending()")}orderByTotalAmountDescending(){return this.order("totalAmount","desc")}groupByCurrency(){return this.group("currency")}groupByStatus(){return this.group("status")}countAs(e){return this.countAlias=e,this.record(`countAs(${N(e)})`)}sumTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e)}averageTotalAmountAs(e){return this.aggregate("Avg","totalAmount",e)}executeForList(e){return this.countAlias&&this.includePageTotalAs(this.countAlias),super.executeForList(e)}executeForRows(e){return this.applyRowCount(),super.executeForRows(e)}applyRowCount(){!this.countAlias||this.rowCountApplied||(this.query.aggregate("Count","id",this.countAlias),this.rowCountApplied=!0)}}class u{static platforms(){return new Ue}static customers(){return new Ye}static customerOrders(){return new de}static customerOrdersWithMinimalFields(){return new de(!0)}static orderItems(){return new Ge}static orderStatuses(){return new je}static payments(){return new Ve}static shipments(){return new He}}const k=document.querySelector("#status"),B=document.querySelector("#persist"),Y=document.querySelector("#reset"),F=document.querySelector("#query-catalog"),w=document.querySelector("#result"),ye=document.querySelector("#result-title"),he=document.querySelector("#result-description"),J=document.querySelector("#result-meta"),ce=document.querySelector("#query-code"),Ze=document.querySelector("#query-params-block"),Je=document.querySelector("#query-params-code"),Xe=document.querySelector("#result-grid"),R=document.querySelector("#result-view-label"),et=document.querySelector("#sql-count"),ue=document.querySelector("#sql-output"),X=document.querySelector("#expand-all"),tt=document.querySelector("#collapse-all"),Q=document.querySelector("#view-table"),V=document.querySelector("#view-tree"),ge=Array.from(document.querySelectorAll("[data-locale]")),rt={heroTitle:{en:"Understand TeaQL queries through a familiar order model.",zh:"用一个熟悉的订单模型,看懂 TeaQL 查询。"},heroIntro:{en:"Platform, customer, order, item, payment, and shipment data all run in the browser. Order status is backed by a constant model. Choose a query below to inspect real SQLite/WASM results.",zh:"平台、用户、订单、明细、支付和物流数据都在浏览器中运行;订单状态由常数模型提供。选择下面的查询,查看真实的 SQLite/WASM 结果。"},runtimeCoverage:{en:"RUNTIME COVERAGE",zh:"RUNTIME 覆盖"},runtimeTitle:{en:"This demo runs TypeScript in your browser.",zh:"这个演示在浏览器中运行 TypeScript。"},runtimeIntro:{en:"The same model-driven Q and TraceChain contract is supported by seven TeaQL runtimes. Select a language to inspect its runtime source.",zh:"同一套模型驱动的 Q 与 TraceChain 契约支持七种 TeaQL runtime。选择一种语言,可以查看对应的 runtime 源码。"},currentBrowserRuntime:{en:"Current browser runtime",zh:"当前浏览器 runtime"},supportedRuntime:{en:"Supported runtime",zh:"已支持 runtime"},observabilityTitle:{en:"TraceChain in OpenObserve",zh:"OpenObserve 中的 TraceChain"},observabilityIntro:{en:"A captured Order query rendered as business lineage: page purpose, nested request comments, and the actual SQL executions remain connected.",zh:"一条真实采集的订单查询被呈现为业务谱系:页面目的、嵌套 request 的 comment 与实际执行的 SQL 始终保持连接。"},observabilityCaption:{en:"OpenObserve dashboard showing one verified trace and its eight actual SQL executions.",zh:"OpenObserve 仪表盘展示一条已验证的 trace,以及它实际执行的八条 SQL。"},platform:{en:"Platform",zh:"平台"},customer:{en:"Customer",zh:"用户"},order:{en:"Order",zh:"订单"},item:{en:"Item",zh:"明细"},payment:{en:"Payment",zh:"支付"},shipment:{en:"Shipment",zh:"物流"},constantModel:{en:"Constant model",zh:"常数模型"},persist:{en:"Persist locally with OPFS",zh:"使用 OPFS 保存在本地"},reset:{en:"Reset demo data",zh:"重置演示数据"},chooseQuery:{en:"Choose a query",zh:"选择一个查询"},queryIntro:{en:"Queries are grouped by purpose and share the same order dataset.",zh:"查询按用途分组,并共用同一份订单数据。"},table:{en:"Table",zh:"表格"},resultTree:{en:"Result Tree",zh:"结果树"},expandAll:{en:"Expand all",zh:"全部展开"},collapseAll:{en:"Collapse all",zh:"全部折叠"},waiting:{en:"Waiting for query…",zh:"等待查询…"},queryNote:{en:"The Q expression stays fixed; search, status cards, and pagination only update dynamic parameters. The underlying SelectQuery remains inside the generated request implementation.",zh:"Q 表达式保持不变;搜索、状态卡片和分页只更新动态参数。底层 SelectQuery 仍封装在生成的请求实现中。"},executionEvidence:{en:"EXECUTION EVIDENCE",zh:"执行证据"},evidenceTime:{en:"Time",zh:"时间"},identity:{en:"Identity",zh:"身份"},traceChain:{en:"Trace chain",zh:"追踪链"},sqlNote:{en:"One plain-text line per statement: time, identity, trace chain, and the SQL SQLite executed.",zh:"每条语句使用一行纯文本:��间、身份、追踪链,以及 SQLite 实际执行的 SQL。"},localData:{en:"Data stays in this browser",zh:"数据只保留在当前浏览器中"}},nt={基本查询:"Basic queries","从订单、用户和关联对象开始":"Start with orders, customers, and related objects",汇总查询:"Aggregations","分组、计数、求和与平均值":"Grouping, counts, sums, and averages",过滤查询:"Filtered queries","精确、范围与组合条件":"Exact, range, and combined predicates",动态查询:"Dynamic queries","由页面条件安全生成,不使用 eval":"Safely generated from page criteria without eval","综合:订单管理中心":"Comprehensive: Order management center","一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。":"A real composite query page: status metrics, search, product previews, and pagination are all driven by TeaQL.",最近订单:"Recent orders","按下单日期倒序浏览全部订单,并带出所属平台与用户。":"Browse all orders by date descending, including their platform and customer.",完整订单详情:"Complete order details","查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。":"Inspect one order with its customer, items, payments, and shipments as a complete object graph.",用户与订单数:"Customers with order counts","列出用户,并通过关联汇总显示每位用户的订单数量。":"List customers and show each customer’s order count through a relation aggregate.",订单状态汇总:"Orders by status","按币种与订单状态统计订单数、总额和平均客单价。":"Aggregate order count, gross amount, and average order value by currency and status.",商品销售汇总:"Product sales summary","按商品汇总销量与销售额,找出最受欢迎的订单明细。":"Aggregate units and revenue by product to identify the most popular order items.",支付渠道对账:"Payment reconciliation","按币种、支付渠道和状态汇总笔数与金额。":"Aggregate transaction count and amount by currency, payment provider, and status.",待支付订单:"Orders awaiting payment","筛选尚未完成付款的订单,并带出对应支付记录。":"Find orders that have not completed payment and include their payment records.",国内大额订单:"High-value domestic orders","组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。":"Combine platform and amount filters to find TeaQL Store orders worth at least CNY 500.",运输中的包裹:"Active shipments","筛选待揽收和运输中的物流单,并关联订单信息。":"Find shipments that are ready or in transit and include their order information.","动态:已付款国内订单":"Dynamic: paid domestic orders","从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。":"Build a query from dynamic criteria: CNY, at least 250, and status PAID or SHIPPED.","动态:九月新订单":"Dynamic: new September orders","运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。":"Pass a date range and sort order at runtime to find orders after September 15.","动态:字段白名单":"Dynamic: field allowlist","未知字段会被报告并忽略;合法条件仍可安全执行。":"Unknown fields are reported and ignored while valid predicates still execute safely."};let d=localStorage.getItem("teaql-browser-locale")==="zh"?"zh":"en";function st(t){return rt[t]?.[d]??t}function O(t){return d==="en"?nt[t]??t:t}let E,W=window.location.hash.slice(1)||"order-center";window.location.hash||history.replaceState(null,"","#order-center");let b="tree",D,fe=0,ee;const A={search:"",page:0,pageSize:4},Ae=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";B.checked=Ae==="opfs";async function G(t,e){const r=u.customerOrders().filterByJson(e).limit(20).comment("what: execute a validated browser search").purpose("why: demonstrate safe dynamic order discovery"),n=await r.executeForList(t.context);return{request:e,warnings:r.warnings(),data:n}}const ot=Object.fromEntries(Object.entries(f).map(([t,e])=>[e,t]));function te(t){const e=String(t.code??"");return e&&e in f?e:"color"in t?ot[String(t.id??"")]??"":""}function Se(t){const e=t.trim();if(!e)return{filter:{}};const r=e.toUpperCase(),n=["PENDING_PAYMENT","PAID","SHIPPED","DELIVERED","CANCELLED"].find(s=>s.includes(r));return n?{filter:{"status.code":n}}:/^(TQL-|\d)/i.test(e)?{filter:{orderNumber:{$contains:r}}}:{filter:{"itemList.productName":{$contains:e}}}}async function at(t){const e=Se(A.search),r=u.customerOrdersWithMinimalFields().filterByJson(e).countAs("totalOrders").facetByStatusAs("statusCounts",u.orderStatuses().selectName().selectColor().countAs("orderCount").sumOrderTotalAmountAs("orderTotalAmount").orderByDisplayOrderAscending().comment("load status facets")).selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor().comment("load status")).selectItemListWith(u.orderItems().selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews")).countItemListAs("itemCount").orderByOrderDateDescending().orderByIdDescending().comment("load order list").purpose("render order list page"),n=r.toQExpression(`offset(pageOffset)
4
  .limit(pageSize)
5
  .executeForList(ctx);`),s=await r.offset(A.page*A.pageSize).limit(A.pageSize).executeForList(t.context),o=s.facet("statusCounts")??[];return{orders:s,totalOrders:Number(s.aggregations.totalOrders??s.totalCount),filteredOrders:s.totalCount??0,statusFacets:o.map(a=>({code:te(a),name:String(a.name??""),color:String(a.color??""),orderCount:Number(a.orderCount??0),orderTotalAmount:Number(a.orderTotalAmount??0)})).filter(a=>a.code&&a.name),search:A.search,page:A.page,pageSize:A.pageSize,queryExpression:n}}const Ce=[{label:"基本查询",description:"从订单、用户和关联对象开始",queries:[{id:"order-center",title:"综合:订单管理中心",description:"一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。",code:"",view:"dashboard",run:at},{id:"recent-orders",title:"最近订单",description:"按下单日期倒序浏览全部订单,并带出所属平台与用户。",code:`await Q.customerOrders()
6
  .selectPlatformWith(Q.platforms().selectName())
@@ -101,4 +101,4 @@ const data = await request
101
  .comment('what: execute a validated browser search')
102
  .purpose('why: demonstrate safe dynamic order discovery')
103
  .executeForList(ctx);
104
- const warnings = request.warnings();`,run:t=>G(t,{filter:{status:"DELIVERED",internalNote:{$contains:"not queryable"}}})}]}],le=Ce.flatMap(t=>t.queries);async function it(t){const e=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),r=await Qe.open(e,{...ie},{storage:t,databaseName:"teaql-order-playground-v3.sqlite3"}),n=new Re().enableSelect();r.install(new $e(ie,{},{constants:Me})),r.setRuntimeTelemetrySink(n).setDiagnosticSQLLogSink(void 0);const s=Object.freeze({policyId:"browser-order-demo-seed",version:"1",fingerprint:"sha256:browser-order-demo-seed-v1"}),o=new Be().insertResource("dataService",r).withMutationPolicyRegistry(new Fe(()=>({identity:s,review:(a,i)=>i.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new ke(a=>({policy:a,approvedBy:"browser-demo-owner",approvedAt:new Date})));return r.setUserContext(o),await o.ensureSchema(),{client:r,context:o,evidence:n}}async function Ie(t){if((await u.customerOrders().selectId().limit(1).comment("what: detect existing order playground data").purpose("why: keep deterministic browser bootstrap idempotent").executeForList(t.context)).length)return;const r=new We("Seed deterministic order playground data");await t.client.executeGraphSave(r,async n=>{const s=pe.map(o=>n.request({entity:o.entity,action:"Create",id:o.id,payload:o.payload}));for(const o of s)t.client.preflightMutation(o);for(const o of s)await t.client.executeMutation(o)})}function dt(){F.replaceChildren();for(const t of Ce){const e=document.createElement("section");e.className="query-group";const r=document.createElement("div");r.className="query-group-heading";const n=document.createElement("h2");n.textContent=O(t.label);const s=document.createElement("p");s.textContent=O(t.description),r.append(n,s);const o=document.createElement("div");o.className="query-links";for(const a of t.queries){const i=document.createElement("a");i.href=`#${a.id}`,i.dataset.queryId=a.id,i.textContent=O(a.title),i.addEventListener("click",c=>{c.preventDefault(),W=a.id,history.replaceState(null,"",`#${a.id}`),H(),E&&v(a,E).catch(L)}),o.append(i)}e.append(r,o),F.append(e)}H()}function H(){F.querySelectorAll("a[data-query-id]").forEach(t=>{const e=t.dataset.queryId===W;t.classList.toggle("active",e),e?t.setAttribute("aria-current","page"):t.removeAttribute("aria-current")})}async function v(t,e){const r=performance.now(),n=new Date;e.evidence.enableSelect(),w.classList.add("loading"),w.setAttribute("aria-busy","true"),ye.textContent=O(t.title),he.textContent=O(t.description),ce.textContent=t.code,Ze.classList.toggle("hidden",t.view!=="dashboard"),Je.textContent=t.view==="dashboard"?JSON.stringify({searchParams:Se(A.search),pageOffset:A.page*A.pageSize,pageSize:A.pageSize},null,2):"",Xe.classList.toggle("dashboard-mode",t.view==="dashboard"),w.classList.toggle("dashboard-result",t.view==="dashboard"),X.closest(".tree-actions")?.classList.toggle("hidden",t.view==="dashboard"),R.textContent=t.view==="dashboard"?d==="en"?"Order management center":"订单管理中心":d==="en"?"Result tree":"结果树",J.textContent=d==="en"?"Running query…":"查询中…";try{const s=await t.run(e);t.view==="dashboard"&&(ce.textContent=s.queryExpression),D={data:s,query:t,active:e},b=t.view==="dashboard"||Z(s)?"table":"tree",z();const o=Math.max(1,Math.round(performance.now()-r));fe=o,ee=n;const a=e.evidence.snapshot();be(a,n),Ne(s,t,o)}finally{w.classList.remove("loading"),w.removeAttribute("aria-busy")}}function be(t,e=ee){ue.replaceChildren(),et.textContent=d==="en"?`${t.length} statement${t.length===1?"":"s"}`:`${t.length} 条语句`,t.forEach((r,n)=>{const s=document.createElement("tr");s.className="evidence-row";const o=[...r.tracePath].reverse().find(m=>m.kind==="relation"||m.kind==="request"||m.kind==="entity"),a=document.createElement("td");a.className="evidence-time",a.dataset.executedAt=e?.toISOString()??"",a.textContent=`${e?.toISOString()??"—"} · ${Math.max(.01,r.elapsedMicros/1e3).toFixed(2)} ms`;const i=document.createElement("td");i.textContent=`${D?.query.id??"query"} · #${n+1} · ${o?.name??"query"}`;const c=document.createElement("td");if(c.className="evidence-trace",r.traceChain?.length){const m=r.traceChain.find(g=>g.kind==="purpose"),S=r.traceChain.filter(g=>g.kind==="comment").map(g=>g.detail||g.name);c.textContent=`${m?.detail||m?.name||""}: ${S.join(" → ")}`}else c.textContent=r.tracePath.map(m=>m.detail||m.name).join(" → ");const l=document.createElement("td");l.className="evidence-sql";const h=r.parameters.length?r.parameters.map(m=>String(m)).join(", "):"none";l.textContent=`${r.parameterizedSQL} · bindings: ${h}`,s.append(a,i,c,l),ue.append(s)})}function Z(t){return Array.isArray(t)&&t.every(e=>e!==null&&typeof e=="object"&&!Array.isArray(e))}function z(){if(!D)return;const{data:t,query:e,active:r}=D,n=e.view==="dashboard"||Z(t);if(n||(b="tree"),Q.disabled=!n,Q.classList.toggle("active",b==="table"),V.classList.toggle("active",b==="tree"),Q.setAttribute("aria-pressed",String(b==="table")),V.setAttribute("aria-pressed",String(b==="tree")),X.closest(".tree-actions")?.classList.toggle("hidden",b!=="tree"),b==="table"&&e.view==="dashboard"){R.textContent=d==="en"?"Result table":"结果表格",mt(t,r,e);return}if(b==="table"&&Z(t)){R.textContent=d==="en"?"Result table":"结果表格",ut(t);return}R.textContent=d==="en"?"Result tree":"结果树",Ee(e.view==="dashboard"?ct(t):t)}function ct(t){return{orders:t.orders,totalOrders:t.totalOrders,filteredOrders:t.filteredOrders,statusFacets:t.statusFacets,search:t.search,page:t.page,pageSize:t.pageSize}}function ut(t){const e=document.createElement("div");if(e.className="result-table-shell",!t.length){const i=document.createElement("p");i.className="result-table-empty",i.textContent=d==="en"?"The query returned no records.":"查询没有返回记录。",e.append(i),w.replaceChildren(e);return}const r=[...new Set(t.flatMap(i=>Object.keys(i)))],n=document.createElement("table");n.className="result-table";const s=document.createElement("thead"),o=document.createElement("tr");for(const i of r){const c=document.createElement("th");c.scope="col",c.textContent=i,o.append(c)}s.append(o);const a=document.createElement("tbody");for(const i of t){const c=document.createElement("tr");for(const l of r){const h=document.createElement("td");h.textContent=lt(i[l]),c.append(h)}a.append(c)}n.append(s,a),e.append(n),w.replaceChildren(e)}function lt(t){if(t==null)return"—";if(Array.isArray(t))return d==="en"?`${t.length} items`:`${t.length} 项`;if(t instanceof Date)return t.toISOString();if(typeof t=="object"){const e=t,r=te(e);if(r)return we(r);const n=e.name??e.orderNumber??e.code??e.id;return n===void 0?d==="en"?`${Object.keys(e).length} fields`:`${Object.keys(e).length} 个字段`:String(n)}return String(t)}function mt(t,e,r){const n=document.createElement("div");n.className="order-center";const s=document.createElement("div");s.className="order-center-toolbar";const o=document.createElement("div"),a=document.createElement("h3");a.textContent=d==="en"?"Order Management Center":"订单管理中心";const i=document.createElement("p");i.textContent=d==="en"?"One generated Q expression describes the entire page":"一个生成式 Q 表达式描述整个页面",o.append(a,i);const c=document.createElement("form");c.className="order-search";const l=document.createElement("input");l.type="search",l.placeholder=d==="en"?"Order number, status, or product…":"订单号、状态或商品名称…",l.value=t.search,l.setAttribute("aria-label",d==="en"?"Search orders":"搜索订单");const h=document.createElement("button");h.type="submit",h.className="order-search-submit",h.setAttribute("aria-label",d==="en"?"Run order query":"执行订单查询"),h.title=d==="en"?"Search":"查询";const m=document.createElement("span");m.className="search-icon",m.setAttribute("aria-hidden","true"),h.append(m),c.append(l,h),c.addEventListener("submit",p=>{p.preventDefault(),A.search=l.value.trim(),A.page=0,v(r,e).catch(L)}),s.append(o,c);const S=document.createElement("div");S.className="order-metrics",S.append(me(d==="en"?"All orders":"全部订单",t.totalOrders,"total","#2B66D9",!t.search,()=>{A.search="",A.page=0,v(r,e).catch(L)}));for(const p of t.statusFacets)S.append(me(p.name,p.orderCount,p.code.toLowerCase(),p.color,t.search.toUpperCase()===p.code,()=>{A.search=p.code,A.page=0,v(r,e).catch(L)},`${d==="en"?"Total":"总额"} ${pt(p.orderTotalAmount)}`));const g=document.createElement("div");g.className="order-table";const M=document.createElement("div");M.className="order-row order-row-head";const De=d==="en"?["Order number","Order date","Status","Product details"]:["订单号","订单日期","状态","商品明细"];for(const p of De){const q=document.createElement("span");q.textContent=p,M.append(q)}if(g.append(M),!t.orders.length){const p=document.createElement("div");p.className="order-empty",p.textContent=d==="en"?"No matching orders. Try an order number, status code, or product name.":"没有匹配的订单,请尝试订单号、状态英文或商品名称。",g.append(p)}for(const p of t.orders)g.append(yt(p));const _=document.createElement("div");_.className="order-center-footer";const ne=document.createElement("p"),se=t.filteredOrders?t.page*t.pageSize+1:0,oe=Math.min(t.filteredOrders,(t.page+1)*t.pageSize);ne.textContent=d==="en"?`Showing ${se}–${oe} of ${t.filteredOrders} orders`:`显示 ${se}–${oe},共 ${t.filteredOrders} 条订单`;const P=document.createElement("div");P.className="pagination";const ae=Math.max(1,Math.ceil(t.filteredOrders/t.pageSize));P.append(j("‹",t.page-1,t.page===0,e,r));for(let p=0;p<ae;p+=1){const q=j(String(p+1),p,!1,e,r);q.classList.toggle("active",p===t.page),P.append(q)}P.append(j("›",t.page+1,t.page>=ae-1,e,r)),_.append(ne,P),n.append(s,S,g,_),w.replaceChildren(n)}function me(t,e,r,n,s,o,a){const i=document.createElement("button");i.type="button",i.className=`metric-card metric-${r}`,n&&i.style.setProperty("--metric-color",n),i.classList.toggle("active",s);const c=document.createElement("span");c.textContent=t;const l=document.createElement("strong");if(l.textContent=String(e),i.append(c,l),a){const h=document.createElement("small");h.textContent=a,i.append(h)}return i.addEventListener("click",o),i}function pt(t){return new Intl.NumberFormat(d==="en"?"en-US":"zh-CN",{minimumFractionDigits:2,maximumFractionDigits:2}).format(t)}function yt(t){const e=document.createElement("div");e.className="order-row";const r=t.status??{},n=Array.isArray(t.itemList)?t.itemList:[];[String(t.orderNumber??""),String(t.orderDate??"")].forEach(m=>{const S=document.createElement("span");S.className="order-primary",S.textContent=m,e.append(S)});const o=document.createElement("span"),a=document.createElement("span"),i=te(r);a.className=`status-badge status-${i.toLowerCase()}`,a.textContent=we(i)||String(r.name??i);const c=String(r.color??"");c&&(a.style.color=c,a.style.backgroundColor=`${c}18`),o.append(a),e.append(o);const l=document.createElement("span");l.className="product-preview",n.forEach((m,S)=>{const g=document.createElement("span");g.className=`product-thumb product-tone-${S%3}`,g.textContent=String(m.productName??"?").slice(0,1),g.title=`${String(m.productName??"")} × ${String(m.quantity??1)}`,l.append(g)});const h=Number(t.itemCount??n.length)-n.length;if(h>0){const m=document.createElement("small");m.textContent=`+${h}`,l.append(m)}return e.append(l),e}function j(t,e,r,n,s){const o=document.createElement("button");return o.type="button",o.textContent=t,o.disabled=r,o.addEventListener("click",()=>{A.page=e,v(s,n).catch(L)}),o}function we(t){return(d==="en"?{PENDING_PAYMENT:"Pending payment",PAID:"Paid",SHIPPED:"Shipped",DELIVERED:"Delivered",CANCELLED:"Cancelled"}:{PENDING_PAYMENT:"待支付",PAID:"已支付",SHIPPED:"运输中",DELIVERED:"已完成",CANCELLED:"已取消"})[t]??t}function Ee(t){w.replaceChildren(Le(t,"result",0))}function Le(t,e,r){if(t!==null&&typeof t=="object"){const a=Array.isArray(t)?t.map((S,g)=>[String(g),S]):Object.entries(t),i=document.createElement("details");i.className="tree-branch",i.open=r===0;const c=document.createElement("summary"),l=document.createElement("span");l.className="tree-key",l.textContent=e;const h=document.createElement("span");h.className="tree-preview",h.textContent=ht(t,a.length),c.append(l,h),i.append(c);const m=document.createElement("div");m.className="tree-children";for(const[S,g]of a)m.append(Le(g,Array.isArray(t)?`#${Number(S)+1}`:S,r+1));return i.append(m),i}const n=document.createElement("div");n.className="tree-leaf";const s=document.createElement("span");s.className="tree-key",s.textContent=e;const o=document.createElement("span");return o.className=`tree-value tree-${t===null?"null":typeof t}`,o.textContent=t===null?"null":typeof t=="string"?`“${t}”`:String(t),n.append(s,o),n}function ht(t,e){if(Array.isArray(t))return d==="en"?`${e} items`:`${e} 项`;const r=t,n=r.orderNumber??r.name??r.productName??r.transactionId??r.trackingNumber;return n?String(n):d==="en"?`${e} fields`:`${e} 个字段`}function gt(t){return Array.isArray(t)?t.length:Array.isArray(t?.data)?t.data.length:1}function Ne(t,e,r){const n=e.view==="dashboard"?t.filteredOrders:gt(t),s=d==="en"?`${n} ${e.view==="dashboard"?`matching order${n===1?"":"s"}`:`result${n===1?"":"s"}`}`:`${n} 条${e.view==="dashboard"?"匹配订单":"结果"}`;J.textContent=`${s} · ${r} ms · ${d==="en"?"in-browser SQLite":"浏览器内 SQLite"}`}function Oe(t){const e=pe.filter(r=>r.entity==="CustomerOrder").length;k.textContent=d==="en"?`${t.toUpperCase()} · ${e} orders · 7 entities · policy installed · ready`:`${t.toUpperCase()} · ${e} 个订单 · 7 个实体 · 已安装策略 · 就绪`}function ve(){document.documentElement.lang=d==="en"?"en":"zh-CN",document.title=d==="en"?"TeaQL Order Query Playground":"TeaQL 订单查询演练场";const t=document.querySelector('meta[name="description"]');if(t&&(t.content=d==="en"?"A TeaQL order-query playground running entirely in the browser":"完全运行在浏览器中的 TeaQL 订单查询演练场"),document.querySelectorAll("[data-i18n]").forEach(e=>{const r=e.dataset.i18n;r&&(e.textContent=st(r))}),ge.forEach(e=>{const r=e.dataset.locale===d;e.classList.toggle("active",r),e.setAttribute("aria-pressed",String(r))}),document.querySelector(".language-switch")?.setAttribute("aria-label",d==="en"?"Language":"语言"),document.querySelector(".brand")?.setAttribute("aria-label",d==="en"?"TeaQL Playground home":"TeaQL 演练场首页"),document.querySelector(".model-map")?.setAttribute("aria-label",d==="en"?"Order domain model":"订单领域模型"),document.querySelector(".runtime-language-selector")?.setAttribute("aria-label",d==="en"?"TeaQL runtimes":"TeaQL 运行时"),document.querySelector(".runtime-bar")?.setAttribute("aria-label",d==="en"?"Runtime settings":"运行时设置"),F.setAttribute("aria-label",d==="en"?"Example queries":"示例查询"),document.querySelector(".result-view-switch")?.setAttribute("aria-label",d==="en"?"Result views":"结果视图"),document.querySelector(".tree-actions")?.setAttribute("aria-label",d==="en"?"Result tree actions":"结果树操作"),dt(),D){const{data:e,query:r,active:n}=D;ye.textContent=O(r.title),he.textContent=O(r.description),z(),be(n.evidence.snapshot(),ee),Ne(e,r,fe),Oe(B.checked?"opfs":"memory")}else k.textContent=d==="en"?"Starting SQLite/WASM…":"正在启动 SQLite/WASM…"}function re(){return le.find(t=>t.id===W)??le[0]}async function Te(t){k.textContent=d==="en"?`Opening ${t.toUpperCase()} SQLite/WASM…`:`正在打开 ${t.toUpperCase()} SQLite/WASM…`;const e=E;E=void 0,await e?.client.close();const r=await it(t);E=r,await Ie(r),await v(re(),r),Oe(t)}B.addEventListener("change",()=>{const t=B.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",t),Te(t).catch(L)});Y.addEventListener("click",async()=>{if(E){Y.disabled=!0;try{await E.client.reset(E.context),await Ie(E),await v(re(),E)}catch(t){L(t)}finally{Y.disabled=!1}}});X.addEventListener("click",()=>{w.querySelectorAll("details").forEach(t=>{t.open=!0})});Q.addEventListener("click",()=>{Q.disabled||(b="table",z())});V.addEventListener("click",()=>{b="tree",z()});tt.addEventListener("click",()=>{w.querySelectorAll("details").forEach((t,e)=>{t.open=e===0})});ge.forEach(t=>{t.addEventListener("click",()=>{d=t.dataset.locale==="zh"?"zh":"en",localStorage.setItem("teaql-browser-locale",d),ve()})});function L(t){const e=t instanceof Error?t:new Error(String(t));k.textContent=`${e.name}: ${e.message}`,J.textContent=d==="en"?"Query failed":"查询失败",Ee({error:e.name,message:e.message})}ve();W=re().id;H();Te(Ae).catch(L);
 
1
+ import{S as x,m as Te,a as qe,e as xe,O as R,B as Qe,b as $e,R as Re,U as Be,D as ke,c as Fe,M as We}from"./dynamic-search-Ch_QcWVU.js";/* empty css */const C=t=>({columnName:t,modelName:t,logicalType:"integer",decode:"string"}),h=t=>({columnName:t,modelName:t,logicalType:"text",decode:"native"}),ze=t=>({columnName:t,modelName:t,logicalType:"date",decode:"date"}),K=t=>({columnName:t,modelName:t,logicalType:"datetime",decode:"date"}),I=(t,e="decimal")=>({columnName:t,modelName:t,logicalType:e,decode:"number"}),f=Object.freeze({PENDING_PAYMENT:"1001",PAID:"1002",SHIPPED:"1003",DELIVERED:"1004",CANCELLED:"1005"}),Me=[{entity:"OrderStatus",id:f.PENDING_PAYMENT,values:{name:"Pending payment",code:"PENDING_PAYMENT",color:"#D97706",displayOrder:10}},{entity:"OrderStatus",id:f.PAID,values:{name:"Paid",code:"PAID",color:"#2563EB",displayOrder:20}},{entity:"OrderStatus",id:f.SHIPPED,values:{name:"Shipped",code:"SHIPPED",color:"#16A34A",displayOrder:30}},{entity:"OrderStatus",id:f.DELIVERED,values:{name:"Delivered",code:"DELIVERED",color:"#047857",displayOrder:40}},{entity:"OrderStatus",id:f.CANCELLED,values:{name:"Cancelled",code:"CANCELLED",color:"#9F1239",displayOrder:50}}],ie={Platform:{table:"platform_data",columns:{id:C("id"),name:h("name"),code:h("code"),region:h("region"),currency:h("currency"),version:I("version","integer")},relations:{customerList:{targetEntity:"Customer",localKey:"id",foreignKey:"platformId",many:!0},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"platformId",many:!0}}},Customer:{table:"customer_data",columns:{id:C("id"),name:h("name"),email:h("email"),city:h("city"),tier:h("tier"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"customerId",many:!0}}},CustomerOrder:{table:"customer_order_data",columns:{id:C("id"),orderNumber:h("order_number"),orderDate:ze("order_date"),status:C("status_id"),totalAmount:I("total_amount"),currency:h("currency"),customerId:C("customer_id"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},customer:{targetEntity:"Customer",localKey:"customerId",foreignKey:"id",many:!1},status:{targetEntity:"OrderStatus",localKey:"status",foreignKey:"id",many:!1},itemList:{targetEntity:"OrderItem",localKey:"id",foreignKey:"orderId",many:!0},paymentList:{targetEntity:"Payment",localKey:"id",foreignKey:"orderId",many:!0},shipmentList:{targetEntity:"Shipment",localKey:"id",foreignKey:"orderId",many:!0}}},OrderStatus:{table:"order_status_data",columns:{id:C("id"),name:h("name"),code:h("code"),color:h("color"),displayOrder:I("display_order","integer"),version:I("version","integer")},relations:{orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"status",many:!0}}},OrderItem:{table:"order_item_data",columns:{id:C("id"),orderId:C("order_id"),productName:h("product_name"),sku:h("sku"),quantity:I("quantity","integer"),unitPrice:I("unit_price"),lineAmount:I("line_amount"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Payment:{table:"payment_data",columns:{id:C("id"),orderId:C("order_id"),provider:h("provider"),status:h("status"),amount:I("amount"),currency:h("currency"),transactionId:h("transaction_id"),paidAt:K("paid_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Shipment:{table:"shipment_data",columns:{id:C("id"),orderId:C("order_id"),carrier:h("carrier"),status:h("status"),trackingNumber:h("tracking_number"),shipToCity:h("ship_to_city"),shippedAt:K("shipped_at"),deliveredAt:K("delivered_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}}},pe=[{entity:"Platform",id:"1",payload:{name:"TeaQL Store",code:"TEAQL-CN",region:"China",currency:"CNY"}},{entity:"Platform",id:"2",payload:{name:"TeaQL Global",code:"TEAQL-GLOBAL",region:"Global",currency:"USD"}},{entity:"Customer",id:"101",payload:{name:"Lin Xiao",email:"lin.xiao@example.com",city:"Shanghai",tier:"GOLD",platformId:"1"}},{entity:"Customer",id:"102",payload:{name:"Zhou Ran",email:"zhou.ran@example.com",city:"Hangzhou",tier:"SILVER",platformId:"1"}},{entity:"Customer",id:"103",payload:{name:"Maya Patel",email:"maya.patel@example.com",city:"Singapore",tier:"GOLD",platformId:"2"}},{entity:"Customer",id:"104",payload:{name:"Lucas Martin",email:"lucas.martin@example.com",city:"Paris",tier:"SILVER",platformId:"2"}},{entity:"Customer",id:"105",payload:{name:"Wang Ning",email:"wang.ning@example.com",city:"Chengdu",tier:"BRONZE",platformId:"1"}},{entity:"CustomerOrder",id:"1001",payload:{orderNumber:"TQL-2026-1001",orderDate:"2026-08-28",status:f.DELIVERED,totalAmount:499,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1002",payload:{orderNumber:"TQL-2026-1002",orderDate:"2026-09-02",status:f.SHIPPED,totalAmount:1299,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1003",payload:{orderNumber:"TQL-2026-1003",orderDate:"2026-09-06",status:f.PAID,totalAmount:328.8,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1004",payload:{orderNumber:"TQL-2026-1004",orderDate:"2026-09-11",status:f.PENDING_PAYMENT,totalAmount:79.9,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"CustomerOrder",id:"1005",payload:{orderNumber:"TQL-2026-1005",orderDate:"2026-09-14",status:f.DELIVERED,totalAmount:219,currency:"USD",customerId:"103",platformId:"2"}},{entity:"CustomerOrder",id:"1006",payload:{orderNumber:"TQL-2026-1006",orderDate:"2026-09-18",status:f.PAID,totalAmount:640,currency:"USD",customerId:"104",platformId:"2"}},{entity:"CustomerOrder",id:"1007",payload:{orderNumber:"TQL-2026-1007",orderDate:"2026-09-21",status:f.CANCELLED,totalAmount:159,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1008",payload:{orderNumber:"TQL-2026-1008",orderDate:"2026-09-25",status:f.SHIPPED,totalAmount:268,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"OrderItem",id:"2001",payload:{orderId:"1001",productName:"TeaQL Mechanical Keyboard",sku:"KB-TQL-87",quantity:1,unitPrice:299,lineAmount:299}},{entity:"OrderItem",id:"2002",payload:{orderId:"1001",productName:"Silent Wireless Mouse",sku:"MS-SILENT",quantity:2,unitPrice:100,lineAmount:200}},{entity:"OrderItem",id:"2003",payload:{orderId:"1002",productName:"27-inch Developer Monitor",sku:"MON-27-4K",quantity:1,unitPrice:1299,lineAmount:1299}},{entity:"OrderItem",id:"2004",payload:{orderId:"1003",productName:"White Porcelain Travel Tea Set",sku:"TEA-TRAVEL",quantity:1,unitPrice:168.8,lineAmount:168.8}},{entity:"OrderItem",id:"2005",payload:{orderId:"1003",productName:"Pre-Qingming Longjing Tea",sku:"TEA-LJ-100",quantity:2,unitPrice:80,lineAmount:160}},{entity:"OrderItem",id:"2006",payload:{orderId:"1004",productName:"Double-wall Glass Tumbler",sku:"CUP-GLASS",quantity:1,unitPrice:79.9,lineAmount:79.9}},{entity:"OrderItem",id:"2007",payload:{orderId:"1005",productName:"Travel Brew Kit",sku:"BREW-KIT",quantity:1,unitPrice:219,lineAmount:219}},{entity:"OrderItem",id:"2008",payload:{orderId:"1006",productName:"Desktop Studio Speaker",sku:"SPK-STUDIO",quantity:2,unitPrice:200,lineAmount:400}},{entity:"OrderItem",id:"2009",payload:{orderId:"1006",productName:"Speaker Stand",sku:"SPK-STAND",quantity:1,unitPrice:80,lineAmount:80}},{entity:"OrderItem",id:"2010",payload:{orderId:"1007",productName:"Desktop Reading Lamp",sku:"LAMP-DESK",quantity:1,unitPrice:159,lineAmount:159}},{entity:"OrderItem",id:"2011",payload:{orderId:"1008",productName:"TeaQL Portable Keyboard",sku:"KB-TQL-68",quantity:1,unitPrice:168,lineAmount:168}},{entity:"OrderItem",id:"2012",payload:{orderId:"1008",productName:"Keyboard Protective Case",sku:"KB-CASE-68",quantity:1,unitPrice:30,lineAmount:30}},{entity:"OrderItem",id:"2013",payload:{orderId:"1008",productName:"Foldable Travel Stand",sku:"KB-STAND-FOLD",quantity:1,unitPrice:25,lineAmount:25}},{entity:"OrderItem",id:"2014",payload:{orderId:"1008",productName:"Braided USB-C Cable",sku:"CABLE-USBC",quantity:1,unitPrice:20,lineAmount:20}},{entity:"OrderItem",id:"2015",payload:{orderId:"1008",productName:"Accent Keycap Set",sku:"KEYCAP-ACCENT",quantity:1,unitPrice:25,lineAmount:25}},{entity:"OrderItem",id:"2016",payload:{orderId:"1006",productName:"Balanced Audio Cable",sku:"AUDIO-XLR",quantity:1,unitPrice:40,lineAmount:40}},{entity:"OrderItem",id:"2017",payload:{orderId:"1006",productName:"Speaker Isolation Pads",sku:"SPK-PADS",quantity:1,unitPrice:60,lineAmount:60}},{entity:"OrderItem",id:"2018",payload:{orderId:"1006",productName:"USB DAC Adapter",sku:"AUDIO-DAC-USB",quantity:1,unitPrice:60,lineAmount:60}},{entity:"Payment",id:"3001",payload:{orderId:"1001",provider:"Alipay",status:"CAPTURED",amount:499,currency:"CNY",transactionId:"ALI-260828-01",paidAt:"2026-08-28T10:14:00Z"}},{entity:"Payment",id:"3002",payload:{orderId:"1002",provider:"WeChat Pay",status:"CAPTURED",amount:1299,currency:"CNY",transactionId:"WX-260902-08",paidAt:"2026-09-02T03:20:00Z"}},{entity:"Payment",id:"3003",payload:{orderId:"1003",provider:"Alipay",status:"CAPTURED",amount:328.8,currency:"CNY",transactionId:"ALI-260906-11",paidAt:"2026-09-06T11:42:00Z"}},{entity:"Payment",id:"3004",payload:{orderId:"1004",provider:"WeChat Pay",status:"PENDING",amount:79.9,currency:"CNY",transactionId:"WX-260911-02",paidAt:null}},{entity:"Payment",id:"3005",payload:{orderId:"1005",provider:"Stripe",status:"CAPTURED",amount:219,currency:"USD",transactionId:"PI-260914-05",paidAt:"2026-09-14T06:10:00Z"}},{entity:"Payment",id:"3006",payload:{orderId:"1006",provider:"Stripe",status:"CAPTURED",amount:640,currency:"USD",transactionId:"PI-260918-03",paidAt:"2026-09-18T15:08:00Z"}},{entity:"Payment",id:"3007",payload:{orderId:"1007",provider:"Alipay",status:"REFUNDED",amount:159,currency:"CNY",transactionId:"ALI-260921-07",paidAt:"2026-09-21T02:55:00Z"}},{entity:"Payment",id:"3008",payload:{orderId:"1008",provider:"WeChat Pay",status:"CAPTURED",amount:268,currency:"CNY",transactionId:"WX-260925-06",paidAt:"2026-09-25T08:31:00Z"}},{entity:"Shipment",id:"4001",payload:{orderId:"1001",carrier:"SF Express",status:"DELIVERED",trackingNumber:"SF2608281001",shipToCity:"Shanghai",shippedAt:"2026-08-29T02:00:00Z",deliveredAt:"2026-08-30T07:26:00Z"}},{entity:"Shipment",id:"4002",payload:{orderId:"1002",carrier:"JD Logistics",status:"IN_TRANSIT",trackingNumber:"JD2609021002",shipToCity:"Hangzhou",shippedAt:"2026-09-03T04:12:00Z",deliveredAt:null}},{entity:"Shipment",id:"4003",payload:{orderId:"1003",carrier:"SF Express",status:"READY",trackingNumber:"SF2609061003",shipToCity:"Shanghai",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4004",payload:{orderId:"1005",carrier:"DHL",status:"DELIVERED",trackingNumber:"DHL2609141005",shipToCity:"Singapore",shippedAt:"2026-09-15T01:10:00Z",deliveredAt:"2026-09-17T09:22:00Z"}},{entity:"Shipment",id:"4005",payload:{orderId:"1006",carrier:"DHL",status:"READY",trackingNumber:"DHL2609181006",shipToCity:"Paris",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4006",payload:{orderId:"1008",carrier:"SF Express",status:"IN_TRANSIT",trackingNumber:"SF2609251008",shipToCity:"Chengdu",shippedAt:"2026-09-26T03:18:00Z",deliveredAt:null}}],L=t=>`'${t.replaceAll("\\","\\\\").replaceAll("'","\\'").replaceAll(`
2
+ `,"\\n")}'`,U=t=>t.toQExpression().replace(/\s*\n\s*/g,""),_e={CustomerOrder:{fields:{id:"integer",orderNumber:"string",orderDate:"date",status:"integer",totalAmount:"decimal",currency:"string",customerId:"integer",platformId:"integer"},relations:{status:"OrderStatus",itemList:"OrderItem"}},OrderStatus:{fields:{id:"integer",name:"string",code:"string",color:"string",displayOrder:"integer"},relations:{}},OrderItem:{fields:{id:"integer",orderId:"integer",productName:"string",sku:"string"},relations:{}}};function Ke(t){if(!t||typeof t!="object"||Array.isArray(t))return t;const e=structuredClone(t),r=e.filter;if(!r||typeof r!="object"||Array.isArray(r)||!("status"in r))return e;const n=r,s=n.status,o=a=>{const d=f[String(a)];return d===void 0?a:Number(d)};return s&&typeof s=="object"&&!Array.isArray(s)&&"$in"in s?n.status={$in:Array.isArray(s.$in)?s.$in.map(o):s.$in}:n.status=o(s),e}class v{query;filters=[];qRoot;qSteps=[];auditComment="";queryPurpose="";pageTotalAlias;constructor(e,r){this.query=new x(e),this.qRoot=r}comment(e){return this.auditComment=e,this.query.comment(e),this.record(`comment(${L(e)})`),this}purpose(e){return this.queryPurpose=e,this.query.purpose(e),this.record(`purpose(${L(e)})`),this}limit(e){return this.query.limit(e),this.record(`limit(${e})`),this}offset(e){return this.query.offset(e),this.record(`offset(${e})`),this}toQExpression(e){const r=e?[...this.qSteps,e]:this.qSteps;return[this.qRoot,...r.map(n=>` .${n}`)].join(`
3
+ `)}toQuery(){const e=this.query.clone();return this.filters.length&&e.filter({$and:[...this.filters]}),e}async executeForList(e){return this.executeList(e,this.pageTotalAlias!==void 0)}async executeForRows(e){return this.executeList(e,!1)}async executeList(e,r){this.ensureIntent();const n=this.service(e),s=this.toQuery(),o=r?await n.executeCount(s,this.pageTotalAlias,{kind:"named-count",method:"countAs",alias:this.pageTotalAlias}):void 0,a=s.clone();r&&(a.aggregateItems=a.aggregateItems.filter(m=>!(String(m.function).toLowerCase()==="count"&&m.alias===this.pageTotalAlias)));const d=await n.executeQuery(e.prepareQuery(a)),c=new qe(d,{totalCount:o});return r&&this.pageTotalAlias!==void 0&&(c.aggregations[this.pageTotalAlias]=o),s.facets.length&&(c.facets=await xe(n,m=>e.prepareQuery(m),s,s.facets)),c}addFilter(e){return this.filters.push(e),this}select(...e){return this.query.select(e),this}order(e,r){return this.query.order(r==="asc"?R.asc(e):R.desc(e)),this}group(e){return this.query.groupBy(e),this}aggregate(e,r,n){return this.query.aggregate(e,r,n),this}record(e){return this.qSteps.push(e),this}includePageTotalAs(e){return this.pageTotalAlias=e,this}service(e){return e.requireResource("dataService")}ensureIntent(){if(!this.auditComment.trim()||!this.queryPurpose.trim())throw new Error("Generated Q requests require comment() and purpose() before execution")}}class Ue extends v{constructor(){super("Platform","Q.platforms()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCode(){return this.select("code")}withIdIs(e){return this.addFilter({id:{$eq:e}})}}class Ye extends v{constructor(){super("Customer","Q.customers()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCity(){return this.select("city")}selectTier(){return this.select("tier")}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}countOrderListAs(e){return this.query.relationAggregate("orderList",e,new x("CustomerOrder").aggregate("Count","id",e)),this}orderByNameAscending(){return this.order("name","asc")}}class Ge extends v{constructor(){super("OrderItem","Q.orderItems()")}selectId(){return this.select("id"),this.record("selectId()")}selectOrderId(){return this.select("orderId"),this.record("selectOrderId()")}selectProductName(){return this.select("productName"),this.record("selectProductName()")}selectSku(){return this.select("sku"),this.record("selectSku()")}selectQuantity(){return this.select("quantity"),this.record("selectQuantity()")}withProductNameContaining(e){return this.addFilter({productName:{$contains:e}})}orderByIdAscending(){return this.order("id","asc"),this.record("orderByIdAscending()")}groupByProductName(){return this.group("productName")}sumQuantityAs(e){return this.aggregate("Sum","quantity",e)}sumLineAmountAs(e){return this.aggregate("Sum","lineAmount",e)}countAs(e){return this.aggregate("Count","id",e)}}class je extends v{constructor(){super("OrderStatus","Q.orderStatuses()")}selectId(){return this.select("id"),this.record("selectId()")}selectName(){return this.select("name"),this.record("selectName()")}selectCode(){return this.select("code"),this.record("selectCode()")}selectColor(){return this.select("color"),this.record("selectColor()")}selectDisplayOrder(){return this.select("displayOrder"),this.record("selectDisplayOrder()")}withCodeIs(e){return this.addFilter({code:{$eq:e}})}countAs(e){return this.aggregate("Count","id",e),this.record(`countAs(${L(e)})`)}sumOrderTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e),this.record(`sumOrderTotalAmountAs(${L(e)})`)}orderByDisplayOrderAscending(){return this.order("displayOrder","asc"),this.record("orderByDisplayOrderAscending()")}}class Ve extends v{constructor(){super("Payment","Q.payments()")}groupByCurrency(){return this.group("currency")}groupByProvider(){return this.group("provider")}groupByStatus(){return this.group("status")}countAs(e){return this.aggregate("Count","id",e)}sumAmountAs(e){return this.aggregate("Sum","amount",e)}orderByCurrencyAscending(){return this.order("currency","asc")}orderByProviderAscending(){return this.order("provider","asc")}orderByIdAscending(){return this.order("id","asc")}}class He extends v{constructor(){super("Shipment","Q.shipments()")}withStatusIn(...e){return this.addFilter({status:{$in:e}})}selectOrderWith(e){return this.query.relationQuery("order",e.toQuery(),"orderId","id",!1),this}orderByStatusAscending(){return this.order("status","asc")}orderByIdAscending(){return this.order("id","asc")}}class de extends v{dynamicWarnings=[];countAlias;rowCountApplied=!1;constructor(e=!1){super("CustomerOrder",e?"Q.customerOrdersWithMinimalFields()":"Q.customerOrders()"),e?this.query.select(["id","version"]):this.query.select(["id","orderNumber","orderDate","status","totalAmount","currency","customerId","platformId","version"])}selectId(){return this.select("id")}selectOrderNumber(){return this.select("orderNumber"),this.record("selectOrderNumber()")}selectOrderDate(){return this.select("orderDate"),this.record("selectOrderDate()")}selectStatus(){return this.select("status")}selectTotalAmount(){return this.select("totalAmount")}selectCurrency(){return this.select("currency")}withOrderNumberIs(e){return this.addFilter({orderNumber:{$eq:e}})}withOrderNumberContaining(e){return this.addFilter({orderNumber:{$contains:e}})}withStatusMatching(e){return this.addFilter({status:{$inSubquery:{query:e.toQuery(),field:"id"}}})}withStatusIsPendingPayment(){return this.addFilter({status:{$eq:f.PENDING_PAYMENT}})}withStatusIsPaid(){return this.addFilter({status:{$eq:f.PAID}})}withStatusIsShipped(){return this.addFilter({status:{$eq:f.SHIPPED}})}withStatusIsDelivered(){return this.addFilter({status:{$eq:f.DELIVERED}})}withStatusIsCancelled(){return this.addFilter({status:{$eq:f.CANCELLED}})}withCurrencyIs(e){return this.addFilter({currency:{$eq:e}})}withTotalAmountGreaterThanOrEqualTo(e){return this.addFilter({totalAmount:{$gte:e}})}withOrderDateGreaterThanOrEqualTo(e){return this.addFilter({orderDate:{$gte:e}})}withPlatformIdIs(e){return this.addFilter({platformId:{$eq:e}})}withItemListMatching(e){return this.addFilter({id:{$inSubquery:{query:e.toQuery(),field:"orderId"}}})}filterByJson(e){const{query:r,warnings:n}=Te(this.toQuery(),Ke(e),_e,{filter:(s,o)=>s==="status.code"?{status:{$inSubquery:{query:new x("OrderStatus").filter({code:o}),field:"id"}}}:s==="itemList.productName"?{id:{$inSubquery:{query:new x("OrderItem").filter({productName:o}),field:"orderId"}}}:{[s]:o},order:(s,o)=>o==="asc"?R.asc(s):R.desc(s)});return this.dynamicWarnings=n,this.query.filterCondition=r.filterCondition,this.query.orderItems=[...r.orderItems],this.record("filterByJson(searchParams)"),this}warnings(){return this.dynamicWarnings}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}selectCustomerWith(e){return this.query.relationQuery("customer",e.toQuery(),"customerId","id",!1),this}selectStatusWith(e){return this.query.select(["status"]),this.query.relationQuery("status",e.toQuery(),"status","id",!1,{kind:"relation-select",method:"selectStatusWith",relation:"status"}),this.record(`selectStatusWith(${U(e)})`)}selectItemListWith(e){return this.query.relationQuery("itemList",e.toQuery(),"id","orderId",!0,{kind:"relation-select",method:"selectItemListWith",relation:"itemList"}),this.record(`selectItemListWith(${U(e)})`)}selectPaymentListWith(e){return this.query.relationQuery("paymentList",e.toQuery(),"id","orderId",!0),this}selectShipmentListWith(e){return this.query.relationQuery("shipmentList",e.toQuery(),"id","orderId",!0),this}countItemListAs(e){return this.query.relationAggregate("itemList",e,new x("OrderItem").aggregate("Count","id",e).comment("count items"),!0,{kind:"relation-count",method:"countItemListAs",relation:"itemList",alias:e}),this.record(`countItemListAs(${L(e)})`)}facetByStatusAs(e,r,n=!0){const s=r.toQuery();return s.commentText||s.comment("load status facets"),this.query.facetBy(e,"status",{toQuery:()=>s},n,{kind:"facet",method:"facetByStatusAs",relation:"status",alias:e}),this.record(`facetByStatusAs(${L(e)}, ${U(r)})`)}orderByOrderDateDescending(){return this.order("orderDate","desc"),this.record("orderByOrderDateDescending()")}orderByOrderDateAscending(){return this.order("orderDate","asc")}orderByIdDescending(){return this.order("id","desc"),this.record("orderByIdDescending()")}orderByTotalAmountDescending(){return this.order("totalAmount","desc")}groupByCurrency(){return this.group("currency")}groupByStatus(){return this.group("status")}countAs(e){return this.countAlias=e,this.record(`countAs(${L(e)})`)}sumTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e)}averageTotalAmountAs(e){return this.aggregate("Avg","totalAmount",e)}executeForList(e){return this.countAlias&&this.includePageTotalAs(this.countAlias),super.executeForList(e)}executeForRows(e){return this.applyRowCount(),super.executeForRows(e)}applyRowCount(){!this.countAlias||this.rowCountApplied||(this.query.aggregate("Count","id",this.countAlias),this.rowCountApplied=!0)}}class u{static platforms(){return new Ue}static customers(){return new Ye}static customerOrders(){return new de}static customerOrdersWithMinimalFields(){return new de(!0)}static orderItems(){return new Ge}static orderStatuses(){return new je}static payments(){return new Ve}static shipments(){return new He}}const F=document.querySelector("#status"),B=document.querySelector("#persist"),Y=document.querySelector("#reset"),k=document.querySelector("#query-catalog"),w=document.querySelector("#result"),ye=document.querySelector("#result-title"),he=document.querySelector("#result-description"),J=document.querySelector("#result-meta"),ce=document.querySelector("#query-code"),Ze=document.querySelector("#query-params-block"),Je=document.querySelector("#query-params-code"),Xe=document.querySelector("#result-grid"),$=document.querySelector("#result-view-label"),et=document.querySelector("#sql-count"),ue=document.querySelector("#sql-output"),X=document.querySelector("#expand-all"),tt=document.querySelector("#collapse-all"),Q=document.querySelector("#view-table"),V=document.querySelector("#view-tree"),ge=Array.from(document.querySelectorAll("[data-locale]")),rt={heroTitle:{en:"Understand TeaQL queries through a familiar order model.",zh:"用一个熟悉的订单模型,看懂 TeaQL 查询。"},heroIntro:{en:"Platform, customer, order, item, payment, and shipment data all run in the browser. Order status is backed by a constant model. Choose a query below to inspect real SQLite/WASM results.",zh:"平台、用户、订单、明细、支付和物流数据都在浏览器中运行;订单状态由常数模型提供。选择下面的查询,查看真实的 SQLite/WASM 结果。"},runtimeCoverage:{en:"RUNTIME COVERAGE",zh:"RUNTIME 覆盖"},runtimeTitle:{en:"This demo runs TypeScript in your browser.",zh:"这个演示在浏览器中运行 TypeScript。"},runtimeIntro:{en:"The same model-driven Q and TraceChain contract is supported by seven TeaQL runtimes. Select a language to inspect its runtime source.",zh:"同一套模型驱动的 Q 与 TraceChain 契约支持七种 TeaQL runtime。选择一种语言,可以查看对应的 runtime 源码。"},currentBrowserRuntime:{en:"Current browser runtime",zh:"当前浏览器 runtime"},supportedRuntime:{en:"Supported runtime",zh:"已支持 runtime"},observabilityTitle:{en:"TraceChain in OpenObserve",zh:"OpenObserve 中的 TraceChain"},observabilityIntro:{en:"A captured Order query rendered as business lineage: page purpose, nested request comments, and the actual SQL executions remain connected.",zh:"一条真实采集的订单查询被呈现为业务谱系:页面目的、嵌套 request 的 comment 与实际执行的 SQL 始终保持连接。"},observabilityCaption:{en:"OpenObserve dashboard showing one verified trace and its eight actual SQL executions.",zh:"OpenObserve 仪表盘展示一条已验证的 trace,以及它实际执行的八条 SQL。"},platform:{en:"Platform",zh:"平台"},customer:{en:"Customer",zh:"用户"},order:{en:"Order",zh:"订单"},item:{en:"Item",zh:"明细"},payment:{en:"Payment",zh:"支付"},shipment:{en:"Shipment",zh:"物流"},constantModel:{en:"Constant model",zh:"常数模型"},persist:{en:"Persist locally with OPFS",zh:"使用 OPFS 保存在本地"},reset:{en:"Reset demo data",zh:"重置演示数据"},chooseQuery:{en:"Choose a query",zh:"选择一个查询"},queryIntro:{en:"Queries are grouped by purpose and share the same order dataset.",zh:"查询按用途分组,并共用同一份订单数据。"},table:{en:"Table",zh:"表格"},resultTree:{en:"Result Tree",zh:"结果树"},expandAll:{en:"Expand all",zh:"全部展开"},collapseAll:{en:"Collapse all",zh:"全部折叠"},waiting:{en:"Waiting for query…",zh:"等待查询…"},queryNote:{en:"The Q expression stays fixed; search, status cards, and pagination only update dynamic parameters. The underlying SelectQuery remains inside the generated request implementation.",zh:"Q 表达式保持不变;搜索、状态卡片和分页只更新动态参数。底层 SelectQuery 仍封装在生成的请求实现中。"},executionEvidence:{en:"EXECUTION EVIDENCE",zh:"执行证据"},evidenceTime:{en:"Time",zh:"时间"},identity:{en:"Identity",zh:"身份"},traceChain:{en:"Trace chain",zh:"追踪链"},sqlNote:{en:"One plain-text line per statement: time, identity, trace chain, and the SQL SQLite executed.",zh:"每条语句使用一行纯文本:时间、身份、追踪链,以及 SQLite 实际执行的 SQL。"},localData:{en:"Data stays in this browser",zh:"数据只保留在当前浏览器中"}},nt={基本查询:"Basic queries","从订单、用户和关联对象开始":"Start with orders, customers, and related objects",汇总查询:"Aggregations","分组、计数、求和与平均值":"Grouping, counts, sums, and averages",过滤查询:"Filtered queries","精确、范围与组合条件":"Exact, range, and combined predicates",动态查询:"Dynamic queries","由页面条件安全生成,不使用 eval":"Safely generated from page criteria without eval","综合:订单管理中心":"Comprehensive: Order management center","一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。":"A real composite query page: status metrics, search, product previews, and pagination are all driven by TeaQL.",最近订单:"Recent orders","按下单日期倒序浏览全部订单,并带出所属平台与用户。":"Browse all orders by date descending, including their platform and customer.",完整订单详情:"Complete order details","查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。":"Inspect one order with its customer, items, payments, and shipments as a complete object graph.",用户与订单数:"Customers with order counts","列出用户,并通过关联汇总显示每位用户的订单数量。":"List customers and show each customer’s order count through a relation aggregate.",订单状态汇总:"Orders by status","按币种与订单状态统计订单数、总额和平均客单价。":"Aggregate order count, gross amount, and average order value by currency and status.",商品销售汇总:"Product sales summary","按商品汇总销量与销售额,找出最受欢迎的订单明细。":"Aggregate units and revenue by product to identify the most popular order items.",支付渠道对账:"Payment reconciliation","按币种、支付渠道和状态汇总笔数与金额。":"Aggregate transaction count and amount by currency, payment provider, and status.",待支付订单:"Orders awaiting payment","筛选尚未完成付款的订单,并带出对应支付记录。":"Find orders that have not completed payment and include their payment records.",国内大额订单:"High-value domestic orders","组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。":"Combine platform and amount filters to find TeaQL Store orders worth at least CNY 500.",运输中的包裹:"Active shipments","筛选待揽收和运输中的物流单,并关联订单信息。":"Find shipments that are ready or in transit and include their order information.","动态:已付款国内订单":"Dynamic: paid domestic orders","从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。":"Build a query from dynamic criteria: CNY, at least 250, and status PAID or SHIPPED.","动态:九月新订单":"Dynamic: new September orders","运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。":"Pass a date range and sort order at runtime to find orders after September 15.","动态:字段白名单":"Dynamic: field allowlist","未知字段会被报告并忽略;合法条件仍可安全执行。":"Unknown fields are reported and ignored while valid predicates still execute safely."};let i=localStorage.getItem("teaql-browser-locale")==="zh"?"zh":"en";function st(t){return rt[t]?.[i]??t}function O(t){return i==="en"?nt[t]??t:t}let E,W=window.location.hash.slice(1)||"order-center";window.location.hash||history.replaceState(null,"","#order-center");let b="tree",D,fe=0,ee;const A={search:"",page:0,pageSize:4},Ae=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";B.checked=Ae==="opfs";async function G(t,e){const r=u.customerOrders().filterByJson(e).limit(20).comment("what: execute a validated browser search").purpose("why: demonstrate safe dynamic order discovery"),n=await r.executeForList(t.context);return{request:e,warnings:r.warnings(),data:n}}const ot=Object.fromEntries(Object.entries(f).map(([t,e])=>[e,t]));function te(t){const e=String(t.code??"");return e&&e in f?e:"color"in t?ot[String(t.id??"")]??"":""}function Se(t){const e=t.trim();if(!e)return{filter:{}};const r=e.toUpperCase(),n=["PENDING_PAYMENT","PAID","SHIPPED","DELIVERED","CANCELLED"].find(s=>s.includes(r));return n?{filter:{"status.code":n}}:/^(TQL-|\d)/i.test(e)?{filter:{orderNumber:{$contains:r}}}:{filter:{"itemList.productName":{$contains:e}}}}async function at(t){const e=Se(A.search),r=u.customerOrdersWithMinimalFields().filterByJson(e).countAs("totalOrders").facetByStatusAs("statusCounts",u.orderStatuses().selectName().selectColor().countAs("orderCount").sumOrderTotalAmountAs("orderTotalAmount").orderByDisplayOrderAscending().comment("load status facets")).selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor().comment("load status")).selectItemListWith(u.orderItems().selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews")).countItemListAs("itemCount").orderByOrderDateDescending().orderByIdDescending().comment("load order list").purpose("render order list page"),n=r.toQExpression(`offset(pageOffset)
4
  .limit(pageSize)
5
  .executeForList(ctx);`),s=await r.offset(A.page*A.pageSize).limit(A.pageSize).executeForList(t.context),o=s.facet("statusCounts")??[];return{orders:s,totalOrders:Number(s.aggregations.totalOrders??s.totalCount),filteredOrders:s.totalCount??0,statusFacets:o.map(a=>({code:te(a),name:String(a.name??""),color:String(a.color??""),orderCount:Number(a.orderCount??0),orderTotalAmount:Number(a.orderTotalAmount??0)})).filter(a=>a.code&&a.name),search:A.search,page:A.page,pageSize:A.pageSize,queryExpression:n}}const Ce=[{label:"基本查询",description:"从订单、用户和关联对象开始",queries:[{id:"order-center",title:"综合:订单管理中心",description:"一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。",code:"",view:"dashboard",run:at},{id:"recent-orders",title:"最近订单",description:"按下单日期倒序浏览全部订单,并带出所属平台与用户。",code:`await Q.customerOrders()
6
  .selectPlatformWith(Q.platforms().selectName())
 
101
  .comment('what: execute a validated browser search')
102
  .purpose('why: demonstrate safe dynamic order discovery')
103
  .executeForList(ctx);
104
+ const warnings = request.warnings();`,run:t=>G(t,{filter:{status:"DELIVERED",internalNote:{$contains:"not queryable"}}})}]}],le=Ce.flatMap(t=>t.queries);async function it(t){const e=new Worker(new URL("/assets/sqlite.worker-DS5P4U1E.js",import.meta.url),{type:"module"}),r=await Qe.open(e,{...ie},{storage:t,databaseName:"teaql-order-playground-v4.sqlite3"}),n=new $e().enableSelect();r.install(new Re(ie,{},{constants:Me})),r.setRuntimeTelemetrySink(n).setDiagnosticSQLLogSink(void 0);const s=Object.freeze({policyId:"browser-order-demo-seed",version:"1",fingerprint:"sha256:browser-order-demo-seed-v2"}),o=new Be().insertResource("dataService",r).withMutationPolicyRegistry(new ke(()=>({identity:s,review:(a,d)=>d.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new Fe(a=>({policy:a,approvedBy:"browser-demo-owner",approvedAt:new Date})));return r.setUserContext(o),await o.ensureSchema(),{client:r,context:o,evidence:n}}async function Ie(t){if((await u.customerOrders().selectId().limit(1).comment("what: detect existing order playground data").purpose("why: keep deterministic browser bootstrap idempotent").executeForList(t.context)).length)return;const r=new We("Seed deterministic order playground data");await t.client.executeGraphSave(r,async n=>{const s=pe.map(o=>n.request({entity:o.entity,action:"Create",id:o.id,payload:o.payload}));for(const o of s)t.client.preflightMutation(o);for(const o of s)await t.client.executeMutation(o)})}function dt(){k.replaceChildren();for(const t of Ce){const e=document.createElement("section");e.className="query-group";const r=document.createElement("div");r.className="query-group-heading";const n=document.createElement("h2");n.textContent=O(t.label);const s=document.createElement("p");s.textContent=O(t.description),r.append(n,s);const o=document.createElement("div");o.className="query-links";for(const a of t.queries){const d=document.createElement("a");d.href=`#${a.id}`,d.dataset.queryId=a.id,d.textContent=O(a.title),d.addEventListener("click",c=>{c.preventDefault(),W=a.id,history.replaceState(null,"",`#${a.id}`),H(),E&&P(a,E).catch(N)}),o.append(d)}e.append(r,o),k.append(e)}H()}function H(){k.querySelectorAll("a[data-query-id]").forEach(t=>{const e=t.dataset.queryId===W;t.classList.toggle("active",e),e?t.setAttribute("aria-current","page"):t.removeAttribute("aria-current")})}async function P(t,e){const r=performance.now(),n=new Date;e.evidence.enableSelect(),w.classList.add("loading"),w.setAttribute("aria-busy","true"),ye.textContent=O(t.title),he.textContent=O(t.description),ce.textContent=t.code,Ze.classList.toggle("hidden",t.view!=="dashboard"),Je.textContent=t.view==="dashboard"?JSON.stringify({searchParams:Se(A.search),pageOffset:A.page*A.pageSize,pageSize:A.pageSize},null,2):"",Xe.classList.toggle("dashboard-mode",t.view==="dashboard"),w.classList.toggle("dashboard-result",t.view==="dashboard"),X.closest(".tree-actions")?.classList.toggle("hidden",t.view==="dashboard"),$.textContent=t.view==="dashboard"?i==="en"?"Order management center":"订单管理中心":i==="en"?"Result tree":"结果树",J.textContent=i==="en"?"Running query…":"查询中…";try{const s=await t.run(e);t.view==="dashboard"&&(ce.textContent=s.queryExpression),D={data:s,query:t,active:e},b=t.view==="dashboard"||Z(s)?"table":"tree",z();const o=Math.max(1,Math.round(performance.now()-r));fe=o,ee=n;const a=e.evidence.snapshot();be(a,n),Le(s,t,o)}finally{w.classList.remove("loading"),w.removeAttribute("aria-busy")}}function be(t,e=ee){ue.replaceChildren(),et.textContent=i==="en"?`${t.length} statement${t.length===1?"":"s"}`:`${t.length} 条语句`,t.forEach((r,n)=>{const s=document.createElement("tr");s.className="evidence-row";const o=[...r.tracePath].reverse().find(l=>l.kind==="relation"||l.kind==="request"||l.kind==="entity"),a=document.createElement("td");a.className="evidence-time",a.dataset.executedAt=e?.toISOString()??"",a.textContent=`${e?.toISOString()??"—"} · ${Math.max(.01,r.elapsedMicros/1e3).toFixed(2)} ms`;const d=document.createElement("td");d.textContent=`${D?.query.id??"query"} · #${n+1} · ${o?.name??"query"}`;const c=document.createElement("td");if(c.className="evidence-trace",r.traceChain?.length){const l=r.traceChain.find(g=>g.kind==="purpose"),S=r.traceChain.filter(g=>g.kind==="comment").map(g=>g.detail||g.name);c.textContent=`${l?.detail||l?.name||""}: ${S.join(" → ")}`}else c.textContent=r.tracePath.map(l=>l.detail||l.name).join(" → ");const m=document.createElement("td");m.className="evidence-sql";const p=r.parameters.length?r.parameters.map(l=>String(l)).join(", "):"none";m.textContent=`${r.parameterizedSQL} · bindings: ${p}`,s.append(a,d,c,m),ue.append(s)})}function Z(t){return Array.isArray(t)&&t.every(e=>e!==null&&typeof e=="object"&&!Array.isArray(e))}function z(){if(!D)return;const{data:t,query:e,active:r}=D,n=e.view==="dashboard"||Z(t);if(n||(b="tree"),Q.disabled=!n,Q.classList.toggle("active",b==="table"),V.classList.toggle("active",b==="tree"),Q.setAttribute("aria-pressed",String(b==="table")),V.setAttribute("aria-pressed",String(b==="tree")),X.closest(".tree-actions")?.classList.toggle("hidden",b!=="tree"),b==="table"&&e.view==="dashboard"){$.textContent=i==="en"?"Result table":"结果表格",mt(t,r,e);return}if(b==="table"&&Z(t)){$.textContent=i==="en"?"Result table":"结果表格",ut(t);return}$.textContent=i==="en"?"Result tree":"结果树",Ee(e.view==="dashboard"?ct(t):t)}function ct(t){return{orders:t.orders,totalOrders:t.totalOrders,filteredOrders:t.filteredOrders,statusFacets:t.statusFacets,search:t.search,page:t.page,pageSize:t.pageSize}}function ut(t){const e=document.createElement("div");if(e.className="result-table-shell",!t.length){const d=document.createElement("p");d.className="result-table-empty",d.textContent=i==="en"?"The query returned no records.":"查询没有返回记录。",e.append(d),w.replaceChildren(e);return}const r=[...new Set(t.flatMap(d=>Object.keys(d)))],n=document.createElement("table");n.className="result-table";const s=document.createElement("thead"),o=document.createElement("tr");for(const d of r){const c=document.createElement("th");c.scope="col",c.textContent=d,o.append(c)}s.append(o);const a=document.createElement("tbody");for(const d of t){const c=document.createElement("tr");for(const m of r){const p=document.createElement("td");p.textContent=lt(d[m]),c.append(p)}a.append(c)}n.append(s,a),e.append(n),w.replaceChildren(e)}function lt(t){if(t==null)return"—";if(Array.isArray(t))return i==="en"?`${t.length} items`:`${t.length} 项`;if(t instanceof Date)return t.toISOString();if(typeof t=="object"){const e=t,r=te(e);if(r)return we(r);const n=e.name??e.orderNumber??e.code??e.id;return n===void 0?i==="en"?`${Object.keys(e).length} fields`:`${Object.keys(e).length} 个字段`:String(n)}return String(t)}function mt(t,e,r){const n=document.createElement("div");n.className="order-center";const s=document.createElement("div");s.className="order-center-toolbar";const o=document.createElement("div"),a=document.createElement("h3");a.textContent=i==="en"?"Order Management Center":"订单管理中心";const d=document.createElement("p");d.textContent=i==="en"?"One generated Q expression describes the entire page":"一个生成式 Q 表达式描述整个页面",o.append(a,d);const c=document.createElement("form");c.className="order-search";const m=document.createElement("input");m.type="search",m.placeholder=i==="en"?"Order number, status, or product…":"订单号、状态或商品名称…",m.value=t.search,m.setAttribute("aria-label",i==="en"?"Search orders":"搜索订单");const p=document.createElement("button");p.type="submit",p.className="order-search-submit",p.setAttribute("aria-label",i==="en"?"Run order query":"执行订单查询"),p.title=i==="en"?"Search":"查询";const l=document.createElement("span");l.className="search-icon",l.setAttribute("aria-hidden","true"),p.append(l),c.append(m,p),c.addEventListener("submit",y=>{y.preventDefault(),A.search=m.value.trim(),A.page=0,P(r,e).catch(N)}),s.append(o,c);const S=document.createElement("div");S.className="order-metrics",S.append(me(i==="en"?"All orders":"全部订单",t.totalOrders,"total","#2B66D9",!t.search,()=>{A.search="",A.page=0,P(r,e).catch(N)}));for(const y of t.statusFacets)S.append(me(y.name,y.orderCount,y.code.toLowerCase(),y.color,t.search.toUpperCase()===y.code,()=>{A.search=y.code,A.page=0,P(r,e).catch(N)},`${i==="en"?"Total":"总额"} ${pt(y.orderTotalAmount)}`));const g=document.createElement("div");g.className="order-table";const M=document.createElement("div");M.className="order-row order-row-head";const De=i==="en"?["Order number","Order date","Status","Line Items"]:["订单号","订单日期","状态","订单明细"];for(const y of De){const q=document.createElement("span");q.textContent=y,M.append(q)}if(g.append(M),!t.orders.length){const y=document.createElement("div");y.className="order-empty",y.textContent=i==="en"?"No matching orders. Try an order number, status code, or product name.":"没有匹配的订单,请尝试订单号、状态英文或商品名称。",g.append(y)}for(const y of t.orders)g.append(yt(y));const _=document.createElement("div");_.className="order-center-footer";const ne=document.createElement("p"),se=t.filteredOrders?t.page*t.pageSize+1:0,oe=Math.min(t.filteredOrders,(t.page+1)*t.pageSize);ne.textContent=i==="en"?`Showing ${se}–${oe} of ${t.filteredOrders} orders`:`显示 ${se}–${oe},共 ${t.filteredOrders} 条订单`;const T=document.createElement("div");T.className="pagination";const ae=Math.max(1,Math.ceil(t.filteredOrders/t.pageSize));T.append(j("‹",t.page-1,t.page===0,e,r));for(let y=0;y<ae;y+=1){const q=j(String(y+1),y,!1,e,r);q.classList.toggle("active",y===t.page),T.append(q)}T.append(j("›",t.page+1,t.page>=ae-1,e,r)),_.append(ne,T),n.append(s,S,g,_),w.replaceChildren(n)}function me(t,e,r,n,s,o,a){const d=document.createElement("button");d.type="button",d.className=`metric-card metric-${r}`,n&&d.style.setProperty("--metric-color",n),d.classList.toggle("active",s);const c=document.createElement("span");c.textContent=t;const m=document.createElement("strong");if(m.textContent=String(e),d.append(c,m),a){const p=document.createElement("small");p.textContent=a,d.append(p)}return d.addEventListener("click",o),d}function pt(t){return new Intl.NumberFormat(i==="en"?"en-US":"zh-CN",{minimumFractionDigits:2,maximumFractionDigits:2}).format(t)}function yt(t){const e=document.createElement("div");e.className="order-row";const r=t.status??{},n=Array.isArray(t.itemList)?t.itemList:[];[String(t.orderNumber??""),String(t.orderDate??"")].forEach(l=>{const S=document.createElement("span");S.className="order-primary",S.textContent=l,e.append(S)});const o=document.createElement("span"),a=document.createElement("span"),d=te(r);a.className=`status-badge status-${d.toLowerCase()}`,a.textContent=we(d)||String(r.name??d);const c=String(r.color??"");c&&(a.style.color=c,a.style.backgroundColor=`${c}18`),o.append(a),e.append(o);const m=document.createElement("span");m.className="product-preview",n.forEach((l,S)=>{const g=document.createElement("span");g.className=`product-thumb product-tone-${S%3}`,g.textContent=String(l.productName??"?").slice(0,1),g.title=`${String(l.productName??"")} × ${String(l.quantity??1)}`,m.append(g)});const p=Number(t.itemCount??n.length);if(p>n.length){const l=document.createElement("small");l.className="line-item-count",l.textContent=i==="en"?`${p} items`:`共 ${p} 项`,l.title=i==="en"?`Showing ${n.length} of ${p} line items`:`显示 ${n.length} 项,共 ${p} 项订单明细`,m.append(l)}return e.append(m),e}function j(t,e,r,n,s){const o=document.createElement("button");return o.type="button",o.textContent=t,o.disabled=r,o.addEventListener("click",()=>{A.page=e,P(s,n).catch(N)}),o}function we(t){return(i==="en"?{PENDING_PAYMENT:"Pending payment",PAID:"Paid",SHIPPED:"Shipped",DELIVERED:"Delivered",CANCELLED:"Cancelled"}:{PENDING_PAYMENT:"待支付",PAID:"已支付",SHIPPED:"运输中",DELIVERED:"已完成",CANCELLED:"已取消"})[t]??t}function Ee(t){w.replaceChildren(Ne(t,"result",0))}function Ne(t,e,r){if(t!==null&&typeof t=="object"){const a=Array.isArray(t)?t.map((S,g)=>[String(g),S]):Object.entries(t),d=document.createElement("details");d.className="tree-branch",d.open=r===0;const c=document.createElement("summary"),m=document.createElement("span");m.className="tree-key",m.textContent=e;const p=document.createElement("span");p.className="tree-preview",p.textContent=ht(t,a.length),c.append(m,p),d.append(c);const l=document.createElement("div");l.className="tree-children";for(const[S,g]of a)l.append(Ne(g,Array.isArray(t)?`#${Number(S)+1}`:S,r+1));return d.append(l),d}const n=document.createElement("div");n.className="tree-leaf";const s=document.createElement("span");s.className="tree-key",s.textContent=e;const o=document.createElement("span");return o.className=`tree-value tree-${t===null?"null":typeof t}`,o.textContent=t===null?"null":typeof t=="string"?`“${t}”`:String(t),n.append(s,o),n}function ht(t,e){if(Array.isArray(t))return i==="en"?`${e} items`:`${e} 项`;const r=t,n=r.orderNumber??r.name??r.productName??r.transactionId??r.trackingNumber;return n?String(n):i==="en"?`${e} fields`:`${e} 个字段`}function gt(t){return Array.isArray(t)?t.length:Array.isArray(t?.data)?t.data.length:1}function Le(t,e,r){const n=e.view==="dashboard"?t.filteredOrders:gt(t),s=i==="en"?`${n} ${e.view==="dashboard"?`matching order${n===1?"":"s"}`:`result${n===1?"":"s"}`}`:`${n} 条${e.view==="dashboard"?"匹配订单":"结果"}`;J.textContent=`${s} · ${r} ms · ${i==="en"?"in-browser SQLite":"浏览器内 SQLite"}`}function Oe(t){const e=pe.filter(r=>r.entity==="CustomerOrder").length;F.textContent=i==="en"?`${t.toUpperCase()} · ${e} orders · 7 entities · policy installed · ready`:`${t.toUpperCase()} · ${e} 个订单 · 7 个实体 · 已安装策略 · 就绪`}function Pe(){document.documentElement.lang=i==="en"?"en":"zh-CN",document.title=i==="en"?"TeaQL Order Query Playground":"TeaQL 订单查询演练场";const t=document.querySelector('meta[name="description"]');if(t&&(t.content=i==="en"?"A TeaQL order-query playground running entirely in the browser":"完全运行在浏览器中的 TeaQL 订单查询演练场"),document.querySelectorAll("[data-i18n]").forEach(e=>{const r=e.dataset.i18n;r&&(e.textContent=st(r))}),ge.forEach(e=>{const r=e.dataset.locale===i;e.classList.toggle("active",r),e.setAttribute("aria-pressed",String(r))}),document.querySelector(".language-switch")?.setAttribute("aria-label",i==="en"?"Language":"语言"),document.querySelector(".brand")?.setAttribute("aria-label",i==="en"?"TeaQL Playground home":"TeaQL 演练场首页"),document.querySelector(".model-map")?.setAttribute("aria-label",i==="en"?"Order domain model":"订单领域模型"),document.querySelector(".runtime-language-selector")?.setAttribute("aria-label",i==="en"?"TeaQL runtimes":"TeaQL 运行时"),document.querySelector(".runtime-bar")?.setAttribute("aria-label",i==="en"?"Runtime settings":"运行时设置"),k.setAttribute("aria-label",i==="en"?"Example queries":"示例查询"),document.querySelector(".result-view-switch")?.setAttribute("aria-label",i==="en"?"Result views":"结果视图"),document.querySelector(".tree-actions")?.setAttribute("aria-label",i==="en"?"Result tree actions":"结果树操作"),dt(),D){const{data:e,query:r,active:n}=D;ye.textContent=O(r.title),he.textContent=O(r.description),z(),be(n.evidence.snapshot(),ee),Le(e,r,fe),Oe(B.checked?"opfs":"memory")}else F.textContent=i==="en"?"Starting SQLite/WASM…":"正在启动 SQLite/WASM…"}function re(){return le.find(t=>t.id===W)??le[0]}async function ve(t){F.textContent=i==="en"?`Opening ${t.toUpperCase()} SQLite/WASM…`:`正在打开 ${t.toUpperCase()} SQLite/WASM…`;const e=E;E=void 0,await e?.client.close();const r=await it(t);E=r,await Ie(r),await P(re(),r),Oe(t)}B.addEventListener("change",()=>{const t=B.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",t),ve(t).catch(N)});Y.addEventListener("click",async()=>{if(E){Y.disabled=!0;try{await E.client.reset(E.context),await Ie(E),await P(re(),E)}catch(t){N(t)}finally{Y.disabled=!1}}});X.addEventListener("click",()=>{w.querySelectorAll("details").forEach(t=>{t.open=!0})});Q.addEventListener("click",()=>{Q.disabled||(b="table",z())});V.addEventListener("click",()=>{b="tree",z()});tt.addEventListener("click",()=>{w.querySelectorAll("details").forEach((t,e)=>{t.open=e===0})});ge.forEach(t=>{t.addEventListener("click",()=>{i=t.dataset.locale==="zh"?"zh":"en",localStorage.setItem("teaql-browser-locale",i),Pe()})});function N(t){const e=t instanceof Error?t:new Error(String(t));F.textContent=`${e.name}: ${e.message}`,J.textContent=i==="en"?"Query failed":"查询失败",Ee({error:e.name,message:e.message})}Pe();W=re().id;H();ve(Ae).catch(N);
dist/index.html CHANGED
@@ -6,7 +6,7 @@
6
  <link rel="icon" href="data:," />
7
  <meta name="description" content="A TeaQL order-query playground running entirely in the browser" />
8
  <title>TeaQL Order Query Playground</title>
9
- <script type="module" crossorigin src="/assets/main-C1ZloXXC.js"></script>
10
  <link rel="modulepreload" crossorigin href="/assets/dynamic-search-Ch_QcWVU.js">
11
  <link rel="stylesheet" crossorigin href="/assets/style-HhgXsO-B.css">
12
  </head>
 
6
  <link rel="icon" href="data:," />
7
  <meta name="description" content="A TeaQL order-query playground running entirely in the browser" />
8
  <title>TeaQL Order Query Playground</title>
9
+ <script type="module" crossorigin src="/assets/main-DKg7I1TH.js"></script>
10
  <link rel="modulepreload" crossorigin href="/assets/dynamic-search-Ch_QcWVU.js">
11
  <link rel="stylesheet" crossorigin href="/assets/style-HhgXsO-B.css">
12
  </head>
index.html CHANGED
@@ -6,7 +6,7 @@
6
  <link rel="icon" href="data:," />
7
  <meta name="description" content="A TeaQL order-query playground running entirely in the browser" />
8
  <title>TeaQL Order Query Playground</title>
9
- <script type="module" crossorigin src="/assets/main-C1ZloXXC.js"></script>
10
  <link rel="modulepreload" crossorigin href="/assets/dynamic-search-Ch_QcWVU.js">
11
  <link rel="stylesheet" crossorigin href="/assets/style-HhgXsO-B.css">
12
  </head>
 
6
  <link rel="icon" href="data:," />
7
  <meta name="description" content="A TeaQL order-query playground running entirely in the browser" />
8
  <title>TeaQL Order Query Playground</title>
9
+ <script type="module" crossorigin src="/assets/main-DKg7I1TH.js"></script>
10
  <link rel="modulepreload" crossorigin href="/assets/dynamic-search-Ch_QcWVU.js">
11
  <link rel="stylesheet" crossorigin href="/assets/style-HhgXsO-B.css">
12
  </head>
source/provenance.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "repository": "https://github.com/teaql/teaql-ts",
3
- "commit": "1b08ed83aaac37a8ebaed7306e646630a8ea0aec",
4
  "branch": "main",
5
  "runtimeVersion": "0.3.1",
6
  "sourceDirectory": "source/teaql-ts",
 
1
  {
2
  "repository": "https://github.com/teaql/teaql-ts",
3
+ "commit": "1e1f50e7a54f2f47753a24cdd988e53fbde78180",
4
  "branch": "main",
5
  "runtimeVersion": "0.3.1",
6
  "sourceDirectory": "source/teaql-ts",
source/teaql-ts/examples/browser-sqlite/README.md CHANGED
@@ -38,6 +38,10 @@ per statement. Each trace is plain text with arrows between its original path
38
  steps; no JSON metadata or decorative visualization is added, and no
39
  application tracing code is required.
40
 
 
 
 
 
41
  The order-center Q expression is stable across free-text search, status-card
42
  selection, and pagination. Those interactions only replace `searchParams`,
43
  `pageOffset`, and `pageSize`; generated dynamic-search bindings compile order
 
38
  steps; no JSON metadata or decorative visualization is added, and no
39
  application tracing code is required.
40
 
41
+ The order list labels its fourth column `Line Items`. Two seeded orders contain
42
+ five internally consistent line items; the query still loads only three bounded
43
+ previews and uses the separately queried item count to display `5 items`.
44
+
45
  The order-center Q expression is stable across free-text search, status-card
46
  selection, and pagination. Those interactions only replace `searchParams`,
47
  `pageOffset`, and `pageSize`; generated dynamic-search bindings compile order
source/teaql-ts/examples/browser-sqlite/scripts/smoke.mjs CHANGED
@@ -136,8 +136,16 @@ try {
136
  const metricCount = await page.$$('#result .metric-card');
137
  const dashboardRows = await page.$$('#result .order-row:not(.order-row-head)');
138
  const dashboardColumns = await page.$$('#result .order-row-head > span');
 
 
139
  const productTitles = await page.$$eval('#result .product-thumb', elements =>
140
  elements.map(element => element.getAttribute('title') || ''));
 
 
 
 
 
 
141
  const selectedColors = await page.$$eval('#result .metric-card:not(.metric-total)', elements =>
142
  elements.map(element => element.style.getPropertyValue('--metric-color')));
143
  const facetCards = await page.$$eval('#result .metric-card:not(.metric-total)', elements =>
@@ -155,7 +163,12 @@ try {
155
  elements.map(element => element.style.color));
156
  if (!dashboard.includes('Order Management Center') || metricCount.length !== 6
157
  || dashboardRows.length !== 4 || dashboardColumns.length !== 4
 
158
  || !productTitles.some(title => title.includes('TeaQL Portable Keyboard'))
 
 
 
 
159
  || !cancelledMetric.text.includes('Cancelled') || !cancelledMetric.text.includes('1')
160
  || cancelledMetric.color !== '#9F1239'
161
  || JSON.stringify(facetCards) !== JSON.stringify([
 
136
  const metricCount = await page.$$('#result .metric-card');
137
  const dashboardRows = await page.$$('#result .order-row:not(.order-row-head)');
138
  const dashboardColumns = await page.$$('#result .order-row-head > span');
139
+ const dashboardColumnLabels = await page.$$eval('#result .order-row-head > span', elements =>
140
+ elements.map(element => element.textContent || ''));
141
  const productTitles = await page.$$eval('#result .product-thumb', elements =>
142
  elements.map(element => element.getAttribute('title') || ''));
143
+ const lineItemPreviews = await page.$$eval('#result .order-row:not(.order-row-head)', rows =>
144
+ rows.map(row => ({
145
+ orderNumber: row.children[0]?.textContent || '',
146
+ previews: row.querySelectorAll('.product-thumb').length,
147
+ count: row.querySelector('.line-item-count')?.textContent || '',
148
+ })));
149
  const selectedColors = await page.$$eval('#result .metric-card:not(.metric-total)', elements =>
150
  elements.map(element => element.style.getPropertyValue('--metric-color')));
151
  const facetCards = await page.$$eval('#result .metric-card:not(.metric-total)', elements =>
 
163
  elements.map(element => element.style.color));
164
  if (!dashboard.includes('Order Management Center') || metricCount.length !== 6
165
  || dashboardRows.length !== 4 || dashboardColumns.length !== 4
166
+ || dashboardColumnLabels.join('|') !== 'Order number|Order date|Status|Line Items'
167
  || !productTitles.some(title => title.includes('TeaQL Portable Keyboard'))
168
+ || JSON.stringify(lineItemPreviews.filter(row => row.count)) !== JSON.stringify([
169
+ { orderNumber: 'TQL-2026-1008', previews: 3, count: '5 items' },
170
+ { orderNumber: 'TQL-2026-1006', previews: 3, count: '5 items' },
171
+ ])
172
  || !cancelledMetric.text.includes('Cancelled') || !cancelledMetric.text.includes('1')
173
  || cancelledMetric.color !== '#9F1239'
174
  || JSON.stringify(facetCards) !== JSON.stringify([
source/teaql-ts/examples/browser-sqlite/src/main.ts CHANGED
@@ -548,7 +548,7 @@ async function openRuntime(storage: BrowserSQLiteStorage): Promise<Runtime> {
548
  const worker = new Worker(new URL('./sqlite.worker.ts', import.meta.url), { type: 'module' });
549
  const client = await BrowserSQLiteTeaQLClient.open(worker, { ...ORDER_SCHEMAS }, {
550
  storage,
551
- databaseName: 'teaql-order-playground-v3.sqlite3',
552
  });
553
  const evidence = new SQLExecutionEvidenceStore().enableSelect();
554
  client.install(new RuntimeModule(ORDER_SCHEMAS, {}, {
@@ -558,7 +558,7 @@ async function openRuntime(storage: BrowserSQLiteStorage): Promise<Runtime> {
558
  const policyIdentity = Object.freeze({
559
  policyId: 'browser-order-demo-seed',
560
  version: '1',
561
- fingerprint: 'sha256:browser-order-demo-seed-v1',
562
  });
563
  const context = new UserContext()
564
  .insertResource('dataService', client)
@@ -886,8 +886,8 @@ function renderDashboard(data: DashboardData, active: Runtime, query: QueryExamp
886
  const tableHeader = document.createElement('div');
887
  tableHeader.className = 'order-row order-row-head';
888
  const columnLabels = locale === 'en'
889
- ? ['Order number', 'Order date', 'Status', 'Product details']
890
- : ['订单号', '订单日期', '状态', '商品明细'];
891
  for (const label of columnLabels) {
892
  const cell = document.createElement('span');
893
  cell.textContent = label;
@@ -1000,11 +1000,15 @@ function renderOrderRow(order: Record<string, unknown>): HTMLElement {
1000
  thumb.title = `${String(item.productName ?? '')} × ${String(item.quantity ?? 1)}`;
1001
  products.append(thumb);
1002
  });
1003
- const remaining = Number(order.itemCount ?? items.length) - items.length;
1004
- if (remaining > 0) {
1005
- const more = document.createElement('small');
1006
- more.textContent = `+${remaining}`;
1007
- products.append(more);
 
 
 
 
1008
  }
1009
  row.append(products);
1010
  return row;
 
548
  const worker = new Worker(new URL('./sqlite.worker.ts', import.meta.url), { type: 'module' });
549
  const client = await BrowserSQLiteTeaQLClient.open(worker, { ...ORDER_SCHEMAS }, {
550
  storage,
551
+ databaseName: 'teaql-order-playground-v4.sqlite3',
552
  });
553
  const evidence = new SQLExecutionEvidenceStore().enableSelect();
554
  client.install(new RuntimeModule(ORDER_SCHEMAS, {}, {
 
558
  const policyIdentity = Object.freeze({
559
  policyId: 'browser-order-demo-seed',
560
  version: '1',
561
+ fingerprint: 'sha256:browser-order-demo-seed-v2',
562
  });
563
  const context = new UserContext()
564
  .insertResource('dataService', client)
 
886
  const tableHeader = document.createElement('div');
887
  tableHeader.className = 'order-row order-row-head';
888
  const columnLabels = locale === 'en'
889
+ ? ['Order number', 'Order date', 'Status', 'Line Items']
890
+ : ['订单号', '订单日期', '状态', '订单明细'];
891
  for (const label of columnLabels) {
892
  const cell = document.createElement('span');
893
  cell.textContent = label;
 
1000
  thumb.title = `${String(item.productName ?? '')} × ${String(item.quantity ?? 1)}`;
1001
  products.append(thumb);
1002
  });
1003
+ const totalItems = Number(order.itemCount ?? items.length);
1004
+ if (totalItems > items.length) {
1005
+ const count = document.createElement('small');
1006
+ count.className = 'line-item-count';
1007
+ count.textContent = locale === 'en' ? `${totalItems} items` : `共 ${totalItems} 项`;
1008
+ count.title = locale === 'en'
1009
+ ? `Showing ${items.length} of ${totalItems} line items`
1010
+ : `显示 ${items.length} 项,共 ${totalItems} 项订单明细`;
1011
+ products.append(count);
1012
  }
1013
  row.append(products);
1014
  return row;
source/teaql-ts/examples/browser-sqlite/src/order-model.ts CHANGED
@@ -204,10 +204,17 @@ export const ORDER_SEED: readonly SeedRecord[] = [
204
  { entity: 'OrderItem', id: '2005', payload: { orderId: '1003', productName: 'Pre-Qingming Longjing Tea', sku: 'TEA-LJ-100', quantity: 2, unitPrice: 80, lineAmount: 160 } },
205
  { entity: 'OrderItem', id: '2006', payload: { orderId: '1004', productName: 'Double-wall Glass Tumbler', sku: 'CUP-GLASS', quantity: 1, unitPrice: 79.9, lineAmount: 79.9 } },
206
  { entity: 'OrderItem', id: '2007', payload: { orderId: '1005', productName: 'Travel Brew Kit', sku: 'BREW-KIT', quantity: 1, unitPrice: 219, lineAmount: 219 } },
207
- { entity: 'OrderItem', id: '2008', payload: { orderId: '1006', productName: 'Desktop Studio Speaker', sku: 'SPK-STUDIO', quantity: 2, unitPrice: 260, lineAmount: 520 } },
208
- { entity: 'OrderItem', id: '2009', payload: { orderId: '1006', productName: 'Speaker Stand', sku: 'SPK-STAND', quantity: 1, unitPrice: 120, lineAmount: 120 } },
209
  { entity: 'OrderItem', id: '2010', payload: { orderId: '1007', productName: 'Desktop Reading Lamp', sku: 'LAMP-DESK', quantity: 1, unitPrice: 159, lineAmount: 159 } },
210
- { entity: 'OrderItem', id: '2011', payload: { orderId: '1008', productName: 'TeaQL Portable Keyboard', sku: 'KB-TQL-68', quantity: 1, unitPrice: 268, lineAmount: 268 } },
 
 
 
 
 
 
 
211
 
212
  { entity: 'Payment', id: '3001', payload: { orderId: '1001', provider: 'Alipay', status: 'CAPTURED', amount: 499, currency: 'CNY', transactionId: 'ALI-260828-01', paidAt: '2026-08-28T10:14:00Z' } },
213
  { entity: 'Payment', id: '3002', payload: { orderId: '1002', provider: 'WeChat Pay', status: 'CAPTURED', amount: 1299, currency: 'CNY', transactionId: 'WX-260902-08', paidAt: '2026-09-02T03:20:00Z' } },
 
204
  { entity: 'OrderItem', id: '2005', payload: { orderId: '1003', productName: 'Pre-Qingming Longjing Tea', sku: 'TEA-LJ-100', quantity: 2, unitPrice: 80, lineAmount: 160 } },
205
  { entity: 'OrderItem', id: '2006', payload: { orderId: '1004', productName: 'Double-wall Glass Tumbler', sku: 'CUP-GLASS', quantity: 1, unitPrice: 79.9, lineAmount: 79.9 } },
206
  { entity: 'OrderItem', id: '2007', payload: { orderId: '1005', productName: 'Travel Brew Kit', sku: 'BREW-KIT', quantity: 1, unitPrice: 219, lineAmount: 219 } },
207
+ { entity: 'OrderItem', id: '2008', payload: { orderId: '1006', productName: 'Desktop Studio Speaker', sku: 'SPK-STUDIO', quantity: 2, unitPrice: 200, lineAmount: 400 } },
208
+ { entity: 'OrderItem', id: '2009', payload: { orderId: '1006', productName: 'Speaker Stand', sku: 'SPK-STAND', quantity: 1, unitPrice: 80, lineAmount: 80 } },
209
  { entity: 'OrderItem', id: '2010', payload: { orderId: '1007', productName: 'Desktop Reading Lamp', sku: 'LAMP-DESK', quantity: 1, unitPrice: 159, lineAmount: 159 } },
210
+ { entity: 'OrderItem', id: '2011', payload: { orderId: '1008', productName: 'TeaQL Portable Keyboard', sku: 'KB-TQL-68', quantity: 1, unitPrice: 168, lineAmount: 168 } },
211
+ { entity: 'OrderItem', id: '2012', payload: { orderId: '1008', productName: 'Keyboard Protective Case', sku: 'KB-CASE-68', quantity: 1, unitPrice: 30, lineAmount: 30 } },
212
+ { entity: 'OrderItem', id: '2013', payload: { orderId: '1008', productName: 'Foldable Travel Stand', sku: 'KB-STAND-FOLD', quantity: 1, unitPrice: 25, lineAmount: 25 } },
213
+ { entity: 'OrderItem', id: '2014', payload: { orderId: '1008', productName: 'Braided USB-C Cable', sku: 'CABLE-USBC', quantity: 1, unitPrice: 20, lineAmount: 20 } },
214
+ { entity: 'OrderItem', id: '2015', payload: { orderId: '1008', productName: 'Accent Keycap Set', sku: 'KEYCAP-ACCENT', quantity: 1, unitPrice: 25, lineAmount: 25 } },
215
+ { entity: 'OrderItem', id: '2016', payload: { orderId: '1006', productName: 'Balanced Audio Cable', sku: 'AUDIO-XLR', quantity: 1, unitPrice: 40, lineAmount: 40 } },
216
+ { entity: 'OrderItem', id: '2017', payload: { orderId: '1006', productName: 'Speaker Isolation Pads', sku: 'SPK-PADS', quantity: 1, unitPrice: 60, lineAmount: 60 } },
217
+ { entity: 'OrderItem', id: '2018', payload: { orderId: '1006', productName: 'USB DAC Adapter', sku: 'AUDIO-DAC-USB', quantity: 1, unitPrice: 60, lineAmount: 60 } },
218
 
219
  { entity: 'Payment', id: '3001', payload: { orderId: '1001', provider: 'Alipay', status: 'CAPTURED', amount: 499, currency: 'CNY', transactionId: 'ALI-260828-01', paidAt: '2026-08-28T10:14:00Z' } },
220
  { entity: 'Payment', id: '3002', payload: { orderId: '1002', provider: 'WeChat Pay', status: 'CAPTURED', amount: 1299, currency: 'CNY', transactionId: 'WX-260902-08', paidAt: '2026-09-02T03:20:00Z' } },