jaz-clio 5.24.12 → 5.24.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/skills/api/SKILL.md +1 -1
- package/assets/skills/cli/SKILL.md +1 -1
- package/assets/skills/conversion/SKILL.md +1 -1
- package/assets/skills/jaz-pseudo-sql/SKILL.md +1 -1
- package/assets/skills/jobs/SKILL.md +1 -1
- package/assets/skills/transaction-recipes/SKILL.md +1 -1
- package/cli.mjs +2 -2
- package/package.json +1 -1
package/cli.mjs
CHANGED
|
@@ -864,7 +864,7 @@ btType enum: SALE = invoice, PURCHASE = bill, SALE_CREDIT_NOTE = customer CN, PU
|
|
|
864
864
|
|
|
865
865
|
Each result carries contactSignals (Mid-7: cadence, outliers, severity, divergences from contact's modal pattern; null if no contact / no history) and breakdown (Balance-panel payload: line items + subtotal/tax/total/balance/exchange rate). Top-level contactSignalsMeta.unavailable=true \u2192 freshness layer offline for whole batch.
|
|
866
866
|
|
|
867
|
-
USE THIS to score a specific draft against contact history. For stand-alone "what does this contact normally look like?" without a draft \u2192 use get_contact_signals.`,params:{items:{type:"array",description:"Draft business transaction references (max 500). Mix any btType freely.",items:{type:"object",properties:{btResourceId:{type:"string",description:"Draft BT resource ID (UUID) \u2014 required"},btType:{type:"string",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],description:"Required"}}}}},required:["items"],group:"drafts",readOnly:!0,isConcurrencySafe:!0,searchHint:"validate drafts eligibility check before convert promote",execute:async(t,e)=>(Cv(e.items),Nz(t.client,e.items))},{name:"convert_drafts_to_active",description:`BULK promote \u2014 finalize up to 500 draft business transactions to ACTIVE in ONE call, mixing any combination of invoices, bills, and credit notes (no per-type tools needed). ${Ll} NOT idempotent: a second call on already-promoted drafts returns 422. Filter the draft list by status: DRAFT before submitting. Pair with validate_drafts for a pre-flight check on large batches.`,params:{items:{type:"array",description:"Draft BT references (max 500). Mix any btType.",items:{type:"object",properties:{btResourceId:{type:"string",description:"Draft BT resource ID (UUID) \u2014 required"},btType:{type:"string",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],description:"Required"}}}}},required:["items"],group:"drafts",readOnly:!1,searchHint:"convert drafts to active promote finalize bulk",execute:async(t,e)=>(Cv(e.items),Oz(t.client,e.items))},{name:"submit_drafts_for_approval",description:`BULK submit \u2014 route up to 500 draft business transactions into the approval workflow in ONE call, mixing any combination of invoices, bills, and credit notes. ${Ll} NOT idempotent on drafts that already have an in-flight approval request.`,params:{items:{type:"array",description:"Draft BT references (max 500). Mix any btType.",items:{type:"object",properties:{btResourceId:{type:"string",description:"Draft BT resource ID (UUID) \u2014 required"},btType:{type:"string",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],description:"Required"}}}}},required:["items"],group:"drafts",readOnly:!1,searchHint:"submit drafts for approval workflow review bulk",execute:async(t,e)=>(Cv(e.items),Fz(t.client,e.items))},{name:"search_help_center",description:'Search the Jaz help center for how-to articles, feature guides, and accounting concepts. Use this for "how do I..." or "what is..." questions about Jaz: bank reconciliation, GST/VAT filing, multi-currency, fixed assets, custom fields, integrations, and so on. Returns top matching articles with title, section, content, and source URL.',params:{query:{type:"string",description:'Natural-language question or keywords (e.g. "how do I reconcile a bank statement", "set up GST", "multi-currency invoice").'},limit:{type:"number",description:"Maximum number of articles to return (default 3, max 10)."},section:{type:"string",description:'Optional: restrict to a single help-center section slug (e.g. "bank-reconciliations", "invoices").'}},required:["query"],group:"help_center",readOnly:!0,searchHint:"help center docs how to guide article search question",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>{let r=typeof e.limit=="number"?e.limit:void 0,n=typeof e.section=="string"?e.section:void 0;return cue(String(e.query??""),{limit:r,section:n})}},{name:"jot",description:"Record judgment entries in the org's judgment journal. THE RULE: log a judgment when you chose among real alternatives and a write followed, or when you deliberately decided NOT to write; skip mechanical actions and calls where the platform, the data, or the user left you no choice. Jot AFTER the write succeeds, never before, and carry the written record's resourceId in refs. Kinds: CLASSIFICATION account/tax/category choice \xB7 MATCH decided which records correspond \xB7 SCOPE chose what is in or out of a set \xB7 ASSUMPTION filled a gap the data left open \xB7 RISK proceeded despite a known concern \xB7 METHOD picked a calculation or approach \xB7 RECOVERY decided how to proceed after a failure (incl. holding a write) \xB7 DEVIATION knowingly departed from a stated rule. Accepting or rejecting an inbound external document (an e-invoice a counterparty sent) is a FINALIZE act, so pin it. A decided omission (you deliberately did not post something) is RECOVERY, which pins via withheld-write, not DEVIATION. Always give why: a call without a basis is half a record. Batch related entries in one call; each entry is acked independently.",params:{entries:{type:"array",description:"Judgment entries to record (1-100). A bad entry never fails the batch: it acks with error while siblings persist.",items:{type:"object",properties:{kind:{type:"string",enum:["CLASSIFICATION","MATCH","SCOPE","ASSUMPTION","RISK","METHOD","RECOVERY","DEVIATION","NOTE"],description:"Judgment kind: one-liners in the tool description."},tier:{type:"string",enum:["LOW","MEDIUM","HIGH","CRITICAL"],description:"Severity you assign the call."},call:{type:"string",description:'The decision, one line (e.g. "Posted to 6420 Travel: recurring Grab vendor pattern").'},why:{type:"string",description:"The basis for the call: a call without a basis is half a record."},ruledOut:{type:"string",description:"Alternatives considered and set aside."},refs:{type:"array",description:"Entity refs this judgment touches. Include the written record's resourceId.",items:{type:"string",description:'Grammar TYPE:resourceId[#field][:RELATION], e.g. "INVOICE:41f6\u2026:CREATE". RELATION: CREATE UPDATE DELETE FINALIZE PAY RECONCILE TRIGGER SUBJECT INPUT REJECTED SUPERSEDES (default SUBJECT).'}},frame:{type:"string",description:'For set-shaped subjects: the defining query + counts (e.g. "search_bills status=UNPAID \xB7 41 in scope, 4 deferred").'},confidence:{type:"string",enum:["LOW","MEDIUM","HIGH"],description:"Routing hint for review attention."},citedRule:{type:"string",description:"Org rule, policy, threshold, or precedent applied."},workflowLabel:{type:"string",description:"Short workflow label (e.g. month-end-close)."},agentLabel:{type:"string",description:"Self-reported product/model (e.g. jaz-clio/claude); informative, never authoritative."},idempotencyKey:{type:"string",description:"Retry key: a replay returns the existing entry, not a duplicate."}},required:["kind","tier","call"]}}},required:["entries"],group:"jots",readOnly:!1,alwaysLoaded:!0,searchHint:"jot judgment judgement journal record decision log rationale reasoning why chose ruled out classification match scope assumption risk method recovery deviation basis precedent note after write",execute:async(t,e)=>yv(t.client,e.entries)},{name:"recall",description:"Search the org's judgment journal (jots) for precedents, prior judgment calls with their basis. Check BEFORE repeating a judgment on the same entity, kind of decision, or workflow: a prior call with its why beats re-deriving from scratch; a FLAG or REJECT disposition on it is a warning, ENDORSE a strong precedent. Sort is pinned server-side (CRITICAL and withheld-write RECOVERY entries first, then newest). An empty page means no prior judgments match this filter, or none are recorded for this org yet.",params:{ref:{type:"string",description:'Entity ref filter, TYPE:resourceId (e.g. "INVOICE:41f626a3-\u2026").'},kind:{type:"string",enum:["CLASSIFICATION","MATCH","SCOPE","ASSUMPTION","RISK","METHOD","RECOVERY","DEVIATION","NOTE"],description:"Judgment kind filter."},tier:{type:"string",enum:["LOW","MEDIUM","HIGH","CRITICAL"],description:"Severity tier filter."},dispositionVerb:{type:"string",enum:["FLAG","REJECT","ENDORSE"],description:"Only entries carrying at least one disposition with this verb."},freetext:{type:"string",description:"Case-insensitive substring over call and why."},createdFrom:{type:"number",description:"Created-at lower bound, epoch ms (inclusive)."},createdTo:{type:"number",description:"Created-at upper bound, epoch ms (inclusive)."},limit:{type:"number",description:"Max results per page (1-1000, default 100)."},offset:{type:"number",description:"Page number, 0-indexed."},includeStats:{type:"boolean",description:"Include per-credential disposition counts."}},required:[],group:"jots",readOnly:!0,isConcurrencySafe:!0,searchHint:"recall search jots judgment judgement journal precedent prior decisions rationale history dispositions flagged rejected endorsed lookup why",maxResultSizeChars:2e4,execute:async(t,e)=>{let r={};for(let n of["ref","kind","tier","dispositionVerb","freetext"])typeof e[n]=="string"&&e[n]&&(r[n]=e[n]);for(let n of["createdFrom","createdTo"])typeof e[n]=="number"&&(r[n]=e[n]);return EH(t.client,{...typeof e.limit=="number"?{limit:e.limit}:{},...typeof e.offset=="number"?{offset:e.offset}:{},...Object.keys(r).length?{filter:r}:{},...e.includeStats===!0?{includeStats:!0}:{}})}},{name:"present_questions",description:`Present the user with a bounded multiple-choice question (or a short sequence of them) as an interactive pick-list, instead of asking in prose. Use as your FINAL action when the user must choose among a KNOWN, finite set of options you ALREADY have from context (a prior search/list result, org defaults, or your own knowledge) to continue (e.g. "which bank account?", "which of these duplicate bills?"). Give 2-4 options per question \u2014 curate to the most likely, never dump a long list \u2014 and at most 4 questions; set multiSelect per question when more than one may apply. List the options and stop \u2014 the user's pick arrives as their next message and starts a new turn. Ask several questions at once when more than one thing is unspecified. Prose-ask only when there's no bounded set to offer (a free-text name or amount), to confirm destructive actions, or instead of fetching data just to populate options. Terminal: do not call further tools or re-list the options in text afterward.`,params:{questions:{type:"array",description:"Questions to ask, each rendered as one page of the pick-list (at most 4). Provide one unless you genuinely have several distinct choices to collect in sequence.",items:{type:"object",properties:{header:{type:"string",description:'Optional short eyebrow label categorizing the question (1-2 words, e.g. "Account", "Period").'},question:{type:"string",description:'The question, shown as the card title (e.g. "Which bank account should I inspect?").'},options:{type:"array",description:"2-4 concrete choices (hard cap \u2014 curate to the most likely; the user can still type a different answer if none fit).",items:{type:"object",properties:{label:{type:"string",description:"The choice shown on the row and relayed verbatim as the user's answer when picked \u2014 keep it self-contained and unambiguous."},description:{type:"string",description:'Optional one-line detail under the label (e.g. "554 unreconciled records").'}},required:["label"]}},multiSelect:{type:"boolean",description:"Set true to let the user select multiple options for this question; omit or false for a single pick."}},required:["question","options"]}}},required:["questions"],group:"interaction",alwaysLoaded:!0,interactive:!0,readOnly:!0,isConcurrencySafe:!0,searchHint:"present questions options choices pick select ask user interactive widget",maxResultSizeChars:2e4,execute:async(t,e)=>{let n=(Array.isArray(e?.questions)?e.questions:[]).filter(o=>typeof o=="object"&&o!==null).map(o=>{let s=(Array.isArray(o.options)?o.options:[]).filter(c=>typeof c=="object"&&c!==null).map(c=>{let u=String(c.label??"").trim();return c.description?{label:u,description:String(c.description)}:{label:u}}).filter(c=>c.label),a=String(o.question??"").trim();return{...o.header?{header:String(o.header)}:{},question:a,options:s,multiSelect:!!o.multiSelect}}).filter(o=>o.question&&o.options.length>=2);if(n.length===0)return{error:"present_questions needs at least one question with non-empty question text and \u22652 labeled options (a single-option pick-list is not a choice).",hint:"Provide questions: [{ question, options: [{ label }, { label }] }]. For open-ended input, ask in prose instead."};if(n.length>4)return{error:`present_questions renders at most 4 questions (got ${n.length}).`,hint:"Ask the 4 most important now; collect the rest on a later turn."};let i=n.find(o=>o.options.length>4);return i?{error:`Each question may offer at most 4 options ("${i.question}" has ${i.options.length}).`,hint:"Curate to the 4 most likely choices \u2014 the user can still type a different answer if none fit."}:{questions:n}}},{name:"navigate",description:'Dashboard navigation: discover destinations, then build deep links. Without `destination`: lists valid destinations as { key, label, kind } \u2014 filter with `query` (substring over key + label), `resource` (e.g. "sales"), or `kind` ("screen" | "modal"); results are capped, narrow if `truncated`. With `destination`: builds the URL to hand the user \u2014 a screen (e.g. "reports.profit-and-loss") or a record modal (e.g. "sales.modal.view-sale"); pass `resourceId` only for a record-specific modal (view/edit one record), never for screens or create/"new" modals. Returns { url, kind, label }; the link opens in the user\'s current org. Never write dashboard URLs or destination keys from memory \u2014 call with no destination to discover keys first.',params:{destination:{type:"string",description:'Destination key to link to, e.g. "reports.profit-and-loss" or "sales.modal.view-sale". Omit to discover valid keys instead.'},resourceId:{type:"string",description:"Jaz resourceId of the record to focus \u2014 only with a record-modal destination (view/edit a specific record). Omit for screens and create modals."},query:{type:"string",description:'Discovery only: case-insensitive substring over destination keys and labels (e.g. "invoice", "p&l", "bank").'},resource:{type:"string",description:'Discovery only: restrict to one resource namespace, e.g. "sales", "purchases", "reports", "settings".'},kind:{type:"string",description:'Discovery only: restrict to "screen" (list/report pages) or "modal" (record view/create/edit).',enum:["screen","modal"]}},required:[],group:"navigation",alwaysLoaded:!0,readOnly:!0,isConcurrencySafe:!0,aliases:["find_dashboard_destinations","get_dashboard_url"],searchHint:"dashboard url deep link navigate go to open screen record modal page share shareable list destinations keys catalog",maxResultSizeChars:16e3,execute:async(t,e)=>{let r=typeof e.destination=="string"&&e.destination?e.destination:void 0,n=typeof e.resourceId=="string"&&e.resourceId?e.resourceId:void 0;if(!r){if(n)return{error:"resourceId given without destination - pass the record-modal destination key, or omit resourceId to discover destinations."};let o=e.kind==="screen"||e.kind==="modal"?e.kind:void 0,s=uQe({query:typeof e.query=="string"?e.query:void 0,resource:typeof e.resource=="string"?e.resource:void 0,kind:o});return s.truncated?{...s,hint:`Showing ${s.results.length} of ${s.total} matches. Narrow with a more specific query, resource, or kind.`}:s.results.length===0?{...s,hint:'No matches. Destinations are named by product area, not task wording \u2014 retry with a broader or synonym term (e.g. "billing" not "card", "sales" not "invoice payment", "settings", "reports", "bank") before concluding the destination does not exist.'}:s}let{dashboardUrl:i}=iQe(t.platform??"jaz");try{return lQe(r,n,{dashboardUrl:i,orgResourceId:t.org?.resourceId})}catch(o){return{error:o instanceof Error?o.message:String(o)}}}}];rQe(Mc)});function nCr(){if(!Iv){Iv=new Map;for(let t of Mc)Iv.set(t.name,t);for(let t of Mc)for(let e of t.aliases??[])Iv.has(e)||Iv.set(e,t)}return Iv}function df(t){return nCr().get(t)}function aT(){return Gue||(Gue=Mc.filter(t=>!t.disabled)),Gue}function oCr(){return Jue||(Jue=aT().filter(t=>!t.interactive)),Jue}function Ent(t){return t!==void 0&&iCr.has(t)?aT():oCr()}function Jh(t){return aT().filter(e=>e.group===t)}var Iv,Gue,iCr,Jue,hy=X(()=>{"use strict";sT();Iv=null,Gue=null;iCr=new Set(["chat"]),Jue=null});var Cnt={};Ja(Cnt,{default:()=>aCr,log:()=>Vue});var wv,sCr,Vue,aCr,vnt=X(()=>{"use strict";wv=()=>{},sCr=()=>Vue,Vue={info:wv,warn:wv,error:wv,debug:wv,trace:wv,fatal:wv,child:sCr,level:"silent"},aCr=Vue});function pct(t,e=5){let r=t.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_-]+/).filter(o=>o.length>=2&&!GIr.has(o));return n.length===0?[]:qc.map(o=>{let s=0,a=o.name.toLowerCase(),c=o.description.toLowerCase();(a===r||a===r.replace(/\s+/g,"_"))&&(s+=5),a.includes(r)&&(s+=3),c.includes(r)&&(s+=1);for(let u of n)a.includes(u)&&(s+=2),c.includes(u)&&(s+=1);return{ns:o,score:s}}).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).slice(0,e).map(o=>o.ns)}var qc,GIr,OT=X(()=>{"use strict";qc=[{name:"invoices",description:"Sales invoices (INV/SI). Create, search, get, update, delete, pay, finalize, apply credits, download PDF. Also: receivables, AR, AR aging, billing, overdue invoices, dunning, recurring invoices. To create from an uploaded invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["invoices"]},{name:"customer_credit_notes",description:"Customer credit notes (CN). Create, search, update, delete, finalize, refund, download PDF. Also: sales returns, customer CN.",groups:["customer_credit_notes"]},{name:"bills",description:"Purchase bills (PO/PI). Create, search, get, update, delete, pay, finalize, apply credits. Also: payables, AP, vendor invoices, supplier bills. To create from an uploaded bill/invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["bills"]},{name:"supplier_credit_notes",description:"Supplier credit notes. Create, search, update, delete, finalize, refund. Also: purchase returns, debit notes, supplier CN.",groups:["supplier_credit_notes"]},{name:"sale_orders",description:"Sales order documents: Sale Quotes (estimates/quotations) and Sale Orders. Create, get, search, update, and transition (accept a quote, confirm an order, void, delete). A Sale Order links to its quote via saleQuoteResourceId; the quote must be accepted first. Tracks fulfillment via orderState. Pipeline: quote \u2192 order \u2192 invoice (raise the invoice separately).",groups:["sale_orders"]},{name:"purchase_orders",description:"Purchase order documents: Purchase Requests (requisitions) and Purchase Orders (POs). Create, get, search, update, and transition (accept a request, confirm an order, void, delete). A Purchase Order links to its request via purchaseRequestResourceId; the request must be accepted first. Tracks fulfillment via orderState. Pipeline: request \u2192 order \u2192 bill (raise the bill separately).",groups:["purchase_orders"]},{name:"journals",description:"Journal entries (JE). Create, search, update, delete manual journals. Also: adjusting entries, accruals, reclassifications, corrections.",groups:["journals"]},{name:"cash_entries",description:"Cash-in receipts and cash-out disbursements for external cash movements. WHEN TO USE: money received from customers/external \u2192 cash-in. Money paid to suppliers/external \u2192 cash-out. For internal account-to-account transfers, use cash_transfers namespace.",groups:["cash_entries"]},{name:"cash_transfers",description:"Cash transfers between your own bank/cash accounts and cashflow transaction search. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). For external receipts/payments, use cash_entries namespace.",groups:["cash_transfers"]},{name:"bank_accounts",description:"Bank accounts, bank statement imports (CSV/OFX), bank records search, auto-reconciliation. For unreconciled queries: ALWAYS search bank records with status UNRECONCILED after listing accounts. Also: bank feeds, bank balance.",groups:["bank"]},{name:"bank_rules",description:"Bank reconciliation rules (action shortcuts). Create, search, update, delete bank rules. Configure auto-matching rules for bank records.",groups:["bank_rules"]},{name:"reconciliations",description:"Apply a reconciliation decision to a bank statement entry \u2014 write side. Match bank records to EXISTING open bills/invoices/payments (reconcile_with_payments \u2014 the primary path, creates the payment for you), or to journals, cash entries, or transfers, or CREATE new bills/invoices (invoice_receipt/bill_receipt). Distinct from bank_accounts/bank_rules (which configure auto-reconciliation) and view_auto_reconciliation (which queries suggestions). Eleven endpoints: quick_reconcile + apply_bank_rule + magic_match (bulk), and direct_cash_entry / cash_journal / manual_journal / cash_transfer / invoice_receipt / bill_receipt / with_payments / learned_prediction (per-entry). Match-to-existing is preferred over create-new to avoid duplicates. Most fields prefill from the bank entry when omitted; FX is resolved server-side.",groups:["reconciliations"]},{name:"financial_reports",description:"Core financial statements: trial balance (TB), balance sheet (BS/B/S), profit & loss (PnL/P&L/income statement), cash flow, general ledger (GL), cash balance/position, equity movement, VAT/GST ledger. Also: how profitable, what is the balance. XLSX/PDF file exports of any of these statements are produced via download_export (lives in operational_reports namespace \u2014 switch there or call by name).",groups:["financial_reports"]},{name:"operational_reports",description:"Aging and operational reports: aged receivables (AR aging), aged payables (AP aging), AR report, bank balance summary, bank reconciliation reports, fixed asset (FA) summary, FA reconciliation. Data exports (CSV/Excel/XLSX). Anomaly detection and audit analysis: anomalous invoices, anomalous bills, cashflow anomalies, GL journal audit, exchange rate audit, receivables customer risk, cash expense health. Also: overdue analysis, how much owed, suspicious transactions, audit trail.",groups:["operational_reports","exports"]},{name:"pseudo_sql",description:"Pseudo-SQL ad-hoc read-only queries against the curated reporting schema (custom select, custom report, query data, run sql). Includes live schema introspection (get_pseudo_sql_schema) + sync preview (\u2264100 rows) + async CSV export. Use when search_* / download_export canonical reports don't cover the question.",groups:["pseudo_sql"]},{name:"contacts",description:"Contacts (customers/suppliers/vendors), contact groups, customer segmentation. Create, search, get, update, delete contacts. Bulk upsert contacts from CSV / spreadsheet imports \u2014 async, returns jobId, poll background_jobs. List/create contact groups.",groups:["contacts","contact_groups"]},{name:"items_and_inventory",description:"Products, services, inventory items. Create, search, get, update, delete items. Check inventory balance. List/search purchase-side catalog items. Also: SKU, catalog, stock.",groups:["items","inventory","purchase_items"]},{name:"catalogs",description:"Catalogs \u2014 named groupings of products/services, optionally scoped to contact groups. Create, search, get, update, delete catalogs.",groups:["catalogs"]},{name:"tags_and_custom_fields",description:"Tags for categorizing transactions. Custom fields for adding metadata (text, date, dropdown). Create, search, delete tags and custom fields.",groups:["tags","custom_fields"]},{name:"nano_classifiers",description:"Nano classifiers (tracking categories/dimensions). List, search, create, update, delete classifiers and their classes. Used for line-item tagging and dimensional reporting. Also: tracking categories, cost centers, departments, projects.",groups:["nano_classifiers"]},{name:"chart_of_accounts",description:"Chart of accounts (COA/GL accounts). Create, search, update accounts \u2014 including setting or removing an account's period lock date (lock / unlock a period, lock date: block recording or editing transactions on the account dated on or before a date). Bookmarks (favorites/shortcuts). Also: ledger codes, account types.",groups:["accounts","bookmarks"]},{name:"currencies",description:"Currencies, exchange rates (FX/forex). List/add org currencies. Set, update, import currency rates. Also: multi-currency, FX rates.",groups:["currencies"]},{name:"tax_profiles",description:"Tax profiles (GST/VAT/sales tax), withholding tax codes (WHT/ATC). Search, create, update tax profiles. List WHT codes.",groups:["tax_profiles"]},{name:"claim_settings",description:"Employee-expense claim configuration (Settings -> Claim Settings): claim types (expense categories) and claim profiles (per-employee policy: approver, limits, visible types, balance account). Full CRUD + search on each.",groups:["claim_types","claim_profiles"]},{name:"posting_rules",description:"Claim posting rules \u2014 how approved employee-expense claims group into journals at conversion (outer/inner grouping axes, line templates, default reimbursement bank). Full CRUD + search.",groups:["posting_rules"]},{name:"claims",description:'Employee-expense claims (the Claims area / Employees). Search, get, update DRAFT claims (line items, employee, vendor), and drive the lifecycle: submit, approve, reject, cancel, unpost (reverse conversion), delete. Status flow DRAFT \u2192 SUBMITTED \u2192 APPROVED \u2192 CONVERTED ("Processed"), or REJECTED / CANCELLED. Claims are born via document attachment / conversion (no bare create); the server enforces legal transitions.',groups:["claims"]},{name:"claim_processing",description:"Process employee-expense claims: convert APPROVED claims into journal entries (preview + commit, books-only \u2014 no real-money disburse), record books-only employee payouts (reimbursements / advances) and search them, run bulk claim actions (submit / approve / reject / cancel / delete many at once \u2014 asynchronous, returns a background-job handle to poll), plus the claim tracking-tag and custom-field-value pickers.",groups:["claim_processing"]},{name:"employees",description:"Employees (expense-claim members): create, update, get, delete, and search employees; search the employee-balance directory (reimbursement balances owed); bind a login user to an employee (permanent); and bulk-import employees from a sheet (preprocess preview \u2192 async import). Archive an employee with update active=false rather than deleting.",groups:["employees"]},{name:"capsules_and_recipes",description:"Capsules (transaction groupings/capsule types). Financial recipes: amortization, depreciation, deferred revenue, IFRS 16 leases, hire purchase, fixed deposits, FX revaluation, loan schedules, ECL/expected credit loss, IAS 37 provisions, asset disposal. Two recipe execution paths: offline (plan_recipe + execute_recipe \u2014 client-side calculators, no API key) and server-side (list/get/preview/resume/rollback_capsule_recipe \u2014 produce real capsule entities via Jaz API). Plus capsuleRecipe payload on trigger mutations (create_bill, create_journal, create_cash_in, etc.) to create and trigger a recipe in one shot, with optional templateOverrides to customize the generated text (Customize Recipe). Keywords: calculate, provision, schedule, expected credit loss, revaluation, amortize, rollback recipe, customize template overrides slots.",groups:["capsules","recipes","capsule_recipes"]},{name:"scheduled_transactions",description:"Scheduled/recurring invoices, bills, journals. Create scheduled invoices/bills/journals, search scheduled transactions. Also: recurring, auto-generate.",groups:["schedulers"]},{name:"subscriptions",description:"Subscriptions (recurring billing/payment plans). Create, update, cancel, search subscriptions. Also: recurring charges, subscription schedules.",groups:["subscriptions"]},{name:"organization",description:"Organization info (name, currency, country, fiscal year). User management: invite, update, remove, search org users. Bulk invite. List enabled modules (org features/capabilities). List/search saved report templates.",groups:["organization","org_users","modules","report_templates"]},{name:"document_ai",description:'File attachments, spreadsheets, and document AI. Read and parse rows from attached spreadsheets \u2014 CSV, Excel, XLSX. Scan a single invoice / bill / receipt PDF or image to create a draft bill or invoice via AI extraction (create_bt_from_attachment, with the file or a sourceUrl). Auto-sort a whole FOLDER, a .zip, or a Dropbox / Google Drive / OneDrive folder share link of mixed paperwork \u2014 "create docs from this Dropbox folder link", a pile/batch of invoices and bills \u2014 into invoices, bills, credit notes, and bank statements with classify_documents, then create the drafts with extract_documents. Upload and list attachments; track extraction workflows.',groups:["attachments","magic"]},{name:"fixed_assets",description:"Fixed assets (PP&E/property, plant, equipment). Search, create, update, discard, sell, transfer, undo disposal. Also: depreciation, asset register.",groups:["fixed_assets"]},{name:"payments_and_search",description:"Payment records: get, update, delete individual payments. List payments/credits on invoices and bills. Reverse credit applications. Cashflow transaction search. Universal cross-entity search. Also: payment run, batch payment, payment matching, void payment, payment history, credit note applications.",groups:["payments","cashflow","search"]},{name:"quick_fix",description:"Quick Fix: bulk-update multiple transactions or line items in one call. Change dates, contacts, tags, accounts, tax profiles, custom fields across many invoices/bills/journals/credit-notes/cash-entries/schedulers at once. Also: batch update, mass edit.",groups:["quick_fix"]},{name:"export_records",description:"Export records to XLSX. List available columns, preview export scope (row count + sample), generate export file with pre-signed download URL. Supports any entity type: invoices, bills, contacts, items, journals, bank records, cashflow, fixed assets, etc. Pass query (structured search syntax) or filter (JSON), never both.",groups:["export_records"]},{name:"background_jobs",description:"Background job tracking. Poll any async operation by jobId (contacts bulk-upsert, items bulk-upsert, bank import, magic file processing, etc.). Filter by resourceId field to look up a specific job. Poll until status is SUCCESS, FAILED, or PARTIAL_SUCCESS.",groups:["background_jobs"]},{name:"drafts",description:"Draft business transactions \u2014 both local payload validation (invoices, bills, journals, credit notes) AND BULK-FRIENDLY server-side lifecycle: validate_drafts (sync eligibility check), convert_drafts_to_active (async promote to ACTIVE), submit_drafts_for_approval (async route to approval). The lifecycle tools are GENERIC and BULK \u2014 one call accepts up to 500 items mixing any combination of {btResourceId, btType: SALE|PURCHASE|SALE_CREDIT_NOTE|PURCHASE_CREDIT_NOTE}. No need for per-entity tools when promoting/submitting drafts at scale. NOT idempotent on already-promoted drafts.",groups:["drafts"]},{name:"help_center",description:"Search the Jaz help center for how-to articles, feature guides, accounting concepts, and troubleshooting. Returns top matches with title, section, snippet, and source URL. Works without an API key.",groups:["help_center"]},{name:"jots",description:"The judgment journal. jot records a judgment call (chose among real alternatives and wrote, or deliberately held a write); recall looks up prior judgments and precedents by entity, kind, or freetext. Also: decision log, rationale, why.",groups:["jots"]},{name:"navigation",description:"Dashboard navigation deep links. Build a URL to any dashboard screen or record for the user \u2014 including the view link for a record just created or updated (a reply reporting on a record carries its link, and dashboard URLs always come from this tool, never written from memory). Also: open, go to, take me to, link, deep link, share a link, url, navigate, show me the page/screen, where can I see \u2014 for invoices, bills, reports, settings, or a specific transaction.",groups:["navigation"]}],GIr=new Set(["a","an","and","are","at","be","by","can","do","does","for","how","i","in","is","it","me","my","of","on","or","our","please","that","the","this","to","us","we","what","when","where","which","with","you","your"])});function O8(t){let e={type:t.type};if(t.description&&(e.description=t.description),t.enum&&(e.enum=t.enum),t.type==="array"&&t.items&&(e.items=O8(t.items)),t.type==="object"&&t.properties){let r={};for(let[n,i]of Object.entries(t.properties))r[n]=O8(i);e.properties=r,t.required?.length&&(e.required=t.required)}return e}function hf(t,e){let r={};for(let[n,i]of Object.entries(t))r[n]=O8(i);return{type:"object",properties:r,...e.length>0?{required:e}:{}}}function yy(t){return{name:t.name,description:t.description,input_schema:hf(t.params,t.required),...t.searchHint?{searchHint:t.searchHint}:{}}}var FT=X(()=>{"use strict"});function QT(t){if(typeof t!="string")return t.isDestructive??!1;let e=t;return e.startsWith("delete_")||e.startsWith("pay_")||e.startsWith("finalize_")||e.includes("refund")||e==="remove_org_user"}function F8(t){return{readOnlyHint:t.readOnly,destructiveHint:!t.readOnly&&QT(t),idempotentHint:t.readOnly,openWorldHint:t.openWorld??!1}}function hct(t){if(!t.trim())return{namespaces:qc.map(i=>{let o=i.groups.flatMap(s=>Jh(s));return{name:i.name,description:i.description,toolCount:o.length,tools:o.map(s=>s.name)}}),hint:"Call describe_tools with specific tool names to get full schemas before executing."};let e=pct(t,5);if(e.length===0)return{matches:[],hint:`No tools match "${t}". Try broader terms or call search_tools with empty query to see all namespaces.`};let n=t.toLowerCase().split(/\s+/).filter(Boolean);return{matches:e.map(i=>{let o=i.groups.flatMap(u=>Jh(u)),s=o.map(u=>`${u.name} ${(u.aliases??[]).join(" ")} ${u.searchHint??""} ${u.description}`.toLowerCase()),a=new Map(n.map(u=>{let d=s.filter(f=>f.includes(u)).length;return[u,Math.log((o.length+1)/(d+1))]})),c=o.map((u,d)=>{let f=s[d],p=n.reduce((h,m)=>f.includes(m)?h+(a.get(m)??0):h,0);return{tool:u,score:p}}).sort((u,d)=>d.score-u.score);return{namespace:i.name,description:i.description,tools:c.map(u=>({name:u.tool.name,description:u.tool.description.split(`
|
|
867
|
+
USE THIS to score a specific draft against contact history. For stand-alone "what does this contact normally look like?" without a draft \u2192 use get_contact_signals.`,params:{items:{type:"array",description:"Draft business transaction references (max 500). Mix any btType freely.",items:{type:"object",properties:{btResourceId:{type:"string",description:"Draft BT resource ID (UUID) \u2014 required"},btType:{type:"string",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],description:"Required"}}}}},required:["items"],group:"drafts",readOnly:!0,isConcurrencySafe:!0,searchHint:"validate drafts eligibility check before convert promote",execute:async(t,e)=>(Cv(e.items),Nz(t.client,e.items))},{name:"convert_drafts_to_active",description:`BULK promote \u2014 finalize up to 500 draft business transactions to ACTIVE in ONE call, mixing any combination of invoices, bills, and credit notes (no per-type tools needed). ${Ll} NOT idempotent: a second call on already-promoted drafts returns 422. Filter the draft list by status: DRAFT before submitting. Pair with validate_drafts for a pre-flight check on large batches.`,params:{items:{type:"array",description:"Draft BT references (max 500). Mix any btType.",items:{type:"object",properties:{btResourceId:{type:"string",description:"Draft BT resource ID (UUID) \u2014 required"},btType:{type:"string",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],description:"Required"}}}}},required:["items"],group:"drafts",readOnly:!1,searchHint:"convert drafts to active promote finalize bulk",execute:async(t,e)=>(Cv(e.items),Oz(t.client,e.items))},{name:"submit_drafts_for_approval",description:`BULK submit \u2014 route up to 500 draft business transactions into the approval workflow in ONE call, mixing any combination of invoices, bills, and credit notes. ${Ll} NOT idempotent on drafts that already have an in-flight approval request.`,params:{items:{type:"array",description:"Draft BT references (max 500). Mix any btType.",items:{type:"object",properties:{btResourceId:{type:"string",description:"Draft BT resource ID (UUID) \u2014 required"},btType:{type:"string",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],description:"Required"}}}}},required:["items"],group:"drafts",readOnly:!1,searchHint:"submit drafts for approval workflow review bulk",execute:async(t,e)=>(Cv(e.items),Fz(t.client,e.items))},{name:"search_help_center",description:'Search the Jaz help center for how-to articles, feature guides, and accounting concepts. Use this for "how do I..." or "what is..." questions about Jaz: bank reconciliation, GST/VAT filing, multi-currency, fixed assets, custom fields, integrations, and so on. Returns top matching articles with title, section, content, and source URL.',params:{query:{type:"string",description:'Natural-language question or keywords (e.g. "how do I reconcile a bank statement", "set up GST", "multi-currency invoice").'},limit:{type:"number",description:"Maximum number of articles to return (default 3, max 10)."},section:{type:"string",description:'Optional: restrict to a single help-center section slug (e.g. "bank-reconciliations", "invoices").'}},required:["query"],group:"help_center",readOnly:!0,searchHint:"help center docs how to guide article search question",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>{let r=typeof e.limit=="number"?e.limit:void 0,n=typeof e.section=="string"?e.section:void 0;return cue(String(e.query??""),{limit:r,section:n})}},{name:"jot",description:"Record judgment entries in the org's judgment journal. THE RULE: log a judgment when you chose among real alternatives and a write followed, or when you deliberately decided NOT to write; skip mechanical actions and calls where the platform, the data, or the user left you no choice. Jot AFTER the write succeeds, never before, and carry the written record's resourceId in refs. Kinds: CLASSIFICATION account/tax/category choice \xB7 MATCH decided which records correspond \xB7 SCOPE chose what is in or out of a set \xB7 ASSUMPTION filled a gap the data left open \xB7 RISK proceeded despite a known concern \xB7 METHOD picked a calculation or approach \xB7 RECOVERY decided how to proceed after a failure (incl. holding a write) \xB7 DEVIATION knowingly departed from a stated rule. Accepting or rejecting an inbound external document (an e-invoice a counterparty sent) is a FINALIZE act, so pin it. A decided omission (you deliberately did not post something) is RECOVERY, which pins via withheld-write, not DEVIATION. Always give why: a call without a basis is half a record. Batch related entries in one call; each entry is acked independently.",params:{entries:{type:"array",description:"Judgment entries to record (1-100). A bad entry never fails the batch: it acks with error while siblings persist.",items:{type:"object",properties:{kind:{type:"string",enum:["CLASSIFICATION","MATCH","SCOPE","ASSUMPTION","RISK","METHOD","RECOVERY","DEVIATION","NOTE"],description:"Judgment kind: one-liners in the tool description."},tier:{type:"string",enum:["LOW","MEDIUM","HIGH","CRITICAL"],description:"Severity you assign the call."},call:{type:"string",description:'The decision, one line (e.g. "Posted to 6420 Travel: recurring Grab vendor pattern").'},why:{type:"string",description:"The basis for the call: a call without a basis is half a record."},ruledOut:{type:"string",description:"Alternatives considered and set aside."},refs:{type:"array",description:"Entity refs this judgment touches. Include the written record's resourceId.",items:{type:"string",description:'Grammar TYPE:resourceId[#field][:RELATION], e.g. "INVOICE:41f6\u2026:CREATE". RELATION: CREATE UPDATE DELETE FINALIZE PAY RECONCILE TRIGGER SUBJECT INPUT REJECTED SUPERSEDES (default SUBJECT).'}},frame:{type:"string",description:'For set-shaped subjects: the defining query + counts (e.g. "search_bills status=UNPAID \xB7 41 in scope, 4 deferred").'},confidence:{type:"string",enum:["LOW","MEDIUM","HIGH"],description:"Routing hint for review attention."},citedRule:{type:"string",description:"Org rule, policy, threshold, or precedent applied."},workflowLabel:{type:"string",description:"Short workflow label (e.g. month-end-close)."},agentLabel:{type:"string",description:"Self-reported product/model (e.g. jaz-clio/claude); informative, never authoritative."},idempotencyKey:{type:"string",description:"Retry key: a replay returns the existing entry, not a duplicate."}},required:["kind","tier","call"]}}},required:["entries"],group:"jots",readOnly:!1,alwaysLoaded:!0,searchHint:"jot judgment judgement journal record decision log rationale reasoning why chose ruled out classification match scope assumption risk method recovery deviation basis precedent note after write",execute:async(t,e)=>yv(t.client,e.entries)},{name:"recall",description:"Search the org's judgment journal (jots) for precedents, prior judgment calls with their basis. Check BEFORE repeating a judgment on the same entity, kind of decision, or workflow: a prior call with its why beats re-deriving from scratch; a FLAG or REJECT disposition on it is a warning, ENDORSE a strong precedent. Sort is pinned server-side (CRITICAL and withheld-write RECOVERY entries first, then newest). An empty page means no prior judgments match this filter, or none are recorded for this org yet.",params:{ref:{type:"string",description:'Entity ref filter, TYPE:resourceId (e.g. "INVOICE:41f626a3-\u2026").'},kind:{type:"string",enum:["CLASSIFICATION","MATCH","SCOPE","ASSUMPTION","RISK","METHOD","RECOVERY","DEVIATION","NOTE"],description:"Judgment kind filter."},tier:{type:"string",enum:["LOW","MEDIUM","HIGH","CRITICAL"],description:"Severity tier filter."},dispositionVerb:{type:"string",enum:["FLAG","REJECT","ENDORSE"],description:"Only entries carrying at least one disposition with this verb."},freetext:{type:"string",description:"Case-insensitive substring over call and why."},createdFrom:{type:"number",description:"Created-at lower bound, epoch ms (inclusive)."},createdTo:{type:"number",description:"Created-at upper bound, epoch ms (inclusive)."},firstParty:{type:"boolean",description:"true = only entries from Jaz-operated agent surfaces (server-stamped origin, never self-reported); false = only external and pre-stamp entries. Omit for all."},pinned:{type:"boolean",description:"true = only pinned entries (critical or withheld-write, the same predicate the pinned sort uses); false = only unpinned. Omit for all."},limit:{type:"number",description:"Max results per page (1-1000, default 100)."},offset:{type:"number",description:"Page number, 0-indexed."},includeStats:{type:"boolean",description:"Include per-credential disposition counts."}},required:[],group:"jots",readOnly:!0,isConcurrencySafe:!0,searchHint:"recall search jots judgment judgement journal precedent prior decisions rationale history dispositions flagged rejected endorsed first party jaz agents pinned lookup why",maxResultSizeChars:2e4,execute:async(t,e)=>{let r={};for(let n of["ref","kind","tier","dispositionVerb","freetext"])typeof e[n]=="string"&&e[n]&&(r[n]=e[n]);for(let n of["createdFrom","createdTo"])typeof e[n]=="number"&&(r[n]=e[n]);for(let n of["firstParty","pinned"])typeof e[n]=="boolean"&&(r[n]=e[n]);return EH(t.client,{...typeof e.limit=="number"?{limit:e.limit}:{},...typeof e.offset=="number"?{offset:e.offset}:{},...Object.keys(r).length?{filter:r}:{},...e.includeStats===!0?{includeStats:!0}:{}})}},{name:"present_questions",description:`Present the user with a bounded multiple-choice question (or a short sequence of them) as an interactive pick-list, instead of asking in prose. Use as your FINAL action when the user must choose among a KNOWN, finite set of options you ALREADY have from context (a prior search/list result, org defaults, or your own knowledge) to continue (e.g. "which bank account?", "which of these duplicate bills?"). Give 2-4 options per question \u2014 curate to the most likely, never dump a long list \u2014 and at most 4 questions; set multiSelect per question when more than one may apply. List the options and stop \u2014 the user's pick arrives as their next message and starts a new turn. Ask several questions at once when more than one thing is unspecified. Prose-ask only when there's no bounded set to offer (a free-text name or amount), to confirm destructive actions, or instead of fetching data just to populate options. Terminal: do not call further tools or re-list the options in text afterward.`,params:{questions:{type:"array",description:"Questions to ask, each rendered as one page of the pick-list (at most 4). Provide one unless you genuinely have several distinct choices to collect in sequence.",items:{type:"object",properties:{header:{type:"string",description:'Optional short eyebrow label categorizing the question (1-2 words, e.g. "Account", "Period").'},question:{type:"string",description:'The question, shown as the card title (e.g. "Which bank account should I inspect?").'},options:{type:"array",description:"2-4 concrete choices (hard cap \u2014 curate to the most likely; the user can still type a different answer if none fit).",items:{type:"object",properties:{label:{type:"string",description:"The choice shown on the row and relayed verbatim as the user's answer when picked \u2014 keep it self-contained and unambiguous."},description:{type:"string",description:'Optional one-line detail under the label (e.g. "554 unreconciled records").'}},required:["label"]}},multiSelect:{type:"boolean",description:"Set true to let the user select multiple options for this question; omit or false for a single pick."}},required:["question","options"]}}},required:["questions"],group:"interaction",alwaysLoaded:!0,interactive:!0,readOnly:!0,isConcurrencySafe:!0,searchHint:"present questions options choices pick select ask user interactive widget",maxResultSizeChars:2e4,execute:async(t,e)=>{let n=(Array.isArray(e?.questions)?e.questions:[]).filter(o=>typeof o=="object"&&o!==null).map(o=>{let s=(Array.isArray(o.options)?o.options:[]).filter(c=>typeof c=="object"&&c!==null).map(c=>{let u=String(c.label??"").trim();return c.description?{label:u,description:String(c.description)}:{label:u}}).filter(c=>c.label),a=String(o.question??"").trim();return{...o.header?{header:String(o.header)}:{},question:a,options:s,multiSelect:!!o.multiSelect}}).filter(o=>o.question&&o.options.length>=2);if(n.length===0)return{error:"present_questions needs at least one question with non-empty question text and \u22652 labeled options (a single-option pick-list is not a choice).",hint:"Provide questions: [{ question, options: [{ label }, { label }] }]. For open-ended input, ask in prose instead."};if(n.length>4)return{error:`present_questions renders at most 4 questions (got ${n.length}).`,hint:"Ask the 4 most important now; collect the rest on a later turn."};let i=n.find(o=>o.options.length>4);return i?{error:`Each question may offer at most 4 options ("${i.question}" has ${i.options.length}).`,hint:"Curate to the 4 most likely choices \u2014 the user can still type a different answer if none fit."}:{questions:n}}},{name:"navigate",description:'Dashboard navigation: discover destinations, then build deep links. Without `destination`: lists valid destinations as { key, label, kind } \u2014 filter with `query` (substring over key + label), `resource` (e.g. "sales"), or `kind` ("screen" | "modal"); results are capped, narrow if `truncated`. With `destination`: builds the URL to hand the user \u2014 a screen (e.g. "reports.profit-and-loss") or a record modal (e.g. "sales.modal.view-sale"); pass `resourceId` only for a record-specific modal (view/edit one record), never for screens or create/"new" modals. Returns { url, kind, label }; the link opens in the user\'s current org. Never write dashboard URLs or destination keys from memory \u2014 call with no destination to discover keys first.',params:{destination:{type:"string",description:'Destination key to link to, e.g. "reports.profit-and-loss" or "sales.modal.view-sale". Omit to discover valid keys instead.'},resourceId:{type:"string",description:"Jaz resourceId of the record to focus \u2014 only with a record-modal destination (view/edit a specific record). Omit for screens and create modals."},query:{type:"string",description:'Discovery only: case-insensitive substring over destination keys and labels (e.g. "invoice", "p&l", "bank").'},resource:{type:"string",description:'Discovery only: restrict to one resource namespace, e.g. "sales", "purchases", "reports", "settings".'},kind:{type:"string",description:'Discovery only: restrict to "screen" (list/report pages) or "modal" (record view/create/edit).',enum:["screen","modal"]}},required:[],group:"navigation",alwaysLoaded:!0,readOnly:!0,isConcurrencySafe:!0,aliases:["find_dashboard_destinations","get_dashboard_url"],searchHint:"dashboard url deep link navigate go to open screen record modal page share shareable list destinations keys catalog",maxResultSizeChars:16e3,execute:async(t,e)=>{let r=typeof e.destination=="string"&&e.destination?e.destination:void 0,n=typeof e.resourceId=="string"&&e.resourceId?e.resourceId:void 0;if(!r){if(n)return{error:"resourceId given without destination - pass the record-modal destination key, or omit resourceId to discover destinations."};let o=e.kind==="screen"||e.kind==="modal"?e.kind:void 0,s=uQe({query:typeof e.query=="string"?e.query:void 0,resource:typeof e.resource=="string"?e.resource:void 0,kind:o});return s.truncated?{...s,hint:`Showing ${s.results.length} of ${s.total} matches. Narrow with a more specific query, resource, or kind.`}:s.results.length===0?{...s,hint:'No matches. Destinations are named by product area, not task wording \u2014 retry with a broader or synonym term (e.g. "billing" not "card", "sales" not "invoice payment", "settings", "reports", "bank") before concluding the destination does not exist.'}:s}let{dashboardUrl:i}=iQe(t.platform??"jaz");try{return lQe(r,n,{dashboardUrl:i,orgResourceId:t.org?.resourceId})}catch(o){return{error:o instanceof Error?o.message:String(o)}}}}];rQe(Mc)});function nCr(){if(!Iv){Iv=new Map;for(let t of Mc)Iv.set(t.name,t);for(let t of Mc)for(let e of t.aliases??[])Iv.has(e)||Iv.set(e,t)}return Iv}function df(t){return nCr().get(t)}function aT(){return Gue||(Gue=Mc.filter(t=>!t.disabled)),Gue}function oCr(){return Jue||(Jue=aT().filter(t=>!t.interactive)),Jue}function Ent(t){return t!==void 0&&iCr.has(t)?aT():oCr()}function Jh(t){return aT().filter(e=>e.group===t)}var Iv,Gue,iCr,Jue,hy=X(()=>{"use strict";sT();Iv=null,Gue=null;iCr=new Set(["chat"]),Jue=null});var Cnt={};Ja(Cnt,{default:()=>aCr,log:()=>Vue});var wv,sCr,Vue,aCr,vnt=X(()=>{"use strict";wv=()=>{},sCr=()=>Vue,Vue={info:wv,warn:wv,error:wv,debug:wv,trace:wv,fatal:wv,child:sCr,level:"silent"},aCr=Vue});function pct(t,e=5){let r=t.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_-]+/).filter(o=>o.length>=2&&!GIr.has(o));return n.length===0?[]:qc.map(o=>{let s=0,a=o.name.toLowerCase(),c=o.description.toLowerCase();(a===r||a===r.replace(/\s+/g,"_"))&&(s+=5),a.includes(r)&&(s+=3),c.includes(r)&&(s+=1);for(let u of n)a.includes(u)&&(s+=2),c.includes(u)&&(s+=1);return{ns:o,score:s}}).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).slice(0,e).map(o=>o.ns)}var qc,GIr,OT=X(()=>{"use strict";qc=[{name:"invoices",description:"Sales invoices (INV/SI). Create, search, get, update, delete, pay, finalize, apply credits, download PDF. Also: receivables, AR, AR aging, billing, overdue invoices, dunning, recurring invoices. To create from an uploaded invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["invoices"]},{name:"customer_credit_notes",description:"Customer credit notes (CN). Create, search, update, delete, finalize, refund, download PDF. Also: sales returns, customer CN.",groups:["customer_credit_notes"]},{name:"bills",description:"Purchase bills (PO/PI). Create, search, get, update, delete, pay, finalize, apply credits. Also: payables, AP, vendor invoices, supplier bills. To create from an uploaded bill/invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["bills"]},{name:"supplier_credit_notes",description:"Supplier credit notes. Create, search, update, delete, finalize, refund. Also: purchase returns, debit notes, supplier CN.",groups:["supplier_credit_notes"]},{name:"sale_orders",description:"Sales order documents: Sale Quotes (estimates/quotations) and Sale Orders. Create, get, search, update, and transition (accept a quote, confirm an order, void, delete). A Sale Order links to its quote via saleQuoteResourceId; the quote must be accepted first. Tracks fulfillment via orderState. Pipeline: quote \u2192 order \u2192 invoice (raise the invoice separately).",groups:["sale_orders"]},{name:"purchase_orders",description:"Purchase order documents: Purchase Requests (requisitions) and Purchase Orders (POs). Create, get, search, update, and transition (accept a request, confirm an order, void, delete). A Purchase Order links to its request via purchaseRequestResourceId; the request must be accepted first. Tracks fulfillment via orderState. Pipeline: request \u2192 order \u2192 bill (raise the bill separately).",groups:["purchase_orders"]},{name:"journals",description:"Journal entries (JE). Create, search, update, delete manual journals. Also: adjusting entries, accruals, reclassifications, corrections.",groups:["journals"]},{name:"cash_entries",description:"Cash-in receipts and cash-out disbursements for external cash movements. WHEN TO USE: money received from customers/external \u2192 cash-in. Money paid to suppliers/external \u2192 cash-out. For internal account-to-account transfers, use cash_transfers namespace.",groups:["cash_entries"]},{name:"cash_transfers",description:"Cash transfers between your own bank/cash accounts and cashflow transaction search. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). For external receipts/payments, use cash_entries namespace.",groups:["cash_transfers"]},{name:"bank_accounts",description:"Bank accounts, bank statement imports (CSV/OFX), bank records search, auto-reconciliation. For unreconciled queries: ALWAYS search bank records with status UNRECONCILED after listing accounts. Also: bank feeds, bank balance.",groups:["bank"]},{name:"bank_rules",description:"Bank reconciliation rules (action shortcuts). Create, search, update, delete bank rules. Configure auto-matching rules for bank records.",groups:["bank_rules"]},{name:"reconciliations",description:"Apply a reconciliation decision to a bank statement entry \u2014 write side. Match bank records to EXISTING open bills/invoices/payments (reconcile_with_payments \u2014 the primary path, creates the payment for you), or to journals, cash entries, or transfers, or CREATE new bills/invoices (invoice_receipt/bill_receipt). Distinct from bank_accounts/bank_rules (which configure auto-reconciliation) and view_auto_reconciliation (which queries suggestions). Eleven endpoints: quick_reconcile + apply_bank_rule + magic_match (bulk), and direct_cash_entry / cash_journal / manual_journal / cash_transfer / invoice_receipt / bill_receipt / with_payments / learned_prediction (per-entry). Match-to-existing is preferred over create-new to avoid duplicates. Most fields prefill from the bank entry when omitted; FX is resolved server-side.",groups:["reconciliations"]},{name:"financial_reports",description:"Core financial statements: trial balance (TB), balance sheet (BS/B/S), profit & loss (PnL/P&L/income statement), cash flow, general ledger (GL), cash balance/position, equity movement, VAT/GST ledger. Also: how profitable, what is the balance. XLSX/PDF file exports of any of these statements are produced via download_export (lives in operational_reports namespace \u2014 switch there or call by name).",groups:["financial_reports"]},{name:"operational_reports",description:"Aging and operational reports: aged receivables (AR aging), aged payables (AP aging), AR report, bank balance summary, bank reconciliation reports, fixed asset (FA) summary, FA reconciliation. Data exports (CSV/Excel/XLSX). Anomaly detection and audit analysis: anomalous invoices, anomalous bills, cashflow anomalies, GL journal audit, exchange rate audit, receivables customer risk, cash expense health. Also: overdue analysis, how much owed, suspicious transactions, audit trail.",groups:["operational_reports","exports"]},{name:"pseudo_sql",description:"Pseudo-SQL ad-hoc read-only queries against the curated reporting schema (custom select, custom report, query data, run sql). Includes live schema introspection (get_pseudo_sql_schema) + sync preview (\u2264100 rows) + async CSV export. Use when search_* / download_export canonical reports don't cover the question.",groups:["pseudo_sql"]},{name:"contacts",description:"Contacts (customers/suppliers/vendors), contact groups, customer segmentation. Create, search, get, update, delete contacts. Bulk upsert contacts from CSV / spreadsheet imports \u2014 async, returns jobId, poll background_jobs. List/create contact groups.",groups:["contacts","contact_groups"]},{name:"items_and_inventory",description:"Products, services, inventory items. Create, search, get, update, delete items. Check inventory balance. List/search purchase-side catalog items. Also: SKU, catalog, stock.",groups:["items","inventory","purchase_items"]},{name:"catalogs",description:"Catalogs \u2014 named groupings of products/services, optionally scoped to contact groups. Create, search, get, update, delete catalogs.",groups:["catalogs"]},{name:"tags_and_custom_fields",description:"Tags for categorizing transactions. Custom fields for adding metadata (text, date, dropdown). Create, search, delete tags and custom fields.",groups:["tags","custom_fields"]},{name:"nano_classifiers",description:"Nano classifiers (tracking categories/dimensions). List, search, create, update, delete classifiers and their classes. Used for line-item tagging and dimensional reporting. Also: tracking categories, cost centers, departments, projects.",groups:["nano_classifiers"]},{name:"chart_of_accounts",description:"Chart of accounts (COA/GL accounts). Create, search, update accounts \u2014 including setting or removing an account's period lock date (lock / unlock a period, lock date: block recording or editing transactions on the account dated on or before a date). Bookmarks (favorites/shortcuts). Also: ledger codes, account types.",groups:["accounts","bookmarks"]},{name:"currencies",description:"Currencies, exchange rates (FX/forex). List/add org currencies. Set, update, import currency rates. Also: multi-currency, FX rates.",groups:["currencies"]},{name:"tax_profiles",description:"Tax profiles (GST/VAT/sales tax), withholding tax codes (WHT/ATC). Search, create, update tax profiles. List WHT codes.",groups:["tax_profiles"]},{name:"claim_settings",description:"Employee-expense claim configuration (Settings -> Claim Settings): claim types (expense categories) and claim profiles (per-employee policy: approver, limits, visible types, balance account). Full CRUD + search on each.",groups:["claim_types","claim_profiles"]},{name:"posting_rules",description:"Claim posting rules \u2014 how approved employee-expense claims group into journals at conversion (outer/inner grouping axes, line templates, default reimbursement bank). Full CRUD + search.",groups:["posting_rules"]},{name:"claims",description:'Employee-expense claims (the Claims area / Employees). Search, get, update DRAFT claims (line items, employee, vendor), and drive the lifecycle: submit, approve, reject, cancel, unpost (reverse conversion), delete. Status flow DRAFT \u2192 SUBMITTED \u2192 APPROVED \u2192 CONVERTED ("Processed"), or REJECTED / CANCELLED. Claims are born via document attachment / conversion (no bare create); the server enforces legal transitions.',groups:["claims"]},{name:"claim_processing",description:"Process employee-expense claims: convert APPROVED claims into journal entries (preview + commit, books-only \u2014 no real-money disburse), record books-only employee payouts (reimbursements / advances) and search them, run bulk claim actions (submit / approve / reject / cancel / delete many at once \u2014 asynchronous, returns a background-job handle to poll), plus the claim tracking-tag and custom-field-value pickers.",groups:["claim_processing"]},{name:"employees",description:"Employees (expense-claim members): create, update, get, delete, and search employees; search the employee-balance directory (reimbursement balances owed); bind a login user to an employee (permanent); and bulk-import employees from a sheet (preprocess preview \u2192 async import). Archive an employee with update active=false rather than deleting.",groups:["employees"]},{name:"capsules_and_recipes",description:"Capsules (transaction groupings/capsule types). Financial recipes: amortization, depreciation, deferred revenue, IFRS 16 leases, hire purchase, fixed deposits, FX revaluation, loan schedules, ECL/expected credit loss, IAS 37 provisions, asset disposal. Two recipe execution paths: offline (plan_recipe + execute_recipe \u2014 client-side calculators, no API key) and server-side (list/get/preview/resume/rollback_capsule_recipe \u2014 produce real capsule entities via Jaz API). Plus capsuleRecipe payload on trigger mutations (create_bill, create_journal, create_cash_in, etc.) to create and trigger a recipe in one shot, with optional templateOverrides to customize the generated text (Customize Recipe). Keywords: calculate, provision, schedule, expected credit loss, revaluation, amortize, rollback recipe, customize template overrides slots.",groups:["capsules","recipes","capsule_recipes"]},{name:"scheduled_transactions",description:"Scheduled/recurring invoices, bills, journals. Create scheduled invoices/bills/journals, search scheduled transactions. Also: recurring, auto-generate.",groups:["schedulers"]},{name:"subscriptions",description:"Subscriptions (recurring billing/payment plans). Create, update, cancel, search subscriptions. Also: recurring charges, subscription schedules.",groups:["subscriptions"]},{name:"organization",description:"Organization info (name, currency, country, fiscal year). User management: invite, update, remove, search org users. Bulk invite. List enabled modules (org features/capabilities). List/search saved report templates.",groups:["organization","org_users","modules","report_templates"]},{name:"document_ai",description:'File attachments, spreadsheets, and document AI. Read and parse rows from attached spreadsheets \u2014 CSV, Excel, XLSX. Scan a single invoice / bill / receipt PDF or image to create a draft bill or invoice via AI extraction (create_bt_from_attachment, with the file or a sourceUrl). Auto-sort a whole FOLDER, a .zip, or a Dropbox / Google Drive / OneDrive folder share link of mixed paperwork \u2014 "create docs from this Dropbox folder link", a pile/batch of invoices and bills \u2014 into invoices, bills, credit notes, and bank statements with classify_documents, then create the drafts with extract_documents. Upload and list attachments; track extraction workflows.',groups:["attachments","magic"]},{name:"fixed_assets",description:"Fixed assets (PP&E/property, plant, equipment). Search, create, update, discard, sell, transfer, undo disposal. Also: depreciation, asset register.",groups:["fixed_assets"]},{name:"payments_and_search",description:"Payment records: get, update, delete individual payments. List payments/credits on invoices and bills. Reverse credit applications. Cashflow transaction search. Universal cross-entity search. Also: payment run, batch payment, payment matching, void payment, payment history, credit note applications.",groups:["payments","cashflow","search"]},{name:"quick_fix",description:"Quick Fix: bulk-update multiple transactions or line items in one call. Change dates, contacts, tags, accounts, tax profiles, custom fields across many invoices/bills/journals/credit-notes/cash-entries/schedulers at once. Also: batch update, mass edit.",groups:["quick_fix"]},{name:"export_records",description:"Export records to XLSX. List available columns, preview export scope (row count + sample), generate export file with pre-signed download URL. Supports any entity type: invoices, bills, contacts, items, journals, bank records, cashflow, fixed assets, etc. Pass query (structured search syntax) or filter (JSON), never both.",groups:["export_records"]},{name:"background_jobs",description:"Background job tracking. Poll any async operation by jobId (contacts bulk-upsert, items bulk-upsert, bank import, magic file processing, etc.). Filter by resourceId field to look up a specific job. Poll until status is SUCCESS, FAILED, or PARTIAL_SUCCESS.",groups:["background_jobs"]},{name:"drafts",description:"Draft business transactions \u2014 both local payload validation (invoices, bills, journals, credit notes) AND BULK-FRIENDLY server-side lifecycle: validate_drafts (sync eligibility check), convert_drafts_to_active (async promote to ACTIVE), submit_drafts_for_approval (async route to approval). The lifecycle tools are GENERIC and BULK \u2014 one call accepts up to 500 items mixing any combination of {btResourceId, btType: SALE|PURCHASE|SALE_CREDIT_NOTE|PURCHASE_CREDIT_NOTE}. No need for per-entity tools when promoting/submitting drafts at scale. NOT idempotent on already-promoted drafts.",groups:["drafts"]},{name:"help_center",description:"Search the Jaz help center for how-to articles, feature guides, accounting concepts, and troubleshooting. Returns top matches with title, section, snippet, and source URL. Works without an API key.",groups:["help_center"]},{name:"jots",description:"The judgment journal. jot records a judgment call (chose among real alternatives and wrote, or deliberately held a write); recall looks up prior judgments and precedents by entity, kind, or freetext. Also: decision log, rationale, why.",groups:["jots"]},{name:"navigation",description:"Dashboard navigation deep links. Build a URL to any dashboard screen or record for the user \u2014 including the view link for a record just created or updated (a reply reporting on a record carries its link, and dashboard URLs always come from this tool, never written from memory). Also: open, go to, take me to, link, deep link, share a link, url, navigate, show me the page/screen, where can I see \u2014 for invoices, bills, reports, settings, or a specific transaction.",groups:["navigation"]}],GIr=new Set(["a","an","and","are","at","be","by","can","do","does","for","how","i","in","is","it","me","my","of","on","or","our","please","that","the","this","to","us","we","what","when","where","which","with","you","your"])});function O8(t){let e={type:t.type};if(t.description&&(e.description=t.description),t.enum&&(e.enum=t.enum),t.type==="array"&&t.items&&(e.items=O8(t.items)),t.type==="object"&&t.properties){let r={};for(let[n,i]of Object.entries(t.properties))r[n]=O8(i);e.properties=r,t.required?.length&&(e.required=t.required)}return e}function hf(t,e){let r={};for(let[n,i]of Object.entries(t))r[n]=O8(i);return{type:"object",properties:r,...e.length>0?{required:e}:{}}}function yy(t){return{name:t.name,description:t.description,input_schema:hf(t.params,t.required),...t.searchHint?{searchHint:t.searchHint}:{}}}var FT=X(()=>{"use strict"});function QT(t){if(typeof t!="string")return t.isDestructive??!1;let e=t;return e.startsWith("delete_")||e.startsWith("pay_")||e.startsWith("finalize_")||e.includes("refund")||e==="remove_org_user"}function F8(t){return{readOnlyHint:t.readOnly,destructiveHint:!t.readOnly&&QT(t),idempotentHint:t.readOnly,openWorldHint:t.openWorld??!1}}function hct(t){if(!t.trim())return{namespaces:qc.map(i=>{let o=i.groups.flatMap(s=>Jh(s));return{name:i.name,description:i.description,toolCount:o.length,tools:o.map(s=>s.name)}}),hint:"Call describe_tools with specific tool names to get full schemas before executing."};let e=pct(t,5);if(e.length===0)return{matches:[],hint:`No tools match "${t}". Try broader terms or call search_tools with empty query to see all namespaces.`};let n=t.toLowerCase().split(/\s+/).filter(Boolean);return{matches:e.map(i=>{let o=i.groups.flatMap(u=>Jh(u)),s=o.map(u=>`${u.name} ${(u.aliases??[]).join(" ")} ${u.searchHint??""} ${u.description}`.toLowerCase()),a=new Map(n.map(u=>{let d=s.filter(f=>f.includes(u)).length;return[u,Math.log((o.length+1)/(d+1))]})),c=o.map((u,d)=>{let f=s[d],p=n.reduce((h,m)=>f.includes(m)?h+(a.get(m)??0):h,0);return{tool:u,score:p}}).sort((u,d)=>d.score-u.score);return{namespace:i.name,description:i.description,tools:c.map(u=>({name:u.tool.name,description:u.tool.description.split(`
|
|
868
868
|
`)[0],...u.tool.searchHint?{searchHint:u.tool.searchHint}:{}}))}}),hint:"Call describe_tools with the tool names you need, then execute_tool to run them."}}function mct(t){if(!Array.isArray(t)||!t.every(n=>typeof n=="string"))return{error:"Invalid `tools` parameter. Expected string[]."};if(t.length===0)return{error:"Provide at least one tool name. Use search_tools first to discover tool names."};let e=[],r=[];for(let n of t){let i=df(n);if(!i){r.push(n);continue}e.push({...yy(i),readOnly:i.readOnly,isDestructive:i.isDestructive??!1,isConcurrencySafe:i.isConcurrencySafe??!1,destructiveHint:!i.readOnly&&QT(i),group:i.group})}return{tools:e,...r.length>0?{notFound:r,hint:`Tools not found: ${r.join(", ")}. Use search_tools to find correct names.`}:{}}}var JIr,VIr,WIr,Kh,mf,LT=X(()=>{"use strict";OT();hy();FT();JIr={name:"search_tools",description:"Search for available Jaz accounting tools by keyword. Returns matching tool namespaces with tool names and descriptions. Call with empty query to list all namespaces. ALWAYS call this first to discover what tools are available.",inputSchema:hf({query:{type:"string",description:'Search keyword (e.g. "invoice", "bank recon", "depreciation"). Empty string lists all namespaces.'}},[])};VIr={name:"describe_tools",description:"Get full JSON Schema (parameters, types, required fields) for specific tools. Call this after search_tools to get the exact input format before calling execute_tool.",inputSchema:hf({tools:{type:"array",items:{type:"string"},description:'Tool names to describe (e.g. ["create_invoice", "search_contacts"])'}},["tools"])},WIr={name:"execute_tool",description:"Execute a Jaz accounting tool. Call describe_tools first to get the required parameters. Pass the tool name and its arguments.",inputSchema:hf({tool:{type:"string",description:'Tool name (e.g. "create_invoice")'},arguments:{type:"object",description:"Tool arguments (see describe_tools for schema)"},org_id:{type:"string",description:"Organization ID (UUID). Required in multi-org mode (PAT or multiple API keys). Call list_organizations to get available IDs."}},["tool"])},Kh={name:"list_organizations",description:"List organizations available to the current authentication. Returns org names and resource IDs for use as org_id in execute_tool calls.",inputSchema:hf({},[])},mf=[JIr,VIr,WIr]});var $T=b(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.regexpCode=Nr.getEsmExportName=Nr.getProperty=Nr.safeStringify=Nr.stringify=Nr.strConcat=Nr.addCodeArg=Nr.str=Nr._=Nr.nil=Nr._Code=Nr.Name=Nr.IDENTIFIER=Nr._CodeOrName=void 0;var PT=class{};Nr._CodeOrName=PT;Nr.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ey=class extends PT{constructor(e){if(super(),!Nr.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Nr.Name=Ey;var jc=class extends PT{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Ey&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Nr._Code=jc;Nr.nil=new jc("");function Ect(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Afe(r,e[n]),r.push(t[++n]);return new jc(r)}Nr._=Ect;var mfe=new jc("+");function bct(t,...e){let r=[UT(t[0])],n=0;for(;n<e.length;)r.push(mfe),Afe(r,e[n]),r.push(mfe,UT(t[++n]));return nwr(r),new jc(r)}Nr.str=bct;function Afe(t,e){e instanceof jc?t.push(...e._items):e instanceof Ey?t.push(e):t.push(swr(e))}Nr.addCodeArg=Afe;function nwr(t){let e=1;for(;e<t.length-1;){if(t[e]===mfe){let r=iwr(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function iwr(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Ey||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Ey))return`"${t}${e.slice(1)}`}function owr(t,e){return e.emptyStr()?t:t.emptyStr()?e:bct`${t}${e}`}Nr.strConcat=owr;function swr(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:UT(Array.isArray(t)?t.join(","):t)}function awr(t){return new jc(UT(t))}Nr.stringify=awr;function UT(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Nr.safeStringify=UT;function cwr(t){return typeof t=="string"&&Nr.IDENTIFIER.test(t)?new jc(`.${t}`):Ect`[${t}]`}Nr.getProperty=cwr;function lwr(t){if(typeof t=="string"&&Nr.IDENTIFIER.test(t))return new jc(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Nr.getEsmExportName=lwr;function uwr(t){return new jc(t.toString())}Nr.regexpCode=uwr});var Efe=b(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0});la.ValueScope=la.ValueScopeName=la.Scope=la.varKinds=la.UsedValueState=void 0;var ca=$T(),gfe=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},M8;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(M8||(la.UsedValueState=M8={}));la.varKinds={const:new ca.Name("const"),let:new ca.Name("let"),var:new ca.Name("var")};var P8=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof ca.Name?e:this.name(e)}name(e){return new ca.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};la.Scope=P8;var U8=class extends ca.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,ca._)`.${new ca.Name(r)}[${n}]`}};la.ValueScopeName=U8;var dwr=(0,ca._)`\n`,yfe=class extends P8{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?dwr:ca.nil}}get(){return this._scope}name(e){return new U8(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:o}=i,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let d=a.get(s);if(d)return d}else a=this._values[o]=new Map;a.set(s,i);let c=this._scope[o]||(this._scope[o]=[]),u=c.length;return c[u]=r.ref,i.setValue(r,{property:o,itemIndex:u}),i}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,ca._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(e,r,n={},i){let o=ca.nil;for(let s in e){let a=e[s];if(!a)continue;let c=n[s]=n[s]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,M8.Started);let d=r(u);if(d){let f=this.opts.es5?la.varKinds.var:la.varKinds.const;o=(0,ca._)`${o}${f} ${u} = ${d};${this.opts._n}`}else if(d=i?.(u))o=(0,ca._)`${o}${d}${this.opts._n}`;else throw new gfe(u);c.set(u,M8.Completed)})}return o}};la.ValueScope=yfe});var Yt=b(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.or=Gt.and=Gt.not=Gt.CodeGen=Gt.operators=Gt.varKinds=Gt.ValueScopeName=Gt.ValueScope=Gt.Scope=Gt.Name=Gt.regexpCode=Gt.stringify=Gt.getProperty=Gt.nil=Gt.strConcat=Gt.str=Gt._=void 0;var Ar=$T(),$l=Efe(),tm=$T();Object.defineProperty(Gt,"_",{enumerable:!0,get:function(){return tm._}});Object.defineProperty(Gt,"str",{enumerable:!0,get:function(){return tm.str}});Object.defineProperty(Gt,"strConcat",{enumerable:!0,get:function(){return tm.strConcat}});Object.defineProperty(Gt,"nil",{enumerable:!0,get:function(){return tm.nil}});Object.defineProperty(Gt,"getProperty",{enumerable:!0,get:function(){return tm.getProperty}});Object.defineProperty(Gt,"stringify",{enumerable:!0,get:function(){return tm.stringify}});Object.defineProperty(Gt,"regexpCode",{enumerable:!0,get:function(){return tm.regexpCode}});Object.defineProperty(Gt,"Name",{enumerable:!0,get:function(){return tm.Name}});var Y8=Efe();Object.defineProperty(Gt,"Scope",{enumerable:!0,get:function(){return Y8.Scope}});Object.defineProperty(Gt,"ValueScope",{enumerable:!0,get:function(){return Y8.ValueScope}});Object.defineProperty(Gt,"ValueScopeName",{enumerable:!0,get:function(){return Y8.ValueScopeName}});Object.defineProperty(Gt,"varKinds",{enumerable:!0,get:function(){return Y8.varKinds}});Gt.operators={GT:new Ar._Code(">"),GTE:new Ar._Code(">="),LT:new Ar._Code("<"),LTE:new Ar._Code("<="),EQ:new Ar._Code("==="),NEQ:new Ar._Code("!=="),NOT:new Ar._Code("!"),OR:new Ar._Code("||"),AND:new Ar._Code("&&"),ADD:new Ar._Code("+")};var gf=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},bfe=class extends gf{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?$l.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Ov(this.rhs,e,r)),this}get names(){return this.rhs instanceof Ar._CodeOrName?this.rhs.names:{}}},$8=class extends gf{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof Ar.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Ov(this.rhs,e,r),this}get names(){let e=this.lhs instanceof Ar.Name?{}:{...this.lhs.names};return j8(e,this.rhs)}},Cfe=class extends $8{constructor(e,r,n,i){super(e,n,i),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},vfe=class extends gf{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ife=class extends gf{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},wfe=class extends gf{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},_fe=class extends gf{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Ov(this.code,e,r),this}get names(){return this.code instanceof Ar._CodeOrName?this.code.names:{}}},qT=class extends gf{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,i=n.length;for(;i--;){let o=n[i];o.optimizeNames(e,r)||(fwr(e,o.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>vy(e,r.names),{})}},yf=class extends qT{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Dfe=class extends qT{},Nv=class extends yf{};Nv.kind="else";var by=class t extends yf{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Nv(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Cct(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Ov(this.condition,e,r),this}get names(){let e=super.names;return j8(e,this.condition),this.else&&vy(e,this.else.names),e}};by.kind="if";var Cy=class extends yf{};Cy.kind="for";var Sfe=class extends Cy{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Ov(this.iteration,e,r),this}get names(){return vy(super.names,this.iteration.names)}},Rfe=class extends Cy{constructor(e,r,n,i){super(),this.varKind=e,this.name=r,this.from=n,this.to=i}render(e){let r=e.es5?$l.varKinds.var:this.varKind,{name:n,from:i,to:o}=this;return`for(${r} ${n}=${i}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=j8(super.names,this.from);return j8(e,this.to)}},q8=class extends Cy{constructor(e,r,n,i){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Ov(this.iterable,e,r),this}get names(){return vy(super.names,this.iterable.names)}},jT=class extends yf{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};jT.kind="func";var YT=class extends qT{render(e){return"return "+super.render(e)}};YT.kind="return";var Bfe=class extends yf{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,i;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(i=this.finally)===null||i===void 0||i.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&vy(e,this.catch.names),this.finally&&vy(e,this.finally.names),e}},HT=class extends yf{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};HT.kind="catch";var zT=class extends yf{render(e){return"finally"+super.render(e)}};zT.kind="finally";var xfe=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
869
869
|
`:""},this._extScope=e,this._scope=new $l.Scope({parent:e}),this._nodes=[new Dfe]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,i){let o=this._scope.toName(r);return n!==void 0&&i&&(this._constants[o.str]=n),this._leafNode(new bfe(e,o,n)),o}const(e,r,n){return this._def($l.varKinds.const,e,r,n)}let(e,r,n){return this._def($l.varKinds.let,e,r,n)}var(e,r,n){return this._def($l.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new $8(e,r,n))}add(e,r){return this._leafNode(new Cfe(e,Gt.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==Ar.nil&&this._leafNode(new _fe(e)),this}object(...e){let r=["{"];for(let[n,i]of e)r.length>1&&r.push(","),r.push(n),(n!==i||this.opts.es5)&&(r.push(":"),(0,Ar.addCodeArg)(r,i));return r.push("}"),new Ar._Code(r)}if(e,r,n){if(this._blockNode(new by(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new by(e))}else(){return this._elseNode(new Nv)}endIf(){return this._endBlockNode(by,Nv)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Sfe(e),r)}forRange(e,r,n,i,o=this.opts.es5?$l.varKinds.var:$l.varKinds.let){let s=this._scope.toName(e);return this._for(new Rfe(o,s,r,n),()=>i(s))}forOf(e,r,n,i=$l.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let s=r instanceof Ar.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Ar._)`${s}.length`,a=>{this.var(o,(0,Ar._)`${s}[${a}]`),n(o)})}return this._for(new q8("of",i,o,r),()=>n(o))}forIn(e,r,n,i=this.opts.es5?$l.varKinds.var:$l.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,Ar._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new q8("in",i,o,r),()=>n(o))}endFor(){return this._endBlockNode(Cy)}label(e){return this._leafNode(new vfe(e))}break(e){return this._leafNode(new Ife(e))}return(e){let r=new YT;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(YT)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new Bfe;if(this._blockNode(i),this.code(e),r){let o=this.name("e");this._currNode=i.catch=new HT(o),r(o)}return n&&(this._currNode=i.finally=new zT,this.code(n)),this._endBlockNode(HT,zT)}throw(e){return this._leafNode(new wfe(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=Ar.nil,n,i){return this._blockNode(new jT(e,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(jT)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof by))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};Gt.CodeGen=xfe;function vy(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function j8(t,e){return e instanceof Ar._CodeOrName?vy(t,e.names):t}function Ov(t,e,r){if(t instanceof Ar.Name)return n(t);if(!i(t))return t;return new Ar._Code(t._items.reduce((o,s)=>(s instanceof Ar.Name&&(s=n(s)),s instanceof Ar._Code?o.push(...s._items):o.push(s),o),[]));function n(o){let s=r[o.str];return s===void 0||e[o.str]!==1?o:(delete e[o.str],s)}function i(o){return o instanceof Ar._Code&&o._items.some(s=>s instanceof Ar.Name&&e[s.str]===1&&r[s.str]!==void 0)}}function fwr(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Cct(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,Ar._)`!${Tfe(t)}`}Gt.not=Cct;var pwr=vct(Gt.operators.AND);function hwr(...t){return t.reduce(pwr)}Gt.and=hwr;var mwr=vct(Gt.operators.OR);function Awr(...t){return t.reduce(mwr)}Gt.or=Awr;function vct(t){return(e,r)=>e===Ar.nil?r:r===Ar.nil?e:(0,Ar._)`${Tfe(e)} ${t} ${Tfe(r)}`}function Tfe(t){return t instanceof Ar.Name?t:(0,Ar._)`(${t})`}});var vr=b(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.checkStrictMode=ir.getErrorPath=ir.Type=ir.useFunc=ir.setEvaluated=ir.evaluatedPropsToName=ir.mergeEvaluated=ir.eachItem=ir.unescapeJsonPointer=ir.escapeJsonPointer=ir.escapeFragment=ir.unescapeFragment=ir.schemaRefOrVal=ir.schemaHasRulesButRef=ir.schemaHasRules=ir.checkUnknownRules=ir.alwaysValidSchema=ir.toHash=void 0;var dn=Yt(),gwr=$T();function ywr(t){let e={};for(let r of t)e[r]=!0;return e}ir.toHash=ywr;function Ewr(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(_ct(t,e),!Dct(e,t.self.RULES.all))}ir.alwaysValidSchema=Ewr;function _ct(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let i=n.RULES.keywords;for(let o in e)i[o]||Bct(t,`unknown keyword: "${o}"`)}ir.checkUnknownRules=_ct;function Dct(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ir.schemaHasRules=Dct;function bwr(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ir.schemaHasRulesButRef=bwr;function Cwr({topSchemaRef:t,schemaPath:e},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,dn._)`${r}`}return(0,dn._)`${t}${e}${(0,dn.getProperty)(n)}`}ir.schemaRefOrVal=Cwr;function vwr(t){return Sct(decodeURIComponent(t))}ir.unescapeFragment=vwr;function Iwr(t){return encodeURIComponent(Nfe(t))}ir.escapeFragment=Iwr;function Nfe(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ir.escapeJsonPointer=Nfe;function Sct(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ir.unescapeJsonPointer=Sct;function wwr(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ir.eachItem=wwr;function Ict({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(i,o,s,a)=>{let c=s===void 0?o:s instanceof dn.Name?(o instanceof dn.Name?t(i,o,s):e(i,o,s),s):o instanceof dn.Name?(e(i,s,o),o):r(o,s);return a===dn.Name&&!(c instanceof dn.Name)?n(i,c):c}}ir.mergeEvaluated={props:Ict({mergeNames:(t,e,r)=>t.if((0,dn._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,dn._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,dn._)`${r} || {}`).code((0,dn._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,dn._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,dn._)`${r} || {}`),Ofe(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Rct}),items:Ict({mergeNames:(t,e,r)=>t.if((0,dn._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,dn._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,dn._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,dn._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Rct(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,dn._)`{}`);return e!==void 0&&Ofe(t,r,e),r}ir.evaluatedPropsToName=Rct;function Ofe(t,e,r){Object.keys(r).forEach(n=>t.assign((0,dn._)`${e}${(0,dn.getProperty)(n)}`,!0))}ir.setEvaluated=Ofe;var wct={};function _wr(t,e){return t.scopeValue("func",{ref:e,code:wct[e.code]||(wct[e.code]=new gwr._Code(e.code))})}ir.useFunc=_wr;var kfe;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(kfe||(ir.Type=kfe={}));function Dwr(t,e,r){if(t instanceof dn.Name){let n=e===kfe.Num;return r?n?(0,dn._)`"[" + ${t} + "]"`:(0,dn._)`"['" + ${t} + "']"`:n?(0,dn._)`"/" + ${t}`:(0,dn._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,dn.getProperty)(t).toString():"/"+Nfe(t)}ir.getErrorPath=Dwr;function Bct(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ir.checkStrictMode=Bct});var Ef=b(Ffe=>{"use strict";Object.defineProperty(Ffe,"__esModule",{value:!0});var as=Yt(),Swr={data:new as.Name("data"),valCxt:new as.Name("valCxt"),instancePath:new as.Name("instancePath"),parentData:new as.Name("parentData"),parentDataProperty:new as.Name("parentDataProperty"),rootData:new as.Name("rootData"),dynamicAnchors:new as.Name("dynamicAnchors"),vErrors:new as.Name("vErrors"),errors:new as.Name("errors"),this:new as.Name("this"),self:new as.Name("self"),scope:new as.Name("scope"),json:new as.Name("json"),jsonPos:new as.Name("jsonPos"),jsonLen:new as.Name("jsonLen"),jsonPart:new as.Name("jsonPart")};Ffe.default=Swr});var GT=b(cs=>{"use strict";Object.defineProperty(cs,"__esModule",{value:!0});cs.extendErrors=cs.resetErrorsCount=cs.reportExtraError=cs.reportError=cs.keyword$DataError=cs.keywordError=void 0;var Ir=Yt(),H8=vr(),Fs=Ef();cs.keywordError={message:({keyword:t})=>(0,Ir.str)`must pass "${t}" keyword validation`};cs.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Ir.str)`"${t}" keyword must be ${e} ($data)`:(0,Ir.str)`"${t}" keyword is invalid ($data)`};function Rwr(t,e=cs.keywordError,r,n){let{it:i}=t,{gen:o,compositeRule:s,allErrors:a}=i,c=kct(t,e,r);n??(s||a)?xct(o,c):Tct(i,(0,Ir._)`[${c}]`)}cs.reportError=Rwr;function Bwr(t,e=cs.keywordError,r){let{it:n}=t,{gen:i,compositeRule:o,allErrors:s}=n,a=kct(t,e,r);xct(i,a),o||s||Tct(n,Fs.default.vErrors)}cs.reportExtraError=Bwr;function xwr(t,e){t.assign(Fs.default.errors,e),t.if((0,Ir._)`${Fs.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Ir._)`${Fs.default.vErrors}.length`,e),()=>t.assign(Fs.default.vErrors,null)))}cs.resetErrorsCount=xwr;function Twr({gen:t,keyword:e,schemaValue:r,data:n,errsCount:i,it:o}){if(i===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",i,Fs.default.errors,a=>{t.const(s,(0,Ir._)`${Fs.default.vErrors}[${a}]`),t.if((0,Ir._)`${s}.instancePath === undefined`,()=>t.assign((0,Ir._)`${s}.instancePath`,(0,Ir.strConcat)(Fs.default.instancePath,o.errorPath))),t.assign((0,Ir._)`${s}.schemaPath`,(0,Ir.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,Ir._)`${s}.schema`,r),t.assign((0,Ir._)`${s}.data`,n))})}cs.extendErrors=Twr;function xct(t,e){let r=t.const("err",e);t.if((0,Ir._)`${Fs.default.vErrors} === null`,()=>t.assign(Fs.default.vErrors,(0,Ir._)`[${r}]`),(0,Ir._)`${Fs.default.vErrors}.push(${r})`),t.code((0,Ir._)`${Fs.default.errors}++`)}function Tct(t,e){let{gen:r,validateName:n,schemaEnv:i}=t;i.$async?r.throw((0,Ir._)`new ${t.ValidationError}(${e})`):(r.assign((0,Ir._)`${n}.errors`,e),r.return(!1))}var Iy={keyword:new Ir.Name("keyword"),schemaPath:new Ir.Name("schemaPath"),params:new Ir.Name("params"),propertyName:new Ir.Name("propertyName"),message:new Ir.Name("message"),schema:new Ir.Name("schema"),parentSchema:new Ir.Name("parentSchema")};function kct(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Ir._)`{}`:kwr(t,e,r)}function kwr(t,e,r={}){let{gen:n,it:i}=t,o=[Nwr(i,r),Owr(t,r)];return Fwr(t,e,o),n.object(...o)}function Nwr({errorPath:t},{instancePath:e}){let r=e?(0,Ir.str)`${t}${(0,H8.getErrorPath)(e,H8.Type.Str)}`:t;return[Fs.default.instancePath,(0,Ir.strConcat)(Fs.default.instancePath,r)]}function Owr({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let i=n?e:(0,Ir.str)`${e}/${t}`;return r&&(i=(0,Ir.str)`${i}${(0,H8.getErrorPath)(r,H8.Type.Str)}`),[Iy.schemaPath,i]}function Fwr(t,{params:e,message:r},n){let{keyword:i,data:o,schemaValue:s,it:a}=t,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:f}=a;n.push([Iy.keyword,i],[Iy.params,typeof e=="function"?e(t):e||(0,Ir._)`{}`]),c.messages&&n.push([Iy.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Iy.schema,s],[Iy.parentSchema,(0,Ir._)`${d}${f}`],[Fs.default.data,o]),u&&n.push([Iy.propertyName,u])}});var Oct=b(Fv=>{"use strict";Object.defineProperty(Fv,"__esModule",{value:!0});Fv.boolOrEmptySchema=Fv.topBoolOrEmptySchema=void 0;var Qwr=GT(),Lwr=Yt(),Mwr=Ef(),Pwr={message:"boolean schema is false"};function Uwr(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Nct(t,!1):typeof r=="object"&&r.$async===!0?e.return(Mwr.default.data):(e.assign((0,Lwr._)`${n}.errors`,null),e.return(!0))}Fv.topBoolOrEmptySchema=Uwr;function $wr(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Nct(t)):r.var(e,!0)}Fv.boolOrEmptySchema=$wr;function Nct(t,e){let{gen:r,data:n}=t,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Qwr.reportError)(i,Pwr,void 0,e)}});var Qfe=b(Qv=>{"use strict";Object.defineProperty(Qv,"__esModule",{value:!0});Qv.getRules=Qv.isJSONType=void 0;var qwr=["string","number","integer","boolean","null","object","array"],jwr=new Set(qwr);function Ywr(t){return typeof t=="string"&&jwr.has(t)}Qv.isJSONType=Ywr;function Hwr(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Qv.getRules=Hwr});var Lfe=b(rm=>{"use strict";Object.defineProperty(rm,"__esModule",{value:!0});rm.shouldUseRule=rm.shouldUseGroup=rm.schemaHasRulesForType=void 0;function zwr({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Fct(t,n)}rm.schemaHasRulesForType=zwr;function Fct(t,e){return e.rules.some(r=>Qct(t,r))}rm.shouldUseGroup=Fct;function Qct(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}rm.shouldUseRule=Qct});var JT=b(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});ls.reportTypeError=ls.checkDataTypes=ls.checkDataType=ls.coerceAndCheckDataType=ls.getJSONTypes=ls.getSchemaTypes=ls.DataType=void 0;var Gwr=Qfe(),Jwr=Lfe(),Vwr=GT(),qt=Yt(),Lct=vr(),Lv;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Lv||(ls.DataType=Lv={}));function Wwr(t){let e=Mct(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}ls.getSchemaTypes=Wwr;function Mct(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Gwr.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ls.getJSONTypes=Mct;function Zwr(t,e){let{gen:r,data:n,opts:i}=t,o=Kwr(e,i.coerceTypes),s=e.length>0&&!(o.length===0&&e.length===1&&(0,Jwr.schemaHasRulesForType)(t,e[0]));if(s){let a=Pfe(e,n,i.strictNumbers,Lv.Wrong);r.if(a,()=>{o.length?Xwr(t,e,o):Ufe(t)})}return s}ls.coerceAndCheckDataType=Zwr;var Pct=new Set(["string","number","integer","boolean","null"]);function Kwr(t,e){return e?t.filter(r=>Pct.has(r)||e==="array"&&r==="array"):[]}function Xwr(t,e,r){let{gen:n,data:i,opts:o}=t,s=n.let("dataType",(0,qt._)`typeof ${i}`),a=n.let("coerced",(0,qt._)`undefined`);o.coerceTypes==="array"&&n.if((0,qt._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,qt._)`${i}[0]`).assign(s,(0,qt._)`typeof ${i}`).if(Pfe(e,i,o.strictNumbers),()=>n.assign(a,i))),n.if((0,qt._)`${a} !== undefined`);for(let u of r)(Pct.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);n.else(),Ufe(t),n.endIf(),n.if((0,qt._)`${a} !== undefined`,()=>{n.assign(i,a),e_r(t,a)});function c(u){switch(u){case"string":n.elseIf((0,qt._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,qt._)`"" + ${i}`).elseIf((0,qt._)`${i} === null`).assign(a,(0,qt._)`""`);return;case"number":n.elseIf((0,qt._)`${s} == "boolean" || ${i} === null
|
|
870
870
|
|| (${s} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,qt._)`+${i}`);return;case"integer":n.elseIf((0,qt._)`${s} === "boolean" || ${i} === null
|
|
@@ -1058,7 +1058,7 @@ clio() {
|
|
|
1058
1058
|
`))}process.exit(1)}await jS(o,n,d);let y=(await Il(o,n)).data,C=f.filter(E=>E!=="saveAsDraft"&&E!=="resourceId");i.json?console.log(JSON.stringify({finalized:!0,resourceId:y.resourceId,reference:y.reference||null,status:y.status,fieldsUpdated:C},null,2)):(console.log(Y(`
|
|
1059
1059
|
\u2713 Supplier credit note finalized: ${y.reference||y.resourceId}`)),console.log(R(" Status:"),y.status),C.length>0&&console.log(R(" Updated:"),C.join(", "))),Ie(o,"finalize_supplier_credit_note",i,y)})(i)),r.command("attachments <resourceId>").description("List attachments for a supplier credit note (URLs for agent inspection)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((n,i)=>Q(async o=>{let a=(await Il(o,n)).data,u=(await si(o,"supplier-credit-notes",n)).data;if(i.json)console.log(JSON.stringify({creditNoteResourceId:n,creditNoteReference:a.reference||null,attachments:u},null,2));else{if(u.length===0){console.log(`No attachments for supplier credit note ${a.reference||n}.`);return}console.log(R(`Attachments for ${a.reference||n}:
|
|
1060
1060
|
`));for(let d of u)console.log(` ${Be(d.resourceId)} ${d.fileName||"(unnamed)"}`),d.fileUrl&&console.log(` ${G(d.fileUrl)}`)}})(i)),e.command("bulk-upsert").description("Create or update supplier credit notes in bulk (max 500). Natural key: creditNoteReference. Returns a jobId \u2014 poll with `clio background-jobs get <jobId>`.").option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(n,i)=>{let o=Ce(i);o||(console.error('Error: --input <file> is required (JSON with { "supplierCreditNotes": [...] } or a bare array)'),process.exit(1));let s=o.supplierCreditNotes??o;Array.isArray(s)||(console.error('Error: expected { "supplierCreditNotes": [...] }'),process.exit(1)),s.length===0&&(console.error("Error: supplierCreditNotes array is empty."),process.exit(1)),s.length>500&&(console.error(`Error: max 500 per call (got ${s.length}). Split into batches.`),process.exit(1));let a=await c2(n,s);i.json?console.log(JSON.stringify(a.data,null,2)):(console.log(Y(`Bulk upsert started. Job ID: ${a.data.jobId}`)),console.log(Be(` Poll progress: clio background-jobs get ${a.data.jobId}`)))}))}Fe();m2();gt();Pt();var cit=[{key:"currencyCode",header:"Code"},{key:"currencyName",header:"Name"},{key:"currencySymbol",header:"Symbol"},{key:"baseCurrency",header:"Base"}];function lit(t){let e=t.command("currencies").description("Manage organization currencies");e.command("list").description("List enabled currencies for the organization").option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=await HS(r),o={data:i.data,totalElements:i.data.length,totalPages:1,truncated:!1};$e(o,cit,n,"Currencies")})),e.command("add <codes...>").description("Add currencies to the organization (e.g. clio currencies add EUR GBP)").option("--jot <text>",we).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let o=r.map(a=>a.toUpperCase()),s=await u2(i,o);if(n.json||n.format){let a=Array.isArray(s.data)?s.data:[s.data],c={data:a,totalElements:a.length,totalPages:1,truncated:!1};$e(c,cit,n,"Currencies")}else console.log(Y(`Added currencies: ${o.join(", ")}`));Ie(i,"add_currency",n,s.data)})(n))}m2();gt();Pt();Lt();Fe();kt();dr();var tde=[{key:"resourceId",header:"ID",format:Te},{key:"rate",header:"Rate"},{key:"rateApplicableFrom",header:"From"},{key:"rateApplicableTo",header:"To"}];function uit(t){let e=t.command("currency-rates").description("Manage currency exchange rates");e.command("list <currencyCode>").description("List exchange rates for a currency").option("--limit <n>","Max results (default 100)",Ee).option("--offset <n>","Page number offset (0-indexed)",Je).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",Ee).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let o=r.toUpperCase(),s=await He(n,a=>d2(i,o,a),{label:`Fetching ${o} rates`});$e(s,tde,n,`${o} Rates`)})(n)),e.command("add <currencyCode>").description("Add an exchange rate for a currency").option("--jot <text>",we).option("--rate <number>","Exchange rate",parseFloat).option("--from <YYYY-MM-DD>","Rate applicable from date").option("--to <YYYY-MM-DD>","Rate applicable to date (optional)").option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action((r,n)=>Q(async i=>{Le(n,[{flag:"--rate",key:"rate"},{flag:"--from",key:"from"}]);let o=r.toUpperCase(),s={rate:n.rate,rateApplicableFrom:n.from};n.to&&(s.rateApplicableTo=n.to);let a=await f2(i,o,s);if(n.json||n.format){let c={data:[a.data],totalElements:1,totalPages:1,truncated:!1};$e(c,tde,n,`${o} Rates`)}else console.log(Y(`Rate added for ${o}: ${n.rate} (from ${n.from})`));Ie(i,"add_currency_rate",n,a.data)})(n)),e.command("update <currencyCode> <rateResourceId>").description("Update an exchange rate").option("--jot <text>",we).option("--rate <number>","Exchange rate",parseFloat).option("--from <YYYY-MM-DD>","Rate applicable from date").option("--to <YYYY-MM-DD>","Rate applicable to date (optional)").option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action((r,n,i)=>Q(async o=>{Le(i,[{flag:"--rate",key:"rate"},{flag:"--from",key:"from"}]);let s=r.toUpperCase(),a={rate:i.rate,rateApplicableFrom:i.from};i.to&&(a.rateApplicableTo=i.to);let c=await p2(o,s,n,a);if(i.json||i.format){let u={data:[c.data],totalElements:1,totalPages:1,truncated:!1};$e(u,tde,i,`${s} Rates`)}else console.log(Y(`Rate updated for ${s}: ${i.rate}`));Ie(o,"update_currency_rate",i,c.data)})(i)),e.command("bulk-upsert").description("Create exchange rates in bulk (max 500). Auto-enables currencies not yet in the org.").option("--jot <text>",we).option("--input <file>","Read JSON body from file (or pipe via stdin with --input -)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=Ce(n);i||(console.error('Error: --input <file> is required (JSON with { "rates": [...] })'),process.exit(1));let o=i.rates??i;Array.isArray(o)||(console.error('Error: expected { "rates": [...] } or a JSON array'),process.exit(1)),o.length>500&&(console.error(`Error: max 500 rates per call (got ${o.length}). Split into batches.`),process.exit(1));let s=await h2(r,o);if(n.json)console.log(JSON.stringify(s.data,null,2));else{let a=s.data.resourceIds??[];console.log(Y(`${a.length} rate(s) upserted.`)),a.forEach(c=>console.log(` ${c}`))}Ie(r,"bulk_upsert_currency_rates",n,s.data)}))}Gh();gt();import{readFileSync as ICr}from"node:fs";import{basename as dit,extname as wCr,resolve as _Cr}from"node:path";Pt();Lt();Fe();var DCr=[{key:"resourceId",header:"ID",format:Te},{key:"fileName",header:"File Name"}],ff=["invoices","bills","journals","scheduled_journals","customer-credit-notes","supplier-credit-notes","sale-quotes","sale-orders","purchase-requests","purchase-orders"],SCr={".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".csv":"text/csv",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};function fit(t){let e=t.command("attachments").description("Manage transaction attachments");e.command("list").description("List attachments for a transaction").requiredOption("--type <type>",`Transaction type (${ff.join(", ")})`).requiredOption("--id <resourceId>","Transaction resourceId").option("--api-key <key>","API key").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=n.type;ff.includes(i)||(console.error(ie(`Invalid type. Use one of: ${ff.join(", ")}`)),process.exit(1));let o=await si(r,i,n.id),s=o.data??[],a={data:s,totalElements:o.totalElements??s.length,totalPages:o.totalPages??1,truncated:o.truncated??!1};$e(a,DCr,n,"Attachments")})),e.command("add").description("Add an attachment to a transaction (file upload or URL download)").option("--jot <text>",we).requiredOption("--type <type>",`Transaction type (${ff.join(", ")})`).requiredOption("--id <resourceId>","Transaction resourceId").option("--file <path>","Local file path (PDF, PNG, JPG, etc.)").option("--url <url>","Download file from URL and attach").option("--attachment-id <id>","Link existing attachment by ID").option("--api-key <key>","API key").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=n.type;ff.includes(i)||(console.error(ie(`Invalid type. Use one of: ${ff.join(", ")}`)),process.exit(1)),!n.attachmentId&&!n.url&&!n.file&&(console.error(ie("Provide --file, --url, or --attachment-id")),process.exit(1)),n.attachmentId&&FH.includes(i)&&(console.error(ie(`link-by-id (--attachment-id) is not supported for order documents (${i}). Use --file or --url instead.`)),process.exit(1));let o,s;if(n.file){let c=_Cr(n.file),u=wCr(c).toLowerCase(),d=SCr[u]??"application/octet-stream",f=ICr(c);o=new Blob([f],{type:d}),s=dit(c)}else if(n.url){let c=await fetch(n.url);c.ok||(console.error(ie(`Failed to download: ${c.status} ${c.statusText}`)),process.exit(1));let u=await c.arrayBuffer(),d=c.headers.get("content-type")??"application/octet-stream";o=new Blob([u],{type:d});let f=new URL(n.url).pathname;s=dit(f)||"attachment"}let a=await QH(r,{businessTransactionType:i,businessTransactionResourceId:n.id,file:o,fileName:s,attachmentId:n.attachmentId});n.json?console.log(JSON.stringify(a,null,2)):console.log(Y("Attachment added.")),Ie(r,"add_attachment",n,a.data)})),e.command("delete").description("Delete an attachment from a transaction").option("--jot <text>",we).requiredOption("--type <type>",`Transaction type (${ff.join(", ")})`).requiredOption("--id <resourceId>","Transaction resourceId").argument("<attachmentResourceId>","Attachment resourceId to delete").option("--api-key <key>","API key").option("--json","Output as JSON").action((r,n)=>{let i=n.type;return ff.includes(i)||(console.error(ie(`Invalid type. Use one of: ${ff.join(", ")}`)),process.exit(1)),Q(async o=>{let s=await LH(o,i,n.id,r);n.json?console.log(JSON.stringify(s,null,2)):console.log(Y("Attachment deleted.")),Ie(o,"delete_attachment",n,{resourceId:r})})(n)})}Fe();nD();pc();gt();kt();dr();Pt();Lt();fr();var pit=[{key:"resourceId",header:"ID",format:Te},{key:"name",header:"Name"},{key:"taxRate",header:"Rate (%)"},{key:"taxTypeCode",header:"Tax Type"}],RCr=[{key:"code",header:"Code"},{key:"name",header:"Name"}];function hit(t){let e=t.command("tax-profiles").description("Manage tax profiles and tax types");e.command("list").description("List tax profiles").option("--limit <n>","Max results (default 100)",Ee).option("--offset <n>","Page number offset (0-indexed)",Je).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",Ee).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=await He(n,o=>Qb(r,o),{label:"Fetching tax profiles"});$e(i,pit,n,"Tax Profiles")})),e.command("types").description("List available tax types (GST, VAT, WHT, etc.)").option("--limit <n>","Max results (default 100)",Ee).option("--offset <n>","Page number offset (0-indexed)",Je).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",Ee).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=await He(n,o=>BL(r,o),{label:"Fetching tax types"});$e(i,RCr,n,"Tax Types")})),e.command("get <resourceId>").description("Get a tax profile by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let s=(await TL(i,r)).data;n.json?console.log(JSON.stringify(s,null,2)):(console.log(R("Name:"),s.name),console.log(R("ID:"),s.resourceId),console.log(R("Rate:"),`${s.taxRate}%`),console.log(R("Tax Type:"),s.taxTypeCode))})(n)),We({parent:e,fields:hS,defaults:mS,fetcher:Lb,columns:pit,label:"Searching tax profiles"}),e.command("update <resourceId>").description("Update a tax profile").option("--jot <text>",we).option("--name <name>","New name").option("--rate <n>","New tax rate as percentage",Ee).option("--tax-type-code <code>","New tax type code").option("--status <status>","New status (ACTIVE, INACTIVE)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let o={};n.name!==void 0&&(o.name=n.name),n.rate!==void 0&&(o.taxRate=n.rate),n.taxTypeCode!==void 0&&(o.taxTypeCode=n.taxTypeCode),n.status!==void 0&&(o.status=n.status);let s=await kL(i,r,o);n.json?console.log(JSON.stringify(s.data,null,2)):console.log(Y(`Tax profile updated: ${s.data.name}`)),Ie(i,"update_tax_profile",n,s.data)})(n)),e.command("wht-codes").description("List withholding tax codes").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=await NL(r);if(n.json)console.log(JSON.stringify(i.data,null,2));else{if(i.data.length===0){console.log("No withholding tax codes found.");return}console.log(R(`Withholding Tax Codes (${i.data.length}):
|
|
1061
|
-
`));for(let o of i.data)console.log(` ${Be(o.code??o.resourceId??"?")} ${o.description??""} ${G(o.countryCode??"")}`)}})),e.command("create").description("Create a new tax profile").option("--jot <text>",we).option("--name <name>",'Tax profile name (e.g., "GST 9%")').option("--rate <n>","Tax rate as percentage (e.g., 9)",Ee).option("--tax-type-code <code>","Tax type code (from tax-profiles types)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{Le(n,[{flag:"--name",key:"name"},{flag:"--rate",key:"rate"},{flag:"--tax-type-code",key:"taxTypeCode"}]);let i=await dM(r,n.name);if(i){n.json?console.log(JSON.stringify({_guard:"duplicate_skipped",existing:i},null,2)):console.log(Oe(`Tax profile "${n.name}" already exists (${i.resourceId}).`));return}let o=await xL(r,{name:n.name,taxRate:n.rate,taxTypeCode:n.taxTypeCode});n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(Y(`Tax profile created: ${n.name} (${n.rate}%)`)),console.log(R("ID:"),o.data.resourceId)),Ie(r,"create_tax_profile",n,o.data)}))}Fe();YL();PY();pc();gt();kt();dr();Pt();Lt();fr();var mit=[{key:"resourceId",header:"ID",format:Te},{key:"name",header:"Name"},{key:"isDefault",header:"Default"},{key:"expenseAccountResourceId",header:"Expense Acct",format:Te}];function Ait(t){let e=t.command("claim-types").description("Manage employee-expense claim types (expense categories)");e.command("list").description("List claim types").option("--limit <n>","Max results (default 100)",Ee).option("--offset <n>","Page number offset (0-indexed)",Je).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",Ee).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=await He(n,o=>PL(r,o),{label:"Fetching claim types"});$e(i,mit,n,"Claim Types")})),e.command("get <resourceId>").description("Get a claim type by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let s=(await UL(i,r)).data;n.json?console.log(JSON.stringify(s,null,2)):(console.log(R("Name:"),s.name),console.log(R("ID:"),s.resourceId),console.log(R("Default:"),s.isDefault),s.expenseAccount&&console.log(R("Expense Account:"),`${s.expenseAccount.code} ${s.expenseAccount.name}`),s.taxProfile&&console.log(R("Tax Profile:"),s.taxProfile.name))})(n)),We({parent:e,fields:eS,defaults:tS,fetcher:Pb,columns:mit,label:"Searching claim types"}),e.command("create").description("Create a claim type").option("--name <name>","Claim type name (unique per org)").option("--expense-account <id>","Default expense account resourceId").option("--tax-profile <id>","Default tax profile resourceId").option("--classifier-config <json>","Magic OCR classifier defaults (JSON string)").option("--default","Make org default").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{Le(n,[{flag:"--name",key:"name"}]);let i=await pM(r,n.name);if(i){n.json?console.log(JSON.stringify({_guard:"duplicate_skipped",existing:i},null,2)):console.log(Oe(`Claim type "${n.name}" already exists (${i.resourceId}).`));return}let o=await $L(r,{name:n.name,expenseAccountResourceId:n.expenseAccount,taxProfileResourceId:n.taxProfile,classifierConfig:n.classifierConfig,isDefault:n.default});n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(Y(`Claim type created: ${n.name}`)),console.log(R("ID:"),o.data.resourceId))})),e.command("update <resourceId>").description("Update a claim type").option("--name <name>","New name").option("--expense-account <id>","Default expense account resourceId").option("--tax-profile <id>","Default tax profile resourceId").option("--classifier-config <json>","Classifier defaults (JSON string)").option("--default","Make org default").option("--clear <fields>","Comma-separated optional fields to NULL (expenseAccountResourceId,taxProfileResourceId,classifierConfig)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let o={};n.name!==void 0&&(o.name=n.name),n.expenseAccount!==void 0&&(o.expenseAccountResourceId=n.expenseAccount),n.taxProfile!==void 0&&(o.taxProfileResourceId=n.taxProfile),n.classifierConfig!==void 0&&(o.classifierConfig=n.classifierConfig),n.default!==void 0&&(o.isDefault=n.default),Object.assign(o,sy(Io(n.clear),oD));let s=await qL(i,r,o);n.json?console.log(JSON.stringify(s.data,null,2)):console.log(Y(`Claim type updated: ${s.data.name}`))})(n)),e.command("delete <resourceId>").description("Soft-delete a claim type").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{await jL(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(Y(`Claim type deleted: ${r}`))})(n))}Fe();cD();PY();pc();gt();kt();dr();Pt();Lt();fr();var git=[{key:"resourceId",header:"ID",format:Te},{key:"name",header:"Name"},{key:"isDefault",header:"Default"},{key:"taxMode",header:"Tax Mode"},{key:"employeeBalanceAccountResourceId",header:"Balance Acct",format:Te}];function yit(t){let e={};return t.name!==void 0&&(e.name=t.name),t.approver!==void 0&&(e.approverUserResourceId=t.approver),t.visibleClaimTypes!==void 0&&(e.visibleClaimTypeIds=Io(t.visibleClaimTypes)),t.visibleTaxProfiles!==void 0&&(e.visibleTaxProfileIds=Io(t.visibleTaxProfiles)),t.visibleClassifiers!==void 0&&(e.visibleClassifierIds=Io(t.visibleClassifiers)),t.visibleVendors!==void 0&&(e.visibleVendorResourceIds=Io(t.visibleVendors)),t.allowedCurrencies!==void 0&&(e.allowedCurrencies=Io(t.allowedCurrencies)),t.minAmount!==void 0&&(e.minClaimAmount=t.minAmount),t.maxAmount!==void 0&&(e.maxClaimAmount=t.maxAmount),t.maxPerPeriod!==void 0&&(e.maxPerPeriodAmount=t.maxPerPeriod),t.perPeriod!==void 0&&(e.perPeriod=t.perPeriod),t.balanceAccount!==void 0&&(e.employeeBalanceAccountResourceId=t.balanceAccount),t.taxMode!==void 0&&(e.taxMode=t.taxMode),t.default!==void 0&&(e.isDefault=t.default),e}function Eit(t){return t.option("--approver <id>","Default approver user resourceId").option("--visible-claim-types <ids>","Allowed claim type IDs (comma-separated)").option("--visible-tax-profiles <ids>","Allowed tax profile IDs (comma-separated)").option("--visible-classifiers <ids>","Allowed classifier IDs (comma-separated)").option("--visible-vendors <ids>","Allowed vendor contact IDs (comma-separated)").option("--allowed-currencies <codes>","Allowed ISO currency codes (comma-separated)").option("--min-amount <n>","Min claim total",lr).option("--max-amount <n>","Max claim total",lr).option("--max-per-period <n>","Per-period spend cap (requires --per-period)",lr).option("--per-period <window>","DAILY | WEEKLY | MONTHLY | QUARTERLY | YEARLY").option("--balance-account <id>","Employee balance (CURRENT_LIABILITY) account resourceId").option("--tax-mode <mode>","NO_TAX | INCLUSIVE (EXCLUSIVE rejected)").option("--default","Make org default")}function bit(t){let e=t.command("claim-profiles").description("Manage employee-expense claim profiles (per-employee policy bundles)");e.command("list").description("List claim profiles").option("--limit <n>","Max results (default 100)",Ee).option("--offset <n>","Page number offset (0-indexed)",Je).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",Ee).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=await He(n,o=>HL(r,o),{label:"Fetching claim profiles"});$e(i,git,n,"Claim Profiles")})),e.command("get <resourceId>").description("Get a claim profile by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let s=(await zL(i,r)).data;n.json?console.log(JSON.stringify(s,null,2)):(console.log(R("Name:"),s.name),console.log(R("ID:"),s.resourceId),console.log(R("Default:"),s.isDefault),s.taxMode&&console.log(R("Tax mode:"),s.taxMode),s.employeeBalanceAccount&&console.log(R("Balance account:"),`${s.employeeBalanceAccount.code} ${s.employeeBalanceAccount.name}`))})(n)),We({parent:e,fields:rS,defaults:nS,fetcher:Ub,columns:git,label:"Searching claim profiles"}),Eit(e.command("create").description("Create a claim profile").option("--name <name>","Profile name (unique per org)")).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{Le(n,[{flag:"--name",key:"name"}]);let i=await hM(r,n.name);if(i){n.json?console.log(JSON.stringify({_guard:"duplicate_skipped",existing:i},null,2)):console.log(Oe(`Claim profile "${n.name}" already exists (${i.resourceId}).`));return}let o=await GL(r,yit(n));n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(Y(`Claim profile created: ${n.name}`)),console.log(R("ID:"),o.data.resourceId))})),Eit(e.command("update <resourceId>").description("Update a claim profile").option("--name <name>","New name")).option("--clear <fields>","Comma-separated optional fields to NULL (e.g. approverUserResourceId,perPeriod,taxMode)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let o=yit(n);Object.assign(o,sy(Io(n.clear),aD));let s=await JL(i,r,o);n.json?console.log(JSON.stringify(s.data,null,2)):console.log(Y(`Claim profile updated: ${s.data.name}`))})(n)),e.command("delete <resourceId>").description("Soft-delete a claim profile").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{await VL(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(Y(`Claim profile deleted: ${r}`))})(n))}Fe();dD();pc();gt();kt();dr();Pt();Lt();fr();var Cit=[{key:"resourceId",header:"ID",format:Te},{key:"name",header:"Name"},{key:"outerAxis",header:"Outer"},{key:"innerAxis",header:"Inner"},{key:"isDefault",header:"Default"}];function vit(t){let e=t.command("posting-rules").description("Manage claim posting rules (how approved claims group into journals at conversion)");e.command("list").description("List posting rules").option("--limit <n>","Max results (default 100)",Ee).option("--offset <n>","Page number offset (0-indexed)",Je).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",Ee).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=await He(n,o=>WL(r,o),{label:"Fetching posting rules"});$e(i,Cit,n,"Posting Rules")})),e.command("get <resourceId>").description("Get a posting rule by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let s=(await ZL(i,r)).data;n.json?console.log(JSON.stringify(s,null,2)):(console.log(R("Name:"),s.name),console.log(R("ID:"),s.resourceId),console.log(R("Outer axis:"),s.outerAxis),console.log(R("Inner axis:"),s.innerAxis),console.log(R("Line template:"),s.lineDescriptionTemplate),console.log(R("Default:"),s.isDefault))})(n)),We({parent:e,fields:iS,defaults:oS,fetcher:$b,columns:Cit,label:"Searching posting rules"}),e.command("create").description("Create a posting rule").option("--name <name>","Rule name (unique per org)").option("--outer-axis <axis>","PER_EMPLOYEE | PER_VENDOR | PER_PAIR | ONE_BATCH | PER_CLAIM").option("--inner-axis <axis>","RAW | BY_CT_TP_NC | BY_CT_TP_NC_EMPLOYEE | BY_CT_TP_NC_VENDOR").option("--line-template <tpl>",'Handlebars line template, e.g. "{employeeName} - {claimType}"').option("--journal-reference-template <tpl>","Optional journal-header reference template").option("--default-bank-account <id>","Default reimbursement bank account resourceId").option("--default-include-payout","Create reimbursement DCE by default").option("--default","Make org default rule").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{Le(n,[{flag:"--name",key:"name"},{flag:"--outer-axis",key:"outerAxis"},{flag:"--inner-axis",key:"innerAxis"},{flag:"--line-template",key:"lineTemplate"}]);let i=await mM(r,n.name);if(i){n.json?console.log(JSON.stringify({_guard:"duplicate_skipped",existing:i},null,2)):console.log(Oe(`Posting rule "${n.name}" already exists (${i.resourceId}).`));return}let o=await KL(r,{name:n.name,outerAxis:n.outerAxis,innerAxis:n.innerAxis,lineDescriptionTemplate:n.lineTemplate,journalReferenceTemplate:n.journalReferenceTemplate,defaultBankAccountResourceId:n.defaultBankAccount,defaultIncludeReimbursementPayout:n.defaultIncludePayout,isDefault:n.default});n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(Y(`Posting rule created: ${n.name}`)),console.log(R("ID:"),o.data.resourceId))})),e.command("update <resourceId>").description("Update a posting rule").option("--name <name>","New name").option("--outer-axis <axis>","Outer grouping axis").option("--inner-axis <axis>","Inner line-aggregation axis").option("--line-template <tpl>","Handlebars line template").option("--journal-reference-template <tpl>","Journal-header reference template").option("--default-bank-account <id>","Default reimbursement bank account resourceId").option("--default-include-payout <bool>","Create reimbursement DCE by default (true/false)").option("--default","Make org default rule").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let o={};n.name!==void 0&&(o.name=n.name),n.outerAxis!==void 0&&(o.outerAxis=n.outerAxis),n.innerAxis!==void 0&&(o.innerAxis=n.innerAxis),n.lineTemplate!==void 0&&(o.lineDescriptionTemplate=n.lineTemplate),n.journalReferenceTemplate!==void 0&&(o.journalReferenceTemplate=n.journalReferenceTemplate),n.defaultBankAccount!==void 0&&(o.defaultBankAccountResourceId=n.defaultBankAccount),n.defaultIncludePayout!==void 0&&(o.defaultIncludeReimbursementPayout=n.defaultIncludePayout==="true"),n.default!==void 0&&(o.isDefault=n.default);let s=await XL(i,r,o);n.json?console.log(JSON.stringify(s.data,null,2)):console.log(Y(`Posting rule updated: ${s.data.name}`))})(n)),e.command("delete <resourceId>").description("Delete a posting rule (the org default cannot be deleted while default)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{await eM(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(Y(`Posting rule deleted: ${r}`))})(n))}Fe();ZM();vue();Iue();u_();MH();gt();kt();Lt();kf();fr();import{randomUUID as BCr}from"node:crypto";import{readFileSync as Iit,statSync as xCr}from"node:fs";import{basename as TCr,extname as kCr,resolve as wit}from"node:path";var NCr=[{key:"resourceId",header:"ID",format:Te},{key:"reference",header:"Reference"},{key:"status",header:"Status"},{key:"employeeResourceId",header:"Employee",format:Te},{key:"totalAmount",header:"Amount"},{key:"currencyCode",header:"Ccy"}];function _it(t){let e=t.command("claims").description("Employee-expense claims: search, edit drafts, lifecycle, bulk actions");We({parent:e,fields:WD,defaults:ZD,fetcher:NM,columns:NCr,label:"Searching claims"}),e.command("get <resourceId>").description("Get a claim by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((s,a)=>Q(async c=>{let d=(await OM(c,s)).data;a.json?console.log(JSON.stringify(d,null,2)):(console.log(R("Reference:"),d.reference??"\u2014"),console.log(R("ID:"),d.resourceId),console.log(R("Status:"),d.status),console.log(R("Total:"),`${d.totalAmount??0} ${d.currencyCode??""}`),console.log(R("Lines:"),(d.claimItems??[]).length))})(a)),e.command("create").description("Create a claim directly (bare create). Vendor is EITHER --contact OR --vendor-name. --items / --custom-fields take a JSON array string.").requiredOption("--value-date <date>","Business-transaction date (YYYY-MM-DD)").requiredOption("--currency <code>","Claim currency (ISO 4217)").option("--reference <ref>","User reference").option("--employee <id>","Employee resourceId the claim is filed for").option("--contact <id>","Vendor contact resourceId").option("--vendor-name <name>","Free-text vendor name").option("--currency-symbol <symbol>","Currency symbol override").option("--internal-notes <text>","Internal notes").option("--claim-profile <id>","Claim profile resourceId").option("--approver <id>","Approver user resourceId").option("--tags <list>","Header tags (comma-separated)").option("--items <json>","Line items as a JSON array").option("--custom-fields <json>","Custom field values as a JSON array").option("--submit","Validate + submit in one call (saveAsDraft=false). Requires --reference (else 422 CLAIM_REFERENCE_REQUIRED_AT_SUBMIT)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(s=>Q(async a=>{let c={valueDate:s.valueDate,currencyCode:s.currency};s.reference!==void 0&&(c.reference=s.reference),s.employee!==void 0&&(c.employeeResourceId=s.employee),s.contact!==void 0&&(c.contactResourceId=s.contact),s.vendorName!==void 0&&(c.vendorName=s.vendorName),s.currencySymbol!==void 0&&(c.currencySymbol=s.currencySymbol),s.internalNotes!==void 0&&(c.internalNotes=s.internalNotes),s.claimProfile!==void 0&&(c.claimProfileResourceId=s.claimProfile),s.approver!==void 0&&(c.approverUserResourceId=s.approver),s.tags!==void 0&&(c.tags=Io(s.tags)??[]),s.items!==void 0&&(c.claimItems=gu(s.items,"--items")),s.customFields!==void 0&&(c.customFields=gu(s.customFields,"--custom-fields")),s.submit&&(c.saveAsDraft=!1);let u=await FM(a,c);s.json?console.log(JSON.stringify(u.data,null,2)):console.log(Y(`Claim created: ${u.data.reference??u.data.resourceId} (${u.data.status})`))})(s)),e.command("update <resourceId>").description("Update a DRAFT claim (partial). --items / --custom-fields take a JSON array string.").option("--reference <ref>","User reference").option("--value-date <date>","Business-transaction date (YYYY-MM-DD)").option("--employee <id>","Employee resourceId").option("--contact <id>","Vendor contact resourceId").option("--vendor-name <name>","Free-text vendor name").option("--currency <code>","Claim currency (ISO 4217)").option("--internal-notes <text>","Internal notes").option("--claim-profile <id>","Claim profile resourceId").option("--approver <id>","Approver user resourceId").option("--tags <list>","Header tags (comma-separated)").option("--items <json>","Line items as a JSON array (REPLACES all lines)").option("--custom-fields <json>","Custom field values as a JSON array").option("--submit","Validate + submit in one call (saveAsDraft=false). Requires --reference (else 422 CLAIM_REFERENCE_REQUIRED_AT_SUBMIT)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((s,a)=>Q(async c=>{let u={};a.reference!==void 0&&(u.reference=a.reference),a.valueDate!==void 0&&(u.valueDate=a.valueDate),a.employee!==void 0&&(u.employeeResourceId=a.employee),a.contact!==void 0&&(u.contactResourceId=a.contact),a.vendorName!==void 0&&(u.vendorName=a.vendorName),a.currency!==void 0&&(u.currencyCode=a.currency),a.internalNotes!==void 0&&(u.internalNotes=a.internalNotes),a.claimProfile!==void 0&&(u.claimProfileResourceId=a.claimProfile),a.approver!==void 0&&(u.approverUserResourceId=a.approver),a.tags!==void 0&&(u.tags=Io(a.tags)??[]),a.items!==void 0&&(u.claimItems=gu(a.items,"--items")),a.customFields!==void 0&&(u.customFields=gu(a.customFields,"--custom-fields")),a.submit&&(u.saveAsDraft=!1);let d=await QM(c,s,u);a.json?console.log(JSON.stringify(d.data,null,2)):console.log(Y(`Claim updated: ${d.data.reference??d.data.resourceId} (${d.data.status})`))})(a)),e.command("delete <resourceId>").description("Delete a claim (only DRAFT / REJECTED / CANCELLED)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((s,a)=>Q(async c=>{await LM(c,s),a.json?console.log(JSON.stringify({deleted:!0,resourceId:s})):console.log(Y(`Claim deleted: ${s}`))})(a)),e.command("delete-attachment <resourceId> <attachmentResourceId>").description("Remove one attachment from a claim").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((s,a,c)=>Q(async u=>{await MM(u,s,a),c.json?console.log(JSON.stringify({deleted:!0,resourceId:s,attachmentResourceId:a})):console.log(Y(`Attachment removed from claim ${s}`))})(c));let r=[["submit",PM,"Submit a DRAFT claim for approval"],["approve",UM,"Approve a SUBMITTED claim"],["unpost",jM,"Unpost a CONVERTED claim (reverse conversion)"]];for(let[s,a,c]of r)e.command(`${s} <resourceId>`).description(c).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((u,d)=>Q(async f=>{let p=await a(f,u);d.json?console.log(JSON.stringify(p,null,2)):console.log(Y(`Claim ${s}: ${u}${p.data?.status?` (${p.data.status})`:""}`))})(d));let n=[["reject",$M,"Reject a SUBMITTED/APPROVED claim"],["cancel",qM,"Cancel a DRAFT/SUBMITTED claim"]];for(let[s,a,c]of n)e.command(`${s} <resourceId>`).description(c).option("--reason <text>","Reason (1-1000 chars), required").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((u,d)=>Q(async f=>{Le(d,[{flag:"--reason",key:"reason"}]);let p=await a(f,u,d.reason);d.json?console.log(JSON.stringify(p,null,2)):console.log(Y(`Claim ${s}ed: ${u}${p.data?.status?` (${p.data.status})`:""}`))})(d));let i=[["bulk-submit",YM,"Bulk-submit DRAFT claims (async)"],["bulk-approve",HM,"Bulk-approve SUBMITTED claims (async)"],["bulk-delete",zM,"Bulk-delete DRAFT/REJECTED/CANCELLED claims (async)"]];for(let[s,a,c]of i)e.command(s).description(`${c}. Poll with: clio background-jobs search`).option("--ids <list>","Claim resourceIds (comma-separated, 1-500)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(u,d)=>{Le(d,[{flag:"--ids",key:"ids"}]);let f=await a(u,Io(d.ids)??[]);d.json?console.log(JSON.stringify(f,null,2)):console.log(Y(`Queued ${s} \u2014 jobId ${f.data?.jobId??"?"}`))}));let o=[["bulk-reject",GM,"Bulk-reject claims (async)"],["bulk-cancel",JM,"Bulk-cancel claims (async)"]];for(let[s,a,c]of o)e.command(s).description(`${c}. Poll with: clio background-jobs search`).option("--ids <list>","Claim resourceIds (comma-separated, 1-500)").option("--reason <text>","Shared reason (1-1000 chars), required").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(u,d)=>{Le(d,[{flag:"--ids",key:"ids"},{flag:"--reason",key:"reason"}]);let f=await a(u,Io(d.ids)??[],d.reason);d.json?console.log(JSON.stringify(f,null,2)):console.log(Y(`Queued ${s} \u2014 jobId ${f.data?.jobId??"?"}`))}));e.command("tracking-tags").description("List claim tracking-tag values (picker)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(s,a)=>{let c=await VM(s);if(a.json)console.log(JSON.stringify(c,null,2));else{console.log(R(`Tracking tags (${c.length}):`));for(let u of c)console.log(` ${typeof u=="string"?u:JSON.stringify(u)}`)}})),e.command("custom-field-values").description("List claim custom-field values (picker)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(s,a)=>{let c=await WM(s);a.json?console.log(JSON.stringify(c,null,2)):console.log(Oe(c.length===0?"No custom field values.":`${c.length} custom field value(s).`))})),e.command("preview-conversion").description("Preview the journals an APPROVED claim batch would produce (no write)").option("--ids <list>","APPROVED claim resourceIds (comma-separated)").option("--posting-rule <id>","Posting rule resourceId (default: org default)").option("--payout-flow <flow>","POST | POST_AND_RECORD").option("--include-payout","Include reimbursement DCE lines").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(s,a)=>{if(Le(a,[{flag:"--ids",key:"ids"}]),a.payoutFlow!==void 0&&!Yx.includes(a.payoutFlow))throw new Error(`--payout-flow must be one of: ${Yx.join(", ")}`);let c=await PH(s,{claimResourceIds:Io(a.ids)??[],postingRuleResourceId:a.postingRule,payoutFlow:a.payoutFlow,includeReimbursementPayout:a.includePayout});console.log(JSON.stringify(c.data,null,2))})),e.command("convert").description("Convert an APPROVED claim batch into journals (atomic). Preview first.").option("--ids <list>","APPROVED claim resourceIds (comma-separated)").option("--value-date <date>","Journal value date (YYYY-MM-DD), required").option("--posting-rule <id>","Posting rule resourceId (default: org default)").option("--include-payout","Create books-only reimbursement DCEs").option("--bank-account <id>","Override reimbursement bank account").option("--idempotency-key <key>","Retry-dedup token (auto-generated if omitted)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(s,a)=>{Le(a,[{flag:"--ids",key:"ids"},{flag:"--value-date",key:"valueDate"}]);let c=await UH(s,{claimResourceIds:Io(a.ids)??[],valueDate:a.valueDate,postingRuleResourceId:a.postingRule,includeReimbursementPayout:a.includePayout,bankAccountResourceIdOverride:a.bankAccount,idempotencyKey:a.idempotencyKey||BCr()});a.json?console.log(JSON.stringify(c.data,null,2)):console.log(Y("Claims converted to journals."))})),e.command("record-payout").description("Record a books-only employee payout (reimbursement / advance)").option("--employee <id>","Employee resourceId").option("--amount <n>","Payout amount (> 0)",lr).option("--payment-account <id>","Bank/cash account the DCE credits").option("--value-date <date>","Value date (YYYY-MM-DD)").option("--payout-for <type>","REIMBURSEMENT | ADVANCE (default ADVANCE)").option("--currency <code>","Settle currency (ISO 4217)").option("--reference <ref>","Payout reference (auto-generated if omitted)").option("--description <text>","DCE line description").option("--internal-notes <text>","Internal notes").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(s,a)=>{Le(a,[{flag:"--employee",key:"employee"},{flag:"--amount",key:"amount"},{flag:"--payment-account",key:"paymentAccount"},{flag:"--value-date",key:"valueDate"}]);let c=await $H(s,{employeeResourceId:a.employee,amount:a.amount,paymentAccountResourceId:a.paymentAccount,valueDate:a.valueDate,payoutFor:a.payoutFor,currencyCode:a.currency,reference:a.reference||$a("EP"),description:a.description,internalNotes:a.internalNotes});a.json?console.log(JSON.stringify(c.data,null,2)):console.log(Y(`Payout recorded: ${c.data.resourceId}`))})),We({parent:e,commandName:"payouts",fields:KD,defaults:XD,fetcher:qH,columns:[{key:"resourceId",header:"ID",format:Te},{key:"reference",header:"Reference"},{key:"employeeResourceId",header:"Employee",format:Te},{key:"amount",header:"Amount"},{key:"payoutType",header:"Type"}],label:"Searching employee payouts"}),e.command("from-attachment").description("Create a claim DRAFT from a receipt via AI extraction \u2014 a local file (--file), a remote URL (--source-url), or raw HTML (--html)").option("--file <path>","Local receipt file (PDF / JPG / PNG / HEIC / XLS / XLSX / EML)").option("--source-url <url>","Remote receipt file URL (alternative to --file)").option("--html <value>","Raw HTML (e.g. an email body) \u2014 inline or @path to read from a file").option("--contact <id>","Vendor contact resourceId").option("--claim-profile <id>","Claim profile resourceId").option("--employee <id>","File on behalf of this employee resourceId (default: the uploader's own; server requires a claims Manager/Admin to name another)").option("--currency <code>","Currency override (ISO 4217)").option("--value-date <date>","Value date override (YYYY-MM-DD)").option("--internal-notes <text>","Internal notes").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(s,a)=>{if([a.file,a.sourceUrl,a.html].filter(Boolean).length!==1)throw new Error("provide exactly one of --file / --source-url / --html.");let u,d;if(a.file){let h=wit(a.file),m=kCr(h).toLowerCase();if(!dd.has(m))throw new Error(`unsupported file type "${m}". Supported: ${[...dd].join(", ")}`);let A=25*1024*1024,g=xCr(h).size;if(g>A)throw new Error(`file too large (${(g/1048576).toFixed(1)}MB > 25MB). Compress or split the receipt.`);u=new Blob([Iit(h)],{type:Ym(m)}),d=TCr(h)}let f;a.html&&(a.html.startsWith("@")||console.error(Oe("Warning: passing HTML inline can leak invoice data into shell history \u2014 prefer --html @path.")),f=a.html.startsWith("@")?Iit(wit(a.html.slice(1)),"utf8"):a.html);let p=await cb(s,{sourceFile:u,sourceFileName:d,sourceURL:a.sourceUrl,html:f,contactResourceId:a.contact,claimProfileResourceId:a.claimProfile,employeeResourceId:a.employee,currencyCode:a.currency,valueDate:a.valueDate,internalNotes:a.internalNotes});console.log(JSON.stringify(p,null,2))}))}Fe();fD();pc();gt();kt();Lt();fr();var Dit=[{key:"resourceId",header:"ID",format:Te},{key:"name",header:"Name"},{key:"email",header:"Email"},{key:"employmentType",header:"Type"},{key:"active",header:"Active"}];function Sit(t){let e=t.command("employees").description("Manage employees (expense-claim members): CRUD, balances, bind-user, import");We({parent:e,fields:sS,defaults:aS,fetcher:qb,columns:Dit,label:"Searching employees"}),We({parent:e,commandName:"balances",fields:cS,defaults:lS,fetcher:tM,columns:Dit,label:"Searching employee balances"}),e.command("get <resourceId>").description("Get an employee by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let s=(await rM(i,r)).data;n.json?console.log(JSON.stringify(s,null,2)):(console.log(R("Name:"),s.name),console.log(R("ID:"),s.resourceId),console.log(R("Email:"),s.email??"\u2014"),console.log(R("Active:"),s.active),s.userBinding&&console.log(R("Bound user:"),`${s.userBinding.name??""} (${s.userBinding.status??""})`),s.claimProfile&&console.log(R("Claim profile:"),s.claimProfile.name))})(n)),e.command("create").description("Create an employee (requires --user to bind; binding is permanent)").option("--name <name>","Employee name").option("--user <id>","Login user resourceId to bind (required)").option("--claim-profile <id>","Claim profile resourceId (defaults to org default)").option("--email <email>","Work email").option("--phone <phone>","Phone").option("--manager <id>","Manager employee resourceId").option("--employment-type <type>","FULL_TIME | PART_TIME | CONTRACTOR | INTERN | TEMPORARY | CONSULTANT").option("--inactive","Create as inactive").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{if(Le(n,[{flag:"--name",key:"name"},{flag:"--user",key:"user"}]),n.email){let o=await AM(r,n.email);if(o){n.json?console.log(JSON.stringify({_guard:"duplicate_skipped",existing:o},null,2)):console.log(Oe(`Employee with email "${n.email}" already exists (${o.resourceId}).`));return}}let i=await nM(r,{name:n.name,userResourceId:n.user,claimProfileResourceId:n.claimProfile,email:n.email,phone:n.phone,managerEmployeeResourceId:n.manager,active:n.inactive?!1:void 0,employmentType:n.employmentType});n.json?console.log(JSON.stringify(i.data,null,2)):(console.log(Y(`Employee created: ${n.name}`)),console.log(R("ID:"),i.data.resourceId))})),e.command("update <resourceId>").description("Update an employee. Use --archive to deactivate (reversible).").option("--name <name>","New name").option("--email <email>","Work email").option("--phone <phone>","Phone").option("--manager <id>","Manager employee resourceId").option("--claim-profile <id>","Claim profile resourceId").option("--employment-type <type>","Employment classification").option("--archive","Set active=false (archive)").option("--activate","Set active=true").option("--clear-employment-type","Unset the classification").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let o={};if(n.name!==void 0&&(o.name=n.name),n.email!==void 0&&(o.email=n.email),n.phone!==void 0&&(o.phone=n.phone),n.manager!==void 0&&(o.managerEmployeeResourceId=n.manager),n.claimProfile!==void 0&&(o.claimProfileResourceId=n.claimProfile),n.employmentType!==void 0&&(o.employmentType=n.employmentType),n.archive&&n.activate)throw new Error("--archive and --activate are mutually exclusive.");n.archive&&(o.active=!1),n.activate&&(o.active=!0),n.clearEmploymentType&&(o.clearEmploymentType=!0);let s=await iM(i,r,o);n.json?console.log(JSON.stringify(s.data,null,2)):console.log(Y(`Employee updated: ${s.data.name??r}`))})(n)),e.command("delete <resourceId>").description("Delete an employee (must be settled). Prefer update --archive.").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{await oM(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(Y(`Employee deleted: ${r}`))})(n)),e.command("bind-user <resourceId> <userResourceId>").description("Bind a login user to an offline employee (no user bound yet). One-way, permanent \u2014 allowed only while unbound.").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n,i)=>Q(async o=>{let s=await sM(o,r,n);i.json?console.log(JSON.stringify(s.data,null,2)):console.log(Y(`Bound user ${n} to employee ${r}`))})(i)),e.command("preprocess <fileUrl>").description("Preview an employee import sheet before importing").option("--file-name <name>","Display file name").option("--file-type <type>","CSV | XLS | XLSX").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let o=await aM(i,{fileUrl:r,fileName:n.fileName,fileType:n.fileType});console.log(JSON.stringify(o.data,null,2))})(n)),e.command("import").description("Bulk import employees (async). Pass --create / --update / --delete JSON arrays (max 100 each).").option("--create <json>","Create rows (JSON array)").option("--update <json>","Update rows (JSON array, each with employeeResourceId)").option("--delete <json>","Delete rows (JSON array, each with employeeResourceId)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{let i={};n.create!==void 0&&(i.create=gu(n.create,"--create")),n.update!==void 0&&(i.update=gu(n.update,"--update")),n.delete!==void 0&&(i.delete=gu(n.delete,"--delete"));let o=await cM(r,i);n.json?console.log(JSON.stringify(o.data,null,2)):console.log(Y(`Queued employee import \u2014 jobId ${o.data?.jobId??"?"}`))}))}mue();gt();kt();dr();Pt();Lt();Fe();var OCr=[{key:"resourceId",header:"ID",format:Te},{key:"name",header:"Name"},{key:"categoryCode",header:"Category"},{key:"value",header:"Value"}];function Rit(t){let e=t.command("bookmarks").description("Manage organization bookmarks");e.command("list").description("List bookmarks").option("--limit <n>","Max results (default 100)",Ee).option("--offset <n>","Page number offset (0-indexed)",Je).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",Ee).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=await He(n,o=>AH(r,o),{label:"Fetching bookmarks"});$e(i,OCr,n,"Bookmarks")})),e.command("get <resourceId>").description("Get a bookmark by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let s=(await gH(i,r)).data;n.json?console.log(JSON.stringify(s,null,2)):(console.log(R("Name:"),s.name),console.log(R("ID:"),s.resourceId),console.log(R("Category:"),s.categoryCode),console.log(R("Value:"),s.value))})(n)),e.command("create").description("Create bookmark(s)").option("--name <name>","Bookmark name").option("--value <value>","Bookmark value").option("--category <code>","Category code (GENERAL_INFORMATION, TAXATION_AND_COMPLIANCE, etc.)").option("--datatype <code>","Datatype code (default: TEXT)").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=Ce(n),o;if(i?o=await qx(r,i.items??[i]):(Le(n,[{flag:"--name",key:"name"},{flag:"--value",key:"value"},{flag:"--category",key:"category"}]),o=await qx(r,[{name:n.name,value:n.value,categoryCode:n.category,datatypeCode:n.datatype??"TEXT"}])),n.json)console.log(JSON.stringify(o.data,null,2));else{console.log(Y(`Bookmark(s) created: ${o.data.length} item(s)`));for(let s of o.data)console.log(` ${Be(s.resourceId)} ${s.name}`)}})),e.command("update <resourceId>").description("Update a bookmark").option("--name <name>","New name").option("--value <value>","New value").option("--category <code>","New category code").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let o=Ce(n),s=o||{...n.name&&{name:n.name},...n.value&&{value:n.value},...n.category&&{categoryCode:n.category}},a=await yH(i,r,s);n.json?console.log(JSON.stringify(a.data,null,2)):console.log(Y(`Bookmark updated: ${a.data.name}`))})(n))}bH();gt();kt();Pt();dr();Lt();Fe();var FCr=[{key:"resourceId",header:"ID",format:Te},{key:"kind",header:"Kind"},{key:"tier",header:"Tier"},{key:"call",header:"Call"},{key:"dispositions",header:"Dispositions",format:t=>Array.isArray(t)?t.map(e=>e.verb).join(" "):String(t)},{key:"createdAt",header:"Created",format:mp}];function Bit(t){let e=t.command("jots").description("Judgment journal: record and look up judgment entries");e.command("create").description("Record judgment entries (batch via --input, single via flags)").option("--kind <kind>","Judgment kind (CLASSIFICATION, MATCH, SCOPE, ASSUMPTION, RISK, METHOD, RECOVERY, DEVIATION, NOTE)").option("--tier <tier>","Severity tier (LOW, MEDIUM, HIGH, CRITICAL)").option("--call <call>","The decision, one line").option("--why <why>","The basis for the call").option("--ruled-out <text>","Alternatives considered and set aside").option("--ref <ref...>","Entity ref, grammar TYPE:resourceId[#field][:RELATION] (repeatable)").option("--frame <frame>","Set anchor: defining query + counts").option("--confidence <level>","Routing hint (LOW, MEDIUM, HIGH)").option("--cited-rule <rule>","Org rule, policy, threshold, or precedent applied").option("--workflow-label <label>","Short workflow label (e.g. month-end-close)").option("--agent-label <label>","Self-reported product/model").option("--idempotency-key <key>","Retry key: a replay returns the existing entry").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=Ce(n),o;i?o=i.entries??[i]:(Le(n,[{flag:"--kind",key:"kind"},{flag:"--tier",key:"tier"},{flag:"--call",key:"call"}]),o=[{kind:n.kind,tier:n.tier,call:n.call,...n.why&&{why:n.why},...n.ruledOut&&{ruledOut:n.ruledOut},...n.ref&&{refs:n.ref},...n.frame&&{frame:n.frame},...n.confidence&&{confidence:n.confidence},...n.citedRule&&{citedRule:n.citedRule},...n.workflowLabel&&{workflowLabel:n.workflowLabel},...n.agentLabel&&{agentLabel:n.agentLabel},...n.idempotencyKey&&{idempotencyKey:n.idempotencyKey}}]),o=o.map(d=>({writePath:"CLI",...d}));let s=await yv(r,o),a=s.data.records??[],c=a.filter(d=>!d.error),u=a.length>0&&c.length===0;u&&(process.exitCode=1),n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(u?ie(`No jots recorded: ${a.length} error(s)`):Y(`Jot(s) recorded: ${c.length}/${a.length} entr${a.length===1?"y":"ies"}`)),a.forEach((d,f)=>{if(d.error)console.log(` ${Oe(`entry ${f}:`)} ${d.error}${d.errorCode?G(` (${d.errorCode})`):""}`);else{let p=[d.replayed&&"replayed",d.duplicateCount&&`${d.duplicateCount} similar`].filter(Boolean).join(", ");console.log(` ${Be(d.resourceId??"")}${p?G(` ${p}`):""}`)}}))})),e.command("recall").description("Search judgment entries (sort pinned server-side: critical first, then newest)").option("--ref <ref>","Entity ref filter, TYPE:resourceId").option("--kind <kind>","Judgment kind filter").option("--tier <tier>","Severity tier filter").option("--disposition-verb <verb>","Only entries with a disposition of this verb (FLAG, REJECT, ENDORSE)").option("--freetext <text>","Case-insensitive substring over call and why").option("--created-from <epochMs>","Created-at lower bound, epoch ms (inclusive)",Je).option("--created-to <epochMs>","Created-at upper bound, epoch ms (inclusive)",Je).option("--stats","Include per-credential disposition counts").option("--limit <n>","Max results (default 100)",Ee).option("--offset <n>","Page number offset (0-indexed)",Je).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",Ee).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{let i={...n.ref&&{ref:n.ref},...n.kind&&{kind:n.kind},...n.tier&&{tier:n.tier},...n.dispositionVerb&&{dispositionVerb:n.dispositionVerb},...n.freetext&&{freetext:n.freetext},...n.createdFrom!==void 0&&{createdFrom:n.createdFrom},...n.createdTo!==void 0&&{createdTo:n.createdTo}},o,s=await He(n,async a=>{let c=await EH(r,{limit:a.limit,offset:a.offset,...Object.keys(i).length?{filter:i}:{},...n.stats&&(!n.all||a.offset===0)&&{includeStats:!0}});return o??=c.stats,c},{label:"Fetching jots"});if($e(o?.length?{...s,stats:o}:s,FCr,n,"Jots"),n.stats&&o?.length&&!Al(n)){console.log(R("Disposition stats (per credential):"));for(let a of o)console.log(` ${a.credential??"(unknown)"} ${a.verb??""} ${a.count??0}`)}})),e.command("dispose <resourceId>").description("Append a review disposition to a jot (append-only)").option("--verb <verb>","Review verb: FLAG, REJECT, or ENDORSE").option("--note <note>","Optional reviewer note").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{Le(n,[{flag:"--verb",key:"verb"}]);let s=(await Trt(i,r,{verb:n.verb,...n.note&&{note:n.note}})).data;n.json?console.log(JSON.stringify(s,null,2)):(console.log(Y(`Disposition recorded: ${s.verb} on ${s.jotResourceId}`)),s.rollbackHandoff&&console.log(G(" Rollback handoff pointer returned: execution lives in the rollback module.")))})(n))}Aue();CD();gt();kt();dr();Pt();Lt();Fe();fr();function e8(t,e){return r=>{let n=r.toUpperCase();if(!t.includes(n))throw new Error(`Invalid ${e}: ${r}. Allowed: ${t.join(", ")}`);return n}}function xit(t){return Kb.map(e=>({moduleName:e,roleCode:t}))}var Tit=[{key:"resourceId",header:"ID",format:Te},{key:"firstName",header:"First Name"},{key:"lastName",header:"Last Name"},{key:"email",header:"Email"},{key:"moduleRoles",header:"Roles",format:t=>Array.isArray(t)?t.map(e=>`${e.moduleName}:${e.roleCode}`).join(", "):String(t??"")}];function kit(t){let e=t.command("org-users").description("Manage organization users");e.command("list").description("List organization users").option("--limit <n>","Max results (default 100)",Ee).option("--offset <n>","Page number offset (0-indexed)",Je).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",Ee).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=await He(n,o=>CH(r,o),{label:"Fetching org users"});$e(i,Tit,n,"Org Users")})),We({parent:e,fields:vS,defaults:IS,fetcher:vH,columns:Tit,label:"Searching org users",positionalArg:"name",positionalFilter:r=>({or:[{firstName:{contains:r}},{lastName:{contains:r}},{email:{contains:r}}]})}),e.command("invite").description("Invite a user to the organization").option("--jot <text>",we).option("--first-name <name>","First name").option("--last-name <name>","Last name").option("--email <email>","Email address").option("--user-type <type>","ADMIN | CUSTOM_USER (default: derived from --role)",e8(OA,"user-type")).option("--role <role>","Role code: ADMIN, PREPARER, MEMBER, NO_ACCESS (default: MEMBER). ADMIN \u2192 userType=ADMIN; others \u2192 userType=CUSTOM_USER with this role on every module.",e8(NA,"role")).option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=Ce(n),o;if(i)o=await Ev(r,i);else{Le(n,[{flag:"--first-name",key:"firstName"},{flag:"--last-name",key:"lastName"},{flag:"--email",key:"email"}]);let s=n.role??"MEMBER",a=n.userType??(s==="ADMIN"?"ADMIN":"CUSTOM_USER");o=await Ev(r,{firstName:n.firstName,lastName:n.lastName,email:n.email,userType:a,...a==="CUSTOM_USER"?{moduleRoles:xit(s)}:{}})}n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(Y(`User invited: ${n.firstName??""} ${n.lastName??""} (${n.email??""})`)),console.log(R("ID:"),o.data.resourceId)),Ie(r,"invite_org_user",n,o.data)})),e.command("update <resourceId>").description("Update a user's access tier and/or module roles").option("--jot <text>",we).option("--user-type <type>","ADMIN | CUSTOM_USER (default: derived from --role)",e8(OA,"user-type")).option("--role <role>","New role code: ADMIN, PREPARER, MEMBER, NO_ACCESS. ADMIN \u2192 userType=ADMIN; others \u2192 userType=CUSTOM_USER with this role on every module.",e8(NA,"role")).option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let o=Ce(n),s;if(o)s=o;else{if(!n.role&&!n.userType)throw new Error("At least one of --role or --user-type is required");let c=n.role,u=n.userType??(c==="ADMIN"?"ADMIN":c?"CUSTOM_USER":void 0);s={...u?{userType:u}:{},...u==="CUSTOM_USER"&&c?{moduleRoles:xit(c)}:{}}}let a=await IH(i,r,s);n.json?console.log(JSON.stringify(a.data,null,2)):console.log(Y(`User updated: ${a.data.firstName} ${a.data.lastName}`)),Ie(i,"update_org_user",n,a.data)})(n)),e.command("remove <resourceId>").description("Remove a user from the organization").option("--jot <text>",we).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{await wH(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(Y(`User ${r} removed.`)),Ie(i,"remove_org_user",n,{resourceId:r})})(n))}Fe();$x();fr();Lt();var QCr=[{key:"resourceId",header:"ID",format:Te},{key:"transactionReference",header:"Reference",format:$n},{key:"direction",header:"Dir",format:yL},{key:"valueDate",header:"Date",format:mp},{key:"totalAmount",header:"Amount",align:"right"},{key:"currencyCode",header:"Ccy"},{key:"businessTransactionType",header:"Type",format:t=>G(String(t??""))}];function Nit(t){let e=t.command("cashflow").description("Search cashflow transactions");We({parent:e,fields:xd,defaults:Td,fetcher:zh,columns:QCr,label:"Searching cashflow"})}function Oit(t){t.command("serve").description("HTTP daemon (not available in bundled CLI)").action(()=>{console.error("clio serve is not available in the bundled CLI. Use the full installation from the private repo."),process.exit(1)})}Fe();gt();kt();Yo();eue();pue();Xle();function ja(t){return t.option("--plan","Plan mode \u2014 show required accounts and step summary (offline, no auth)").option("--input <file>","Account mapping JSON file (optional \u2014 auto-resolves from chart of accounts if omitted)").option("--bank-account <id>","Bank/cash account name or resourceId (for cash-in/cash-out steps)").option("--contact <id>","Contact name or resourceId \u2014 supplier for bills, customer for invoices").option("--existing-txn <id>","Attach to existing transaction \u2014 skip initial step, create delta only").option("--ref <prefix>","Reference prefix (generates prefix-1, prefix-2, ...)").option("--finalize","Approve transactions immediately (default: create as drafts)").option("--jot <text>",we).option("--json","Output as JSON").option("--api-key <key>","API key override")}function Ya(t,e){return async r=>{try{let n=e(r);if(r.plan){let s=gv(t,n);r.json?console.log(JSON.stringify(s,null,2)):LCr(s);return}let i=Fx(n);i||(console.error(ie("Error: no blueprint generated. Provide --start-date to enable blueprint.")),process.exit(1)),await Q(async(s,a,c)=>{let u=!!a.json,d,f=Ce(a);if(f)d=f;else{let h=gv(t,n);u||process.stderr.write(G(` Auto-resolving accounts from chart of accounts...
|
|
1061
|
+
`));for(let o of i.data)console.log(` ${Be(o.code??o.resourceId??"?")} ${o.description??""} ${G(o.countryCode??"")}`)}})),e.command("create").description("Create a new tax profile").option("--jot <text>",we).option("--name <name>",'Tax profile name (e.g., "GST 9%")').option("--rate <n>","Tax rate as percentage (e.g., 9)",Ee).option("--tax-type-code <code>","Tax type code (from tax-profiles types)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{Le(n,[{flag:"--name",key:"name"},{flag:"--rate",key:"rate"},{flag:"--tax-type-code",key:"taxTypeCode"}]);let i=await dM(r,n.name);if(i){n.json?console.log(JSON.stringify({_guard:"duplicate_skipped",existing:i},null,2)):console.log(Oe(`Tax profile "${n.name}" already exists (${i.resourceId}).`));return}let o=await xL(r,{name:n.name,taxRate:n.rate,taxTypeCode:n.taxTypeCode});n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(Y(`Tax profile created: ${n.name} (${n.rate}%)`)),console.log(R("ID:"),o.data.resourceId)),Ie(r,"create_tax_profile",n,o.data)}))}Fe();YL();PY();pc();gt();kt();dr();Pt();Lt();fr();var mit=[{key:"resourceId",header:"ID",format:Te},{key:"name",header:"Name"},{key:"isDefault",header:"Default"},{key:"expenseAccountResourceId",header:"Expense Acct",format:Te}];function Ait(t){let e=t.command("claim-types").description("Manage employee-expense claim types (expense categories)");e.command("list").description("List claim types").option("--limit <n>","Max results (default 100)",Ee).option("--offset <n>","Page number offset (0-indexed)",Je).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",Ee).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=await He(n,o=>PL(r,o),{label:"Fetching claim types"});$e(i,mit,n,"Claim Types")})),e.command("get <resourceId>").description("Get a claim type by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let s=(await UL(i,r)).data;n.json?console.log(JSON.stringify(s,null,2)):(console.log(R("Name:"),s.name),console.log(R("ID:"),s.resourceId),console.log(R("Default:"),s.isDefault),s.expenseAccount&&console.log(R("Expense Account:"),`${s.expenseAccount.code} ${s.expenseAccount.name}`),s.taxProfile&&console.log(R("Tax Profile:"),s.taxProfile.name))})(n)),We({parent:e,fields:eS,defaults:tS,fetcher:Pb,columns:mit,label:"Searching claim types"}),e.command("create").description("Create a claim type").option("--name <name>","Claim type name (unique per org)").option("--expense-account <id>","Default expense account resourceId").option("--tax-profile <id>","Default tax profile resourceId").option("--classifier-config <json>","Magic OCR classifier defaults (JSON string)").option("--default","Make org default").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{Le(n,[{flag:"--name",key:"name"}]);let i=await pM(r,n.name);if(i){n.json?console.log(JSON.stringify({_guard:"duplicate_skipped",existing:i},null,2)):console.log(Oe(`Claim type "${n.name}" already exists (${i.resourceId}).`));return}let o=await $L(r,{name:n.name,expenseAccountResourceId:n.expenseAccount,taxProfileResourceId:n.taxProfile,classifierConfig:n.classifierConfig,isDefault:n.default});n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(Y(`Claim type created: ${n.name}`)),console.log(R("ID:"),o.data.resourceId))})),e.command("update <resourceId>").description("Update a claim type").option("--name <name>","New name").option("--expense-account <id>","Default expense account resourceId").option("--tax-profile <id>","Default tax profile resourceId").option("--classifier-config <json>","Classifier defaults (JSON string)").option("--default","Make org default").option("--clear <fields>","Comma-separated optional fields to NULL (expenseAccountResourceId,taxProfileResourceId,classifierConfig)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let o={};n.name!==void 0&&(o.name=n.name),n.expenseAccount!==void 0&&(o.expenseAccountResourceId=n.expenseAccount),n.taxProfile!==void 0&&(o.taxProfileResourceId=n.taxProfile),n.classifierConfig!==void 0&&(o.classifierConfig=n.classifierConfig),n.default!==void 0&&(o.isDefault=n.default),Object.assign(o,sy(Io(n.clear),oD));let s=await qL(i,r,o);n.json?console.log(JSON.stringify(s.data,null,2)):console.log(Y(`Claim type updated: ${s.data.name}`))})(n)),e.command("delete <resourceId>").description("Soft-delete a claim type").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{await jL(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(Y(`Claim type deleted: ${r}`))})(n))}Fe();cD();PY();pc();gt();kt();dr();Pt();Lt();fr();var git=[{key:"resourceId",header:"ID",format:Te},{key:"name",header:"Name"},{key:"isDefault",header:"Default"},{key:"taxMode",header:"Tax Mode"},{key:"employeeBalanceAccountResourceId",header:"Balance Acct",format:Te}];function yit(t){let e={};return t.name!==void 0&&(e.name=t.name),t.approver!==void 0&&(e.approverUserResourceId=t.approver),t.visibleClaimTypes!==void 0&&(e.visibleClaimTypeIds=Io(t.visibleClaimTypes)),t.visibleTaxProfiles!==void 0&&(e.visibleTaxProfileIds=Io(t.visibleTaxProfiles)),t.visibleClassifiers!==void 0&&(e.visibleClassifierIds=Io(t.visibleClassifiers)),t.visibleVendors!==void 0&&(e.visibleVendorResourceIds=Io(t.visibleVendors)),t.allowedCurrencies!==void 0&&(e.allowedCurrencies=Io(t.allowedCurrencies)),t.minAmount!==void 0&&(e.minClaimAmount=t.minAmount),t.maxAmount!==void 0&&(e.maxClaimAmount=t.maxAmount),t.maxPerPeriod!==void 0&&(e.maxPerPeriodAmount=t.maxPerPeriod),t.perPeriod!==void 0&&(e.perPeriod=t.perPeriod),t.balanceAccount!==void 0&&(e.employeeBalanceAccountResourceId=t.balanceAccount),t.taxMode!==void 0&&(e.taxMode=t.taxMode),t.default!==void 0&&(e.isDefault=t.default),e}function Eit(t){return t.option("--approver <id>","Default approver user resourceId").option("--visible-claim-types <ids>","Allowed claim type IDs (comma-separated)").option("--visible-tax-profiles <ids>","Allowed tax profile IDs (comma-separated)").option("--visible-classifiers <ids>","Allowed classifier IDs (comma-separated)").option("--visible-vendors <ids>","Allowed vendor contact IDs (comma-separated)").option("--allowed-currencies <codes>","Allowed ISO currency codes (comma-separated)").option("--min-amount <n>","Min claim total",lr).option("--max-amount <n>","Max claim total",lr).option("--max-per-period <n>","Per-period spend cap (requires --per-period)",lr).option("--per-period <window>","DAILY | WEEKLY | MONTHLY | QUARTERLY | YEARLY").option("--balance-account <id>","Employee balance (CURRENT_LIABILITY) account resourceId").option("--tax-mode <mode>","NO_TAX | INCLUSIVE (EXCLUSIVE rejected)").option("--default","Make org default")}function bit(t){let e=t.command("claim-profiles").description("Manage employee-expense claim profiles (per-employee policy bundles)");e.command("list").description("List claim profiles").option("--limit <n>","Max results (default 100)",Ee).option("--offset <n>","Page number offset (0-indexed)",Je).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",Ee).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=await He(n,o=>HL(r,o),{label:"Fetching claim profiles"});$e(i,git,n,"Claim Profiles")})),e.command("get <resourceId>").description("Get a claim profile by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let s=(await zL(i,r)).data;n.json?console.log(JSON.stringify(s,null,2)):(console.log(R("Name:"),s.name),console.log(R("ID:"),s.resourceId),console.log(R("Default:"),s.isDefault),s.taxMode&&console.log(R("Tax mode:"),s.taxMode),s.employeeBalanceAccount&&console.log(R("Balance account:"),`${s.employeeBalanceAccount.code} ${s.employeeBalanceAccount.name}`))})(n)),We({parent:e,fields:rS,defaults:nS,fetcher:Ub,columns:git,label:"Searching claim profiles"}),Eit(e.command("create").description("Create a claim profile").option("--name <name>","Profile name (unique per org)")).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{Le(n,[{flag:"--name",key:"name"}]);let i=await hM(r,n.name);if(i){n.json?console.log(JSON.stringify({_guard:"duplicate_skipped",existing:i},null,2)):console.log(Oe(`Claim profile "${n.name}" already exists (${i.resourceId}).`));return}let o=await GL(r,yit(n));n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(Y(`Claim profile created: ${n.name}`)),console.log(R("ID:"),o.data.resourceId))})),Eit(e.command("update <resourceId>").description("Update a claim profile").option("--name <name>","New name")).option("--clear <fields>","Comma-separated optional fields to NULL (e.g. approverUserResourceId,perPeriod,taxMode)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let o=yit(n);Object.assign(o,sy(Io(n.clear),aD));let s=await JL(i,r,o);n.json?console.log(JSON.stringify(s.data,null,2)):console.log(Y(`Claim profile updated: ${s.data.name}`))})(n)),e.command("delete <resourceId>").description("Soft-delete a claim profile").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{await VL(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(Y(`Claim profile deleted: ${r}`))})(n))}Fe();dD();pc();gt();kt();dr();Pt();Lt();fr();var Cit=[{key:"resourceId",header:"ID",format:Te},{key:"name",header:"Name"},{key:"outerAxis",header:"Outer"},{key:"innerAxis",header:"Inner"},{key:"isDefault",header:"Default"}];function vit(t){let e=t.command("posting-rules").description("Manage claim posting rules (how approved claims group into journals at conversion)");e.command("list").description("List posting rules").option("--limit <n>","Max results (default 100)",Ee).option("--offset <n>","Page number offset (0-indexed)",Je).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",Ee).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=await He(n,o=>WL(r,o),{label:"Fetching posting rules"});$e(i,Cit,n,"Posting Rules")})),e.command("get <resourceId>").description("Get a posting rule by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let s=(await ZL(i,r)).data;n.json?console.log(JSON.stringify(s,null,2)):(console.log(R("Name:"),s.name),console.log(R("ID:"),s.resourceId),console.log(R("Outer axis:"),s.outerAxis),console.log(R("Inner axis:"),s.innerAxis),console.log(R("Line template:"),s.lineDescriptionTemplate),console.log(R("Default:"),s.isDefault))})(n)),We({parent:e,fields:iS,defaults:oS,fetcher:$b,columns:Cit,label:"Searching posting rules"}),e.command("create").description("Create a posting rule").option("--name <name>","Rule name (unique per org)").option("--outer-axis <axis>","PER_EMPLOYEE | PER_VENDOR | PER_PAIR | ONE_BATCH | PER_CLAIM").option("--inner-axis <axis>","RAW | BY_CT_TP_NC | BY_CT_TP_NC_EMPLOYEE | BY_CT_TP_NC_VENDOR").option("--line-template <tpl>",'Handlebars line template, e.g. "{employeeName} - {claimType}"').option("--journal-reference-template <tpl>","Optional journal-header reference template").option("--default-bank-account <id>","Default reimbursement bank account resourceId").option("--default-include-payout","Create reimbursement DCE by default").option("--default","Make org default rule").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{Le(n,[{flag:"--name",key:"name"},{flag:"--outer-axis",key:"outerAxis"},{flag:"--inner-axis",key:"innerAxis"},{flag:"--line-template",key:"lineTemplate"}]);let i=await mM(r,n.name);if(i){n.json?console.log(JSON.stringify({_guard:"duplicate_skipped",existing:i},null,2)):console.log(Oe(`Posting rule "${n.name}" already exists (${i.resourceId}).`));return}let o=await KL(r,{name:n.name,outerAxis:n.outerAxis,innerAxis:n.innerAxis,lineDescriptionTemplate:n.lineTemplate,journalReferenceTemplate:n.journalReferenceTemplate,defaultBankAccountResourceId:n.defaultBankAccount,defaultIncludeReimbursementPayout:n.defaultIncludePayout,isDefault:n.default});n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(Y(`Posting rule created: ${n.name}`)),console.log(R("ID:"),o.data.resourceId))})),e.command("update <resourceId>").description("Update a posting rule").option("--name <name>","New name").option("--outer-axis <axis>","Outer grouping axis").option("--inner-axis <axis>","Inner line-aggregation axis").option("--line-template <tpl>","Handlebars line template").option("--journal-reference-template <tpl>","Journal-header reference template").option("--default-bank-account <id>","Default reimbursement bank account resourceId").option("--default-include-payout <bool>","Create reimbursement DCE by default (true/false)").option("--default","Make org default rule").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let o={};n.name!==void 0&&(o.name=n.name),n.outerAxis!==void 0&&(o.outerAxis=n.outerAxis),n.innerAxis!==void 0&&(o.innerAxis=n.innerAxis),n.lineTemplate!==void 0&&(o.lineDescriptionTemplate=n.lineTemplate),n.journalReferenceTemplate!==void 0&&(o.journalReferenceTemplate=n.journalReferenceTemplate),n.defaultBankAccount!==void 0&&(o.defaultBankAccountResourceId=n.defaultBankAccount),n.defaultIncludePayout!==void 0&&(o.defaultIncludeReimbursementPayout=n.defaultIncludePayout==="true"),n.default!==void 0&&(o.isDefault=n.default);let s=await XL(i,r,o);n.json?console.log(JSON.stringify(s.data,null,2)):console.log(Y(`Posting rule updated: ${s.data.name}`))})(n)),e.command("delete <resourceId>").description("Delete a posting rule (the org default cannot be deleted while default)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{await eM(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(Y(`Posting rule deleted: ${r}`))})(n))}Fe();ZM();vue();Iue();u_();MH();gt();kt();Lt();kf();fr();import{randomUUID as BCr}from"node:crypto";import{readFileSync as Iit,statSync as xCr}from"node:fs";import{basename as TCr,extname as kCr,resolve as wit}from"node:path";var NCr=[{key:"resourceId",header:"ID",format:Te},{key:"reference",header:"Reference"},{key:"status",header:"Status"},{key:"employeeResourceId",header:"Employee",format:Te},{key:"totalAmount",header:"Amount"},{key:"currencyCode",header:"Ccy"}];function _it(t){let e=t.command("claims").description("Employee-expense claims: search, edit drafts, lifecycle, bulk actions");We({parent:e,fields:WD,defaults:ZD,fetcher:NM,columns:NCr,label:"Searching claims"}),e.command("get <resourceId>").description("Get a claim by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((s,a)=>Q(async c=>{let d=(await OM(c,s)).data;a.json?console.log(JSON.stringify(d,null,2)):(console.log(R("Reference:"),d.reference??"\u2014"),console.log(R("ID:"),d.resourceId),console.log(R("Status:"),d.status),console.log(R("Total:"),`${d.totalAmount??0} ${d.currencyCode??""}`),console.log(R("Lines:"),(d.claimItems??[]).length))})(a)),e.command("create").description("Create a claim directly (bare create). Vendor is EITHER --contact OR --vendor-name. --items / --custom-fields take a JSON array string.").requiredOption("--value-date <date>","Business-transaction date (YYYY-MM-DD)").requiredOption("--currency <code>","Claim currency (ISO 4217)").option("--reference <ref>","User reference").option("--employee <id>","Employee resourceId the claim is filed for").option("--contact <id>","Vendor contact resourceId").option("--vendor-name <name>","Free-text vendor name").option("--currency-symbol <symbol>","Currency symbol override").option("--internal-notes <text>","Internal notes").option("--claim-profile <id>","Claim profile resourceId").option("--approver <id>","Approver user resourceId").option("--tags <list>","Header tags (comma-separated)").option("--items <json>","Line items as a JSON array").option("--custom-fields <json>","Custom field values as a JSON array").option("--submit","Validate + submit in one call (saveAsDraft=false). Requires --reference (else 422 CLAIM_REFERENCE_REQUIRED_AT_SUBMIT)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(s=>Q(async a=>{let c={valueDate:s.valueDate,currencyCode:s.currency};s.reference!==void 0&&(c.reference=s.reference),s.employee!==void 0&&(c.employeeResourceId=s.employee),s.contact!==void 0&&(c.contactResourceId=s.contact),s.vendorName!==void 0&&(c.vendorName=s.vendorName),s.currencySymbol!==void 0&&(c.currencySymbol=s.currencySymbol),s.internalNotes!==void 0&&(c.internalNotes=s.internalNotes),s.claimProfile!==void 0&&(c.claimProfileResourceId=s.claimProfile),s.approver!==void 0&&(c.approverUserResourceId=s.approver),s.tags!==void 0&&(c.tags=Io(s.tags)??[]),s.items!==void 0&&(c.claimItems=gu(s.items,"--items")),s.customFields!==void 0&&(c.customFields=gu(s.customFields,"--custom-fields")),s.submit&&(c.saveAsDraft=!1);let u=await FM(a,c);s.json?console.log(JSON.stringify(u.data,null,2)):console.log(Y(`Claim created: ${u.data.reference??u.data.resourceId} (${u.data.status})`))})(s)),e.command("update <resourceId>").description("Update a DRAFT claim (partial). --items / --custom-fields take a JSON array string.").option("--reference <ref>","User reference").option("--value-date <date>","Business-transaction date (YYYY-MM-DD)").option("--employee <id>","Employee resourceId").option("--contact <id>","Vendor contact resourceId").option("--vendor-name <name>","Free-text vendor name").option("--currency <code>","Claim currency (ISO 4217)").option("--internal-notes <text>","Internal notes").option("--claim-profile <id>","Claim profile resourceId").option("--approver <id>","Approver user resourceId").option("--tags <list>","Header tags (comma-separated)").option("--items <json>","Line items as a JSON array (REPLACES all lines)").option("--custom-fields <json>","Custom field values as a JSON array").option("--submit","Validate + submit in one call (saveAsDraft=false). Requires --reference (else 422 CLAIM_REFERENCE_REQUIRED_AT_SUBMIT)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((s,a)=>Q(async c=>{let u={};a.reference!==void 0&&(u.reference=a.reference),a.valueDate!==void 0&&(u.valueDate=a.valueDate),a.employee!==void 0&&(u.employeeResourceId=a.employee),a.contact!==void 0&&(u.contactResourceId=a.contact),a.vendorName!==void 0&&(u.vendorName=a.vendorName),a.currency!==void 0&&(u.currencyCode=a.currency),a.internalNotes!==void 0&&(u.internalNotes=a.internalNotes),a.claimProfile!==void 0&&(u.claimProfileResourceId=a.claimProfile),a.approver!==void 0&&(u.approverUserResourceId=a.approver),a.tags!==void 0&&(u.tags=Io(a.tags)??[]),a.items!==void 0&&(u.claimItems=gu(a.items,"--items")),a.customFields!==void 0&&(u.customFields=gu(a.customFields,"--custom-fields")),a.submit&&(u.saveAsDraft=!1);let d=await QM(c,s,u);a.json?console.log(JSON.stringify(d.data,null,2)):console.log(Y(`Claim updated: ${d.data.reference??d.data.resourceId} (${d.data.status})`))})(a)),e.command("delete <resourceId>").description("Delete a claim (only DRAFT / REJECTED / CANCELLED)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((s,a)=>Q(async c=>{await LM(c,s),a.json?console.log(JSON.stringify({deleted:!0,resourceId:s})):console.log(Y(`Claim deleted: ${s}`))})(a)),e.command("delete-attachment <resourceId> <attachmentResourceId>").description("Remove one attachment from a claim").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((s,a,c)=>Q(async u=>{await MM(u,s,a),c.json?console.log(JSON.stringify({deleted:!0,resourceId:s,attachmentResourceId:a})):console.log(Y(`Attachment removed from claim ${s}`))})(c));let r=[["submit",PM,"Submit a DRAFT claim for approval"],["approve",UM,"Approve a SUBMITTED claim"],["unpost",jM,"Unpost a CONVERTED claim (reverse conversion)"]];for(let[s,a,c]of r)e.command(`${s} <resourceId>`).description(c).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((u,d)=>Q(async f=>{let p=await a(f,u);d.json?console.log(JSON.stringify(p,null,2)):console.log(Y(`Claim ${s}: ${u}${p.data?.status?` (${p.data.status})`:""}`))})(d));let n=[["reject",$M,"Reject a SUBMITTED/APPROVED claim"],["cancel",qM,"Cancel a DRAFT/SUBMITTED claim"]];for(let[s,a,c]of n)e.command(`${s} <resourceId>`).description(c).option("--reason <text>","Reason (1-1000 chars), required").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((u,d)=>Q(async f=>{Le(d,[{flag:"--reason",key:"reason"}]);let p=await a(f,u,d.reason);d.json?console.log(JSON.stringify(p,null,2)):console.log(Y(`Claim ${s}ed: ${u}${p.data?.status?` (${p.data.status})`:""}`))})(d));let i=[["bulk-submit",YM,"Bulk-submit DRAFT claims (async)"],["bulk-approve",HM,"Bulk-approve SUBMITTED claims (async)"],["bulk-delete",zM,"Bulk-delete DRAFT/REJECTED/CANCELLED claims (async)"]];for(let[s,a,c]of i)e.command(s).description(`${c}. Poll with: clio background-jobs search`).option("--ids <list>","Claim resourceIds (comma-separated, 1-500)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(u,d)=>{Le(d,[{flag:"--ids",key:"ids"}]);let f=await a(u,Io(d.ids)??[]);d.json?console.log(JSON.stringify(f,null,2)):console.log(Y(`Queued ${s} \u2014 jobId ${f.data?.jobId??"?"}`))}));let o=[["bulk-reject",GM,"Bulk-reject claims (async)"],["bulk-cancel",JM,"Bulk-cancel claims (async)"]];for(let[s,a,c]of o)e.command(s).description(`${c}. Poll with: clio background-jobs search`).option("--ids <list>","Claim resourceIds (comma-separated, 1-500)").option("--reason <text>","Shared reason (1-1000 chars), required").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(u,d)=>{Le(d,[{flag:"--ids",key:"ids"},{flag:"--reason",key:"reason"}]);let f=await a(u,Io(d.ids)??[],d.reason);d.json?console.log(JSON.stringify(f,null,2)):console.log(Y(`Queued ${s} \u2014 jobId ${f.data?.jobId??"?"}`))}));e.command("tracking-tags").description("List claim tracking-tag values (picker)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(s,a)=>{let c=await VM(s);if(a.json)console.log(JSON.stringify(c,null,2));else{console.log(R(`Tracking tags (${c.length}):`));for(let u of c)console.log(` ${typeof u=="string"?u:JSON.stringify(u)}`)}})),e.command("custom-field-values").description("List claim custom-field values (picker)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(s,a)=>{let c=await WM(s);a.json?console.log(JSON.stringify(c,null,2)):console.log(Oe(c.length===0?"No custom field values.":`${c.length} custom field value(s).`))})),e.command("preview-conversion").description("Preview the journals an APPROVED claim batch would produce (no write)").option("--ids <list>","APPROVED claim resourceIds (comma-separated)").option("--posting-rule <id>","Posting rule resourceId (default: org default)").option("--payout-flow <flow>","POST | POST_AND_RECORD").option("--include-payout","Include reimbursement DCE lines").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(s,a)=>{if(Le(a,[{flag:"--ids",key:"ids"}]),a.payoutFlow!==void 0&&!Yx.includes(a.payoutFlow))throw new Error(`--payout-flow must be one of: ${Yx.join(", ")}`);let c=await PH(s,{claimResourceIds:Io(a.ids)??[],postingRuleResourceId:a.postingRule,payoutFlow:a.payoutFlow,includeReimbursementPayout:a.includePayout});console.log(JSON.stringify(c.data,null,2))})),e.command("convert").description("Convert an APPROVED claim batch into journals (atomic). Preview first.").option("--ids <list>","APPROVED claim resourceIds (comma-separated)").option("--value-date <date>","Journal value date (YYYY-MM-DD), required").option("--posting-rule <id>","Posting rule resourceId (default: org default)").option("--include-payout","Create books-only reimbursement DCEs").option("--bank-account <id>","Override reimbursement bank account").option("--idempotency-key <key>","Retry-dedup token (auto-generated if omitted)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(s,a)=>{Le(a,[{flag:"--ids",key:"ids"},{flag:"--value-date",key:"valueDate"}]);let c=await UH(s,{claimResourceIds:Io(a.ids)??[],valueDate:a.valueDate,postingRuleResourceId:a.postingRule,includeReimbursementPayout:a.includePayout,bankAccountResourceIdOverride:a.bankAccount,idempotencyKey:a.idempotencyKey||BCr()});a.json?console.log(JSON.stringify(c.data,null,2)):console.log(Y("Claims converted to journals."))})),e.command("record-payout").description("Record a books-only employee payout (reimbursement / advance)").option("--employee <id>","Employee resourceId").option("--amount <n>","Payout amount (> 0)",lr).option("--payment-account <id>","Bank/cash account the DCE credits").option("--value-date <date>","Value date (YYYY-MM-DD)").option("--payout-for <type>","REIMBURSEMENT | ADVANCE (default ADVANCE)").option("--currency <code>","Settle currency (ISO 4217)").option("--reference <ref>","Payout reference (auto-generated if omitted)").option("--description <text>","DCE line description").option("--internal-notes <text>","Internal notes").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(s,a)=>{Le(a,[{flag:"--employee",key:"employee"},{flag:"--amount",key:"amount"},{flag:"--payment-account",key:"paymentAccount"},{flag:"--value-date",key:"valueDate"}]);let c=await $H(s,{employeeResourceId:a.employee,amount:a.amount,paymentAccountResourceId:a.paymentAccount,valueDate:a.valueDate,payoutFor:a.payoutFor,currencyCode:a.currency,reference:a.reference||$a("EP"),description:a.description,internalNotes:a.internalNotes});a.json?console.log(JSON.stringify(c.data,null,2)):console.log(Y(`Payout recorded: ${c.data.resourceId}`))})),We({parent:e,commandName:"payouts",fields:KD,defaults:XD,fetcher:qH,columns:[{key:"resourceId",header:"ID",format:Te},{key:"reference",header:"Reference"},{key:"employeeResourceId",header:"Employee",format:Te},{key:"amount",header:"Amount"},{key:"payoutType",header:"Type"}],label:"Searching employee payouts"}),e.command("from-attachment").description("Create a claim DRAFT from a receipt via AI extraction \u2014 a local file (--file), a remote URL (--source-url), or raw HTML (--html)").option("--file <path>","Local receipt file (PDF / JPG / PNG / HEIC / XLS / XLSX / EML)").option("--source-url <url>","Remote receipt file URL (alternative to --file)").option("--html <value>","Raw HTML (e.g. an email body) \u2014 inline or @path to read from a file").option("--contact <id>","Vendor contact resourceId").option("--claim-profile <id>","Claim profile resourceId").option("--employee <id>","File on behalf of this employee resourceId (default: the uploader's own; server requires a claims Manager/Admin to name another)").option("--currency <code>","Currency override (ISO 4217)").option("--value-date <date>","Value date override (YYYY-MM-DD)").option("--internal-notes <text>","Internal notes").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(s,a)=>{if([a.file,a.sourceUrl,a.html].filter(Boolean).length!==1)throw new Error("provide exactly one of --file / --source-url / --html.");let u,d;if(a.file){let h=wit(a.file),m=kCr(h).toLowerCase();if(!dd.has(m))throw new Error(`unsupported file type "${m}". Supported: ${[...dd].join(", ")}`);let A=25*1024*1024,g=xCr(h).size;if(g>A)throw new Error(`file too large (${(g/1048576).toFixed(1)}MB > 25MB). Compress or split the receipt.`);u=new Blob([Iit(h)],{type:Ym(m)}),d=TCr(h)}let f;a.html&&(a.html.startsWith("@")||console.error(Oe("Warning: passing HTML inline can leak invoice data into shell history \u2014 prefer --html @path.")),f=a.html.startsWith("@")?Iit(wit(a.html.slice(1)),"utf8"):a.html);let p=await cb(s,{sourceFile:u,sourceFileName:d,sourceURL:a.sourceUrl,html:f,contactResourceId:a.contact,claimProfileResourceId:a.claimProfile,employeeResourceId:a.employee,currencyCode:a.currency,valueDate:a.valueDate,internalNotes:a.internalNotes});console.log(JSON.stringify(p,null,2))}))}Fe();fD();pc();gt();kt();Lt();fr();var Dit=[{key:"resourceId",header:"ID",format:Te},{key:"name",header:"Name"},{key:"email",header:"Email"},{key:"employmentType",header:"Type"},{key:"active",header:"Active"}];function Sit(t){let e=t.command("employees").description("Manage employees (expense-claim members): CRUD, balances, bind-user, import");We({parent:e,fields:sS,defaults:aS,fetcher:qb,columns:Dit,label:"Searching employees"}),We({parent:e,commandName:"balances",fields:cS,defaults:lS,fetcher:tM,columns:Dit,label:"Searching employee balances"}),e.command("get <resourceId>").description("Get an employee by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let s=(await rM(i,r)).data;n.json?console.log(JSON.stringify(s,null,2)):(console.log(R("Name:"),s.name),console.log(R("ID:"),s.resourceId),console.log(R("Email:"),s.email??"\u2014"),console.log(R("Active:"),s.active),s.userBinding&&console.log(R("Bound user:"),`${s.userBinding.name??""} (${s.userBinding.status??""})`),s.claimProfile&&console.log(R("Claim profile:"),s.claimProfile.name))})(n)),e.command("create").description("Create an employee (requires --user to bind; binding is permanent)").option("--name <name>","Employee name").option("--user <id>","Login user resourceId to bind (required)").option("--claim-profile <id>","Claim profile resourceId (defaults to org default)").option("--email <email>","Work email").option("--phone <phone>","Phone").option("--manager <id>","Manager employee resourceId").option("--employment-type <type>","FULL_TIME | PART_TIME | CONTRACTOR | INTERN | TEMPORARY | CONSULTANT").option("--inactive","Create as inactive").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{if(Le(n,[{flag:"--name",key:"name"},{flag:"--user",key:"user"}]),n.email){let o=await AM(r,n.email);if(o){n.json?console.log(JSON.stringify({_guard:"duplicate_skipped",existing:o},null,2)):console.log(Oe(`Employee with email "${n.email}" already exists (${o.resourceId}).`));return}}let i=await nM(r,{name:n.name,userResourceId:n.user,claimProfileResourceId:n.claimProfile,email:n.email,phone:n.phone,managerEmployeeResourceId:n.manager,active:n.inactive?!1:void 0,employmentType:n.employmentType});n.json?console.log(JSON.stringify(i.data,null,2)):(console.log(Y(`Employee created: ${n.name}`)),console.log(R("ID:"),i.data.resourceId))})),e.command("update <resourceId>").description("Update an employee. Use --archive to deactivate (reversible).").option("--name <name>","New name").option("--email <email>","Work email").option("--phone <phone>","Phone").option("--manager <id>","Manager employee resourceId").option("--claim-profile <id>","Claim profile resourceId").option("--employment-type <type>","Employment classification").option("--archive","Set active=false (archive)").option("--activate","Set active=true").option("--clear-employment-type","Unset the classification").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let o={};if(n.name!==void 0&&(o.name=n.name),n.email!==void 0&&(o.email=n.email),n.phone!==void 0&&(o.phone=n.phone),n.manager!==void 0&&(o.managerEmployeeResourceId=n.manager),n.claimProfile!==void 0&&(o.claimProfileResourceId=n.claimProfile),n.employmentType!==void 0&&(o.employmentType=n.employmentType),n.archive&&n.activate)throw new Error("--archive and --activate are mutually exclusive.");n.archive&&(o.active=!1),n.activate&&(o.active=!0),n.clearEmploymentType&&(o.clearEmploymentType=!0);let s=await iM(i,r,o);n.json?console.log(JSON.stringify(s.data,null,2)):console.log(Y(`Employee updated: ${s.data.name??r}`))})(n)),e.command("delete <resourceId>").description("Delete an employee (must be settled). Prefer update --archive.").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{await oM(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(Y(`Employee deleted: ${r}`))})(n)),e.command("bind-user <resourceId> <userResourceId>").description("Bind a login user to an offline employee (no user bound yet). One-way, permanent \u2014 allowed only while unbound.").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n,i)=>Q(async o=>{let s=await sM(o,r,n);i.json?console.log(JSON.stringify(s.data,null,2)):console.log(Y(`Bound user ${n} to employee ${r}`))})(i)),e.command("preprocess <fileUrl>").description("Preview an employee import sheet before importing").option("--file-name <name>","Display file name").option("--file-type <type>","CSV | XLS | XLSX").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let o=await aM(i,{fileUrl:r,fileName:n.fileName,fileType:n.fileType});console.log(JSON.stringify(o.data,null,2))})(n)),e.command("import").description("Bulk import employees (async). Pass --create / --update / --delete JSON arrays (max 100 each).").option("--create <json>","Create rows (JSON array)").option("--update <json>","Update rows (JSON array, each with employeeResourceId)").option("--delete <json>","Delete rows (JSON array, each with employeeResourceId)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{let i={};n.create!==void 0&&(i.create=gu(n.create,"--create")),n.update!==void 0&&(i.update=gu(n.update,"--update")),n.delete!==void 0&&(i.delete=gu(n.delete,"--delete"));let o=await cM(r,i);n.json?console.log(JSON.stringify(o.data,null,2)):console.log(Y(`Queued employee import \u2014 jobId ${o.data?.jobId??"?"}`))}))}mue();gt();kt();dr();Pt();Lt();Fe();var OCr=[{key:"resourceId",header:"ID",format:Te},{key:"name",header:"Name"},{key:"categoryCode",header:"Category"},{key:"value",header:"Value"}];function Rit(t){let e=t.command("bookmarks").description("Manage organization bookmarks");e.command("list").description("List bookmarks").option("--limit <n>","Max results (default 100)",Ee).option("--offset <n>","Page number offset (0-indexed)",Je).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",Ee).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=await He(n,o=>AH(r,o),{label:"Fetching bookmarks"});$e(i,OCr,n,"Bookmarks")})),e.command("get <resourceId>").description("Get a bookmark by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let s=(await gH(i,r)).data;n.json?console.log(JSON.stringify(s,null,2)):(console.log(R("Name:"),s.name),console.log(R("ID:"),s.resourceId),console.log(R("Category:"),s.categoryCode),console.log(R("Value:"),s.value))})(n)),e.command("create").description("Create bookmark(s)").option("--name <name>","Bookmark name").option("--value <value>","Bookmark value").option("--category <code>","Category code (GENERAL_INFORMATION, TAXATION_AND_COMPLIANCE, etc.)").option("--datatype <code>","Datatype code (default: TEXT)").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=Ce(n),o;if(i?o=await qx(r,i.items??[i]):(Le(n,[{flag:"--name",key:"name"},{flag:"--value",key:"value"},{flag:"--category",key:"category"}]),o=await qx(r,[{name:n.name,value:n.value,categoryCode:n.category,datatypeCode:n.datatype??"TEXT"}])),n.json)console.log(JSON.stringify(o.data,null,2));else{console.log(Y(`Bookmark(s) created: ${o.data.length} item(s)`));for(let s of o.data)console.log(` ${Be(s.resourceId)} ${s.name}`)}})),e.command("update <resourceId>").description("Update a bookmark").option("--name <name>","New name").option("--value <value>","New value").option("--category <code>","New category code").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let o=Ce(n),s=o||{...n.name&&{name:n.name},...n.value&&{value:n.value},...n.category&&{categoryCode:n.category}},a=await yH(i,r,s);n.json?console.log(JSON.stringify(a.data,null,2)):console.log(Y(`Bookmark updated: ${a.data.name}`))})(n))}bH();gt();kt();Pt();dr();Lt();Fe();var FCr=[{key:"resourceId",header:"ID",format:Te},{key:"kind",header:"Kind"},{key:"tier",header:"Tier"},{key:"call",header:"Call"},{key:"dispositions",header:"Dispositions",format:t=>Array.isArray(t)?t.map(e=>e.verb).join(" "):String(t)},{key:"createdAt",header:"Created",format:mp}];function Bit(t){let e=t.command("jots").description("Judgment journal: record and look up judgment entries");e.command("create").description("Record judgment entries (batch via --input, single via flags)").option("--kind <kind>","Judgment kind (CLASSIFICATION, MATCH, SCOPE, ASSUMPTION, RISK, METHOD, RECOVERY, DEVIATION, NOTE)").option("--tier <tier>","Severity tier (LOW, MEDIUM, HIGH, CRITICAL)").option("--call <call>","The decision, one line").option("--why <why>","The basis for the call").option("--ruled-out <text>","Alternatives considered and set aside").option("--ref <ref...>","Entity ref, grammar TYPE:resourceId[#field][:RELATION] (repeatable)").option("--frame <frame>","Set anchor: defining query + counts").option("--confidence <level>","Routing hint (LOW, MEDIUM, HIGH)").option("--cited-rule <rule>","Org rule, policy, threshold, or precedent applied").option("--workflow-label <label>","Short workflow label (e.g. month-end-close)").option("--agent-label <label>","Self-reported product/model").option("--idempotency-key <key>","Retry key: a replay returns the existing entry").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=Ce(n),o;i?o=i.entries??[i]:(Le(n,[{flag:"--kind",key:"kind"},{flag:"--tier",key:"tier"},{flag:"--call",key:"call"}]),o=[{kind:n.kind,tier:n.tier,call:n.call,...n.why&&{why:n.why},...n.ruledOut&&{ruledOut:n.ruledOut},...n.ref&&{refs:n.ref},...n.frame&&{frame:n.frame},...n.confidence&&{confidence:n.confidence},...n.citedRule&&{citedRule:n.citedRule},...n.workflowLabel&&{workflowLabel:n.workflowLabel},...n.agentLabel&&{agentLabel:n.agentLabel},...n.idempotencyKey&&{idempotencyKey:n.idempotencyKey}}]),o=o.map(d=>({writePath:"CLI",...d}));let s=await yv(r,o),a=s.data.records??[],c=a.filter(d=>!d.error),u=a.length>0&&c.length===0;u&&(process.exitCode=1),n.json?console.log(JSON.stringify(s.data,null,2)):(console.log(u?ie(`No jots recorded: ${a.length} error(s)`):Y(`Jot(s) recorded: ${c.length}/${a.length} entr${a.length===1?"y":"ies"}`)),a.forEach((d,f)=>{if(d.error)console.log(` ${Oe(`entry ${f}:`)} ${d.error}${d.errorCode?G(` (${d.errorCode})`):""}`);else{let p=[d.replayed&&"replayed",d.duplicateCount&&`${d.duplicateCount} similar`].filter(Boolean).join(", ");console.log(` ${Be(d.resourceId??"")}${p?G(` ${p}`):""}`)}}))})),e.command("recall").description("Search judgment entries (sort pinned server-side: critical first, then newest)").option("--ref <ref>","Entity ref filter, TYPE:resourceId").option("--kind <kind>","Judgment kind filter").option("--tier <tier>","Severity tier filter").option("--disposition-verb <verb>","Only entries with a disposition of this verb (FLAG, REJECT, ENDORSE)").option("--freetext <text>","Case-insensitive substring over call and why").option("--created-from <epochMs>","Created-at lower bound, epoch ms (inclusive)",Je).option("--created-to <epochMs>","Created-at upper bound, epoch ms (inclusive)",Je).option("--first-party","Only entries from Jaz-operated agent surfaces (server-stamped origin)").option("--pinned","Only pinned entries (critical or withheld-write)").option("--stats","Include per-credential disposition counts").option("--limit <n>","Max results (default 100)",Ee).option("--offset <n>","Page number offset (0-indexed)",Je).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",Ee).option("--format <type>","Output format: table, json, csv, yaml").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{let i={...n.ref&&{ref:n.ref},...n.kind&&{kind:n.kind},...n.tier&&{tier:n.tier},...n.dispositionVerb&&{dispositionVerb:n.dispositionVerb},...n.freetext&&{freetext:n.freetext},...n.createdFrom!==void 0&&{createdFrom:n.createdFrom},...n.createdTo!==void 0&&{createdTo:n.createdTo},...n.firstParty&&{firstParty:!0},...n.pinned&&{pinned:!0}},o,s=await He(n,async a=>{let c=await EH(r,{limit:a.limit,offset:a.offset,...Object.keys(i).length?{filter:i}:{},...n.stats&&(!n.all||a.offset===0)&&{includeStats:!0}});return o??=c.stats,c},{label:"Fetching jots"});if($e(o?.length?{...s,stats:o}:s,FCr,n,"Jots"),n.stats&&o?.length&&!Al(n)){console.log(R("Disposition stats (per credential):"));for(let a of o)console.log(` ${a.credential??"(unknown)"} ${a.verb??""} ${a.count??0}`)}})),e.command("dispose <resourceId>").description("Append a review disposition to a jot (append-only)").option("--verb <verb>","Review verb: FLAG, REJECT, or ENDORSE").option("--note <note>","Optional reviewer note").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{Le(n,[{flag:"--verb",key:"verb"}]);let s=(await Trt(i,r,{verb:n.verb,...n.note&&{note:n.note}})).data;n.json?console.log(JSON.stringify(s,null,2)):(console.log(Y(`Disposition recorded: ${s.verb} on ${s.jotResourceId}`)),s.rollbackHandoff&&console.log(G(" Rollback handoff pointer returned: execution lives in the rollback module.")))})(n))}Aue();CD();gt();kt();dr();Pt();Lt();Fe();fr();function e8(t,e){return r=>{let n=r.toUpperCase();if(!t.includes(n))throw new Error(`Invalid ${e}: ${r}. Allowed: ${t.join(", ")}`);return n}}function xit(t){return Kb.map(e=>({moduleName:e,roleCode:t}))}var Tit=[{key:"resourceId",header:"ID",format:Te},{key:"firstName",header:"First Name"},{key:"lastName",header:"Last Name"},{key:"email",header:"Email"},{key:"moduleRoles",header:"Roles",format:t=>Array.isArray(t)?t.map(e=>`${e.moduleName}:${e.roleCode}`).join(", "):String(t??"")}];function kit(t){let e=t.command("org-users").description("Manage organization users");e.command("list").description("List organization users").option("--limit <n>","Max results (default 100)",Ee).option("--offset <n>","Page number offset (0-indexed)",Je).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",Ee).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=await He(n,o=>CH(r,o),{label:"Fetching org users"});$e(i,Tit,n,"Org Users")})),We({parent:e,fields:vS,defaults:IS,fetcher:vH,columns:Tit,label:"Searching org users",positionalArg:"name",positionalFilter:r=>({or:[{firstName:{contains:r}},{lastName:{contains:r}},{email:{contains:r}}]})}),e.command("invite").description("Invite a user to the organization").option("--jot <text>",we).option("--first-name <name>","First name").option("--last-name <name>","Last name").option("--email <email>","Email address").option("--user-type <type>","ADMIN | CUSTOM_USER (default: derived from --role)",e8(OA,"user-type")).option("--role <role>","Role code: ADMIN, PREPARER, MEMBER, NO_ACCESS (default: MEMBER). ADMIN \u2192 userType=ADMIN; others \u2192 userType=CUSTOM_USER with this role on every module.",e8(NA,"role")).option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(Q(async(r,n)=>{let i=Ce(n),o;if(i)o=await Ev(r,i);else{Le(n,[{flag:"--first-name",key:"firstName"},{flag:"--last-name",key:"lastName"},{flag:"--email",key:"email"}]);let s=n.role??"MEMBER",a=n.userType??(s==="ADMIN"?"ADMIN":"CUSTOM_USER");o=await Ev(r,{firstName:n.firstName,lastName:n.lastName,email:n.email,userType:a,...a==="CUSTOM_USER"?{moduleRoles:xit(s)}:{}})}n.json?console.log(JSON.stringify(o.data,null,2)):(console.log(Y(`User invited: ${n.firstName??""} ${n.lastName??""} (${n.email??""})`)),console.log(R("ID:"),o.data.resourceId)),Ie(r,"invite_org_user",n,o.data)})),e.command("update <resourceId>").description("Update a user's access tier and/or module roles").option("--jot <text>",we).option("--user-type <type>","ADMIN | CUSTOM_USER (default: derived from --role)",e8(OA,"user-type")).option("--role <role>","New role code: ADMIN, PREPARER, MEMBER, NO_ACCESS. ADMIN \u2192 userType=ADMIN; others \u2192 userType=CUSTOM_USER with this role on every module.",e8(NA,"role")).option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{let o=Ce(n),s;if(o)s=o;else{if(!n.role&&!n.userType)throw new Error("At least one of --role or --user-type is required");let c=n.role,u=n.userType??(c==="ADMIN"?"ADMIN":c?"CUSTOM_USER":void 0);s={...u?{userType:u}:{},...u==="CUSTOM_USER"&&c?{moduleRoles:xit(c)}:{}}}let a=await IH(i,r,s);n.json?console.log(JSON.stringify(a.data,null,2)):console.log(Y(`User updated: ${a.data.firstName} ${a.data.lastName}`)),Ie(i,"update_org_user",n,a.data)})(n)),e.command("remove <resourceId>").description("Remove a user from the organization").option("--jot <text>",we).option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>Q(async i=>{await wH(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(Y(`User ${r} removed.`)),Ie(i,"remove_org_user",n,{resourceId:r})})(n))}Fe();$x();fr();Lt();var QCr=[{key:"resourceId",header:"ID",format:Te},{key:"transactionReference",header:"Reference",format:$n},{key:"direction",header:"Dir",format:yL},{key:"valueDate",header:"Date",format:mp},{key:"totalAmount",header:"Amount",align:"right"},{key:"currencyCode",header:"Ccy"},{key:"businessTransactionType",header:"Type",format:t=>G(String(t??""))}];function Nit(t){let e=t.command("cashflow").description("Search cashflow transactions");We({parent:e,fields:xd,defaults:Td,fetcher:zh,columns:QCr,label:"Searching cashflow"})}function Oit(t){t.command("serve").description("HTTP daemon (not available in bundled CLI)").action(()=>{console.error("clio serve is not available in the bundled CLI. Use the full installation from the private repo."),process.exit(1)})}Fe();gt();kt();Yo();eue();pue();Xle();function ja(t){return t.option("--plan","Plan mode \u2014 show required accounts and step summary (offline, no auth)").option("--input <file>","Account mapping JSON file (optional \u2014 auto-resolves from chart of accounts if omitted)").option("--bank-account <id>","Bank/cash account name or resourceId (for cash-in/cash-out steps)").option("--contact <id>","Contact name or resourceId \u2014 supplier for bills, customer for invoices").option("--existing-txn <id>","Attach to existing transaction \u2014 skip initial step, create delta only").option("--ref <prefix>","Reference prefix (generates prefix-1, prefix-2, ...)").option("--finalize","Approve transactions immediately (default: create as drafts)").option("--jot <text>",we).option("--json","Output as JSON").option("--api-key <key>","API key override")}function Ya(t,e){return async r=>{try{let n=e(r);if(r.plan){let s=gv(t,n);r.json?console.log(JSON.stringify(s,null,2)):LCr(s);return}let i=Fx(n);i||(console.error(ie("Error: no blueprint generated. Provide --start-date to enable blueprint.")),process.exit(1)),await Q(async(s,a,c)=>{let u=!!a.json,d,f=Ce(a);if(f)d=f;else{let h=gv(t,n);u||process.stderr.write(G(` Auto-resolving accounts from chart of accounts...
|
|
1062
1062
|
`)),d=await E1e(s,h.plan.requiredAccounts,{silent:u})}if(a.contact){let h=await gi(s,a.contact,{silent:u});a.contact=h.resourceId}if(a.bankAccount){let h=await IM(s,a.bankAccount,{silent:u});a.bankAccount=h.resourceId}let p=await hH(s,{blueprint:i,calcType:t,accountMap:d,bankAccountId:a.bankAccount,contactId:a.contact,existingTxnId:a.existingTxn,referencePrefix:a.ref,finalize:a.finalize});a.json?console.log(JSON.stringify(p,null,2)):MCr(p),Ie(s,"execute_recipe",a,p)})(r)}catch(n){throw(n instanceof zt||n instanceof Error&&n.message.includes("blueprint"))&&(console.error(ie("Error: "+n.message)),process.exit(1)),n}}}function LCr(t){console.log(R(`
|
|
1063
1063
|
Capsule Transaction Plan: `+t.recipe+`
|
|
1064
1064
|
`)),console.log(" Capsule Type: "+t.plan.capsuleType),console.log(" Capsule Name: "+t.plan.capsuleName),console.log(" Total Steps: "+t.plan.steps.total),console.log(" Step Breakdown:");for(let[e,r]of Object.entries(t.plan.steps.byAction))console.log(" "+e+": "+r);console.log(`
|