@voxgig/sdkgen 4.36.0 → 4.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/bin/voxgig-sdkgen +1 -1
  2. package/dist/helpers/flowGuard.js +4 -4
  3. package/dist/helpers/flowGuard.js.map +1 -1
  4. package/dist/helpers/liveDiscovery.d.ts +7 -0
  5. package/dist/helpers/liveDiscovery.js +20 -0
  6. package/dist/helpers/liveDiscovery.js.map +1 -0
  7. package/dist/helpers/opShape.d.ts +2 -1
  8. package/dist/helpers/opShape.js +4 -0
  9. package/dist/helpers/opShape.js.map +1 -1
  10. package/dist/helpers/pointPath.d.ts +2 -1
  11. package/dist/helpers/pointPath.js +6 -0
  12. package/dist/helpers/pointPath.js.map +1 -1
  13. package/dist/helpers/testPolicy.d.ts +14 -4
  14. package/dist/helpers/testPolicy.js +152 -54
  15. package/dist/helpers/testPolicy.js.map +1 -1
  16. package/dist/sdkgen.d.ts +8 -6
  17. package/dist/sdkgen.js +11 -5
  18. package/dist/sdkgen.js.map +1 -1
  19. package/dist/tsconfig.tsbuildinfo +1 -1
  20. package/dist/utility.js +7 -3
  21. package/dist/utility.js.map +1 -1
  22. package/package.json +1 -1
  23. package/project/.sdk/src/cmp/c/TestDirect_c.ts +3 -2
  24. package/project/.sdk/src/cmp/cpp/TestDirect_cpp.ts +3 -2
  25. package/project/.sdk/src/cmp/cpp/TestEntity_cpp.ts +33 -10
  26. package/project/.sdk/src/cmp/csharp/TestDirect_csharp.ts +12 -12
  27. package/project/.sdk/src/cmp/csharp/TestEntity_csharp.ts +73 -28
  28. package/project/.sdk/src/cmp/go/Entity_go.ts +1 -1
  29. package/project/.sdk/src/cmp/go/MainEntity_go.ts +1 -1
  30. package/project/.sdk/src/cmp/go/Main_go.ts +7 -3
  31. package/project/.sdk/src/cmp/go/ReadmeModel_go.ts +3 -3
  32. package/project/.sdk/src/cmp/go/ReadmeRef_go.ts +1 -1
  33. package/project/.sdk/src/cmp/go/TestDirect_go.ts +12 -10
  34. package/project/.sdk/src/cmp/go/TestEntity_go.ts +67 -23
  35. package/project/.sdk/src/cmp/go-cli/fragment/words.fragment.go +1 -1
  36. package/project/.sdk/src/cmp/go-mcp/fragment/tools.fragment.go +1 -1
  37. package/project/.sdk/src/cmp/java/TestDirect_java.ts +12 -11
  38. package/project/.sdk/src/cmp/java/TestEntity_java.ts +71 -23
  39. package/project/.sdk/src/cmp/js/TestDirect_js.ts +13 -12
  40. package/project/.sdk/src/cmp/js/TestEntity_js.ts +41 -17
  41. package/project/.sdk/src/cmp/kotlin/TestDirect_kotlin.ts +12 -10
  42. package/project/.sdk/src/cmp/kotlin/TestEntity_kotlin.ts +64 -23
  43. package/project/.sdk/src/cmp/lua/TestDirect_lua.ts +9 -5
  44. package/project/.sdk/src/cmp/lua/TestEntity_lua.ts +61 -23
  45. package/project/.sdk/src/cmp/perl/TestDirect_perl.ts +9 -5
  46. package/project/.sdk/src/cmp/perl/TestEntity_perl.ts +58 -24
  47. package/project/.sdk/src/cmp/php/TestDirect_php.ts +9 -5
  48. package/project/.sdk/src/cmp/php/TestEntity_php.ts +61 -23
  49. package/project/.sdk/src/cmp/py/TestDirect_py.ts +10 -6
  50. package/project/.sdk/src/cmp/py/TestEntity_py.ts +59 -27
  51. package/project/.sdk/src/cmp/rb/TestDirect_rb.ts +9 -5
  52. package/project/.sdk/src/cmp/rb/TestEntity_rb.ts +59 -23
  53. package/project/.sdk/src/cmp/rust/EntityOperation_rust.ts +1 -1
  54. package/project/.sdk/src/cmp/rust/Main_rust.ts +3 -1
  55. package/project/.sdk/src/cmp/rust/ReadmeHowto_rust.ts +1 -1
  56. package/project/.sdk/src/cmp/rust/ReadmeModel_rust.ts +1 -1
  57. package/project/.sdk/src/cmp/rust/ReadmeQuick_rust.ts +1 -1
  58. package/project/.sdk/src/cmp/rust/ReadmeRef_rust.ts +1 -1
  59. package/project/.sdk/src/cmp/rust/ReadmeTopQuick_rust.ts +1 -1
  60. package/project/.sdk/src/cmp/rust/ReadmeTopTest_rust.ts +1 -1
  61. package/project/.sdk/src/cmp/rust/TestClean_rust.ts +1 -1
  62. package/project/.sdk/src/cmp/rust/TestDirect_rust.ts +9 -8
  63. package/project/.sdk/src/cmp/rust/TestEntity_rust.ts +57 -25
  64. package/project/.sdk/src/cmp/rust/fragment/Entity.fragment.rs +2 -2
  65. package/project/.sdk/src/cmp/scala/TestDirect_scala.ts +3 -2
  66. package/project/.sdk/src/cmp/scala/TestEntity_scala.ts +36 -9
  67. package/project/.sdk/src/cmp/ts/TestDirect_ts.ts +15 -32
  68. package/project/.sdk/src/cmp/ts/TestEntity_ts.ts +41 -17
  69. package/project/.sdk/tm/c/core/sdk.h +2 -2
  70. package/project/.sdk/tm/c/tests/transport_test.c +33 -0
  71. package/project/.sdk/tm/c/utility/fetcher.c +151 -2
  72. package/project/.sdk/tm/c/utility/make_url.c +8 -6
  73. package/project/.sdk/tm/clojure/src/sdk/core.clj +17 -10
  74. package/project/.sdk/tm/clojure/test/sdk/test/pipeline.clj +38 -0
  75. package/project/.sdk/tm/cpp/utility/pipeline.hpp +5 -4
  76. package/project/.sdk/tm/csharp/test/PrimaryUtilityTest.cs +69 -0
  77. package/project/.sdk/tm/csharp/utility/Fetcher.cs +3 -1
  78. package/project/.sdk/tm/csharp/utility/MakeUrl.cs +5 -4
  79. package/project/.sdk/tm/elixir/lib/projectname/utility.ex +10 -6
  80. package/project/.sdk/tm/elixir/test/pipeline_test.exs +61 -0
  81. package/project/.sdk/tm/go/core/helpers.go +1 -1
  82. package/project/.sdk/tm/go/core/types.go +9 -1
  83. package/project/.sdk/tm/go/test/primary_utility_test.go +60 -0
  84. package/project/.sdk/tm/go/utility/fetcher.go +15 -4
  85. package/project/.sdk/tm/go/utility/make_url.go +4 -3
  86. package/project/.sdk/tm/java/test/PrimaryUtilityTest.java +47 -0
  87. package/project/.sdk/tm/java/utility/MakeUrl.java +5 -4
  88. package/project/.sdk/tm/js/src/utility/MakeUrlUtility.js +5 -3
  89. package/project/.sdk/tm/js/test/live-runner.js +4 -3
  90. package/project/.sdk/tm/js/test/utility/PrimaryUtility.test.js +40 -0
  91. package/project/.sdk/tm/kotlin/test/PrimaryUtilityTest.kt +41 -0
  92. package/project/.sdk/tm/kotlin/utility/MakeSpecUrl.kt +4 -3
  93. package/project/.sdk/tm/lua/test/primary_utility_test.lua +61 -0
  94. package/project/.sdk/tm/lua/utility/fetcher.lua +54 -6
  95. package/project/.sdk/tm/lua/utility/make_url.lua +5 -4
  96. package/project/.sdk/tm/ocaml/sdk_runtime.ml +5 -5
  97. package/project/.sdk/tm/perl/t/primary_utility.t +54 -0
  98. package/project/.sdk/tm/perl/utility/fetcher.pm +65 -11
  99. package/project/.sdk/tm/perl/utility/make_url.pm +4 -3
  100. package/project/.sdk/tm/php/test/PipelineTest.php +52 -0
  101. package/project/.sdk/tm/php/utility/Fetcher.php +81 -15
  102. package/project/.sdk/tm/php/utility/MakeUrl.php +5 -3
  103. package/project/.sdk/tm/py/pkg/utility/fetcher.py +1 -0
  104. package/project/.sdk/tm/py/pkg/utility/make_url.py +5 -4
  105. package/project/.sdk/tm/py/test/test_primary_utility.py +52 -0
  106. package/project/.sdk/tm/rb/test/primary_utility_test.rb +46 -0
  107. package/project/.sdk/tm/rb/utility/fetcher.rb +41 -5
  108. package/project/.sdk/tm/rb/utility/make_url.rb +5 -3
  109. package/project/.sdk/tm/rust/core/helpers.rs +1 -1
  110. package/project/.sdk/tm/rust/core/types.rs +2 -2
  111. package/project/.sdk/tm/rust/tests/primary_utility_test.rs +65 -0
  112. package/project/.sdk/tm/rust/utility/make_url.rs +7 -6
  113. package/project/.sdk/tm/scala/sdktest/SdkTestMain.scala +47 -1
  114. package/project/.sdk/tm/scala/utility/Make.scala +8 -6
  115. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/utility/Fetcher.swift +59 -15
  116. package/project/.sdk/tm/swift/Sources/ProjectNameSDK/utility/Make.swift +4 -4
  117. package/project/.sdk/tm/swift/Tests/ProjectNameSDKTests/PrimaryUtilityTest.swift +72 -0
  118. package/project/.sdk/tm/ts/src/utility/MakeUrlUtility.ts +5 -3
  119. package/project/.sdk/tm/ts/test/live-runner.ts +4 -3
  120. package/project/.sdk/tm/ts/test/utility/PrimaryUtility.test.ts +40 -0
  121. package/project/.sdk/tm/zig/core/utility.zig +5 -5
  122. package/project/sdkgen-package.json +1 -1
  123. package/src/helpers/flowGuard.ts +4 -4
  124. package/src/helpers/liveDiscovery.ts +31 -0
  125. package/src/helpers/opShape.ts +6 -0
  126. package/src/helpers/pointPath.ts +8 -0
  127. package/src/helpers/testPolicy.ts +193 -55
  128. package/src/sdkgen.ts +13 -3
  129. package/src/utility.ts +10 -4
@@ -19,6 +19,7 @@ import {
19
19
  buildIdNames,
20
20
  getMatchEntries,
21
21
  entityDataIdField,
22
+ entityRecordIdField,
22
23
  } from '@voxgig/sdkgen'
23
24
 
24
25
 
@@ -104,7 +105,7 @@ ${failureScopes(SDK, entity, accessor)}
104
105
  rep.scope("${ENTLOWER}.basic") {
105
106
  val entityData = Helpers.toMapAny(SdkTestSupport.readJson(
106
107
  "../.sdk/test/entity/${ENTLOWER}/${EntityName}TestData.json"))
107
- val options = new LinkedHashMap[String, Object]()
108
+ ${fixtureIdentity(entity)} val options = new LinkedHashMap[String, Object]()
108
109
  options.put("entity", entityData.get("existing"))
109
110
  val client = ${SDK}.testSDK(options, null)
110
111
 
@@ -184,7 +185,7 @@ const generateCreate: OpGen = (ctx, step, index) => {
184
185
  rep.check("${ENTLOWER}.create.map", ${datavar} != null, "expected create result to be a map")
185
186
  `)
186
187
  if (null != entityDataIdField(entity)) {
187
- Content(` rep.check("${ENTLOWER}.create.id", ${datavar} != null && ${datavar}.get("id") != null, "expected created entity to have an id")
188
+ Content(` rep.check("${ENTLOWER}.create.id", ${datavar} != null && ${datavar}.get(${rid(entity)}) != null, "expected created entity to have an id")
188
189
  `)
189
190
  }
190
191
  }
@@ -242,12 +243,12 @@ const generateList: OpGen = (ctx, step, index) => {
242
243
 
243
244
  if ('ItemExists' === validator.apply && hasRefData && hasDataId) {
244
245
  Content(` val ${listvar}Found = Struct.select(
245
- SdkTestSupport.entityListToData(${listvar}), SdkTestSupport.om("id" -> ${refDataVar}.get("id")))
246
+ SdkTestSupport.entityListToData(${listvar}), SdkTestSupport.om(${rid(entity)} -> ${refDataVar}.get(${rid(entity)})))
246
247
  rep.check("${ENTLOWER}.list.exists", !Struct.isempty(${listvar}Found), "expected to find created entity in list")
247
248
  `)
248
249
  } else if ('ItemNotExists' === validator.apply && hasRefData && hasDataId) {
249
250
  Content(` val ${listvar}NotFound = Struct.select(
250
- SdkTestSupport.entityListToData(${listvar}), SdkTestSupport.om("id" -> ${refDataVar}.get("id")))
251
+ SdkTestSupport.entityListToData(${listvar}), SdkTestSupport.om(${rid(entity)} -> ${refDataVar}.get(${rid(entity)})))
251
252
  rep.check("${ENTLOWER}.list.notexists", Struct.isempty(${listvar}NotFound), "expected removed entity to not be in list")
252
253
  `)
253
254
  }
@@ -280,7 +281,7 @@ const generateUpdate: OpGen = (ctx, step, index) => {
280
281
  Content(` val ${datavar}Up = new LinkedHashMap[String, Object]()
281
282
  `)
282
283
  if (hasDataId) {
283
- Content(` ${datavar}Up.put("id", ${srcdatavar}.get("id"))
284
+ Content(` ${datavar}Up.put("id", ${srcdatavar}.get(${rid(entity)}))
284
285
  `)
285
286
  }
286
287
 
@@ -312,7 +313,7 @@ const generateUpdate: OpGen = (ctx, step, index) => {
312
313
  rep.check("${ENTLOWER}.update.map", ${resdatavar} != null, "expected update result to be a map")
313
314
  `)
314
315
  if (hasDataId) {
315
- Content(` rep.eq("${ENTLOWER}.update.id", ${datavar}Up.get("id"), ${resdatavar}.get("id"))
316
+ Content(` rep.eq("${ENTLOWER}.update.id", ${datavar}Up.get("id"), ${resdatavar}.get(${rid(entity)}))
316
317
  `)
317
318
  }
318
319
  if (hasMark) {
@@ -363,11 +364,11 @@ const generateLoad: OpGen = (ctx, step, index) => {
363
364
  Content(` val ${matchvar} = new LinkedHashMap[String, Object]()
364
365
  `)
365
366
  if (hasDataId) {
366
- Content(` ${matchvar}.put("id", ${srcdatavar}.get("id"))
367
+ Content(` ${matchvar}.put("id", ${srcdatavar}.get(${rid(entity)}))
367
368
  ${loadMatch(entity, step, matchvar, srcdatavar)} val ${datavar}Loaded = ${entvar}.load(${matchvar}, null)
368
369
  val ${datavar}LoadResult = Helpers.toMapAny(${datavar}Loaded match { case e: SdkEntity => e.data(); case o => o })
369
370
  rep.check("${ENTLOWER}.load.map", ${datavar}LoadResult != null, "expected load result to be a map")
370
- rep.eq("${ENTLOWER}.load.id", ${srcdatavar}.get("id"), ${datavar}LoadResult.get("id"))
371
+ rep.eq("${ENTLOWER}.load.id", ${srcdatavar}.get(${rid(entity)}), ${datavar}LoadResult.get(${rid(entity)}))
371
372
  `)
372
373
  } else {
373
374
  Content(`${loadMatch(entity, step, matchvar, srcdatavar)} val ${datavar}Loaded = ${entvar}.load(${matchvar}, null)
@@ -401,12 +402,38 @@ const generateRemove: OpGen = (ctx, step, index) => {
401
402
  `)
402
403
  }
403
404
  Content(` val ${matchvar} = new LinkedHashMap[String, Object]()
404
- ${matchvar}.put("id", ${srcdatavar}.get("id"))
405
+ ${matchvar}.put("id", ${srcdatavar}.get(${rid(entity)}))
405
406
  ${parentMatch(step, matchvar)} ${entvar}.remove(${matchvar}, null)
406
407
  `)
407
408
  }
408
409
 
409
410
 
411
+ // The record field the entity's identity is read from, as a Scala string.
412
+ function rid(entity: any): string {
413
+ return JSON.stringify(entityRecordIdField(entity))
414
+ }
415
+
416
+
417
+ // The fixture keeps each record's key in `id`; an entity keeping its identity
418
+ // in another field reads the key from there too.
419
+ function fixtureIdentity(entity: any): string {
420
+ const field = entityRecordIdField(entity)
421
+ return 'id' === field ? '' : ` entityData.get("existing") match {
422
+ case fixtureEntities: java.util.Map[_, _] => fixtureEntities.get(${JSON.stringify(entity.name)}) match {
423
+ case fixtureRecords: java.util.Map[_, _] => fixtureRecords.values().toArray.foreach {
424
+ case fixtureRec: java.util.Map[_, _] if null != fixtureRec.get("id") =>
425
+ fixtureRec.asInstanceOf[java.util.Map[String, Object]]
426
+ .put(${JSON.stringify(field)}, fixtureRec.get("id").asInstanceOf[Object])
427
+ case _ =>
428
+ }
429
+ case _ =>
430
+ }
431
+ case _ =>
432
+ }
433
+ `
434
+ }
435
+
436
+
410
437
  // A child's route names its parents, and an entity no earlier step has
411
438
  // filled knows none of them, so the call itself gives each parent id.
412
439
  function parentMatch(step: any, matchvar: string): string {
@@ -24,6 +24,7 @@ import {
24
24
  jsOptProp, envName, envToken, liveStrict, liveStrictNote,
25
25
  jsKey,
26
26
  pointParts,
27
+ pointSlash,
27
28
  pointPlaceholders,
28
29
  pointIsGraphql,
29
30
  hasLiveScenarios,
@@ -34,6 +35,7 @@ import {
34
35
  liveEntity,
35
36
  liveGetOnlyReason, LIVE_GETONLY_ENV,
36
37
  liveDirectGetOnly, liveExcludedLines, liveExcludedSummary,
38
+ liveDirectDiscovery, liveIdKey,
37
39
  } from '@voxgig/sdkgen'
38
40
 
39
41
 
@@ -300,7 +302,7 @@ function generateDirectLoad(model: Model, entity: ModelEntity) {
300
302
  }
301
303
 
302
304
  const allLoadParams = loadPoint.g?.params || []
303
- const loadPath = normalizePathParams(pointParts(loadPoint), allLoadParams, loadPoint.r?.param)
305
+ const loadPath = normalizePathParams(pointParts(loadPoint), allLoadParams, loadPoint.r?.param) + pointSlash(loadPoint)
304
306
 
305
307
  // Some upstream OpenAPI specs declare a parameter as `in: path` even when
306
308
  // that path has no `{name}` placeholder for it. Only path params that
@@ -331,25 +333,13 @@ function generateDirectLoad(model: Model, entity: ModelEntity) {
331
333
  const listPoint = null == listOp?.points ? undefined :
332
334
  primaryPoint(listOp.points, entity.name, 'list')
333
335
  const listParams = listPoint?.g?.params || []
334
- const listPath = listPoint ? normalizePathParams(pointParts(listPoint), listParams, listPoint.r?.param) : ''
335
- const hasList = null != listPoint
336
-
337
- const ancestorParams = loadParams.filter((p: any) => p.n !== 'id')
336
+ const listPath = listPoint ? normalizePathParams(pointParts(listPoint), listParams, listPoint.r?.param) + pointSlash(listPoint) : ''
337
+ const discovery = liveDirectDiscovery(entity, loadParams, listPoint)
338
338
 
339
339
  const paramAsserts = loadParams.map((p: any, i: number) =>
340
340
  ' assert(calls[0].url.includes(\'direct0' + (i + 1) + '\'))\n').join('')
341
341
 
342
- const liveListParams = listParams.map((p: any) => {
343
- const key = p.n === 'id'
344
- ? entity.name + '01'
345
- : p.n.replace(/_id$/, '') + '01'
346
- return { name: p.n, key }
347
- })
348
-
349
- const liveAncestorParams = ancestorParams.map((p: any) => {
350
- const key = p.n.replace(/_id$/, '') + '01'
351
- return { name: p.n, key }
352
- })
342
+ const liveListParams = listParams.map((p: any) => ({ name: p.n, key: liveIdKey(entity.name, p.n) }))
353
343
 
354
344
  const liveQueryPrefix = liveQueryLines ? liveQueryLines + '\n' : ''
355
345
 
@@ -377,19 +367,14 @@ ${liveQueryPrefix}${exampleLines}
377
367
  ${loadParams.map((p: any, i: number) => ` ${jsProp('params', p.n)} = 'direct0${i + 1}'`).join('\n')}
378
368
  }`
379
369
  }
380
- else if (hasList) {
381
- // List-bootstrap pattern picks the load id from a list call's response,
382
- // so the test can succeed without ENTID env var. Ancestor params, if
383
- // any, still need ENTID overrides because the list call itself can need
384
- // them embedded.
370
+ else if (null != discovery) {
371
+ const liveAncestorParams = loadParams.filter((p: any) => p.n !== discovery.param)
372
+ .map((p: any) => ({ name: p.n, key: liveIdKey(entity.name, p.n) }))
385
373
  liveIdKeys = [...new Set([...liveListParams, ...liveAncestorParams].map((lp: any) => lp.key))]
386
374
  const listParamLines = liveListParams.map((lp: any) =>
387
375
  ` ${lp.name}: setup.idmap['${lp.key}'],`).join('\n')
388
376
  const ancestorParamLines = liveAncestorParams.map((lp: any) =>
389
377
  ` ${jsProp('params', lp.name)} = setup.idmap['${lp.key}']`).join('\n')
390
- const idParamName = loadParams.find((p: any) => p.n === 'id')
391
- ? 'id'
392
- : (loadParams[0]?.n ?? 'id')
393
378
 
394
379
  liveParamsBlock = ` if (setup.live) {
395
380
  ${liveQueryPrefix} const listResult: any = await client.direct({
@@ -409,21 +394,19 @@ ${listParamLines}
409
394
  if (0 === listArr.length) {
410
395
  return void liveEmpty(t, 'The account has no ${entity.name} record to load')
411
396
  }
412
- const candidateId = ${jsOptProp('listArr[0]', idParamName)} ?? listArr[0]?.id
397
+ const candidateId = ${jsOptProp('listArr[0]', discovery.field)}
413
398
  if (null == candidateId) {
414
399
  return void liveMiss(t, LIVE_STRICT, 'Live load blocked: discovery returned no usable identity')
415
400
  }
416
- ${jsProp('params', idParamName)} = candidateId
401
+ ${jsProp('params', discovery.param)} = candidateId
417
402
  ${ancestorParamLines}
418
403
  } else {
419
404
  ${loadParams.map((p: any, i: number) => ` ${jsProp('params', p.n)} = 'direct0${i + 1}'`).join('\n')}
420
405
  }`
421
406
  } else if (hasLiveQuery || loadParams.length > 0) {
422
- // With no examples and no list to discover from, the ids come from the
423
- // *_ENTID variable; without them the test is blocked.
424
- const liveLoadParams = loadParams.map((p: any) => ({
425
- name: p.n, key: p.n === 'id' ? entity.name + '01' : p.n.replace(/_id$/, '') + '01',
426
- }))
407
+ // A path parameter no listed record gives comes from *_ENTID and the
408
+ // examples merged into it; without them the test is blocked.
409
+ const liveLoadParams = loadParams.map((p: any) => ({ name: p.n, key: liveIdKey(entity.name, p.n) }))
427
410
  liveIdKeys = liveLoadParams.map((lp: any) => lp.key)
428
411
  liveParamsBlock = ` if (setup.live) {
429
412
  ${liveQueryPrefix}${liveLoadParams.map((lp: any) =>
@@ -488,7 +471,7 @@ function generateDirectList(model: Model, entity: ModelEntity) {
488
471
  }
489
472
 
490
473
  const listParams = listPoint.g?.params || []
491
- const listPath = normalizePathParams(pointParts(listPoint), listParams, listPoint.r?.param)
474
+ const listPath = normalizePathParams(pointParts(listPoint), listParams, listPoint.r?.param) + pointSlash(listPoint)
492
475
 
493
476
  const liveQueryLines = liveQueryLinesTs(listPoint)
494
477
 
@@ -36,19 +36,20 @@ import {
36
36
  serverVarEnv,
37
37
  serverVariables,
38
38
  isHttpBasicAuth,
39
- entityDataIdField, envName, envToken,
39
+ entityDataIdField, entityRecordIdField, envName, envToken,
40
40
  jsKey,
41
41
  jsProp,
42
42
  hasLiveScenarios,
43
43
  liveStrict,
44
44
  liveStrictNote,
45
45
  liveEntity,
46
- liveGetOnly,
46
+ liveGates,
47
47
  liveFlowRoutes,
48
48
  flowLoadRoute,
49
49
  flowLoadReadsRecord,
50
50
  LIVE_GETONLY_ENV,
51
51
  } from '@voxgig/sdkgen'
52
+ import type { LiveGate } from '@voxgig/sdkgen'
52
53
 
53
54
 
54
55
  import {
@@ -56,11 +57,16 @@ import {
56
57
  } from './utility_ts'
57
58
 
58
59
 
59
- // The steps a GET-only live run leaves out, for the live harness.
60
- function getOnlyArg(entity: any, flow: any): string {
61
- const plan = liveGetOnly(entity, flow)
62
- return null == plan ? '' : `, 'TRUE' === process.env.${LIVE_GETONLY_ENV} ? ${JSON.stringify(
63
- Object.fromEntries(plan.excluded.map(({ id, reason }) => [id, reason])))} : {}`
60
+ // The steps a live run leaves out, for the live harness: a GET-only run's
61
+ // when the guard is set, else those any live run leaves out.
62
+ function excludedArg(entity: any, flow: any): string {
63
+ const gates = liveGates(entity, flow)
64
+ const getOnly = gates.find((gate) => gate.getOnly)
65
+ const any = gates.find((gate) => !gate.getOnly)
66
+ const map = (gate?: LiveGate) => JSON.stringify(
67
+ Object.fromEntries((gate?.plan.excluded || []).map(({ id, reason }) => [id, reason])))
68
+ return null != getOnly ? `, 'TRUE' === process.env.${LIVE_GETONLY_ENV} ? ${map(getOnly)} : ${map(any)}` :
69
+ 0 < (any?.plan.excluded.length || 0) ? ', ' + map(any) : ''
64
70
  }
65
71
 
66
72
 
@@ -161,7 +167,7 @@ function basicSetup(extra?: any) {
161
167
 
162
168
  // TODO: need a xlang JSON parse utility in voxgig/struct with better error msgs
163
169
  const entityData = JSON.parse(entityDataSource)
164
-
170
+ ${fixtureIdentity(entity)}
165
171
  options.entity = entityData.existing
166
172
 
167
173
  let client = ${model.Name}SDK.test(options, extra)
@@ -254,7 +260,7 @@ function basicSetup(extra?: any) {
254
260
  ${hasLiveScenarios(model) ? `if (live) { t.skip('Covered by live operation scenarios'); return }` : ''}
255
261
  const setup = basicSetup()
256
262
  if (setup.live) {
257
- return runLiveEntity(setup, ${JSON.stringify(liveEntity(ctx$, entity))}, ${JSON.stringify(liveFlowRoutes(entity, basicflow))}, '${nom(entity, 'Name')}', ${JSON.stringify(liveFacts)}, { strict: LIVE_STRICT, t }${getOnlyArg(entity, basicflow)})
263
+ return runLiveEntity(setup, ${JSON.stringify(liveEntity(ctx$, entity))}, ${JSON.stringify(liveFlowRoutes(entity, basicflow))}, '${nom(entity, 'Name')}', ${JSON.stringify(liveFacts)}, { strict: LIVE_STRICT, t }${excludedArg(entity, basicflow)})
258
264
  }
259
265
  const client = setup.client
260
266
  const struct = setup.struct
@@ -343,7 +349,7 @@ const generateCreate: OpGen = (ctx, step, index) => {
343
349
  ${datavar} = (await ${entvar}.create(${datavar})).data()
344
350
  `)
345
351
  if (hasEntIdC) {
346
- Content(` assert(null != ${datavar}.id)
352
+ Content(` assert(null != ${rid(entity, datavar)})
347
353
  `)
348
354
  }
349
355
  else {
@@ -392,12 +398,12 @@ const generateList: OpGen = (ctx, step, index) => {
392
398
 
393
399
  if ('ItemExists' === validator.apply && hasRefData && hasDataId) {
394
400
  Content(`
395
- assert(!isempty(select(${listvar}, { id: ${validRef}_data.id })))
401
+ assert(!isempty(select(${listvar}, { ${jsKey(entityRecordIdField(entity))}: ${rid(entity, validRef + '_data')} })))
396
402
  `)
397
403
  }
398
404
  else if ('ItemNotExists' === validator.apply && hasRefData && hasDataId) {
399
405
  Content(`
400
- assert(isempty(select(${listvar}, { id: ${validRef}_data.id })))
406
+ assert(isempty(select(${listvar}, { ${jsKey(entityRecordIdField(entity))}: ${rid(entity, validRef + '_data')} })))
401
407
  `)
402
408
  }
403
409
  }
@@ -429,7 +435,7 @@ const generateUpdate: OpGen = (ctx, step, index) => {
429
435
  Content(` const ${datavar}: any = {}
430
436
  `)
431
437
  if (hasEntIdU) {
432
- Content(` ${datavar}.id = ${srcdatavar}.id
438
+ Content(` ${datavar}.id = ${rid(entity, srcdatavar)}
433
439
  `)
434
440
  }
435
441
 
@@ -459,7 +465,7 @@ const generateUpdate: OpGen = (ctx, step, index) => {
459
465
  const ${resdatavar} = (await ${entvar}.update(${datavar})).data()
460
466
  `)
461
467
  if (hasEntIdU) {
462
- Content(` assert(${resdatavar}.id === ${datavar}.id)
468
+ Content(` assert(${rid(entity, resdatavar)} === ${datavar}.id)
463
469
  `)
464
470
  }
465
471
  else {
@@ -536,7 +542,7 @@ const generateLoad: OpGen = (ctx, step, index) => {
536
542
  Content(` const ${matchvar}: any = {}
537
543
  `)
538
544
  if (hasEntId) {
539
- Content(` ${matchvar}.id = ${srcdatavar}.id
545
+ Content(` ${matchvar}.id = ${rid(entity, srcdatavar)}
540
546
  `)
541
547
  loadMatch(entity, step, matchvar, srcdatavar)
542
548
  }
@@ -545,7 +551,7 @@ const generateLoad: OpGen = (ctx, step, index) => {
545
551
  }
546
552
  if (hasEntId) {
547
553
  Content(` const ${datavar} = (await ${entvar}.load(${matchvar})).data()
548
- assert(${datavar}.id === ${srcdatavar}.id)
554
+ assert(${rid(entity, datavar)} === ${rid(entity, srcdatavar)})
549
555
  `)
550
556
  }
551
557
  else {
@@ -585,7 +591,7 @@ const generateRemove: OpGen = (ctx, step, index) => {
585
591
  // Always match the prior-created entity by id. The mock test feature
586
592
  // removes the first match in entmap, so without a specific id the
587
593
  // result depends on hash-sort order and flakes (see cheapshark).
588
- Content(` const ${matchvar}: any = { id: ${srcdatavar}.id }
594
+ Content(` const ${matchvar}: any = { id: ${rid(entity, srcdatavar)} }
589
595
  `)
590
596
  parentMatch(step, matchvar)
591
597
  Content(` await ${entvar}.remove(${matchvar})
@@ -593,6 +599,24 @@ const generateRemove: OpGen = (ctx, step, index) => {
593
599
  }
594
600
 
595
601
 
602
+ // The record field the entity's identity is read from, on a record.
603
+ function rid(entity: any, record: string): string {
604
+ return jsProp(record, entityRecordIdField(entity))
605
+ }
606
+
607
+
608
+ // The fixture keeps each record's key in `id`; an entity keeping its identity
609
+ // in another field reads the key from there too.
610
+ function fixtureIdentity(entity: any): string {
611
+ const field = entityRecordIdField(entity)
612
+ return 'id' === field ? '' : `
613
+ for (const rec of Object.values(entityData.existing?.[${JSON.stringify(entity.name)}] ?? {}) as any[]) {
614
+ if (null != rec?.id) ${jsProp('rec', field)} = rec.id
615
+ }
616
+ `
617
+ }
618
+
619
+
596
620
  // A child's route names its parents, and an entity no earlier step has
597
621
  // filled knows none of them, so the call itself gives each parent id.
598
622
  function parentMatch(step: any, matchvar: string) {
@@ -333,7 +333,7 @@ voxgig_value* utility_fetch(Utility* u, Context* ctx, const char* url,
333
333
  voxgig_value* fetchdef, PNError** err);
334
334
 
335
335
  // ===========================================================================
336
- // Entity (vtable; mirrors core/types.rs Entity + ProjectNameEntity)
336
+ // Entity (vtable; mirrors core/types.rs Entity + ProjectNameEntityBase)
337
337
  // ===========================================================================
338
338
 
339
339
  // Every operation resolves to the ENTITY, not the raw data. `list` resolves
@@ -356,7 +356,7 @@ typedef struct EntityVT {
356
356
  void (*mark_deleted)(Entity*);
357
357
  bool (*deleted)(Entity*);
358
358
 
359
- // CRUD ops (ProjectNameEntity). On error set *err and return NULL.
359
+ // CRUD ops (ProjectNameEntityBase). On error set *err and return NULL.
360
360
  Entity* (*load)(Entity*, voxgig_value* reqmatch, voxgig_value* ctrl, PNError** err);
361
361
  // Returns a NULL-terminated Entity* array (never NULL on success).
362
362
  Entity** (*list)(Entity*, voxgig_value* reqmatch, voxgig_value* ctrl, PNError** err);
@@ -122,6 +122,20 @@ static void answer(int c) {
122
122
  return;
123
123
  }
124
124
 
125
+ // A Django route answers its slashless form with a relative Location.
126
+ if (0 == strcmp(target, "/redirect/r1")) {
127
+ say(c, "HTTP/1.1 301 Moved Permanently\r\nLocation: /redirect/r1/\r\nContent-Length: 0\r\n\r\n");
128
+ return;
129
+ }
130
+ if (0 == strcmp(target, "/redirect/r1/")) {
131
+ say(c, "HTTP/1.1 308 Permanent Redirect\r\nLocation: done\r\nContent-Length: 0\r\n\r\n");
132
+ return;
133
+ }
134
+ if (0 == strcmp(target, "/redirect/r1/done")) {
135
+ reply(c, "200 OK", "application/json", "{\"id\":\"r1\"}");
136
+ return;
137
+ }
138
+
125
139
  // The last segment names the case, whatever prefix the API's config adds.
126
140
  char path[256];
127
141
  size_t plen = strcspn(target, "?");
@@ -390,6 +404,25 @@ int main(void) {
390
404
  CHECK(NULL == err && v_eq(getp(direct, "ok"), v_bool(true)), "a direct request goes live");
391
405
  CHECK_STR_EQ(get_str(getp(direct, "data"), "framing"), "length", "and reads the response");
392
406
 
407
+ // The fetcher follows each hop, relative Location and all, and answers a
408
+ // "manual" fetch with the 3xx.
409
+ Utility* util = sdk_get_utility(sdk);
410
+ CtxSpec cs;
411
+ memset(&cs, 0, sizeof(cs));
412
+ cs.opname = "load";
413
+ cs.client = sdk;
414
+ cs.utility = util;
415
+ Context* ctx = make_context_util(cs, NULL);
416
+ snprintf(url, sizeof(url), "%s/redirect/r1", base);
417
+ err = NULL;
418
+ res = utility_fetch(util, ctx, url, cmap(2, "method", v_str("GET"), "headers", v_map()), &err);
419
+ CHECK(NULL == err && 200 == to_int(getp(res, "status")), "a redirect is followed, hop by hop");
420
+ CHECK_STR_EQ(get_str(json_of(res), "id"), "r1", "to the route its Location names");
421
+ err = NULL;
422
+ res = utility_fetch(util, ctx, url, cmap(3, "method", v_str("GET"), "headers", v_map(),
423
+ "redirect", v_str("manual")), &err);
424
+ CHECK(NULL == err && 301 == to_int(getp(res, "status")), "a manual fetch is answered by the 301");
425
+
393
426
  kill(server, SIGKILL);
394
427
  waitpid(server, NULL, 0);
395
428
  TEST_SUMMARY("transport");
@@ -36,6 +36,156 @@ static PNError* getonly_refusal(Context* ctx, const char* fullurl, voxgig_value*
36
36
  return context_make_error(ctx, "fetch_getonly_block", buf);
37
37
  }
38
38
 
39
+ #define REDIRECT_MAX 5
40
+
41
+ static int same_text(const char* a, const char* b) {
42
+ for (; '\0' != *a && tolower((unsigned char)*a) == tolower((unsigned char)*b); a++, b++) {}
43
+ return tolower((unsigned char)*a) == tolower((unsigned char)*b);
44
+ }
45
+
46
+ // The Location resolved against the URL that answered with it (RFC 3986
47
+ // 5.2), or NULL when the base has no scheme. The caller frees it.
48
+ static char* resolve_location(const char* base, const char* raw) {
49
+ size_t n = 0, rlen = strlen(raw);
50
+ char* loc = (char*)malloc(rlen + 1);
51
+ for (size_t i = 0; i < rlen && '#' != raw[i]; i++) {
52
+ if (!isspace((unsigned char)raw[i])) loc[n++] = raw[i];
53
+ }
54
+ loc[n] = '\0';
55
+ size_t s = 0;
56
+ while (isalnum((unsigned char)loc[s]) || (0 < s && '\0' != loc[s] && NULL != strchr("+-.", loc[s]))) {
57
+ s++;
58
+ }
59
+ if (0 < s && isalpha((unsigned char)loc[0]) && ':' == loc[s]) return loc;
60
+
61
+ const char* sep = strstr(base, "://");
62
+ if (NULL == sep) {
63
+ free(loc);
64
+ return NULL;
65
+ }
66
+ const char* auth = sep + 3;
67
+ const char* path = auth + strcspn(auth, "/?#");
68
+ size_t plen = strcspn(path, "?#");
69
+ const char* query = '?' == path[plen] ? path + plen : "";
70
+ size_t qlen = strcspn(query, "#");
71
+ size_t cap = strlen(base) + n + 4;
72
+ char* out = (char*)malloc(cap);
73
+ if ('/' == loc[0] && '/' == loc[1]) {
74
+ snprintf(out, cap, "%.*s:%s", (int)(sep - base), base, loc);
75
+ free(loc);
76
+ return out;
77
+ }
78
+
79
+ const char* lq = strchr(loc, '?');
80
+ size_t lplen = NULL == lq ? n : (size_t)(lq - loc);
81
+ char* merged = (char*)malloc(cap);
82
+ if (0 == lplen) {
83
+ snprintf(merged, cap, "%.*s", 0 == plen ? 1 : (int)plen, 0 == plen ? "/" : path);
84
+ if (NULL == lq) lq = query;
85
+ } else if ('/' == loc[0]) {
86
+ snprintf(merged, cap, "%.*s", (int)lplen, loc);
87
+ } else {
88
+ size_t dir = plen;
89
+ while (0 < dir && '/' != path[dir - 1]) dir--;
90
+ snprintf(merged, cap, "%.*s%.*s", 0 == dir ? 1 : (int)dir, 0 == dir ? "/" : path,
91
+ (int)lplen, loc);
92
+ }
93
+ if (NULL == lq) lq = "";
94
+
95
+ size_t mlen = strlen(merged), count = 0;
96
+ const char** segs = (const char**)malloc(sizeof(char*) * (mlen + 2));
97
+ size_t* lens = (size_t*)malloc(sizeof(size_t) * (mlen + 2));
98
+ for (const char* p = merged;; ) {
99
+ size_t len = strcspn(p, "/");
100
+ if (2 == len && 0 == strncmp(p, "..", 2)) {
101
+ if (1 < count) count--;
102
+ } else if (!(1 == len && '.' == p[0])) {
103
+ segs[count] = p;
104
+ lens[count++] = len;
105
+ }
106
+ if ('\0' == p[len]) {
107
+ if ((1 == len && '.' == p[0]) || (2 == len && 0 == strncmp(p, "..", 2))) {
108
+ segs[count] = p + len;
109
+ lens[count++] = 0;
110
+ }
111
+ break;
112
+ }
113
+ p += len + 1;
114
+ }
115
+ size_t o = (size_t)snprintf(out, cap, "%.*s", (int)(path - base), base);
116
+ for (size_t i = 0; i < count; i++) {
117
+ o += (size_t)snprintf(out + o, cap - o, "%s%.*s", 0 == i ? "" : "/", (int)lens[i], segs[i]);
118
+ }
119
+ snprintf(out + o, cap - o, "%.*s", (int)(lq == query ? qlen : strlen(lq)), lq);
120
+ free(segs);
121
+ free(lens);
122
+ free(merged);
123
+ free(loc);
124
+ return out;
125
+ }
126
+
127
+ static int same_origin(const char* a, const char* b) {
128
+ const char* as = strstr(a, "://");
129
+ const char* bs = strstr(b, "://");
130
+ if (NULL == as || NULL == bs) return 0;
131
+ size_t alen = (size_t)(as - a) + 3 + strcspn(as + 3, "/?#");
132
+ size_t blen = (size_t)(bs - b) + 3 + strcspn(bs + 3, "/?#");
133
+ if (alen != blen) return 0;
134
+ for (size_t i = 0; i < alen; i++) {
135
+ if (tolower((unsigned char)a[i]) != tolower((unsigned char)b[i])) return 0;
136
+ }
137
+ return 1;
138
+ }
139
+
140
+ // The request as another origin may see it: without its credentials.
141
+ static voxgig_value* without_credentials(voxgig_value* fetchdef) {
142
+ voxgig_value* copy = voxgig_clone(fetchdef);
143
+ voxgig_value* headers = getp(copy, "headers");
144
+ if (voxgig_is_map(headers)) {
145
+ voxgig_map* hm = voxgig_as_map(headers);
146
+ voxgig_value* kept = cmap(0);
147
+ for (size_t i = 0; i < hm->len; i++) {
148
+ const char* name = hm->entries[i].key;
149
+ if (!same_text(name, "authorization") && !same_text(name, "cookie") &&
150
+ !same_text(name, "proxy-authorization")) {
151
+ setp(kept, name, hm->entries[i].value);
152
+ }
153
+ }
154
+ setp(copy, "headers", kept);
155
+ }
156
+ return copy;
157
+ }
158
+
159
+ // The default transport follows no redirect. A GET or HEAD follows one here,
160
+ // unless the fetch definition says "manual", each hop passing the GET-only
161
+ // guard first; past REDIRECT_MAX hops the last 3xx is the answer. Another
162
+ // origin is not sent the request's credentials.
163
+ static voxgig_value* follow_redirects(Context* ctx, const char* fullurl,
164
+ voxgig_value* fetchdef, PNError** err) {
165
+ const char* method = get_str(fetchdef, "method");
166
+ const char* redirect = get_str(fetchdef, "redirect");
167
+ int follow = (NULL == method || '\0' == method[0] || same_text(method, "GET") ||
168
+ same_text(method, "HEAD")) && !(NULL != redirect && 0 == strcmp(redirect, "manual"));
169
+ char* url = (char*)malloc(strlen(fullurl) + 1);
170
+ strcpy(url, fullurl);
171
+ for (int hops = 0;; hops++) {
172
+ *err = getonly_refusal(ctx, url, fetchdef);
173
+ voxgig_value* res = NULL != *err ? NULL : http_fetch(ctx, url, fetchdef, err);
174
+ const char* location = NULL == res ? NULL : get_str(getp(res, "headers"), "location");
175
+ int64_t status = NULL == res ? -1 : to_int(getp(res, "status"));
176
+ int moved = 301 == status || 302 == status || 303 == status || 307 == status || 308 == status;
177
+ char* next = follow && moved && NULL != location && hops < REDIRECT_MAX
178
+ ? resolve_location(url, location) : NULL;
179
+ if (NULL == next) {
180
+ free(url);
181
+ return res;
182
+ }
183
+ if (!same_origin(url, next)) fetchdef = without_credentials(fetchdef);
184
+ free(url);
185
+ url = next;
186
+ }
187
+ }
188
+
39
189
  voxgig_value* fetcher_util(Fetcher* self, Context* ctx, const char* fullurl,
40
190
  voxgig_value* fetchdef, PNError** err) {
41
191
  (void)self;
@@ -73,8 +223,7 @@ voxgig_value* fetcher_util(Fetcher* self, Context* ctx, const char* fullurl,
73
223
  voxgig_value* sys_fetch = getpath2(options, "system", "fetch");
74
224
 
75
225
  if (v_is_noval(sys_fetch) || v_is_null(sys_fetch)) {
76
- *err = getonly_refusal(ctx, fullurl, fetchdef);
77
- return NULL != *err ? NULL : http_fetch(ctx, fullurl, fetchdef, err);
226
+ return follow_redirects(ctx, fullurl, fetchdef, err);
78
227
  }
79
228
 
80
229
  if (voxgig_is_func(sys_fetch)) {
@@ -58,13 +58,15 @@ char* make_url_util(Context* ctx, PNError** err) {
58
58
  char* url = str_append(NULL, joined ? joined : "");
59
59
  free(joined);
60
60
 
61
- // A route the definition ends with a slash keeps it, for a Django REST server,
62
- // and a host with no path takes /, or luasocket reads a query as the host.
61
+ // A route ending in a slash keeps it, as defined or as passed to direct(), for
62
+ // Django, and a host with no path takes /, or luasocket reads a query as the host.
63
63
  voxgig_value* orig = getp(ctx->point, "orig");
64
- if (voxgig_is_string(orig) && (NULL == spec->suffix || '\0' == spec->suffix[0])) {
65
- const char* o = voxgig_as_string(orig);
66
- size_t olen = strlen(o), ulen = strlen(url);
67
- if (0 < olen && '/' == o[olen - 1] && (0 == ulen || '/' != url[ulen - 1])) {
64
+ if (NULL == spec->suffix || '\0' == spec->suffix[0]) {
65
+ const char* o = voxgig_is_string(orig) ? voxgig_as_string(orig) : "";
66
+ const char* p = NULL == spec->path ? "" : spec->path;
67
+ size_t olen = strlen(o), plen = strlen(p), ulen = strlen(url);
68
+ if (((0 < olen && '/' == o[olen - 1]) || (0 < plen && '/' == p[plen - 1])) &&
69
+ (0 == ulen || '/' != url[ulen - 1])) {
68
70
  url = str_append(url, "/");
69
71
  }
70
72
  }