@huaqiu/hardware-artifacts 0.7.23 → 0.7.24

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/lib/service.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { C as SourceResult, S as SourceRequest, T as parseCsv, _ as OrderConfigInfo, a as FabricationResult, b as PlaceOrderRequest, c as HardwareArtifact, d as HardwareProject, f as InstallationInfo, g as OpenArtifactResult, h as OpenArtifactRequest, i as DiscoveryResult, l as HardwareArtifactService, m as NativeApplication, n as BomResult, o as GlbRequest, p as Installations, r as BomRow, s as GlbResult, t as ArtifactKind, u as HardwareArtifactsOptions, v as OrderPackageSummary, w as groupBomRows, x as PlaceOrderResult, y as OrderReadiness } from "./service-DQV0soSK.mjs";
2
- export { ArtifactKind, BomResult, BomRow, DiscoveryResult, FabricationResult, GlbRequest, GlbResult, HardwareArtifact, HardwareArtifactService, HardwareArtifactsOptions, HardwareProject, InstallationInfo, Installations, NativeApplication, OpenArtifactRequest, OpenArtifactResult, OrderConfigInfo, OrderPackageSummary, OrderReadiness, PlaceOrderRequest, PlaceOrderResult, SourceRequest, SourceResult, groupBomRows, parseCsv };
1
+ import { A as parseCsv, C as QuotePcbResult, D as SourceResult, E as SourceRequest, O as SpawnedProcess, S as QuotePcbRequest, T as QuoteSmtResult, _ as OrderConfigInfo, a as FabricationResult, b as PlaceOrderRequest, c as HardwareArtifact, d as HardwareProject, f as InstallationInfo, g as OpenArtifactResult, h as OpenArtifactRequest, i as DiscoveryResult, k as groupBomRows, l as HardwareArtifactService, m as NativeApplication, n as BomResult, o as GlbRequest, p as Installations, r as BomRow, s as GlbResult, t as ArtifactKind, u as HardwareArtifactsOptions, v as OrderPackageSummary, w as QuoteSmtRequest, x as PlaceOrderResult, y as OrderReadiness } from "./service-DDUXPMvb.mjs";
2
+ export { ArtifactKind, BomResult, BomRow, DiscoveryResult, FabricationResult, GlbRequest, GlbResult, HardwareArtifact, HardwareArtifactService, HardwareArtifactsOptions, HardwareProject, InstallationInfo, Installations, NativeApplication, OpenArtifactRequest, OpenArtifactResult, OrderConfigInfo, OrderPackageSummary, OrderReadiness, PlaceOrderRequest, PlaceOrderResult, QuotePcbRequest, QuotePcbResult, QuoteSmtRequest, QuoteSmtResult, SourceRequest, SourceResult, SpawnedProcess, groupBomRows, parseCsv };
package/lib/service.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { n as groupBomRows, r as parseCsv, t as HardwareArtifactService } from "./service-JazWEnwB.mjs";
1
+ import { n as groupBomRows, r as parseCsv, t as HardwareArtifactService } from "./service-DFQ0q0uR.mjs";
2
2
  export { HardwareArtifactService, groupBomRows, parseCsv };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@huaqiu/hardware-artifacts",
3
- "version": "0.7.23",
3
+ "version": "0.7.24",
4
4
  "type": "module",
5
5
  "description": "Hardware Engineering host capability: deterministic artifact discovery, installation resolution, native application launch and compact agent context.",
6
6
  "license": "MIT",
package/src/index.ts CHANGED
@@ -29,6 +29,10 @@ export type {
29
29
  OrderReadiness,
30
30
  PlaceOrderRequest,
31
31
  PlaceOrderResult,
32
+ QuotePcbRequest,
33
+ QuotePcbResult,
34
+ QuoteSmtRequest,
35
+ QuoteSmtResult,
32
36
  } from './service.js'
33
37
  export { HardwareArtifactService } from './service.js'
34
38
  export {
@@ -42,8 +46,18 @@ export {
42
46
  expectedCopperLayers, validateFabricationPackage, validationSummary,
43
47
  } from './package.js'
44
48
  export type { PackageIssue, PackageIssueCode, PackageValidation } from './package.js'
49
+ export {
50
+ DEFAULT_QUOTE_BASE_URL, DEFAULT_QUOTE_QUANTITY, leadTimeDays, parsePcbQuote, parseSmtQuote,
51
+ pcbQuoteForm, QUOTE_PATHS, smtQuoteForm,
52
+ } from './quote.js'
53
+ export type {
54
+ PcbQuote, PcbQuoteOverrides, QuoteColor, QuoteDelivery, QuoteFee, QuoteSurfaceFinish,
55
+ SmtQuote, SmtQuoteOverrides,
56
+ } from './quote.js'
45
57
  export { createHardwareTools, hardwareToolNames } from './tools.js'
46
58
  export type { HardwareToolEnv } from './tools.js'
59
+ export { isSolidcraftInput, SOLIDCRAFT_INPUT_EXTENSIONS, SOLIDCRAFT_INPUT_FORMATS } from './solidcraft-inputs.js'
60
+ export { isKicadInput, KICAD_INPUT_EXTENSIONS, KICAD_INPUT_FORMATS } from './kicad-inputs.js'
47
61
  export { createHardwareHandler, HARDWARE_ROUTE_PREFIX, TOOLCHAIN_ROUTE_PREFIX } from './routes.js'
48
62
  export type { HardwareHandlerOptions, WorkspaceResolver } from './routes.js'
49
63
  export { ToolchainManager } from './toolchain/index.js'
@@ -0,0 +1,45 @@
1
+ /**
2
+ * What KiCad verifiably opens as a *design document*, and what it does not.
3
+ *
4
+ * This list is the routing table's KiCad half, and it is deliberately short:
5
+ * each suffix here has an editor resolution behind it in `service.open()` —
6
+ * `eeschema` for a schematic, `pcbnew` for a board, `kicad` for a project — and
7
+ * that resolution is what the launch path has always used and what the tests
8
+ * exercise. A suffix without an editor is not offered, because §2 of the
9
+ * toolchain-aware open-in-app task enables a format only after its support is
10
+ * verified rather than assumed.
11
+ *
12
+ * `.kicad_wks` is the case that proves the rule: KiCad's page-layout editor does
13
+ * open worksheet files from its own File menu, but this product resolves no
14
+ * worksheet editor, has no launch path for one, and therefore does not claim it.
15
+ * Adding it later is adding a resolution *and* a test, not adding a string here.
16
+ *
17
+ * The list lives in this module — not in the client action, not in the previewer
18
+ * — so the document action, the launch route and the agent prompt cannot
19
+ * disagree about what a KiCad hand-off accepts.
20
+ *
21
+ * @module @huaqiu/hardware-artifacts/kicad-inputs
22
+ */
23
+
24
+ /** Suffixes KiCad's editors open as design documents, lower case, no dot. */
25
+ export const KICAD_INPUT_EXTENSIONS: readonly string[] = Object.freeze(['kicad_sch', 'kicad_pcb', 'kicad_pro'])
26
+
27
+ /** Display form of {@link KICAD_INPUT_EXTENSIONS}, for capability text and prompts. */
28
+ export const KICAD_INPUT_FORMATS: readonly string[] = Object.freeze(
29
+ KICAD_INPUT_EXTENSIONS.map(extension => `.${extension}`),
30
+ )
31
+
32
+ /**
33
+ * Is this path a KiCad document this product can hand to a configured editor?
34
+ * @param path - any filesystem path or bare file name; only its suffix is read.
35
+ * @returns true for a verified KiCad design document, false for everything else.
36
+ */
37
+ export function isKicadInput(path: string): boolean {
38
+ const lower = path.toLowerCase()
39
+ const dot = lower.lastIndexOf('.')
40
+ if (dot === -1) return false
41
+ // A path may carry a query or fragment when it came from an address; neither
42
+ // is part of the file name.
43
+ const suffix = lower.slice(dot + 1).replace(/[?#].*$/u, '')
44
+ return KICAD_INPUT_EXTENSIONS.includes(suffix)
45
+ }
package/src/order.ts CHANGED
@@ -61,6 +61,23 @@ export interface BoardFacts {
61
61
  readonly innerOz?: number
62
62
  /** Placed pads, used for the assembly form's `patch_pad_number`. */
63
63
  readonly padCount?: number
64
+ /**
65
+ * SMD pads alone — the assembly *price* endpoint's `patch_pad_number`.
66
+ *
67
+ * The order form uses `padCount` (any pad when the board has no SMD ones);
68
+ * the valuation endpoint prices the placed SMD pads, so it needs the split.
69
+ */
70
+ readonly smdPadCount?: number
71
+ /** Plated through-hole pads — the valuation endpoint's `plug_number`. */
72
+ readonly pthPadCount?: number
73
+ /**
74
+ * Distinct (value, footprint) pairs — the valuation endpoint's
75
+ * `bom_material_type_number`.
76
+ *
77
+ * Counted from the board's own footprints, so an assembly price needs no BOM
78
+ * export and no `kicad-cli` run.
79
+ */
80
+ readonly partCount?: number
64
81
  /**
65
82
  * Display names the board gives its copper layers, canonical name as value
66
83
  * (`{ top_copper: 'F_Cu' }`).
@@ -217,6 +234,16 @@ function snapOz(thicknessMm: number, allowed: readonly number[]): number {
217
234
  return best
218
235
  }
219
236
 
237
+ /** A footprint's value text: the `Value` property (KiCad 8+) or its legacy `fp_text`. */
238
+ function footprintValue(node: SExpr[]): string {
239
+ for (const entry of node) {
240
+ if (!isNode(entry)) continue
241
+ if (head(entry) === 'property' && entry[1] === 'Value' && typeof entry[2] === 'string') return entry[2]
242
+ if (head(entry) === 'fp_text' && entry[1] === 'value' && typeof entry[2] === 'string') return entry[2]
243
+ }
244
+ return ''
245
+ }
246
+
220
247
  /**
221
248
  * Derive the fabrication facts the order form needs from a saved board.
222
249
  *
@@ -255,6 +282,9 @@ export function readBoardFacts(text: string): BoardFacts {
255
282
  let minViaDrillMm: number | undefined
256
283
  let smdPads = 0
257
284
  let allPads = 0
285
+ let smdPadCount = 0
286
+ let pthPadCount = 0
287
+ const parts = new Set<string>()
258
288
 
259
289
  for (const node of root) {
260
290
  if (!isNode(node)) continue
@@ -270,10 +300,27 @@ export function readBoardFacts(text: string): BoardFacts {
270
300
  continue
271
301
  }
272
302
  if (name === 'footprint') {
273
- const pads = node.filter((entry): entry is SExpr[] => isNode(entry) && head(entry) === 'pad').length
274
- allPads += pads
303
+ const padNodes = node.filter((entry): entry is SExpr[] => isNode(entry) && head(entry) === 'pad')
304
+ allPads += padNodes.length
275
305
  const attr = child(node, 'attr') ?? []
276
- if (attr.some(entry => entry === 'smd')) smdPads += pads
306
+ const isSmd = attr.some(entry => entry === 'smd')
307
+ if (isSmd) smdPads += padNodes.length
308
+ // Pad *type* is per pad, so it survives a footprint whose attr is not
309
+ // the whole story (a module with mixed pads). `np_thru_hole` pads are
310
+ // mounting holes: neither placed nor plugged.
311
+ for (const pad of padNodes) {
312
+ if (pad[2] === 'smd') smdPadCount += 1
313
+ else if (pad[2] === 'thru_hole') pthPadCount += 1
314
+ }
315
+ // Distinct value/footprint pairs, the assembly price's material count.
316
+ // A BOM-less count keeps quoting free of a kicad-cli run; the library
317
+ // part name after `:` is what a BOM's Footprint column would show.
318
+ const libId = typeof node[1] === 'string' ? node[1] : ''
319
+ const excluded = attr.some(entry => entry === 'exclude_from_bom' || entry === 'board_only')
320
+ if (libId !== '' && !excluded) {
321
+ const footprint = libId.slice(libId.lastIndexOf(':') + 1)
322
+ parts.add(`${footprintValue(node)}\u0000${footprint}`)
323
+ }
277
324
  continue
278
325
  }
279
326
  if (name === 'segment' || name === 'arc') {
@@ -313,6 +360,8 @@ export function readBoardFacts(text: string): BoardFacts {
313
360
  ...(outerThickness === undefined ? {} : { outerOz: snapOz(outerThickness, [1, 2, 3, 4]) }),
314
361
  ...(innerThickness === undefined ? {} : { innerOz: snapOz(innerThickness, [0.5, 1, 2, 3, 4]) }),
315
362
  ...(allPads === 0 ? {} : { padCount: smdPads > 0 ? smdPads : allPads }),
363
+ ...(allPads === 0 ? {} : { smdPadCount, pthPadCount }),
364
+ ...(parts.size === 0 ? {} : { partCount: parts.size }),
316
365
  ...(Object.keys(copperAliases).length === 0 ? {} : { copperAliases }),
317
366
  }
318
367
  }
package/src/quote.ts ADDED
@@ -0,0 +1,488 @@
1
+ /**
2
+ * Real-time PCB and SMT price quoting, straight from the board file.
3
+ *
4
+ * `order.ts` can already reach the Huaqiu *order* endpoints, but an order
5
+ * endpoint answers with a page URL — the price is drawn by that page, which is
6
+ * why asking "how much is this board?" used to mean opening the order page.
7
+ * The vendor has a second, separate endpoint family for that question:
8
+ *
9
+ * PCB POST <base>/openapi/api/hqpcb/public/ajax_valuation form
10
+ * SMT POST <base>/openapi/api/smt-hqchip/smtservice/app/price/pricing JSON
11
+ *
12
+ * Both are anonymous (no login, no token, no order id), both return itemized
13
+ * JSON, and neither knows anything about KiCad — so a price needs no running
14
+ * editor, no HQ Edge and no `kicad-cli`: only the `.kicad_pcb` file, whose
15
+ * geometry and pad counts are read by `readBoardFacts`.
16
+ *
17
+ * The PCB form is deliberately built *on top of* `pcbOrderForm`: the quote is
18
+ * the price of the exact form this plugin would order, with only the five
19
+ * fields the valuation endpoint insists on (its region/transport block plus a
20
+ * delivery address) replaced. Anything else the board or the caller controls
21
+ * therefore cannot drift between "what the agent quoted" and "what the order
22
+ * page shows".
23
+ *
24
+ * Wire contract provenance: the same one hq-edge implements for
25
+ * `hq.fab.v1.QuoteService` (`apps/server/src/quote/{defaults,serialize,parse}`),
26
+ * itself ported from the reference plugin's `pcb_price_model.py` /
27
+ * `smt_price_model.py` and the KiCad copilot's quote views. Two behaviours are
28
+ * load-bearing and were verified against the live endpoint while writing this:
29
+ *
30
+ * - `pbnum` (panel count) and `address` are REQUIRED; omitting either is a
31
+ * Spring `400 Bad Request` with no explanation. `insidecopper` must be
32
+ * present even for 2-layer boards (value 0).
33
+ * - `total` already includes `expressage` (shipping), so the fee items plus
34
+ * the shipping line are what the total is made of — never add them twice.
35
+ *
36
+ * Nothing here mutates state: a quote creates no order, uploads nothing and
37
+ * needs no confirmation.
38
+ *
39
+ * @module
40
+ */
41
+
42
+ import { pcbOrderForm, type BoardFacts } from './order.js'
43
+
44
+ /** Endpoint paths relative to the quote base URL (the host, not a DSH route). */
45
+ export const QUOTE_PATHS = Object.freeze({
46
+ pcb: '/openapi/api/hqpcb/public/ajax_valuation',
47
+ smt: '/openapi/api/smt-hqchip/smtservice/app/price/pricing',
48
+ })
49
+
50
+ /** Origin serving the two valuation endpoints. */
51
+ export const DEFAULT_QUOTE_BASE_URL = 'https://www.eda.cn'
52
+
53
+ /** Boards per quote when the caller names no quantity (the reference default). */
54
+ export const DEFAULT_QUOTE_QUANTITY = 5
55
+
56
+ /** Solder mask colours the price endpoint knows, by the form's Chinese label. */
57
+ const MASK_LABEL: Readonly<Record<string, string>> = Object.freeze({
58
+ green: '绿色',
59
+ red: '红色',
60
+ yellow: '黄色',
61
+ blue: '蓝色',
62
+ white: '白色',
63
+ black: '黑色',
64
+ matte_black: '哑黑',
65
+ })
66
+
67
+ /** Surface finishes, by the form's Chinese label. */
68
+ const FINISH_LABEL: Readonly<Record<string, string>> = Object.freeze({
69
+ hasl_lead: '有铅喷锡',
70
+ hasl_lf: '无铅喷锡',
71
+ enig: '沉金',
72
+ osp: 'OSP',
73
+ })
74
+
75
+ /**
76
+ * The valuation endpoint's own transport block for the China region.
77
+ *
78
+ * Distinct from the order form's block (`service: ''`, `region_id: 'cn'`,
79
+ * `express: ''`): the price endpoint validates its region/mail values and
80
+ * refuses the quote without an `address`, while the order endpoint derives all
81
+ * of that from the signed-in account. These five fields are the only ones a
82
+ * quote overrides.
83
+ */
84
+ const CN_QUOTE_TRANSPORT: Readonly<Record<string, string>> = Object.freeze({
85
+ service: 'pcb',
86
+ region_id: '211',
87
+ country: '211',
88
+ express: '顺丰快递',
89
+ address: '广东省深圳市',
90
+ })
91
+
92
+ /** The PCB form field carrying shipping — reported on its own line. */
93
+ const SHIPPING_KEY = 'expressage'
94
+
95
+ /**
96
+ * Fee keys that are not `*fee`-suffixed. Everything else the endpoint charges
97
+ * for does end in `fee`, so a vendor fee we have never seen still lands in the
98
+ * itemized list instead of vanishing from the total.
99
+ */
100
+ const PLAIN_FEE_KEYS: readonly string[] = [
101
+ 'plate', 'clc', 'gch', 'pin', 'luocao', 'luocheng',
102
+ ]
103
+
104
+ export type QuoteColor =
105
+ | 'green' | 'red' | 'yellow' | 'blue' | 'white' | 'black' | 'matte_black'
106
+
107
+ export type QuoteSurfaceFinish = 'hasl_lead' | 'hasl_lf' | 'enig' | 'osp'
108
+
109
+ export interface PcbQuoteOverrides {
110
+ /** Boards to price (the form's `bcount`). */
111
+ readonly quantity?: number
112
+ /** Price a different copper stack-up than the file's (what-if). */
113
+ readonly layers?: number
114
+ /**
115
+ * Board thickness in mm, snapped onto the fabricator's menu for the layer
116
+ * count. `kicad_pcb`'s `general.thickness` is used when absent.
117
+ */
118
+ readonly thicknessMm?: number
119
+ readonly color?: QuoteColor
120
+ readonly surfaceFinish?: QuoteSurfaceFinish
121
+ }
122
+
123
+ export interface SmtQuoteOverrides {
124
+ /** Assembled quantity (the form's `number`). */
125
+ readonly quantity?: number
126
+ readonly sides?: 'single' | 'double'
127
+ }
128
+
129
+ /** `mm` → the centimetre-grade string the endpoint expects. */
130
+ function cm(mm: number): string {
131
+ return (mm / 10).toFixed(2)
132
+ }
133
+
134
+ /**
135
+ * The PCB valuation form: our own order form, plus the endpoint's transport.
136
+ *
137
+ * Reusing `pcbOrderForm` is the point — the thickness menu, the trace/hole
138
+ * tiers, TG grade, inner copper and the default mask/finish are all resolved in
139
+ * one place, so a quote can never describe a board differently from the order
140
+ * this plugin would place for it.
141
+ */
142
+ export function pcbQuoteForm(
143
+ facts: BoardFacts,
144
+ overrides: PcbQuoteOverrides = {},
145
+ ): Record<string, string> {
146
+ // A what-if layer count has to reach the derived fields too: thickness menu,
147
+ // inner copper and TG grade are all keyed on the copper count.
148
+ const shaped: BoardFacts = overrides.layers === undefined || overrides.layers === facts.layers
149
+ ? facts
150
+ : { ...facts, layers: overrides.layers }
151
+ const order = pcbOrderForm(shaped, {
152
+ ...(overrides.quantity === undefined ? {} : { quantity: overrides.quantity }),
153
+ ...(overrides.color === undefined
154
+ ? {}
155
+ : { solderMaskColor: MASK_LABEL[overrides.color] ?? overrides.color }),
156
+ ...(overrides.surfaceFinish === undefined
157
+ ? {}
158
+ : { surfaceFinish: FINISH_LABEL[overrides.surfaceFinish] ?? overrides.surfaceFinish }),
159
+ ...(overrides.thicknessMm === undefined ? {} : { thicknessMm: overrides.thicknessMm }),
160
+ })
161
+ return { ...order, ...CN_QUOTE_TRANSPORT }
162
+ }
163
+
164
+ /**
165
+ * The SMT valuation form.
166
+ *
167
+ * Not the order form: the assembly *order* endpoint reads `pcb_ban_height` as
168
+ * the board's thickness and `pcb_ban_width` as its length, while the *price*
169
+ * endpoint reads them as the panel's height and width in cm. Two endpoints,
170
+ * two readings of the same key names — this is why the quote builds its own
171
+ * assembly form instead of borrowing `smtOrderForm`.
172
+ */
173
+ export function smtQuoteForm(
174
+ facts: BoardFacts,
175
+ overrides: SmtQuoteOverrides = {},
176
+ ): Record<string, string | number> {
177
+ const patchPads = facts.smdPadCount ?? facts.padCount ?? 0
178
+ const plugPads = facts.pthPadCount ?? 0
179
+ return {
180
+ add_plat_form: 5,
181
+ patch_file_name: '',
182
+ bom_file_name: '',
183
+ pcb_file_name: '',
184
+ application_sphere: 1,
185
+ is_pcb_soft_board: 0,
186
+ single_or_double_technique: overrides.sides === 'single' ? '1' : '2',
187
+ custom_pcb_ban: 1,
188
+ // Huaqiu agent part purchasing, the reference default. The price endpoint
189
+ // prices assembly labour either way — no part list is uploaded here.
190
+ bom_purchase: '1',
191
+ number: String(overrides.quantity ?? DEFAULT_QUOTE_QUANTITY),
192
+ pcb_ban_height: cm(facts.heightMm),
193
+ pcb_ban_width: cm(facts.widthMm),
194
+ bom_material_type_number: String(facts.partCount ?? 1),
195
+ patch_pad_number: String(patchPads),
196
+ is_plug: 1,
197
+ plug_number: String(plugPads),
198
+ steel_type: 0,
199
+ is_steel_follow_delivery: 0,
200
+ solder_paste_type: 0,
201
+ is_assembly_weld: 0,
202
+ is_layout_cleaning: 0,
203
+ is_material_baking: 0,
204
+ is_welding_wire: 0,
205
+ is_test: 0,
206
+ is_assemble: 0,
207
+ is_program_burning: 0,
208
+ need_split: 0,
209
+ is_increase_tinning: 0,
210
+ need_conformal_coating: 0,
211
+ is_first_confirm: 0,
212
+ packing_type: 0,
213
+ x_ray_number: 1,
214
+ x_ray_unit_number: 1,
215
+ }
216
+ }
217
+
218
+ // ---------------------------------------------------------------------------
219
+ // Response shapes
220
+ // ---------------------------------------------------------------------------
221
+
222
+ /** One charged line, under the vendor's own key (its UI shows the same name). */
223
+ export interface QuoteFee {
224
+ readonly key: string
225
+ readonly amount: number
226
+ }
227
+
228
+ /** One delivery option the quote offers. */
229
+ export interface QuoteDelivery {
230
+ /** Lead-time name as returned, e.g. "正常5天". */
231
+ readonly name: string
232
+ readonly days?: number
233
+ /** This option's total, when the endpoint prices it separately. */
234
+ readonly totalPrice?: number
235
+ }
236
+
237
+ export interface PcbQuote {
238
+ readonly kind: 'pcb'
239
+ readonly region: 'cn'
240
+ readonly currency: 'CNY'
241
+ readonly currencySymbol: '¥'
242
+ /** Boards priced (the form's `bcount`). */
243
+ readonly quantity: number
244
+ /** What the whole panel run costs, shipping included. */
245
+ readonly totalPrice: number
246
+ /** `totalPrice / quantity`, rounded to fen. */
247
+ readonly unitPrice: number
248
+ /** The `expressage` line, when the endpoint charged one. */
249
+ readonly shipping?: number
250
+ readonly leadTimeDays?: number
251
+ /** Fabrication fees, shipping excluded. */
252
+ readonly items: readonly QuoteFee[]
253
+ readonly delivery: readonly QuoteDelivery[]
254
+ }
255
+
256
+ export interface SmtQuote {
257
+ readonly kind: 'smt'
258
+ readonly region: 'cn'
259
+ readonly currency: 'CNY'
260
+ readonly currencySymbol: '¥'
261
+ readonly quantity: number
262
+ readonly totalPrice: number
263
+ readonly unitPrice: number
264
+ /** Assembly fees, tax included. */
265
+ readonly items: readonly QuoteFee[]
266
+ /** The endpoint's own tax split (the CN body reports it explicitly). */
267
+ readonly smt: {
268
+ readonly noTax?: number
269
+ readonly tax?: number
270
+ readonly total?: number
271
+ }
272
+ }
273
+
274
+ type Wire = Record<string, unknown>
275
+
276
+ function toNumber(value: unknown): number | undefined {
277
+ if (typeof value === 'number') return Number.isFinite(value) ? value : undefined
278
+ if (typeof value !== 'string') return undefined
279
+ const trimmed = value.trim()
280
+ if (trimmed === '') return undefined
281
+ const parsed = Number(trimmed)
282
+ return Number.isFinite(parsed) ? parsed : undefined
283
+ }
284
+
285
+ function round2(value: number): number {
286
+ return Math.round(value * 100) / 100
287
+ }
288
+
289
+ /** A payload we cannot price is a failure, not an empty quote. */
290
+ function unreadable(detail: string, code = 'quote-unreadable'): Error {
291
+ return Object.assign(new Error(`the price endpoint returned an unexpected payload: ${detail}`), {
292
+ code,
293
+ status: 502,
294
+ })
295
+ }
296
+
297
+ /** "正常5天" / "5 days" → 5; hours are reported as a fraction of a day. */
298
+ export function leadTimeDays(name: unknown): number | undefined {
299
+ if (typeof name !== 'string') return undefined
300
+ const digits = /\d+/u.exec(name)?.[0]
301
+ if (digits === undefined) return undefined
302
+ const time = Number(digits)
303
+ if (!Number.isFinite(time)) return undefined
304
+ if (name.includes('天')) return time
305
+ if (name.includes('小时') || /hour/iu.test(name)) return round2(time / 24)
306
+ // The international payloads say "5 days" / "5-7 days": the first number is
307
+ // the advertised lead time, the range's upper bound the worst case.
308
+ if (/day/iu.test(name)) return time
309
+ return undefined
310
+ }
311
+
312
+ /** The delivery options a `suggest.deltime` array describes. */
313
+ function deliveryOf(suggest: unknown, total: number): QuoteDelivery[] {
314
+ if (typeof suggest !== 'object' || suggest === null) return []
315
+ const deltime = (suggest as Wire)['deltime']
316
+ if (!Array.isArray(deltime)) return []
317
+ const options: QuoteDelivery[] = []
318
+ for (const entry of deltime) {
319
+ if (typeof entry !== 'object' || entry === null) continue
320
+ const record = entry as Wire
321
+ const name = typeof record['name'] === 'string' ? record['name'] : ''
322
+ if (name === '') continue
323
+ const days = leadTimeDays(name)
324
+ // `fee` is an extra charge on top of the quote (an urgent option);
325
+ // `total`, when present, is that option's own price.
326
+ const fee = toNumber(record['fee'])
327
+ const own = toNumber(record['total'])
328
+ const totalPrice = own ?? (fee === undefined ? undefined : round2(total + fee))
329
+ options.push({
330
+ name,
331
+ ...(days === undefined ? {} : { days }),
332
+ ...(totalPrice === undefined ? {} : { totalPrice }),
333
+ })
334
+ }
335
+ return options
336
+ }
337
+
338
+ /**
339
+ * The record that actually carries the PCB fees.
340
+ *
341
+ * Two shapes exist in the wild: `{data: {list: {pcb: {...}}}}` (the
342
+ * international shape) and the flat one the CN endpoint returns, where the
343
+ * payload itself is the fee record and `suggest` rides along. Only the `pcb`
344
+ * category is a board price, so it is picked explicitly rather than letting
345
+ * whichever category came last win.
346
+ */
347
+ function pcbFeeRecord(body: Wire): Wire {
348
+ const data = body['data']
349
+ if (typeof data === 'object' && data !== null) {
350
+ const list = (data as Wire)['list']
351
+ if (typeof list === 'object' && list !== null) {
352
+ const categories = list as Wire
353
+ for (const category of ['pcb', ...Object.keys(categories)]) {
354
+ const entry = categories[category]
355
+ if (typeof entry === 'object' && entry !== null && hasFees(entry as Wire)) return entry as Wire
356
+ }
357
+ }
358
+ }
359
+ if (typeof body['suggest'] === 'object' && body['suggest'] !== null) return body
360
+ throw unreadable('no PCB fee record (data.list.pcb or suggest) in the response')
361
+ }
362
+
363
+ function hasFees(record: Wire): boolean {
364
+ for (const key of Object.keys(record)) {
365
+ if (isFeeKey(key) && toNumber(record[key]) !== undefined) return true
366
+ }
367
+ return false
368
+ }
369
+
370
+ function isFeeKey(key: string): boolean {
371
+ if (key === SHIPPING_KEY) return false
372
+ if (PLAIN_FEE_KEYS.includes(key)) return true
373
+ return key.endsWith('fee')
374
+ }
375
+
376
+ /**
377
+ * Normalize a PCB valuation response.
378
+ *
379
+ * The total is the endpoint's own `total` whenever it sends one: it is the
380
+ * number the order page shows, and it already includes shipping. Summing the
381
+ * items is only the fallback for a payload without it, because not every fee
382
+ * key is one we know about.
383
+ */
384
+ export function parsePcbQuote(body: unknown, quantity: number): PcbQuote {
385
+ if (typeof body !== 'object' || body === null || Array.isArray(body)) {
386
+ throw unreadable('the response is not a JSON object')
387
+ }
388
+ const record = pcbFeeRecord(body as Wire)
389
+
390
+ const items: QuoteFee[] = []
391
+ for (const [key, raw] of Object.entries(record)) {
392
+ if (!isFeeKey(key)) continue
393
+ const amount = toNumber(raw)
394
+ if (amount === undefined || amount === 0) continue
395
+ items.push({ key, amount })
396
+ }
397
+
398
+ const shipping = toNumber(record[SHIPPING_KEY])
399
+ const summed = round2(items.reduce((total, item) => total + item.amount, 0) + (shipping ?? 0))
400
+ const total = toNumber(record['total']) ?? toNumber(record['webpay']) ?? summed
401
+ if (items.length === 0 && total === 0) {
402
+ const message = typeof record['msg'] === 'string' ? record['msg'] : 'no fees in the response'
403
+ throw unreadable(message, 'quote-rejected')
404
+ }
405
+
406
+ const suggest = typeof record['suggest'] === 'object' && record['suggest'] !== null
407
+ ? record['suggest']
408
+ : (body as Wire)['suggest']
409
+ const delivery = deliveryOf(suggest, total)
410
+ const days = leadTimeDays(record['deltime']) ?? delivery.find(option => option.days !== undefined)?.days
411
+
412
+ return {
413
+ kind: 'pcb',
414
+ region: 'cn',
415
+ currency: 'CNY',
416
+ currencySymbol: '¥',
417
+ quantity,
418
+ totalPrice: round2(total),
419
+ unitPrice: quantity > 0 ? round2(total / quantity) : round2(total),
420
+ ...(shipping === undefined || shipping === 0 ? {} : { shipping }),
421
+ ...(days === undefined ? {} : { leadTimeDays: days }),
422
+ items,
423
+ delivery,
424
+ }
425
+ }
426
+
427
+ /**
428
+ * Normalize an SMT valuation response (`{suc, body}`).
429
+ *
430
+ * The CN body reports `smt_goods_fee_no_tax` and `smt_goods_fee_tax`, where the
431
+ * "tax" figure is the tax *amount* (13% of the net) — so the price is their
432
+ * sum. It also itemizes the assembly (`boot_fee` stencil, `patch_fee`, …), all
433
+ * tax included, and those lines add up to that sum exactly.
434
+ */
435
+ export function parseSmtQuote(body: unknown, quantity: number): SmtQuote {
436
+ if (typeof body !== 'object' || body === null || Array.isArray(body)) {
437
+ throw unreadable('the response is not a JSON object')
438
+ }
439
+ const envelope = body as Wire
440
+ if (envelope['suc'] !== true && envelope['suc'] !== 1) {
441
+ const message = typeof envelope['msg'] === 'string' ? envelope['msg'] : 'the assembly endpoint refused the quote'
442
+ throw unreadable(message, 'quote-rejected')
443
+ }
444
+ const payload = envelope['body']
445
+ if (typeof payload !== 'object' || payload === null) {
446
+ throw unreadable('the assembly response carries no body')
447
+ }
448
+ const record = payload as Wire
449
+
450
+ const items: QuoteFee[] = []
451
+ for (const [key, raw] of Object.entries(record)) {
452
+ // `smt_goods_fee` / `smt_order_fee` are the body's own aggregates (and
453
+ // their `_no_tax`/`_tax` splits), not lines: listing them would double the
454
+ // price. Every other `*_fee` is a real charge.
455
+ if (/^smt_(?:goods|order)_fee/u.test(key)) continue
456
+ if (!key.endsWith('fee') || key.endsWith('_no_tax')) continue
457
+ const amount = toNumber(raw)
458
+ if (amount === undefined || amount === 0) continue
459
+ items.push({ key, amount })
460
+ }
461
+
462
+ const noTax = toNumber(record['smt_goods_fee_no_tax']) ?? toNumber(record['smt_order_fee_no_tax'])
463
+ const tax = toNumber(record['smt_goods_fee_tax']) ?? toNumber(record['smt_order_fee_tax'])
464
+ const declared = toNumber(record['total'])
465
+ const total = declared
466
+ ?? (noTax !== undefined && tax !== undefined ? round2(noTax + tax) : undefined)
467
+ ?? (noTax !== undefined || tax !== undefined ? round2((noTax ?? 0) + (tax ?? 0)) : undefined)
468
+ ?? round2(items.reduce((sum, item) => sum + item.amount, 0))
469
+ if (total === 0 && items.length === 0) {
470
+ throw unreadable('no assembly fees in the response', 'quote-rejected')
471
+ }
472
+
473
+ return {
474
+ kind: 'smt',
475
+ region: 'cn',
476
+ currency: 'CNY',
477
+ currencySymbol: '¥',
478
+ quantity,
479
+ totalPrice: round2(total),
480
+ unitPrice: quantity > 0 ? round2(total / quantity) : round2(total),
481
+ items,
482
+ smt: {
483
+ ...(noTax === undefined ? {} : { noTax }),
484
+ ...(tax === undefined ? {} : { tax }),
485
+ ...(declared === undefined ? {} : { total: declared }),
486
+ },
487
+ }
488
+ }