fixed issue in org. indices address

fixed issue in org. indices address

import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(:
   The query will be executed against the root element of the CSD document.

   The dynamic context of this query has $careServicesRequest set to contain any of the search
   and limit paramaters as sent by the Service Finder
:)
  let $orgs0 :=
    if (exists($careServicesRequest/id/@entityID)) then
      csd_bl:filter_by_primary_id(/CSD/organizationDirectory/*,$careServicesRequest/id)
    else (/CSD/organizationDirectory/*)
  let $orgs1:=
      for $organization in  $orgs0
      return
      <organization entityID="{$organization/@entityID}">
	  {
	    for $address in  $organization/address
	    return <address type="{$address/@type}"/>
	  }
      </organization>

    return csd_bl:wrap_organizations($orgs1)

import module namespace csd_bl = "https://github.com/openhie/openinfoman/csd_bl";
declare default element  namespace   "urn:ihe:iti:csd:2013";
declare variable $careServicesRequest as item() external;

(:
   The query will be executed against the root element of the CSD document.

   The dynamic context of this query has $careServicesRequest set to contain any of the search
   and limit paramaters as sent by the Service Finder
:)
  let $orgs0 :=
    if (exists($careServicesRequest/id/@entityID)) then
      csd_bl:filter_by_primary_id(/CSD/organizationDirectory/*,$careServicesRequest/id)
    else (/CSD/organizationDirectory/*)
  let $orgs1:=
      for $organization in  $orgs0
      return
      <organization entityID="{$organization/@entityID}">
	  {
	    for $address in  $organization/address
	    return <address type="{$address/@type}"/>
	  }
    </provider>

    return csd_bl:wrap_organizations($orgs1)


[ignore] function docs: controller failed to load stylesheet after recent changes to URL rewriting.

svn path=/trunk/eXist/; revision=15769

xquery version "1.0";

(: $Id$ :)

(:~
	Controller XQuery for the RESTful function docs application.

	Demonstrates how to use in URL Rewriting for RESTful applications, e.g.:
	   - functions/ forwards transparently to functions/functions.xql
	   - functions/xmldb displays the docs for the xmldb module
	   - functions/xmldb/login displays the docs for the xmldb:login() module
	   - functions/xmldb:login() redirects to functions/xmldb/login
	       in order to display the docs for the xmldb:login() module

    Un-comment logging functions and monitor EXIST_HOME/webapp/WEB-INF/logs/exist.log
    to follow the construction of these parameters.
:)

import module namespace request="http://exist-db.org/xquery/request";

(: standard variables passed automatically to controller.xql  :)

declare variable $exist:root external;
declare variable $exist:prefix external;
declare variable $exist:controller external;
declare variable $exist:path external;
declare variable $exist:resource external;

(: variables from the HTTP Request module :)
let $url := request:get-url()
let $uri := request:get-uri()
let $context := request:get-context-path()
let $effective-uri := request:get-effective-uri()

(: the default query for this app:)
let $app-default-query := 'functions.xql'

(: used to forward matching requests to the correct 'internal' path to the main query :)
let $internal-path-to-app := concat($exist:controller, '/', $app-default-query)

(: the 'external' path to app to the for use in constructing URLs  :)
let $external-path-to-app := concat($context, $exist:prefix, $exist:controller, '/')

(: prepare the URL parameters for use :)
let $post-query-url-params := subsequence(tokenize($exist:path, '/'), 2)

(: logging to demonstrate how variables are constructed for use in URL Rewriting :)
(:
let $log := util:log("DEBUG", concat("URL Info: request:get-url():           ", $url))
let $log := util:log("DEBUG", concat("URL Info: request:get-uri():           ", $uri))
let $log := util:log("DEBUG", concat("URL Info: request:get-effective-uri(): ", $effective-uri))
let $log := util:log("DEBUG", concat("URL Info: request:get-context-path():  ", $context))

let $log := util:log("DEBUG", concat("URL Info: $exist:root:                 ", $exist:root))
let $log := util:log("DEBUG", concat("URL Info: $exist:prefix:               ", $exist:prefix))
let $log := util:log("DEBUG", concat("URL Info: $exist:controller:           ", $exist:controller))
let $log := util:log("DEBUG", concat("URL Info: $exist:path:                 ", $exist:path))
let $log := util:log("DEBUG", concat("URL Info: $exist:resource:             ", $exist:resource))

let $log := util:log("DEBUG", concat("URL Info: $internal-path-to-app:       ", $internal-path-to-app))
let $log := util:log("DEBUG", concat("URL Info: $external-path-to-app:       ", $external-path-to-app))
:)

return
    (: force trailing slash so relative URLs (e.g. "../sidebar.xml") resolve properly :)
    if ($exist:path eq '') then
        let $newPath := concat($url, '/')
        return
            <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
                <redirect url="{$newPath}"/>
            </dispatch>

	(: make sure the global css, js and image files are resolved :)
    else if (matches($exist:path, '((styles|scripts|resources)/|logo.jpg)')) then
        let $newPath := replace($exist:path, '^.*(((styles|scripts|resources)/|logo).*)$', '/$1')
        return
            <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
    			<forward url="{$newPath}"/>
    			<cache-control cache="yes"/>
    		</dispatch>

    (: catch requests like 'functions/xmldb:login()' and redirect them to 'functions/xmldb/login',
       thereby making it easier to paste in functions :)
    else if (contains($post-query-url-params[1], ':')) then
        let $module := substring-before($post-query-url-params[1], ':')
        let $function := replace(substring-after($post-query-url-params[1], ':'), '\(\)', '')
        let $newPath := string-join(($external-path-to-app, $module, $function), '/')
        return
            <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
                <redirect url="{$newPath}"/>
            </dispatch>

	(: Execute RESTful queries by passing URL parameters to the query :)
    else
        let $module := $post-query-url-params[1]
        let $function := $post-query-url-params[2]

        (: logging to demonstrate the RESTful URL parameters :)
        (:
        let $log := util:log("DEBUG", concat("Functions App module:                  ", $module))
        let $log := util:log("DEBUG", concat("Functions App function:                ", $function))
        :)

        return
        (: handle the special case of "xpath-functions", which this app redirects to "fn" :)
        if ($module eq 'xpath-functions') then
            let $newPath := string-join(($external-path-to-app, 'fn', $function), '/')
            return
                <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
                    <redirect url="{$newPath}"/>
                </dispatch>
        else
            <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
    			<forward url="{$internal-path-to-app}">
        			<add-parameter name="basepath" value="{$external-path-to-app}"/>
            	    <add-parameter name="module" value="{$module}"/>,
            	    <add-parameter name="function" value="{$function}"/>
            	    <!-- query results are passed to XSLT servlet via request attribute -->
              		<set-attribute name="xquery.attribute" value="model"/>
    			</forward>
          		<view>
              	    <!-- Apply db2xhtml stylesheet -->
          			<forward servlet="XSLTServlet">
          			    <set-attribute name="xslt.base" value="{$exist:controller}"/>
          				<set-attribute name="xslt.input" value="model"/>
          				<set-attribute name="xslt.root" value="{request:get-context-path()}{$exist:prefix}"/>
          				<set-attribute name="xslt.stylesheet" value="{$exist:root}/stylesheets/db2xhtml.xsl"/>
          				<set-attribute name="xslt.output.media-type" value="text/html"/>
          				<set-attribute name="xslt.output.doctype-public" value="-//W3C//DTD XHTML 1.0 Transitional//EN"/>
          				<set-attribute name="xslt.output.doctype-system" value="resources/xhtml1-transitional.dtd"/>
          			</forward>
          		</view>
    		</dispatch>

xquery version "1.0";

(: $Id$ :)

(:~
	Controller XQuery for the RESTful function docs application.

	Demonstrates how to use in URL Rewriting for RESTful applications, e.g.:
	   - functions/ forwards transparently to functions/functions.xql
	   - functions/xmldb displays the docs for the xmldb module
	   - functions/xmldb/login displays the docs for the xmldb:login() module
	   - functions/xmldb:login() redirects to functions/xmldb/login
	       in order to display the docs for the xmldb:login() module

    Un-comment logging functions and monitor EXIST_HOME/webapp/WEB-INF/logs/exist.log
    to follow the construction of these parameters.
:)

import module namespace request="http://exist-db.org/xquery/request";

(: standard variables passed automatically to controller.xql  :)

declare variable $exist:root external;
declare variable $exist:prefix external;
declare variable $exist:controller external;
declare variable $exist:path external;
declare variable $exist:resource external;

(: variables from the HTTP Request module :)
let $url := request:get-url()
let $uri := request:get-uri()
let $context := request:get-context-path()
let $effective-uri := request:get-effective-uri()

(: the default query for this app:)
let $app-default-query := 'functions.xql'

(: used to forward matching requests to the correct 'internal' path to the main query :)
let $internal-path-to-app := concat($exist:controller, '/', $app-default-query)

(: the 'external' path to app to the for use in constructing URLs  :)
let $external-path-to-app := concat($context, $exist:prefix, $exist:controller, '/')

(: prepare the URL parameters for use :)
let $post-query-url-params := subsequence(tokenize($exist:path, '/'), 2)

(: logging to demonstrate how variables are constructed for use in URL Rewriting :)
(:
let $log := util:log("DEBUG", concat("URL Info: request:get-url():           ", $url))
let $log := util:log("DEBUG", concat("URL Info: request:get-uri():           ", $uri))
let $log := util:log("DEBUG", concat("URL Info: request:get-effective-uri(): ", $effective-uri))
let $log := util:log("DEBUG", concat("URL Info: request:get-context-path():  ", $context))

let $log := util:log("DEBUG", concat("URL Info: $exist:root:                 ", $exist:root))
let $log := util:log("DEBUG", concat("URL Info: $exist:prefix:               ", $exist:prefix))
let $log := util:log("DEBUG", concat("URL Info: $exist:controller:           ", $exist:controller))
let $log := util:log("DEBUG", concat("URL Info: $exist:path:                 ", $exist:path))
let $log := util:log("DEBUG", concat("URL Info: $exist:resource:             ", $exist:resource))

let $log := util:log("DEBUG", concat("URL Info: $internal-path-to-app:       ", $internal-path-to-app))
let $log := util:log("DEBUG", concat("URL Info: $external-path-to-app:       ", $external-path-to-app))
:)

return
    (: force trailing slash so relative URLs (e.g. "../sidebar.xml") resolve properly :)
    if ($exist:path eq '') then
        let $newPath := concat($url, '/')
        return
            <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
                <redirect url="{$newPath}"/>
            </dispatch>

	(: make sure the global css, js and image files are resolved :)
    else if (matches($exist:path, '((styles|scripts|resources)/|logo.jpg)')) then
        let $newPath := replace($exist:path, '^.*(((styles|scripts|resources)/|logo).*)$', '/$1')
        return
            <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
    			<forward url="{$newPath}"/>
    			<cache-control cache="yes"/>
    		</dispatch>

    (: catch requests like 'functions/xmldb:login()' and redirect them to 'functions/xmldb/login',
       thereby making it easier to paste in functions :)
    else if (contains($post-query-url-params[1], ':')) then
        let $module := substring-before($post-query-url-params[1], ':')
        let $function := replace(substring-after($post-query-url-params[1], ':'), '\(\)', '')
        let $newPath := string-join(($external-path-to-app, $module, $function), '/')
        return
            <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
                <redirect url="{$newPath}"/>
            </dispatch>

	(: Execute RESTful queries by passing URL parameters to the query :)
    else
        let $module := $post-query-url-params[1]
        let $function := $post-query-url-params[2]

        (: logging to demonstrate the RESTful URL parameters :)
        (:
        let $log := util:log("DEBUG", concat("Functions App module:                  ", $module))
        let $log := util:log("DEBUG", concat("Functions App function:                ", $function))
        :)

        return
        (: handle the special case of "xpath-functions", which this app redirects to "fn" :)
        if ($module eq 'xpath-functions') then
            let $newPath := string-join(($external-path-to-app, 'fn', $function), '/')
            return
                <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
                    <redirect url="{$newPath}"/>
                </dispatch>
        else
            <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
    			<forward url="{$internal-path-to-app}">
        			<add-parameter name="basepath" value="{$external-path-to-app}"/>
            	    <add-parameter name="module" value="{$module}"/>,
            	    <add-parameter name="function" value="{$function}"/>
            	    <!-- query results are passed to XSLT servlet via request attribute -->
              		<set-attribute name="xquery.attribute" value="model"/>
    			</forward>
          		<view>
              	    <!-- Apply db2xhtml stylesheet -->
          			<forward servlet="XSLTServlet">
          				<set-attribute name="xslt.input" value="model"/>
          				<set-attribute name="xslt.root" value="{request:get-context-path()}{$exist:prefix}"/>
          				<set-attribute name="xslt.stylesheet" value="{$exist:root}/stylesheets/db2xhtml.xsl"/>
          				<set-attribute name="xslt.output.media-type" value="text/html"/>
          				<set-attribute name="xslt.output.doctype-public" value="-//W3C//DTD XHTML 1.0 Transitional//EN"/>
          				<set-attribute name="xslt.output.doctype-system" value="resources/xhtml1-transitional.dtd"/>
          			</forward>
          		</view>
    		</dispatch>


Remove xdmp:log

Remove xdmp:log

(:
 Copyright 2002-2016 MarkLogic Corporation.  All Rights Reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
:)
xquery version "1.0-ml";

module namespace es-codegen = "http://marklogic.com/entity-services-codegen";

import module namespace esi = "http://marklogic.com/entity-services-impl"
    at "entity-services-impl.xqy";

declare namespace es = "http://marklogic.com/entity-services";
declare namespace tde = "http://marklogic.com/xdmp/tde";

declare function es-codegen:conversion-module-generate(
    $entity-type as map:map
) as document-node()
{
    let $default-base-uri := "http://example.org/"
    let $info := map:get($entity-type, "info")
    let $prefix := map:get($info, "title")
    let $version:= map:get($info, "version")
    let $definitions := map:get($entity-type, "definitions")
    let $base-uri := fn:head((map:get($info, "baseUri"), $default-base-uri))
    let $base-uri :=
            if (fn:matches($base-uri, "[#/]$"))
            then $base-uri
            else concat($base-uri, "#")
    return
document {
<conversion-module>
xquery version "1.0-ml";

(: This module was generated by MarkLogic Entity Services.
 : The source entity type document was {$prefix}-{$version}
 :
 : Modification History:
 :   Generated at timestamp: {fn:current-dateTime()}
 :   Persisted by AUTHOR
 :   Date: DATE
 :)
module namespace {$prefix} = "{$base-uri}{$prefix}-{$version}";

import module namespace es = "http://marklogic.com/entity-services"
    at "/MarkLogic/entity-services/entity-services.xqy";

(: extract-instance-{{entity-type}} Functions
 : The following functions take as input some source document from which to
 : extract values.  Edit each function to create a valid entity instance.
 :)
{ (: iterate over entity types to make extract instance stubs :)
    for $entity-type-key in map:keys(map:get($entity-type, "definitions"))
    return
    <extract-instance>
declare function {$prefix}:extract-instance-{$entity-type-key}(
    $source-node as node()
) as map:map
{{
    let $instance := json:object()
    let $_ := map:put($instance, "$type", "{$entity-type-key}")
    {
    let $this-type := map:get($definitions, $entity-type-key)
    let $properties-map := map:get($this-type, "properties")
    let $properties-keys := map:keys($properties-map)
    for $property-key in map:keys($properties-map)
    let $is-array := map:get(map:get($properties-map, $property-key), "datatype") eq "array"
    let $ref :=
        if ($is-array)
        then map:get(map:get(map:get($properties-map, $property-key), "items"), "$ref")
        else map:get(map:get($properties-map, $property-key), "$ref")
    let $path-to-property := concat("$source-node/", $entity-type-key, "/", $property-key)
    let $value :=
        if (empty($ref))
        then
            concat($path-to-property, "! data(.)")
        else
            if(contains($ref, "#definitions"))
            then
            concat("if (not(",
                    $path-to-property,
                    "/element()))
then ",
                    "data(", $path-to-property, ")",
                    "
else ",
                    $path-to-property,
                    " ! ",
                    $prefix,
                    ":extract-instance-",
                    replace($ref, "#definitions/", ""),
                    "(.)"
                    )
            else
               concat($path-to-property, " ! data(.)")

    return

    concat("let $_ := if (empty( (",
            $value,
            ")))
",
            "         then ()
",
            "         else map:put($instance, '", $property-key, "', ",$value, ")
   "
          )
    }
        return $instance
}};
    </extract-instance>/text()
}

(: instance-to-canonical-xml function
 : Depending on the relationships among your entity types
 : you may wish to modify sections of this function
 : to meet your own purposes.
 :)
declare function {$prefix}:instance-to-canonical-xml(
    $entity-instance as map:map
) as element(es:instance)
{{
    let $title := "{$prefix}"
    let $version := "{$version}"
    let $instance-keys := map:keys($entity-instance)
    let $instance-node :=
        element es:instance {{
            element es:info {{
                element es:title {{ $title }},
                element es:version {{ $version }}
                (: id :)
            }},
            element {{ map:get($entity-instance, "$type") }}  {{
                for $key in $instance-keys
                let $instance-property := map:get($entity-instance, $key)
                where ($key castable as xs:NCName and $key ne "$type")
                return
                    typeswitch ($instance-property)
                    case json:object+
                        return
                            for $prop in $instance-property
                            return element {{ $key }} {{ {$prefix}:instance-to-canonical-xml($prop)/(*[exists(./*)] except es:info) }}
                    case item()+
                        return
                            for $val in $instance-property
                            return element {{ $key }} {{ $val }}
                    case json:array
                        return
                            for $val in json:array-values($instance-property)
                            return element {{ $key }} {{ $val }}
                    default return element {{ $key }} {{ $instance-property }}
            }}
        }}
    return $instance-node
}};

(: instance-to-envelope
 : This function is used to wrap sources and entity instances
 : within the same document
 :)
declare function {$prefix}:instance-to-envelope(
    $entity-instance as map:map
) as text()
{{
    element es:envelope {{
        {$prefix}:instance-to-canonical-xml($entity-instance),
        element es:constrained {{
            map:get($entity-instance, "$sources")
        }}
    }}
}};

(: instance-from-document
 : if you have modified instance-to-envelope
 : you may need also to modify this function
 :)
declare function {$prefix}:instance-from-document(
    $document as document-node()
) as map:map
{{
    let $xml-from-document := {$prefix}:instance-xml-from-document($document)
    let $instance := map:map()
    let $_ := map:put($instance, "key", "val")
    return $instance
}};

declare function {$prefix}:instance-xml-from-document(
    $document as document-node()
) as element()
{{
    $document//es:entity/(* except es:info)[es:info/es:version eq "{$version}"]
}};

declare function {$prefix}:instance-json-from-document(
    $document as document-node()
) as object-node()
{{
    xdmp:to-json( {$prefix}:instance-from-document($document) )
}};
</conversion-module>/text()
}
};

(:
 Copyright 2002-2016 MarkLogic Corporation.  All Rights Reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
:)
xquery version "1.0-ml";

module namespace es-codegen = "http://marklogic.com/entity-services-codegen";

import module namespace esi = "http://marklogic.com/entity-services-impl"
    at "entity-services-impl.xqy";

declare namespace es = "http://marklogic.com/entity-services";
declare namespace tde = "http://marklogic.com/xdmp/tde";

declare function es-codegen:conversion-module-generate(
    $entity-type as map:map
) as document-node()
{
    let $default-base-uri := "http://example.org/"
    let $info := map:get($entity-type, "info")
    let $prefix := map:get($info, "title")
    let $version:= map:get($info, "version")
    let $definitions := map:get($entity-type, "definitions")
    let $base-uri := fn:head((map:get($info, "baseUri"), $default-base-uri))
    let $base-uri :=
            if (fn:matches($base-uri, "[#/]$"))
            then $base-uri
            else concat($base-uri, "#")
    return
document {
<conversion-module>
xquery version "1.0-ml";

(: This module was generated by MarkLogic Entity Services.
 : The source entity type document was {$prefix}-{$version}
 :
 : Modification History:
 :   Generated at timestamp: {fn:current-dateTime()}
 :   Persisted by AUTHOR
 :   Date: DATE
 :)
module namespace {$prefix} = "{$base-uri}{$prefix}-{$version}";

import module namespace es = "http://marklogic.com/entity-services"
    at "/MarkLogic/entity-services/entity-services.xqy";

(: extract-instance-{{entity-type}} Functions
 : The following functions take as input some source document from which to
 : extract values.  Edit each function to create a valid entity instance.
 :)
{ (: iterate over entity types to make extract instance stubs :)
    for $entity-type-key in map:keys(map:get($entity-type, "definitions"))
    return
    <extract-instance>
declare function {$prefix}:extract-instance-{$entity-type-key}(
    $source-node as node()
) as map:map
{{
    let $instance := json:object()
    let $_ := map:put($instance, "$type", "{$entity-type-key}")
    {
    let $this-type := map:get($definitions, $entity-type-key)
    let $properties-map := map:get($this-type, "properties")
    let $properties-keys := map:keys($properties-map)
    for $property-key in map:keys($properties-map)
    let $is-array := map:get(map:get($properties-map, $property-key), "datatype") eq "array"
    let $ref :=
        if ($is-array)
        then map:get(map:get(map:get($properties-map, $property-key), "items"), "$ref")
        else map:get(map:get($properties-map, $property-key), "$ref")
    let $path-to-property := concat("$source-node/", $entity-type-key, "/", $property-key)
    let $value :=
        if (empty($ref))
        then
            concat($path-to-property, "! data(.)")
        else
            if(contains($ref, "#definitions"))
            then
            concat("if (not(",
                    $path-to-property,
                    "/element()))
then ",
                    "data(", $path-to-property, ")",
                    "
else ",
                    $path-to-property,
                    " ! ",
                    $prefix,
                    ":extract-instance-",
                    replace($ref, "#definitions/", ""),
                    "(.)"
                    )
            else
               concat($path-to-property, " ! data(.)")

    let $_ := xdmp:log(("ET", $prefix, $version, "PK", $property-key, "REF", $ref))
    return

    concat("let $_ := if (empty( (",
            $value,
            ")))
",
            "         then ()
",
            "         else map:put($instance, '", $property-key, "', ",$value, ")
   "
          )
    }
        return $instance
}};
    </extract-instance>/text()
}

(: instance-to-canonical-xml function
 : Depending on the relationships among your entity types
 : you may wish to modify sections of this function
 : to meet your own purposes.
 :)
declare function {$prefix}:instance-to-canonical-xml(
    $entity-instance as map:map
) as element(es:instance)
{{
    let $title := "{$prefix}"
    let $version := "{$version}"
    let $instance-keys := map:keys($entity-instance)
    let $instance-node :=
        element es:instance {{
            element es:info {{
                element es:title {{ $title }},
                element es:version {{ $version }}
                (: id :)
            }},
            element {{ map:get($entity-instance, "$type") }}  {{
                for $key in $instance-keys
                let $instance-property := map:get($entity-instance, $key)
                where ($key castable as xs:NCName and $key ne "$type")
                return
                    typeswitch ($instance-property)
                    case json:object+
                        return
                            for $prop in $instance-property
                            return element {{ $key }} {{ {$prefix}:instance-to-canonical-xml($prop)/(*[exists(./*)] except es:info) }}
                    case item()+
                        return
                            for $val in $instance-property
                            return element {{ $key }} {{ $val }}
                    case json:array
                        return
                            for $val in json:array-values($instance-property)
                            return element {{ $key }} {{ $val }}
                    default return element {{ $key }} {{ $instance-property }}
            }}
        }}
    return $instance-node
}};

(: instance-to-envelope
 : This function is used to wrap sources and entity instances
 : within the same document
 :)
declare function {$prefix}:instance-to-envelope(
    $entity-instance as map:map
) as text()
{{
    element es:envelope {{
        {$prefix}:instance-to-canonical-xml($entity-instance),
        element es:constrained {{
            map:get($entity-instance, "$sources")
        }}
    }}
}};

(: instance-from-document
 : if you have modified instance-to-envelope
 : you may need also to modify this function
 :)
declare function {$prefix}:instance-from-document(
    $document as document-node()
) as map:map
{{
    let $xml-from-document := {$prefix}:instance-xml-from-document($document)
    let $instance := map:map()
    let $_ := map:put($instance, "key", "val")
    return $instance
}};

declare function {$prefix}:instance-xml-from-document(
    $document as document-node()
) as element()
{{
    $document//es:entity/(* except es:info)[es:info/es:version eq "{$version}"]
}};

declare function {$prefix}:instance-json-from-document(
    $document as document-node()
) as object-node()
{{
    xdmp:to-json( {$prefix}:instance-from-document($document) )
}};
</conversion-module>/text()
}
};


Update BaseX client module function signatures.

xquery version "3.0";
(:~
: BaseX client module functions
:
: @see http://docs.basex.org/wiki/Client_Module
:)
module namespace client = "http://basex.org/";

import module namespace a = "http://reecedunn.co.uk/xquery/annotations" at "res://reecedunn.co.uk/xquery/annotations.xqy";

declare %a:since("basex", "7.3") function client:connect($host as xs:string, $port as xs:integer, $user as xs:string, $password as xs:string) as xs:anyURI external;
declare %a:since("basex", "7.3") function client:execute($id as xs:anyURI, $command as xs:string) as xs:string external;
declare %a:since("basex", "7.5") function client:info($id as xs:anyURI) as xs:string external;
declare %a:since("basex", "7.3") function client:query($id as xs:anyURI, $query as xs:string) as item()* external;
declare %a:since("basex", "7.3") function client:query($id as xs:anyURI, $query as xs:string, $bindings as map(*)?) as item()* (: $bindings [7.3]as map(*) [8.0]as map(*)? :) external;
declare %a:since("basex", "7.3") function client:close($id as xs:anyURI) as empty-sequence() external;

xquery version "3.0";
(:~
: BaseX client module functions
:
: @see http://docs.basex.org/wiki/Client_Module
:)
module namespace client = "http://basex.org/";

import module namespace a = "http://reecedunn.co.uk/xquery/annotations" at "res://reecedunn.co.uk/xquery/annotations.xqy";

declare %a:since("basex", "9.0") function client:connect($host as xs:string, $port as xs:integer, $user as xs:string, $password as xs:string) as xs:anyURI external;
declare %a:since("basex", "9.0") function client:execute($id as xs:anyURI, $command as xs:string) as xs:string external;
declare %a:since("basex", "9.0") function client:info($id as xs:anyURI) as xs:string external;
declare %a:since("basex", "9.0") function client:query($id as xs:anyURI, $query as xs:string) as item()* external;
declare %a:since("basex", "9.0") function client:query($id as xs:anyURI, $query as xs:string, $bindings as map(*)?) as item()* external;
declare %a:since("basex", "9.0") function client:close($id as xs:anyURI) as empty-sequence() external;